wuff-mann commited on
Commit
77eb195
·
verified ·
1 Parent(s): ac2e98a

Upload Experiments/V3_S2_A1_R2/cidm_v3_scs_s2_a1_r2_conditional_external_innovation_capacity.py with huggingface_hub

Browse files
Experiments/V3_S2_A1_R2/cidm_v3_scs_s2_a1_r2_conditional_external_innovation_capacity.py ADDED
@@ -0,0 +1,2731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ CIDM-v3 SCS V3-S2-A1-R2
5
+ 条件外部创新可预测容量、事件活跃子集与来源残差资格实验
6
+ ===========================================================
7
+
8
+ 本轮不是继续堆叠 BER,而是回答一个前置问题:
9
+
10
+ 在冻结 A0(内部状态 + 历史/当前大气、边界、垂向)之后,
11
+ 未来大气创新和未来域外边界创新是否仍能独立预测 A0 的剩余误差?
12
+
13
+ 设计原则:
14
+ - 以 A0 残差为监督目标,直接测量条件增量信息;
15
+ - 大气与边界使用严格来源专属、零输入零输出的小探针;
16
+ - 不使用内部特征作为探针输入,杜绝闭合系统捷径;
17
+ - 不加入方差校准,避免把统一异常放大误判为来源信息;
18
+ - 正确未来与同季节负样本、历史重复、时间反转公平比较;
19
+ - 仅用夏季验证集选择检查点和非负收缩系数;
20
+ - 秋季测试集完全不参与选择;
21
+ - 额外评估外部活动度最高的 20% 样本,判断信号是否只在事件期出现。
22
+
23
+ 若本轮仍无法建立稳定的正确未来优势,则应停止继续调 BER,
24
+ 转向扩大事件富集数据,而不是继续增加网络分支。
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import copy
30
+ import dataclasses
31
+ import datetime as dt
32
+ import io
33
+ import json
34
+ import math
35
+ import os
36
+ import random
37
+ import shutil
38
+ import time
39
+ import traceback
40
+ import zipfile
41
+ from pathlib import Path
42
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
43
+
44
+ import numpy as np
45
+ import pandas as pd
46
+ import torch
47
+ import torch.nn as nn
48
+ import torch.nn.functional as F
49
+ from torch.utils.data import DataLoader, Dataset
50
+
51
+ import matplotlib
52
+ matplotlib.use("Agg")
53
+ import matplotlib.pyplot as plt
54
+
55
+
56
+ WINDOWS = [
57
+ {"name": "winter", "role": "train"},
58
+ {"name": "spring", "role": "train"},
59
+ {"name": "summer", "role": "validation"},
60
+ {"name": "autumn", "role": "test"},
61
+ ]
62
+ HORIZONS = [1, 4, 12]
63
+ INTERNAL_VARIABLES = [
64
+ "sst", "sss", "ssh", "u_surface", "v_surface",
65
+ "u_100m", "v_100m", "temperature_100m", "salinity_100m",
66
+ "significant_wave_height", "peak_wave_period", "tm02",
67
+ "peak_wave_direction_sin", "peak_wave_direction_cos",
68
+ "wind_sea_significant_height", "primary_swell_significant_height",
69
+ ]
70
+ SOURCE_VARIABLES = {
71
+ "atmosphere": [
72
+ "u10", "v10", "wind_speed", "tau_x", "tau_y", "msl",
73
+ "net_heat_flux", "freshwater_flux", "wind_stress_curl",
74
+ ],
75
+ "boundary": [
76
+ "boundary_normal_inflow", "boundary_ssh", "boundary_sst", "boundary_sss",
77
+ "boundary_u_surface", "boundary_v_surface",
78
+ "boundary_temperature_100m", "boundary_salinity_100m",
79
+ "boundary_u_100m", "boundary_v_100m",
80
+ ],
81
+ "vertical": [
82
+ "mld_temperature_proxy", "thermocline_depth_proxy", "ohc_0_200_proxy",
83
+ "temperature_0_100_difference", "salinity_0_100_difference",
84
+ "current_shear_0_100", "density_stratification_0_100",
85
+ "temperature_100_200_difference", "salinity_100_200_difference",
86
+ "current_shear_100_200",
87
+ ],
88
+ "tide": [
89
+ "tide_elevation", "tide_u", "tide_v",
90
+ "m2_sin", "m2_cos", "s2_sin", "s2_cos",
91
+ "k1_sin", "k1_cos", "o1_sin", "o1_cos",
92
+ ],
93
+ "river": ["river_discharge_map", "river_discharge_anomaly"],
94
+ "events": ["event_intensity", "event_confidence", "event_type_code"],
95
+ }
96
+ SOURCE_KEYS = list(SOURCE_VARIABLES)
97
+ REQUIRED_SOURCES = ["atmosphere", "boundary", "vertical"]
98
+ GROUPS = {
99
+ "surface_thermohaline": [0, 1, 2],
100
+ "currents": [3, 4, 5, 6],
101
+ "subsurface_thermohaline": [7, 8],
102
+ "waves": list(range(9, 16)),
103
+ }
104
+ SOURCES = ["atmosphere", "boundary"]
105
+ CONTROLS = ["correct", "negative", "history", "reversed", "shifted"]
106
+
107
+
108
+ def json_default(value: Any) -> Any:
109
+ if isinstance(value, Path):
110
+ return str(value)
111
+ if isinstance(value, (np.integer, np.floating, np.bool_)):
112
+ return value.item()
113
+ if isinstance(value, np.ndarray):
114
+ return value.tolist()
115
+ if isinstance(value, (pd.Timestamp, dt.datetime, dt.date)):
116
+ return pd.Timestamp(value).isoformat()
117
+ raise TypeError(type(value).__name__)
118
+
119
+
120
+ def atomic_json(payload: Any, path: Path) -> None:
121
+ path.parent.mkdir(parents=True, exist_ok=True)
122
+ temporary = path.with_suffix(path.suffix + ".tmp")
123
+ temporary.write_text(
124
+ json.dumps(payload, ensure_ascii=False, indent=2, default=json_default),
125
+ encoding="utf-8",
126
+ )
127
+ os.replace(temporary, path)
128
+
129
+
130
+ def stage(index: int, total: int, title: str) -> None:
131
+ print(f"\n[V3-S2-A1-R2] 阶段 {index}/{total}:{title}", flush=True)
132
+
133
+
134
+ def seed_everything(seed: int) -> None:
135
+ random.seed(seed)
136
+ np.random.seed(seed)
137
+ torch.manual_seed(seed)
138
+ if torch.cuda.is_available():
139
+ torch.cuda.manual_seed_all(seed)
140
+
141
+
142
+ def ensure_hf_assets(args: argparse.Namespace) -> Dict[str, Any]:
143
+ cache = Path(args.cache_dir)
144
+ prepared = cache / "prepared"
145
+ prepared.mkdir(parents=True, exist_ok=True)
146
+ r1_zip = Path(args.r1_zip)
147
+ required: List[Tuple[str, Path]] = [
148
+ (
149
+ "Experiments/V3_S2_A1_R1/CIDM_v3_SCS_V3_S2_A1_R1.zip",
150
+ r1_zip,
151
+ )
152
+ ]
153
+ for window in WINDOWS:
154
+ name = window["name"]
155
+ required.extend([
156
+ (f"Cache/prepared/{name}_cmems.npz", prepared / f"{name}_cmems.npz"),
157
+ (
158
+ f"Cache/prepared/{name}_atmosphere_aligned.npz",
159
+ prepared / f"{name}_atmosphere_aligned.npz",
160
+ ),
161
+ (f"Cache/prepared/{name}_tide.npz", prepared / f"{name}_tide.npz"),
162
+ (f"Cache/prepared/{name}_river.npz", prepared / f"{name}_river.npz"),
163
+ (f"Cache/prepared/{name}_events.npz", prepared / f"{name}_events.npz"),
164
+ ])
165
+
166
+ missing = [
167
+ (repo_path, local_path)
168
+ for repo_path, local_path in required
169
+ if not local_path.is_file() or local_path.stat().st_size <= 128
170
+ ]
171
+ report = {
172
+ "repo_id": args.hf_repo_id,
173
+ "requested_files": len(required),
174
+ "already_local": len(required) - len(missing),
175
+ "downloaded": [],
176
+ }
177
+ if missing:
178
+ if not args.hf_repo_id:
179
+ raise RuntimeError("Missing assets and --hf_repo_id is empty")
180
+ from huggingface_hub import hf_hub_download
181
+ token = args.hf_token or os.environ.get("HF_TOKEN") or None
182
+ for repo_path, local_path in missing:
183
+ print(f"[HF download] {repo_path}", flush=True)
184
+ downloaded = Path(
185
+ hf_hub_download(
186
+ repo_id=args.hf_repo_id,
187
+ filename=repo_path,
188
+ repo_type="dataset",
189
+ token=token,
190
+ )
191
+ )
192
+ local_path.parent.mkdir(parents=True, exist_ok=True)
193
+ local_path.unlink(missing_ok=True)
194
+ try:
195
+ local_path.symlink_to(downloaded)
196
+ except Exception:
197
+ shutil.copy2(downloaded, local_path)
198
+ report["downloaded"].append(repo_path)
199
+
200
+ for repo_path, local_path in required:
201
+ if not local_path.is_file() or local_path.stat().st_size <= 128:
202
+ raise RuntimeError(f"Asset missing: {repo_path} -> {local_path}")
203
+ return report
204
+
205
+
206
+ def extract_r1_lineage(r1_zip: Path, work_dir: Path) -> Dict[str, Path]:
207
+ """Extract only R1 lineage and the nested frozen A0 parent assets."""
208
+ prefix = "CIDM_v3_SCS_V3_S2_A1_R1/"
209
+ a0_prefix = (
210
+ prefix
211
+ + "_a1_parent/CIDM_v3_SCS_V3_S2_A1/"
212
+ + "_a0_parent/CIDM_v3_SCS_V3_S2_A0/"
213
+ )
214
+ required = [
215
+ prefix + "S2A1R1_verdict.json",
216
+ prefix + "S2A1R1_main_aggregate.json",
217
+ a0_prefix + "audits/S2A0_normalization_stats.npz",
218
+ ]
219
+ for seed in [20260910, 20260911, 20260912]:
220
+ required.extend([
221
+ a0_prefix + f"checkpoints/baseline/seed_{seed}.pt",
222
+ a0_prefix + f"checkpoints/all_required/seed_{seed}.pt",
223
+ ])
224
+ work_dir.mkdir(parents=True, exist_ok=True)
225
+ with zipfile.ZipFile(r1_zip) as archive:
226
+ names = set(archive.namelist())
227
+ missing = [name for name in required if name not in names]
228
+ if missing:
229
+ raise RuntimeError(f"R1 archive misses required entries: {missing}")
230
+ for name in required:
231
+ target = work_dir / name
232
+ if not target.is_file():
233
+ archive.extract(name, work_dir)
234
+ r1_root = work_dir / prefix
235
+ a0_root = work_dir / a0_prefix
236
+ return {
237
+ "r1_root": r1_root,
238
+ "r1_verdict": r1_root / "S2A1R1_verdict.json",
239
+ "r1_aggregate": r1_root / "S2A1R1_main_aggregate.json",
240
+ "a0_root": a0_root,
241
+ "stats": a0_root / "audits" / "S2A0_normalization_stats.npz",
242
+ }
243
+
244
+
245
+ @dataclasses.dataclass
246
+ class WindowData:
247
+ name: str
248
+ role: str
249
+ time: np.ndarray
250
+ latitude: np.ndarray
251
+ longitude: np.ndarray
252
+ internal: np.ndarray
253
+ ocean_mask: np.ndarray
254
+ sources: Dict[str, np.ndarray]
255
+ actual: Dict[str, bool]
256
+
257
+
258
+ def load_window(cache: Path, spec: Mapping[str, str]) -> WindowData:
259
+ name = spec["name"]
260
+ prepared = cache / "prepared"
261
+ cmems = np.load(prepared / f"{name}_cmems.npz")
262
+ atmosphere = np.load(prepared / f"{name}_atmosphere_aligned.npz")
263
+ tide = np.load(prepared / f"{name}_tide.npz")
264
+ river = np.load(prepared / f"{name}_river.npz")
265
+ events = np.load(prepared / f"{name}_events.npz")
266
+ arrays = {
267
+ "atmosphere": atmosphere["atmosphere"].astype(np.float32),
268
+ "boundary": cmems["boundary"].astype(np.float32),
269
+ "vertical": cmems["vertical"].astype(np.float32),
270
+ "tide": tide["tide"].astype(np.float32),
271
+ "river": river["river"].astype(np.float32),
272
+ "events": events["events"].astype(np.float32),
273
+ }
274
+ lengths = {key: value.shape[0] for key, value in arrays.items()}
275
+ lengths["internal"] = cmems["internal"].shape[0]
276
+ if len(set(lengths.values())) != 1:
277
+ raise RuntimeError(f"{name} time length mismatch: {lengths}")
278
+ finite = (
279
+ np.isfinite(cmems["internal"]).all()
280
+ and all(np.isfinite(value).all() for value in arrays.values())
281
+ )
282
+ if not finite:
283
+ raise RuntimeError(f"{name} contains non-finite values")
284
+ return WindowData(
285
+ name=name,
286
+ role=spec["role"],
287
+ time=cmems["time"].astype("datetime64[ns]"),
288
+ latitude=cmems["latitude"].astype(np.float32),
289
+ longitude=cmems["longitude"].astype(np.float32),
290
+ internal=cmems["internal"].astype(np.float32),
291
+ ocean_mask=cmems["ocean_mask"].astype(np.float32),
292
+ sources=arrays,
293
+ actual={
294
+ "atmosphere": True,
295
+ "boundary": True,
296
+ "vertical": True,
297
+ "tide": bool(int(tide["actual_spatial_tide"][0])),
298
+ "river": bool(int(river["available"][0])),
299
+ "events": bool(int(events["available"][0])),
300
+ },
301
+ )
302
+
303
+
304
+ class SequenceIndex:
305
+ def __init__(self, windows: Sequence[WindowData], history: int):
306
+ self.windows = list(windows)
307
+ self.history = int(history)
308
+ self.records: List[Tuple[int, int, int]] = []
309
+ max_h = max(HORIZONS)
310
+ for wi, window in enumerate(self.windows):
311
+ valid = list(range(self.history - 1, len(window.time) - max_h))
312
+ if len(valid) < 2:
313
+ continue
314
+ offset = max(1, len(valid) // 2)
315
+ for position, t in enumerate(valid):
316
+ negative_t = valid[(position + offset) % len(valid)]
317
+ self.records.append((wi, t, negative_t))
318
+
319
+
320
+ class R2Dataset(Dataset):
321
+ def __init__(
322
+ self,
323
+ index: SequenceIndex,
324
+ internal_mean: np.ndarray,
325
+ internal_std: np.ndarray,
326
+ source_stats: Mapping[str, Tuple[np.ndarray, np.ndarray]],
327
+ ):
328
+ self.index = index
329
+ self.internal_mean = internal_mean
330
+ self.internal_std = internal_std
331
+ self.source_stats = source_stats
332
+
333
+ def __len__(self) -> int:
334
+ return len(self.index.records)
335
+
336
+ @staticmethod
337
+ def norm(value: np.ndarray, mean: np.ndarray, std: np.ndarray) -> np.ndarray:
338
+ return (
339
+ np.nan_to_num(value, nan=0.0)
340
+ - mean[None, :, None, None]
341
+ ) / std[None, :, None, None]
342
+
343
+ def __getitem__(self, item: int) -> Dict[str, torch.Tensor]:
344
+ wi, t, negative_t = self.index.records[item]
345
+ window = self.index.windows[wi]
346
+ history = self.index.history
347
+ internal_history = self.norm(
348
+ window.internal[t - history + 1:t + 1],
349
+ self.internal_mean,
350
+ self.internal_std,
351
+ )
352
+ targets = np.stack([
353
+ (
354
+ window.internal[t + horizon]
355
+ - self.internal_mean[:, None, None]
356
+ ) / self.internal_std[:, None, None]
357
+ for horizon in HORIZONS
358
+ ], axis=0).astype(np.float32)
359
+ result: Dict[str, torch.Tensor] = {
360
+ "internal": torch.from_numpy(
361
+ internal_history.reshape(
362
+ -1, *internal_history.shape[-2:]
363
+ ).astype(np.float32)
364
+ ),
365
+ "target": torch.from_numpy(targets),
366
+ "mask": torch.from_numpy(window.ocean_mask[t].astype(np.float32)),
367
+ "sample_index": torch.tensor(item, dtype=torch.long),
368
+ "time_ns": torch.tensor(
369
+ window.time[t].astype("datetime64[ns]").astype(np.int64),
370
+ dtype=torch.long,
371
+ ),
372
+ }
373
+ for source, values in window.sources.items():
374
+ mean, std = self.source_stats[source]
375
+ history_values = self.norm(
376
+ values[t - history + 1:t + 1], mean, std
377
+ ).astype(np.float32)
378
+ actual = 1.0 if window.actual[source] else 0.0
379
+ uncertainty = (
380
+ 0.10 if source in REQUIRED_SOURCES
381
+ else (0.25 if actual else 1.0)
382
+ )
383
+ availability = np.full(
384
+ (history, 1, *history_values.shape[-2:]),
385
+ actual,
386
+ dtype=np.float32,
387
+ )
388
+ uncertainty_map = np.full(
389
+ (history, 1, *history_values.shape[-2:]),
390
+ uncertainty,
391
+ dtype=np.float32,
392
+ )
393
+ parent_value = np.concatenate(
394
+ [history_values, availability, uncertainty_map], axis=1
395
+ )
396
+ result[f"parent_{source}"] = torch.from_numpy(
397
+ parent_value.reshape(
398
+ -1, *history_values.shape[-2:]
399
+ ).astype(np.float32)
400
+ )
401
+
402
+ for source in SOURCES:
403
+ mean, std = self.source_stats[source]
404
+ correct = self.norm(
405
+ window.sources[source][t:t + max(HORIZONS) + 1],
406
+ mean, std,
407
+ ).astype(np.float32)
408
+ negative = self.norm(
409
+ window.sources[source][
410
+ negative_t:negative_t + max(HORIZONS) + 1
411
+ ],
412
+ mean, std,
413
+ ).astype(np.float32)
414
+ result[f"future_{source}"] = torch.from_numpy(correct)
415
+ result[f"negative_{source}"] = torch.from_numpy(negative)
416
+ return result
417
+
418
+
419
+ class DepthwiseBlock(nn.Module):
420
+ def __init__(self, channels: int):
421
+ super().__init__()
422
+ self.norm = nn.GroupNorm(1, channels)
423
+ self.dw = nn.Conv2d(
424
+ channels, channels, 3, padding=1, groups=channels
425
+ )
426
+ self.pw1 = nn.Conv2d(channels, channels * 2, 1)
427
+ self.pw2 = nn.Conv2d(channels * 2, channels, 1)
428
+ nn.init.zeros_(self.pw2.weight)
429
+ nn.init.zeros_(self.pw2.bias)
430
+
431
+ def forward(self, value: torch.Tensor) -> torch.Tensor:
432
+ update = self.dw(F.silu(self.norm(value)))
433
+ update = self.pw2(F.silu(self.pw1(update)))
434
+ return value + update
435
+
436
+
437
+ class InternalProbe(nn.Module):
438
+ def __init__(
439
+ self,
440
+ history: int = 4,
441
+ channels: int = 16,
442
+ hidden: int = 48,
443
+ horizons: int = 3,
444
+ ):
445
+ super().__init__()
446
+ self.horizons = horizons
447
+ self.channels = channels
448
+ self.stem = nn.Conv2d(history * channels, hidden, 3, padding=1)
449
+ self.blocks = nn.Sequential(
450
+ *[DepthwiseBlock(hidden) for _ in range(3)]
451
+ )
452
+ self.head = nn.Conv2d(hidden, horizons * channels, 1)
453
+
454
+ def forward_features(self, value: torch.Tensor) -> torch.Tensor:
455
+ return self.blocks(self.stem(value))
456
+
457
+ def forward(
458
+ self, value: torch.Tensor
459
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
460
+ features = self.forward_features(value)
461
+ prediction = self.head(features)
462
+ b, _, h, w = prediction.shape
463
+ return (
464
+ prediction.reshape(
465
+ b, self.horizons, self.channels, h, w
466
+ ),
467
+ features,
468
+ )
469
+
470
+
471
+ class SourceBranch(nn.Module):
472
+ def __init__(self, in_channels: int, out_channels: int):
473
+ super().__init__()
474
+ self.net = nn.Sequential(
475
+ nn.Conv2d(in_channels, out_channels, 1),
476
+ nn.GroupNorm(1, out_channels),
477
+ nn.SiLU(),
478
+ nn.Conv2d(
479
+ out_channels,
480
+ out_channels,
481
+ 3,
482
+ padding=1,
483
+ groups=out_channels,
484
+ ),
485
+ nn.Conv2d(out_channels, out_channels, 1),
486
+ nn.SiLU(),
487
+ )
488
+
489
+ def forward(self, value: torch.Tensor) -> torch.Tensor:
490
+ return self.net(value)
491
+
492
+
493
+ class A0ExternalResidualAdapter(nn.Module):
494
+ def __init__(
495
+ self,
496
+ source_channels: Mapping[str, int],
497
+ history: int = 4,
498
+ internal_hidden: int = 48,
499
+ branch_hidden: int = 16,
500
+ channels: int = 16,
501
+ horizons: int = 3,
502
+ ):
503
+ super().__init__()
504
+ self.source_keys = list(source_channels)
505
+ self.branches = nn.ModuleDict({
506
+ key: SourceBranch(history * value, branch_hidden)
507
+ for key, value in source_channels.items()
508
+ })
509
+ fusion_in = internal_hidden + branch_hidden * len(self.source_keys)
510
+ self.fusion = nn.Sequential(
511
+ nn.Conv2d(fusion_in, internal_hidden, 1),
512
+ DepthwiseBlock(internal_hidden),
513
+ DepthwiseBlock(internal_hidden),
514
+ )
515
+ self.head = nn.Conv2d(
516
+ internal_hidden, horizons * channels, 1
517
+ )
518
+ self.ratio_logit = nn.Parameter(torch.tensor(-1.5))
519
+ self.channels = channels
520
+ self.horizons = horizons
521
+
522
+ def forward(
523
+ self,
524
+ internal_features: torch.Tensor,
525
+ sources: Mapping[str, torch.Tensor],
526
+ enabled: Sequence[str],
527
+ ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
528
+ enabled_set = set(enabled)
529
+ values = []
530
+ energies: Dict[str, torch.Tensor] = {}
531
+ for key in self.source_keys:
532
+ feature = self.branches[key](sources[key])
533
+ if key not in enabled_set:
534
+ feature = torch.zeros_like(feature)
535
+ values.append(feature)
536
+ energies[key] = feature.square().mean().sqrt()
537
+ fused = self.fusion(
538
+ torch.cat([internal_features] + values, dim=1)
539
+ )
540
+ raw = self.head(fused)
541
+ cap = 0.02 + 0.48 * torch.sigmoid(self.ratio_logit)
542
+ update = cap * torch.tanh(raw)
543
+ b, _, h, w = update.shape
544
+ return (
545
+ update.reshape(
546
+ b, self.horizons, self.channels, h, w
547
+ ),
548
+ {
549
+ "adapter_cap": cap,
550
+ **{
551
+ f"{key}_energy": value
552
+ for key, value in energies.items()
553
+ },
554
+ },
555
+ )
556
+
557
+
558
+ class FrozenA0Parent(nn.Module):
559
+ def __init__(
560
+ self,
561
+ baseline: InternalProbe,
562
+ adapter: A0ExternalResidualAdapter,
563
+ ):
564
+ super().__init__()
565
+ self.baseline = baseline
566
+ self.adapter = adapter
567
+ for parameter in self.parameters():
568
+ parameter.requires_grad = False
569
+
570
+ def forward(
571
+ self,
572
+ internal: torch.Tensor,
573
+ sources: Mapping[str, torch.Tensor],
574
+ ) -> torch.Tensor:
575
+ base, features = self.baseline(internal)
576
+ update, _ = self.adapter(features, sources, REQUIRED_SOURCES)
577
+ return base + update
578
+
579
+
580
+ def load_parent(
581
+ a0_root: Path,
582
+ seed: int,
583
+ device: torch.device,
584
+ ) -> FrozenA0Parent:
585
+ baseline = InternalProbe()
586
+ source_channels = {
587
+ key: len(SOURCE_VARIABLES[key]) + 2 for key in SOURCE_KEYS
588
+ }
589
+ adapter = A0ExternalResidualAdapter(source_channels)
590
+ baseline_checkpoint = torch.load(
591
+ a0_root / "checkpoints" / "baseline" / f"seed_{seed}.pt",
592
+ map_location="cpu",
593
+ weights_only=False,
594
+ )
595
+ adapter_checkpoint = torch.load(
596
+ a0_root / "checkpoints" / "all_required" / f"seed_{seed}.pt",
597
+ map_location="cpu",
598
+ weights_only=False,
599
+ )
600
+ baseline.load_state_dict(
601
+ baseline_checkpoint["model_state"], strict=True
602
+ )
603
+ adapter.load_state_dict(
604
+ adapter_checkpoint["adapter_state"], strict=True
605
+ )
606
+ parent = FrozenA0Parent(baseline, adapter).to(device)
607
+ parent.eval()
608
+ return parent
609
+
610
+
611
+ def load_stats(
612
+ path: Path,
613
+ ) -> Tuple[
614
+ np.ndarray,
615
+ np.ndarray,
616
+ Dict[str, Tuple[np.ndarray, np.ndarray]],
617
+ ]:
618
+ with np.load(path) as stats:
619
+ internal_mean = stats["internal_mean"].astype(np.float32)
620
+ internal_std = stats["internal_std"].astype(np.float32)
621
+ source_stats = {
622
+ key: (
623
+ stats[f"{key}_mean"].astype(np.float32),
624
+ stats[f"{key}_std"].astype(np.float32),
625
+ )
626
+ for key in SOURCE_KEYS
627
+ }
628
+ return internal_mean, internal_std, source_stats
629
+
630
+
631
+ def build_loaders(
632
+ windows: Sequence[WindowData],
633
+ stats_path: Path,
634
+ args: argparse.Namespace,
635
+ ) -> Tuple[Dict[str, DataLoader], Dict[str, Any]]:
636
+ internal_mean, internal_std, source_stats = load_stats(stats_path)
637
+ loaders: Dict[str, DataLoader] = {}
638
+ audit: Dict[str, Any] = {}
639
+ for role in ["train", "validation", "test"]:
640
+ selected = [
641
+ window for window in windows if window.role == role
642
+ ]
643
+ index = SequenceIndex(selected, args.history)
644
+ dataset = R2Dataset(
645
+ index,
646
+ internal_mean,
647
+ internal_std,
648
+ source_stats,
649
+ )
650
+ loaders[role] = DataLoader(
651
+ dataset,
652
+ batch_size=args.batch_size,
653
+ shuffle=(role == "train"),
654
+ num_workers=args.num_workers,
655
+ pin_memory=torch.cuda.is_available(),
656
+ drop_last=(
657
+ role == "train"
658
+ and len(dataset) >= args.batch_size
659
+ ),
660
+ )
661
+ audit[role] = {
662
+ "windows": [window.name for window in selected],
663
+ "samples": len(dataset),
664
+ }
665
+ return loaders, audit
666
+
667
+
668
+ def batch_to_device(
669
+ batch: Mapping[str, torch.Tensor],
670
+ device: torch.device,
671
+ ) -> Dict[str, torch.Tensor]:
672
+ return {
673
+ key: (
674
+ value.to(device, non_blocking=True)
675
+ if torch.is_tensor(value) else value
676
+ )
677
+ for key, value in batch.items()
678
+ }
679
+
680
+
681
+ def parent_sources(
682
+ batch: Mapping[str, torch.Tensor],
683
+ ) -> Dict[str, torch.Tensor]:
684
+ return {
685
+ key: batch[f"parent_{key}"] for key in SOURCE_KEYS
686
+ }
687
+
688
+
689
+ def control_sequence(
690
+ correct: torch.Tensor,
691
+ negative: torch.Tensor,
692
+ control: str,
693
+ ) -> torch.Tensor:
694
+ if control == "correct":
695
+ return correct
696
+ if control == "negative":
697
+ return negative
698
+ if control == "history":
699
+ return correct[:, :1].expand_as(correct)
700
+ if control == "reversed":
701
+ return torch.flip(correct, dims=[1])
702
+ if control == "shifted":
703
+ return torch.cat([correct[:, 1:], correct[:, -1:]], dim=1)
704
+ raise ValueError(control)
705
+
706
+
707
+ def build_innovation(
708
+ sequence: torch.Tensor,
709
+ source: str,
710
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
711
+ """
712
+ Return:
713
+ features [B,H,F,Y,X]
714
+ activity [B,H]
715
+ Current absolute source state is excluded because A0 already receives it.
716
+ """
717
+ feature_list = []
718
+ activity_list = []
719
+ for horizon in HORIZONS:
720
+ segment = sequence[:, :horizon + 1]
721
+ current = segment[:, 0]
722
+ endpoint_delta = segment[:, -1] - current
723
+ mean_delta = segment.mean(dim=1) - current
724
+ temporal_std = segment.std(dim=1, unbiased=False)
725
+ feature = torch.cat(
726
+ [endpoint_delta, mean_delta, temporal_std], dim=1
727
+ )
728
+ if source == "boundary":
729
+ steps = {1: 1, 4: 3, 12: 6}[horizon]
730
+ diffused = feature
731
+ for _ in range(steps):
732
+ diffused = F.avg_pool2d(
733
+ diffused, 3, stride=1, padding=1
734
+ )
735
+ feature = torch.cat([feature, diffused], dim=1)
736
+ feature_list.append(feature)
737
+ activity_list.append(
738
+ torch.sqrt(
739
+ feature.square().mean(
740
+ dim=(1, 2, 3)
741
+ ) + 1e-12
742
+ )
743
+ )
744
+ return (
745
+ torch.stack(feature_list, dim=1),
746
+ torch.stack(activity_list, dim=1),
747
+ )
748
+
749
+
750
+ class ZeroSourceResidualHead(nn.Module):
751
+ """Strict zero-input -> zero-output source residual probe."""
752
+ def __init__(
753
+ self,
754
+ input_channels: int,
755
+ hidden: int,
756
+ output_channels: int = 16,
757
+ ):
758
+ super().__init__()
759
+ self.net = nn.Sequential(
760
+ nn.Conv2d(
761
+ input_channels,
762
+ hidden,
763
+ 3,
764
+ padding=1,
765
+ bias=False,
766
+ ),
767
+ nn.SiLU(),
768
+ nn.Conv2d(
769
+ hidden,
770
+ hidden,
771
+ 3,
772
+ padding=1,
773
+ groups=hidden,
774
+ bias=False,
775
+ ),
776
+ nn.SiLU(),
777
+ nn.Conv2d(hidden, hidden, 1, bias=False),
778
+ nn.SiLU(),
779
+ nn.Conv2d(
780
+ hidden,
781
+ output_channels,
782
+ 1,
783
+ bias=False,
784
+ ),
785
+ )
786
+ nn.init.normal_(
787
+ self.net[-1].weight,
788
+ mean=0.0,
789
+ std=1e-3,
790
+ )
791
+
792
+ def forward(self, value: torch.Tensor) -> torch.Tensor:
793
+ return self.net(value)
794
+
795
+
796
+ class ConditionalInnovationProbe(nn.Module):
797
+ def __init__(
798
+ self,
799
+ source: str,
800
+ source_channels: int,
801
+ hidden: int,
802
+ ):
803
+ super().__init__()
804
+ self.source = source
805
+ feature_channels = source_channels * (
806
+ 6 if source == "boundary" else 3
807
+ )
808
+ self.heads = nn.ModuleList([
809
+ ZeroSourceResidualHead(feature_channels, hidden)
810
+ for _ in HORIZONS
811
+ ])
812
+
813
+ def forward(
814
+ self,
815
+ sequence: torch.Tensor,
816
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
817
+ features, activity = build_innovation(
818
+ sequence, self.source
819
+ )
820
+ outputs = [
821
+ self.heads[index](features[:, index])
822
+ for index in range(len(HORIZONS))
823
+ ]
824
+ return torch.stack(outputs, dim=1), activity
825
+
826
+
827
+ class DualInnovationAudit(nn.Module):
828
+ def __init__(self, hidden: int):
829
+ super().__init__()
830
+ self.atmosphere = ConditionalInnovationProbe(
831
+ "atmosphere",
832
+ len(SOURCE_VARIABLES["atmosphere"]),
833
+ hidden,
834
+ )
835
+ self.boundary = ConditionalInnovationProbe(
836
+ "boundary",
837
+ len(SOURCE_VARIABLES["boundary"]),
838
+ hidden,
839
+ )
840
+
841
+ def forward(
842
+ self,
843
+ atmosphere: torch.Tensor,
844
+ boundary: torch.Tensor,
845
+ ) -> Dict[str, torch.Tensor]:
846
+ atmosphere_update, atmosphere_activity = self.atmosphere(
847
+ atmosphere
848
+ )
849
+ boundary_update, boundary_activity = self.boundary(
850
+ boundary
851
+ )
852
+ return {
853
+ "atmosphere": atmosphere_update,
854
+ "boundary": boundary_update,
855
+ "joint": atmosphere_update + boundary_update,
856
+ "atmosphere_activity": atmosphere_activity,
857
+ "boundary_activity": boundary_activity,
858
+ }
859
+
860
+
861
+ def masked_sample_mse(
862
+ prediction: torch.Tensor,
863
+ target: torch.Tensor,
864
+ mask: torch.Tensor,
865
+ ) -> torch.Tensor:
866
+ expanded = mask[:, None].expand_as(prediction)
867
+ numerator = (
868
+ (prediction - target).square() * expanded
869
+ ).flatten(2).sum(dim=2)
870
+ denominator = (
871
+ expanded.flatten(2).sum(dim=2).clamp_min(1.0)
872
+ )
873
+ return numerator / denominator
874
+
875
+
876
+ def masked_sample_cosine(
877
+ prediction: torch.Tensor,
878
+ target: torch.Tensor,
879
+ mask: torch.Tensor,
880
+ ) -> torch.Tensor:
881
+ expanded = mask[:, None].expand_as(prediction)
882
+ p = (prediction * expanded).flatten(2)
883
+ t = (target * expanded).flatten(2)
884
+ return (
885
+ (p * t).sum(dim=2)
886
+ / (
887
+ p.norm(dim=2) * t.norm(dim=2)
888
+ + 1e-8
889
+ )
890
+ )
891
+
892
+
893
+ @torch.no_grad()
894
+ def estimate_residual_scale(
895
+ parent: FrozenA0Parent,
896
+ loader: DataLoader,
897
+ device: torch.device,
898
+ ) -> torch.Tensor:
899
+ numerator = torch.zeros(
900
+ len(HORIZONS),
901
+ len(INTERNAL_VARIABLES),
902
+ device=device,
903
+ )
904
+ denominator = torch.zeros_like(numerator)
905
+ for raw_batch in loader:
906
+ batch = batch_to_device(raw_batch, device)
907
+ parent_prediction = parent(
908
+ batch["internal"], parent_sources(batch)
909
+ )
910
+ residual = batch["target"] - parent_prediction
911
+ mask = batch["mask"][:, None]
912
+ numerator += (
913
+ residual.square() * mask
914
+ ).sum(dim=(0, 3, 4))
915
+ denominator += (
916
+ mask.expand_as(residual)
917
+ ).sum(dim=(0, 3, 4))
918
+ scale = torch.sqrt(
919
+ numerator / denominator.clamp_min(1.0) + 1e-8
920
+ )
921
+ return scale.clamp_min(1e-3)
922
+
923
+
924
+ def apply_scale(
925
+ normalized_update: torch.Tensor,
926
+ scale: torch.Tensor,
927
+ ) -> torch.Tensor:
928
+ return normalized_update * scale[
929
+ None, :, :, None, None
930
+ ]
931
+
932
+
933
+ def weighted_source_loss(
934
+ prediction: torch.Tensor,
935
+ target: torch.Tensor,
936
+ mask: torch.Tensor,
937
+ activity: torch.Tensor,
938
+ ) -> torch.Tensor:
939
+ per_sample = masked_sample_mse(
940
+ prediction, target, mask
941
+ )
942
+ normalized_activity = activity / (
943
+ activity.mean(dim=0, keepdim=True) + 1e-6
944
+ )
945
+ weights = (0.5 + 0.5 * normalized_activity).clamp(
946
+ 0.5, 2.0
947
+ )
948
+ horizon_weights = torch.tensor(
949
+ [0.25, 0.50, 1.0],
950
+ device=prediction.device,
951
+ dtype=prediction.dtype,
952
+ )
953
+ return (
954
+ per_sample * weights * horizon_weights[None]
955
+ ).mean()
956
+
957
+
958
+ def rank_loss(
959
+ correct: torch.Tensor,
960
+ negative: torch.Tensor,
961
+ target: torch.Tensor,
962
+ mask: torch.Tensor,
963
+ margin: float,
964
+ ) -> torch.Tensor:
965
+ correct_mse = masked_sample_mse(
966
+ correct, target, mask
967
+ )
968
+ negative_mse = masked_sample_mse(
969
+ negative, target, mask
970
+ )
971
+ return F.relu(
972
+ margin + correct_mse - negative_mse
973
+ ).mean()
974
+
975
+
976
+ def train_probe(
977
+ seed: int,
978
+ parent: FrozenA0Parent,
979
+ loaders: Mapping[str, DataLoader],
980
+ args: argparse.Namespace,
981
+ device: torch.device,
982
+ output_dir: Path,
983
+ ) -> Tuple[DualInnovationAudit, torch.Tensor, Dict[str, Any]]:
984
+ seed_everything(seed)
985
+ residual_scale = estimate_residual_scale(
986
+ parent, loaders["train"], device
987
+ )
988
+ model = DualInnovationAudit(args.hidden).to(device)
989
+
990
+ # Strict source zero sentinel.
991
+ sentinel_batch = batch_to_device(
992
+ next(iter(loaders["validation"])),
993
+ device,
994
+ )
995
+ with torch.no_grad():
996
+ zero_atmosphere = torch.zeros_like(
997
+ sentinel_batch["future_atmosphere"]
998
+ )
999
+ zero_boundary = torch.zeros_like(
1000
+ sentinel_batch["future_boundary"]
1001
+ )
1002
+ zero_output = model(
1003
+ zero_atmosphere, zero_boundary
1004
+ )
1005
+ source_zero_max = max(
1006
+ float(zero_output["atmosphere"].abs().max()),
1007
+ float(zero_output["boundary"].abs().max()),
1008
+ )
1009
+ if source_zero_max > 1e-8:
1010
+ raise RuntimeError(
1011
+ f"Source-zero sentinel failed: {source_zero_max}"
1012
+ )
1013
+
1014
+ optimizer = torch.optim.AdamW(
1015
+ model.parameters(),
1016
+ lr=args.learning_rate,
1017
+ weight_decay=args.weight_decay,
1018
+ )
1019
+ best_state: Optional[Dict[str, torch.Tensor]] = None
1020
+ best_score = float("inf")
1021
+ best_epoch = -1
1022
+ logs: List[Dict[str, Any]] = []
1023
+
1024
+ for epoch in range(1, args.epochs + 1):
1025
+ model.train()
1026
+ sums = {
1027
+ "total": 0.0,
1028
+ "atmosphere": 0.0,
1029
+ "boundary": 0.0,
1030
+ "joint": 0.0,
1031
+ "rank": 0.0,
1032
+ "alignment": 0.0,
1033
+ }
1034
+ for raw_batch in loaders["train"]:
1035
+ batch = batch_to_device(raw_batch, device)
1036
+ with torch.no_grad():
1037
+ parent_prediction = parent(
1038
+ batch["internal"],
1039
+ parent_sources(batch),
1040
+ )
1041
+ residual = batch["target"] - parent_prediction
1042
+ normalized_target = residual / residual_scale[
1043
+ None, :, :, None, None
1044
+ ]
1045
+
1046
+ correct = model(
1047
+ batch["future_atmosphere"],
1048
+ batch["future_boundary"],
1049
+ )
1050
+ negative = model(
1051
+ batch["negative_atmosphere"],
1052
+ batch["negative_boundary"],
1053
+ )
1054
+ atmosphere_loss = weighted_source_loss(
1055
+ correct["atmosphere"],
1056
+ normalized_target,
1057
+ batch["mask"],
1058
+ correct["atmosphere_activity"],
1059
+ )
1060
+ boundary_loss = weighted_source_loss(
1061
+ correct["boundary"],
1062
+ normalized_target,
1063
+ batch["mask"],
1064
+ correct["boundary_activity"],
1065
+ )
1066
+ joint_activity = torch.maximum(
1067
+ correct["atmosphere_activity"],
1068
+ correct["boundary_activity"],
1069
+ )
1070
+ joint_loss = weighted_source_loss(
1071
+ correct["joint"],
1072
+ normalized_target,
1073
+ batch["mask"],
1074
+ joint_activity,
1075
+ )
1076
+ causal_rank = (
1077
+ rank_loss(
1078
+ correct["atmosphere"],
1079
+ negative["atmosphere"],
1080
+ normalized_target,
1081
+ batch["mask"],
1082
+ args.rank_margin,
1083
+ )
1084
+ + rank_loss(
1085
+ correct["boundary"],
1086
+ negative["boundary"],
1087
+ normalized_target,
1088
+ batch["mask"],
1089
+ args.rank_margin,
1090
+ )
1091
+ + rank_loss(
1092
+ correct["joint"],
1093
+ negative["joint"],
1094
+ normalized_target,
1095
+ batch["mask"],
1096
+ args.rank_margin,
1097
+ )
1098
+ ) / 3.0
1099
+ correct_cos = masked_sample_cosine(
1100
+ correct["joint"],
1101
+ normalized_target,
1102
+ batch["mask"],
1103
+ ).mean()
1104
+ negative_cos = masked_sample_cosine(
1105
+ negative["joint"],
1106
+ normalized_target,
1107
+ batch["mask"],
1108
+ ).mean()
1109
+ alignment = F.relu(
1110
+ args.cosine_margin
1111
+ - correct_cos
1112
+ + negative_cos
1113
+ )
1114
+ loss = (
1115
+ args.atmosphere_weight * atmosphere_loss
1116
+ + args.boundary_weight * boundary_loss
1117
+ + args.joint_weight * joint_loss
1118
+ + args.rank_weight * causal_rank
1119
+ + args.alignment_weight * alignment
1120
+ )
1121
+ if not torch.isfinite(loss):
1122
+ raise RuntimeError(
1123
+ f"Non-finite training loss seed={seed} epoch={epoch}"
1124
+ )
1125
+ optimizer.zero_grad(set_to_none=True)
1126
+ loss.backward()
1127
+ torch.nn.utils.clip_grad_norm_(
1128
+ model.parameters(), args.grad_clip
1129
+ )
1130
+ optimizer.step()
1131
+ sums["total"] += float(loss.detach())
1132
+ sums["atmosphere"] += float(atmosphere_loss.detach())
1133
+ sums["boundary"] += float(boundary_loss.detach())
1134
+ sums["joint"] += float(joint_loss.detach())
1135
+ sums["rank"] += float(causal_rank.detach())
1136
+ sums["alignment"] += float(alignment.detach())
1137
+
1138
+ validation = evaluate_raw_capacity(
1139
+ model,
1140
+ parent,
1141
+ loaders["validation"],
1142
+ residual_scale,
1143
+ device,
1144
+ )
1145
+ # Lower normalized residual MSE is better; positive correct-control
1146
+ # gaps lower the score without allowing variance objectives to dominate.
1147
+ score = (
1148
+ validation["joint_correct_mse"]
1149
+ + 0.30 * validation["atmosphere_correct_mse"]
1150
+ + 0.30 * validation["boundary_correct_mse"]
1151
+ - args.selection_causal_weight
1152
+ * max(validation["joint_negative_gap"], 0.0)
1153
+ )
1154
+ row = {
1155
+ "seed": seed,
1156
+ "epoch": epoch,
1157
+ "validation_score": score,
1158
+ **validation,
1159
+ **{
1160
+ f"train_{key}": value
1161
+ / max(len(loaders["train"]), 1)
1162
+ for key, value in sums.items()
1163
+ },
1164
+ }
1165
+ logs.append(row)
1166
+ print(
1167
+ f"[R2 seed={seed}] epoch={epoch}/{args.epochs} "
1168
+ f"score={score:.6f} joint={validation['joint_correct_mse']:.6f} "
1169
+ f"atm_gap={validation['atmosphere_negative_gap']:.6e} "
1170
+ f"bnd_gap={validation['boundary_negative_gap']:.6e} "
1171
+ f"joint_gap={validation['joint_negative_gap']:.6e}",
1172
+ flush=True,
1173
+ )
1174
+ if score < best_score:
1175
+ best_score = score
1176
+ best_epoch = epoch
1177
+ best_state = {
1178
+ key: value.detach().cpu().clone()
1179
+ for key, value in model.state_dict().items()
1180
+ }
1181
+
1182
+ if best_state is None:
1183
+ raise RuntimeError("No R2 checkpoint selected")
1184
+ model.load_state_dict(best_state, strict=True)
1185
+ checkpoint = output_dir / "checkpoints" / f"seed_{seed}.pt"
1186
+ checkpoint.parent.mkdir(parents=True, exist_ok=True)
1187
+ torch.save(
1188
+ {
1189
+ "model_state": best_state,
1190
+ "residual_scale": residual_scale.detach().cpu(),
1191
+ "seed": seed,
1192
+ "best_epoch": best_epoch,
1193
+ "validation_score": best_score,
1194
+ "source_zero_max": source_zero_max,
1195
+ },
1196
+ checkpoint,
1197
+ )
1198
+ pd.DataFrame(logs).to_csv(
1199
+ output_dir / "training" / f"seed_{seed}.csv",
1200
+ index=False,
1201
+ )
1202
+ return model, residual_scale, {
1203
+ "seed": seed,
1204
+ "checkpoint": str(checkpoint),
1205
+ "best_epoch": best_epoch,
1206
+ "validation_score": best_score,
1207
+ "source_zero_max": source_zero_max,
1208
+ }
1209
+
1210
+
1211
+ @torch.no_grad()
1212
+ def evaluate_raw_capacity(
1213
+ model: DualInnovationAudit,
1214
+ parent: FrozenA0Parent,
1215
+ loader: DataLoader,
1216
+ residual_scale: torch.Tensor,
1217
+ device: torch.device,
1218
+ ) -> Dict[str, float]:
1219
+ model.eval()
1220
+ accum: Dict[str, List[float]] = {
1221
+ "atmosphere_correct": [],
1222
+ "atmosphere_negative": [],
1223
+ "boundary_correct": [],
1224
+ "boundary_negative": [],
1225
+ "joint_correct": [],
1226
+ "joint_negative": [],
1227
+ }
1228
+ cosine: Dict[str, List[float]] = {
1229
+ "atmosphere": [],
1230
+ "boundary": [],
1231
+ "joint": [],
1232
+ }
1233
+ for raw_batch in loader:
1234
+ batch = batch_to_device(raw_batch, device)
1235
+ parent_prediction = parent(
1236
+ batch["internal"], parent_sources(batch)
1237
+ )
1238
+ residual = batch["target"] - parent_prediction
1239
+ normalized_target = residual / residual_scale[
1240
+ None, :, :, None, None
1241
+ ]
1242
+ correct = model(
1243
+ batch["future_atmosphere"],
1244
+ batch["future_boundary"],
1245
+ )
1246
+ negative = model(
1247
+ batch["negative_atmosphere"],
1248
+ batch["negative_boundary"],
1249
+ )
1250
+ for source in ["atmosphere", "boundary", "joint"]:
1251
+ accum[f"{source}_correct"].extend(
1252
+ masked_sample_mse(
1253
+ correct[source],
1254
+ normalized_target,
1255
+ batch["mask"],
1256
+ ).mean(dim=1).cpu().tolist()
1257
+ )
1258
+ accum[f"{source}_negative"].extend(
1259
+ masked_sample_mse(
1260
+ negative[source],
1261
+ normalized_target,
1262
+ batch["mask"],
1263
+ ).mean(dim=1).cpu().tolist()
1264
+ )
1265
+ cosine[source].extend(
1266
+ masked_sample_cosine(
1267
+ correct[source],
1268
+ normalized_target,
1269
+ batch["mask"],
1270
+ ).mean(dim=1).cpu().tolist()
1271
+ )
1272
+ result: Dict[str, float] = {}
1273
+ for source in ["atmosphere", "boundary", "joint"]:
1274
+ correct_value = float(
1275
+ np.mean(accum[f"{source}_correct"])
1276
+ )
1277
+ negative_value = float(
1278
+ np.mean(accum[f"{source}_negative"])
1279
+ )
1280
+ result[f"{source}_correct_mse"] = correct_value
1281
+ result[f"{source}_negative_mse"] = negative_value
1282
+ result[f"{source}_negative_gap"] = (
1283
+ negative_value - correct_value
1284
+ )
1285
+ result[f"{source}_residual_cosine"] = float(
1286
+ np.mean(cosine[source])
1287
+ )
1288
+ return result
1289
+
1290
+
1291
+ def group_alpha_tensor(
1292
+ alpha: np.ndarray,
1293
+ device: torch.device,
1294
+ dtype: torch.dtype,
1295
+ ) -> torch.Tensor:
1296
+ # alpha [H,G] -> [1,H,C,1,1]
1297
+ result = torch.zeros(
1298
+ 1,
1299
+ len(HORIZONS),
1300
+ len(INTERNAL_VARIABLES),
1301
+ 1,
1302
+ 1,
1303
+ device=device,
1304
+ dtype=dtype,
1305
+ )
1306
+ for group_index, indices in enumerate(GROUPS.values()):
1307
+ result[:, :, indices] = torch.as_tensor(
1308
+ alpha[:, group_index],
1309
+ device=device,
1310
+ dtype=dtype,
1311
+ )[None, :, None, None, None]
1312
+ return result
1313
+
1314
+
1315
+ @torch.no_grad()
1316
+ def collect_validation_arrays(
1317
+ model: DualInnovationAudit,
1318
+ parent: FrozenA0Parent,
1319
+ loader: DataLoader,
1320
+ residual_scale: torch.Tensor,
1321
+ device: torch.device,
1322
+ ) -> Dict[str, np.ndarray]:
1323
+ model.eval()
1324
+ collected: Dict[str, List[np.ndarray]] = {
1325
+ "residual": [],
1326
+ "mask": [],
1327
+ "atmosphere": [],
1328
+ "boundary": [],
1329
+ "atmosphere_activity": [],
1330
+ "boundary_activity": [],
1331
+ }
1332
+ for raw_batch in loader:
1333
+ batch = batch_to_device(raw_batch, device)
1334
+ parent_prediction = parent(
1335
+ batch["internal"], parent_sources(batch)
1336
+ )
1337
+ residual = batch["target"] - parent_prediction
1338
+ output = model(
1339
+ batch["future_atmosphere"],
1340
+ batch["future_boundary"],
1341
+ )
1342
+ collected["residual"].append(
1343
+ residual.cpu().numpy()
1344
+ )
1345
+ collected["mask"].append(
1346
+ batch["mask"].cpu().numpy()
1347
+ )
1348
+ for source in SOURCES:
1349
+ collected[source].append(
1350
+ apply_scale(
1351
+ output[source], residual_scale
1352
+ ).cpu().numpy()
1353
+ )
1354
+ collected[f"{source}_activity"].append(
1355
+ output[f"{source}_activity"]
1356
+ .cpu().numpy()
1357
+ )
1358
+ return {
1359
+ key: np.concatenate(values, axis=0)
1360
+ for key, values in collected.items()
1361
+ }
1362
+
1363
+
1364
+ def fit_nonnegative_group_coefficients(
1365
+ arrays: Mapping[str, np.ndarray],
1366
+ max_alpha: float,
1367
+ ) -> Dict[str, Any]:
1368
+ residual = arrays["residual"]
1369
+ mask = arrays["mask"][:, None]
1370
+ atmosphere = arrays["atmosphere"]
1371
+ boundary = arrays["boundary"]
1372
+ alpha_atmosphere = np.zeros(
1373
+ (len(HORIZONS), len(GROUPS)), dtype=np.float32
1374
+ )
1375
+ alpha_boundary = np.zeros_like(alpha_atmosphere)
1376
+ alpha_joint_atmosphere = np.zeros_like(alpha_atmosphere)
1377
+ alpha_joint_boundary = np.zeros_like(alpha_atmosphere)
1378
+ grid = np.linspace(0.0, max_alpha, 13, dtype=np.float32)
1379
+
1380
+ for hi in range(len(HORIZONS)):
1381
+ for gi, indices in enumerate(GROUPS.values()):
1382
+ r = residual[:, hi, indices]
1383
+ a = atmosphere[:, hi, indices]
1384
+ b = boundary[:, hi, indices]
1385
+ m = mask[:, 0]
1386
+ denominator_a = float((a * a * m).sum()) + 1e-12
1387
+ denominator_b = float((b * b * m).sum()) + 1e-12
1388
+ alpha_atmosphere[hi, gi] = np.clip(
1389
+ float((a * r * m).sum()) / denominator_a,
1390
+ 0.0,
1391
+ max_alpha,
1392
+ )
1393
+ alpha_boundary[hi, gi] = np.clip(
1394
+ float((b * r * m).sum()) / denominator_b,
1395
+ 0.0,
1396
+ max_alpha,
1397
+ )
1398
+ best = (float("inf"), 0.0, 0.0)
1399
+ for aa in grid:
1400
+ for bb in grid:
1401
+ error = (
1402
+ (r - aa * a - bb * b) ** 2 * m
1403
+ ).sum()
1404
+ if float(error) < best[0]:
1405
+ best = (float(error), float(aa), float(bb))
1406
+ alpha_joint_atmosphere[hi, gi] = best[1]
1407
+ alpha_joint_boundary[hi, gi] = best[2]
1408
+
1409
+ thresholds = {
1410
+ source: np.quantile(
1411
+ arrays[f"{source}_activity"],
1412
+ 0.80,
1413
+ axis=0,
1414
+ ).astype(np.float32)
1415
+ for source in SOURCES
1416
+ }
1417
+ return {
1418
+ "alpha_atmosphere": alpha_atmosphere,
1419
+ "alpha_boundary": alpha_boundary,
1420
+ "alpha_joint_atmosphere": alpha_joint_atmosphere,
1421
+ "alpha_joint_boundary": alpha_joint_boundary,
1422
+ "activity_thresholds": thresholds,
1423
+ }
1424
+
1425
+
1426
+ def mode_definition(mode: str) -> Tuple[str, str]:
1427
+ if mode == "parent":
1428
+ return "none", "correct"
1429
+ if mode.startswith("atmosphere_"):
1430
+ return "atmosphere", mode.split("_", 1)[1]
1431
+ if mode.startswith("boundary_"):
1432
+ return "boundary", mode.split("_", 1)[1]
1433
+ if mode.startswith("joint_"):
1434
+ return "joint", mode.split("_", 1)[1]
1435
+ raise ValueError(mode)
1436
+
1437
+
1438
+ @torch.no_grad()
1439
+ def evaluate_mode(
1440
+ model: DualInnovationAudit,
1441
+ parent: FrozenA0Parent,
1442
+ loader: DataLoader,
1443
+ residual_scale: torch.Tensor,
1444
+ coefficients: Mapping[str, Any],
1445
+ device: torch.device,
1446
+ mode: str,
1447
+ ) -> Dict[str, Any]:
1448
+ model.eval()
1449
+ source_mode, control = mode_definition(mode)
1450
+ squared = {horizon: 0.0 for horizon in HORIZONS}
1451
+ count = {horizon: 0.0 for horizon in HORIZONS}
1452
+ prediction_values = {
1453
+ horizon: [] for horizon in HORIZONS
1454
+ }
1455
+ target_values = {
1456
+ horizon: [] for horizon in HORIZONS
1457
+ }
1458
+ sample_rows: List[Dict[str, Any]] = []
1459
+ group_rows: Dict[Tuple[int, str], List[float]] = {
1460
+ (horizon, group): []
1461
+ for horizon in HORIZONS
1462
+ for group in GROUPS
1463
+ }
1464
+ cosine_rows: List[Dict[str, Any]] = []
1465
+ update_ratio_rows: List[Dict[str, Any]] = []
1466
+
1467
+ for raw_batch in loader:
1468
+ batch = batch_to_device(raw_batch, device)
1469
+ parent_prediction = parent(
1470
+ batch["internal"], parent_sources(batch)
1471
+ )
1472
+ target = batch["target"]
1473
+ if source_mode == "none":
1474
+ update = torch.zeros_like(parent_prediction)
1475
+ atmosphere_activity = torch.zeros(
1476
+ parent_prediction.shape[0],
1477
+ len(HORIZONS),
1478
+ device=device,
1479
+ )
1480
+ boundary_activity = torch.zeros_like(
1481
+ atmosphere_activity
1482
+ )
1483
+ else:
1484
+ atmosphere_sequence = control_sequence(
1485
+ batch["future_atmosphere"],
1486
+ batch["negative_atmosphere"],
1487
+ control,
1488
+ )
1489
+ boundary_sequence = control_sequence(
1490
+ batch["future_boundary"],
1491
+ batch["negative_boundary"],
1492
+ control,
1493
+ )
1494
+ output = model(
1495
+ atmosphere_sequence, boundary_sequence
1496
+ )
1497
+ atmosphere_raw = apply_scale(
1498
+ output["atmosphere"], residual_scale
1499
+ )
1500
+ boundary_raw = apply_scale(
1501
+ output["boundary"], residual_scale
1502
+ )
1503
+ atmosphere_activity = output[
1504
+ "atmosphere_activity"
1505
+ ]
1506
+ boundary_activity = output[
1507
+ "boundary_activity"
1508
+ ]
1509
+ if source_mode == "atmosphere":
1510
+ alpha = group_alpha_tensor(
1511
+ coefficients["alpha_atmosphere"],
1512
+ device,
1513
+ parent_prediction.dtype,
1514
+ )
1515
+ update = alpha * atmosphere_raw
1516
+ elif source_mode == "boundary":
1517
+ alpha = group_alpha_tensor(
1518
+ coefficients["alpha_boundary"],
1519
+ device,
1520
+ parent_prediction.dtype,
1521
+ )
1522
+ update = alpha * boundary_raw
1523
+ else:
1524
+ alpha_a = group_alpha_tensor(
1525
+ coefficients["alpha_joint_atmosphere"],
1526
+ device,
1527
+ parent_prediction.dtype,
1528
+ )
1529
+ alpha_b = group_alpha_tensor(
1530
+ coefficients["alpha_joint_boundary"],
1531
+ device,
1532
+ parent_prediction.dtype,
1533
+ )
1534
+ update = (
1535
+ alpha_a * atmosphere_raw
1536
+ + alpha_b * boundary_raw
1537
+ )
1538
+
1539
+ prediction = parent_prediction + update
1540
+ residual_target = target - parent_prediction
1541
+ update_cosine = masked_sample_cosine(
1542
+ update,
1543
+ residual_target,
1544
+ batch["mask"],
1545
+ )
1546
+ update_ratio = torch.sqrt(
1547
+ update.square().mean(dim=(2, 3, 4)) + 1e-12
1548
+ ) / (
1549
+ torch.sqrt(
1550
+ parent_prediction.square().mean(
1551
+ dim=(2, 3, 4)
1552
+ ) + 1e-12
1553
+ ) + 1e-6
1554
+ )
1555
+ for hi, horizon in enumerate(HORIZONS):
1556
+ error = (
1557
+ (prediction[:, hi] - target[:, hi]).square()
1558
+ * batch["mask"]
1559
+ )
1560
+ denominator = (
1561
+ batch["mask"].flatten(1).sum(dim=1)
1562
+ .clamp_min(1.0)
1563
+ * prediction.shape[2]
1564
+ )
1565
+ per_sample_mse = (
1566
+ error.flatten(1).sum(dim=1)
1567
+ / denominator
1568
+ )
1569
+ squared[horizon] += float(error.sum())
1570
+ count[horizon] += (
1571
+ float(batch["mask"].sum())
1572
+ * prediction.shape[2]
1573
+ )
1574
+ prediction_values[horizon].append(
1575
+ (prediction[:, hi] * batch["mask"])
1576
+ .flatten(1).cpu()
1577
+ )
1578
+ target_values[horizon].append(
1579
+ (target[:, hi] * batch["mask"])
1580
+ .flatten(1).cpu()
1581
+ )
1582
+ for bi in range(prediction.shape[0]):
1583
+ sample_rows.append({
1584
+ "sample_index": int(
1585
+ batch["sample_index"][bi]
1586
+ ),
1587
+ "horizon": horizon,
1588
+ "mse": float(per_sample_mse[bi]),
1589
+ "rmse": math.sqrt(
1590
+ max(float(per_sample_mse[bi]), 0.0)
1591
+ ),
1592
+ "atmosphere_activity": float(
1593
+ atmosphere_activity[bi, hi]
1594
+ ),
1595
+ "boundary_activity": float(
1596
+ boundary_activity[bi, hi]
1597
+ ),
1598
+ })
1599
+ cosine_rows.append({
1600
+ "sample_index": int(
1601
+ batch["sample_index"][bi]
1602
+ ),
1603
+ "horizon": horizon,
1604
+ "cosine": float(
1605
+ update_cosine[bi, hi]
1606
+ ),
1607
+ })
1608
+ update_ratio_rows.append({
1609
+ "sample_index": int(
1610
+ batch["sample_index"][bi]
1611
+ ),
1612
+ "horizon": horizon,
1613
+ "update_ratio": float(
1614
+ update_ratio[bi, hi]
1615
+ ),
1616
+ })
1617
+ for group, indices in GROUPS.items():
1618
+ group_error = (
1619
+ (
1620
+ prediction[:, hi, indices]
1621
+ - target[:, hi, indices]
1622
+ ).square()
1623
+ * batch["mask"]
1624
+ )
1625
+ group_denominator = (
1626
+ batch["mask"].flatten(1)
1627
+ .sum(dim=1).clamp_min(1.0)
1628
+ * len(indices)
1629
+ )
1630
+ group_rmse = torch.sqrt(
1631
+ group_error.flatten(1).sum(dim=1)
1632
+ / group_denominator
1633
+ )
1634
+ group_rows[(horizon, group)].extend(
1635
+ group_rmse.cpu().tolist()
1636
+ )
1637
+
1638
+ metrics: Dict[str, Any] = {}
1639
+ for horizon in HORIZONS:
1640
+ metrics[f"rmse_h{horizon}"] = math.sqrt(
1641
+ squared[horizon]
1642
+ / max(count[horizon], 1.0)
1643
+ )
1644
+ pred = torch.cat(
1645
+ prediction_values[horizon], dim=0
1646
+ )
1647
+ truth = torch.cat(
1648
+ target_values[horizon], dim=0
1649
+ )
1650
+ metrics[f"variance_ratio_h{horizon}"] = float(
1651
+ pred.var(unbiased=False)
1652
+ / (truth.var(unbiased=False) + 1e-8)
1653
+ )
1654
+ for (horizon, group), values in group_rows.items():
1655
+ metrics[
1656
+ f"group_rmse_{group}_h{horizon}"
1657
+ ] = float(np.mean(values))
1658
+ metrics["sample_rows"] = sample_rows
1659
+ metrics["cosine_mean"] = float(
1660
+ pd.DataFrame(cosine_rows)["cosine"].mean()
1661
+ )
1662
+ metrics["update_ratio_mean"] = float(
1663
+ pd.DataFrame(update_ratio_rows)[
1664
+ "update_ratio"
1665
+ ].mean()
1666
+ )
1667
+ return metrics
1668
+
1669
+
1670
+ def paired_bootstrap(
1671
+ reference: np.ndarray,
1672
+ candidate: np.ndarray,
1673
+ replicates: int,
1674
+ seed: int,
1675
+ ) -> Dict[str, float]:
1676
+ if len(reference) != len(candidate):
1677
+ raise ValueError("Paired arrays have different lengths")
1678
+ difference = candidate - reference
1679
+ generator = np.random.default_rng(seed)
1680
+ estimates = []
1681
+ for _ in range(replicates):
1682
+ indices = generator.integers(
1683
+ 0, len(difference), len(difference)
1684
+ )
1685
+ estimates.append(
1686
+ float(difference[indices].mean())
1687
+ )
1688
+ low, high = np.percentile(estimates, [2.5, 97.5])
1689
+ return {
1690
+ "mean_mse_difference": float(difference.mean()),
1691
+ "ci_low": float(low),
1692
+ "ci_high": float(high),
1693
+ "mse_gain_percent": float(
1694
+ 100.0
1695
+ * (reference.mean() - candidate.mean())
1696
+ / max(reference.mean(), 1e-12)
1697
+ ),
1698
+ "n": int(len(difference)),
1699
+ }
1700
+
1701
+
1702
+ def activity_subset_result(
1703
+ parent_table: pd.DataFrame,
1704
+ correct_table: pd.DataFrame,
1705
+ negative_table: pd.DataFrame,
1706
+ source: str,
1707
+ horizon: int,
1708
+ threshold: float,
1709
+ ) -> Dict[str, float]:
1710
+ activity_column = f"{source}_activity"
1711
+ correct = correct_table[
1712
+ correct_table.horizon == horizon
1713
+ ].sort_values("sample_index")
1714
+ parent = parent_table[
1715
+ parent_table.horizon == horizon
1716
+ ].sort_values("sample_index")
1717
+ negative = negative_table[
1718
+ negative_table.horizon == horizon
1719
+ ].sort_values("sample_index")
1720
+ if not (
1721
+ np.array_equal(
1722
+ correct.sample_index.to_numpy(),
1723
+ parent.sample_index.to_numpy(),
1724
+ )
1725
+ and np.array_equal(
1726
+ correct.sample_index.to_numpy(),
1727
+ negative.sample_index.to_numpy(),
1728
+ )
1729
+ ):
1730
+ raise RuntimeError("Activity subset pairing mismatch")
1731
+ active = correct[activity_column].to_numpy() >= threshold
1732
+ if active.sum() == 0:
1733
+ return {
1734
+ "n": 0,
1735
+ "gain_vs_parent_percent": float("nan"),
1736
+ "gain_vs_negative_percent": float("nan"),
1737
+ }
1738
+ parent_mse = parent.mse.to_numpy()[active]
1739
+ correct_mse = correct.mse.to_numpy()[active]
1740
+ negative_mse = negative.mse.to_numpy()[active]
1741
+ return {
1742
+ "n": int(active.sum()),
1743
+ "gain_vs_parent_percent": float(
1744
+ 100.0
1745
+ * (parent_mse.mean() - correct_mse.mean())
1746
+ / max(parent_mse.mean(), 1e-12)
1747
+ ),
1748
+ "gain_vs_negative_percent": float(
1749
+ 100.0
1750
+ * (negative_mse.mean() - correct_mse.mean())
1751
+ / max(negative_mse.mean(), 1e-12)
1752
+ ),
1753
+ }
1754
+
1755
+
1756
+ def runtime_audit(
1757
+ model: DualInnovationAudit,
1758
+ loader: DataLoader,
1759
+ device: torch.device,
1760
+ warmup: int = 10,
1761
+ repeats: int = 50,
1762
+ ) -> Dict[str, float]:
1763
+ model.eval()
1764
+ batch = batch_to_device(
1765
+ next(iter(loader)), device
1766
+ )
1767
+ def execute() -> None:
1768
+ model(
1769
+ batch["future_atmosphere"],
1770
+ batch["future_boundary"],
1771
+ )
1772
+ with torch.no_grad():
1773
+ for _ in range(warmup):
1774
+ execute()
1775
+ if device.type == "cuda":
1776
+ torch.cuda.synchronize()
1777
+ start = time.perf_counter()
1778
+ for _ in range(repeats):
1779
+ execute()
1780
+ if device.type == "cuda":
1781
+ torch.cuda.synchronize()
1782
+ elapsed = time.perf_counter() - start
1783
+ batch_size = batch["internal"].shape[0]
1784
+ return {
1785
+ "batch_size": int(batch_size),
1786
+ "mean_batch_ms": 1000.0 * elapsed / repeats,
1787
+ "mean_sample_ms": (
1788
+ 1000.0 * elapsed / repeats / batch_size
1789
+ ),
1790
+ }
1791
+
1792
+
1793
+ def plot_summary(
1794
+ summary: pd.DataFrame,
1795
+ activity: pd.DataFrame,
1796
+ output_dir: Path,
1797
+ ) -> None:
1798
+ output_dir.mkdir(parents=True, exist_ok=True)
1799
+ subset = summary[
1800
+ summary["horizon"] == 12
1801
+ ].copy()
1802
+ plt.figure(figsize=(11, 5))
1803
+ plt.bar(
1804
+ subset["mode"],
1805
+ subset["rmse_gain_vs_parent_percent"],
1806
+ )
1807
+ plt.axhline(0, linewidth=1)
1808
+ plt.ylabel("72 h RMSE gain over A0 parent (%)")
1809
+ plt.xticks(rotation=30, ha="right")
1810
+ plt.tight_layout()
1811
+ plt.savefig(
1812
+ output_dir / "S2A1R2_72h_RMSE_gain.png",
1813
+ dpi=180,
1814
+ )
1815
+ plt.close()
1816
+
1817
+ plt.figure(figsize=(8, 5))
1818
+ active72 = activity[
1819
+ activity["horizon"] == 12
1820
+ ]
1821
+ labels = (
1822
+ active72["source"]
1823
+ + "_"
1824
+ + active72["seed"].astype(str)
1825
+ )
1826
+ plt.bar(
1827
+ labels,
1828
+ active72["gain_vs_parent_percent"],
1829
+ )
1830
+ plt.axhline(0, linewidth=1)
1831
+ plt.ylabel("Top-20% active subset RMSE gain (%)")
1832
+ plt.xticks(rotation=30, ha="right")
1833
+ plt.tight_layout()
1834
+ plt.savefig(
1835
+ output_dir / "S2A1R2_active_subset_gain.png",
1836
+ dpi=180,
1837
+ )
1838
+ plt.close()
1839
+
1840
+
1841
+ def package_output(output_dir: Path) -> Path:
1842
+ target = output_dir.parent / f"{output_dir.name}.zip"
1843
+ target.unlink(missing_ok=True)
1844
+ with zipfile.ZipFile(
1845
+ target, "w", zipfile.ZIP_DEFLATED
1846
+ ) as archive:
1847
+ for path in output_dir.rglob("*"):
1848
+ if path.is_file():
1849
+ archive.write(
1850
+ path,
1851
+ path.relative_to(output_dir.parent),
1852
+ )
1853
+ return target
1854
+
1855
+
1856
+ def create_synthetic_assets(args: argparse.Namespace) -> None:
1857
+ cache = Path(args.cache_dir)
1858
+ prepared = cache / "prepared"
1859
+ prepared.mkdir(parents=True, exist_ok=True)
1860
+ generator = np.random.default_rng(20260930)
1861
+ for wi, spec in enumerate(WINDOWS):
1862
+ t = args.smoke_time_steps
1863
+ h = args.smoke_height
1864
+ w = args.smoke_width
1865
+ time_values = (
1866
+ np.datetime64("2023-01-01")
1867
+ + np.arange(t) * np.timedelta64(6, "h")
1868
+ + wi * np.timedelta64(100, "D")
1869
+ )
1870
+ atmosphere = generator.normal(
1871
+ 0, 1, (t, 9, h, w)
1872
+ ).astype(np.float32)
1873
+ boundary = generator.normal(
1874
+ 0, 1, (t, 10, h, w)
1875
+ ).astype(np.float32)
1876
+ vertical = generator.normal(
1877
+ 0, 1, (t, 10, h, w)
1878
+ ).astype(np.float32)
1879
+ internal = generator.normal(
1880
+ 0, 0.5, (t, 16, h, w)
1881
+ ).astype(np.float32)
1882
+ for index in range(1, t):
1883
+ forcing = (
1884
+ 0.04 * atmosphere[index, :1]
1885
+ + 0.03 * boundary[index, :1]
1886
+ )
1887
+ internal[index] = (
1888
+ 0.90 * internal[index - 1]
1889
+ + forcing
1890
+ + generator.normal(
1891
+ 0, 0.03, internal[index].shape
1892
+ )
1893
+ )
1894
+ mask = np.ones((t, 1, h, w), np.float32)
1895
+ lat = np.linspace(0, 25, h, dtype=np.float32)
1896
+ lon = np.linspace(99, 123, w, dtype=np.float32)
1897
+ stamp = time_values.astype(
1898
+ "datetime64[ns]"
1899
+ ).astype("int64")
1900
+ np.savez_compressed(
1901
+ prepared / f"{spec['name']}_cmems.npz",
1902
+ time=stamp,
1903
+ latitude=lat,
1904
+ longitude=lon,
1905
+ internal=internal,
1906
+ vertical=vertical,
1907
+ boundary=boundary,
1908
+ ocean_mask=mask,
1909
+ )
1910
+ np.savez_compressed(
1911
+ prepared
1912
+ / f"{spec['name']}_atmosphere_aligned.npz",
1913
+ time=stamp,
1914
+ atmosphere=atmosphere,
1915
+ )
1916
+ np.savez_compressed(
1917
+ prepared / f"{spec['name']}_tide.npz",
1918
+ time=stamp,
1919
+ tide=np.zeros(
1920
+ (t, 11, h, w), np.float32
1921
+ ),
1922
+ actual_spatial_tide=np.asarray([0], np.int8),
1923
+ )
1924
+ np.savez_compressed(
1925
+ prepared / f"{spec['name']}_river.npz",
1926
+ time=stamp,
1927
+ river=np.zeros(
1928
+ (t, 2, h, w), np.float32
1929
+ ),
1930
+ available=np.asarray([0], np.int8),
1931
+ )
1932
+ np.savez_compressed(
1933
+ prepared / f"{spec['name']}_events.npz",
1934
+ time=stamp,
1935
+ events=np.zeros(
1936
+ (t, 3, h, w), np.float32
1937
+ ),
1938
+ available=np.asarray([0], np.int8),
1939
+ )
1940
+
1941
+
1942
+ def build_parser() -> argparse.ArgumentParser:
1943
+ parser = argparse.ArgumentParser(
1944
+ description=(
1945
+ "CIDM-v3 S2-A1-R2 conditional external "
1946
+ "innovation capacity audit"
1947
+ )
1948
+ )
1949
+ parser.add_argument(
1950
+ "--cache_dir",
1951
+ default="/content/CIDM_v3_SCS_S2A0_Cache",
1952
+ )
1953
+ parser.add_argument(
1954
+ "--r1_zip",
1955
+ default="/content/CIDM_v3_SCS_V3_S2_A1_R1.zip",
1956
+ )
1957
+ parser.add_argument(
1958
+ "--output_dir",
1959
+ default="/content/CIDM_v3_SCS_V3_S2_A1_R2",
1960
+ )
1961
+ parser.add_argument(
1962
+ "--hf_repo_id",
1963
+ default="wuff-mann/CIDM-v3-SCS-S2A0-Data",
1964
+ )
1965
+ parser.add_argument("--hf_token", default="")
1966
+ parser.add_argument("--history", type=int, default=4)
1967
+ parser.add_argument("--epochs", type=int, default=10)
1968
+ parser.add_argument("--batch_size", type=int, default=4)
1969
+ parser.add_argument("--num_workers", type=int, default=0)
1970
+ parser.add_argument("--hidden", type=int, default=40)
1971
+ parser.add_argument(
1972
+ "--learning_rate", type=float, default=3e-4
1973
+ )
1974
+ parser.add_argument(
1975
+ "--weight_decay", type=float, default=1e-4
1976
+ )
1977
+ parser.add_argument(
1978
+ "--atmosphere_weight", type=float, default=0.30
1979
+ )
1980
+ parser.add_argument(
1981
+ "--boundary_weight", type=float, default=0.30
1982
+ )
1983
+ parser.add_argument(
1984
+ "--joint_weight", type=float, default=0.40
1985
+ )
1986
+ parser.add_argument(
1987
+ "--rank_weight", type=float, default=0.20
1988
+ )
1989
+ parser.add_argument(
1990
+ "--alignment_weight", type=float, default=0.05
1991
+ )
1992
+ parser.add_argument(
1993
+ "--rank_margin", type=float, default=0.002
1994
+ )
1995
+ parser.add_argument(
1996
+ "--cosine_margin", type=float, default=0.01
1997
+ )
1998
+ parser.add_argument(
1999
+ "--selection_causal_weight",
2000
+ type=float,
2001
+ default=0.50,
2002
+ )
2003
+ parser.add_argument(
2004
+ "--max_alpha", type=float, default=1.5
2005
+ )
2006
+ parser.add_argument(
2007
+ "--grad_clip", type=float, default=1.0
2008
+ )
2009
+ parser.add_argument(
2010
+ "--seeds",
2011
+ default="20260910,20260911,20260912",
2012
+ )
2013
+ parser.add_argument(
2014
+ "--bootstrap_reps", type=int, default=1000
2015
+ )
2016
+ parser.add_argument(
2017
+ "--synthetic_smoke", action="store_true"
2018
+ )
2019
+ parser.add_argument(
2020
+ "--smoke_time_steps", type=int, default=48
2021
+ )
2022
+ parser.add_argument(
2023
+ "--smoke_height", type=int, default=16
2024
+ )
2025
+ parser.add_argument(
2026
+ "--smoke_width", type=int, default=16
2027
+ )
2028
+ return parser
2029
+
2030
+
2031
+ def main() -> None:
2032
+ args = build_parser().parse_args()
2033
+ seeds = [
2034
+ int(value)
2035
+ for value in args.seeds.split(",")
2036
+ if value.strip()
2037
+ ]
2038
+ if not seeds:
2039
+ raise ValueError("At least one seed is required")
2040
+ device = torch.device(
2041
+ "cuda" if torch.cuda.is_available() else "cpu"
2042
+ )
2043
+ if not args.synthetic_smoke and device.type != "cuda":
2044
+ raise RuntimeError(
2045
+ "Formal S2-A1-R2 requires a CUDA GPU"
2046
+ )
2047
+ torch.set_float32_matmul_precision("highest")
2048
+ output_dir = Path(args.output_dir)
2049
+ if output_dir.exists():
2050
+ shutil.rmtree(output_dir)
2051
+ for subdir in [
2052
+ "training",
2053
+ "checkpoints",
2054
+ "evaluation",
2055
+ "audits",
2056
+ "figures",
2057
+ "lineage",
2058
+ ]:
2059
+ (output_dir / subdir).mkdir(
2060
+ parents=True, exist_ok=True
2061
+ )
2062
+
2063
+ try:
2064
+ stage(1, 11, "恢复R1谱系和四季prepared数据")
2065
+ if args.synthetic_smoke:
2066
+ create_synthetic_assets(args)
2067
+ hf_report = {"synthetic_smoke": True}
2068
+ else:
2069
+ hf_report = ensure_hf_assets(args)
2070
+ atomic_json(
2071
+ hf_report,
2072
+ output_dir
2073
+ / "audits"
2074
+ / "S2A1R2_HF_asset_audit.json",
2075
+ )
2076
+
2077
+ stage(2, 11, "提取R1结论与嵌套A0冻结父链")
2078
+ assets = extract_r1_lineage(
2079
+ Path(args.r1_zip),
2080
+ output_dir / "_parent",
2081
+ )
2082
+ r1_verdict = json.loads(
2083
+ assets["r1_verdict"].read_text(
2084
+ encoding="utf-8"
2085
+ )
2086
+ )
2087
+ r1_aggregate = json.loads(
2088
+ assets["r1_aggregate"].read_text(
2089
+ encoding="utf-8"
2090
+ )
2091
+ )
2092
+ atomic_json(
2093
+ {
2094
+ "r1_verdict": r1_verdict,
2095
+ "r1_aggregate": r1_aggregate,
2096
+ "r2_parent": (
2097
+ "Frozen S2-A0 internal + history/current "
2098
+ "external adapter"
2099
+ ),
2100
+ "vertical_note": (
2101
+ "Current vertical context is already contained "
2102
+ "in A0 and is not treated as new future innovation."
2103
+ ),
2104
+ },
2105
+ output_dir
2106
+ / "lineage"
2107
+ / "S2A1R2_parent_lineage.json",
2108
+ )
2109
+
2110
+ stage(3, 11, "加载四季数据并建立同季节负样本")
2111
+ windows = [
2112
+ load_window(Path(args.cache_dir), spec)
2113
+ for spec in WINDOWS
2114
+ ]
2115
+ loaders, split_audit = build_loaders(
2116
+ windows, assets["stats"], args
2117
+ )
2118
+ atomic_json(
2119
+ split_audit,
2120
+ output_dir
2121
+ / "audits"
2122
+ / "S2A1R2_split_audit.json",
2123
+ )
2124
+ shape_rows = []
2125
+ for window in windows:
2126
+ shape_rows.append({
2127
+ "window": window.name,
2128
+ "role": window.role,
2129
+ "time_steps": len(window.time),
2130
+ "internal_shape": str(
2131
+ tuple(window.internal.shape)
2132
+ ),
2133
+ "atmosphere_shape": str(
2134
+ tuple(
2135
+ window.sources["atmosphere"].shape
2136
+ )
2137
+ ),
2138
+ "boundary_shape": str(
2139
+ tuple(
2140
+ window.sources["boundary"].shape
2141
+ )
2142
+ ),
2143
+ "finite": True,
2144
+ })
2145
+ pd.DataFrame(shape_rows).to_csv(
2146
+ output_dir
2147
+ / "audits"
2148
+ / "S2A1R2_data_shape_audit.csv",
2149
+ index=False,
2150
+ )
2151
+
2152
+ stage(4, 11, "重建三种子A0父模型")
2153
+ parents = {
2154
+ seed: load_parent(
2155
+ assets["a0_root"], seed, device
2156
+ )
2157
+ for seed in seeds
2158
+ }
2159
+
2160
+ stage(5, 11, "训练来源专属条件创新残差探针")
2161
+ models: Dict[int, DualInnovationAudit] = {}
2162
+ residual_scales: Dict[int, torch.Tensor] = {}
2163
+ training_records = []
2164
+ for seed in seeds:
2165
+ model, scale, record = train_probe(
2166
+ seed,
2167
+ parents[seed],
2168
+ loaders,
2169
+ args,
2170
+ device,
2171
+ output_dir,
2172
+ )
2173
+ models[seed] = model
2174
+ residual_scales[seed] = scale
2175
+ training_records.append(record)
2176
+ training_table = pd.DataFrame(training_records)
2177
+ training_table.to_csv(
2178
+ output_dir
2179
+ / "S2A1R2_training_summary.csv",
2180
+ index=False,
2181
+ )
2182
+
2183
+ stage(6, 11, "仅用验证集拟合非负来源收缩系数")
2184
+ coefficient_payload: Dict[str, Any] = {}
2185
+ coefficients: Dict[int, Dict[str, Any]] = {}
2186
+ for seed in seeds:
2187
+ arrays = collect_validation_arrays(
2188
+ models[seed],
2189
+ parents[seed],
2190
+ loaders["validation"],
2191
+ residual_scales[seed],
2192
+ device,
2193
+ )
2194
+ fitted = fit_nonnegative_group_coefficients(
2195
+ arrays, args.max_alpha
2196
+ )
2197
+ coefficients[seed] = fitted
2198
+ coefficient_payload[str(seed)] = {
2199
+ key: value
2200
+ for key, value in fitted.items()
2201
+ }
2202
+ atomic_json(
2203
+ coefficient_payload,
2204
+ output_dir
2205
+ / "S2A1R2_validation_coefficients.json",
2206
+ )
2207
+
2208
+ stage(7, 11, "评估正确创新、负样本和时间反事实")
2209
+ modes = [
2210
+ "parent",
2211
+ "atmosphere_correct",
2212
+ "atmosphere_negative",
2213
+ "atmosphere_history",
2214
+ "atmosphere_reversed",
2215
+ "atmosphere_shifted",
2216
+ "boundary_correct",
2217
+ "boundary_negative",
2218
+ "boundary_history",
2219
+ "boundary_reversed",
2220
+ "boundary_shifted",
2221
+ "joint_correct",
2222
+ "joint_negative",
2223
+ "joint_history",
2224
+ "joint_reversed",
2225
+ "joint_shifted",
2226
+ ]
2227
+ metric_rows = []
2228
+ sample_tables: Dict[Tuple[int, str], pd.DataFrame] = {}
2229
+ for seed in seeds:
2230
+ for mode in modes:
2231
+ metrics = evaluate_mode(
2232
+ models[seed],
2233
+ parents[seed],
2234
+ loaders["test"],
2235
+ residual_scales[seed],
2236
+ coefficients[seed],
2237
+ device,
2238
+ mode,
2239
+ )
2240
+ sample_tables[(seed, mode)] = pd.DataFrame(
2241
+ metrics.pop("sample_rows")
2242
+ )
2243
+ metric_rows.append({
2244
+ "seed": seed,
2245
+ "mode": mode,
2246
+ **metrics,
2247
+ })
2248
+ metric_table = pd.DataFrame(metric_rows)
2249
+ metric_table.to_csv(
2250
+ output_dir
2251
+ / "evaluation"
2252
+ / "S2A1R2_seed_metrics.csv",
2253
+ index=False,
2254
+ )
2255
+
2256
+ stage(8, 11, "配对Bootstrap和事件活跃子集审计")
2257
+ parent_rmse = {
2258
+ horizon: metric_table[
2259
+ metric_table["mode"] == "parent"
2260
+ ][f"rmse_h{horizon}"].mean()
2261
+ for horizon in HORIZONS
2262
+ }
2263
+ summary_rows = []
2264
+ bootstrap_payload: Dict[str, Any] = {}
2265
+ for mode in modes:
2266
+ for horizon in HORIZONS:
2267
+ subset = metric_table[
2268
+ metric_table["mode"] == mode
2269
+ ]
2270
+ rmse = float(
2271
+ subset[f"rmse_h{horizon}"].mean()
2272
+ )
2273
+ variance = float(
2274
+ subset[
2275
+ f"variance_ratio_h{horizon}"
2276
+ ].mean()
2277
+ )
2278
+ reference_all = []
2279
+ candidate_all = []
2280
+ seed_gains = []
2281
+ for seed in seeds:
2282
+ reference = sample_tables[
2283
+ (seed, "parent")
2284
+ ]
2285
+ candidate = sample_tables[(seed, mode)]
2286
+ reference_mse = reference[
2287
+ reference.horizon == horizon
2288
+ ].sort_values(
2289
+ "sample_index"
2290
+ ).mse.to_numpy()
2291
+ candidate_mse = candidate[
2292
+ candidate.horizon == horizon
2293
+ ].sort_values(
2294
+ "sample_index"
2295
+ ).mse.to_numpy()
2296
+ reference_all.append(reference_mse)
2297
+ candidate_all.append(candidate_mse)
2298
+ reference_rmse = float(
2299
+ metric_table[
2300
+ (metric_table.seed == seed)
2301
+ & (metric_table["mode"] == "parent")
2302
+ ][f"rmse_h{horizon}"].iloc[0]
2303
+ )
2304
+ candidate_rmse = float(
2305
+ metric_table[
2306
+ (metric_table.seed == seed)
2307
+ & (metric_table["mode"] == mode)
2308
+ ][f"rmse_h{horizon}"].iloc[0]
2309
+ )
2310
+ seed_gains.append(
2311
+ 100.0
2312
+ * (
2313
+ reference_rmse
2314
+ - candidate_rmse
2315
+ )
2316
+ / reference_rmse
2317
+ )
2318
+ bootstrap = paired_bootstrap(
2319
+ np.concatenate(reference_all),
2320
+ np.concatenate(candidate_all),
2321
+ args.bootstrap_reps,
2322
+ seeds[0]
2323
+ + horizon * 1000
2324
+ + sum(ord(char) for char in mode),
2325
+ )
2326
+ bootstrap_payload[
2327
+ f"{mode}_h{horizon}"
2328
+ ] = bootstrap
2329
+ summary_rows.append({
2330
+ "mode": mode,
2331
+ "horizon": horizon,
2332
+ "lead_hours": horizon * 6,
2333
+ "rmse": rmse,
2334
+ "variance_ratio": variance,
2335
+ "rmse_gain_vs_parent_percent": (
2336
+ 100.0
2337
+ * (parent_rmse[horizon] - rmse)
2338
+ / parent_rmse[horizon]
2339
+ ),
2340
+ "mse_gain_vs_parent_percent": (
2341
+ bootstrap["mse_gain_percent"]
2342
+ ),
2343
+ "bootstrap_low": bootstrap["ci_low"],
2344
+ "bootstrap_high": bootstrap["ci_high"],
2345
+ "all_seed_positive": bool(
2346
+ all(value > 0 for value in seed_gains)
2347
+ ),
2348
+ "seed_gain_min": float(
2349
+ min(seed_gains)
2350
+ ),
2351
+ "seed_gain_max": float(
2352
+ max(seed_gains)
2353
+ ),
2354
+ })
2355
+ summary = pd.DataFrame(summary_rows)
2356
+ summary.to_csv(
2357
+ output_dir
2358
+ / "S2A1R2_counterfactual_summary.csv",
2359
+ index=False,
2360
+ )
2361
+ atomic_json(
2362
+ bootstrap_payload,
2363
+ output_dir / "paired_bootstrap.json",
2364
+ )
2365
+
2366
+ activity_rows = []
2367
+ for seed in seeds:
2368
+ for source in SOURCES:
2369
+ correct_mode = f"{source}_correct"
2370
+ negative_mode = f"{source}_negative"
2371
+ for hi, horizon in enumerate(HORIZONS):
2372
+ result = activity_subset_result(
2373
+ sample_tables[(seed, "parent")],
2374
+ sample_tables[(seed, correct_mode)],
2375
+ sample_tables[(seed, negative_mode)],
2376
+ source,
2377
+ horizon,
2378
+ float(
2379
+ coefficients[seed][
2380
+ "activity_thresholds"
2381
+ ][source][hi]
2382
+ ),
2383
+ )
2384
+ activity_rows.append({
2385
+ "seed": seed,
2386
+ "source": source,
2387
+ "horizon": horizon,
2388
+ "lead_hours": horizon * 6,
2389
+ "validation_threshold": float(
2390
+ coefficients[seed][
2391
+ "activity_thresholds"
2392
+ ][source][hi]
2393
+ ),
2394
+ **result,
2395
+ })
2396
+ activity_table = pd.DataFrame(activity_rows)
2397
+ activity_table.to_csv(
2398
+ output_dir
2399
+ / "S2A1R2_active_subset_summary.csv",
2400
+ index=False,
2401
+ )
2402
+
2403
+ stage(9, 11, "来源容量与正式分流判决")
2404
+ runtime_rows = []
2405
+ for seed in seeds:
2406
+ runtime_row = runtime_audit(
2407
+ models[seed],
2408
+ loaders["test"],
2409
+ device,
2410
+ )
2411
+ runtime_row["seed"] = seed
2412
+ runtime_rows.append(runtime_row)
2413
+ runtime_table = pd.DataFrame(runtime_rows)
2414
+ runtime_table.to_csv(
2415
+ output_dir / "S2A1R2_runtime.csv",
2416
+ index=False,
2417
+ )
2418
+
2419
+ def value(
2420
+ mode: str,
2421
+ horizon: int,
2422
+ column: str,
2423
+ ) -> float:
2424
+ return float(
2425
+ summary[
2426
+ (summary["mode"] == mode)
2427
+ & (summary["horizon"] == horizon)
2428
+ ][column].iloc[0]
2429
+ )
2430
+
2431
+ atmosphere_gain = value(
2432
+ "atmosphere_correct",
2433
+ 12,
2434
+ "rmse_gain_vs_parent_percent",
2435
+ )
2436
+ boundary_gain = value(
2437
+ "boundary_correct",
2438
+ 12,
2439
+ "rmse_gain_vs_parent_percent",
2440
+ )
2441
+ joint_gain = value(
2442
+ "joint_correct",
2443
+ 12,
2444
+ "rmse_gain_vs_parent_percent",
2445
+ )
2446
+ atmosphere_negative_gap = (
2447
+ value(
2448
+ "atmosphere_negative", 12, "rmse"
2449
+ )
2450
+ - value(
2451
+ "atmosphere_correct", 12, "rmse"
2452
+ )
2453
+ ) / value(
2454
+ "atmosphere_negative", 12, "rmse"
2455
+ ) * 100.0
2456
+ boundary_negative_gap = (
2457
+ value(
2458
+ "boundary_negative", 12, "rmse"
2459
+ )
2460
+ - value(
2461
+ "boundary_correct", 12, "rmse"
2462
+ )
2463
+ ) / value(
2464
+ "boundary_negative", 12, "rmse"
2465
+ ) * 100.0
2466
+ joint_negative_gap = (
2467
+ value("joint_negative", 12, "rmse")
2468
+ - value("joint_correct", 12, "rmse")
2469
+ ) / value(
2470
+ "joint_negative", 12, "rmse"
2471
+ ) * 100.0
2472
+ joint_variance_change = (
2473
+ value(
2474
+ "joint_correct", 12, "variance_ratio"
2475
+ )
2476
+ - value(
2477
+ "parent", 12, "variance_ratio"
2478
+ )
2479
+ )
2480
+ atmosphere_active = float(
2481
+ activity_table[
2482
+ (activity_table.source == "atmosphere")
2483
+ & (activity_table.horizon == 12)
2484
+ ]["gain_vs_parent_percent"].mean()
2485
+ )
2486
+ boundary_active = float(
2487
+ activity_table[
2488
+ (activity_table.source == "boundary")
2489
+ & (activity_table.horizon == 12)
2490
+ ]["gain_vs_parent_percent"].mean()
2491
+ )
2492
+ source_zero_max = float(
2493
+ training_table["source_zero_max"].max()
2494
+ )
2495
+ all_seed_joint = bool(
2496
+ summary[
2497
+ (summary["mode"] == "joint_correct")
2498
+ & (summary["horizon"] == 12)
2499
+ ]["all_seed_positive"].iloc[0]
2500
+ )
2501
+ joint_bootstrap_positive = value(
2502
+ "joint_correct", 12, "bootstrap_high"
2503
+ ) < 0
2504
+ atmosphere_bootstrap_positive = value(
2505
+ "atmosphere_correct", 12, "bootstrap_high"
2506
+ ) < 0
2507
+ boundary_bootstrap_positive = value(
2508
+ "boundary_correct", 12, "bootstrap_high"
2509
+ ) < 0
2510
+
2511
+ checks = {
2512
+ "r1_and_nested_a0_loaded_three_seeds": (
2513
+ len(parents) == 3 and len(seeds) == 3
2514
+ ),
2515
+ "source_zero_sentinel_lt_1e8": (
2516
+ source_zero_max < 1e-8
2517
+ ),
2518
+ "validation_only_coefficients_present": (
2519
+ len(coefficients) == len(seeds)
2520
+ ),
2521
+ "atmosphere_72h_gain_ge_0_10pct": (
2522
+ atmosphere_gain >= 0.10
2523
+ ),
2524
+ "atmosphere_72h_bootstrap_positive": (
2525
+ atmosphere_bootstrap_positive
2526
+ ),
2527
+ "atmosphere_correct_beats_negative_ge_0_05pct": (
2528
+ atmosphere_negative_gap >= 0.05
2529
+ ),
2530
+ "boundary_72h_gain_ge_0_05pct": (
2531
+ boundary_gain >= 0.05
2532
+ ),
2533
+ "boundary_72h_bootstrap_positive": (
2534
+ boundary_bootstrap_positive
2535
+ ),
2536
+ "boundary_correct_beats_negative_ge_0_03pct": (
2537
+ boundary_negative_gap >= 0.03
2538
+ ),
2539
+ "joint_72h_gain_ge_0_30pct": (
2540
+ joint_gain >= 0.30
2541
+ ),
2542
+ "joint_all_three_seeds_positive": (
2543
+ all_seed_joint
2544
+ ),
2545
+ "joint_72h_bootstrap_positive": (
2546
+ joint_bootstrap_positive
2547
+ ),
2548
+ "joint_correct_beats_negative_ge_0_08pct": (
2549
+ joint_negative_gap >= 0.08
2550
+ ),
2551
+ "atmosphere_active_top20_gain_ge_0_30pct": (
2552
+ atmosphere_active >= 0.30
2553
+ ),
2554
+ "boundary_active_top20_gain_ge_0_20pct": (
2555
+ boundary_active >= 0.20
2556
+ ),
2557
+ "joint_variance_not_worse_by_0_02": (
2558
+ joint_variance_change >= -0.02
2559
+ ),
2560
+ "mean_probe_runtime_lt_10ms": (
2561
+ float(
2562
+ runtime_table[
2563
+ "mean_sample_ms"
2564
+ ].mean()
2565
+ ) < 10.0
2566
+ ),
2567
+ "all_metrics_finite": bool(
2568
+ np.isfinite(
2569
+ metric_table.select_dtypes(
2570
+ include=[np.number]
2571
+ ).to_numpy()
2572
+ ).all()
2573
+ ),
2574
+ }
2575
+ passed = sum(bool(item) for item in checks.values())
2576
+ critical = [
2577
+ "source_zero_sentinel_lt_1e8",
2578
+ "joint_72h_gain_ge_0_30pct",
2579
+ "joint_all_three_seeds_positive",
2580
+ "joint_72h_bootstrap_positive",
2581
+ "joint_correct_beats_negative_ge_0_08pct",
2582
+ ]
2583
+ if all(checks[item] for item in critical) and passed >= 14:
2584
+ verdict_name = (
2585
+ "V3_S2_A1_R2_CONDITIONAL_EXTERNAL_INNOVATION_CAPACITY_QUALIFIED"
2586
+ )
2587
+ recommendation = (
2588
+ "Proceed to S2-A1-R3 and construct the production BER "
2589
+ "only from the source representations qualified here."
2590
+ )
2591
+ elif (
2592
+ atmosphere_active >= 0.30
2593
+ or boundary_active >= 0.20
2594
+ ) and passed >= 9:
2595
+ verdict_name = (
2596
+ "V3_S2_A1_R2_CONDITIONAL_EXTERNAL_INNOVATION_CAPACITY_EVENT_CONDITIONAL"
2597
+ )
2598
+ recommendation = (
2599
+ "Do not integrate BER yet. Expand event-rich windows and "
2600
+ "train an event-conditioned reservoir using the winning source."
2601
+ )
2602
+ else:
2603
+ verdict_name = (
2604
+ "V3_S2_A1_R2_CONDITIONAL_EXTERNAL_INNOVATION_CAPACITY_NOT_ESTABLISHED"
2605
+ )
2606
+ recommendation = (
2607
+ "Stop tuning BER on the 139-day ordinary-season dataset. "
2608
+ "Expand event-rich and boundary-entry data before another BER round."
2609
+ )
2610
+ aggregate = {
2611
+ "atmosphere_72h_rmse_gain_percent": atmosphere_gain,
2612
+ "boundary_72h_rmse_gain_percent": boundary_gain,
2613
+ "joint_72h_rmse_gain_percent": joint_gain,
2614
+ "atmosphere_correct_vs_negative_percent": (
2615
+ atmosphere_negative_gap
2616
+ ),
2617
+ "boundary_correct_vs_negative_percent": (
2618
+ boundary_negative_gap
2619
+ ),
2620
+ "joint_correct_vs_negative_percent": (
2621
+ joint_negative_gap
2622
+ ),
2623
+ "atmosphere_active_top20_gain_percent": (
2624
+ atmosphere_active
2625
+ ),
2626
+ "boundary_active_top20_gain_percent": (
2627
+ boundary_active
2628
+ ),
2629
+ "joint_variance_change": joint_variance_change,
2630
+ "source_zero_max": source_zero_max,
2631
+ "mean_probe_runtime_ms": float(
2632
+ runtime_table["mean_sample_ms"].mean()
2633
+ ),
2634
+ }
2635
+ verdict = {
2636
+ "automatic_verdict": verdict_name,
2637
+ "passed": passed,
2638
+ "total": len(checks),
2639
+ "checks": checks,
2640
+ "critical_checks": critical,
2641
+ "aggregate": aggregate,
2642
+ "next_stage_recommendation": recommendation,
2643
+ }
2644
+ atomic_json(
2645
+ aggregate,
2646
+ output_dir
2647
+ / "S2A1R2_main_aggregate.json",
2648
+ )
2649
+ atomic_json(
2650
+ verdict,
2651
+ output_dir / "S2A1R2_verdict.json",
2652
+ )
2653
+
2654
+ stage(10, 11, "生成图表、报告和HF续接清单")
2655
+ plot_summary(
2656
+ summary,
2657
+ activity_table,
2658
+ output_dir / "figures",
2659
+ )
2660
+ report = [
2661
+ "# V3-S2-A1-R2 条件外部创新容量报告",
2662
+ "",
2663
+ f"自动判决:`{verdict_name}`",
2664
+ "",
2665
+ f"- 大气72小时RMSE增益:{atmosphere_gain:.4f}%",
2666
+ f"- 边界72小时RMSE增益:{boundary_gain:.4f}%",
2667
+ f"- 联合72小时RMSE增益:{joint_gain:.4f}%",
2668
+ f"- 大气正确相对负样本:{atmosphere_negative_gap:.4f}%",
2669
+ f"- 边界正确相对负样本:{boundary_negative_gap:.4f}%",
2670
+ f"- 联合正确相对负样本:{joint_negative_gap:.4f}%",
2671
+ f"- 大气活跃Top20增益:{atmosphere_active:.4f}%",
2672
+ f"- 边界活跃Top20增益:{boundary_active:.4f}%",
2673
+ "",
2674
+ "本轮不使用方差校准;所有增益必须由来源创新残差本身产生。",
2675
+ "当前垂向背景已包含在A0父模型中,不被重复计为新的未来来源。",
2676
+ ]
2677
+ (
2678
+ output_dir
2679
+ / "实验V3S2A1R2_条件外部创新容量报告.md"
2680
+ ).write_text(
2681
+ "\n".join(report), encoding="utf-8"
2682
+ )
2683
+ atomic_json(
2684
+ {
2685
+ "source_dataset_repo": args.hf_repo_id,
2686
+ "parent_result": (
2687
+ "Experiments/V3_S2_A1_R1/"
2688
+ "CIDM_v3_SCS_V3_S2_A1_R1.zip"
2689
+ ),
2690
+ "recommended_result_path": (
2691
+ "Experiments/V3_S2_A1_R2/"
2692
+ ),
2693
+ },
2694
+ output_dir / "S2A1R2_HF_handoff.json",
2695
+ )
2696
+ sanitized_arguments = dict(vars(args))
2697
+ sanitized_arguments["hf_token"] = "<redacted>"
2698
+ atomic_json(
2699
+ {
2700
+ "experiment": "CIDM_v3_SCS_V3_S2_A1_R2",
2701
+ "created_at": dt.datetime.now().isoformat(),
2702
+ "device": str(device),
2703
+ "seeds": seeds,
2704
+ "arguments": sanitized_arguments,
2705
+ "security": (
2706
+ "No plaintext access token is written."
2707
+ ),
2708
+ },
2709
+ output_dir / "S2A1R2_manifest.json",
2710
+ )
2711
+
2712
+ stage(11, 11, "结果打包")
2713
+ package = package_output(output_dir)
2714
+ print(
2715
+ json.dumps(
2716
+ verdict, ensure_ascii=False, indent=2
2717
+ ),
2718
+ flush=True,
2719
+ )
2720
+ print(f"[result] {package}", flush=True)
2721
+ except Exception:
2722
+ trace = traceback.format_exc()
2723
+ (
2724
+ output_dir / "failure_traceback.txt"
2725
+ ).write_text(trace, encoding="utf-8")
2726
+ print(trace, flush=True)
2727
+ raise
2728
+
2729
+
2730
+ if __name__ == "__main__":
2731
+ main()