wuff-mann commited on
Commit
deca934
·
verified ·
1 Parent(s): 874e978

Upload Experiments/V3_S3_A1/cidm_v3_scs_s3_a1_long_horizon_objective_repair.py with huggingface_hub

Browse files
Experiments/V3_S3_A1/cidm_v3_scs_s3_a1_long_horizon_objective_repair.py ADDED
@@ -0,0 +1,2112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ CIDM-v3 SCS V3-S3-A1
5
+ 长期目标修复、Persistence Skill与最终架构冻结资格实验
6
+ ========================================================
7
+
8
+ S3-A0的有效结论:
9
+ - 显式尺度 + Band Closure 在72 h和7 d的加权RMSE优于参数匹配Single-State;
10
+ - Band Closure在72 h、7 d、15 d均稳定正向;
11
+ - 15 d时显式尺度反而落后Single-State;
12
+ - 所有神经模型显著落后Persistence;
13
+ - 旧模型只训练到12步,却被外推到60步;
14
+ - 旧S1-R3每个Epoch重建AdamW,优化器动量被重置;
15
+ - 加权全域RMSE和等样本Bootstrap方向冲突,说明样本/海域权重需要严格审计。
16
+
17
+ 本轮遵守“只修训练,不加模块”:
18
+ 1. 架构完全不变;
19
+ 2. 未来BER继续删除;
20
+ 3. Cross-scale Flux、慢闭合、垂向闭合、因果方差放大继续关闭;
21
+ 4. 只训练Core、Decoder、Scale输出与Band Closure;
22
+ 5. AdamW在全部Epoch持续保存动量;
23
+ 6. 训练跨度课程扩展到60步;
24
+ 7. 加入Persistence-relative skill、增量、频谱、方差和波浪物理损失;
25
+ 8. 参数匹配Single-State执行同样训练目标;
26
+ 9. 秋季测试同时报告像素加权、等样本与时间块Bootstrap。
27
+
28
+ 没有新增神经分支、Router、Gate、Reservoir或新的闭合器。
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import copy
34
+ import hashlib
35
+ import json
36
+ import math
37
+ import os
38
+ import random
39
+ import shutil
40
+ import time
41
+ import traceback
42
+ import zipfile
43
+ from pathlib import Path
44
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
45
+
46
+ import numpy as np
47
+ import pandas as pd
48
+ import torch
49
+ import torch.nn as nn
50
+ import torch.nn.functional as F
51
+ from torch.utils.data import DataLoader, Dataset
52
+
53
+ import matplotlib
54
+ matplotlib.use("Agg")
55
+ import matplotlib.pyplot as plt
56
+
57
+ import scs_c0_data_runtime as data_runtime
58
+ import v3s1_r1_base as r1base
59
+ import cidm_v3_scs_s1_r3_slowfast_causal_closure as s1r3
60
+ import cidm_v3_scs_s2_a1_r2_conditional_external_innovation_capacity as s2r2
61
+ import cidm_v3_scs_s3_a0_long_rollout_freeze as s3a0
62
+
63
+
64
+ VARIABLE_NAMES = list(data_runtime.VARIABLE_NAMES)
65
+ S1_SEEDS = [20260902, 20260903, 20260904]
66
+ HORIZONS = [1, 4, 12, 28, 60]
67
+ HORIZON_LABELS = {1: "6h", 4: "24h", 12: "72h", 28: "7d", 60: "15d"}
68
+ GROUPS = dict(s2r2.GROUPS)
69
+ NONNEGATIVE_WAVE_INDICES = [9, 10, 11, 14, 15]
70
+ DIRECTION_INDICES = [12, 13]
71
+ METHODS = [
72
+ "persistence",
73
+ "parent_single",
74
+ "parent_explicit_band",
75
+ "repaired_single",
76
+ "repaired_explicit_no_band",
77
+ "repaired_explicit_band",
78
+ ]
79
+
80
+
81
+ def json_default(value: Any) -> Any:
82
+ return data_runtime.json_default(value)
83
+
84
+
85
+ def atomic_json(payload: Any, path: Path) -> None:
86
+ path.parent.mkdir(parents=True, exist_ok=True)
87
+ temp = path.with_suffix(path.suffix + ".tmp")
88
+ temp.write_text(
89
+ json.dumps(payload, ensure_ascii=False, indent=2, default=json_default),
90
+ encoding="utf-8",
91
+ )
92
+ os.replace(temp, path)
93
+
94
+
95
+ def stage(index: int, total: int, title: str) -> None:
96
+ print(f"\n[V3-S3-A1] 阶段 {index}/{total}:{title}", flush=True)
97
+
98
+
99
+ def sha256_file(path: Path) -> str:
100
+ digest = hashlib.sha256()
101
+ with path.open("rb") as handle:
102
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
103
+ digest.update(block)
104
+ return digest.hexdigest()
105
+
106
+
107
+ def seed_everything(seed: int) -> None:
108
+ random.seed(seed)
109
+ np.random.seed(seed)
110
+ torch.manual_seed(seed)
111
+ if torch.cuda.is_available():
112
+ torch.cuda.manual_seed_all(seed)
113
+
114
+
115
+ def hf_download_file(
116
+ repo_id: str,
117
+ repo_path: str,
118
+ local_path: Path,
119
+ token: Optional[str],
120
+ ) -> bool:
121
+ try:
122
+ from huggingface_hub import hf_hub_download
123
+ downloaded = Path(
124
+ hf_hub_download(
125
+ repo_id=repo_id,
126
+ filename=repo_path,
127
+ repo_type="dataset",
128
+ token=token,
129
+ )
130
+ )
131
+ except Exception as exc:
132
+ print(f"[HF miss] {repo_path}: {exc}", flush=True)
133
+ return False
134
+ local_path.parent.mkdir(parents=True, exist_ok=True)
135
+ if local_path.exists() or local_path.is_symlink():
136
+ local_path.unlink()
137
+ try:
138
+ local_path.symlink_to(downloaded)
139
+ except Exception:
140
+ shutil.copy2(downloaded, local_path)
141
+ print(f"[HF restored] {repo_path}", flush=True)
142
+ return True
143
+
144
+
145
+ def ensure_assets(args: argparse.Namespace) -> Dict[str, Any]:
146
+ token = args.hf_token or os.environ.get("HF_TOKEN") or None
147
+ parent_zip = Path(args.parent_zip)
148
+ if not parent_zip.is_file():
149
+ candidates = [
150
+ "Experiments/V3_S3_A0/CIDM_v3_SCS_V3_S3_A0.zip",
151
+ "CIDM_v3_SCS_V3_S3_A0.zip",
152
+ ]
153
+ for candidate in candidates:
154
+ if hf_download_file(args.hf_repo_id, candidate, parent_zip, token):
155
+ break
156
+ if not parent_zip.is_file():
157
+ raise FileNotFoundError("CIDM_v3_SCS_V3_S3_A0.zip is required.")
158
+
159
+ restored = []
160
+ for season in ["summer", "autumn"]:
161
+ root = Path(args.native_cache_dir) / season / "prepared"
162
+ root.mkdir(parents=True, exist_ok=True)
163
+ for filename in [
164
+ "scs_c0_data.npy",
165
+ "scs_c0_mask.npy",
166
+ "scs_c0_variable_masks.npy",
167
+ "scs_c0_metadata.json",
168
+ "C0_data_audit.csv",
169
+ ]:
170
+ local_path = root / filename
171
+ if local_path.is_file() and local_path.stat().st_size > 128:
172
+ continue
173
+ repo_path = f"Cache/native_1_12/{season}/{filename}"
174
+ if not hf_download_file(args.hf_repo_id, repo_path, local_path, token):
175
+ raise FileNotFoundError(repo_path)
176
+ restored.append(repo_path)
177
+ metadata = json.loads(
178
+ (root / "scs_c0_metadata.json").read_text(encoding="utf-8")
179
+ )
180
+ if abs(float(metadata["native_resolution_degrees"]) - 1 / 12) > 1e-6:
181
+ raise RuntimeError(f"{season} cache is not native 1/12 degree.")
182
+
183
+ return {
184
+ "parent_zip_sha256": sha256_file(parent_zip),
185
+ "restored": restored,
186
+ }
187
+
188
+
189
+ def extract_parent_assets(
190
+ parent_zip: Path,
191
+ destination: Path,
192
+ ) -> Dict[str, Any]:
193
+ destination.mkdir(parents=True, exist_ok=True)
194
+ with zipfile.ZipFile(parent_zip) as archive:
195
+ archive.extractall(destination)
196
+
197
+ s1_verdicts = list(destination.rglob("V3S1R3_verdict.json"))
198
+ if len(s1_verdicts) != 1:
199
+ raise RuntimeError(
200
+ f"Expected one nested S1-R3 verdict, found {len(s1_verdicts)}"
201
+ )
202
+ s1_root = s1_verdicts[0].parent
203
+ metadata_path = s1_root / "scs_c0_metadata.json"
204
+ if not metadata_path.is_file():
205
+ raise FileNotFoundError(metadata_path)
206
+
207
+ explicit_checkpoints: Dict[int, Path] = {}
208
+ for path in (
209
+ s1_root / "checkpoints" / "slowfast_causal"
210
+ ).glob("seed_*.pt"):
211
+ payload = torch.load(path, map_location="cpu", weights_only=False)
212
+ explicit_checkpoints[int(payload["seed"])] = path
213
+
214
+ single_checkpoints: Dict[int, Path] = {}
215
+ for path in s1_root.rglob("checkpoints/single/seed_*.pt"):
216
+ payload = torch.load(path, map_location="cpu", weights_only=False)
217
+ seed = int(payload["seed"])
218
+ if seed not in single_checkpoints:
219
+ single_checkpoints[seed] = path
220
+
221
+ missing_explicit = [seed for seed in S1_SEEDS if seed not in explicit_checkpoints]
222
+ missing_single = [seed for seed in S1_SEEDS if seed not in single_checkpoints]
223
+ if missing_explicit or missing_single:
224
+ raise RuntimeError(
225
+ f"Missing checkpoints explicit={missing_explicit}, single={missing_single}"
226
+ )
227
+
228
+ s3_verdicts = list(destination.rglob("S3A0_verdict.json"))
229
+ s3_verdict = (
230
+ json.loads(s3_verdicts[0].read_text(encoding="utf-8"))
231
+ if s3_verdicts else {}
232
+ )
233
+ return {
234
+ "s1_root": s1_root,
235
+ "metadata": json.loads(metadata_path.read_text(encoding="utf-8")),
236
+ "s1_verdict": json.loads(s1_verdicts[0].read_text(encoding="utf-8")),
237
+ "s3_verdict": s3_verdict,
238
+ "explicit_checkpoints": explicit_checkpoints,
239
+ "single_checkpoints": single_checkpoints,
240
+ }
241
+
242
+
243
+ class LongHorizonDataset(Dataset):
244
+ def __init__(
245
+ self,
246
+ native_root: Path,
247
+ reference_mean: np.ndarray,
248
+ reference_std: np.ndarray,
249
+ samples: int,
250
+ seed: int,
251
+ history: int,
252
+ patch_size: int,
253
+ maximum_horizon: int,
254
+ split_tag: str,
255
+ forbidden_keys: Optional[set] = None,
256
+ ):
257
+ self.data = np.load(native_root / "scs_c0_data.npy", mmap_mode="r")
258
+ self.variable_masks = np.load(
259
+ native_root / "scs_c0_variable_masks.npy", mmap_mode="r"
260
+ )
261
+ self.metadata = json.loads(
262
+ (native_root / "scs_c0_metadata.json").read_text(encoding="utf-8")
263
+ )
264
+ self.window_mean = np.asarray(self.metadata["means"], dtype=np.float32)
265
+ self.window_std = np.asarray(self.metadata["stds"], dtype=np.float32)
266
+ self.reference_mean = np.asarray(reference_mean, dtype=np.float32)
267
+ self.reference_std = np.asarray(reference_std, dtype=np.float32)
268
+ self.history = history
269
+ self.patch_size = patch_size
270
+ self.maximum_horizon = maximum_horizon
271
+ self.split_tag = split_tag
272
+
273
+ valid_times = np.arange(
274
+ history - 1,
275
+ self.data.shape[0] - maximum_horizon,
276
+ dtype=np.int64,
277
+ )
278
+ if len(valid_times) < 8:
279
+ raise RuntimeError(f"Only {len(valid_times)} valid starts for {split_tag}")
280
+
281
+ generator = np.random.default_rng(seed)
282
+ height, width = self.data.shape[-2:]
283
+ max_y = height - patch_size
284
+ max_x = width - patch_size
285
+ records = []
286
+ used = set()
287
+ forbidden = set() if forbidden_keys is None else set(forbidden_keys)
288
+ attempts = 0
289
+ while len(records) < samples and attempts < samples * 100:
290
+ attempts += 1
291
+ time_index = int(generator.choice(valid_times))
292
+ y = int(generator.integers(0, max_y + 1))
293
+ x = int(generator.integers(0, max_x + 1))
294
+ # Tile key limits exact/near-identical duplicates and supports split audit.
295
+ key = (
296
+ time_index,
297
+ int(y // max(patch_size // 2, 1)),
298
+ int(x // max(patch_size // 2, 1)),
299
+ )
300
+ if key in used or key in forbidden:
301
+ continue
302
+ used.add(key)
303
+ records.append((time_index, y, x))
304
+ if len(records) < samples:
305
+ raise RuntimeError(
306
+ f"Could build only {len(records)}/{samples} unique records"
307
+ )
308
+ self.records = records
309
+ self.record_keys = used
310
+
311
+ def __len__(self) -> int:
312
+ return len(self.records)
313
+
314
+ def _to_reference(self, value: np.ndarray) -> np.ndarray:
315
+ physical = (
316
+ value
317
+ * self.window_std[None, :, None, None]
318
+ + self.window_mean[None, :, None, None]
319
+ )
320
+ return (
321
+ physical - self.reference_mean[None, :, None, None]
322
+ ) / self.reference_std[None, :, None, None]
323
+
324
+ def __getitem__(self, item: int) -> Dict[str, torch.Tensor]:
325
+ time_index, y, x = self.records[item]
326
+ p = self.patch_size
327
+ history_window = np.asarray(
328
+ self.data[
329
+ time_index - self.history + 1:time_index + 1,
330
+ :,
331
+ y:y + p,
332
+ x:x + p,
333
+ ],
334
+ dtype=np.float32,
335
+ ).copy()
336
+ future_window = np.asarray(
337
+ self.data[
338
+ time_index + 1:time_index + self.maximum_horizon + 1,
339
+ :,
340
+ y:y + p,
341
+ x:x + p,
342
+ ],
343
+ dtype=np.float32,
344
+ ).copy()
345
+ mask = np.asarray(
346
+ self.variable_masks[:, y:y + p, x:x + p],
347
+ dtype=np.float32,
348
+ ).copy()
349
+ history = self._to_reference(history_window).astype(np.float32)
350
+ future = self._to_reference(future_window).astype(np.float32)
351
+ valid_count = float(mask.sum())
352
+ return {
353
+ "history": torch.from_numpy(history),
354
+ "future": torch.from_numpy(future),
355
+ "mask": torch.from_numpy(mask),
356
+ "sample_index": torch.tensor(item, dtype=torch.long),
357
+ "time_index": torch.tensor(time_index, dtype=torch.long),
358
+ "origin_y": torch.tensor(y, dtype=torch.long),
359
+ "origin_x": torch.tensor(x, dtype=torch.long),
360
+ "valid_count": torch.tensor(valid_count, dtype=torch.float32),
361
+ }
362
+
363
+
364
+ def make_loaders(
365
+ native_cache_dir: Path,
366
+ reference_mean: np.ndarray,
367
+ reference_std: np.ndarray,
368
+ args: argparse.Namespace,
369
+ ) -> Tuple[Dict[str, DataLoader], Dict[str, LongHorizonDataset]]:
370
+ roots = {
371
+ "train": native_cache_dir / "summer" / "prepared",
372
+ "validation": native_cache_dir / "summer" / "prepared",
373
+ "test": native_cache_dir / "autumn" / "prepared",
374
+ }
375
+ train_dataset = LongHorizonDataset(
376
+ roots["train"], reference_mean, reference_std,
377
+ args.train_samples, args.train_seed, args.history,
378
+ args.patch_size, args.max_horizon, "summer_train",
379
+ )
380
+ validation_dataset = LongHorizonDataset(
381
+ roots["validation"], reference_mean, reference_std,
382
+ args.validation_samples, args.validation_seed, args.history,
383
+ args.patch_size, args.max_horizon, "summer_validation",
384
+ forbidden_keys=train_dataset.record_keys,
385
+ )
386
+ test_dataset = LongHorizonDataset(
387
+ roots["test"], reference_mean, reference_std,
388
+ args.test_samples, args.test_seed, args.history,
389
+ args.patch_size, args.max_horizon, "autumn_test",
390
+ )
391
+ datasets = {
392
+ "train": train_dataset,
393
+ "validation": validation_dataset,
394
+ "test": test_dataset,
395
+ }
396
+ loaders = {
397
+ "train": DataLoader(
398
+ datasets["train"],
399
+ batch_size=args.batch_size,
400
+ shuffle=True,
401
+ num_workers=args.num_workers,
402
+ pin_memory=torch.cuda.is_available(),
403
+ ),
404
+ "validation": DataLoader(
405
+ datasets["validation"],
406
+ batch_size=args.batch_size,
407
+ shuffle=False,
408
+ num_workers=args.num_workers,
409
+ pin_memory=torch.cuda.is_available(),
410
+ ),
411
+ "test": DataLoader(
412
+ datasets["test"],
413
+ batch_size=args.batch_size,
414
+ shuffle=False,
415
+ num_workers=args.num_workers,
416
+ pin_memory=torch.cuda.is_available(),
417
+ ),
418
+ }
419
+ return loaders, datasets
420
+
421
+
422
+ def make_explicit(checkpoint: Path, device: torch.device):
423
+ return s3a0.make_explicit(checkpoint, device)
424
+
425
+
426
+ def make_single(checkpoint: Path, device: torch.device):
427
+ return s3a0.make_single(checkpoint, device)
428
+
429
+
430
+ def set_explicit_trainable(model: nn.Module) -> List[nn.Parameter]:
431
+ for parameter in model.parameters():
432
+ parameter.requires_grad = False
433
+ train_modules = [
434
+ model.core,
435
+ model.decoder,
436
+ model.dec_film,
437
+ model.scale_out,
438
+ model.band_energy_closure,
439
+ ]
440
+ parameters = []
441
+ for module in train_modules:
442
+ for parameter in module.parameters():
443
+ parameter.requires_grad = True
444
+ parameters.append(parameter)
445
+ # Explicitly keep all deferred/removed components frozen.
446
+ for module in [
447
+ model.encoder,
448
+ model.enc_film,
449
+ model.frame,
450
+ model.flux,
451
+ model.rt_closure,
452
+ model.slow_memory,
453
+ model.vertical_closure,
454
+ model.causal_variance,
455
+ ]:
456
+ for parameter in module.parameters():
457
+ parameter.requires_grad = False
458
+ return parameters
459
+
460
+
461
+ def set_single_trainable(model: nn.Module) -> List[nn.Parameter]:
462
+ parameters = []
463
+ for parameter in model.parameters():
464
+ parameter.requires_grad = True
465
+ parameters.append(parameter)
466
+ return parameters
467
+
468
+
469
+ @torch.no_grad()
470
+ def rollout_explicit(
471
+ model: nn.Module,
472
+ history: torch.Tensor,
473
+ mask: torch.Tensor,
474
+ steps: int,
475
+ band_closure: bool,
476
+ ) -> List[torch.Tensor]:
477
+ outputs, _ = model.rollout_latent(
478
+ history,
479
+ mask,
480
+ steps,
481
+ flux_mode="none",
482
+ projection=True,
483
+ radial_delta=False,
484
+ band_closure=band_closure,
485
+ slow_memory=False,
486
+ vertical_closure=False,
487
+ causal_variance=False,
488
+ counterfactual=False,
489
+ )
490
+ return [output["pred"] for output in outputs]
491
+
492
+
493
+ @torch.no_grad()
494
+ def rollout_single(
495
+ model: nn.Module,
496
+ history: torch.Tensor,
497
+ mask: torch.Tensor,
498
+ steps: int,
499
+ ) -> List[torch.Tensor]:
500
+ outputs, _ = model.rollout_latent(history, mask, steps)
501
+ return [output["pred"] for output in outputs]
502
+
503
+
504
+ def rollout_explicit_train(
505
+ model: nn.Module,
506
+ history: torch.Tensor,
507
+ mask: torch.Tensor,
508
+ steps: int,
509
+ ) -> List[torch.Tensor]:
510
+ outputs, _ = model.rollout_latent(
511
+ history,
512
+ mask,
513
+ steps,
514
+ flux_mode="none",
515
+ projection=True,
516
+ radial_delta=False,
517
+ band_closure=True,
518
+ slow_memory=False,
519
+ vertical_closure=False,
520
+ causal_variance=False,
521
+ counterfactual=False,
522
+ )
523
+ return [output["pred"] for output in outputs]
524
+
525
+
526
+ def rollout_single_train(
527
+ model: nn.Module,
528
+ history: torch.Tensor,
529
+ mask: torch.Tensor,
530
+ steps: int,
531
+ ) -> List[torch.Tensor]:
532
+ outputs, _ = model.rollout_latent(history, mask, steps)
533
+ return [output["pred"] for output in outputs]
534
+
535
+
536
+ def masked_sample_mse(
537
+ prediction: torch.Tensor,
538
+ target: torch.Tensor,
539
+ mask: torch.Tensor,
540
+ ) -> torch.Tensor:
541
+ denominator = mask.flatten(1).sum(dim=1).clamp_min(1.0)
542
+ return (
543
+ ((prediction - target).square() * mask)
544
+ .flatten(1).sum(dim=1)
545
+ / denominator
546
+ )
547
+
548
+
549
+ def masked_gradient_loss(
550
+ prediction: torch.Tensor,
551
+ target: torch.Tensor,
552
+ mask: torch.Tensor,
553
+ ) -> torch.Tensor:
554
+ px = prediction[..., :, 1:] - prediction[..., :, :-1]
555
+ tx = target[..., :, 1:] - target[..., :, :-1]
556
+ py = prediction[..., 1:, :] - prediction[..., :-1, :]
557
+ ty = target[..., 1:, :] - target[..., :-1, :]
558
+ mx = mask[..., :, 1:] * mask[..., :, :-1]
559
+ my = mask[..., 1:, :] * mask[..., :-1, :]
560
+ numerator = (
561
+ ((px - tx).square() * mx).sum()
562
+ + ((py - ty).square() * my).sum()
563
+ )
564
+ denominator = (mx.sum() + my.sum()).clamp_min(1.0)
565
+ return numerator / denominator
566
+
567
+
568
+ def channel_variance_log_loss(
569
+ prediction: torch.Tensor,
570
+ target: torch.Tensor,
571
+ mask: torch.Tensor,
572
+ ) -> torch.Tensor:
573
+ denominator = mask.sum(dim=(-2, -1), keepdim=True).clamp_min(1.0)
574
+ pred_mean = (prediction * mask).sum(dim=(-2, -1), keepdim=True) / denominator
575
+ target_mean = (target * mask).sum(dim=(-2, -1), keepdim=True) / denominator
576
+ pred_var = (
577
+ (prediction - pred_mean).square() * mask
578
+ ).sum(dim=(-2, -1)) / denominator.squeeze(-1).squeeze(-1)
579
+ target_var = (
580
+ (target - target_mean).square() * mask
581
+ ).sum(dim=(-2, -1)) / denominator.squeeze(-1).squeeze(-1)
582
+ return (
583
+ torch.log(pred_var + 1e-6) - torch.log(target_var + 1e-6)
584
+ ).square().mean()
585
+
586
+
587
+ def spectral_log_loss(
588
+ prediction: torch.Tensor,
589
+ target: torch.Tensor,
590
+ mask: torch.Tensor,
591
+ ) -> torch.Tensor:
592
+ pred_energy = s3a0.spectral_energy_ratios(prediction, mask)
593
+ target_energy = s3a0.spectral_energy_ratios(target, mask)
594
+ return (
595
+ torch.log(pred_energy + 1e-7)
596
+ - torch.log(target_energy + 1e-7)
597
+ ).abs().mean()
598
+
599
+
600
+ def physical_domain_loss(
601
+ prediction: torch.Tensor,
602
+ mask: torch.Tensor,
603
+ means: torch.Tensor,
604
+ stds: torch.Tensor,
605
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
606
+ physical = (
607
+ prediction
608
+ * stds[None, :, None, None]
609
+ + means[None, :, None, None]
610
+ )
611
+ wave_mask = mask[:, NONNEGATIVE_WAVE_INDICES]
612
+ wave = physical[:, NONNEGATIVE_WAVE_INDICES]
613
+ negative = (
614
+ F.relu(-wave).square() * wave_mask
615
+ ).sum() / wave_mask.sum().clamp_min(1.0)
616
+
617
+ sin_value = physical[:, DIRECTION_INDICES[0]]
618
+ cos_value = physical[:, DIRECTION_INDICES[1]]
619
+ direction_mask = (
620
+ mask[:, DIRECTION_INDICES[0]]
621
+ * mask[:, DIRECTION_INDICES[1]]
622
+ )
623
+ unit = torch.sqrt(
624
+ sin_value.square() + cos_value.square() + 1e-8
625
+ )
626
+ circle = (
627
+ (unit - 1.0).square() * direction_mask
628
+ ).sum() / direction_mask.sum().clamp_min(1.0)
629
+ return negative, circle
630
+
631
+
632
+ def selected_steps(horizon: int) -> List[int]:
633
+ candidates = [1, 4, 12, 28, horizon]
634
+ return sorted(set(step for step in candidates if step <= horizon))
635
+
636
+
637
+ def sequence_objective(
638
+ outputs: Sequence[torch.Tensor],
639
+ history: torch.Tensor,
640
+ future: torch.Tensor,
641
+ mask: torch.Tensor,
642
+ means: torch.Tensor,
643
+ stds: torch.Tensor,
644
+ args: argparse.Namespace,
645
+ ) -> Dict[str, torch.Tensor]:
646
+ horizon = len(outputs)
647
+ steps = selected_steps(horizon)
648
+ raw_weights = torch.tensor(
649
+ [0.12, 0.18, 0.24, 0.24, 0.32][:len(steps)],
650
+ device=history.device,
651
+ dtype=history.dtype,
652
+ )
653
+ weights = raw_weights / raw_weights.sum()
654
+
655
+ totals = {
656
+ "value": torch.zeros((), device=history.device),
657
+ "gradient": torch.zeros((), device=history.device),
658
+ "increment": torch.zeros((), device=history.device),
659
+ "skill": torch.zeros((), device=history.device),
660
+ "variance": torch.zeros((), device=history.device),
661
+ "spectral": torch.zeros((), device=history.device),
662
+ "wave_negative": torch.zeros((), device=history.device),
663
+ "direction_circle": torch.zeros((), device=history.device),
664
+ }
665
+ persistence = history[:, -1]
666
+ previous_prediction = persistence
667
+ previous_target = persistence
668
+ previous_step = 0
669
+
670
+ for weight, step in zip(weights, steps):
671
+ prediction = outputs[step - 1]
672
+ target = future[:, step - 1]
673
+ sample_mse = masked_sample_mse(prediction, target, mask)
674
+ persistence_mse = masked_sample_mse(persistence, target, mask)
675
+ totals["value"] += weight * sample_mse.mean()
676
+ totals["gradient"] += weight * masked_gradient_loss(
677
+ prediction, target, mask
678
+ )
679
+ # Multi-step displacement objective over the selected interval.
680
+ predicted_increment = prediction - previous_prediction
681
+ target_increment = target - previous_target
682
+ totals["increment"] += weight * masked_sample_mse(
683
+ predicted_increment, target_increment, mask
684
+ ).mean()
685
+ previous_prediction = prediction
686
+ previous_target = target
687
+ previous_step = step
688
+
689
+ normalized_skill_gap = (
690
+ sample_mse - args.persistence_target_ratio * persistence_mse
691
+ ) / (persistence_mse.detach() + 0.05)
692
+ totals["skill"] += weight * F.relu(normalized_skill_gap).mean()
693
+ totals["variance"] += weight * channel_variance_log_loss(
694
+ prediction, target, mask
695
+ )
696
+ if step >= 12:
697
+ totals["spectral"] += weight * spectral_log_loss(
698
+ prediction, target, mask
699
+ )
700
+ negative, circle = physical_domain_loss(
701
+ prediction, mask, means, stds
702
+ )
703
+ totals["wave_negative"] += weight * negative
704
+ totals["direction_circle"] += weight * circle
705
+
706
+ total = (
707
+ totals["value"]
708
+ + args.gradient_weight * totals["gradient"]
709
+ + args.increment_weight * totals["increment"]
710
+ + args.persistence_skill_weight * totals["skill"]
711
+ + args.variance_weight * totals["variance"]
712
+ + args.spectral_weight * totals["spectral"]
713
+ + args.wave_nonnegative_weight * totals["wave_negative"]
714
+ + args.direction_circle_weight * totals["direction_circle"]
715
+ )
716
+ return {"total": total, **totals}
717
+
718
+
719
+ def horizon_schedule(args: argparse.Namespace) -> List[int]:
720
+ default = [12, 20, 28, 40, 60, 60]
721
+ if args.epochs <= len(default):
722
+ schedule = default[:args.epochs]
723
+ else:
724
+ schedule = default + [60] * (args.epochs - len(default))
725
+ return [min(args.max_horizon, value) for value in schedule]
726
+
727
+
728
+ @torch.no_grad()
729
+ def validation_score(
730
+ model: nn.Module,
731
+ kind: str,
732
+ loader: DataLoader,
733
+ device: torch.device,
734
+ means: torch.Tensor,
735
+ stds: torch.Tensor,
736
+ ) -> Dict[str, float]:
737
+ model.eval()
738
+ rmse_acc = {step: [] for step in HORIZONS}
739
+ variance_acc = {step: [] for step in [28, 60]}
740
+ skill_acc = {step: [] for step in [12, 28, 60]}
741
+ direction_acc = []
742
+ for batch in loader:
743
+ history = batch["history"].to(device)
744
+ future = batch["future"].to(device)
745
+ mask = batch["mask"].to(device)
746
+ if kind == "explicit":
747
+ outputs = rollout_explicit(model, history, mask, 60, True)
748
+ else:
749
+ outputs = rollout_single(model, history, mask, 60)
750
+ persistence = history[:, -1]
751
+ for step in HORIZONS:
752
+ prediction = outputs[step - 1]
753
+ target = future[:, step - 1]
754
+ rmse_acc[step].extend(
755
+ torch.sqrt(
756
+ masked_sample_mse(prediction, target, mask) + 1e-12
757
+ ).cpu().tolist()
758
+ )
759
+ if step in variance_acc:
760
+ variance_acc[step].append(
761
+ float(channel_variance_log_loss(
762
+ prediction, target, mask
763
+ ))
764
+ )
765
+ if step in skill_acc:
766
+ model_mse = masked_sample_mse(prediction, target, mask)
767
+ persist_mse = masked_sample_mse(persistence, target, mask)
768
+ skill_acc[step].extend(
769
+ (
770
+ (model_mse - persist_mse)
771
+ / (persist_mse + 0.05)
772
+ ).cpu().tolist()
773
+ )
774
+ _, circle = physical_domain_loss(
775
+ outputs[59], mask, means, stds
776
+ )
777
+ direction_acc.append(float(circle))
778
+
779
+ result = {
780
+ f"rmse_h{step}": float(np.mean(values))
781
+ for step, values in rmse_acc.items()
782
+ }
783
+ result["variance_log_7d"] = float(np.mean(variance_acc[28]))
784
+ result["variance_log_15d"] = float(np.mean(variance_acc[60]))
785
+ result["skill_gap_72h"] = float(np.mean(skill_acc[12]))
786
+ result["skill_gap_7d"] = float(np.mean(skill_acc[28]))
787
+ result["skill_gap_15d"] = float(np.mean(skill_acc[60]))
788
+ result["direction_circle_15d"] = float(np.mean(direction_acc))
789
+ result["score"] = (
790
+ 0.10 * result["rmse_h4"]
791
+ + 0.20 * result["rmse_h12"]
792
+ + 0.30 * result["rmse_h28"]
793
+ + 0.40 * result["rmse_h60"]
794
+ + 0.08 * max(result["skill_gap_72h"], 0.0)
795
+ + 0.10 * max(result["skill_gap_7d"], 0.0)
796
+ + 0.12 * max(result["skill_gap_15d"], 0.0)
797
+ + 0.02 * result["variance_log_7d"]
798
+ + 0.03 * result["variance_log_15d"]
799
+ + 0.02 * result["direction_circle_15d"]
800
+ )
801
+ return result
802
+
803
+
804
+ def train_model(
805
+ model: nn.Module,
806
+ kind: str,
807
+ seed: int,
808
+ loader: DataLoader,
809
+ validation_loader: DataLoader,
810
+ device: torch.device,
811
+ means: torch.Tensor,
812
+ stds: torch.Tensor,
813
+ args: argparse.Namespace,
814
+ output_dir: Path,
815
+ ) -> Tuple[nn.Module, Dict[str, Any]]:
816
+ seed_everything(seed)
817
+ if kind == "explicit":
818
+ parameters = set_explicit_trainable(model)
819
+ learning_rate = args.explicit_learning_rate
820
+ else:
821
+ parameters = set_single_trainable(model)
822
+ learning_rate = args.single_learning_rate
823
+
824
+ optimizer = torch.optim.AdamW(
825
+ parameters,
826
+ lr=learning_rate,
827
+ weight_decay=args.weight_decay,
828
+ )
829
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
830
+ optimizer, T_max=max(args.epochs, 1), eta_min=learning_rate * 0.2
831
+ )
832
+ schedule = horizon_schedule(args)
833
+ best_score = float("inf")
834
+ best_epoch = -1
835
+ best_state = None
836
+ logs = []
837
+
838
+ for epoch, horizon in enumerate(schedule, start=1):
839
+ model.train()
840
+ optimizer.zero_grad(set_to_none=True)
841
+ running = {}
842
+ for batch_index, batch in enumerate(loader, start=1):
843
+ history = batch["history"].to(device, non_blocking=True)
844
+ future = batch["future"].to(device, non_blocking=True)
845
+ mask = batch["mask"].to(device, non_blocking=True)
846
+ if kind == "explicit":
847
+ outputs = rollout_explicit_train(
848
+ model, history, mask, horizon
849
+ )
850
+ else:
851
+ outputs = rollout_single_train(
852
+ model, history, mask, horizon
853
+ )
854
+ parts = sequence_objective(
855
+ outputs,
856
+ history,
857
+ future[:, :horizon],
858
+ mask,
859
+ means,
860
+ stds,
861
+ args,
862
+ )
863
+ if not torch.isfinite(parts["total"]):
864
+ raise RuntimeError(
865
+ f"Non-finite {kind} loss seed={seed} "
866
+ f"epoch={epoch} batch={batch_index}"
867
+ )
868
+ (parts["total"] / args.accumulation).backward()
869
+ if (
870
+ batch_index % args.accumulation == 0
871
+ or batch_index == len(loader)
872
+ ):
873
+ torch.nn.utils.clip_grad_norm_(
874
+ parameters, args.grad_clip
875
+ )
876
+ optimizer.step()
877
+ optimizer.zero_grad(set_to_none=True)
878
+ for key, value in parts.items():
879
+ running[key] = running.get(key, 0.0) + float(
880
+ value.detach()
881
+ )
882
+ if batch_index % max(len(loader) // 5, 1) == 0:
883
+ print(
884
+ f"[{kind} seed={seed}] epoch={epoch}/{args.epochs} "
885
+ f"H={horizon} batch={batch_index}/{len(loader)} "
886
+ f"loss={running['total']/batch_index:.6f}",
887
+ flush=True,
888
+ )
889
+
890
+ scheduler.step()
891
+ validation = validation_score(
892
+ model, kind, validation_loader, device, means, stds
893
+ )
894
+ row = {
895
+ "kind": kind,
896
+ "seed": seed,
897
+ "epoch": epoch,
898
+ "train_horizon": horizon,
899
+ "learning_rate": optimizer.param_groups[0]["lr"],
900
+ **{
901
+ f"train_{key}": value / max(len(loader), 1)
902
+ for key, value in running.items()
903
+ },
904
+ **{
905
+ f"validation_{key}": value
906
+ for key, value in validation.items()
907
+ },
908
+ }
909
+ logs.append(row)
910
+ print(
911
+ f"[VAL {kind} seed={seed}] epoch={epoch} H={horizon} "
912
+ f"score={validation['score']:.6f} "
913
+ f"rmse72={validation['rmse_h12']:.5f} "
914
+ f"rmse7d={validation['rmse_h28']:.5f} "
915
+ f"rmse15d={validation['rmse_h60']:.5f}",
916
+ flush=True,
917
+ )
918
+ if validation["score"] < best_score:
919
+ best_score = validation["score"]
920
+ best_epoch = epoch
921
+ best_state = {
922
+ key: value.detach().cpu().clone()
923
+ for key, value in model.state_dict().items()
924
+ }
925
+
926
+ if best_state is None:
927
+ raise RuntimeError(f"No best state for {kind} seed={seed}")
928
+ model.load_state_dict(best_state, strict=True)
929
+ checkpoint_dir = output_dir / "checkpoints" / kind
930
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
931
+ checkpoint = checkpoint_dir / f"seed_{seed}.pt"
932
+ torch.save(
933
+ {
934
+ "kind": kind,
935
+ "seed": seed,
936
+ "best_epoch": best_epoch,
937
+ "best_score": best_score,
938
+ "model_state": best_state,
939
+ "args": vars(args),
940
+ "architecture_change": "none",
941
+ "optimizer_persistent_across_epochs": True,
942
+ },
943
+ checkpoint,
944
+ )
945
+ log_path = output_dir / "training" / f"{kind}_seed_{seed}.csv"
946
+ log_path.parent.mkdir(parents=True, exist_ok=True)
947
+ pd.DataFrame(logs).to_csv(log_path, index=False)
948
+ return model, {
949
+ "kind": kind,
950
+ "seed": seed,
951
+ "best_epoch": best_epoch,
952
+ "best_score": best_score,
953
+ "checkpoint": str(checkpoint),
954
+ }
955
+
956
+
957
+ def empty_accumulator() -> Dict[str, Any]:
958
+ return {
959
+ "squared": {step: 0.0 for step in HORIZONS},
960
+ "count": {step: 0.0 for step in HORIZONS},
961
+ "pred": {step: [] for step in HORIZONS},
962
+ "target": {step: [] for step in HORIZONS},
963
+ "samples": [],
964
+ "groups": {
965
+ (step, group): []
966
+ for step in HORIZONS
967
+ for group in GROUPS
968
+ },
969
+ "gradient": {step: [] for step in HORIZONS},
970
+ "wave_invalid": {step: [] for step in HORIZONS},
971
+ "direction_norm": {step: [] for step in HORIZONS},
972
+ "spectral_pred": {step: [] for step in [12, 28, 60]},
973
+ "spectral_target": {step: [] for step in [12, 28, 60]},
974
+ "finite": True,
975
+ "max_abs": 0.0,
976
+ }
977
+
978
+
979
+ def update_accumulator(
980
+ accumulator: Dict[str, Any],
981
+ outputs: Sequence[torch.Tensor],
982
+ future: torch.Tensor,
983
+ mask: torch.Tensor,
984
+ batch: Mapping[str, torch.Tensor],
985
+ means: torch.Tensor,
986
+ stds: torch.Tensor,
987
+ ) -> None:
988
+ for step in HORIZONS:
989
+ prediction = outputs[step - 1]
990
+ target = future[:, step - 1]
991
+ error = (prediction - target).square() * mask
992
+ sample_sse = error.flatten(1).sum(dim=1)
993
+ sample_count = mask.flatten(1).sum(dim=1).clamp_min(1.0)
994
+ sample_mse = sample_sse / sample_count
995
+ accumulator["squared"][step] += float(sample_sse.sum())
996
+ accumulator["count"][step] += float(sample_count.sum())
997
+ accumulator["pred"][step].append((prediction * mask).flatten(1).cpu())
998
+ accumulator["target"][step].append((target * mask).flatten(1).cpu())
999
+ gradient = torch.sqrt(
1000
+ masked_gradient_loss(prediction, target, mask).detach()
1001
+ + 1e-12
1002
+ )
1003
+ accumulator["gradient"][step].append(float(gradient))
1004
+
1005
+ for bi in range(prediction.shape[0]):
1006
+ accumulator["samples"].append({
1007
+ "sample_index": int(batch["sample_index"][bi]),
1008
+ "time_index": int(batch["time_index"][bi]),
1009
+ "origin_y": int(batch["origin_y"][bi]),
1010
+ "origin_x": int(batch["origin_x"][bi]),
1011
+ "horizon": step,
1012
+ "sse": float(sample_sse[bi]),
1013
+ "valid_count": float(sample_count[bi]),
1014
+ "mse": float(sample_mse[bi]),
1015
+ "rmse": math.sqrt(max(float(sample_mse[bi]), 0.0)),
1016
+ })
1017
+
1018
+ for group, indices in GROUPS.items():
1019
+ group_mask = mask[:, indices]
1020
+ group_error = error[:, indices]
1021
+ denominator = group_mask.flatten(1).sum(dim=1).clamp_min(1.0)
1022
+ group_rmse = torch.sqrt(
1023
+ group_error.flatten(1).sum(dim=1) / denominator
1024
+ )
1025
+ accumulator["groups"][(step, group)].extend(
1026
+ group_rmse.cpu().tolist()
1027
+ )
1028
+
1029
+ invalid, direction = s3a0.physical_wave_audit(
1030
+ prediction, means, stds, mask
1031
+ )
1032
+ accumulator["wave_invalid"][step].extend(invalid.cpu().tolist())
1033
+ accumulator["direction_norm"][step].extend(direction.cpu().tolist())
1034
+
1035
+ if step in accumulator["spectral_pred"]:
1036
+ accumulator["spectral_pred"][step].append(
1037
+ s3a0.spectral_energy_ratios(prediction, mask).cpu()
1038
+ )
1039
+ accumulator["spectral_target"][step].append(
1040
+ s3a0.spectral_energy_ratios(target, mask).cpu()
1041
+ )
1042
+
1043
+ accumulator["finite"] = (
1044
+ accumulator["finite"]
1045
+ and bool(torch.isfinite(prediction).all())
1046
+ )
1047
+ accumulator["max_abs"] = max(
1048
+ accumulator["max_abs"],
1049
+ float(prediction.abs().max()),
1050
+ )
1051
+
1052
+
1053
+ def finalize_accumulator(accumulator: Dict[str, Any]) -> Dict[str, Any]:
1054
+ result = {
1055
+ "finite": bool(accumulator["finite"]),
1056
+ "max_abs": float(accumulator["max_abs"]),
1057
+ }
1058
+ for step in HORIZONS:
1059
+ result[f"rmse_h{step}"] = math.sqrt(
1060
+ accumulator["squared"][step]
1061
+ / max(accumulator["count"][step], 1.0)
1062
+ )
1063
+ prediction = torch.cat(accumulator["pred"][step], dim=0)
1064
+ target = torch.cat(accumulator["target"][step], dim=0)
1065
+ result[f"variance_ratio_h{step}"] = float(
1066
+ prediction.var(unbiased=False)
1067
+ / (target.var(unbiased=False) + 1e-8)
1068
+ )
1069
+ result[f"gradient_rmse_h{step}"] = float(
1070
+ np.mean(accumulator["gradient"][step])
1071
+ )
1072
+ result[f"wave_invalid_fraction_h{step}"] = float(
1073
+ np.mean(accumulator["wave_invalid"][step])
1074
+ )
1075
+ result[f"direction_norm_error_h{step}"] = float(
1076
+ np.mean(accumulator["direction_norm"][step])
1077
+ )
1078
+ for group in GROUPS:
1079
+ result[f"group_rmse_{group}_h{step}"] = float(
1080
+ np.mean(accumulator["groups"][(step, group)])
1081
+ )
1082
+ if step in accumulator["spectral_pred"]:
1083
+ pred_energy = torch.cat(
1084
+ accumulator["spectral_pred"][step], dim=0
1085
+ ).mean(dim=0)
1086
+ target_energy = torch.cat(
1087
+ accumulator["spectral_target"][step], dim=0
1088
+ ).mean(dim=0)
1089
+ ratio = pred_energy / (target_energy + 1e-8)
1090
+ for band_index, band in enumerate(["low", "mid", "high"]):
1091
+ result[f"spectral_{band}_ratio_h{step}"] = float(
1092
+ ratio[band_index]
1093
+ )
1094
+ result["sample_rows"] = accumulator["samples"]
1095
+ return result
1096
+
1097
+
1098
+ @torch.no_grad()
1099
+ def evaluate_methods(
1100
+ models: Mapping[str, nn.Module],
1101
+ loader: DataLoader,
1102
+ device: torch.device,
1103
+ means: torch.Tensor,
1104
+ stds: torch.Tensor,
1105
+ ) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, pd.DataFrame]]:
1106
+ accumulators = {method: empty_accumulator() for method in METHODS}
1107
+ for batch_number, batch in enumerate(loader, start=1):
1108
+ history = batch["history"].to(device)
1109
+ future = batch["future"].to(device)
1110
+ mask = batch["mask"].to(device)
1111
+ persistence = [history[:, -1] * mask for _ in range(60)]
1112
+ outputs = {
1113
+ "persistence": persistence,
1114
+ "parent_single": rollout_single(
1115
+ models["parent_single"], history, mask, 60
1116
+ ),
1117
+ "parent_explicit_band": rollout_explicit(
1118
+ models["parent_explicit"], history, mask, 60, True
1119
+ ),
1120
+ "repaired_single": rollout_single(
1121
+ models["repaired_single"], history, mask, 60
1122
+ ),
1123
+ "repaired_explicit_no_band": rollout_explicit(
1124
+ models["repaired_explicit"], history, mask, 60, False
1125
+ ),
1126
+ "repaired_explicit_band": rollout_explicit(
1127
+ models["repaired_explicit"], history, mask, 60, True
1128
+ ),
1129
+ }
1130
+ for method, current in outputs.items():
1131
+ update_accumulator(
1132
+ accumulators[method],
1133
+ current,
1134
+ future,
1135
+ mask,
1136
+ batch,
1137
+ means,
1138
+ stds,
1139
+ )
1140
+ if batch_number % max(len(loader) // 6, 1) == 0:
1141
+ print(
1142
+ f"[test] batch={batch_number}/{len(loader)}",
1143
+ flush=True,
1144
+ )
1145
+
1146
+ metrics = {}
1147
+ sample_tables = {}
1148
+ for method, accumulator in accumulators.items():
1149
+ current = finalize_accumulator(accumulator)
1150
+ sample_tables[method] = pd.DataFrame(
1151
+ current.pop("sample_rows")
1152
+ )
1153
+ metrics[method] = current
1154
+ return metrics, sample_tables
1155
+
1156
+
1157
+ def time_block_bootstrap(
1158
+ reference_tables: Sequence[pd.DataFrame],
1159
+ candidate_tables: Sequence[pd.DataFrame],
1160
+ horizon: int,
1161
+ repetitions: int,
1162
+ seed: int,
1163
+ ) -> Dict[str, float]:
1164
+ # Average model seeds within each exact sample before bootstrapping time blocks.
1165
+ merged_rows = []
1166
+ for model_seed, (reference, candidate) in enumerate(
1167
+ zip(reference_tables, candidate_tables)
1168
+ ):
1169
+ ref = reference[reference.horizon == horizon].copy()
1170
+ cand = candidate[candidate.horizon == horizon].copy()
1171
+ merged = ref.merge(
1172
+ cand,
1173
+ on=[
1174
+ "sample_index",
1175
+ "time_index",
1176
+ "origin_y",
1177
+ "origin_x",
1178
+ "horizon",
1179
+ "valid_count",
1180
+ ],
1181
+ suffixes=("_reference", "_candidate"),
1182
+ )
1183
+ merged["model_seed_index"] = model_seed
1184
+ merged_rows.append(merged)
1185
+ table = pd.concat(merged_rows, ignore_index=True)
1186
+ grouped = (
1187
+ table.groupby(
1188
+ [
1189
+ "sample_index",
1190
+ "time_index",
1191
+ "origin_y",
1192
+ "origin_x",
1193
+ "horizon",
1194
+ "valid_count",
1195
+ ],
1196
+ as_index=False,
1197
+ )[
1198
+ ["sse_reference", "sse_candidate", "mse_reference", "mse_candidate"]
1199
+ ]
1200
+ .mean()
1201
+ )
1202
+ blocks = sorted(grouped.time_index.unique().tolist())
1203
+ generator = np.random.default_rng(seed)
1204
+ weighted_differences = []
1205
+ equal_sample_differences = []
1206
+ for _ in range(repetitions):
1207
+ sampled_blocks = generator.choice(
1208
+ blocks, size=len(blocks), replace=True
1209
+ )
1210
+ sampled = pd.concat(
1211
+ [grouped[grouped.time_index == block] for block in sampled_blocks],
1212
+ ignore_index=True,
1213
+ )
1214
+ reference_weighted = (
1215
+ sampled.sse_reference.sum()
1216
+ / sampled.valid_count.sum()
1217
+ )
1218
+ candidate_weighted = (
1219
+ sampled.sse_candidate.sum()
1220
+ / sampled.valid_count.sum()
1221
+ )
1222
+ weighted_differences.append(
1223
+ candidate_weighted - reference_weighted
1224
+ )
1225
+ equal_sample_differences.append(
1226
+ float(
1227
+ (
1228
+ sampled.mse_candidate
1229
+ - sampled.mse_reference
1230
+ ).mean()
1231
+ )
1232
+ )
1233
+ weighted_low, weighted_high = np.percentile(
1234
+ weighted_differences, [2.5, 97.5]
1235
+ )
1236
+ sample_low, sample_high = np.percentile(
1237
+ equal_sample_differences, [2.5, 97.5]
1238
+ )
1239
+ reference_weighted = (
1240
+ grouped.sse_reference.sum()
1241
+ / grouped.valid_count.sum()
1242
+ )
1243
+ candidate_weighted = (
1244
+ grouped.sse_candidate.sum()
1245
+ / grouped.valid_count.sum()
1246
+ )
1247
+ return {
1248
+ "weighted_mean_mse_difference": float(
1249
+ candidate_weighted - reference_weighted
1250
+ ),
1251
+ "weighted_ci_low": float(weighted_low),
1252
+ "weighted_ci_high": float(weighted_high),
1253
+ "weighted_mse_gain_percent": float(
1254
+ 100.0
1255
+ * (reference_weighted - candidate_weighted)
1256
+ / max(reference_weighted, 1e-12)
1257
+ ),
1258
+ "equal_sample_mean_difference": float(
1259
+ (grouped.mse_candidate - grouped.mse_reference).mean()
1260
+ ),
1261
+ "equal_sample_ci_low": float(sample_low),
1262
+ "equal_sample_ci_high": float(sample_high),
1263
+ "fraction_samples_improved": float(
1264
+ (grouped.mse_candidate < grouped.mse_reference).mean()
1265
+ ),
1266
+ "time_blocks": int(len(blocks)),
1267
+ "unique_samples": int(len(grouped)),
1268
+ }
1269
+
1270
+
1271
+ @torch.no_grad()
1272
+ def runtime_audit(
1273
+ explicit: nn.Module,
1274
+ single: nn.Module,
1275
+ loader: DataLoader,
1276
+ device: torch.device,
1277
+ repetitions: int = 8,
1278
+ ) -> Dict[str, float]:
1279
+ batch = next(iter(loader))
1280
+ history = batch["history"].to(device)
1281
+ mask = batch["mask"].to(device)
1282
+ for _ in range(2):
1283
+ rollout_explicit(explicit, history, mask, 60, True)
1284
+ rollout_single(single, history, mask, 60)
1285
+ if device.type == "cuda":
1286
+ torch.cuda.synchronize()
1287
+ start = time.perf_counter()
1288
+ for _ in range(repetitions):
1289
+ rollout_explicit(explicit, history, mask, 60, True)
1290
+ if device.type == "cuda":
1291
+ torch.cuda.synchronize()
1292
+ explicit_time = time.perf_counter() - start
1293
+ start = time.perf_counter()
1294
+ for _ in range(repetitions):
1295
+ rollout_single(single, history, mask, 60)
1296
+ if device.type == "cuda":
1297
+ torch.cuda.synchronize()
1298
+ single_time = time.perf_counter() - start
1299
+ batch_size = history.shape[0]
1300
+ return {
1301
+ "explicit_60step_ms_per_sample": (
1302
+ 1000.0 * explicit_time / repetitions / batch_size
1303
+ ),
1304
+ "single_60step_ms_per_sample": (
1305
+ 1000.0 * single_time / repetitions / batch_size
1306
+ ),
1307
+ }
1308
+
1309
+
1310
+ def create_synthetic_native(
1311
+ destination: Path,
1312
+ reference_metadata: Mapping[str, Any],
1313
+ time_steps: int = 80,
1314
+ height: int = 64,
1315
+ width: int = 64,
1316
+ ) -> None:
1317
+ destination.mkdir(parents=True, exist_ok=True)
1318
+ generator = np.random.default_rng(20261020 + len(destination.parts))
1319
+ data = generator.normal(
1320
+ 0.0,
1321
+ 1.0,
1322
+ (time_steps, len(VARIABLE_NAMES), height, width),
1323
+ ).astype(np.float32)
1324
+ np.save(destination / "scs_c0_data.npy", data)
1325
+ np.save(
1326
+ destination / "scs_c0_mask.npy",
1327
+ np.ones((height, width), np.float32),
1328
+ )
1329
+ np.save(
1330
+ destination / "scs_c0_variable_masks.npy",
1331
+ np.ones((len(VARIABLE_NAMES), height, width), np.float32),
1332
+ )
1333
+ metadata = {
1334
+ "variable_names": VARIABLE_NAMES,
1335
+ "means": reference_metadata["means"],
1336
+ "stds": reference_metadata["stds"],
1337
+ "times_ns": (
1338
+ np.datetime64("2023-07-10")
1339
+ + np.arange(time_steps) * np.timedelta64(6, "h")
1340
+ ).astype("datetime64[ns]").astype(np.int64).tolist(),
1341
+ "latitude": np.linspace(0, 25, height).tolist(),
1342
+ "longitude": np.linspace(99, 123, width).tolist(),
1343
+ "shape": list(data.shape),
1344
+ "native_resolution_degrees": 1 / 12,
1345
+ }
1346
+ atomic_json(metadata, destination / "scs_c0_metadata.json")
1347
+ pd.DataFrame({
1348
+ "variable": VARIABLE_NAMES,
1349
+ "mean": metadata["means"],
1350
+ "std": metadata["stds"],
1351
+ }).to_csv(destination / "C0_data_audit.csv", index=False)
1352
+
1353
+
1354
+ def build_parser() -> argparse.ArgumentParser:
1355
+ parser = argparse.ArgumentParser(
1356
+ description="CIDM-v3 S3-A1 long-horizon objective repair"
1357
+ )
1358
+ parser.add_argument(
1359
+ "--parent_zip",
1360
+ default="/content/CIDM_v3_SCS_V3_S3_A0.zip",
1361
+ )
1362
+ parser.add_argument(
1363
+ "--native_cache_dir",
1364
+ default="/content/CIDM_v3_SCS_S2A2_NATIVE_1_12",
1365
+ )
1366
+ parser.add_argument(
1367
+ "--parent_cache",
1368
+ default="/content/CIDM_v3_SCS_S3A1_PARENT_CACHE",
1369
+ )
1370
+ parser.add_argument(
1371
+ "--output_dir",
1372
+ default="/content/CIDM_v3_SCS_V3_S3_A1",
1373
+ )
1374
+ parser.add_argument(
1375
+ "--hf_repo_id",
1376
+ default="wuff-mann/CIDM-v3-SCS-S2A0-Data",
1377
+ )
1378
+ parser.add_argument("--hf_token", default="")
1379
+ parser.add_argument("--history", type=int, default=4)
1380
+ parser.add_argument("--patch_size", type=int, default=48)
1381
+ parser.add_argument("--max_horizon", type=int, default=60)
1382
+ parser.add_argument("--train_samples", type=int, default=192)
1383
+ parser.add_argument("--validation_samples", type=int, default=48)
1384
+ parser.add_argument("--test_samples", type=int, default=64)
1385
+ parser.add_argument("--train_seed", type=int, default=20261021)
1386
+ parser.add_argument("--validation_seed", type=int, default=20261022)
1387
+ parser.add_argument("--test_seed", type=int, default=20261010)
1388
+ parser.add_argument("--batch_size", type=int, default=1)
1389
+ parser.add_argument("--num_workers", type=int, default=0)
1390
+ parser.add_argument("--epochs", type=int, default=6)
1391
+ parser.add_argument("--accumulation", type=int, default=4)
1392
+ parser.add_argument("--explicit_learning_rate", type=float, default=2e-5)
1393
+ parser.add_argument("--single_learning_rate", type=float, default=3e-5)
1394
+ parser.add_argument("--weight_decay", type=float, default=1e-4)
1395
+ parser.add_argument("--grad_clip", type=float, default=1.0)
1396
+ parser.add_argument("--gradient_weight", type=float, default=0.08)
1397
+ parser.add_argument("--increment_weight", type=float, default=0.12)
1398
+ parser.add_argument("--persistence_skill_weight", type=float, default=0.20)
1399
+ parser.add_argument("--persistence_target_ratio", type=float, default=0.98)
1400
+ parser.add_argument("--variance_weight", type=float, default=0.04)
1401
+ parser.add_argument("--spectral_weight", type=float, default=0.04)
1402
+ parser.add_argument("--wave_nonnegative_weight", type=float, default=0.02)
1403
+ parser.add_argument("--direction_circle_weight", type=float, default=0.04)
1404
+ parser.add_argument("--bootstrap_reps", type=int, default=1000)
1405
+ parser.add_argument(
1406
+ "--seeds",
1407
+ default="20260902,20260903,20260904",
1408
+ )
1409
+ parser.add_argument("--synthetic_smoke", action="store_true")
1410
+ return parser
1411
+
1412
+
1413
+ def main() -> None:
1414
+ args = build_parser().parse_args()
1415
+ seeds = [
1416
+ int(value) for value in args.seeds.split(",") if value.strip()
1417
+ ]
1418
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
1419
+ if not args.synthetic_smoke and device.type != "cuda":
1420
+ raise RuntimeError("Formal S3-A1 requires CUDA.")
1421
+ torch.set_float32_matmul_precision("highest")
1422
+ if torch.cuda.is_available():
1423
+ torch.backends.cuda.matmul.allow_tf32 = False
1424
+ torch.backends.cudnn.allow_tf32 = False
1425
+
1426
+ output_dir = Path(args.output_dir)
1427
+ shutil.rmtree(output_dir, ignore_errors=True)
1428
+ for subdir in [
1429
+ "audits",
1430
+ "training",
1431
+ "checkpoints",
1432
+ "evaluation",
1433
+ "figures",
1434
+ "lineage",
1435
+ "deployment",
1436
+ ]:
1437
+ (output_dir / subdir).mkdir(parents=True, exist_ok=True)
1438
+
1439
+ try:
1440
+ stage(1, 9, "恢复S3-A0谱系与夏季/秋季原生缓存")
1441
+ if args.synthetic_smoke:
1442
+ if not Path(args.parent_zip).is_file():
1443
+ raise FileNotFoundError(args.parent_zip)
1444
+ asset_report = {
1445
+ "synthetic_smoke": True,
1446
+ "parent_zip_sha256": sha256_file(Path(args.parent_zip)),
1447
+ }
1448
+ else:
1449
+ asset_report = ensure_assets(args)
1450
+ atomic_json(
1451
+ asset_report,
1452
+ output_dir / "audits" / "S3A1_asset_audit.json",
1453
+ )
1454
+
1455
+ stage(2, 9, "提取显式尺度与Single-State父检查点")
1456
+ parent_cache = Path(args.parent_cache)
1457
+ shutil.rmtree(parent_cache, ignore_errors=True)
1458
+ assets = extract_parent_assets(
1459
+ Path(args.parent_zip), parent_cache
1460
+ )
1461
+ reference_mean = np.asarray(
1462
+ assets["metadata"]["means"], dtype=np.float32
1463
+ )
1464
+ reference_std = np.asarray(
1465
+ assets["metadata"]["stds"], dtype=np.float32
1466
+ )
1467
+ atomic_json(
1468
+ {
1469
+ "s1_verdict": assets["s1_verdict"],
1470
+ "s3a0_verdict": assets["s3_verdict"],
1471
+ "architecture_policy": {
1472
+ "unchanged": True,
1473
+ "keep": [
1474
+ "explicit scale state",
1475
+ "shared scale-conditioned core",
1476
+ "multi-step recurrence",
1477
+ "Band Closure",
1478
+ ],
1479
+ "remain_off": [
1480
+ "future BER",
1481
+ "learned cross-scale flux",
1482
+ "slow memory closure",
1483
+ "vertical closure",
1484
+ "causal variance amplifier",
1485
+ "event router",
1486
+ ],
1487
+ },
1488
+ },
1489
+ output_dir / "lineage" / "S3A1_parent_lineage.json",
1490
+ )
1491
+
1492
+ if args.synthetic_smoke:
1493
+ for season in ["summer", "autumn"]:
1494
+ create_synthetic_native(
1495
+ Path(args.native_cache_dir) / season / "prepared",
1496
+ assets["metadata"],
1497
+ time_steps=max(args.max_horizon + args.history + 12, 80),
1498
+ height=64,
1499
+ width=64,
1500
+ )
1501
+
1502
+ stage(3, 9, "构建夏季训练/验证与秋季独立测试")
1503
+ loaders, datasets = make_loaders(
1504
+ Path(args.native_cache_dir),
1505
+ reference_mean,
1506
+ reference_std,
1507
+ args,
1508
+ )
1509
+ train_keys = set(datasets["train"].record_keys)
1510
+ validation_keys = set(datasets["validation"].record_keys)
1511
+ exact_overlap = len(train_keys & validation_keys)
1512
+ atomic_json(
1513
+ {
1514
+ split: {
1515
+ "samples": len(dataset),
1516
+ "native_shape": list(dataset.data.shape),
1517
+ "unique_records": len(set(dataset.records)),
1518
+ }
1519
+ for split, dataset in datasets.items()
1520
+ }
1521
+ | {
1522
+ "train_validation_exact_overlap": exact_overlap,
1523
+ "train_horizon_schedule": horizon_schedule(args),
1524
+ "normalization": (
1525
+ "season storage -> physical -> original S1-R3 training"
1526
+ ),
1527
+ },
1528
+ output_dir / "audits" / "S3A1_split_audit.json",
1529
+ )
1530
+ if exact_overlap > 0:
1531
+ raise RuntimeError(
1532
+ f"Train/validation exact overlap: {exact_overlap}"
1533
+ )
1534
+
1535
+ means = torch.as_tensor(reference_mean, device=device)
1536
+ stds = torch.as_tensor(reference_std, device=device)
1537
+
1538
+ stage(4, 9, "同目标修复显式尺度与参数匹配Single-State")
1539
+ repaired_models = {}
1540
+ parent_models = {}
1541
+ training_summary = []
1542
+ for seed in seeds:
1543
+ print(f"[seed {seed}] loading parents", flush=True)
1544
+ parent_explicit = make_explicit(
1545
+ assets["explicit_checkpoints"][seed], device
1546
+ )
1547
+ parent_single = make_single(
1548
+ assets["single_checkpoints"][seed], device
1549
+ )
1550
+ repaired_explicit = copy.deepcopy(parent_explicit)
1551
+ repaired_single = copy.deepcopy(parent_single)
1552
+
1553
+ repaired_explicit, explicit_record = train_model(
1554
+ repaired_explicit,
1555
+ "explicit",
1556
+ seed,
1557
+ loaders["train"],
1558
+ loaders["validation"],
1559
+ device,
1560
+ means,
1561
+ stds,
1562
+ args,
1563
+ output_dir,
1564
+ )
1565
+ repaired_single, single_record = train_model(
1566
+ repaired_single,
1567
+ "single",
1568
+ seed,
1569
+ loaders["train"],
1570
+ loaders["validation"],
1571
+ device,
1572
+ means,
1573
+ stds,
1574
+ args,
1575
+ output_dir,
1576
+ )
1577
+ repaired_models[seed] = {
1578
+ "repaired_explicit": repaired_explicit,
1579
+ "repaired_single": repaired_single,
1580
+ }
1581
+ parent_models[seed] = {
1582
+ "parent_explicit": parent_explicit,
1583
+ "parent_single": parent_single,
1584
+ }
1585
+ training_summary.extend([explicit_record, single_record])
1586
+ pd.DataFrame(training_summary).to_csv(
1587
+ output_dir / "S3A1_training_summary.csv", index=False
1588
+ )
1589
+
1590
+ stage(5, 9, "秋季60步测试与严格样本审计")
1591
+ metric_rows = []
1592
+ sample_tables: Dict[Tuple[int, str], pd.DataFrame] = {}
1593
+ runtime_rows = []
1594
+ for seed in seeds:
1595
+ models = {
1596
+ **parent_models[seed],
1597
+ **repaired_models[seed],
1598
+ }
1599
+ metrics, tables = evaluate_methods(
1600
+ models,
1601
+ loaders["test"],
1602
+ device,
1603
+ means,
1604
+ stds,
1605
+ )
1606
+ for method, current in metrics.items():
1607
+ metric_rows.append({
1608
+ "seed": seed,
1609
+ "method": method,
1610
+ **current,
1611
+ })
1612
+ table = tables[method]
1613
+ table["seed"] = seed
1614
+ sample_tables[(seed, method)] = table
1615
+ table.to_csv(
1616
+ output_dir
1617
+ / "evaluation"
1618
+ / f"S3A1_samples_{method}_seed_{seed}.csv",
1619
+ index=False,
1620
+ )
1621
+ runtime = runtime_audit(
1622
+ repaired_models[seed]["repaired_explicit"],
1623
+ repaired_models[seed]["repaired_single"],
1624
+ loaders["test"],
1625
+ device,
1626
+ )
1627
+ runtime["seed"] = seed
1628
+ runtime_rows.append(runtime)
1629
+ if device.type == "cuda":
1630
+ torch.cuda.empty_cache()
1631
+
1632
+ metric_table = pd.DataFrame(metric_rows)
1633
+ metric_table.to_csv(
1634
+ output_dir / "evaluation" / "S3A1_seed_metrics.csv",
1635
+ index=False,
1636
+ )
1637
+ runtime_table = pd.DataFrame(runtime_rows)
1638
+ runtime_table.to_csv(
1639
+ output_dir / "S3A1_runtime.csv", index=False
1640
+ )
1641
+
1642
+ stage(6, 9, "时间块Bootstrap与加权/等样本一致性")
1643
+ comparisons = [
1644
+ ("repaired_explicit_band", "repaired_single"),
1645
+ ("repaired_explicit_band", "parent_explicit_band"),
1646
+ ("repaired_explicit_band", "repaired_explicit_no_band"),
1647
+ ("repaired_explicit_band", "persistence"),
1648
+ ("repaired_single", "parent_single"),
1649
+ ]
1650
+ bootstrap_payload = {}
1651
+ comparison_rows = []
1652
+ for candidate, reference in comparisons:
1653
+ for horizon in [12, 28, 60]:
1654
+ result = time_block_bootstrap(
1655
+ [sample_tables[(seed, reference)] for seed in seeds],
1656
+ [sample_tables[(seed, candidate)] for seed in seeds],
1657
+ horizon,
1658
+ args.bootstrap_reps,
1659
+ seeds[0] + horizon + sum(map(ord, candidate + reference)),
1660
+ )
1661
+ key = f"{candidate}_vs_{reference}_h{horizon}"
1662
+ bootstrap_payload[key] = result
1663
+ comparison_rows.append({
1664
+ "candidate": candidate,
1665
+ "reference": reference,
1666
+ "horizon": horizon,
1667
+ "lead": HORIZON_LABELS[horizon],
1668
+ **result,
1669
+ })
1670
+ comparison_table = pd.DataFrame(comparison_rows)
1671
+ comparison_table.to_csv(
1672
+ output_dir / "S3A1_block_bootstrap_comparisons.csv",
1673
+ index=False,
1674
+ )
1675
+ atomic_json(
1676
+ bootstrap_payload,
1677
+ output_dir / "paired_block_bootstrap.json",
1678
+ )
1679
+
1680
+ summary_rows = []
1681
+ for method in METHODS:
1682
+ current = metric_table[
1683
+ metric_table["method"] == method
1684
+ ].set_index("seed")
1685
+ for horizon in HORIZONS:
1686
+ summary_rows.append({
1687
+ "method": method,
1688
+ "horizon": horizon,
1689
+ "lead": HORIZON_LABELS[horizon],
1690
+ "rmse": float(current[f"rmse_h{horizon}"].mean()),
1691
+ "variance_ratio": float(
1692
+ current[f"variance_ratio_h{horizon}"].mean()
1693
+ ),
1694
+ "gradient_rmse": float(
1695
+ current[f"gradient_rmse_h{horizon}"].mean()
1696
+ ),
1697
+ "wave_invalid_fraction": float(
1698
+ current[f"wave_invalid_fraction_h{horizon}"].mean()
1699
+ ),
1700
+ "direction_norm_error": float(
1701
+ current[f"direction_norm_error_h{horizon}"].mean()
1702
+ ),
1703
+ "finite": bool(current["finite"].all()),
1704
+ "max_abs": float(current["max_abs"].max()),
1705
+ })
1706
+ summary = pd.DataFrame(summary_rows)
1707
+ summary.to_csv(
1708
+ output_dir / "S3A1_long_rollout_summary.csv",
1709
+ index=False,
1710
+ )
1711
+
1712
+ stage(7, 9, "最终架构冻结判决")
1713
+ mean_metrics = metric_table.groupby(
1714
+ "method"
1715
+ ).mean(numeric_only=True)
1716
+
1717
+ def gain(candidate: str, reference: str, horizon: int) -> float:
1718
+ return 100.0 * (
1719
+ mean_metrics.loc[reference, f"rmse_h{horizon}"]
1720
+ - mean_metrics.loc[candidate, f"rmse_h{horizon}"]
1721
+ ) / mean_metrics.loc[reference, f"rmse_h{horizon}"]
1722
+
1723
+ def block(candidate: str, reference: str, horizon: int) -> pd.Series:
1724
+ return comparison_table[
1725
+ (comparison_table.candidate == candidate)
1726
+ & (comparison_table.reference == reference)
1727
+ & (comparison_table.horizon == horizon)
1728
+ ].iloc[0]
1729
+
1730
+ scale_vs_single_72 = gain(
1731
+ "repaired_explicit_band", "repaired_single", 12
1732
+ )
1733
+ scale_vs_single_7d = gain(
1734
+ "repaired_explicit_band", "repaired_single", 28
1735
+ )
1736
+ scale_vs_single_15d = gain(
1737
+ "repaired_explicit_band", "repaired_single", 60
1738
+ )
1739
+ repair_gain_72 = gain(
1740
+ "repaired_explicit_band", "parent_explicit_band", 12
1741
+ )
1742
+ repair_gain_7d = gain(
1743
+ "repaired_explicit_band", "parent_explicit_band", 28
1744
+ )
1745
+ repair_gain_15d = gain(
1746
+ "repaired_explicit_band", "parent_explicit_band", 60
1747
+ )
1748
+ band_gain_72 = gain(
1749
+ "repaired_explicit_band", "repaired_explicit_no_band", 12
1750
+ )
1751
+ band_gain_7d = gain(
1752
+ "repaired_explicit_band", "repaired_explicit_no_band", 28
1753
+ )
1754
+ band_gain_15d = gain(
1755
+ "repaired_explicit_band", "repaired_explicit_no_band", 60
1756
+ )
1757
+ persistence_gap_72 = gain(
1758
+ "repaired_explicit_band", "persistence", 12
1759
+ )
1760
+ persistence_gap_7d = gain(
1761
+ "repaired_explicit_band", "persistence", 28
1762
+ )
1763
+ persistence_gap_15d = gain(
1764
+ "repaired_explicit_band", "persistence", 60
1765
+ )
1766
+ parent_persistence_gap_7d = gain(
1767
+ "parent_explicit_band", "persistence", 28
1768
+ )
1769
+ persistence_gap_closed_7d = (
1770
+ persistence_gap_7d - parent_persistence_gap_7d
1771
+ )
1772
+
1773
+ variance_7d = float(
1774
+ mean_metrics.loc[
1775
+ "repaired_explicit_band", "variance_ratio_h28"
1776
+ ]
1777
+ )
1778
+ variance_15d = float(
1779
+ mean_metrics.loc[
1780
+ "repaired_explicit_band", "variance_ratio_h60"
1781
+ ]
1782
+ )
1783
+ high_spectral_15d = float(
1784
+ mean_metrics.loc[
1785
+ "repaired_explicit_band", "spectral_high_ratio_h60"
1786
+ ]
1787
+ )
1788
+ direction_error_15d = float(
1789
+ mean_metrics.loc[
1790
+ "repaired_explicit_band", "direction_norm_error_h60"
1791
+ ]
1792
+ )
1793
+ wave_invalid_15d = float(
1794
+ mean_metrics.loc[
1795
+ "repaired_explicit_band", "wave_invalid_fraction_h60"
1796
+ ]
1797
+ )
1798
+ finite = bool(
1799
+ metric_table[
1800
+ metric_table.method == "repaired_explicit_band"
1801
+ ]["finite"].all()
1802
+ )
1803
+ runtime_ms = float(
1804
+ runtime_table["explicit_60step_ms_per_sample"].mean()
1805
+ )
1806
+
1807
+ block_scale_72 = block(
1808
+ "repaired_explicit_band", "repaired_single", 12
1809
+ )
1810
+ block_scale_7d = block(
1811
+ "repaired_explicit_band", "repaired_single", 28
1812
+ )
1813
+ block_scale_15d = block(
1814
+ "repaired_explicit_band", "repaired_single", 60
1815
+ )
1816
+ block_repair_7d = block(
1817
+ "repaired_explicit_band", "parent_explicit_band", 28
1818
+ )
1819
+ block_persistence_7d = block(
1820
+ "repaired_explicit_band", "persistence", 28
1821
+ )
1822
+
1823
+ checks = {
1824
+ "same_architecture_no_new_module": True,
1825
+ "persistent_optimizer_across_epochs": True,
1826
+ "three_repaired_explicit_and_single_pairs": len(seeds) == 3,
1827
+ "all_repaired_explicit_rollouts_finite": finite,
1828
+ "repair_improves_parent_explicit_72h": repair_gain_72 > 0.0,
1829
+ "repair_improves_parent_explicit_7d": repair_gain_7d > 0.0,
1830
+ "repair_improves_parent_explicit_15d": repair_gain_15d > 0.0,
1831
+ "repair_7d_block_bootstrap_positive": (
1832
+ float(block_repair_7d.weighted_ci_high) < 0.0
1833
+ ),
1834
+ "explicit_beats_single_72h_ge_1pct": scale_vs_single_72 >= 1.0,
1835
+ "explicit_beats_single_7d_ge_1pct": scale_vs_single_7d >= 1.0,
1836
+ "explicit_15d_nonworse_than_single": scale_vs_single_15d >= 0.0,
1837
+ "scale_72h_block_bootstrap_positive": (
1838
+ float(block_scale_72.weighted_ci_high) < 0.0
1839
+ ),
1840
+ "scale_7d_block_bootstrap_positive": (
1841
+ float(block_scale_7d.weighted_ci_high) < 0.0
1842
+ ),
1843
+ "scale_15d_equal_sample_majority_positive": (
1844
+ float(block_scale_15d.fraction_samples_improved) >= 0.50
1845
+ ),
1846
+ "band_closure_72h_positive": band_gain_72 >= 0.2,
1847
+ "band_closure_7d_nonnegative": band_gain_7d >= 0.0,
1848
+ "band_closure_15d_nonnegative": band_gain_15d >= 0.0,
1849
+ "persistence_gap_closed_7d_by_5pct_points": (
1850
+ persistence_gap_closed_7d >= 5.0
1851
+ ),
1852
+ "repaired_7d_beats_persistence": persistence_gap_7d > 0.0,
1853
+ "repaired_7d_persistence_block_positive": (
1854
+ float(block_persistence_7d.weighted_ci_high) < 0.0
1855
+ ),
1856
+ "variance_ratio_7d_ge_0_50": variance_7d >= 0.50,
1857
+ "variance_ratio_15d_ge_0_35": variance_15d >= 0.35,
1858
+ "high_spectral_ratio_15d_0_5_to_1_5": (
1859
+ 0.50 <= high_spectral_15d <= 1.50
1860
+ ),
1861
+ "direction_norm_error_15d_lt_0_30": direction_error_15d < 0.30,
1862
+ "wave_invalid_fraction_15d_lt_0_03": wave_invalid_15d < 0.03,
1863
+ "60step_runtime_lt_1200ms": runtime_ms < 1200.0,
1864
+ "all_metrics_finite": bool(
1865
+ np.isfinite(
1866
+ metric_table.select_dtypes(
1867
+ include=[np.number]
1868
+ ).to_numpy()
1869
+ ).all()
1870
+ ),
1871
+ }
1872
+ passed = sum(bool(value) for value in checks.values())
1873
+ architecture_critical = [
1874
+ "all_repaired_explicit_rollouts_finite",
1875
+ "repair_improves_parent_explicit_7d",
1876
+ "repair_improves_parent_explicit_15d",
1877
+ "explicit_beats_single_72h_ge_1pct",
1878
+ "explicit_beats_single_7d_ge_1pct",
1879
+ "explicit_15d_nonworse_than_single",
1880
+ "band_closure_72h_positive",
1881
+ "band_closure_7d_nonnegative",
1882
+ "band_closure_15d_nonnegative",
1883
+ "variance_ratio_7d_ge_0_50",
1884
+ ]
1885
+ product_readiness = [
1886
+ "repaired_7d_beats_persistence",
1887
+ "repaired_7d_persistence_block_positive",
1888
+ "direction_norm_error_15d_lt_0_30",
1889
+ ]
1890
+
1891
+ architecture_qualified = all(
1892
+ checks[key] for key in architecture_critical
1893
+ )
1894
+ product_ready = architecture_qualified and all(
1895
+ checks[key] for key in product_readiness
1896
+ )
1897
+
1898
+ if product_ready and passed >= 23:
1899
+ verdict_name = (
1900
+ "V3_S3_A1_MINIMAL_SCALE_ARCHITECTURE_AND_TRAINING_OBJECTIVE_QUALIFIED"
1901
+ )
1902
+ recommendation = (
1903
+ "Freeze CIDM-v3 and proceed to the medium-scale distributed "
1904
+ "training-pipeline qualification. No architecture changes."
1905
+ )
1906
+ elif architecture_qualified:
1907
+ verdict_name = (
1908
+ "V3_S3_A1_MINIMAL_SCALE_ARCHITECTURE_QUALIFIED_PRODUCT_TRAINING_NOT_YET"
1909
+ )
1910
+ recommendation = (
1911
+ "Freeze the architecture. Proceed to medium-scale multi-season "
1912
+ "training qualification before formal product training."
1913
+ )
1914
+ elif finite and passed >= 17:
1915
+ verdict_name = (
1916
+ "V3_S3_A1_LONG_HORIZON_OBJECTIVE_PARTIALLY_QUALIFIED"
1917
+ )
1918
+ recommendation = (
1919
+ "Keep the same architecture. Do not add modules. The next step "
1920
+ "must be a multi-season medium-scale training qualification, not "
1921
+ "another architecture experiment."
1922
+ )
1923
+ else:
1924
+ verdict_name = (
1925
+ "V3_S3_A1_LONG_HORIZON_OBJECTIVE_NOT_QUALIFIED"
1926
+ )
1927
+ recommendation = (
1928
+ "Do not add modules. Reconsider whether the current explicit-scale "
1929
+ "core offers enough value over the mature Single-State baseline."
1930
+ )
1931
+
1932
+ aggregate = {
1933
+ "scale_vs_single_72h_percent": scale_vs_single_72,
1934
+ "scale_vs_single_7d_percent": scale_vs_single_7d,
1935
+ "scale_vs_single_15d_percent": scale_vs_single_15d,
1936
+ "repair_gain_72h_percent": repair_gain_72,
1937
+ "repair_gain_7d_percent": repair_gain_7d,
1938
+ "repair_gain_15d_percent": repair_gain_15d,
1939
+ "band_gain_72h_percent": band_gain_72,
1940
+ "band_gain_7d_percent": band_gain_7d,
1941
+ "band_gain_15d_percent": band_gain_15d,
1942
+ "repaired_vs_persistence_72h_percent": persistence_gap_72,
1943
+ "repaired_vs_persistence_7d_percent": persistence_gap_7d,
1944
+ "repaired_vs_persistence_15d_percent": persistence_gap_15d,
1945
+ "persistence_gap_closed_7d_percentage_points": (
1946
+ persistence_gap_closed_7d
1947
+ ),
1948
+ "variance_ratio_7d": variance_7d,
1949
+ "variance_ratio_15d": variance_15d,
1950
+ "high_spectral_ratio_15d": high_spectral_15d,
1951
+ "direction_norm_error_15d": direction_error_15d,
1952
+ "wave_invalid_fraction_15d": wave_invalid_15d,
1953
+ "runtime_60step_ms": runtime_ms,
1954
+ "architecture_qualified": architecture_qualified,
1955
+ "product_ready": product_ready,
1956
+ }
1957
+ verdict = {
1958
+ "automatic_verdict": verdict_name,
1959
+ "passed": passed,
1960
+ "total": len(checks),
1961
+ "checks": checks,
1962
+ "architecture_critical_checks": architecture_critical,
1963
+ "product_readiness_checks": product_readiness,
1964
+ "aggregate": aggregate,
1965
+ "frozen_candidate": {
1966
+ "modules": [
1967
+ "MultiScalePhysicalEncoder",
1968
+ "ExplicitScaleInformationState",
1969
+ "SharedScaleConditionedCIDMCore",
1970
+ "MultiStepRecurrence",
1971
+ "BandClosure",
1972
+ "MultiResolutionDecoder",
1973
+ ],
1974
+ "default_off": [
1975
+ "CrossScaleFlux",
1976
+ "FutureBER",
1977
+ "BoundaryBER",
1978
+ "VerticalBER",
1979
+ "SlowMemoryClosure",
1980
+ "VerticalOutputClosure",
1981
+ "CausalVarianceAmplifier",
1982
+ "EventRouter",
1983
+ ],
1984
+ },
1985
+ "next_stage_recommendation": recommendation,
1986
+ }
1987
+ atomic_json(
1988
+ aggregate,
1989
+ output_dir / "S3A1_main_aggregate.json",
1990
+ )
1991
+ atomic_json(
1992
+ verdict,
1993
+ output_dir / "S3A1_verdict.json",
1994
+ )
1995
+
1996
+ stage(8, 9, "图表与架构冻结合同")
1997
+ plt.figure(figsize=(11, 6))
1998
+ for method in METHODS:
1999
+ current = summary[summary.method == method]
2000
+ plt.plot(
2001
+ current.horizon,
2002
+ current.rmse,
2003
+ marker="o",
2004
+ label=method,
2005
+ )
2006
+ plt.xlabel("Rollout steps (6 h each)")
2007
+ plt.ylabel("RMSE")
2008
+ plt.legend()
2009
+ plt.tight_layout()
2010
+ plt.savefig(
2011
+ output_dir / "figures" / "S3A1_RMSE_growth.png",
2012
+ dpi=180,
2013
+ )
2014
+ plt.close()
2015
+
2016
+ plt.figure(figsize=(11, 6))
2017
+ for method in [
2018
+ "persistence",
2019
+ "repaired_single",
2020
+ "repaired_explicit_band",
2021
+ ]:
2022
+ current = summary[summary.method == method]
2023
+ plt.plot(
2024
+ current.horizon,
2025
+ current.variance_ratio,
2026
+ marker="o",
2027
+ label=method,
2028
+ )
2029
+ plt.axhline(1.0, linewidth=1)
2030
+ plt.xlabel("Rollout steps (6 h each)")
2031
+ plt.ylabel("Variance ratio")
2032
+ plt.legend()
2033
+ plt.tight_layout()
2034
+ plt.savefig(
2035
+ output_dir / "figures" / "S3A1_variance_ratio.png",
2036
+ dpi=180,
2037
+ )
2038
+ plt.close()
2039
+
2040
+ atomic_json(
2041
+ {
2042
+ "architecture_name": "CIDM-v3-SCS-Minimal",
2043
+ "architecture_changed_in_S3A1": False,
2044
+ "modules": [
2045
+ "MultiScalePhysicalEncoder",
2046
+ "ExplicitScaleInformationState",
2047
+ "SharedScaleConditionedCIDMCore",
2048
+ "MultiStepRecurrence",
2049
+ "BandClosure",
2050
+ "MultiResolutionDecoder",
2051
+ ],
2052
+ "training_contract": {
2053
+ "optimizer_state_persistent_across_epochs": True,
2054
+ "rollout_curriculum": horizon_schedule(args),
2055
+ "persistence_relative_skill": True,
2056
+ "increment_loss": True,
2057
+ "spectral_and_variance_losses": True,
2058
+ "wave_domain_losses": True,
2059
+ },
2060
+ "grid": "native 1/12 degree",
2061
+ "base_time_step_hours": 6,
2062
+ "maximum_training_horizon_steps": args.max_horizon,
2063
+ },
2064
+ output_dir
2065
+ / "deployment"
2066
+ / "CIDM_v3_candidate_architecture_and_training_contract.json",
2067
+ )
2068
+
2069
+ safe_args = dict(vars(args))
2070
+ safe_args["hf_token"] = "<redacted>"
2071
+ atomic_json(
2072
+ {
2073
+ "experiment": "CIDM_v3_SCS_V3_S3_A1",
2074
+ "created_at": pd.Timestamp.now().isoformat(),
2075
+ "device": str(device),
2076
+ "arguments": safe_args,
2077
+ "security": "No plaintext access token is written.",
2078
+ },
2079
+ output_dir / "S3A1_manifest.json",
2080
+ )
2081
+
2082
+ stage(9, 9, "结果打包")
2083
+ package = output_dir.parent / f"{output_dir.name}.zip"
2084
+ package.unlink(missing_ok=True)
2085
+ with zipfile.ZipFile(package, "w", zipfile.ZIP_DEFLATED) as archive:
2086
+ for path in output_dir.rglob("*"):
2087
+ if path.is_file():
2088
+ archive.write(
2089
+ path,
2090
+ path.relative_to(output_dir.parent),
2091
+ )
2092
+ print(
2093
+ json.dumps(
2094
+ verdict,
2095
+ ensure_ascii=False,
2096
+ indent=2,
2097
+ default=json_default,
2098
+ ),
2099
+ flush=True,
2100
+ )
2101
+ print(f"[result] {package}", flush=True)
2102
+ except Exception:
2103
+ trace = traceback.format_exc()
2104
+ (output_dir / "failure_traceback.txt").write_text(
2105
+ trace, encoding="utf-8"
2106
+ )
2107
+ print(trace, flush=True)
2108
+ raise
2109
+
2110
+
2111
+ if __name__ == "__main__":
2112
+ main()