wuff-mann commited on
Commit
b072f20
·
verified ·
1 Parent(s): 7a4a865

Upload Experiments/V3_S4_A0/cidm_v3_scs_s4_a0_multiseason_training_qualification.py with huggingface_hub

Browse files
Experiments/V3_S4_A0/cidm_v3_scs_s4_a0_multiseason_training_qualification.py ADDED
@@ -0,0 +1,2003 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ CIDM-v3 SCS V3-S4-A0
5
+ 多季节中等规模训练、近岸公平性与正式训练启动资格
6
+ =====================================================
7
+
8
+ 本轮是V3正式训练前的最后资格阶段,不再进行架构探索。
9
+
10
+ 冻结架构:
11
+ - MultiScalePhysicalEncoder
12
+ - ExplicitScaleInformationState
13
+ - SharedScaleConditionedCIDMCore
14
+ - MultiStepRecurrence
15
+ - BandClosure
16
+ - MultiResolutionDecoder
17
+
18
+ 持续关闭:
19
+ - Future/Boundary/Vertical BER
20
+ - CrossScaleFlux
21
+ - SlowMemory/VerticalOutput Closure
22
+ - CausalVarianceAmplifier
23
+ - EventRouter
24
+
25
+ 本轮只扩大数据覆盖并修复训练公平性:
26
+ 1. 冬季+春季原生1/12°训练;
27
+ 2. 夏季验证,秋季独立测试;
28
+ 3. 训练补丁按近岸/陆架/开阔海域平衡;
29
+ 4. 显式尺度与参数匹配Single-State使用同一数据、目标和课程;
30
+ 5. 所有保留模块允许训练,延期模块保持冻结;
31
+ 6. AdamW跨Epoch持续;
32
+ 7. 12→20→28→40→60步课程;
33
+ 8. 像素加权、等样本、海洋占比分层与时间块Bootstrap同时报告;
34
+ 9. 每Epoch保存远端续接资产,正式运行可恢复。
35
+
36
+ 本轮通过后:
37
+ - CIDM-v3结构与训练合同正式冻结;
38
+ - 下一步直接进入多年数据的正式训练,不再增加架构模块。
39
+ """
40
+ from __future__ import annotations
41
+
42
+ import argparse
43
+ import copy
44
+ import hashlib
45
+ import json
46
+ import math
47
+ import os
48
+ import random
49
+ import shutil
50
+ import time
51
+ import traceback
52
+ import zipfile
53
+ from pathlib import Path
54
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
55
+
56
+ import numpy as np
57
+ import pandas as pd
58
+ import torch
59
+ import torch.nn as nn
60
+ from torch.utils.data import DataLoader, Dataset
61
+
62
+ import matplotlib
63
+ matplotlib.use("Agg")
64
+ import matplotlib.pyplot as plt
65
+
66
+ import scs_c0_data_runtime as data_runtime
67
+ import cidm_v3_scs_s2_a2_r1_native_grid_integration as native_runtime
68
+ import cidm_v3_scs_s3_a0_long_rollout_freeze as s3a0
69
+ import cidm_v3_scs_s3_a1_long_horizon_objective_repair as s3a1
70
+ import cidm_v3_scs_s2_a1_r2_conditional_external_innovation_capacity as s2r2
71
+
72
+
73
+ VARIABLE_NAMES = list(data_runtime.VARIABLE_NAMES)
74
+ SEASONS = {
75
+ "winter": {
76
+ "role": "train",
77
+ "start": "2023-01-15T00:00:00",
78
+ "end": "2023-02-18T18:00:00",
79
+ },
80
+ "spring": {
81
+ "role": "train",
82
+ "start": "2023-04-10T00:00:00",
83
+ "end": "2023-05-14T18:00:00",
84
+ },
85
+ "summer": {
86
+ "role": "validation",
87
+ "start": "2023-07-10T00:00:00",
88
+ "end": "2023-08-13T18:00:00",
89
+ },
90
+ "autumn": {
91
+ "role": "test",
92
+ "start": "2023-10-05T00:00:00",
93
+ "end": "2023-11-08T18:00:00",
94
+ },
95
+ }
96
+ HORIZONS = [1, 4, 12, 28, 60]
97
+ HORIZON_LABELS = {1: "6h", 4: "24h", 12: "72h", 28: "7d", 60: "15d"}
98
+ S1_SEEDS = [20260902, 20260903, 20260904]
99
+ GROUPS = dict(s2r2.GROUPS)
100
+ METHODS = [
101
+ "persistence",
102
+ "parent_single",
103
+ "parent_explicit_band",
104
+ "medium_single",
105
+ "medium_explicit_no_band",
106
+ "medium_explicit_band",
107
+ ]
108
+ OCEAN_BINS = {
109
+ "coastal": (0.10, 0.50),
110
+ "shelf": (0.50, 0.85),
111
+ "open_ocean": (0.85, 1.000001),
112
+ }
113
+
114
+
115
+ def json_default(value: Any) -> Any:
116
+ return data_runtime.json_default(value)
117
+
118
+
119
+ def atomic_json(payload: Any, path: Path) -> None:
120
+ path.parent.mkdir(parents=True, exist_ok=True)
121
+ tmp = path.with_suffix(path.suffix + ".tmp")
122
+ tmp.write_text(
123
+ json.dumps(payload, ensure_ascii=False, indent=2, default=json_default),
124
+ encoding="utf-8",
125
+ )
126
+ os.replace(tmp, path)
127
+
128
+
129
+ def stage(index: int, total: int, title: str) -> None:
130
+ print(f"\n[V3-S4-A0] 阶段 {index}/{total}:{title}", flush=True)
131
+
132
+
133
+ def sha256_file(path: Path) -> str:
134
+ digest = hashlib.sha256()
135
+ with path.open("rb") as handle:
136
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
137
+ digest.update(block)
138
+ return digest.hexdigest()
139
+
140
+
141
+ def seed_everything(seed: int) -> None:
142
+ random.seed(seed)
143
+ np.random.seed(seed)
144
+ torch.manual_seed(seed)
145
+ if torch.cuda.is_available():
146
+ torch.cuda.manual_seed_all(seed)
147
+
148
+
149
+ def hf_download_file(
150
+ repo_id: str,
151
+ repo_path: str,
152
+ local_path: Path,
153
+ token: Optional[str],
154
+ ) -> bool:
155
+ try:
156
+ from huggingface_hub import hf_hub_download
157
+ downloaded = Path(
158
+ hf_hub_download(
159
+ repo_id=repo_id,
160
+ filename=repo_path,
161
+ repo_type="dataset",
162
+ token=token,
163
+ )
164
+ )
165
+ except Exception as exc:
166
+ print(f"[HF miss] {repo_path}: {exc}", flush=True)
167
+ return False
168
+ local_path.parent.mkdir(parents=True, exist_ok=True)
169
+ if local_path.exists() or local_path.is_symlink():
170
+ local_path.unlink()
171
+ try:
172
+ local_path.symlink_to(downloaded)
173
+ except Exception:
174
+ shutil.copy2(downloaded, local_path)
175
+ print(f"[HF restored] {repo_path}", flush=True)
176
+ return True
177
+
178
+
179
+ def ensure_parent_assets(args: argparse.Namespace) -> Dict[str, Any]:
180
+ token = args.hf_token or os.environ.get("HF_TOKEN") or None
181
+ s3a1_zip = Path(args.s3a1_zip)
182
+ s3a0_zip = Path(args.s3a0_zip)
183
+ if not s3a1_zip.is_file():
184
+ candidates = [
185
+ "Experiments/V3_S3_A1/CIDM_v3_SCS_V3_S3_A1.zip",
186
+ "CIDM_v3_SCS_V3_S3_A1.zip",
187
+ ]
188
+ for candidate in candidates:
189
+ if hf_download_file(args.hf_repo_id, candidate, s3a1_zip, token):
190
+ break
191
+ if not s3a0_zip.is_file():
192
+ candidates = [
193
+ "Experiments/V3_S3_A0/CIDM_v3_SCS_V3_S3_A0.zip",
194
+ "CIDM_v3_SCS_V3_S3_A0.zip",
195
+ ]
196
+ for candidate in candidates:
197
+ if hf_download_file(args.hf_repo_id, candidate, s3a0_zip, token):
198
+ break
199
+ if not s3a1_zip.is_file() or not s3a0_zip.is_file():
200
+ raise FileNotFoundError(
201
+ f"Missing parents: S3-A1={s3a1_zip.is_file()}, "
202
+ f"S3-A0={s3a0_zip.is_file()}"
203
+ )
204
+ return {
205
+ "s3a1_sha256": sha256_file(s3a1_zip),
206
+ "s3a0_sha256": sha256_file(s3a0_zip),
207
+ }
208
+
209
+
210
+ def native_file_map(root: Path) -> Dict[str, Path]:
211
+ return {
212
+ "data": root / "scs_c0_data.npy",
213
+ "mask": root / "scs_c0_mask.npy",
214
+ "variable_masks": root / "scs_c0_variable_masks.npy",
215
+ "metadata": root / "scs_c0_metadata.json",
216
+ "audit": root / "C0_data_audit.csv",
217
+ }
218
+
219
+
220
+ def native_cache_valid(root: Path) -> bool:
221
+ files = native_file_map(root)
222
+ if not all(path.is_file() for path in files.values()):
223
+ return False
224
+ try:
225
+ metadata = json.loads(files["metadata"].read_text(encoding="utf-8"))
226
+ return (
227
+ len(metadata["shape"]) == 4
228
+ and int(metadata["shape"][1]) == len(VARIABLE_NAMES)
229
+ and abs(float(metadata["native_resolution_degrees"]) - 1 / 12) < 1e-6
230
+ )
231
+ except Exception:
232
+ return False
233
+
234
+
235
+ def restore_native_from_hf(
236
+ args: argparse.Namespace,
237
+ season: str,
238
+ destination: Path,
239
+ ) -> bool:
240
+ token = args.hf_token or os.environ.get("HF_TOKEN") or None
241
+ destination.mkdir(parents=True, exist_ok=True)
242
+ downloaded: List[Path] = []
243
+ for filename in [
244
+ "scs_c0_data.npy",
245
+ "scs_c0_mask.npy",
246
+ "scs_c0_variable_masks.npy",
247
+ "scs_c0_metadata.json",
248
+ "C0_data_audit.csv",
249
+ ]:
250
+ local_path = destination / filename
251
+ if local_path.is_file():
252
+ continue
253
+ repo_path = f"Cache/native_1_12/{season}/{filename}"
254
+ if not hf_download_file(args.hf_repo_id, repo_path, local_path, token):
255
+ for path in downloaded:
256
+ path.unlink(missing_ok=True)
257
+ return False
258
+ downloaded.append(local_path)
259
+ return native_cache_valid(destination)
260
+
261
+
262
+ def prepare_native_season(
263
+ args: argparse.Namespace,
264
+ season: str,
265
+ ) -> Tuple[Path, Dict[str, Any]]:
266
+ destination = Path(args.native_cache_dir) / season / "prepared"
267
+ if native_cache_valid(destination):
268
+ return destination, {"season": season, "source": "local"}
269
+ if restore_native_from_hf(args, season, destination):
270
+ return destination, {"season": season, "source": "hf"}
271
+ if args.no_live_download:
272
+ raise FileNotFoundError(
273
+ f"Native 1/12° cache missing for {season}; live download disabled."
274
+ )
275
+
276
+ print(
277
+ f"[CMEMS native download] {season}: "
278
+ f"{SEASONS[season]['start']} .. {SEASONS[season]['end']}",
279
+ flush=True,
280
+ )
281
+ root = Path(args.native_cache_dir) / season
282
+ build_args = argparse.Namespace(
283
+ start_datetime=SEASONS[season]["start"],
284
+ end_datetime=SEASONS[season]["end"],
285
+ minimum_time_steps=100,
286
+ )
287
+ prepared = data_runtime.prepare_cmems_cube(build_args, root)
288
+ if prepared != destination or not native_cache_valid(prepared):
289
+ raise RuntimeError(f"Native preparation failed: {season}")
290
+ if args.delete_native_raw:
291
+ shutil.rmtree(root / "raw", ignore_errors=True)
292
+ return prepared, {"season": season, "source": "cmems_live"}
293
+
294
+
295
+ def extract_s3a0_assets(
296
+ zip_path: Path,
297
+ destination: Path,
298
+ ) -> Dict[str, Any]:
299
+ destination.mkdir(parents=True, exist_ok=True)
300
+ with zipfile.ZipFile(zip_path) as archive:
301
+ archive.extractall(destination)
302
+ verdicts = list(destination.rglob("V3S1R3_verdict.json"))
303
+ if len(verdicts) != 1:
304
+ raise RuntimeError(f"Expected one nested S1-R3 verdict, found {len(verdicts)}")
305
+ s1_root = verdicts[0].parent
306
+ metadata_path = s1_root / "scs_c0_metadata.json"
307
+ if not metadata_path.is_file():
308
+ raise FileNotFoundError(metadata_path)
309
+
310
+ explicit = {}
311
+ for path in (s1_root / "checkpoints" / "slowfast_causal").glob("seed_*.pt"):
312
+ payload = torch.load(path, map_location="cpu", weights_only=False)
313
+ explicit[int(payload["seed"])] = path
314
+ single = {}
315
+ for path in s1_root.rglob("checkpoints/single/seed_*.pt"):
316
+ payload = torch.load(path, map_location="cpu", weights_only=False)
317
+ seed = int(payload["seed"])
318
+ if seed not in single:
319
+ single[seed] = path
320
+ return {
321
+ "metadata": json.loads(metadata_path.read_text(encoding="utf-8")),
322
+ "explicit_parent_checkpoints": explicit,
323
+ "single_parent_checkpoints": single,
324
+ }
325
+
326
+
327
+ def extract_s3a1_assets(
328
+ zip_path: Path,
329
+ destination: Path,
330
+ ) -> Dict[str, Any]:
331
+ destination.mkdir(parents=True, exist_ok=True)
332
+ with zipfile.ZipFile(zip_path) as archive:
333
+ archive.extractall(destination)
334
+ verdicts = list(destination.rglob("S3A1_verdict.json"))
335
+ if len(verdicts) != 1:
336
+ raise RuntimeError(f"Expected one S3-A1 verdict, found {len(verdicts)}")
337
+ root = verdicts[0].parent
338
+ explicit = {}
339
+ single = {}
340
+ for path in (root / "checkpoints" / "explicit").glob("seed_*.pt"):
341
+ payload = torch.load(path, map_location="cpu", weights_only=False)
342
+ explicit[int(payload["seed"])] = path
343
+ for path in (root / "checkpoints" / "single").glob("seed_*.pt"):
344
+ payload = torch.load(path, map_location="cpu", weights_only=False)
345
+ single[int(payload["seed"])] = path
346
+ missing = [
347
+ seed for seed in S1_SEEDS
348
+ if seed not in explicit or seed not in single
349
+ ]
350
+ if missing:
351
+ raise RuntimeError(f"S3-A1 repaired checkpoints missing: {missing}")
352
+ return {
353
+ "root": root,
354
+ "verdict": json.loads(verdicts[0].read_text(encoding="utf-8")),
355
+ "explicit_checkpoints": explicit,
356
+ "single_checkpoints": single,
357
+ }
358
+
359
+
360
+ def ocean_bin(fraction: float) -> str:
361
+ for name, (low, high) in OCEAN_BINS.items():
362
+ if low <= fraction < high:
363
+ return name
364
+ return "excluded"
365
+
366
+
367
+ class SeasonCube:
368
+ def __init__(
369
+ self,
370
+ season: str,
371
+ root: Path,
372
+ reference_mean: np.ndarray,
373
+ reference_std: np.ndarray,
374
+ history: int,
375
+ patch_size: int,
376
+ maximum_horizon: int,
377
+ ):
378
+ self.season = season
379
+ self.data = np.load(root / "scs_c0_data.npy", mmap_mode="r")
380
+ self.variable_masks = np.load(
381
+ root / "scs_c0_variable_masks.npy", mmap_mode="r"
382
+ )
383
+ self.metadata = json.loads(
384
+ (root / "scs_c0_metadata.json").read_text(encoding="utf-8")
385
+ )
386
+ self.window_mean = np.asarray(self.metadata["means"], dtype=np.float32)
387
+ self.window_std = np.asarray(self.metadata["stds"], dtype=np.float32)
388
+ self.reference_mean = np.asarray(reference_mean, dtype=np.float32)
389
+ self.reference_std = np.asarray(reference_std, dtype=np.float32)
390
+ self.history = history
391
+ self.patch_size = patch_size
392
+ self.maximum_horizon = maximum_horizon
393
+ self.valid_times = np.arange(
394
+ history - 1,
395
+ self.data.shape[0] - maximum_horizon,
396
+ dtype=np.int64,
397
+ )
398
+ self.height, self.width = self.data.shape[-2:]
399
+
400
+ def valid_fraction(self, y: int, x: int) -> float:
401
+ p = self.patch_size
402
+ mask = self.variable_masks[:, y:y+p, x:x+p]
403
+ return float(mask.mean())
404
+
405
+ def sample(
406
+ self,
407
+ time_index: int,
408
+ y: int,
409
+ x: int,
410
+ ) -> Dict[str, torch.Tensor]:
411
+ p = self.patch_size
412
+ history_window = np.asarray(
413
+ self.data[
414
+ time_index - self.history + 1:time_index + 1,
415
+ :,
416
+ y:y+p,
417
+ x:x+p,
418
+ ],
419
+ dtype=np.float32,
420
+ ).copy()
421
+ future_window = np.asarray(
422
+ self.data[
423
+ time_index + 1:time_index + self.maximum_horizon + 1,
424
+ :,
425
+ y:y+p,
426
+ x:x+p,
427
+ ],
428
+ dtype=np.float32,
429
+ ).copy()
430
+ mask = np.asarray(
431
+ self.variable_masks[:, y:y+p, x:x+p],
432
+ dtype=np.float32,
433
+ ).copy()
434
+
435
+ history_physical = (
436
+ history_window * self.window_std[None, :, None, None]
437
+ + self.window_mean[None, :, None, None]
438
+ )
439
+ future_physical = (
440
+ future_window * self.window_std[None, :, None, None]
441
+ + self.window_mean[None, :, None, None]
442
+ )
443
+ history = (
444
+ history_physical - self.reference_mean[None, :, None, None]
445
+ ) / self.reference_std[None, :, None, None]
446
+ future = (
447
+ future_physical - self.reference_mean[None, :, None, None]
448
+ ) / self.reference_std[None, :, None, None]
449
+ valid_fraction = float(mask.mean())
450
+ return {
451
+ "history": torch.from_numpy(history.astype(np.float32)),
452
+ "future": torch.from_numpy(future.astype(np.float32)),
453
+ "mask": torch.from_numpy(mask),
454
+ "time_index": torch.tensor(time_index, dtype=torch.long),
455
+ "origin_y": torch.tensor(y, dtype=torch.long),
456
+ "origin_x": torch.tensor(x, dtype=torch.long),
457
+ "valid_count": torch.tensor(float(mask.sum()), dtype=torch.float32),
458
+ "ocean_fraction": torch.tensor(valid_fraction, dtype=torch.float32),
459
+ "ocean_bin_id": torch.tensor(
460
+ list(OCEAN_BINS).index(ocean_bin(valid_fraction)),
461
+ dtype=torch.long,
462
+ ),
463
+ }
464
+
465
+
466
+ class MultiSeasonPatchDataset(Dataset):
467
+ def __init__(
468
+ self,
469
+ cubes: Mapping[str, SeasonCube],
470
+ samples: int,
471
+ seed: int,
472
+ balanced: bool,
473
+ minimum_ocean_fraction: float,
474
+ ):
475
+ self.cubes = dict(cubes)
476
+ self.seasons = list(self.cubes)
477
+ self.records: List[Tuple[str, int, int, int, str]] = []
478
+ generator = np.random.default_rng(seed)
479
+ used = set()
480
+
481
+ targets: List[Tuple[str, str]] = []
482
+ if balanced:
483
+ combinations = [
484
+ (season, bin_name)
485
+ for season in self.seasons
486
+ for bin_name in OCEAN_BINS
487
+ ]
488
+ for index in range(samples):
489
+ targets.append(combinations[index % len(combinations)])
490
+ else:
491
+ for index in range(samples):
492
+ targets.append((self.seasons[index % len(self.seasons)], "any"))
493
+
494
+ for season, requested_bin in targets:
495
+ cube = self.cubes[season]
496
+ max_y = cube.height - cube.patch_size
497
+ max_x = cube.width - cube.patch_size
498
+ selected = None
499
+ for _ in range(5000):
500
+ time_index = int(generator.choice(cube.valid_times))
501
+ y = int(generator.integers(0, max_y + 1))
502
+ x = int(generator.integers(0, max_x + 1))
503
+ fraction = cube.valid_fraction(y, x)
504
+ current_bin = ocean_bin(fraction)
505
+ key = (season, time_index, y, x)
506
+ if key in used or fraction < minimum_ocean_fraction:
507
+ continue
508
+ if requested_bin != "any" and current_bin != requested_bin:
509
+ continue
510
+ selected = (season, time_index, y, x, current_bin)
511
+ break
512
+ if selected is None:
513
+ raise RuntimeError(
514
+ f"Could not sample season={season}, bin={requested_bin}"
515
+ )
516
+ used.add(selected[:4])
517
+ self.records.append(selected)
518
+
519
+ def __len__(self) -> int:
520
+ return len(self.records)
521
+
522
+ def __getitem__(self, item: int) -> Dict[str, torch.Tensor]:
523
+ season, time_index, y, x, current_bin = self.records[item]
524
+ result = self.cubes[season].sample(time_index, y, x)
525
+ result["sample_index"] = torch.tensor(item, dtype=torch.long)
526
+ result["season_id"] = torch.tensor(
527
+ self.seasons.index(season), dtype=torch.long
528
+ )
529
+ return result
530
+
531
+
532
+ def build_datasets(
533
+ native_roots: Mapping[str, Path],
534
+ reference_mean: np.ndarray,
535
+ reference_std: np.ndarray,
536
+ args: argparse.Namespace,
537
+ ) -> Tuple[Dict[str, MultiSeasonPatchDataset], Dict[str, SeasonCube]]:
538
+ cubes = {
539
+ season: SeasonCube(
540
+ season,
541
+ root,
542
+ reference_mean,
543
+ reference_std,
544
+ args.history,
545
+ args.patch_size,
546
+ args.max_horizon,
547
+ )
548
+ for season, root in native_roots.items()
549
+ }
550
+ datasets = {
551
+ "train": MultiSeasonPatchDataset(
552
+ {season: cubes[season] for season in ["winter", "spring"]},
553
+ args.train_samples,
554
+ args.train_seed,
555
+ balanced=True,
556
+ minimum_ocean_fraction=args.minimum_ocean_fraction,
557
+ ),
558
+ "validation": MultiSeasonPatchDataset(
559
+ {"summer": cubes["summer"]},
560
+ args.validation_samples,
561
+ args.validation_seed,
562
+ balanced=True,
563
+ minimum_ocean_fraction=args.minimum_ocean_fraction,
564
+ ),
565
+ "test": MultiSeasonPatchDataset(
566
+ {"autumn": cubes["autumn"]},
567
+ args.test_samples,
568
+ args.test_seed,
569
+ balanced=True,
570
+ minimum_ocean_fraction=args.minimum_ocean_fraction,
571
+ ),
572
+ }
573
+ return datasets, cubes
574
+
575
+
576
+ def build_loaders(
577
+ datasets: Mapping[str, Dataset],
578
+ args: argparse.Namespace,
579
+ ) -> Dict[str, DataLoader]:
580
+ return {
581
+ "train": DataLoader(
582
+ datasets["train"],
583
+ batch_size=args.batch_size,
584
+ shuffle=True,
585
+ num_workers=args.num_workers,
586
+ pin_memory=torch.cuda.is_available(),
587
+ ),
588
+ "validation": DataLoader(
589
+ datasets["validation"],
590
+ batch_size=args.batch_size,
591
+ shuffle=False,
592
+ num_workers=args.num_workers,
593
+ pin_memory=torch.cuda.is_available(),
594
+ ),
595
+ "test": DataLoader(
596
+ datasets["test"],
597
+ batch_size=args.batch_size,
598
+ shuffle=False,
599
+ num_workers=args.num_workers,
600
+ pin_memory=torch.cuda.is_available(),
601
+ ),
602
+ }
603
+
604
+
605
+ def instantiate_repaired_models(
606
+ parent_assets: Mapping[str, Any],
607
+ repaired_assets: Mapping[str, Any],
608
+ seed: int,
609
+ device: torch.device,
610
+ ) -> Tuple[nn.Module, nn.Module]:
611
+ explicit = s3a0.make_explicit(
612
+ parent_assets["explicit_parent_checkpoints"][seed],
613
+ device,
614
+ )
615
+ single = s3a0.make_single(
616
+ parent_assets["single_parent_checkpoints"][seed],
617
+ device,
618
+ )
619
+ explicit_payload = torch.load(
620
+ repaired_assets["explicit_checkpoints"][seed],
621
+ map_location="cpu",
622
+ weights_only=False,
623
+ )
624
+ single_payload = torch.load(
625
+ repaired_assets["single_checkpoints"][seed],
626
+ map_location="cpu",
627
+ weights_only=False,
628
+ )
629
+ explicit.load_state_dict(explicit_payload["model_state"], strict=True)
630
+ single.load_state_dict(single_payload["model_state"], strict=True)
631
+ return explicit, single
632
+
633
+
634
+ def set_explicit_trainable_full(model: nn.Module) -> List[nn.Parameter]:
635
+ for parameter in model.parameters():
636
+ parameter.requires_grad = False
637
+ retained = [
638
+ model.encoder,
639
+ model.enc_film,
640
+ model.frame,
641
+ model.core,
642
+ model.decoder,
643
+ model.dec_film,
644
+ model.scale_out,
645
+ model.band_energy_closure,
646
+ ]
647
+ parameters: List[nn.Parameter] = []
648
+ for module in retained:
649
+ for parameter in module.parameters():
650
+ parameter.requires_grad = True
651
+ parameters.append(parameter)
652
+ # Deferred modules remain frozen even if present in the class.
653
+ for module in [
654
+ model.flux,
655
+ model.rt_closure,
656
+ model.slow_memory,
657
+ model.vertical_closure,
658
+ model.causal_variance,
659
+ ]:
660
+ for parameter in module.parameters():
661
+ parameter.requires_grad = False
662
+ return parameters
663
+
664
+
665
+ def set_single_trainable(model: nn.Module) -> List[nn.Parameter]:
666
+ parameters = []
667
+ for parameter in model.parameters():
668
+ parameter.requires_grad = True
669
+ parameters.append(parameter)
670
+ return parameters
671
+
672
+
673
+ def schedule(args: argparse.Namespace) -> List[int]:
674
+ base = [12, 20, 28, 40, 60, 60, 60]
675
+ if args.epochs <= len(base):
676
+ return base[:args.epochs]
677
+ return base + [60] * (args.epochs - len(base))
678
+
679
+
680
+
681
+ def resume_repo_path(kind: str, seed: int) -> str:
682
+ return (
683
+ "Experiments/V3_S4_A0/resume/"
684
+ f"{kind}_seed_{seed}_latest.pt"
685
+ )
686
+
687
+
688
+ def restore_resume_checkpoint(
689
+ args: argparse.Namespace,
690
+ kind: str,
691
+ seed: int,
692
+ local_path: Path,
693
+ ) -> Optional[Dict[str, Any]]:
694
+ if not args.resume or args.synthetic_smoke:
695
+ return None
696
+ token = args.hf_token or os.environ.get("HF_TOKEN") or None
697
+ if not token:
698
+ return None
699
+ if not hf_download_file(
700
+ args.hf_repo_id,
701
+ resume_repo_path(kind, seed),
702
+ local_path,
703
+ token,
704
+ ):
705
+ return None
706
+ payload = torch.load(
707
+ local_path, map_location="cpu", weights_only=False
708
+ )
709
+ saved_args = payload.get("args", {})
710
+ contract_keys = [
711
+ "train_samples",
712
+ "validation_samples",
713
+ "epochs",
714
+ "accumulation",
715
+ "minimum_ocean_fraction",
716
+ ]
717
+ mismatches = {
718
+ key: (saved_args.get(key), getattr(args, key))
719
+ for key in contract_keys
720
+ if saved_args.get(key) != getattr(args, key)
721
+ }
722
+ if mismatches:
723
+ print(
724
+ f"[resume ignored] {kind} seed={seed}, "
725
+ f"contract mismatch={mismatches}",
726
+ flush=True,
727
+ )
728
+ local_path.unlink(missing_ok=True)
729
+ return None
730
+ print(
731
+ f"[resume restored] {kind} seed={seed}, "
732
+ f"epoch={payload.get('epoch')}",
733
+ flush=True,
734
+ )
735
+ return payload
736
+
737
+
738
+ def upload_resume_checkpoint(
739
+ args: argparse.Namespace,
740
+ kind: str,
741
+ seed: int,
742
+ local_path: Path,
743
+ ) -> None:
744
+ if not args.upload_each_epoch or args.synthetic_smoke:
745
+ return
746
+ token = args.hf_token or os.environ.get("HF_TOKEN") or None
747
+ if not token:
748
+ print(
749
+ "[resume upload skipped] HF_TOKEN unavailable",
750
+ flush=True,
751
+ )
752
+ return
753
+ from huggingface_hub import HfApi
754
+ HfApi(token=token).upload_file(
755
+ path_or_fileobj=str(local_path),
756
+ path_in_repo=resume_repo_path(kind, seed),
757
+ repo_id=args.hf_repo_id,
758
+ repo_type="dataset",
759
+ )
760
+ print(
761
+ f"[resume uploaded] {kind} seed={seed}",
762
+ flush=True,
763
+ )
764
+
765
+
766
+ def train_medium(
767
+ model: nn.Module,
768
+ kind: str,
769
+ seed: int,
770
+ loaders: Mapping[str, DataLoader],
771
+ device: torch.device,
772
+ means: torch.Tensor,
773
+ stds: torch.Tensor,
774
+ args: argparse.Namespace,
775
+ output_dir: Path,
776
+ ) -> Tuple[nn.Module, Dict[str, Any]]:
777
+ seed_everything(seed)
778
+ if kind == "explicit":
779
+ parameters = set_explicit_trainable_full(model)
780
+ learning_rate = args.explicit_learning_rate
781
+ else:
782
+ parameters = set_single_trainable(model)
783
+ learning_rate = args.single_learning_rate
784
+
785
+ optimizer = torch.optim.AdamW(
786
+ parameters,
787
+ lr=learning_rate,
788
+ weight_decay=args.weight_decay,
789
+ )
790
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
791
+ optimizer,
792
+ T_max=max(args.epochs, 1),
793
+ eta_min=learning_rate * 0.2,
794
+ )
795
+ best_score = float("inf")
796
+ best_epoch = -1
797
+ best_state = None
798
+ best_optimizer = None
799
+ logs = []
800
+ start_time = time.time()
801
+ horizons = schedule(args)
802
+ resume_path = (
803
+ output_dir / "resume" / f"{kind}_seed_{seed}_latest.pt"
804
+ )
805
+ resume_payload = restore_resume_checkpoint(
806
+ args, kind, seed, resume_path
807
+ )
808
+ start_epoch = 1
809
+ if resume_payload is not None:
810
+ model.load_state_dict(
811
+ resume_payload["model_state"], strict=True
812
+ )
813
+ optimizer.load_state_dict(
814
+ resume_payload["optimizer_state"]
815
+ )
816
+ scheduler.load_state_dict(
817
+ resume_payload["scheduler_state"]
818
+ )
819
+ best_state = resume_payload.get("best_state")
820
+ best_score = float(
821
+ resume_payload.get("best_score", best_score)
822
+ )
823
+ best_epoch = int(
824
+ resume_payload.get("best_epoch", best_epoch)
825
+ )
826
+ start_epoch = int(resume_payload["epoch"]) + 1
827
+
828
+ for epoch, horizon in enumerate(horizons, start=1):
829
+ if epoch < start_epoch:
830
+ continue
831
+ model.train()
832
+ optimizer.zero_grad(set_to_none=True)
833
+ totals: Dict[str, float] = {}
834
+ for batch_index, batch in enumerate(loaders["train"], start=1):
835
+ history = batch["history"].to(device, non_blocking=True)
836
+ future = batch["future"].to(device, non_blocking=True)
837
+ mask = batch["mask"].to(device, non_blocking=True)
838
+ if kind == "explicit":
839
+ outputs = s3a1.rollout_explicit_train(
840
+ model, history, mask, horizon
841
+ )
842
+ else:
843
+ outputs = s3a1.rollout_single_train(
844
+ model, history, mask, horizon
845
+ )
846
+ parts = s3a1.sequence_objective(
847
+ outputs,
848
+ history,
849
+ future[:, :horizon],
850
+ mask,
851
+ means,
852
+ stds,
853
+ args,
854
+ )
855
+ if not torch.isfinite(parts["total"]):
856
+ raise RuntimeError(
857
+ f"Non-finite loss kind={kind}, seed={seed}, "
858
+ f"epoch={epoch}, batch={batch_index}"
859
+ )
860
+ (parts["total"] / args.accumulation).backward()
861
+ if (
862
+ batch_index % args.accumulation == 0
863
+ or batch_index == len(loaders["train"])
864
+ ):
865
+ torch.nn.utils.clip_grad_norm_(parameters, args.grad_clip)
866
+ optimizer.step()
867
+ optimizer.zero_grad(set_to_none=True)
868
+ for key, value in parts.items():
869
+ totals[key] = totals.get(key, 0.0) + float(value.detach())
870
+
871
+ if batch_index % max(len(loaders["train"]) // 5, 1) == 0:
872
+ elapsed = time.time() - start_time
873
+ completed = (
874
+ (epoch - 1) * len(loaders["train"]) + batch_index
875
+ )
876
+ total_batches = len(horizons) * len(loaders["train"])
877
+ eta = elapsed / max(completed, 1) * max(total_batches - completed, 0)
878
+ print(
879
+ f"[{kind} seed={seed}] epoch={epoch}/{args.epochs} "
880
+ f"H={horizon} batch={batch_index}/{len(loaders['train'])} "
881
+ f"loss={totals['total']/batch_index:.6f} "
882
+ f"ETA={eta/3600:.2f}h",
883
+ flush=True,
884
+ )
885
+
886
+ scheduler.step()
887
+ validation = s3a1.validation_score(
888
+ model,
889
+ kind,
890
+ loaders["validation"],
891
+ device,
892
+ means,
893
+ stds,
894
+ )
895
+ row = {
896
+ "kind": kind,
897
+ "seed": seed,
898
+ "epoch": epoch,
899
+ "train_horizon": horizon,
900
+ "learning_rate": optimizer.param_groups[0]["lr"],
901
+ **{
902
+ f"train_{key}": value / max(len(loaders["train"]), 1)
903
+ for key, value in totals.items()
904
+ },
905
+ **{
906
+ f"validation_{key}": value
907
+ for key, value in validation.items()
908
+ },
909
+ }
910
+ logs.append(row)
911
+ print(
912
+ f"[VAL {kind} seed={seed}] epoch={epoch} "
913
+ f"score={validation['score']:.6f} "
914
+ f"72h={validation['rmse_h12']:.5f} "
915
+ f"7d={validation['rmse_h28']:.5f} "
916
+ f"15d={validation['rmse_h60']:.5f}",
917
+ flush=True,
918
+ )
919
+ if validation["score"] < best_score:
920
+ best_score = validation["score"]
921
+ best_epoch = epoch
922
+ best_state = {
923
+ key: value.detach().cpu().clone()
924
+ for key, value in model.state_dict().items()
925
+ }
926
+ best_optimizer = copy.deepcopy(optimizer.state_dict())
927
+
928
+ epoch_dir = output_dir / "resume"
929
+ epoch_dir.mkdir(parents=True, exist_ok=True)
930
+ latest_path = epoch_dir / f"{kind}_seed_{seed}_latest.pt"
931
+ torch.save(
932
+ {
933
+ "kind": kind,
934
+ "seed": seed,
935
+ "epoch": epoch,
936
+ "model_state": model.state_dict(),
937
+ "optimizer_state": optimizer.state_dict(),
938
+ "scheduler_state": scheduler.state_dict(),
939
+ "best_state": best_state,
940
+ "best_score": best_score,
941
+ "best_epoch": best_epoch,
942
+ "args": vars(args),
943
+ },
944
+ latest_path,
945
+ )
946
+ upload_resume_checkpoint(
947
+ args, kind, seed, latest_path
948
+ )
949
+
950
+ if best_state is None:
951
+ raise RuntimeError(f"No checkpoint selected for {kind} seed={seed}")
952
+ model.load_state_dict(best_state, strict=True)
953
+ checkpoint_dir = output_dir / "checkpoints" / kind
954
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
955
+ checkpoint = checkpoint_dir / f"seed_{seed}.pt"
956
+ torch.save(
957
+ {
958
+ "kind": kind,
959
+ "seed": seed,
960
+ "best_epoch": best_epoch,
961
+ "best_score": best_score,
962
+ "model_state": best_state,
963
+ "optimizer_state_at_best": best_optimizer,
964
+ "args": vars(args),
965
+ "architecture_change": "none",
966
+ "training_scope": "multi-season medium-scale qualification",
967
+ },
968
+ checkpoint,
969
+ )
970
+ log_path = output_dir / "training" / f"{kind}_seed_{seed}.csv"
971
+ log_path.parent.mkdir(parents=True, exist_ok=True)
972
+ pd.DataFrame(logs).to_csv(log_path, index=False)
973
+ return model, {
974
+ "kind": kind,
975
+ "seed": seed,
976
+ "best_epoch": best_epoch,
977
+ "best_score": best_score,
978
+ "checkpoint": str(checkpoint),
979
+ }
980
+
981
+
982
+ def empty_accumulator() -> Dict[str, Any]:
983
+ return {
984
+ "squared": {step: 0.0 for step in HORIZONS},
985
+ "count": {step: 0.0 for step in HORIZONS},
986
+ "pred": {step: [] for step in HORIZONS},
987
+ "target": {step: [] for step in HORIZONS},
988
+ "samples": [],
989
+ "groups": {
990
+ (step, group): []
991
+ for step in HORIZONS
992
+ for group in GROUPS
993
+ },
994
+ "finite": True,
995
+ "max_abs": 0.0,
996
+ "wave_invalid": {step: [] for step in HORIZONS},
997
+ "direction_norm": {step: [] for step in HORIZONS},
998
+ "spectral_pred": {step: [] for step in [12, 28, 60]},
999
+ "spectral_target": {step: [] for step in [12, 28, 60]},
1000
+ }
1001
+
1002
+
1003
+ def update_accumulator(
1004
+ accumulator: Dict[str, Any],
1005
+ outputs: Sequence[torch.Tensor],
1006
+ future: torch.Tensor,
1007
+ mask: torch.Tensor,
1008
+ batch: Mapping[str, torch.Tensor],
1009
+ means: torch.Tensor,
1010
+ stds: torch.Tensor,
1011
+ ) -> None:
1012
+ for step in HORIZONS:
1013
+ prediction = outputs[step - 1]
1014
+ target = future[:, step - 1]
1015
+ error = (prediction - target).square() * mask
1016
+ sample_sse = error.flatten(1).sum(dim=1)
1017
+ sample_count = mask.flatten(1).sum(dim=1).clamp_min(1.0)
1018
+ sample_mse = sample_sse / sample_count
1019
+ accumulator["squared"][step] += float(sample_sse.sum())
1020
+ accumulator["count"][step] += float(sample_count.sum())
1021
+ accumulator["pred"][step].append((prediction * mask).flatten(1).cpu())
1022
+ accumulator["target"][step].append((target * mask).flatten(1).cpu())
1023
+
1024
+ for bi in range(prediction.shape[0]):
1025
+ fraction = float(batch["ocean_fraction"][bi])
1026
+ accumulator["samples"].append({
1027
+ "sample_index": int(batch["sample_index"][bi]),
1028
+ "time_index": int(batch["time_index"][bi]),
1029
+ "origin_y": int(batch["origin_y"][bi]),
1030
+ "origin_x": int(batch["origin_x"][bi]),
1031
+ "horizon": step,
1032
+ "sse": float(sample_sse[bi]),
1033
+ "valid_count": float(sample_count[bi]),
1034
+ "mse": float(sample_mse[bi]),
1035
+ "rmse": math.sqrt(max(float(sample_mse[bi]), 0.0)),
1036
+ "ocean_fraction": fraction,
1037
+ "ocean_bin": ocean_bin(fraction),
1038
+ })
1039
+
1040
+ for group, indices in GROUPS.items():
1041
+ group_mask = mask[:, indices]
1042
+ group_error = error[:, indices]
1043
+ denominator = group_mask.flatten(1).sum(dim=1).clamp_min(1.0)
1044
+ values = torch.sqrt(
1045
+ group_error.flatten(1).sum(dim=1) / denominator
1046
+ )
1047
+ accumulator["groups"][(step, group)].extend(values.cpu().tolist())
1048
+
1049
+ invalid, direction = s3a0.physical_wave_audit(
1050
+ prediction, means, stds, mask
1051
+ )
1052
+ accumulator["wave_invalid"][step].extend(invalid.cpu().tolist())
1053
+ accumulator["direction_norm"][step].extend(direction.cpu().tolist())
1054
+
1055
+ if step in accumulator["spectral_pred"]:
1056
+ accumulator["spectral_pred"][step].append(
1057
+ s3a0.spectral_energy_ratios(prediction, mask).cpu()
1058
+ )
1059
+ accumulator["spectral_target"][step].append(
1060
+ s3a0.spectral_energy_ratios(target, mask).cpu()
1061
+ )
1062
+
1063
+ accumulator["finite"] = (
1064
+ accumulator["finite"] and bool(torch.isfinite(prediction).all())
1065
+ )
1066
+ accumulator["max_abs"] = max(
1067
+ accumulator["max_abs"], float(prediction.abs().max())
1068
+ )
1069
+
1070
+
1071
+ def finalize_accumulator(accumulator: Dict[str, Any]) -> Dict[str, Any]:
1072
+ result = {
1073
+ "finite": bool(accumulator["finite"]),
1074
+ "max_abs": float(accumulator["max_abs"]),
1075
+ }
1076
+ for step in HORIZONS:
1077
+ result[f"rmse_h{step}"] = math.sqrt(
1078
+ accumulator["squared"][step]
1079
+ / max(accumulator["count"][step], 1.0)
1080
+ )
1081
+ prediction = torch.cat(accumulator["pred"][step], dim=0)
1082
+ target = torch.cat(accumulator["target"][step], dim=0)
1083
+ result[f"variance_ratio_h{step}"] = float(
1084
+ prediction.var(unbiased=False)
1085
+ / (target.var(unbiased=False) + 1e-8)
1086
+ )
1087
+ result[f"wave_invalid_fraction_h{step}"] = float(
1088
+ np.mean(accumulator["wave_invalid"][step])
1089
+ )
1090
+ result[f"direction_norm_error_h{step}"] = float(
1091
+ np.mean(accumulator["direction_norm"][step])
1092
+ )
1093
+ for group in GROUPS:
1094
+ result[f"group_rmse_{group}_h{step}"] = float(
1095
+ np.mean(accumulator["groups"][(step, group)])
1096
+ )
1097
+ if step in accumulator["spectral_pred"]:
1098
+ pred_energy = torch.cat(
1099
+ accumulator["spectral_pred"][step], dim=0
1100
+ ).mean(dim=0)
1101
+ target_energy = torch.cat(
1102
+ accumulator["spectral_target"][step], dim=0
1103
+ ).mean(dim=0)
1104
+ ratio = pred_energy / (target_energy + 1e-8)
1105
+ for index, band in enumerate(["low", "mid", "high"]):
1106
+ result[f"spectral_{band}_ratio_h{step}"] = float(ratio[index])
1107
+ result["sample_rows"] = accumulator["samples"]
1108
+ return result
1109
+
1110
+
1111
+ @torch.no_grad()
1112
+ def evaluate_methods(
1113
+ models: Mapping[str, nn.Module],
1114
+ loader: DataLoader,
1115
+ device: torch.device,
1116
+ means: torch.Tensor,
1117
+ stds: torch.Tensor,
1118
+ ) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, pd.DataFrame]]:
1119
+ accumulators = {method: empty_accumulator() for method in METHODS}
1120
+ for batch_number, batch in enumerate(loader, start=1):
1121
+ history = batch["history"].to(device)
1122
+ future = batch["future"].to(device)
1123
+ mask = batch["mask"].to(device)
1124
+ persistence = [history[:, -1] * mask for _ in range(60)]
1125
+ outputs = {
1126
+ "persistence": persistence,
1127
+ "parent_single": s3a1.rollout_single(
1128
+ models["parent_single"], history, mask, 60
1129
+ ),
1130
+ "parent_explicit_band": s3a1.rollout_explicit(
1131
+ models["parent_explicit"], history, mask, 60, True
1132
+ ),
1133
+ "medium_single": s3a1.rollout_single(
1134
+ models["medium_single"], history, mask, 60
1135
+ ),
1136
+ "medium_explicit_no_band": s3a1.rollout_explicit(
1137
+ models["medium_explicit"], history, mask, 60, False
1138
+ ),
1139
+ "medium_explicit_band": s3a1.rollout_explicit(
1140
+ models["medium_explicit"], history, mask, 60, True
1141
+ ),
1142
+ }
1143
+ for method, current in outputs.items():
1144
+ update_accumulator(
1145
+ accumulators[method],
1146
+ current,
1147
+ future,
1148
+ mask,
1149
+ batch,
1150
+ means,
1151
+ stds,
1152
+ )
1153
+ if batch_number % max(len(loader) // 6, 1) == 0:
1154
+ print(f"[test] batch={batch_number}/{len(loader)}", flush=True)
1155
+
1156
+ metrics = {}
1157
+ tables = {}
1158
+ for method, accumulator in accumulators.items():
1159
+ current = finalize_accumulator(accumulator)
1160
+ tables[method] = pd.DataFrame(current.pop("sample_rows"))
1161
+ metrics[method] = current
1162
+ return metrics, tables
1163
+
1164
+
1165
+ def block_bootstrap(
1166
+ reference_tables: Sequence[pd.DataFrame],
1167
+ candidate_tables: Sequence[pd.DataFrame],
1168
+ horizon: int,
1169
+ repetitions: int,
1170
+ seed: int,
1171
+ ) -> Dict[str, float]:
1172
+ return s3a1.time_block_bootstrap(
1173
+ reference_tables,
1174
+ candidate_tables,
1175
+ horizon,
1176
+ repetitions,
1177
+ seed,
1178
+ )
1179
+
1180
+
1181
+ def ocean_bin_comparison(
1182
+ candidate_tables: Sequence[pd.DataFrame],
1183
+ reference_tables: Sequence[pd.DataFrame],
1184
+ horizon: int,
1185
+ ) -> List[Dict[str, Any]]:
1186
+ candidate = pd.concat(candidate_tables, ignore_index=True)
1187
+ reference = pd.concat(reference_tables, ignore_index=True)
1188
+ keys = [
1189
+ "seed",
1190
+ "sample_index",
1191
+ "time_index",
1192
+ "origin_y",
1193
+ "origin_x",
1194
+ "horizon",
1195
+ "ocean_bin",
1196
+ "ocean_fraction",
1197
+ "valid_count",
1198
+ ]
1199
+ merged = reference.merge(
1200
+ candidate,
1201
+ on=keys,
1202
+ suffixes=("_reference", "_candidate"),
1203
+ )
1204
+ merged = merged[merged.horizon == horizon]
1205
+ rows = []
1206
+ for bin_name in OCEAN_BINS:
1207
+ current = merged[merged.ocean_bin == bin_name]
1208
+ if current.empty:
1209
+ continue
1210
+ reference_mse = (
1211
+ current.sse_reference.sum() / current.valid_count.sum()
1212
+ )
1213
+ candidate_mse = (
1214
+ current.sse_candidate.sum() / current.valid_count.sum()
1215
+ )
1216
+ rows.append({
1217
+ "horizon": horizon,
1218
+ "lead": HORIZON_LABELS[horizon],
1219
+ "ocean_bin": bin_name,
1220
+ "samples_with_seed_repeats": len(current),
1221
+ "mean_ocean_fraction": float(current.ocean_fraction.mean()),
1222
+ "weighted_mse_gain_percent": float(
1223
+ 100.0 * (reference_mse - candidate_mse)
1224
+ / max(reference_mse, 1e-12)
1225
+ ),
1226
+ "equal_sample_mse_gain_percent": float(
1227
+ 100.0
1228
+ * (
1229
+ current.mse_reference.mean()
1230
+ - current.mse_candidate.mean()
1231
+ )
1232
+ / max(current.mse_reference.mean(), 1e-12)
1233
+ ),
1234
+ "fraction_improved": float(
1235
+ (current.mse_candidate < current.mse_reference).mean()
1236
+ ),
1237
+ })
1238
+ return rows
1239
+
1240
+
1241
+ def build_parser() -> argparse.ArgumentParser:
1242
+ parser = argparse.ArgumentParser(
1243
+ description="CIDM-v3 multi-season medium-scale qualification"
1244
+ )
1245
+ parser.add_argument(
1246
+ "--s3a1_zip",
1247
+ default="/content/CIDM_v3_SCS_V3_S3_A1.zip",
1248
+ )
1249
+ parser.add_argument(
1250
+ "--s3a0_zip",
1251
+ default="/content/CIDM_v3_SCS_V3_S3_A0.zip",
1252
+ )
1253
+ parser.add_argument(
1254
+ "--native_cache_dir",
1255
+ default="/content/CIDM_v3_SCS_S2A2_NATIVE_1_12",
1256
+ )
1257
+ parser.add_argument(
1258
+ "--parent_cache",
1259
+ default="/content/CIDM_v3_SCS_S4A0_PARENT_CACHE",
1260
+ )
1261
+ parser.add_argument(
1262
+ "--output_dir",
1263
+ default="/content/CIDM_v3_SCS_V3_S4_A0",
1264
+ )
1265
+ parser.add_argument(
1266
+ "--hf_repo_id",
1267
+ default="wuff-mann/CIDM-v3-SCS-S2A0-Data",
1268
+ )
1269
+ parser.add_argument("--hf_token", default="")
1270
+ parser.add_argument("--history", type=int, default=4)
1271
+ parser.add_argument("--patch_size", type=int, default=48)
1272
+ parser.add_argument("--max_horizon", type=int, default=60)
1273
+ parser.add_argument("--minimum_ocean_fraction", type=float, default=0.10)
1274
+ parser.add_argument("--train_samples", type=int, default=288)
1275
+ parser.add_argument("--validation_samples", type=int, default=72)
1276
+ parser.add_argument("--test_samples", type=int, default=96)
1277
+ parser.add_argument("--train_seed", type=int, default=20261031)
1278
+ parser.add_argument("--validation_seed", type=int, default=20261101)
1279
+ parser.add_argument("--test_seed", type=int, default=20261102)
1280
+ parser.add_argument("--batch_size", type=int, default=1)
1281
+ parser.add_argument("--num_workers", type=int, default=0)
1282
+ parser.add_argument("--epochs", type=int, default=7)
1283
+ parser.add_argument("--accumulation", type=int, default=4)
1284
+ parser.add_argument("--explicit_learning_rate", type=float, default=1.5e-5)
1285
+ parser.add_argument("--single_learning_rate", type=float, default=2.5e-5)
1286
+ parser.add_argument("--weight_decay", type=float, default=1e-4)
1287
+ parser.add_argument("--grad_clip", type=float, default=1.0)
1288
+ parser.add_argument("--gradient_weight", type=float, default=0.08)
1289
+ parser.add_argument("--increment_weight", type=float, default=0.12)
1290
+ parser.add_argument("--persistence_skill_weight", type=float, default=0.25)
1291
+ parser.add_argument("--persistence_target_ratio", type=float, default=0.98)
1292
+ parser.add_argument("--variance_weight", type=float, default=0.08)
1293
+ parser.add_argument("--spectral_weight", type=float, default=0.04)
1294
+ parser.add_argument("--wave_nonnegative_weight", type=float, default=0.02)
1295
+ parser.add_argument("--direction_circle_weight", type=float, default=0.08)
1296
+ parser.add_argument("--bootstrap_reps", type=int, default=1000)
1297
+ parser.add_argument(
1298
+ "--resume",
1299
+ action=argparse.BooleanOptionalAction,
1300
+ default=True,
1301
+ )
1302
+ parser.add_argument(
1303
+ "--upload_each_epoch",
1304
+ action=argparse.BooleanOptionalAction,
1305
+ default=True,
1306
+ )
1307
+ parser.add_argument(
1308
+ "--seeds",
1309
+ default="20260902,20260903,20260904",
1310
+ )
1311
+ parser.add_argument("--no_live_download", action="store_true")
1312
+ parser.add_argument("--delete_native_raw", action="store_true")
1313
+ parser.add_argument("--synthetic_smoke", action="store_true")
1314
+ return parser
1315
+
1316
+
1317
+ def create_synthetic_native(
1318
+ destination: Path,
1319
+ metadata: Mapping[str, Any],
1320
+ season_index: int,
1321
+ time_steps: int = 80,
1322
+ height: int = 64,
1323
+ width: int = 96,
1324
+ ) -> None:
1325
+ destination.mkdir(parents=True, exist_ok=True)
1326
+ generator = np.random.default_rng(20261100 + season_index)
1327
+ data = generator.normal(
1328
+ 0.0, 1.0,
1329
+ (time_steps, len(VARIABLE_NAMES), height, width),
1330
+ ).astype(np.float32)
1331
+ np.save(destination / "scs_c0_data.npy", data)
1332
+ np.save(
1333
+ destination / "scs_c0_mask.npy",
1334
+ np.ones((height, width), dtype=np.float32),
1335
+ )
1336
+ variable_masks = np.ones(
1337
+ (len(VARIABLE_NAMES), height, width),
1338
+ dtype=np.float32,
1339
+ )
1340
+ # Add a deterministic coastal strip for bin-path validation.
1341
+ variable_masks[:, :, :32] = 0.0
1342
+ np.save(destination / "scs_c0_variable_masks.npy", variable_masks)
1343
+ current = {
1344
+ "variable_names": VARIABLE_NAMES,
1345
+ "means": metadata["means"],
1346
+ "stds": metadata["stds"],
1347
+ "times_ns": (
1348
+ np.datetime64("2023-01-15")
1349
+ + np.arange(time_steps) * np.timedelta64(6, "h")
1350
+ ).astype("datetime64[ns]").astype(np.int64).tolist(),
1351
+ "latitude": np.linspace(0, 25, height).tolist(),
1352
+ "longitude": np.linspace(99, 123, width).tolist(),
1353
+ "shape": list(data.shape),
1354
+ "native_resolution_degrees": 1 / 12,
1355
+ }
1356
+ atomic_json(current, destination / "scs_c0_metadata.json")
1357
+ pd.DataFrame({
1358
+ "variable": VARIABLE_NAMES,
1359
+ "mean": current["means"],
1360
+ "std": current["stds"],
1361
+ }).to_csv(destination / "C0_data_audit.csv", index=False)
1362
+
1363
+
1364
+ def main() -> None:
1365
+ args = build_parser().parse_args()
1366
+ seeds = [
1367
+ int(value) for value in args.seeds.split(",") if value.strip()
1368
+ ]
1369
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
1370
+ if not args.synthetic_smoke and device.type != "cuda":
1371
+ raise RuntimeError("Formal S4-A0 requires CUDA.")
1372
+ torch.set_float32_matmul_precision("highest")
1373
+ if torch.cuda.is_available():
1374
+ torch.backends.cuda.matmul.allow_tf32 = False
1375
+ torch.backends.cudnn.allow_tf32 = False
1376
+
1377
+ output_dir = Path(args.output_dir)
1378
+ shutil.rmtree(output_dir, ignore_errors=True)
1379
+ for subdir in [
1380
+ "audits", "training", "checkpoints", "resume",
1381
+ "evaluation", "figures", "lineage", "deployment",
1382
+ ]:
1383
+ (output_dir / subdir).mkdir(parents=True, exist_ok=True)
1384
+
1385
+ try:
1386
+ stage(1, 10, "恢复S3-A1/S3-A0父资产")
1387
+ if args.synthetic_smoke:
1388
+ if not Path(args.s3a1_zip).is_file() or not Path(args.s3a0_zip).is_file():
1389
+ raise FileNotFoundError("Synthetic smoke requires local parent ZIPs.")
1390
+ parent_report = {
1391
+ "synthetic_smoke": True,
1392
+ "s3a1_sha256": sha256_file(Path(args.s3a1_zip)),
1393
+ "s3a0_sha256": sha256_file(Path(args.s3a0_zip)),
1394
+ }
1395
+ else:
1396
+ parent_report = ensure_parent_assets(args)
1397
+ atomic_json(
1398
+ parent_report,
1399
+ output_dir / "audits" / "S4A0_parent_asset_audit.json",
1400
+ )
1401
+
1402
+ stage(2, 10, "提取结构父模型和S3-A1修复权重")
1403
+ parent_cache = Path(args.parent_cache)
1404
+ shutil.rmtree(parent_cache, ignore_errors=True)
1405
+ s3a0_assets = extract_s3a0_assets(
1406
+ Path(args.s3a0_zip), parent_cache / "s3a0"
1407
+ )
1408
+ s3a1_assets = extract_s3a1_assets(
1409
+ Path(args.s3a1_zip), parent_cache / "s3a1"
1410
+ )
1411
+ reference_mean = np.asarray(
1412
+ s3a0_assets["metadata"]["means"], dtype=np.float32
1413
+ )
1414
+ reference_std = np.asarray(
1415
+ s3a0_assets["metadata"]["stds"], dtype=np.float32
1416
+ )
1417
+ atomic_json(
1418
+ {
1419
+ "s3a1_verdict": s3a1_assets["verdict"],
1420
+ "architecture_changed": False,
1421
+ "architecture_policy": {
1422
+ "keep": [
1423
+ "explicit multi-scale information state",
1424
+ "shared scale-conditioned CIDM Core",
1425
+ "multi-step recurrence",
1426
+ "Band Closure",
1427
+ "multi-resolution decoder",
1428
+ ],
1429
+ "remain_off": [
1430
+ "all BER branches",
1431
+ "learned cross-scale flux",
1432
+ "slow/vertical output closure",
1433
+ "causal variance amplifier",
1434
+ "event router",
1435
+ ],
1436
+ },
1437
+ },
1438
+ output_dir / "lineage" / "S4A0_parent_lineage.json",
1439
+ )
1440
+
1441
+ stage(3, 10, "准备四季原生1/12°缓存")
1442
+ native_roots = {}
1443
+ native_reports = []
1444
+ for index, season in enumerate(SEASONS):
1445
+ if args.synthetic_smoke:
1446
+ root = Path(args.native_cache_dir) / season / "prepared"
1447
+ create_synthetic_native(
1448
+ root,
1449
+ s3a0_assets["metadata"],
1450
+ index,
1451
+ time_steps=max(args.max_horizon + args.history + 16, 80),
1452
+ )
1453
+ report = {"season": season, "source": "synthetic"}
1454
+ else:
1455
+ root, report = prepare_native_season(args, season)
1456
+ native_roots[season] = root
1457
+ native_reports.append(report)
1458
+ atomic_json(
1459
+ native_reports,
1460
+ output_dir / "audits" / "S4A0_native_sources.json",
1461
+ )
1462
+
1463
+ stage(4, 10, "构建近岸/陆架/开阔海域平衡训练集")
1464
+ datasets, cubes = build_datasets(
1465
+ native_roots,
1466
+ reference_mean,
1467
+ reference_std,
1468
+ args,
1469
+ )
1470
+ loaders = build_loaders(datasets, args)
1471
+ split_audit = {}
1472
+ for split, dataset in datasets.items():
1473
+ bins = pd.Series(
1474
+ [record[-1] for record in dataset.records]
1475
+ ).value_counts().to_dict()
1476
+ split_audit[split] = {
1477
+ "samples": len(dataset),
1478
+ "bin_counts": bins,
1479
+ "seasons": sorted(set(record[0] for record in dataset.records)),
1480
+ "unique_records": len(set(record[:4] for record in dataset.records)),
1481
+ }
1482
+ split_audit["training_schedule"] = schedule(args)
1483
+ split_audit["minimum_ocean_fraction"] = args.minimum_ocean_fraction
1484
+ atomic_json(
1485
+ split_audit,
1486
+ output_dir / "audits" / "S4A0_split_audit.json",
1487
+ )
1488
+
1489
+ means = torch.as_tensor(reference_mean, device=device)
1490
+ stds = torch.as_tensor(reference_std, device=device)
1491
+
1492
+ stage(5, 10, "三种子同目标多季节训练")
1493
+ parents = {}
1494
+ trained = {}
1495
+ training_rows = []
1496
+ for seed in seeds:
1497
+ parent_explicit, parent_single = instantiate_repaired_models(
1498
+ s3a0_assets,
1499
+ s3a1_assets,
1500
+ seed,
1501
+ device,
1502
+ )
1503
+ medium_explicit = copy.deepcopy(parent_explicit)
1504
+ medium_single = copy.deepcopy(parent_single)
1505
+ medium_explicit, explicit_record = train_medium(
1506
+ medium_explicit,
1507
+ "explicit",
1508
+ seed,
1509
+ loaders,
1510
+ device,
1511
+ means,
1512
+ stds,
1513
+ args,
1514
+ output_dir,
1515
+ )
1516
+ medium_single, single_record = train_medium(
1517
+ medium_single,
1518
+ "single",
1519
+ seed,
1520
+ loaders,
1521
+ device,
1522
+ means,
1523
+ stds,
1524
+ args,
1525
+ output_dir,
1526
+ )
1527
+ parents[seed] = {
1528
+ "parent_explicit": parent_explicit,
1529
+ "parent_single": parent_single,
1530
+ }
1531
+ trained[seed] = {
1532
+ "medium_explicit": medium_explicit,
1533
+ "medium_single": medium_single,
1534
+ }
1535
+ training_rows.extend([explicit_record, single_record])
1536
+ pd.DataFrame(training_rows).to_csv(
1537
+ output_dir / "S4A0_training_summary.csv", index=False
1538
+ )
1539
+
1540
+ stage(6, 10, "秋季独立测试和样本级记录")
1541
+ metric_rows = []
1542
+ sample_tables: Dict[Tuple[int, str], pd.DataFrame] = {}
1543
+ for seed in seeds:
1544
+ models = {
1545
+ **parents[seed],
1546
+ **trained[seed],
1547
+ }
1548
+ metrics, tables = evaluate_methods(
1549
+ models,
1550
+ loaders["test"],
1551
+ device,
1552
+ means,
1553
+ stds,
1554
+ )
1555
+ for method, current in metrics.items():
1556
+ metric_rows.append({
1557
+ "seed": seed,
1558
+ "method": method,
1559
+ **current,
1560
+ })
1561
+ table = tables[method].copy()
1562
+ table["seed"] = seed
1563
+ sample_tables[(seed, method)] = table
1564
+ table.to_csv(
1565
+ output_dir
1566
+ / "evaluation"
1567
+ / f"S4A0_samples_{method}_seed_{seed}.csv",
1568
+ index=False,
1569
+ )
1570
+ metric_table = pd.DataFrame(metric_rows)
1571
+ metric_table.to_csv(
1572
+ output_dir / "evaluation" / "S4A0_seed_metrics.csv",
1573
+ index=False,
1574
+ )
1575
+
1576
+ stage(7, 10, "时间块Bootstrap和海洋占比分层")
1577
+ comparisons = [
1578
+ ("medium_explicit_band", "medium_single"),
1579
+ ("medium_explicit_band", "parent_explicit_band"),
1580
+ ("medium_explicit_band", "medium_explicit_no_band"),
1581
+ ("medium_explicit_band", "persistence"),
1582
+ ("medium_single", "parent_single"),
1583
+ ]
1584
+ comparison_rows = []
1585
+ bootstrap_payload = {}
1586
+ for candidate, reference in comparisons:
1587
+ for horizon in [12, 28, 60]:
1588
+ result = block_bootstrap(
1589
+ [sample_tables[(seed, reference)] for seed in seeds],
1590
+ [sample_tables[(seed, candidate)] for seed in seeds],
1591
+ horizon,
1592
+ args.bootstrap_reps,
1593
+ seeds[0] + horizon + sum(map(ord, candidate + reference)),
1594
+ )
1595
+ key = f"{candidate}_vs_{reference}_h{horizon}"
1596
+ bootstrap_payload[key] = result
1597
+ comparison_rows.append({
1598
+ "candidate": candidate,
1599
+ "reference": reference,
1600
+ "horizon": horizon,
1601
+ "lead": HORIZON_LABELS[horizon],
1602
+ **result,
1603
+ })
1604
+ comparison_table = pd.DataFrame(comparison_rows)
1605
+ comparison_table.to_csv(
1606
+ output_dir / "S4A0_block_bootstrap_comparisons.csv",
1607
+ index=False,
1608
+ )
1609
+ atomic_json(
1610
+ bootstrap_payload,
1611
+ output_dir / "paired_block_bootstrap.json",
1612
+ )
1613
+
1614
+ bin_rows = []
1615
+ for horizon in [12, 28, 60]:
1616
+ bin_rows.extend(
1617
+ ocean_bin_comparison(
1618
+ [sample_tables[(seed, "medium_explicit_band")] for seed in seeds],
1619
+ [sample_tables[(seed, "medium_single")] for seed in seeds],
1620
+ horizon,
1621
+ )
1622
+ )
1623
+ bin_table = pd.DataFrame(bin_rows)
1624
+ bin_table.to_csv(
1625
+ output_dir / "S4A0_ocean_fraction_bin_comparisons.csv",
1626
+ index=False,
1627
+ )
1628
+
1629
+ summary_rows = []
1630
+ for method in METHODS:
1631
+ current = metric_table[
1632
+ metric_table.method == method
1633
+ ].set_index("seed")
1634
+ for horizon in HORIZONS:
1635
+ summary_rows.append({
1636
+ "method": method,
1637
+ "horizon": horizon,
1638
+ "lead": HORIZON_LABELS[horizon],
1639
+ "rmse": float(current[f"rmse_h{horizon}"].mean()),
1640
+ "variance_ratio": float(
1641
+ current[f"variance_ratio_h{horizon}"].mean()
1642
+ ),
1643
+ "wave_invalid_fraction": float(
1644
+ current[f"wave_invalid_fraction_h{horizon}"].mean()
1645
+ ),
1646
+ "direction_norm_error": float(
1647
+ current[f"direction_norm_error_h{horizon}"].mean()
1648
+ ),
1649
+ "finite": bool(current["finite"].all()),
1650
+ "max_abs": float(current["max_abs"].max()),
1651
+ })
1652
+ summary = pd.DataFrame(summary_rows)
1653
+ summary.to_csv(
1654
+ output_dir / "S4A0_long_rollout_summary.csv",
1655
+ index=False,
1656
+ )
1657
+
1658
+ stage(8, 10, "正式训练启动资格判决")
1659
+ mean_metrics = metric_table.groupby("method").mean(numeric_only=True)
1660
+
1661
+ def gain(candidate: str, reference: str, horizon: int) -> float:
1662
+ return 100.0 * (
1663
+ mean_metrics.loc[reference, f"rmse_h{horizon}"]
1664
+ - mean_metrics.loc[candidate, f"rmse_h{horizon}"]
1665
+ ) / mean_metrics.loc[reference, f"rmse_h{horizon}"]
1666
+
1667
+ def block(candidate: str, reference: str, horizon: int) -> pd.Series:
1668
+ return comparison_table[
1669
+ (comparison_table.candidate == candidate)
1670
+ & (comparison_table.reference == reference)
1671
+ & (comparison_table.horizon == horizon)
1672
+ ].iloc[0]
1673
+
1674
+ scale_72 = gain("medium_explicit_band", "medium_single", 12)
1675
+ scale_7d = gain("medium_explicit_band", "medium_single", 28)
1676
+ scale_15d = gain("medium_explicit_band", "medium_single", 60)
1677
+ repair_72 = gain(
1678
+ "medium_explicit_band", "parent_explicit_band", 12
1679
+ )
1680
+ repair_7d = gain(
1681
+ "medium_explicit_band", "parent_explicit_band", 28
1682
+ )
1683
+ repair_15d = gain(
1684
+ "medium_explicit_band", "parent_explicit_band", 60
1685
+ )
1686
+ band_72 = gain(
1687
+ "medium_explicit_band", "medium_explicit_no_band", 12
1688
+ )
1689
+ band_7d = gain(
1690
+ "medium_explicit_band", "medium_explicit_no_band", 28
1691
+ )
1692
+ band_15d = gain(
1693
+ "medium_explicit_band", "medium_explicit_no_band", 60
1694
+ )
1695
+ persistence_7d = gain(
1696
+ "medium_explicit_band", "persistence", 28
1697
+ )
1698
+ persistence_15d = gain(
1699
+ "medium_explicit_band", "persistence", 60
1700
+ )
1701
+ variance_7d = float(
1702
+ mean_metrics.loc["medium_explicit_band", "variance_ratio_h28"]
1703
+ )
1704
+ variance_15d = float(
1705
+ mean_metrics.loc["medium_explicit_band", "variance_ratio_h60"]
1706
+ )
1707
+ direction_15d = float(
1708
+ mean_metrics.loc[
1709
+ "medium_explicit_band", "direction_norm_error_h60"
1710
+ ]
1711
+ )
1712
+ wave_invalid_15d = float(
1713
+ mean_metrics.loc[
1714
+ "medium_explicit_band", "wave_invalid_fraction_h60"
1715
+ ]
1716
+ )
1717
+ finite = bool(
1718
+ metric_table[
1719
+ metric_table.method == "medium_explicit_band"
1720
+ ]["finite"].all()
1721
+ )
1722
+
1723
+ def bin_gain(bin_name: str) -> float:
1724
+ selected = bin_table[
1725
+ (bin_table.horizon == 28)
1726
+ & (bin_table.ocean_bin == bin_name)
1727
+ ]["weighted_mse_gain_percent"]
1728
+ return float(selected.iloc[0]) if len(selected) else float("nan")
1729
+
1730
+ coastal_7d = bin_gain("coastal")
1731
+ shelf_7d = bin_gain("shelf")
1732
+ open_7d = bin_gain("open_ocean")
1733
+
1734
+ checks = {
1735
+ "architecture_unchanged": True,
1736
+ "four_season_native_data_available": len(native_roots) == 4,
1737
+ "winter_spring_training_summer_validation_autumn_test": True,
1738
+ "balanced_training_bins_present": all(
1739
+ split_audit["train"]["bin_counts"].get(name, 0) > 0
1740
+ for name in OCEAN_BINS
1741
+ ),
1742
+ "three_explicit_and_single_pairs": len(seeds) == 3,
1743
+ "all_explicit_rollouts_finite": finite,
1744
+ "multi_season_repair_improves_parent_72h": repair_72 > 0.0,
1745
+ "multi_season_repair_improves_parent_7d": repair_7d > 0.0,
1746
+ "multi_season_repair_improves_parent_15d": repair_15d > 0.0,
1747
+ "explicit_beats_single_72h_ge_2pct": scale_72 >= 2.0,
1748
+ "explicit_beats_single_7d_ge_1pct": scale_7d >= 1.0,
1749
+ "explicit_15d_nonworse_than_single": scale_15d >= 0.0,
1750
+ "scale_72h_block_bootstrap_positive": (
1751
+ float(block(
1752
+ "medium_explicit_band", "medium_single", 12
1753
+ ).weighted_ci_high) < 0.0
1754
+ ),
1755
+ "scale_7d_block_bootstrap_positive": (
1756
+ float(block(
1757
+ "medium_explicit_band", "medium_single", 28
1758
+ ).weighted_ci_high) < 0.0
1759
+ ),
1760
+ "scale_15d_not_significantly_worse": (
1761
+ float(block(
1762
+ "medium_explicit_band", "medium_single", 60
1763
+ ).weighted_ci_high) <= 0.02
1764
+ ),
1765
+ "band_closure_72h_positive": band_72 >= 0.2,
1766
+ "band_closure_7d_nonnegative": band_7d >= 0.0,
1767
+ "band_closure_15d_nonnegative": band_15d >= 0.0,
1768
+ "coastal_7d_not_worse_by_2pct_mse": bool(np.isfinite(coastal_7d) and coastal_7d >= -2.0),
1769
+ "shelf_7d_positive": bool(np.isfinite(shelf_7d) and shelf_7d > 0.0),
1770
+ "open_ocean_7d_positive": bool(np.isfinite(open_7d) and open_7d > 0.0),
1771
+ "variance_ratio_7d_ge_0_45": variance_7d >= 0.45,
1772
+ "variance_ratio_15d_ge_0_30": variance_15d >= 0.30,
1773
+ "direction_norm_error_15d_lt_0_35": direction_15d < 0.35,
1774
+ "wave_invalid_fraction_15d_lt_0_03": wave_invalid_15d < 0.03,
1775
+ "all_metrics_finite": bool(
1776
+ np.isfinite(
1777
+ metric_table.select_dtypes(
1778
+ include=[np.number]
1779
+ ).to_numpy()
1780
+ ).all()
1781
+ ),
1782
+ }
1783
+ passed = sum(bool(value) for value in checks.values())
1784
+ architecture_freeze = [
1785
+ "all_explicit_rollouts_finite",
1786
+ "multi_season_repair_improves_parent_7d",
1787
+ "multi_season_repair_improves_parent_15d",
1788
+ "explicit_beats_single_72h_ge_2pct",
1789
+ "explicit_beats_single_7d_ge_1pct",
1790
+ "explicit_15d_nonworse_than_single",
1791
+ "band_closure_72h_positive",
1792
+ "band_closure_7d_nonnegative",
1793
+ "band_closure_15d_nonnegative",
1794
+ "coastal_7d_not_worse_by_2pct_mse",
1795
+ ]
1796
+ architecture_qualified = all(checks[key] for key in architecture_freeze)
1797
+ product_signal = (
1798
+ persistence_7d > 0.0
1799
+ and float(block(
1800
+ "medium_explicit_band", "persistence", 28
1801
+ ).weighted_ci_high) < 0.0
1802
+ )
1803
+
1804
+ if architecture_qualified and passed >= 21:
1805
+ verdict_name = (
1806
+ "V3_S4_A0_ARCHITECTURE_AND_TRAINING_CONTRACT_QUALIFIED"
1807
+ )
1808
+ recommendation = (
1809
+ "Freeze CIDM-v3. Start the formal multi-year distributed "
1810
+ "training run. No architecture modules may be added."
1811
+ )
1812
+ elif architecture_qualified:
1813
+ verdict_name = (
1814
+ "V3_S4_A0_ARCHITECTURE_QUALIFIED_FORMAL_TRAINING_ALLOWED"
1815
+ )
1816
+ recommendation = (
1817
+ "Freeze CIDM-v3 and begin formal training. Treat persistence "
1818
+ "and physical gaps as training-scale targets, not architecture gates."
1819
+ )
1820
+ elif finite and passed >= 16:
1821
+ verdict_name = (
1822
+ "V3_S4_A0_MULTI_SEASON_TRAINING_PARTIALLY_QUALIFIED"
1823
+ )
1824
+ recommendation = (
1825
+ "Do not add modules. One data/loss calibration pass is allowed; "
1826
+ "otherwise select the mature Single-State baseline for V3."
1827
+ )
1828
+ else:
1829
+ verdict_name = (
1830
+ "V3_S4_A0_EXPLICIT_SCALE_VALUE_NOT_CONFIRMED_AT_MEDIUM_SCALE"
1831
+ )
1832
+ recommendation = (
1833
+ "Do not add modules. Prefer the mature Single-State backbone "
1834
+ "for V3 product training and retain explicit-scale research for V4."
1835
+ )
1836
+
1837
+ aggregate = {
1838
+ "scale_vs_single_72h_percent": scale_72,
1839
+ "scale_vs_single_7d_percent": scale_7d,
1840
+ "scale_vs_single_15d_percent": scale_15d,
1841
+ "repair_gain_72h_percent": repair_72,
1842
+ "repair_gain_7d_percent": repair_7d,
1843
+ "repair_gain_15d_percent": repair_15d,
1844
+ "band_gain_72h_percent": band_72,
1845
+ "band_gain_7d_percent": band_7d,
1846
+ "band_gain_15d_percent": band_15d,
1847
+ "vs_persistence_7d_percent": persistence_7d,
1848
+ "vs_persistence_15d_percent": persistence_15d,
1849
+ "coastal_7d_mse_gain_percent": coastal_7d,
1850
+ "shelf_7d_mse_gain_percent": shelf_7d,
1851
+ "open_ocean_7d_mse_gain_percent": open_7d,
1852
+ "variance_ratio_7d": variance_7d,
1853
+ "variance_ratio_15d": variance_15d,
1854
+ "direction_norm_error_15d": direction_15d,
1855
+ "wave_invalid_fraction_15d": wave_invalid_15d,
1856
+ "architecture_qualified": architecture_qualified,
1857
+ "product_signal_vs_persistence": product_signal,
1858
+ }
1859
+ verdict = {
1860
+ "automatic_verdict": verdict_name,
1861
+ "passed": passed,
1862
+ "total": len(checks),
1863
+ "checks": checks,
1864
+ "architecture_freeze_checks": architecture_freeze,
1865
+ "aggregate": aggregate,
1866
+ "final_candidate": {
1867
+ "modules": [
1868
+ "MultiScalePhysicalEncoder",
1869
+ "ExplicitScaleInformationState",
1870
+ "SharedScaleConditionedCIDMCore",
1871
+ "MultiStepRecurrence",
1872
+ "BandClosure",
1873
+ "MultiResolutionDecoder",
1874
+ ],
1875
+ "permanently_deferred_from_v3": [
1876
+ "all BER branches",
1877
+ "learned CrossScaleFlux",
1878
+ "SlowMemoryClosure",
1879
+ "VerticalOutputClosure",
1880
+ "CausalVarianceAmplifier",
1881
+ "EventRouter",
1882
+ ],
1883
+ },
1884
+ "next_stage_recommendation": recommendation,
1885
+ }
1886
+ atomic_json(
1887
+ aggregate,
1888
+ output_dir / "S4A0_main_aggregate.json",
1889
+ )
1890
+ atomic_json(
1891
+ verdict,
1892
+ output_dir / "S4A0_verdict.json",
1893
+ )
1894
+
1895
+ stage(9, 10, "图表、冻结合同和HF交接")
1896
+ plt.figure(figsize=(11, 6))
1897
+ for method in METHODS:
1898
+ current = summary[summary.method == method]
1899
+ plt.plot(
1900
+ current.horizon,
1901
+ current.rmse,
1902
+ marker="o",
1903
+ label=method,
1904
+ )
1905
+ plt.xlabel("Rollout steps (6 h each)")
1906
+ plt.ylabel("RMSE")
1907
+ plt.legend()
1908
+ plt.tight_layout()
1909
+ plt.savefig(
1910
+ output_dir / "figures" / "S4A0_RMSE_growth.png",
1911
+ dpi=180,
1912
+ )
1913
+ plt.close()
1914
+
1915
+ atomic_json(
1916
+ {
1917
+ "architecture_name": "CIDM-v3-SCS-Minimal-Final-Candidate",
1918
+ "architecture_changes_in_S4A0": False,
1919
+ "modules": [
1920
+ "MultiScalePhysicalEncoder",
1921
+ "ExplicitScaleInformationState",
1922
+ "SharedScaleConditionedCIDMCore",
1923
+ "MultiStepRecurrence",
1924
+ "BandClosure",
1925
+ "MultiResolutionDecoder",
1926
+ ],
1927
+ "training_contract": {
1928
+ "native_grid": "1/12 degree",
1929
+ "base_timestep_hours": 6,
1930
+ "history_steps": args.history,
1931
+ "maximum_rollout_steps": args.max_horizon,
1932
+ "optimizer_persistent": True,
1933
+ "multi_season_training": True,
1934
+ "balanced_ocean_fraction_sampling": True,
1935
+ "persistence_relative_skill": True,
1936
+ "increment_variance_spectral_wave_losses": True,
1937
+ "per_epoch_resume_checkpoint": True,
1938
+ },
1939
+ "formal_training_allowed": architecture_qualified,
1940
+ },
1941
+ output_dir
1942
+ / "deployment"
1943
+ / "CIDM_v3_final_candidate_architecture_and_training_contract.json",
1944
+ )
1945
+ atomic_json(
1946
+ {
1947
+ "repo_id": args.hf_repo_id,
1948
+ "native_cache_paths": {
1949
+ season: f"Cache/native_1_12/{season}/"
1950
+ for season in SEASONS
1951
+ },
1952
+ "result_path": (
1953
+ "Experiments/V3_S4_A0/"
1954
+ "CIDM_v3_SCS_V3_S4_A0.zip"
1955
+ ),
1956
+ },
1957
+ output_dir / "S4A0_HF_handoff.json",
1958
+ )
1959
+ safe_args = dict(vars(args))
1960
+ safe_args["hf_token"] = "<redacted>"
1961
+ atomic_json(
1962
+ {
1963
+ "experiment": "CIDM_v3_SCS_V3_S4_A0",
1964
+ "created_at": pd.Timestamp.now().isoformat(),
1965
+ "device": str(device),
1966
+ "arguments": safe_args,
1967
+ "security": "No plaintext access token is written.",
1968
+ },
1969
+ output_dir / "S4A0_manifest.json",
1970
+ )
1971
+
1972
+ stage(10, 10, "结果打包")
1973
+ package = output_dir.parent / f"{output_dir.name}.zip"
1974
+ package.unlink(missing_ok=True)
1975
+ with zipfile.ZipFile(package, "w", zipfile.ZIP_DEFLATED) as archive:
1976
+ for path in output_dir.rglob("*"):
1977
+ if path.is_file():
1978
+ archive.write(
1979
+ path,
1980
+ path.relative_to(output_dir.parent),
1981
+ )
1982
+ print(
1983
+ json.dumps(
1984
+ verdict,
1985
+ ensure_ascii=False,
1986
+ indent=2,
1987
+ default=json_default,
1988
+ ),
1989
+ flush=True,
1990
+ )
1991
+ print(f"[result] {package}", flush=True)
1992
+
1993
+ except Exception:
1994
+ trace = traceback.format_exc()
1995
+ (output_dir / "failure_traceback.txt").write_text(
1996
+ trace, encoding="utf-8"
1997
+ )
1998
+ print(trace, flush=True)
1999
+ raise
2000
+
2001
+
2002
+ if __name__ == "__main__":
2003
+ main()