"""Versioned, source-backed annual and semi-annual observations for compute comparisons.""" from copy import deepcopy from datetime import date from typing import Literal from app.schemas.compute_configuration import ( ComputeConfiguration, ComputeObservation, has_mixed_sources, source_for, ) from app.services.compute_catalog import ( CATALOG, DEFAULT_PARTICIPANTS, PARTICIPANTS, participant_members, ) from app.services.compute_configuration import DEFAULT_CONFIGURATION ComputeSeriesMode = Literal[ "global_share", "intelligent_share", "bilateral_rpi", "bilateral_share", "absolute", "frontier_cluster_share", "chip_inflow_share", ] MODE_TO_METRIC: dict[str, str] = { "global_share": "global_share", "intelligent_share": "intelligent_share", "bilateral_rpi": "global_share", "bilateral_share": "global_share", "absolute": "absolute", "frontier_cluster_share": "frontier_cluster_share", "chip_inflow_share": "chip_inflow_share", } MODE_DENOMINATOR: dict[str, str | None] = { "global_share": "global", "intelligent_share": "global_intelligent", "bilateral_rpi": "US=100", "bilateral_share": "US+CN", "absolute": None, "frontier_cluster_share": "public_frontier_clusters", "chip_inflow_share": "ai_chip_inflow", } def _participant_value( members: tuple[str, ...], observations: dict[str, float | int], mode: str ) -> tuple[float | int | None, dict]: covered = [member for member in members if member in observations] missing = [member for member in members if member not in observations] coverage = { "status": "complete" if not missing else "incomplete", "required_members": list(members), "covered_members": covered, "missing_members": missing, } if missing: return None, coverage if mode == "bilateral_share": if ( not set(members).issubset({"CN", "US"}) or not {"CN", "US"}.issubset(observations) or observations["US"] + observations["CN"] <= 0 ): coverage.update( { "status": "incompatible", "reason": "bilateral_share_requires_CN_and_US_observations", } ) return None, coverage return ( round( sum(observations[member] for member in members) / (observations["US"] + observations["CN"]) * 100, 2, ), coverage, ) if mode == "bilateral_rpi": if ( not set(members).issubset({"CN", "US"}) or not {"CN", "US"}.issubset(observations) or observations["US"] <= 0 ): coverage.update( { "status": "incompatible", "reason": "bilateral_rpi_requires_CN_and_US_observations", } ) return None, coverage if members == ("US",): return 100.0, coverage return ( round( sum(observations[member] for member in members) / observations["US"] * 100, 1, ), coverage, ) return sum(observations[member] for member in members), coverage def _latest_bilateral_pair( rows: list[ComputeObservation], metric: str ) -> dict | None: candidates = sorted( ( row for row in rows if row.metric == metric and {"CN", "US"}.issubset(row.values) and row.values["US"] > 0 ), key=lambda item: item.year, ) if not candidates: return None latest = candidates[-1] cn_val = latest.values["CN"] us_val = latest.values["US"] summary: dict = { "year": latest.year, "period_label": latest.period_label or str(latest.year), "cn_value": cn_val, "us_value": us_val, "rpi_percent": round(cn_val / us_val * 100, 1), "gap_pp": round(cn_val - us_val, 2), "evidence_id": latest.source_id, "cn_evidence_id": source_for(latest, "CN"), "us_evidence_id": source_for(latest, "US"), } if len(candidates) >= 2: prev = candidates[-2] summary["from_year"] = prev.year summary["yoy_cn_pp"] = round(cn_val - prev.values["CN"], 2) summary["yoy_us_pp"] = round(us_val - prev.values["US"], 2) return summary def _build_bilateral_rpi(config: ComputeConfiguration, enabled: bool) -> dict | None: if not enabled: return None total_rows = sorted( ( row for row in config.observations if row.metric == "global_share" and {"CN", "US"}.issubset(row.values) and row.values["US"] > 0 ), key=lambda item: item.year, ) total_series = [ { "year": row.year, "period_label": row.period_label or str(row.year), "cn_value": row.values["CN"], "us_value": row.values["US"], "rpi_percent": round(row.values["CN"] / row.values["US"] * 100, 1), "gap_pp": round(row.values["CN"] - row.values["US"], 2), "evidence_id": row.source_id, "cn_evidence_id": source_for(row, "CN"), "us_evidence_id": source_for(row, "US"), } for row in total_rows ] latest_total = _latest_bilateral_pair(config.observations, "global_share") latest_intelligent = _latest_bilateral_pair(config.observations, "intelligent_share") latest_frontier = _latest_bilateral_pair(config.observations, "frontier_cluster_share") latest_chip = _latest_bilateral_pair(config.observations, "chip_inflow_share") if not any([total_series, latest_intelligent, latest_frontier, latest_chip]): return None return { "benchmark": "US", "subject": "CN", "total_series": total_series, "latest_total": latest_total, "latest_intelligent": latest_intelligent, "latest_frontier_cluster": latest_frontier, "latest_chip_inflow": latest_chip, } def _build_denominator_attribution( config: ComputeConfiguration, members_by_participant: dict[str, tuple[str, ...]] ) -> dict[str, dict]: absolute_rows = sorted( (row for row in config.observations if row.metric == "absolute"), key=lambda item: item.year, ) result: dict[str, dict] = {} for code, members in members_by_participant.items(): if len(members) != 1: continue country = members[0] country_rows = [row for row in absolute_rows if country in row.values and row.values[country] > 0] if not country_rows: continue latest = country_rows[-1] entry: dict = { "latest_year": latest.year, "latest_period": latest.period_label or str(latest.year), "latest_value": latest.values[country], "latest_global_total": latest.global_total, "unit": "EFlop/s (FP32)", "evidence_ids": [source_for(latest, country)], } denom_rows = [row for row in country_rows if row.global_total and row.global_total > 0] if len(denom_rows) >= 2: prev_row, curr_row = denom_rows[-2], denom_rows[-1] prev_val = prev_row.values[country] curr_val = curr_row.values[country] prev_global = float(prev_row.global_total or 0) curr_global = float(curr_row.global_total or 0) country_growth = (curr_val - prev_val) / prev_val * 100 global_growth = (curr_global - prev_global) / prev_global * 100 entry.update( { "from_year": prev_row.year, "from_period": prev_row.period_label or str(prev_row.year), "to_year": curr_row.year, "to_period": curr_row.period_label or str(curr_row.year), "country_from": prev_val, "country_to": curr_val, "country_growth_pct": round(country_growth, 1), "global_from": prev_global, "global_to": curr_global, "global_growth_pct": round(global_growth, 1), "diluted_by_global_expansion": global_growth > country_growth, "evidence_ids": list( dict.fromkeys([source_for(prev_row, country), source_for(curr_row, country)]) ), } ) elif len(country_rows) >= 2: prev_row, curr_row = country_rows[-2], country_rows[-1] prev_val = prev_row.values[country] curr_val = curr_row.values[country] entry.update( { "from_year": prev_row.year, "from_period": prev_row.period_label or str(prev_row.year), "to_year": curr_row.year, "to_period": curr_row.period_label or str(curr_row.year), "country_from": prev_val, "country_to": curr_val, "country_growth_pct": round((curr_val - prev_val) / prev_val * 100, 1), "evidence_ids": list( dict.fromkeys([source_for(prev_row, country), source_for(curr_row, country)]) ), } ) result[code] = entry return result def _build_structures( config: ComputeConfiguration, members_by_participant: dict[str, tuple[str, ...]] ) -> dict[str, dict]: latest_by_scope: dict[str, dict] = {} for row in sorted(config.structures, key=lambda item: item.year): latest_by_scope[row.scope] = row.model_dump(mode="json") selected_structures: dict[str, dict] = {} if "GLOBAL" in latest_by_scope: selected_structures["GLOBAL"] = latest_by_scope["GLOBAL"] for code, members in members_by_participant.items(): if len(members) == 1 and members[0] in latest_by_scope: selected_structures[code] = latest_by_scope[members[0]] return selected_structures def compute_history( countries: list[str], mode: str = "global_share", config: ComputeConfiguration | None = None, ) -> dict: """Aggregate only fully covered, same-year compatible observations.""" config = config if config is not None else DEFAULT_CONFIGURATION if mode not in MODE_TO_METRIC: raise ValueError(f"Unsupported compute series mode: {mode}") metric = MODE_TO_METRIC[mode] annual = {row.year: row for row in config.observations if row.metric == metric} global_share_annual = { row.year: row for row in config.observations if row.metric == "global_share" } gaps = {row.year: row for row in config.innovation} observed_years = [row.year for row in config.observations] + list(gaps) years = tuple( range( min(observed_years, default=date.today().year), max([date.today().year, *observed_years]) + 1, ) ) members_by_participant = participant_members(countries) rows = [] divergence_rows = [] for year in years: record = annual.get(year) observations = record.values if record else {} values, coverage = {}, {} evidence_by_code: dict[str, list[str]] = {} for code, members in members_by_participant.items(): values[code], coverage[code] = _participant_value(members, observations, mode) if record is not None: evidence_by_code[code] = list( dict.fromkeys( source_for(record, member) for member in members if member in record.values ) ) else: evidence_by_code[code] = [] evidence_id = record.source_id if record else None rows.append( { "year": year, "period_label": (record.period_label or str(year)) if record else None, "values": values, "coverage": coverage, "global_total": record.global_total if record else None, "evidence_id": evidence_id, "evidence_by_code": evidence_by_code, "mixed_sources": has_mixed_sources(record) if record else False, } ) share_record = global_share_annual.get(year) share_obs = share_record.values if share_record else {} share_values = { code: _participant_value(members, share_obs, "global_share")[0] for code, members in members_by_participant.items() } share_evidence_by_code = { code: ( list( dict.fromkeys( source_for(share_record, member) for member in members if member in share_record.values ) ) if share_record is not None else [] ) for code, members in members_by_participant.items() } divergence_rows.append( { "year": year, "period_label": (share_record.period_label or str(year)) if share_record else None, "values": share_values, "evidence_id": share_record.source_id if share_record else None, "evidence_by_code": share_evidence_by_code, "mixed_sources": has_mixed_sources(share_record) if share_record else False, } ) selected_members = {member for members in members_by_participant.values() for member in members} has_bilateral_scope = {"CN", "US"}.issubset(selected_members) has_innovation_scope = has_bilateral_scope sorted_gaps = sorted(config.innovation, key=lambda item: item.year) innovation_summary = None if has_innovation_scope and len(sorted_gaps) >= 2: first_gap, last_gap = sorted_gaps[0], sorted_gaps[-1] innovation_summary = { "from_year": first_gap.year, "to_year": last_gap.year, "from_value": first_gap.value, "to_value": last_gap.value, "delta": round(last_gap.value - first_gap.value, 2), "evidence_id": last_gap.source_id, } scope_codes = set(countries) | selected_members milestones = [ event.model_dump(mode="json") for event in sorted( config.milestones, key=lambda item: (item.year, item.month or 0, item.id) ) if set(event.participants) & scope_codes ] national_hubs = ( [hub.model_dump(mode="json") for hub in config.national_hubs] if "CN" in selected_members else [] ) return { "version": f"compute-history-{config.reviewed_at}", "provenance": "curated_reports", "reviewed_at": config.reviewed_at.isoformat(), "time_basis": "retrospective", "years": years, "mode": mode, "unit": "EFlop/s (FP32)" if mode == "absolute" else "%", "denominator": MODE_DENOMINATOR[mode], "catalog": deepcopy(CATALOG), "default_participants": list(DEFAULT_PARTICIPANTS), "countries": [deepcopy(PARTICIPANTS[code]) for code in countries], "compute": rows, "divergence_series": divergence_rows, "bilateral_rpi": _build_bilateral_rpi(config, has_bilateral_scope), "denominator_attribution": _build_denominator_attribution(config, members_by_participant), "structures": _build_structures(config, members_by_participant), "innovation": [ { "year": year, "value": gaps[year].value if year in gaps and has_innovation_scope else None, "evidence_id": gaps[year].source_id if year in gaps and has_innovation_scope else None, } for year in years ], "innovation_summary": innovation_summary, "milestones": milestones, "national_hubs": national_hubs, "evidence": { source.id: source.model_dump(mode="json", exclude={"id"}) for source in config.sources }, "innovation_scope": ["US", "CN"], "limitations": [ "公开设施样本不代表全国总算力;FP64、FP16 与 FP32 不可直接相加。", "区域值只在全部成员有同年、同指标、可比较观测时汇总;缺失成员时返回 null。", "全球竞争份额(如中国全球智算占 21%)与本国内部算力构成(如中国国内智算占约 81%)分母不同,严禁混减。", "Epoch AI 前沿集群与高端芯片流向受商业保密与匿名记录影响,仅反映公开可核验样本结构。", "创新分差为美国减中国;只有分差,不反推单国得分,不证明算力与创新的简单线性因果关系。", ], }