wuff-mann commited on
Commit
0746071
·
verified ·
1 Parent(s): 05b0188

Upload Experiments/V3_S2_A2_MIN/cidm_v3_scs_s2_a2_minimal_ber_scale_core_integration.py with huggingface_hub

Browse files
Experiments/V3_S2_A2_MIN/cidm_v3_scs_s2_a2_minimal_ber_scale_core_integration.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ CIDM-v3 SCS V3-S2-A2-MIN
5
+ 显式尺度主干 × 最小大气创新 BER 冻结集成资格实验
6
+ ====================================================
7
+
8
+ 目的
9
+ ----
10
+ R3-MIN 已经证明,经过部署退化的未来大气创新对 A0 父模型具有稳定、
11
+ 来源专属和强因果预测价值。本轮不再增加任何新神经模块,只验证该最小
12
+ BER 是否能够作为外部创新修正器,安全地叠加到冻结的 S1-R3 显式尺度主干。
13
+
14
+ 冻结结构
15
+ --------
16
+ 1. S1-R3 显式多尺度编码/动力学/解码;
17
+ 2. S1-R3 Band Closure;
18
+ 3. flux_mode='none';
19
+ 4. slow_memory=False;vertical_closure=False;causal_variance=False;
20
+ 5. R3-MIN 未来大气创新探针;
21
+ 6. 只修正 currents 与 waves;
22
+ 7. 只允许 3 个时效 × 2 个责任组的验证集非负接口系数。
23
+
24
+ 本轮没有
25
+ ------
26
+ - 新的边界 BER;
27
+ - 新的垂向 BER;
28
+ - 方差放大器;
29
+ - Router;
30
+ - 多源交互;
31
+ - S1-R3 主干微调;
32
+ - 测试集选参。
33
+
34
+ 若通过:冻结 V3 的最小开放系统接口,进入物理约束/长滚动正式冻结阶段。
35
+ 若失败:V3 删除未来 BER,只保留显式尺度主干;复杂 BER 延期到 V4/V5。
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import argparse
40
+ import datetime as dt
41
+ import hashlib
42
+ import json
43
+ import math
44
+ import os
45
+ import random
46
+ import shutil
47
+ import time
48
+ import traceback
49
+ import zipfile
50
+ from pathlib import Path
51
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
52
+
53
+ import numpy as np
54
+ import pandas as pd
55
+ import torch
56
+ import torch.nn.functional as F
57
+ from torch.utils.data import DataLoader
58
+
59
+ import matplotlib
60
+ matplotlib.use("Agg")
61
+ import matplotlib.pyplot as plt
62
+
63
+ import cidm_v3_scs_s1_r3_slowfast_causal_closure as s1r3
64
+ import cidm_v3_scs_s2_a1_r2_conditional_external_innovation_capacity as s2r2
65
+ import cidm_v3_scs_s2_a1_r3_minimal_atmosphere_ber as minber
66
+
67
+
68
+ HORIZONS = [1, 4, 12]
69
+ CURRENT_CHANNELS = [3, 4, 5, 6]
70
+ WAVE_CHANNELS = list(range(9, 16))
71
+ RESPONSIBILITY_GROUPS = {
72
+ "currents": CURRENT_CHANNELS,
73
+ "waves": WAVE_CHANNELS,
74
+ }
75
+ RESPONSIBILITY_CHANNELS = CURRENT_CHANNELS + WAVE_CHANNELS
76
+ UNRESPONSIBLE_GROUPS = {
77
+ "surface_thermohaline": [0, 1, 2],
78
+ "subsurface_thermohaline": [7, 8],
79
+ }
80
+ PAIRING = {
81
+ 20260902: 20260910,
82
+ 20260903: 20260911,
83
+ 20260904: 20260912,
84
+ }
85
+ S1_CONFIG_DEFAULTS = {
86
+ "latent_dim": 64,
87
+ "hidden": 72,
88
+ "flux_hidden": 48,
89
+ "flux_downsample": 4,
90
+ "exchange_dim": 32,
91
+ "energy_trend_clip": 0.06,
92
+ "energy_band": 0.10,
93
+ }
94
+
95
+
96
+ def json_default(value: Any) -> Any:
97
+ if isinstance(value, Path):
98
+ return str(value)
99
+ if isinstance(value, (np.integer, np.floating, np.bool_)):
100
+ return value.item()
101
+ if isinstance(value, np.ndarray):
102
+ return value.tolist()
103
+ if isinstance(value, (pd.Timestamp, dt.datetime, dt.date)):
104
+ return pd.Timestamp(value).isoformat()
105
+ raise TypeError(type(value).__name__)
106
+
107
+
108
+ def atomic_json(payload: Any, path: Path) -> None:
109
+ path.parent.mkdir(parents=True, exist_ok=True)
110
+ temp = path.with_suffix(path.suffix + ".tmp")
111
+ temp.write_text(
112
+ json.dumps(payload, ensure_ascii=False, indent=2, default=json_default),
113
+ encoding="utf-8",
114
+ )
115
+ os.replace(temp, path)
116
+
117
+
118
+ def stage(index: int, total: int, title: str) -> None:
119
+ print(f"\n[V3-S2-A2-MIN] 阶段 {index}/{total}:{title}", flush=True)
120
+
121
+
122
+ def seed_everything(seed: int) -> None:
123
+ random.seed(seed)
124
+ np.random.seed(seed)
125
+ torch.manual_seed(seed)
126
+ if torch.cuda.is_available():
127
+ torch.cuda.manual_seed_all(seed)
128
+
129
+
130
+ def sha256_file(path: Path) -> str:
131
+ digest = hashlib.sha256()
132
+ with path.open("rb") as handle:
133
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
134
+ digest.update(block)
135
+ return digest.hexdigest()
136
+
137
+
138
+ def ensure_prepared_and_parent_assets(args: argparse.Namespace) -> Dict[str, Any]:
139
+ """Restore prepared arrays, R3-MIN, and the frozen S1-R3 parent when missing.
140
+
141
+ S1-R3 is an earlier architecture-parent asset, not an output of R3-MIN. The
142
+ function first reuses a local file, then tries several stable paths in the
143
+ user's HF dataset repository. This prevents the integration run from
144
+ silently assuming that the user retained an old local ZIP.
145
+ """
146
+ cache = Path(args.cache_dir)
147
+ prepared = cache / "prepared"
148
+ prepared.mkdir(parents=True, exist_ok=True)
149
+ min_zip = Path(args.min_zip)
150
+ s1r3_zip = Path(args.s1r3_zip)
151
+ needed: List[Tuple[str, Path]] = [
152
+ (
153
+ "Experiments/V3_S2_A1_R3_MIN/CIDM_v3_SCS_V3_S2_A1_R3_MIN.zip",
154
+ min_zip,
155
+ )
156
+ ]
157
+ for window in s2r2.WINDOWS:
158
+ name = window["name"]
159
+ needed.extend([
160
+ (f"Cache/prepared/{name}_cmems.npz", prepared / f"{name}_cmems.npz"),
161
+ (
162
+ f"Cache/prepared/{name}_atmosphere_aligned.npz",
163
+ prepared / f"{name}_atmosphere_aligned.npz",
164
+ ),
165
+ (f"Cache/prepared/{name}_tide.npz", prepared / f"{name}_tide.npz"),
166
+ (f"Cache/prepared/{name}_river.npz", prepared / f"{name}_river.npz"),
167
+ (f"Cache/prepared/{name}_events.npz", prepared / f"{name}_events.npz"),
168
+ ])
169
+ missing = [(repo_path, local) for repo_path, local in needed if not local.is_file()]
170
+ report = {
171
+ "repo_id": args.hf_repo_id,
172
+ "requested": len(needed) + 1,
173
+ "already_local": len(needed) - len(missing) + int(s1r3_zip.is_file()),
174
+ "downloaded": [],
175
+ "s1r3_source": "local" if s1r3_zip.is_file() else None,
176
+ }
177
+ from huggingface_hub import hf_hub_download
178
+ token = os.environ.get("HF_TOKEN") or args.hf_token or None
179
+ if missing:
180
+ for repo_path, local in missing:
181
+ print(f"[HF download] {repo_path}", flush=True)
182
+ source = Path(hf_hub_download(
183
+ repo_id=args.hf_repo_id,
184
+ filename=repo_path,
185
+ repo_type="dataset",
186
+ token=token,
187
+ ))
188
+ local.parent.mkdir(parents=True, exist_ok=True)
189
+ if local.exists() or local.is_symlink():
190
+ local.unlink()
191
+ try:
192
+ local.symlink_to(source)
193
+ except Exception:
194
+ shutil.copy2(source, local)
195
+ report["downloaded"].append(repo_path)
196
+
197
+ # S1-R3 is not produced by R3-MIN. Recover the earlier parent from HF when
198
+ # the local runtime does not already contain it. Multiple candidate paths
199
+ # are supported so old and new repositories remain compatible.
200
+ if not s1r3_zip.is_file():
201
+ candidates = [
202
+ item.strip() for item in args.s1r3_hf_candidates.split(",")
203
+ if item.strip()
204
+ ]
205
+ failures = []
206
+ for repo_path in candidates:
207
+ try:
208
+ print(f"[HF parent lookup] {repo_path}", flush=True)
209
+ source = Path(hf_hub_download(
210
+ repo_id=args.hf_repo_id,
211
+ filename=repo_path,
212
+ repo_type="dataset",
213
+ token=token,
214
+ ))
215
+ s1r3_zip.parent.mkdir(parents=True, exist_ok=True)
216
+ if s1r3_zip.exists() or s1r3_zip.is_symlink():
217
+ s1r3_zip.unlink()
218
+ try:
219
+ s1r3_zip.symlink_to(source)
220
+ except Exception:
221
+ shutil.copy2(source, s1r3_zip)
222
+ report["downloaded"].append(repo_path)
223
+ report["s1r3_source"] = repo_path
224
+ break
225
+ except Exception as exc:
226
+ failures.append(f"{repo_path}: {type(exc).__name__}: {exc}")
227
+ if not s1r3_zip.is_file():
228
+ raise FileNotFoundError(
229
+ "The frozen explicit-scale parent is required for S2-A2, but it "
230
+ "was neither local nor present at the configured HF candidate "
231
+ "paths. Upload CIDM_v3_SCS_V3_S1_R3.zip (or the compatible "
232
+ "CIDM_v3_SCS_V3_S1_R4.zip containing nested R3 assets) to "
233
+ f"{s1r3_zip}. Tried: {failures}"
234
+ )
235
+
236
+ for repo_path, local in needed:
237
+ if not local.is_file() or local.stat().st_size <= 128:
238
+ raise RuntimeError(f"Missing or invalid asset: {repo_path} -> {local}")
239
+ if s1r3_zip.stat().st_size <= 128:
240
+ raise RuntimeError(f"Invalid S1-R3 parent asset: {s1r3_zip}")
241
+ return report
242
+
243
+
244
+ def extract_s1r3_assets(zip_path: Path, destination: Path) -> Dict[str, Any]:
245
+ if not zip_path.is_file():
246
+ raise FileNotFoundError(zip_path)
247
+ destination.mkdir(parents=True, exist_ok=True)
248
+ with zipfile.ZipFile(zip_path) as archive:
249
+ archive.extractall(destination)
250
+ verdicts = list(destination.rglob("V3S1R3_verdict.json"))
251
+ if len(verdicts) != 1:
252
+ raise RuntimeError(f"Expected one V3S1R3 verdict, found {len(verdicts)}")
253
+ root = verdicts[0].parent
254
+ metadata_path = root / "scs_c0_metadata.json"
255
+ if not metadata_path.is_file():
256
+ raise FileNotFoundError(metadata_path)
257
+ checkpoints: Dict[int, Path] = {}
258
+ for path in (root / "checkpoints" / "slowfast_causal").glob("seed_*.pt"):
259
+ payload = torch.load(path, map_location="cpu", weights_only=False)
260
+ checkpoints[int(payload.get("seed", path.stem.split("_")[-1]))] = path
261
+ missing = [seed for seed in PAIRING if seed not in checkpoints]
262
+ if missing:
263
+ raise RuntimeError(f"S1-R3 checkpoints missing: {missing}")
264
+ return {
265
+ "root": root,
266
+ "verdict": json.loads((root / "V3S1R3_verdict.json").read_text(encoding="utf-8")),
267
+ "manifest": json.loads((root / "V3S1R3_manifest.json").read_text(encoding="utf-8")),
268
+ "metadata": json.loads(metadata_path.read_text(encoding="utf-8")),
269
+ "checkpoints": checkpoints,
270
+ "sha256": sha256_file(zip_path),
271
+ }
272
+
273
+
274
+ def extract_min_assets(zip_path: Path, destination: Path) -> Dict[str, Any]:
275
+ if not zip_path.is_file():
276
+ raise FileNotFoundError(zip_path)
277
+ destination.mkdir(parents=True, exist_ok=True)
278
+ with zipfile.ZipFile(zip_path) as archive:
279
+ archive.extractall(destination)
280
+ verdicts = list(destination.rglob("MIN_verdict.json"))
281
+ if len(verdicts) != 1:
282
+ raise RuntimeError(f"Expected one MIN verdict, found {len(verdicts)}")
283
+ root = verdicts[0].parent
284
+ stats_paths = list(root.rglob("S2A0_normalization_stats.npz"))
285
+ if len(stats_paths) != 1:
286
+ raise RuntimeError(f"Expected one A0 stats file, found {len(stats_paths)}")
287
+ checkpoints: Dict[int, Path] = {}
288
+ for path in (root / "checkpoints").glob("seed_*.pt"):
289
+ payload = torch.load(path, map_location="cpu", weights_only=False)
290
+ checkpoints[int(payload["seed"])] = path
291
+ missing = [seed for seed in PAIRING.values() if seed not in checkpoints]
292
+ if missing:
293
+ raise RuntimeError(f"MIN checkpoints missing: {missing}")
294
+ coefficients = json.loads((root / "MIN_validation_coefficients.json").read_text(encoding="utf-8"))
295
+ return {
296
+ "root": root,
297
+ "verdict": json.loads((root / "MIN_verdict.json").read_text(encoding="utf-8")),
298
+ "aggregate": json.loads((root / "MIN_main_aggregate.json").read_text(encoding="utf-8")),
299
+ "stats": stats_paths[0],
300
+ "checkpoints": checkpoints,
301
+ "coefficients": {int(key): np.asarray(value, dtype=np.float32) for key, value in coefficients.items()},
302
+ "sha256": sha256_file(zip_path),
303
+ }
304
+
305
+
306
+ def make_s1_model(args: argparse.Namespace, checkpoint: Path, device: torch.device):
307
+ model = s1r3.ExplicitScaleDynamicsR3(
308
+ channels=len(s1r3.VARIABLE_NAMES),
309
+ latent=args.s1_latent_dim,
310
+ hidden=args.s1_hidden,
311
+ flux_hidden=args.s1_flux_hidden,
312
+ flux_downsample=args.s1_flux_downsample,
313
+ exchange_dim=args.s1_exchange_dim,
314
+ trend_clip=args.s1_energy_trend_clip,
315
+ energy_band=args.s1_energy_band,
316
+ ).to(device)
317
+ payload = torch.load(checkpoint, map_location="cpu", weights_only=False)
318
+ missing, unexpected = model.load_state_dict(payload["model_state"], strict=False)
319
+ if missing or unexpected:
320
+ raise RuntimeError(
321
+ f"S1-R3 checkpoint mismatch. missing={missing}, unexpected={unexpected}"
322
+ )
323
+ model.eval()
324
+ for parameter in model.parameters():
325
+ parameter.requires_grad = False
326
+ return model, {
327
+ "seed": int(payload.get("seed", -1)),
328
+ "epoch": int(payload.get("epoch", -1)),
329
+ "validation_score": float(payload.get("validation_score", float("nan"))),
330
+ }
331
+
332
+
333
+ def make_min_model(args: argparse.Namespace, checkpoint: Path, device: torch.device):
334
+ model = minber.MinimalAtmosphereBER(args.min_hidden).to(device)
335
+ payload = torch.load(checkpoint, map_location="cpu", weights_only=False)
336
+ model.load_state_dict(payload["model_state"], strict=True)
337
+ model.eval()
338
+ for parameter in model.parameters():
339
+ parameter.requires_grad = False
340
+ residual_scale = payload["residual_scale"].to(device)
341
+ return model, residual_scale, {
342
+ "seed": int(payload["seed"]),
343
+ "best_epoch": int(payload["best_epoch"]),
344
+ "source_zero_max": float(payload["source_zero_max"]),
345
+ }
346
+
347
+
348
+ def load_a0_internal_stats(path: Path) -> Tuple[np.ndarray, np.ndarray]:
349
+ with np.load(path) as stats:
350
+ return (
351
+ stats["internal_mean"].astype(np.float32),
352
+ stats["internal_std"].astype(np.float32),
353
+ )
354
+
355
+
356
+ def convert_batch_to_s1(
357
+ batch: Mapping[str, torch.Tensor],
358
+ a0_mean: torch.Tensor,
359
+ a0_std: torch.Tensor,
360
+ s1_mean: torch.Tensor,
361
+ s1_std: torch.Tensor,
362
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
363
+ b, flat, h, w = batch["internal"].shape
364
+ channels = len(s1r3.VARIABLE_NAMES)
365
+ history = flat // channels
366
+ internal_a0 = batch["internal"].reshape(b, history, channels, h, w)
367
+ physical_history = (
368
+ internal_a0 * a0_std[None, None, :, None, None]
369
+ + a0_mean[None, None, :, None, None]
370
+ )
371
+ history_s1 = (
372
+ physical_history - s1_mean[None, None, :, None, None]
373
+ ) / s1_std[None, None, :, None, None]
374
+
375
+ target_physical = (
376
+ batch["target"] * a0_std[None, None, :, None, None]
377
+ + a0_mean[None, None, :, None, None]
378
+ )
379
+ target_s1 = (
380
+ target_physical - s1_mean[None, None, :, None, None]
381
+ ) / s1_std[None, None, :, None, None]
382
+
383
+ mask = batch["mask"]
384
+ if mask.shape[1] == 1:
385
+ mask = mask.expand(-1, channels, -1, -1)
386
+ return history_s1, target_s1, mask
387
+
388
+
389
+ @torch.no_grad()
390
+ def core_predict(model, history: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
391
+ outputs, _ = model.rollout_latent(
392
+ history,
393
+ mask,
394
+ max(HORIZONS),
395
+ flux_mode="none",
396
+ projection=True,
397
+ radial_delta=False,
398
+ band_closure=True,
399
+ slow_memory=False,
400
+ vertical_closure=False,
401
+ causal_variance=False,
402
+ counterfactual=False,
403
+ )
404
+ return torch.stack([outputs[horizon - 1]["pred"] for horizon in HORIZONS], dim=1)
405
+
406
+
407
+ def min_update_in_s1_units(
408
+ model: minber.MinimalAtmosphereBER,
409
+ residual_scale: torch.Tensor,
410
+ min_coefficients: np.ndarray,
411
+ sequence: torch.Tensor,
412
+ a0_std: torch.Tensor,
413
+ s1_std: torch.Tensor,
414
+ ) -> torch.Tensor:
415
+ normalized, _ = model(sequence)
416
+ alpha = minber.coefficient_tensor(
417
+ min_coefficients,
418
+ normalized.device,
419
+ normalized.dtype,
420
+ )
421
+ update_a0_normalized = alpha * minber.apply_residual_scale(
422
+ normalized, residual_scale
423
+ )
424
+ update_physical = update_a0_normalized * a0_std[None, None, :, None, None]
425
+ return update_physical / s1_std[None, None, :, None, None]
426
+
427
+
428
+ def quantize_alpha(value: float, max_alpha: float) -> float:
429
+ grid = np.asarray([0.0, 0.25, 0.50, 0.75, 1.0, 1.25], dtype=np.float32)
430
+ grid = grid[grid <= max_alpha + 1e-8]
431
+ return float(grid[np.argmin(np.abs(grid - value))])
432
+
433
+
434
+ @torch.no_grad()
435
+ def fit_integration_coefficients(
436
+ s1_model,
437
+ min_model,
438
+ residual_scale: torch.Tensor,
439
+ min_coefficients: np.ndarray,
440
+ loader: DataLoader,
441
+ device: torch.device,
442
+ a0_mean: torch.Tensor,
443
+ a0_std: torch.Tensor,
444
+ s1_mean: torch.Tensor,
445
+ s1_std: torch.Tensor,
446
+ max_alpha: float,
447
+ ) -> np.ndarray:
448
+ numerator = np.zeros((len(HORIZONS), len(RESPONSIBILITY_GROUPS)), dtype=np.float64)
449
+ denominator = np.zeros_like(numerator)
450
+ for step, raw_batch in enumerate(loader):
451
+ batch = s2r2.batch_to_device(raw_batch, device)
452
+ history, target, mask = convert_batch_to_s1(
453
+ batch, a0_mean, a0_std, s1_mean, s1_std
454
+ )
455
+ core = core_predict(s1_model, history, mask)
456
+ sequence = minber.degrade_sequence(
457
+ batch["future_atmosphere"], "medium", 880000 + step
458
+ )
459
+ update = min_update_in_s1_units(
460
+ min_model,
461
+ residual_scale,
462
+ min_coefficients,
463
+ sequence,
464
+ a0_std,
465
+ s1_std,
466
+ )
467
+ residual = target - core
468
+ mask_h = mask[:, None]
469
+ for hi in range(len(HORIZONS)):
470
+ for gi, indices in enumerate(RESPONSIBILITY_GROUPS.values()):
471
+ u = update[:, hi, indices]
472
+ r = residual[:, hi, indices]
473
+ m = mask_h[:, :, indices]
474
+ numerator[hi, gi] += float((u * r * m).sum())
475
+ denominator[hi, gi] += float((u.square() * m).sum())
476
+ raw = numerator / np.maximum(denominator, 1e-12)
477
+ raw = np.clip(raw, 0.0, max_alpha)
478
+ quantized = np.vectorize(lambda value: quantize_alpha(float(value), max_alpha))(raw)
479
+ return quantized.astype(np.float32)
480
+
481
+
482
+ def integration_alpha_tensor(
483
+ coefficients: np.ndarray,
484
+ device: torch.device,
485
+ dtype: torch.dtype,
486
+ ) -> torch.Tensor:
487
+ result = torch.zeros(
488
+ len(HORIZONS), len(s1r3.VARIABLE_NAMES), device=device, dtype=dtype
489
+ )
490
+ for gi, indices in enumerate(RESPONSIBILITY_GROUPS.values()):
491
+ result[:, indices] = torch.as_tensor(
492
+ coefficients[:, gi:gi + 1], device=device, dtype=dtype
493
+ )
494
+ return result[None, :, :, None, None]
495
+
496
+
497
+ def empty_accumulator() -> Dict[str, Any]:
498
+ return {
499
+ "squared": {h: 0.0 for h in HORIZONS},
500
+ "count": {h: 0.0 for h in HORIZONS},
501
+ "pred": {h: [] for h in HORIZONS},
502
+ "target": {h: [] for h in HORIZONS},
503
+ "sample_rows": [],
504
+ "groups": {
505
+ (h, group): []
506
+ for h in HORIZONS
507
+ for group in {**s2r2.GROUPS}
508
+ },
509
+ "update_ratios": [],
510
+ "wave_negative": [],
511
+ "direction_error": [],
512
+ }
513
+
514
+
515
+ def update_metrics(
516
+ accumulator: Dict[str, Any],
517
+ prediction: torch.Tensor,
518
+ target: torch.Tensor,
519
+ mask: torch.Tensor,
520
+ update: torch.Tensor,
521
+ sample_index: torch.Tensor,
522
+ s1_mean: torch.Tensor,
523
+ s1_std: torch.Tensor,
524
+ ) -> None:
525
+ channels = prediction.shape[2]
526
+ for hi, horizon in enumerate(HORIZONS):
527
+ error = (prediction[:, hi] - target[:, hi]).square() * mask
528
+ denominator = (
529
+ mask.flatten(1).sum(dim=1).clamp_min(1.0) * channels
530
+ )
531
+ per_sample_mse = error.flatten(1).sum(dim=1) / denominator
532
+ accumulator["squared"][horizon] += float(error.sum())
533
+ accumulator["count"][horizon] += float(mask.sum()) * channels
534
+ accumulator["pred"][horizon].append(
535
+ (prediction[:, hi] * mask).flatten(1).cpu()
536
+ )
537
+ accumulator["target"][horizon].append(
538
+ (target[:, hi] * mask).flatten(1).cpu()
539
+ )
540
+ for index, mse in zip(sample_index.cpu().tolist(), per_sample_mse.cpu().tolist()):
541
+ accumulator["sample_rows"].append({
542
+ "sample_index": int(index),
543
+ "horizon": horizon,
544
+ "mse": float(mse),
545
+ "rmse": math.sqrt(max(float(mse), 0.0)),
546
+ })
547
+ for group, indices in s2r2.GROUPS.items():
548
+ group_error = (
549
+ (prediction[:, hi, indices] - target[:, hi, indices]).square()
550
+ * mask[:, indices]
551
+ )
552
+ group_denominator = (
553
+ mask[:, indices].flatten(1).sum(dim=1).clamp_min(1.0)
554
+ )
555
+ group_rmse = torch.sqrt(
556
+ group_error.flatten(1).sum(dim=1) / group_denominator
557
+ )
558
+ accumulator["groups"][(horizon, group)].extend(group_rmse.cpu().tolist())
559
+
560
+ physical = prediction[:, hi] * s1_std[None, :, None, None] + s1_mean[None, :, None, None]
561
+ physical_target = target[:, hi] * s1_std[None, :, None, None] + s1_mean[None, :, None, None]
562
+ magnitude_channels = [9, 10, 11, 14, 15]
563
+ valid_wave = mask[:, magnitude_channels] > 0
564
+ negative_fraction = (
565
+ ((physical[:, magnitude_channels] < 0) & valid_wave).float().sum()
566
+ / valid_wave.float().sum().clamp_min(1.0)
567
+ )
568
+ accumulator["wave_negative"].append(float(negative_fraction))
569
+
570
+ pred_angle = torch.atan2(physical[:, 12], physical[:, 13])
571
+ true_angle = torch.atan2(physical_target[:, 12], physical_target[:, 13])
572
+ diff = torch.atan2(torch.sin(pred_angle - true_angle), torch.cos(pred_angle - true_angle)).abs()
573
+ direction_mask = mask[:, 12] * mask[:, 13]
574
+ direction_error = (
575
+ (diff * direction_mask).sum()
576
+ / direction_mask.sum().clamp_min(1.0)
577
+ ) * (180.0 / math.pi)
578
+ accumulator["direction_error"].append(float(direction_error))
579
+
580
+ ratio = torch.sqrt(update.square().mean(dim=(2, 3, 4)) + 1e-12) / (
581
+ torch.sqrt(prediction.square().mean(dim=(2, 3, 4)) + 1e-12) + 1e-6
582
+ )
583
+ accumulator["update_ratios"].extend(ratio.cpu().flatten().tolist())
584
+
585
+
586
+ def finalize_metrics(accumulator: Dict[str, Any]) -> Dict[str, Any]:
587
+ metrics: Dict[str, Any] = {}
588
+ for horizon in HORIZONS:
589
+ metrics[f"rmse_h{horizon}"] = math.sqrt(
590
+ accumulator["squared"][horizon]
591
+ / max(accumulator["count"][horizon], 1.0)
592
+ )
593
+ pred = torch.cat(accumulator["pred"][horizon], dim=0)
594
+ target = torch.cat(accumulator["target"][horizon], dim=0)
595
+ metrics[f"variance_ratio_h{horizon}"] = float(
596
+ pred.var(unbiased=False) / (target.var(unbiased=False) + 1e-8)
597
+ )
598
+ for (horizon, group), values in accumulator["groups"].items():
599
+ metrics[f"group_rmse_{group}_h{horizon}"] = float(np.mean(values))
600
+ metrics["update_ratio_mean"] = float(np.mean(accumulator["update_ratios"]))
601
+ metrics["wave_negative_fraction"] = float(np.mean(accumulator["wave_negative"]))
602
+ metrics["wave_direction_error_deg"] = float(np.mean(accumulator["direction_error"]))
603
+ metrics["sample_rows"] = accumulator["sample_rows"]
604
+ return metrics
605
+
606
+
607
+ @torch.no_grad()
608
+ def evaluate_all_modes(
609
+ s1_model,
610
+ min_model,
611
+ residual_scale: torch.Tensor,
612
+ min_coefficients: np.ndarray,
613
+ integration_coefficients: np.ndarray,
614
+ loader: DataLoader,
615
+ device: torch.device,
616
+ a0_mean: torch.Tensor,
617
+ a0_std: torch.Tensor,
618
+ s1_mean: torch.Tensor,
619
+ s1_std: torch.Tensor,
620
+ seed: int,
621
+ ) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, pd.DataFrame]]:
622
+ mode_specs = {
623
+ "core": ("oracle", False, False, False),
624
+ "raw_medium": ("medium", False, False, True),
625
+ "integrated_oracle": ("oracle", False, False, False),
626
+ "integrated_mild": ("mild", False, False, False),
627
+ "integrated_medium": ("medium", False, False, False),
628
+ "integrated_severe": ("severe", False, False, False),
629
+ "integrated_history": ("history", False, False, False),
630
+ "integrated_negative": ("medium", True, False, False),
631
+ "integrated_reversed": ("reversed", False, False, False),
632
+ "integrated_shifted": ("shifted", False, False, False),
633
+ "fallback": ("medium", False, True, False),
634
+ }
635
+ accumulators = {name: empty_accumulator() for name in mode_specs}
636
+ calibrated_alpha = integration_alpha_tensor(
637
+ integration_coefficients, device, torch.float32
638
+ )
639
+ raw_alpha = integration_alpha_tensor(
640
+ np.ones_like(integration_coefficients, dtype=np.float32),
641
+ device,
642
+ torch.float32,
643
+ )
644
+
645
+ for step, raw_batch in enumerate(loader):
646
+ batch = s2r2.batch_to_device(raw_batch, device)
647
+ history, target, mask = convert_batch_to_s1(
648
+ batch, a0_mean, a0_std, s1_mean, s1_std
649
+ )
650
+ core = core_predict(s1_model, history, mask)
651
+ for name, (mode, negative, disabled, raw_interface) in mode_specs.items():
652
+ if disabled or name == "core":
653
+ update = torch.zeros_like(core)
654
+ else:
655
+ sequence = (
656
+ batch["negative_atmosphere"]
657
+ if negative else batch["future_atmosphere"]
658
+ )
659
+ sequence = minber.degrade_sequence(
660
+ sequence,
661
+ mode,
662
+ seed * 10000 + step + sum(map(ord, name)),
663
+ )
664
+ update = min_update_in_s1_units(
665
+ min_model,
666
+ residual_scale,
667
+ min_coefficients,
668
+ sequence,
669
+ a0_std,
670
+ s1_std,
671
+ )
672
+ update = (
673
+ raw_alpha.to(update)
674
+ if raw_interface else calibrated_alpha.to(update)
675
+ ) * update
676
+ prediction = core + update
677
+ update_metrics(
678
+ accumulators[name],
679
+ prediction,
680
+ target,
681
+ mask,
682
+ update,
683
+ batch["sample_index"],
684
+ s1_mean,
685
+ s1_std,
686
+ )
687
+ metrics = {}
688
+ sample_tables = {}
689
+ for name, accumulator in accumulators.items():
690
+ result = finalize_metrics(accumulator)
691
+ sample_tables[name] = pd.DataFrame(result.pop("sample_rows"))
692
+ metrics[name] = result
693
+ return metrics, sample_tables
694
+
695
+
696
+ def paired_bootstrap(reference: np.ndarray, candidate: np.ndarray, reps: int, seed: int) -> Dict[str, float]:
697
+ return s2r2.paired_bootstrap(reference, candidate, reps, seed)
698
+
699
+
700
+ @torch.no_grad()
701
+ def runtime_audit(
702
+ s1_model,
703
+ min_model,
704
+ residual_scale: torch.Tensor,
705
+ min_coefficients: np.ndarray,
706
+ integration_coefficients: np.ndarray,
707
+ loader: DataLoader,
708
+ device: torch.device,
709
+ a0_mean: torch.Tensor,
710
+ a0_std: torch.Tensor,
711
+ s1_mean: torch.Tensor,
712
+ s1_std: torch.Tensor,
713
+ repeats: int = 20,
714
+ ) -> Dict[str, float]:
715
+ batch = s2r2.batch_to_device(next(iter(loader)), device)
716
+ history, _, mask = convert_batch_to_s1(
717
+ batch, a0_mean, a0_std, s1_mean, s1_std
718
+ )
719
+ sequence = minber.degrade_sequence(batch["future_atmosphere"], "medium", 12345)
720
+ alpha = integration_alpha_tensor(
721
+ integration_coefficients, device, torch.float32
722
+ )
723
+
724
+ def core_only():
725
+ return core_predict(s1_model, history, mask)
726
+
727
+ def integrated():
728
+ core = core_predict(s1_model, history, mask)
729
+ update = min_update_in_s1_units(
730
+ min_model,
731
+ residual_scale,
732
+ min_coefficients,
733
+ sequence,
734
+ a0_std,
735
+ s1_std,
736
+ )
737
+ return core + alpha.to(update) * update
738
+
739
+ for _ in range(3):
740
+ core_only(); integrated()
741
+ if device.type == "cuda":
742
+ torch.cuda.synchronize()
743
+ start = time.perf_counter()
744
+ for _ in range(repeats):
745
+ core_only()
746
+ if device.type == "cuda":
747
+ torch.cuda.synchronize()
748
+ core_seconds = time.perf_counter() - start
749
+
750
+ if device.type == "cuda":
751
+ torch.cuda.synchronize()
752
+ start = time.perf_counter()
753
+ for _ in range(repeats):
754
+ integrated()
755
+ if device.type == "cuda":
756
+ torch.cuda.synchronize()
757
+ integrated_seconds = time.perf_counter() - start
758
+
759
+ batch_size = int(history.shape[0])
760
+ core_ms = 1000.0 * core_seconds / repeats / batch_size
761
+ integrated_ms = 1000.0 * integrated_seconds / repeats / batch_size
762
+ return {
763
+ "batch_size": batch_size,
764
+ "core_sample_ms": core_ms,
765
+ "integrated_sample_ms": integrated_ms,
766
+ "ber_overhead_ms": integrated_ms - core_ms,
767
+ "ber_overhead_percent": 100.0 * (integrated_ms - core_ms) / max(core_ms, 1e-8),
768
+ }
769
+
770
+
771
+ def package_output(output_dir: Path) -> Path:
772
+ target = output_dir.parent / f"{output_dir.name}.zip"
773
+ target.unlink(missing_ok=True)
774
+ with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as archive:
775
+ for path in output_dir.rglob("*"):
776
+ if path.is_file() and "_parents" not in path.parts:
777
+ archive.write(path, path.relative_to(output_dir.parent))
778
+ return target
779
+
780
+
781
+ def build_parser() -> argparse.ArgumentParser:
782
+ parser = argparse.ArgumentParser(
783
+ description="Frozen S1-R3 × minimal atmosphere BER integration audit"
784
+ )
785
+ parser.add_argument("--cache_dir", default="/content/CIDM_v3_SCS_S2A0_Cache")
786
+ parser.add_argument("--s1r3_zip", default="/content/CIDM_v3_SCS_V3_S1_R3.zip")
787
+ parser.add_argument(
788
+ "--s1r3_hf_candidates",
789
+ default=(
790
+ "Parents/CIDM_v3_SCS_V3_S1_R3.zip,"
791
+ "Experiments/V3_S1_R3/CIDM_v3_SCS_V3_S1_R3.zip,"
792
+ "CIDM_v3_SCS_V3_S1_R3.zip,"
793
+ "Parents/CIDM_v3_SCS_V3_S1_R4.zip,"
794
+ "CIDM_v3_SCS_V3_S1_R4.zip"
795
+ ),
796
+ )
797
+ parser.add_argument("--min_zip", default="/content/CIDM_v3_SCS_V3_S2_A1_R3_MIN.zip")
798
+ parser.add_argument("--parent_cache", default="/content/CIDM_v3_SCS_S2A2_ParentCache")
799
+ parser.add_argument("--output_dir", default="/content/CIDM_v3_SCS_V3_S2_A2_MIN")
800
+ parser.add_argument("--hf_repo_id", default="wuff-mann/CIDM-v3-SCS-S2A0-Data")
801
+ parser.add_argument("--hf_token", default="")
802
+ parser.add_argument("--history", type=int, default=4)
803
+ parser.add_argument("--batch_size", type=int, default=1)
804
+ parser.add_argument("--num_workers", type=int, default=0)
805
+ parser.add_argument("--min_hidden", type=int, default=40)
806
+ parser.add_argument("--max_integration_alpha", type=float, default=1.25)
807
+ parser.add_argument("--bootstrap_reps", type=int, default=1000)
808
+ parser.add_argument("--s1_latent_dim", type=int, default=64)
809
+ parser.add_argument("--s1_hidden", type=int, default=72)
810
+ parser.add_argument("--s1_flux_hidden", type=int, default=48)
811
+ parser.add_argument("--s1_flux_downsample", type=int, default=4)
812
+ parser.add_argument("--s1_exchange_dim", type=int, default=32)
813
+ parser.add_argument("--s1_energy_trend_clip", type=float, default=0.06)
814
+ parser.add_argument("--s1_energy_band", type=float, default=0.10)
815
+ parser.add_argument("--pairing", default="20260902:20260910,20260903:20260911,20260904:20260912")
816
+ parser.add_argument("--synthetic_smoke", action="store_true")
817
+ parser.add_argument("--smoke_time_steps", type=int, default=36)
818
+ parser.add_argument("--smoke_height", type=int, default=24)
819
+ parser.add_argument("--smoke_width", type=int, default=24)
820
+ return parser
821
+
822
+
823
+ def parse_pairing(value: str) -> Dict[int, int]:
824
+ result = {}
825
+ for item in value.split(","):
826
+ left, right = item.split(":")
827
+ result[int(left)] = int(right)
828
+ return result
829
+
830
+
831
+ def main() -> None:
832
+ args = build_parser().parse_args()
833
+ pairing = parse_pairing(args.pairing)
834
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
835
+ if not args.synthetic_smoke and device.type != "cuda":
836
+ raise RuntimeError("Formal S2-A2 integration audit requires CUDA")
837
+ torch.set_float32_matmul_precision("highest")
838
+
839
+ output_dir = Path(args.output_dir)
840
+ if output_dir.exists():
841
+ shutil.rmtree(output_dir)
842
+ for subdir in ["evaluation", "audits", "figures", "lineage", "deployment"]:
843
+ (output_dir / subdir).mkdir(parents=True, exist_ok=True)
844
+
845
+ parent_cache = Path(args.parent_cache)
846
+ if parent_cache.exists() and args.synthetic_smoke:
847
+ shutil.rmtree(parent_cache)
848
+ parent_cache.mkdir(parents=True, exist_ok=True)
849
+
850
+ try:
851
+ stage(1, 9, "恢复prepared数据、S1-R3和R3-MIN父资产")
852
+ if args.synthetic_smoke:
853
+ s2r2.create_synthetic_assets(args)
854
+ asset_report = {"synthetic_smoke": True}
855
+ else:
856
+ asset_report = ensure_prepared_and_parent_assets(args)
857
+ atomic_json(asset_report, output_dir / "audits" / "S2A2_asset_audit.json")
858
+
859
+ stage(2, 9, "提取冻结主干、最小BER和归一化谱系")
860
+ s1_assets = extract_s1r3_assets(
861
+ Path(args.s1r3_zip), parent_cache / "s1r3"
862
+ )
863
+ min_assets = extract_min_assets(
864
+ Path(args.min_zip), parent_cache / "min"
865
+ )
866
+ if min_assets["verdict"]["automatic_verdict"] != "V3_S2_A1_R3_MINIMAL_ATMOSPHERE_BER_QUALIFIED":
867
+ raise RuntimeError("R3-MIN parent is not formally qualified")
868
+ a0_mean_np, a0_std_np = load_a0_internal_stats(min_assets["stats"])
869
+ s1_mean_np = np.asarray(s1_assets["metadata"]["means"], dtype=np.float32)
870
+ s1_std_np = np.asarray(s1_assets["metadata"]["stds"], dtype=np.float32)
871
+ a0_mean = torch.as_tensor(a0_mean_np, device=device)
872
+ a0_std = torch.as_tensor(a0_std_np, device=device)
873
+ s1_mean = torch.as_tensor(s1_mean_np, device=device)
874
+ s1_std = torch.as_tensor(s1_std_np, device=device)
875
+ atomic_json(
876
+ {
877
+ "s1r3_sha256": s1_assets["sha256"],
878
+ "min_sha256": min_assets["sha256"],
879
+ "s1r3_verdict": s1_assets["verdict"],
880
+ "min_verdict": min_assets["verdict"],
881
+ "pairing": pairing,
882
+ "canonical_s1_settings": {
883
+ "flux_mode": "none",
884
+ "band_closure": True,
885
+ "slow_memory": False,
886
+ "vertical_closure": False,
887
+ "causal_variance": False,
888
+ "radial_delta": False,
889
+ },
890
+ },
891
+ output_dir / "lineage" / "S2A2_parent_lineage.json",
892
+ )
893
+
894
+ stage(3, 9, "加载四季资格数据和冻结模型对")
895
+ windows = [
896
+ s2r2.load_window(Path(args.cache_dir), spec)
897
+ for spec in s2r2.WINDOWS
898
+ ]
899
+ loaders, split_audit = s2r2.build_loaders(
900
+ windows, min_assets["stats"], args
901
+ )
902
+ atomic_json(split_audit, output_dir / "audits" / "S2A2_split_audit.json")
903
+
904
+ pairs = {}
905
+ loading_rows = []
906
+ for s1_seed, min_seed in pairing.items():
907
+ s1_model, s1_report = make_s1_model(
908
+ args, s1_assets["checkpoints"][s1_seed], device
909
+ )
910
+ min_model, residual_scale, min_report = make_min_model(
911
+ args, min_assets["checkpoints"][min_seed], device
912
+ )
913
+ pairs[s1_seed] = {
914
+ "min_seed": min_seed,
915
+ "s1_model": s1_model,
916
+ "min_model": min_model,
917
+ "residual_scale": residual_scale,
918
+ "min_coefficients": min_assets["coefficients"][min_seed],
919
+ }
920
+ loading_rows.append({
921
+ "s1_seed": s1_seed,
922
+ "min_seed": min_seed,
923
+ **{f"s1_{key}": value for key, value in s1_report.items()},
924
+ **{f"min_{key}": value for key, value in min_report.items()},
925
+ })
926
+ pd.DataFrame(loading_rows).to_csv(
927
+ output_dir / "audits" / "S2A2_model_loading.csv", index=False
928
+ )
929
+
930
+ stage(4, 9, "仅用夏季验证集拟合六个接口系数")
931
+ integration_coefficients = {}
932
+ for s1_seed, pair in pairs.items():
933
+ integration_coefficients[s1_seed] = fit_integration_coefficients(
934
+ pair["s1_model"],
935
+ pair["min_model"],
936
+ pair["residual_scale"],
937
+ pair["min_coefficients"],
938
+ loaders["validation"],
939
+ device,
940
+ a0_mean,
941
+ a0_std,
942
+ s1_mean,
943
+ s1_std,
944
+ args.max_integration_alpha,
945
+ )
946
+ print(
947
+ f"[integration alpha s1={s1_seed} min={pair['min_seed']}] "
948
+ f"{integration_coefficients[s1_seed].tolist()}",
949
+ flush=True,
950
+ )
951
+ atomic_json(
952
+ {str(seed): value for seed, value in integration_coefficients.items()},
953
+ output_dir / "S2A2_validation_interface_coefficients.json",
954
+ )
955
+
956
+ stage(5, 9, "秋季测试:核心、集成、重度退化和因果反事实")
957
+ metric_rows = []
958
+ sample_tables: Dict[Tuple[int, str], pd.DataFrame] = {}
959
+ runtime_rows = []
960
+ for s1_seed, pair in pairs.items():
961
+ metrics, samples = evaluate_all_modes(
962
+ pair["s1_model"],
963
+ pair["min_model"],
964
+ pair["residual_scale"],
965
+ pair["min_coefficients"],
966
+ integration_coefficients[s1_seed],
967
+ loaders["test"],
968
+ device,
969
+ a0_mean,
970
+ a0_std,
971
+ s1_mean,
972
+ s1_std,
973
+ s1_seed,
974
+ )
975
+ for mode, values in metrics.items():
976
+ metric_rows.append({
977
+ "s1_seed": s1_seed,
978
+ "min_seed": pair["min_seed"],
979
+ "mode": mode,
980
+ **values,
981
+ })
982
+ sample_tables[(s1_seed, mode)] = samples[mode]
983
+ runtime = runtime_audit(
984
+ pair["s1_model"],
985
+ pair["min_model"],
986
+ pair["residual_scale"],
987
+ pair["min_coefficients"],
988
+ integration_coefficients[s1_seed],
989
+ loaders["test"],
990
+ device,
991
+ a0_mean,
992
+ a0_std,
993
+ s1_mean,
994
+ s1_std,
995
+ repeats=5 if args.synthetic_smoke else 20,
996
+ )
997
+ runtime_rows.append({
998
+ "s1_seed": s1_seed,
999
+ "min_seed": pair["min_seed"],
1000
+ **runtime,
1001
+ })
1002
+ metrics_table = pd.DataFrame(metric_rows)
1003
+ metrics_table.to_csv(
1004
+ output_dir / "evaluation" / "S2A2_seed_metrics.csv", index=False
1005
+ )
1006
+ runtime_table = pd.DataFrame(runtime_rows)
1007
+ runtime_table.to_csv(output_dir / "S2A2_runtime.csv", index=False)
1008
+
1009
+ stage(6, 9, "配对Bootstrap、责任组和物理安全汇总")
1010
+ summary_rows = []
1011
+ bootstrap_payload = {}
1012
+ core_mean = metrics_table[metrics_table["mode"] == "core"].set_index("s1_seed")
1013
+ modes = list(metrics_table["mode"].unique())
1014
+ for mode in modes:
1015
+ candidate = metrics_table[metrics_table["mode"] == mode].set_index("s1_seed")
1016
+ for horizon in HORIZONS:
1017
+ rmse = float(candidate[f"rmse_h{horizon}"].mean())
1018
+ core_rmse = float(core_mean[f"rmse_h{horizon}"].mean())
1019
+ seed_gains = [
1020
+ 100.0 * (
1021
+ core_mean.loc[seed, f"rmse_h{horizon}"]
1022
+ - candidate.loc[seed, f"rmse_h{horizon}"]
1023
+ ) / core_mean.loc[seed, f"rmse_h{horizon}"]
1024
+ for seed in pairing
1025
+ ]
1026
+ ref_all = []
1027
+ cand_all = []
1028
+ for seed in pairing:
1029
+ ref = sample_tables[(seed, "core")]
1030
+ cand = sample_tables[(seed, mode)]
1031
+ ref_all.append(
1032
+ ref[ref.horizon == horizon]
1033
+ .sort_values("sample_index").mse.to_numpy()
1034
+ )
1035
+ cand_all.append(
1036
+ cand[cand.horizon == horizon]
1037
+ .sort_values("sample_index").mse.to_numpy()
1038
+ )
1039
+ boot = paired_bootstrap(
1040
+ np.concatenate(ref_all),
1041
+ np.concatenate(cand_all),
1042
+ args.bootstrap_reps,
1043
+ min(pairing) + horizon * 100 + sum(map(ord, mode)),
1044
+ )
1045
+ bootstrap_payload[f"{mode}_h{horizon}"] = boot
1046
+ summary_rows.append({
1047
+ "mode": mode,
1048
+ "horizon": horizon,
1049
+ "lead_hours": horizon * 6,
1050
+ "rmse": rmse,
1051
+ "variance_ratio": float(candidate[f"variance_ratio_h{horizon}"].mean()),
1052
+ "rmse_gain_vs_core_percent": 100.0 * (core_rmse - rmse) / core_rmse,
1053
+ "mse_gain_vs_core_percent": boot["mse_gain_percent"],
1054
+ "bootstrap_low": boot["ci_low"],
1055
+ "bootstrap_high": boot["ci_high"],
1056
+ "all_seed_positive": bool(all(value > 0 for value in seed_gains)),
1057
+ "seed_gain_min": float(min(seed_gains)),
1058
+ "seed_gain_max": float(max(seed_gains)),
1059
+ })
1060
+ summary = pd.DataFrame(summary_rows)
1061
+ summary.to_csv(output_dir / "S2A2_counterfactual_summary.csv", index=False)
1062
+ atomic_json(bootstrap_payload, output_dir / "paired_bootstrap.json")
1063
+
1064
+ stage(7, 9, "冻结判决:通过则结束S2,否则V3删除未来BER")
1065
+ def value(mode: str, horizon: int, column: str) -> float:
1066
+ return float(summary[
1067
+ (summary["mode"] == mode)
1068
+ & (summary["horizon"] == horizon)
1069
+ ][column].iloc[0])
1070
+
1071
+ medium_gain = value("integrated_medium", 12, "rmse_gain_vs_core_percent")
1072
+ raw_gain = value("raw_medium", 12, "rmse_gain_vs_core_percent")
1073
+ severe_gain = value("integrated_severe", 12, "rmse_gain_vs_core_percent")
1074
+ negative_gap = 100.0 * (
1075
+ value("integrated_negative", 12, "rmse")
1076
+ - value("integrated_medium", 12, "rmse")
1077
+ ) / value("integrated_negative", 12, "rmse")
1078
+ history_gap = 100.0 * (
1079
+ value("integrated_history", 12, "rmse")
1080
+ - value("integrated_medium", 12, "rmse")
1081
+ ) / value("integrated_history", 12, "rmse")
1082
+ shifted_gap = 100.0 * (
1083
+ value("integrated_shifted", 12, "rmse")
1084
+ - value("integrated_medium", 12, "rmse")
1085
+ ) / value("integrated_shifted", 12, "rmse")
1086
+ mean_metrics = metrics_table.groupby("mode").mean(numeric_only=True)
1087
+ core_metrics = mean_metrics.loc["core"]
1088
+ medium_metrics = mean_metrics.loc["integrated_medium"]
1089
+ current_gain = 100.0 * (
1090
+ core_metrics["group_rmse_currents_h12"]
1091
+ - medium_metrics["group_rmse_currents_h12"]
1092
+ ) / core_metrics["group_rmse_currents_h12"]
1093
+ wave_gain = 100.0 * (
1094
+ core_metrics["group_rmse_waves_h12"]
1095
+ - medium_metrics["group_rmse_waves_h12"]
1096
+ ) / core_metrics["group_rmse_waves_h12"]
1097
+ surface_change = abs(
1098
+ medium_metrics["group_rmse_surface_thermohaline_h12"]
1099
+ - core_metrics["group_rmse_surface_thermohaline_h12"]
1100
+ )
1101
+ subsurface_change = abs(
1102
+ medium_metrics["group_rmse_subsurface_thermohaline_h12"]
1103
+ - core_metrics["group_rmse_subsurface_thermohaline_h12"]
1104
+ )
1105
+ variance_change = (
1106
+ medium_metrics["variance_ratio_h12"]
1107
+ - core_metrics["variance_ratio_h12"]
1108
+ )
1109
+ direction_change = (
1110
+ medium_metrics["wave_direction_error_deg"]
1111
+ - core_metrics["wave_direction_error_deg"]
1112
+ )
1113
+ negative_fraction_change = (
1114
+ medium_metrics["wave_negative_fraction"]
1115
+ - core_metrics["wave_negative_fraction"]
1116
+ )
1117
+ mean_alpha = float(np.mean([
1118
+ value for array in integration_coefficients.values() for value in array.flatten()
1119
+ ]))
1120
+ active_alpha_fraction = float(np.mean([
1121
+ value > 0 for array in integration_coefficients.values() for value in array.flatten()
1122
+ ]))
1123
+ source_zero_max = max(row["min_source_zero_max"] for row in loading_rows)
1124
+ fallback_error = abs(
1125
+ value("fallback", 12, "rmse") - value("core", 12, "rmse")
1126
+ )
1127
+ bootstrap_upper = value("integrated_medium", 12, "bootstrap_high")
1128
+ all_seed_positive = bool(summary[
1129
+ (summary["mode"] == "integrated_medium")
1130
+ & (summary["horizon"] == 12)
1131
+ ]["all_seed_positive"].iloc[0])
1132
+
1133
+ checks = {
1134
+ "s1r3_and_min_three_pairs_loaded": len(pairs) == 3 and len(pairing) == 3,
1135
+ "min_parent_formally_qualified": min_assets["verdict"]["automatic_verdict"] == "V3_S2_A1_R3_MINIMAL_ATMOSPHERE_BER_QUALIFIED",
1136
+ "source_zero_sentinel_lt_1e8": source_zero_max < 1e-8,
1137
+ "fallback_exactly_reproduces_core": fallback_error < 1e-10,
1138
+ "raw_medium_not_harmful_0_3pct": raw_gain >= -0.3,
1139
+ "integrated_medium_72h_gain_ge_0_5pct": medium_gain >= 0.5,
1140
+ "integrated_medium_all_three_positive": all_seed_positive,
1141
+ "integrated_medium_bootstrap_positive": bootstrap_upper < 0,
1142
+ "correct_beats_negative_ge_0_5pct": negative_gap >= 0.5,
1143
+ "correct_beats_history_ge_0_5pct": history_gap >= 0.5,
1144
+ "correct_beats_shifted_ge_0_1pct": shifted_gap >= 0.1,
1145
+ "severe_72h_nonnegative": severe_gain >= 0.0,
1146
+ "currents_72h_gain_ge_0_25pct": current_gain >= 0.25,
1147
+ "waves_72h_gain_ge_0_75pct": wave_gain >= 0.75,
1148
+ "surface_group_exactly_unchanged": surface_change < 1e-8,
1149
+ "subsurface_group_exactly_unchanged": subsurface_change < 1e-8,
1150
+ "variance_not_worse_by_0_02": variance_change >= -0.02,
1151
+ "wave_direction_not_worse_0_5deg": direction_change <= 0.5,
1152
+ "wave_negative_fraction_not_worse": negative_fraction_change <= 1e-4,
1153
+ "interface_coefficients_nontrivial": mean_alpha >= 0.15 and active_alpha_fraction >= 0.5,
1154
+ "ber_runtime_overhead_lt_15pct": float(runtime_table["ber_overhead_percent"].mean()) < 15.0,
1155
+ "all_metrics_finite": bool(np.isfinite(
1156
+ metrics_table.select_dtypes(include=[np.number]).to_numpy()
1157
+ ).all()),
1158
+ }
1159
+ passed = sum(bool(value) for value in checks.values())
1160
+ critical = [
1161
+ "source_zero_sentinel_lt_1e8",
1162
+ "fallback_exactly_reproduces_core",
1163
+ "integrated_medium_72h_gain_ge_0_5pct",
1164
+ "integrated_medium_all_three_positive",
1165
+ "integrated_medium_bootstrap_positive",
1166
+ "correct_beats_negative_ge_0_5pct",
1167
+ "currents_72h_gain_ge_0_25pct",
1168
+ "waves_72h_gain_ge_0_75pct",
1169
+ "surface_group_exactly_unchanged",
1170
+ "subsurface_group_exactly_unchanged",
1171
+ ]
1172
+ qualified = all(checks[key] for key in critical) and passed >= 18
1173
+ if qualified:
1174
+ verdict_name = "V3_S2_A2_MINIMAL_BER_SCALE_CORE_INTEGRATION_QUALIFIED"
1175
+ recommendation = (
1176
+ "Freeze the V3 minimal architecture and proceed to S3 physical "
1177
+ "alignment plus 7-15 day rollout qualification. Do not add deferred modules."
1178
+ )
1179
+ else:
1180
+ verdict_name = "V3_S2_A2_MINIMAL_BER_SCALE_CORE_INTEGRATION_NOT_QUALIFIED"
1181
+ recommendation = (
1182
+ "Drop future BER from V3. Freeze the explicit-scale S1-R3 core with "
1183
+ "Band Closure only; defer richer BER integration to V4/V5."
1184
+ )
1185
+ aggregate = {
1186
+ "raw_medium_72h_rmse_gain_percent": raw_gain,
1187
+ "integrated_medium_72h_rmse_gain_percent": medium_gain,
1188
+ "integrated_severe_72h_rmse_gain_percent": severe_gain,
1189
+ "correct_vs_negative_percent": negative_gap,
1190
+ "correct_vs_history_percent": history_gap,
1191
+ "correct_vs_shifted_percent": shifted_gap,
1192
+ "currents_72h_gain_percent": current_gain,
1193
+ "waves_72h_gain_percent": wave_gain,
1194
+ "variance_ratio_change_72h": variance_change,
1195
+ "wave_direction_error_change_deg": direction_change,
1196
+ "wave_negative_fraction_change": negative_fraction_change,
1197
+ "mean_interface_alpha": mean_alpha,
1198
+ "active_interface_alpha_fraction": active_alpha_fraction,
1199
+ "mean_ber_runtime_overhead_percent": float(runtime_table["ber_overhead_percent"].mean()),
1200
+ }
1201
+ verdict = {
1202
+ "automatic_verdict": verdict_name,
1203
+ "passed": passed,
1204
+ "total": len(checks),
1205
+ "checks": checks,
1206
+ "critical_checks": critical,
1207
+ "aggregate": aggregate,
1208
+ "v3_frozen_scope_if_qualified": [
1209
+ "explicit multi-scale state",
1210
+ "shared scale-conditioned dynamics",
1211
+ "multi-step rollout training",
1212
+ "Band Closure",
1213
+ "minimal future-atmosphere innovation BER",
1214
+ "currents/waves responsibility mask",
1215
+ "six validation-frozen interface coefficients",
1216
+ ],
1217
+ "permanently_excluded_from_v3": [
1218
+ "future boundary BER",
1219
+ "duplicate vertical BER",
1220
+ "explicit variance amplifier",
1221
+ "event router",
1222
+ "multi-source interaction head",
1223
+ "dual-timescale latent core",
1224
+ "strong learned cross-scale flux",
1225
+ ],
1226
+ "next_stage_recommendation": recommendation,
1227
+ }
1228
+ atomic_json(aggregate, output_dir / "S2A2_main_aggregate.json")
1229
+ atomic_json(verdict, output_dir / "S2A2_verdict.json")
1230
+
1231
+ stage(8, 9, "生成冻结合同、图表和部署引用")
1232
+ deployment_contract = {
1233
+ "format": "CIDM_V3_SCS_MINIMAL_FROZEN_INTEGRATION_V1",
1234
+ "s1r3_parent_sha256": s1_assets["sha256"],
1235
+ "min_parent_sha256": min_assets["sha256"],
1236
+ "pairing": pairing,
1237
+ "interface_coefficients": integration_coefficients,
1238
+ "core_runtime_settings": {
1239
+ "flux_mode": "none",
1240
+ "projection": True,
1241
+ "radial_delta": False,
1242
+ "band_closure": True,
1243
+ "slow_memory": False,
1244
+ "vertical_closure": False,
1245
+ "causal_variance": False,
1246
+ },
1247
+ "ber_responsibility": RESPONSIBILITY_GROUPS,
1248
+ "ber_input": "future atmosphere innovation only",
1249
+ "ber_default_deployment_proxy": "medium",
1250
+ "ber_fallback": "exact zero update",
1251
+ }
1252
+ atomic_json(
1253
+ deployment_contract,
1254
+ output_dir / "deployment" / "CIDM_v3_minimal_integration_contract.json",
1255
+ )
1256
+ plt.figure(figsize=(10, 5))
1257
+ subset = summary[summary.horizon == 12]
1258
+ plt.bar(subset["mode"], subset["rmse_gain_vs_core_percent"])
1259
+ plt.axhline(0, linewidth=1)
1260
+ plt.ylabel("72 h RMSE gain over frozen scale core (%)")
1261
+ plt.xticks(rotation=35, ha="right")
1262
+ plt.tight_layout()
1263
+ plt.savefig(output_dir / "figures" / "S2A2_72h_integration_gain.png", dpi=180)
1264
+ plt.close()
1265
+
1266
+ report = f"""# V3-S2-A2-MIN 显式尺度主干与最小BER冻结集成报告
1267
+
1268
+ 自动判决:`{verdict_name}`
1269
+
1270
+ - 原始中等退化接口72小时增益:{raw_gain:.4f}%
1271
+ - 验证校准后中等退化72小时增益:{medium_gain:.4f}%
1272
+ - 重度退化72小时增益:{severe_gain:.4f}%
1273
+ - 正确未来相对负样本:{negative_gap:.4f}%
1274
+ - 流场72小时增益:{current_gain:.4f}%
1275
+ - 波浪72小时增益:{wave_gain:.4f}%
1276
+ - 72小时方差比变化:{variance_change:.4f}
1277
+ - 平均接口系数:{mean_alpha:.4f}
1278
+ - BER运行时开销:{aggregate['mean_ber_runtime_overhead_percent']:.4f}%
1279
+
1280
+ 本轮没有训练S1-R3主干,也没有增加新的神经模块。只有六个验证集冻结接口系数。
1281
+ """
1282
+ (output_dir / "实验V3S2A2MIN_冻结集成报告.md").write_text(report, encoding="utf-8")
1283
+
1284
+ stage(9, 9, "安全manifest和结果打包")
1285
+ safe_args = dict(vars(args))
1286
+ safe_args["hf_token"] = "<redacted>"
1287
+ atomic_json(
1288
+ {
1289
+ "experiment": "CIDM_v3_SCS_V3_S2_A2_MIN",
1290
+ "created_at": dt.datetime.now().isoformat(),
1291
+ "device": str(device),
1292
+ "arguments": safe_args,
1293
+ "verdict": verdict_name,
1294
+ "security": "No plaintext access token is written.",
1295
+ },
1296
+ output_dir / "S2A2_manifest.json",
1297
+ )
1298
+ package = package_output(output_dir)
1299
+ print(json.dumps(verdict, ensure_ascii=False, indent=2, default=json_default), flush=True)
1300
+ print(f"[result] {package}", flush=True)
1301
+ except Exception:
1302
+ trace = traceback.format_exc()
1303
+ (output_dir / "failure_traceback.txt").write_text(trace, encoding="utf-8")
1304
+ print(trace, flush=True)
1305
+ raise
1306
+
1307
+
1308
+ if __name__ == "__main__":
1309
+ main()