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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
CIDM-v3 SCS V3-S2-A1
|
| 5 |
+
真实外部输入 BER、未来强迫因果性与方差恢复资格实验
|
| 6 |
+
=====================================================
|
| 7 |
+
|
| 8 |
+
父链:
|
| 9 |
+
- S2-A0 内部状态冻结探针;
|
| 10 |
+
- S2-A0 all_required 历史外部信息适配器;
|
| 11 |
+
- S2-A0 四季 CMEMS + ERA5 prepared cache。
|
| 12 |
+
|
| 13 |
+
本轮只训练零初始化的新 BER:
|
| 14 |
+
- 未来大气强迫分支;
|
| 15 |
+
- 未来域外海洋边界分支;
|
| 16 |
+
- 当前垂向背景条件;
|
| 17 |
+
- 来源可用性/不确定度门;
|
| 18 |
+
- 有界变量组方差恢复闭合。
|
| 19 |
+
|
| 20 |
+
严格区分:
|
| 21 |
+
- oracle_future:真实未来再分析,表示信息上限;
|
| 22 |
+
- degraded_future:加入时滞、噪声和不确定度,作为业务预报代理;
|
| 23 |
+
- history_only:只使用当前及历史外部信息;
|
| 24 |
+
- shuffled_future:打乱未来外部输入,执行因果反证。
|
| 25 |
+
|
| 26 |
+
注意:
|
| 27 |
+
本轮仍是 1/4° BER 架构资格,不是正式 1/12° 产品训练。
|
| 28 |
+
"""
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
import copy
|
| 33 |
+
import dataclasses
|
| 34 |
+
import datetime as dt
|
| 35 |
+
import io
|
| 36 |
+
import json
|
| 37 |
+
import math
|
| 38 |
+
import os
|
| 39 |
+
import random
|
| 40 |
+
import shutil
|
| 41 |
+
import time
|
| 42 |
+
import traceback
|
| 43 |
+
import zipfile
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
|
| 46 |
+
|
| 47 |
+
import numpy as np
|
| 48 |
+
import pandas as pd
|
| 49 |
+
import torch
|
| 50 |
+
import torch.nn as nn
|
| 51 |
+
import torch.nn.functional as F
|
| 52 |
+
from torch.utils.data import DataLoader, Dataset
|
| 53 |
+
|
| 54 |
+
import matplotlib
|
| 55 |
+
matplotlib.use("Agg")
|
| 56 |
+
import matplotlib.pyplot as plt
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
WINDOWS = [
|
| 60 |
+
{"name": "winter", "role": "train"},
|
| 61 |
+
{"name": "spring", "role": "train"},
|
| 62 |
+
{"name": "summer", "role": "validation"},
|
| 63 |
+
{"name": "autumn", "role": "test"},
|
| 64 |
+
]
|
| 65 |
+
HORIZONS = [1, 4, 12]
|
| 66 |
+
INTERNAL_VARIABLES = [
|
| 67 |
+
"sst", "sss", "ssh", "u_surface", "v_surface",
|
| 68 |
+
"u_100m", "v_100m", "temperature_100m", "salinity_100m",
|
| 69 |
+
"significant_wave_height", "peak_wave_period", "tm02",
|
| 70 |
+
"peak_wave_direction_sin", "peak_wave_direction_cos",
|
| 71 |
+
"wind_sea_significant_height", "primary_swell_significant_height",
|
| 72 |
+
]
|
| 73 |
+
SOURCE_VARIABLES = {
|
| 74 |
+
"atmosphere": [
|
| 75 |
+
"u10", "v10", "wind_speed", "tau_x", "tau_y", "msl",
|
| 76 |
+
"net_heat_flux", "freshwater_flux", "wind_stress_curl",
|
| 77 |
+
],
|
| 78 |
+
"boundary": [
|
| 79 |
+
"boundary_normal_inflow", "boundary_ssh", "boundary_sst", "boundary_sss",
|
| 80 |
+
"boundary_u_surface", "boundary_v_surface",
|
| 81 |
+
"boundary_temperature_100m", "boundary_salinity_100m",
|
| 82 |
+
"boundary_u_100m", "boundary_v_100m",
|
| 83 |
+
],
|
| 84 |
+
"vertical": [
|
| 85 |
+
"mld_temperature_proxy", "thermocline_depth_proxy", "ohc_0_200_proxy",
|
| 86 |
+
"temperature_0_100_difference", "salinity_0_100_difference",
|
| 87 |
+
"current_shear_0_100", "density_stratification_0_100",
|
| 88 |
+
"temperature_100_200_difference", "salinity_100_200_difference",
|
| 89 |
+
"current_shear_100_200",
|
| 90 |
+
],
|
| 91 |
+
"tide": [
|
| 92 |
+
"tide_elevation", "tide_u", "tide_v",
|
| 93 |
+
"m2_sin", "m2_cos", "s2_sin", "s2_cos",
|
| 94 |
+
"k1_sin", "k1_cos", "o1_sin", "o1_cos",
|
| 95 |
+
],
|
| 96 |
+
"river": ["river_discharge_map", "river_discharge_anomaly"],
|
| 97 |
+
"events": ["event_intensity", "event_confidence", "event_type_code"],
|
| 98 |
+
}
|
| 99 |
+
SOURCE_KEYS = list(SOURCE_VARIABLES)
|
| 100 |
+
REQUIRED_SOURCES = ["atmosphere", "boundary", "vertical"]
|
| 101 |
+
GROUPS = {
|
| 102 |
+
"surface_thermohaline": [0, 1, 2],
|
| 103 |
+
"currents": [3, 4, 5, 6],
|
| 104 |
+
"subsurface_thermohaline": [7, 8],
|
| 105 |
+
"waves": list(range(9, 16)),
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def json_default(value: Any) -> Any:
|
| 110 |
+
if isinstance(value, Path):
|
| 111 |
+
return str(value)
|
| 112 |
+
if isinstance(value, (np.integer, np.floating, np.bool_)):
|
| 113 |
+
return value.item()
|
| 114 |
+
if isinstance(value, np.ndarray):
|
| 115 |
+
return value.tolist()
|
| 116 |
+
if isinstance(value, (pd.Timestamp, dt.datetime, dt.date)):
|
| 117 |
+
return pd.Timestamp(value).isoformat()
|
| 118 |
+
raise TypeError(type(value).__name__)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def atomic_json(payload: Any, path: Path) -> None:
|
| 122 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 123 |
+
temp = path.with_suffix(path.suffix + ".tmp")
|
| 124 |
+
temp.write_text(
|
| 125 |
+
json.dumps(payload, ensure_ascii=False, indent=2, default=json_default),
|
| 126 |
+
encoding="utf-8",
|
| 127 |
+
)
|
| 128 |
+
os.replace(temp, path)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def stage(index: int, total: int, title: str) -> None:
|
| 132 |
+
print(f"\n[V3-S2-A1] 阶段 {index}/{total}:{title}", flush=True)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def seed_everything(seed: int) -> None:
|
| 136 |
+
random.seed(seed)
|
| 137 |
+
np.random.seed(seed)
|
| 138 |
+
torch.manual_seed(seed)
|
| 139 |
+
if torch.cuda.is_available():
|
| 140 |
+
torch.cuda.manual_seed_all(seed)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def ensure_hf_assets(args: argparse.Namespace) -> Dict[str, Any]:
|
| 144 |
+
"""优先复用本地资产;缺失时从用户的 HF Dataset 仓库按文件下载。"""
|
| 145 |
+
cache = Path(args.cache_dir)
|
| 146 |
+
prepared = cache / "prepared"
|
| 147 |
+
prepared.mkdir(parents=True, exist_ok=True)
|
| 148 |
+
a0_zip = Path(args.a0_zip)
|
| 149 |
+
needed: List[Tuple[str, Path]] = [("CIDM_v3_SCS_V3_S2_A0.zip", a0_zip)]
|
| 150 |
+
for window in WINDOWS:
|
| 151 |
+
name = window["name"]
|
| 152 |
+
needed.extend([
|
| 153 |
+
(f"Cache/prepared/{name}_cmems.npz", prepared / f"{name}_cmems.npz"),
|
| 154 |
+
(
|
| 155 |
+
f"Cache/prepared/{name}_atmosphere_aligned.npz",
|
| 156 |
+
prepared / f"{name}_atmosphere_aligned.npz",
|
| 157 |
+
),
|
| 158 |
+
(f"Cache/prepared/{name}_tide.npz", prepared / f"{name}_tide.npz"),
|
| 159 |
+
(f"Cache/prepared/{name}_river.npz", prepared / f"{name}_river.npz"),
|
| 160 |
+
(f"Cache/prepared/{name}_events.npz", prepared / f"{name}_events.npz"),
|
| 161 |
+
])
|
| 162 |
+
|
| 163 |
+
missing = [(repo_path, local_path) for repo_path, local_path in needed if not local_path.is_file()]
|
| 164 |
+
report = {
|
| 165 |
+
"repo_id": args.hf_repo_id,
|
| 166 |
+
"requested": len(needed),
|
| 167 |
+
"already_local": len(needed) - len(missing),
|
| 168 |
+
"downloaded": [],
|
| 169 |
+
}
|
| 170 |
+
if missing:
|
| 171 |
+
if not args.hf_repo_id:
|
| 172 |
+
raise RuntimeError(
|
| 173 |
+
"Prepared cache or A0 result is missing and --hf_repo_id is empty."
|
| 174 |
+
)
|
| 175 |
+
from huggingface_hub import hf_hub_download
|
| 176 |
+
token = args.hf_token or os.environ.get("HF_TOKEN") or None
|
| 177 |
+
for repo_path, local_path in missing:
|
| 178 |
+
print(f"[HF download] {repo_path}", flush=True)
|
| 179 |
+
downloaded = Path(
|
| 180 |
+
hf_hub_download(
|
| 181 |
+
repo_id=args.hf_repo_id,
|
| 182 |
+
filename=repo_path,
|
| 183 |
+
repo_type="dataset",
|
| 184 |
+
token=token,
|
| 185 |
+
)
|
| 186 |
+
)
|
| 187 |
+
local_path.parent.mkdir(parents=True, exist_ok=True)
|
| 188 |
+
if local_path.exists() or local_path.is_symlink():
|
| 189 |
+
local_path.unlink()
|
| 190 |
+
try:
|
| 191 |
+
local_path.symlink_to(downloaded)
|
| 192 |
+
except Exception:
|
| 193 |
+
shutil.copy2(downloaded, local_path)
|
| 194 |
+
report["downloaded"].append(repo_path)
|
| 195 |
+
|
| 196 |
+
for repo_path, local_path in needed:
|
| 197 |
+
if not local_path.is_file() or local_path.stat().st_size <= 128:
|
| 198 |
+
raise RuntimeError(f"Asset missing or invalid: {repo_path} -> {local_path}")
|
| 199 |
+
return report
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def extract_a0_assets(a0_zip: Path, work_dir: Path) -> Dict[str, Path]:
|
| 203 |
+
work_dir.mkdir(parents=True, exist_ok=True)
|
| 204 |
+
required = [
|
| 205 |
+
"CIDM_v3_SCS_V3_S2_A0/audits/S2A0_normalization_stats.npz",
|
| 206 |
+
"CIDM_v3_SCS_V3_S2_A0/S2A0_verdict.json",
|
| 207 |
+
"CIDM_v3_SCS_V3_S2_A0/S2A0_main_aggregate.json",
|
| 208 |
+
]
|
| 209 |
+
for seed in [20260910, 20260911, 20260912]:
|
| 210 |
+
required.extend([
|
| 211 |
+
f"CIDM_v3_SCS_V3_S2_A0/checkpoints/baseline/seed_{seed}.pt",
|
| 212 |
+
f"CIDM_v3_SCS_V3_S2_A0/checkpoints/all_required/seed_{seed}.pt",
|
| 213 |
+
])
|
| 214 |
+
with zipfile.ZipFile(a0_zip) as archive:
|
| 215 |
+
names = set(archive.namelist())
|
| 216 |
+
missing = [name for name in required if name not in names]
|
| 217 |
+
if missing:
|
| 218 |
+
raise RuntimeError(f"A0 result zip misses required entries: {missing}")
|
| 219 |
+
for name in required:
|
| 220 |
+
target = work_dir / name
|
| 221 |
+
if not target.is_file():
|
| 222 |
+
archive.extract(name, work_dir)
|
| 223 |
+
root = work_dir / "CIDM_v3_SCS_V3_S2_A0"
|
| 224 |
+
return {
|
| 225 |
+
"root": root,
|
| 226 |
+
"stats": root / "audits" / "S2A0_normalization_stats.npz",
|
| 227 |
+
"verdict": root / "S2A0_verdict.json",
|
| 228 |
+
"aggregate": root / "S2A0_main_aggregate.json",
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@dataclasses.dataclass
|
| 233 |
+
class WindowData:
|
| 234 |
+
name: str
|
| 235 |
+
role: str
|
| 236 |
+
time: np.ndarray
|
| 237 |
+
latitude: np.ndarray
|
| 238 |
+
longitude: np.ndarray
|
| 239 |
+
internal: np.ndarray
|
| 240 |
+
ocean_mask: np.ndarray
|
| 241 |
+
sources: Dict[str, np.ndarray]
|
| 242 |
+
actual: Dict[str, bool]
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def load_window(cache: Path, spec: Mapping[str, str]) -> WindowData:
|
| 246 |
+
name = spec["name"]
|
| 247 |
+
prepared = cache / "prepared"
|
| 248 |
+
cmems = np.load(prepared / f"{name}_cmems.npz")
|
| 249 |
+
atmosphere = np.load(prepared / f"{name}_atmosphere_aligned.npz")
|
| 250 |
+
tide = np.load(prepared / f"{name}_tide.npz")
|
| 251 |
+
river = np.load(prepared / f"{name}_river.npz")
|
| 252 |
+
events = np.load(prepared / f"{name}_events.npz")
|
| 253 |
+
|
| 254 |
+
arrays = {
|
| 255 |
+
"atmosphere": atmosphere["atmosphere"].astype(np.float32),
|
| 256 |
+
"boundary": cmems["boundary"].astype(np.float32),
|
| 257 |
+
"vertical": cmems["vertical"].astype(np.float32),
|
| 258 |
+
"tide": tide["tide"].astype(np.float32),
|
| 259 |
+
"river": river["river"].astype(np.float32),
|
| 260 |
+
"events": events["events"].astype(np.float32),
|
| 261 |
+
}
|
| 262 |
+
lengths = {key: value.shape[0] for key, value in arrays.items()}
|
| 263 |
+
lengths["internal"] = cmems["internal"].shape[0]
|
| 264 |
+
if len(set(lengths.values())) != 1:
|
| 265 |
+
raise RuntimeError(f"Window {name} time-length mismatch: {lengths}")
|
| 266 |
+
return WindowData(
|
| 267 |
+
name=name,
|
| 268 |
+
role=spec["role"],
|
| 269 |
+
time=cmems["time"].astype("datetime64[ns]"),
|
| 270 |
+
latitude=cmems["latitude"].astype(np.float32),
|
| 271 |
+
longitude=cmems["longitude"].astype(np.float32),
|
| 272 |
+
internal=cmems["internal"].astype(np.float32),
|
| 273 |
+
ocean_mask=cmems["ocean_mask"].astype(np.float32),
|
| 274 |
+
sources=arrays,
|
| 275 |
+
actual={
|
| 276 |
+
"atmosphere": True,
|
| 277 |
+
"boundary": True,
|
| 278 |
+
"vertical": True,
|
| 279 |
+
"tide": bool(int(tide["actual_spatial_tide"][0])),
|
| 280 |
+
"river": bool(int(river["available"][0])),
|
| 281 |
+
"events": bool(int(events["available"][0])),
|
| 282 |
+
},
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class SequenceIndex:
|
| 287 |
+
def __init__(self, windows: Sequence[WindowData], history: int):
|
| 288 |
+
self.windows = list(windows)
|
| 289 |
+
self.history = int(history)
|
| 290 |
+
self.records: List[Tuple[int, int]] = []
|
| 291 |
+
max_h = max(HORIZONS)
|
| 292 |
+
for wi, window in enumerate(self.windows):
|
| 293 |
+
for t in range(self.history - 1, len(window.time) - max_h):
|
| 294 |
+
self.records.append((wi, t))
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class A1Dataset(Dataset):
|
| 298 |
+
def __init__(
|
| 299 |
+
self,
|
| 300 |
+
index: SequenceIndex,
|
| 301 |
+
internal_mean: np.ndarray,
|
| 302 |
+
internal_std: np.ndarray,
|
| 303 |
+
source_stats: Mapping[str, Tuple[np.ndarray, np.ndarray]],
|
| 304 |
+
):
|
| 305 |
+
self.index = index
|
| 306 |
+
self.internal_mean = internal_mean
|
| 307 |
+
self.internal_std = internal_std
|
| 308 |
+
self.source_stats = source_stats
|
| 309 |
+
|
| 310 |
+
def __len__(self) -> int:
|
| 311 |
+
return len(self.index.records)
|
| 312 |
+
|
| 313 |
+
@staticmethod
|
| 314 |
+
def norm(value: np.ndarray, mean: np.ndarray, std: np.ndarray) -> np.ndarray:
|
| 315 |
+
return (
|
| 316 |
+
np.nan_to_num(value, nan=0.0)
|
| 317 |
+
- mean[None, :, None, None]
|
| 318 |
+
) / std[None, :, None, None]
|
| 319 |
+
|
| 320 |
+
def __getitem__(self, item: int) -> Dict[str, torch.Tensor]:
|
| 321 |
+
wi, t = self.index.records[item]
|
| 322 |
+
window = self.index.windows[wi]
|
| 323 |
+
h = self.index.history
|
| 324 |
+
|
| 325 |
+
internal_history = self.norm(
|
| 326 |
+
window.internal[t - h + 1:t + 1],
|
| 327 |
+
self.internal_mean,
|
| 328 |
+
self.internal_std,
|
| 329 |
+
)
|
| 330 |
+
targets = np.stack(
|
| 331 |
+
[
|
| 332 |
+
(window.internal[t + horizon] - self.internal_mean[:, None, None])
|
| 333 |
+
/ self.internal_std[:, None, None]
|
| 334 |
+
for horizon in HORIZONS
|
| 335 |
+
],
|
| 336 |
+
axis=0,
|
| 337 |
+
).astype(np.float32)
|
| 338 |
+
|
| 339 |
+
result: Dict[str, torch.Tensor] = {
|
| 340 |
+
"internal": torch.from_numpy(
|
| 341 |
+
internal_history.reshape(-1, *internal_history.shape[-2:]).astype(np.float32)
|
| 342 |
+
),
|
| 343 |
+
"target": torch.from_numpy(targets),
|
| 344 |
+
"mask": torch.from_numpy(window.ocean_mask[t].astype(np.float32)),
|
| 345 |
+
"sample_index": torch.tensor(item, dtype=torch.long),
|
| 346 |
+
"time_ns": torch.tensor(
|
| 347 |
+
window.time[t].astype("datetime64[ns]").astype(np.int64),
|
| 348 |
+
dtype=torch.long,
|
| 349 |
+
),
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
for source, values in window.sources.items():
|
| 353 |
+
mean, std = self.source_stats[source]
|
| 354 |
+
history = self.norm(values[t - h + 1:t + 1], mean, std).astype(np.float32)
|
| 355 |
+
actual = 1.0 if window.actual[source] else 0.0
|
| 356 |
+
uncertainty = (
|
| 357 |
+
0.10 if source in REQUIRED_SOURCES
|
| 358 |
+
else (0.25 if actual else 1.0)
|
| 359 |
+
)
|
| 360 |
+
availability = np.full(
|
| 361 |
+
(h, 1, *history.shape[-2:]), actual, dtype=np.float32
|
| 362 |
+
)
|
| 363 |
+
uncertainty_map = np.full(
|
| 364 |
+
(h, 1, *history.shape[-2:]), uncertainty, dtype=np.float32
|
| 365 |
+
)
|
| 366 |
+
parent_source = np.concatenate(
|
| 367 |
+
[history, availability, uncertainty_map], axis=1
|
| 368 |
+
)
|
| 369 |
+
result[f"parent_{source}"] = torch.from_numpy(
|
| 370 |
+
parent_source.reshape(-1, *history.shape[-2:]).astype(np.float32)
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
# Future external trajectories use t..t+12. Vertical future truth is not used.
|
| 374 |
+
for source in ["atmosphere", "boundary"]:
|
| 375 |
+
mean, std = self.source_stats[source]
|
| 376 |
+
future = self.norm(
|
| 377 |
+
window.sources[source][t:t + max(HORIZONS) + 1],
|
| 378 |
+
mean,
|
| 379 |
+
std,
|
| 380 |
+
).astype(np.float32)
|
| 381 |
+
result[f"future_{source}"] = torch.from_numpy(future)
|
| 382 |
+
|
| 383 |
+
mean, std = self.source_stats["vertical"]
|
| 384 |
+
current_vertical = (
|
| 385 |
+
window.sources["vertical"][t] - mean[:, None, None]
|
| 386 |
+
) / std[:, None, None]
|
| 387 |
+
result["current_vertical"] = torch.from_numpy(
|
| 388 |
+
np.nan_to_num(current_vertical).astype(np.float32)
|
| 389 |
+
)
|
| 390 |
+
return result
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class DepthwiseBlock(nn.Module):
|
| 394 |
+
def __init__(self, channels: int):
|
| 395 |
+
super().__init__()
|
| 396 |
+
self.norm = nn.GroupNorm(1, channels)
|
| 397 |
+
self.dw = nn.Conv2d(channels, channels, 3, padding=1, groups=channels)
|
| 398 |
+
self.pw1 = nn.Conv2d(channels, channels * 2, 1)
|
| 399 |
+
self.pw2 = nn.Conv2d(channels * 2, channels, 1)
|
| 400 |
+
nn.init.zeros_(self.pw2.weight)
|
| 401 |
+
nn.init.zeros_(self.pw2.bias)
|
| 402 |
+
|
| 403 |
+
def forward(self, value: torch.Tensor) -> torch.Tensor:
|
| 404 |
+
update = self.dw(F.silu(self.norm(value)))
|
| 405 |
+
update = self.pw2(F.silu(self.pw1(update)))
|
| 406 |
+
return value + update
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
class InternalProbe(nn.Module):
|
| 410 |
+
def __init__(self, history: int = 4, channels: int = 16,
|
| 411 |
+
hidden: int = 48, horizons: int = 3):
|
| 412 |
+
super().__init__()
|
| 413 |
+
self.horizons = horizons
|
| 414 |
+
self.channels = channels
|
| 415 |
+
self.stem = nn.Conv2d(history * channels, hidden, 3, padding=1)
|
| 416 |
+
self.blocks = nn.Sequential(*[DepthwiseBlock(hidden) for _ in range(3)])
|
| 417 |
+
self.head = nn.Conv2d(hidden, horizons * channels, 1)
|
| 418 |
+
|
| 419 |
+
def forward_features(self, value: torch.Tensor) -> torch.Tensor:
|
| 420 |
+
return self.blocks(self.stem(value))
|
| 421 |
+
|
| 422 |
+
def forward(self, value: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 423 |
+
features = self.forward_features(value)
|
| 424 |
+
prediction = self.head(features)
|
| 425 |
+
b, _, h, w = prediction.shape
|
| 426 |
+
return (
|
| 427 |
+
prediction.reshape(b, self.horizons, self.channels, h, w),
|
| 428 |
+
features,
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class SourceBranch(nn.Module):
|
| 433 |
+
def __init__(self, in_channels: int, out_channels: int):
|
| 434 |
+
super().__init__()
|
| 435 |
+
self.net = nn.Sequential(
|
| 436 |
+
nn.Conv2d(in_channels, out_channels, 1),
|
| 437 |
+
nn.GroupNorm(1, out_channels),
|
| 438 |
+
nn.SiLU(),
|
| 439 |
+
nn.Conv2d(
|
| 440 |
+
out_channels, out_channels, 3,
|
| 441 |
+
padding=1, groups=out_channels,
|
| 442 |
+
),
|
| 443 |
+
nn.Conv2d(out_channels, out_channels, 1),
|
| 444 |
+
nn.SiLU(),
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
def forward(self, value: torch.Tensor) -> torch.Tensor:
|
| 448 |
+
return self.net(value)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class A0ExternalResidualAdapter(nn.Module):
|
| 452 |
+
"""Exact S2-A0 adapter reconstruction."""
|
| 453 |
+
def __init__(
|
| 454 |
+
self,
|
| 455 |
+
source_channels: Mapping[str, int],
|
| 456 |
+
history: int = 4,
|
| 457 |
+
internal_hidden: int = 48,
|
| 458 |
+
branch_hidden: int = 16,
|
| 459 |
+
channels: int = 16,
|
| 460 |
+
horizons: int = 3,
|
| 461 |
+
):
|
| 462 |
+
super().__init__()
|
| 463 |
+
self.source_keys = list(source_channels)
|
| 464 |
+
self.branches = nn.ModuleDict({
|
| 465 |
+
key: SourceBranch(history * value, branch_hidden)
|
| 466 |
+
for key, value in source_channels.items()
|
| 467 |
+
})
|
| 468 |
+
fusion_in = internal_hidden + branch_hidden * len(self.source_keys)
|
| 469 |
+
self.fusion = nn.Sequential(
|
| 470 |
+
nn.Conv2d(fusion_in, internal_hidden, 1),
|
| 471 |
+
DepthwiseBlock(internal_hidden),
|
| 472 |
+
DepthwiseBlock(internal_hidden),
|
| 473 |
+
)
|
| 474 |
+
self.head = nn.Conv2d(internal_hidden, horizons * channels, 1)
|
| 475 |
+
self.ratio_logit = nn.Parameter(torch.tensor(-1.5))
|
| 476 |
+
self.channels = channels
|
| 477 |
+
self.horizons = horizons
|
| 478 |
+
|
| 479 |
+
def forward(
|
| 480 |
+
self,
|
| 481 |
+
internal_features: torch.Tensor,
|
| 482 |
+
sources: Mapping[str, torch.Tensor],
|
| 483 |
+
enabled: Sequence[str],
|
| 484 |
+
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
|
| 485 |
+
enabled_set = set(enabled)
|
| 486 |
+
values = []
|
| 487 |
+
energies: Dict[str, torch.Tensor] = {}
|
| 488 |
+
for key in self.source_keys:
|
| 489 |
+
feature = self.branches[key](sources[key])
|
| 490 |
+
if key not in enabled_set:
|
| 491 |
+
feature = torch.zeros_like(feature)
|
| 492 |
+
values.append(feature)
|
| 493 |
+
energies[key] = feature.square().mean().sqrt()
|
| 494 |
+
fused = self.fusion(torch.cat([internal_features] + values, dim=1))
|
| 495 |
+
raw = self.head(fused)
|
| 496 |
+
cap = 0.02 + 0.48 * torch.sigmoid(self.ratio_logit)
|
| 497 |
+
update = cap * torch.tanh(raw)
|
| 498 |
+
b, _, h, w = update.shape
|
| 499 |
+
return (
|
| 500 |
+
update.reshape(b, self.horizons, self.channels, h, w),
|
| 501 |
+
{"adapter_cap": cap, **{f"{key}_energy": value for key, value in energies.items()}},
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
class FrozenA0Parent(nn.Module):
|
| 506 |
+
def __init__(self, baseline: InternalProbe, adapter: A0ExternalResidualAdapter):
|
| 507 |
+
super().__init__()
|
| 508 |
+
self.baseline = baseline
|
| 509 |
+
self.adapter = adapter
|
| 510 |
+
for parameter in self.parameters():
|
| 511 |
+
parameter.requires_grad = False
|
| 512 |
+
|
| 513 |
+
def forward(
|
| 514 |
+
self,
|
| 515 |
+
internal: torch.Tensor,
|
| 516 |
+
parent_sources: Mapping[str, torch.Tensor],
|
| 517 |
+
) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, torch.Tensor]]:
|
| 518 |
+
base, features = self.baseline(internal)
|
| 519 |
+
update, diagnostics = self.adapter(
|
| 520 |
+
features, parent_sources, REQUIRED_SOURCES
|
| 521 |
+
)
|
| 522 |
+
return base + update, features, {"a0_update": update, **diagnostics}
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
class TemporalSourceEncoder(nn.Module):
|
| 526 |
+
def __init__(self, source_channels: int, hidden: int):
|
| 527 |
+
super().__init__()
|
| 528 |
+
self.hidden = hidden
|
| 529 |
+
self.stem = nn.Sequential(
|
| 530 |
+
nn.Conv2d(source_channels + 2, hidden, 1),
|
| 531 |
+
nn.GroupNorm(1, hidden),
|
| 532 |
+
nn.SiLU(),
|
| 533 |
+
DepthwiseBlock(hidden),
|
| 534 |
+
)
|
| 535 |
+
self.temporal_logits = nn.Parameter(torch.zeros(len(HORIZONS), max(HORIZONS) + 1))
|
| 536 |
+
|
| 537 |
+
def forward(
|
| 538 |
+
self,
|
| 539 |
+
sequence: torch.Tensor,
|
| 540 |
+
availability: torch.Tensor,
|
| 541 |
+
uncertainty: torch.Tensor,
|
| 542 |
+
) -> torch.Tensor:
|
| 543 |
+
# sequence [B,T,C,H,W]
|
| 544 |
+
b, t, _, h, w = sequence.shape
|
| 545 |
+
availability_map = availability[:, None, None, None, None].expand(
|
| 546 |
+
b, t, 1, h, w
|
| 547 |
+
)
|
| 548 |
+
uncertainty_map = uncertainty[:, None, None, None, None].expand(
|
| 549 |
+
b, t, 1, h, w
|
| 550 |
+
)
|
| 551 |
+
value = torch.cat([sequence, availability_map, uncertainty_map], dim=2)
|
| 552 |
+
encoded = self.stem(value.reshape(b * t, value.shape[2], h, w))
|
| 553 |
+
encoded = encoded.reshape(b, t, self.hidden, h, w)
|
| 554 |
+
|
| 555 |
+
outputs = []
|
| 556 |
+
for hi, horizon in enumerate(HORIZONS):
|
| 557 |
+
allowed = min(horizon + 1, t)
|
| 558 |
+
weights = torch.softmax(self.temporal_logits[hi, :allowed], dim=0)
|
| 559 |
+
outputs.append(
|
| 560 |
+
(encoded[:, :allowed] * weights[None, :, None, None, None]).sum(dim=1)
|
| 561 |
+
)
|
| 562 |
+
return torch.stack(outputs, dim=1)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
class HorizonFusionHead(nn.Module):
|
| 566 |
+
def __init__(self, input_channels: int, hidden: int, output_channels: int):
|
| 567 |
+
super().__init__()
|
| 568 |
+
self.net = nn.Sequential(
|
| 569 |
+
nn.Conv2d(input_channels, hidden, 1),
|
| 570 |
+
nn.GroupNorm(1, hidden),
|
| 571 |
+
nn.SiLU(),
|
| 572 |
+
DepthwiseBlock(hidden),
|
| 573 |
+
nn.Conv2d(hidden, output_channels, 1),
|
| 574 |
+
)
|
| 575 |
+
nn.init.zeros_(self.net[-1].weight)
|
| 576 |
+
nn.init.zeros_(self.net[-1].bias)
|
| 577 |
+
|
| 578 |
+
def forward(self, value: torch.Tensor) -> torch.Tensor:
|
| 579 |
+
b, horizon_count, c, h, w = value.shape
|
| 580 |
+
output = self.net(value.reshape(b * horizon_count, c, h, w))
|
| 581 |
+
return output.reshape(b, horizon_count, output.shape[1], h, w)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
class OpenSystemBER(nn.Module):
|
| 585 |
+
def __init__(
|
| 586 |
+
self,
|
| 587 |
+
parent: FrozenA0Parent,
|
| 588 |
+
internal_hidden: int = 48,
|
| 589 |
+
source_hidden: int = 24,
|
| 590 |
+
fusion_hidden: int = 48,
|
| 591 |
+
):
|
| 592 |
+
super().__init__()
|
| 593 |
+
self.parent = parent
|
| 594 |
+
self.atmosphere_encoder = TemporalSourceEncoder(9, source_hidden)
|
| 595 |
+
self.boundary_encoder = TemporalSourceEncoder(10, source_hidden)
|
| 596 |
+
self.vertical_encoder = nn.Sequential(
|
| 597 |
+
nn.Conv2d(10, source_hidden, 1),
|
| 598 |
+
nn.GroupNorm(1, source_hidden),
|
| 599 |
+
nn.SiLU(),
|
| 600 |
+
DepthwiseBlock(source_hidden),
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
source_input = internal_hidden + source_hidden * 2
|
| 604 |
+
self.atmosphere_head = HorizonFusionHead(
|
| 605 |
+
source_input, fusion_hidden, len(INTERNAL_VARIABLES)
|
| 606 |
+
)
|
| 607 |
+
self.boundary_head = HorizonFusionHead(
|
| 608 |
+
source_input, fusion_hidden, len(INTERNAL_VARIABLES)
|
| 609 |
+
)
|
| 610 |
+
self.vertical_head = HorizonFusionHead(
|
| 611 |
+
internal_hidden + source_hidden,
|
| 612 |
+
fusion_hidden,
|
| 613 |
+
len(INTERNAL_VARIABLES),
|
| 614 |
+
)
|
| 615 |
+
interaction_input = internal_hidden + source_hidden * 3
|
| 616 |
+
self.interaction_head = HorizonFusionHead(
|
| 617 |
+
interaction_input, fusion_hidden, len(INTERNAL_VARIABLES)
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
gate_input = internal_hidden + source_hidden * 3 + 4
|
| 621 |
+
self.gate_mlp = nn.Sequential(
|
| 622 |
+
nn.Linear(gate_input, fusion_hidden),
|
| 623 |
+
nn.SiLU(),
|
| 624 |
+
nn.Linear(fusion_hidden, len(HORIZONS) * 4),
|
| 625 |
+
)
|
| 626 |
+
nn.init.zeros_(self.gate_mlp[-1].weight)
|
| 627 |
+
nn.init.constant_(self.gate_mlp[-1].bias, -1.5)
|
| 628 |
+
|
| 629 |
+
self.cap_logits = nn.Parameter(torch.full((len(HORIZONS),), -2.0))
|
| 630 |
+
self.variance_mlp = nn.Sequential(
|
| 631 |
+
nn.Linear(gate_input, fusion_hidden),
|
| 632 |
+
nn.SiLU(),
|
| 633 |
+
nn.Linear(fusion_hidden, len(HORIZONS) * len(GROUPS)),
|
| 634 |
+
)
|
| 635 |
+
nn.init.zeros_(self.variance_mlp[-1].weight)
|
| 636 |
+
nn.init.zeros_(self.variance_mlp[-1].bias)
|
| 637 |
+
|
| 638 |
+
@staticmethod
|
| 639 |
+
def edge_support(height: int, width: int, device: torch.device,
|
| 640 |
+
dtype: torch.dtype) -> torch.Tensor:
|
| 641 |
+
y = torch.linspace(0, 1, height, device=device, dtype=dtype)
|
| 642 |
+
x = torch.linspace(0, 1, width, device=device, dtype=dtype)
|
| 643 |
+
yy, xx = torch.meshgrid(y, x, indexing="ij")
|
| 644 |
+
distance = torch.minimum(
|
| 645 |
+
torch.minimum(xx, 1 - xx),
|
| 646 |
+
torch.minimum(yy, 1 - yy),
|
| 647 |
+
)
|
| 648 |
+
support = torch.exp(-distance / 0.09)
|
| 649 |
+
return support[None, None, None]
|
| 650 |
+
|
| 651 |
+
@staticmethod
|
| 652 |
+
def apply_variance_gain(
|
| 653 |
+
prediction: torch.Tensor,
|
| 654 |
+
mask: torch.Tensor,
|
| 655 |
+
log_gain: torch.Tensor,
|
| 656 |
+
) -> torch.Tensor:
|
| 657 |
+
# prediction [B,H,C,Y,X], log_gain [B,H,G]
|
| 658 |
+
expanded_mask = mask[:, None]
|
| 659 |
+
denominator = expanded_mask.sum(dim=(-2, -1), keepdim=True).clamp_min(1.0)
|
| 660 |
+
mean = (prediction * expanded_mask).sum(
|
| 661 |
+
dim=(-2, -1), keepdim=True
|
| 662 |
+
) / denominator
|
| 663 |
+
anomaly = prediction - mean
|
| 664 |
+
channel_gain = torch.zeros(
|
| 665 |
+
prediction.shape[:3], device=prediction.device, dtype=prediction.dtype
|
| 666 |
+
)
|
| 667 |
+
for gi, indices in enumerate(GROUPS.values()):
|
| 668 |
+
channel_gain[:, :, indices] = log_gain[:, :, gi:gi + 1]
|
| 669 |
+
return mean + torch.exp(channel_gain[:, :, :, None, None]) * anomaly
|
| 670 |
+
|
| 671 |
+
def forward(
|
| 672 |
+
self,
|
| 673 |
+
internal: torch.Tensor,
|
| 674 |
+
parent_sources: Mapping[str, torch.Tensor],
|
| 675 |
+
future_atmosphere: torch.Tensor,
|
| 676 |
+
future_boundary: torch.Tensor,
|
| 677 |
+
current_vertical: torch.Tensor,
|
| 678 |
+
mask: torch.Tensor,
|
| 679 |
+
atmosphere_quality: torch.Tensor,
|
| 680 |
+
boundary_quality: torch.Tensor,
|
| 681 |
+
enable_atmosphere: bool = True,
|
| 682 |
+
enable_boundary: bool = True,
|
| 683 |
+
enable_vertical: bool = True,
|
| 684 |
+
enable_variance: bool = True,
|
| 685 |
+
disable_ber: bool = False,
|
| 686 |
+
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
|
| 687 |
+
with torch.no_grad():
|
| 688 |
+
parent_prediction, internal_features, parent_diag = self.parent(
|
| 689 |
+
internal, parent_sources
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
b, _, h, w = internal_features.shape
|
| 693 |
+
atm_available = torch.ones(b, device=internal.device)
|
| 694 |
+
bnd_available = torch.ones(b, device=internal.device)
|
| 695 |
+
atm_uncertainty = 1.0 - atmosphere_quality
|
| 696 |
+
bnd_uncertainty = 1.0 - boundary_quality
|
| 697 |
+
|
| 698 |
+
atmosphere = self.atmosphere_encoder(
|
| 699 |
+
future_atmosphere, atm_available, atm_uncertainty
|
| 700 |
+
)
|
| 701 |
+
boundary = self.boundary_encoder(
|
| 702 |
+
future_boundary, bnd_available, bnd_uncertainty
|
| 703 |
+
)
|
| 704 |
+
vertical = self.vertical_encoder(current_vertical)
|
| 705 |
+
vertical_h = vertical[:, None].expand(-1, len(HORIZONS), -1, -1, -1)
|
| 706 |
+
internal_h = internal_features[:, None].expand(
|
| 707 |
+
-1, len(HORIZONS), -1, -1, -1
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
if not enable_atmosphere:
|
| 711 |
+
atmosphere = torch.zeros_like(atmosphere)
|
| 712 |
+
if not enable_boundary:
|
| 713 |
+
boundary = torch.zeros_like(boundary)
|
| 714 |
+
if not enable_vertical:
|
| 715 |
+
vertical_h = torch.zeros_like(vertical_h)
|
| 716 |
+
vertical_pool = torch.zeros_like(vertical)
|
| 717 |
+
else:
|
| 718 |
+
vertical_pool = vertical
|
| 719 |
+
|
| 720 |
+
atm_input = torch.cat([internal_h, atmosphere, vertical_h], dim=2)
|
| 721 |
+
bnd_input = torch.cat([internal_h, boundary, vertical_h], dim=2)
|
| 722 |
+
interaction_input = torch.cat(
|
| 723 |
+
[internal_h, atmosphere, boundary, vertical_h], dim=2
|
| 724 |
+
)
|
| 725 |
+
atm_update = self.atmosphere_head(atm_input)
|
| 726 |
+
bnd_update = self.boundary_head(bnd_input)
|
| 727 |
+
bnd_update = bnd_update * self.edge_support(
|
| 728 |
+
h, w, internal.device, internal.dtype
|
| 729 |
+
)
|
| 730 |
+
vertical_update = self.vertical_head(
|
| 731 |
+
torch.cat([internal_h, vertical_h], dim=2)
|
| 732 |
+
)
|
| 733 |
+
interaction_update = self.interaction_head(interaction_input)
|
| 734 |
+
|
| 735 |
+
pooled = torch.cat([
|
| 736 |
+
internal_features.mean(dim=(-2, -1)),
|
| 737 |
+
atmosphere.mean(dim=(1, -2, -1)),
|
| 738 |
+
boundary.mean(dim=(1, -2, -1)),
|
| 739 |
+
vertical_pool.mean(dim=(-2, -1)),
|
| 740 |
+
atmosphere_quality[:, None],
|
| 741 |
+
boundary_quality[:, None],
|
| 742 |
+
(1.0 - atmosphere_quality)[:, None],
|
| 743 |
+
(1.0 - boundary_quality)[:, None],
|
| 744 |
+
], dim=1)
|
| 745 |
+
raw_gates = torch.sigmoid(
|
| 746 |
+
self.gate_mlp(pooled).reshape(b, len(HORIZONS), 4)
|
| 747 |
+
)
|
| 748 |
+
quality_scale = torch.stack([
|
| 749 |
+
atmosphere_quality,
|
| 750 |
+
boundary_quality,
|
| 751 |
+
torch.full_like(atmosphere_quality, 0.90 if enable_vertical else 0.0),
|
| 752 |
+
torch.minimum(atmosphere_quality, boundary_quality),
|
| 753 |
+
], dim=1)[:, None, :]
|
| 754 |
+
gates = raw_gates * quality_scale
|
| 755 |
+
|
| 756 |
+
caps = 0.01 + 0.24 * torch.sigmoid(self.cap_logits)
|
| 757 |
+
raw_update = (
|
| 758 |
+
gates[:, :, 0, None, None, None] * atm_update
|
| 759 |
+
+ gates[:, :, 1, None, None, None] * bnd_update
|
| 760 |
+
+ gates[:, :, 2, None, None, None] * vertical_update
|
| 761 |
+
+ gates[:, :, 3, None, None, None] * interaction_update
|
| 762 |
+
)
|
| 763 |
+
update = caps[None, :, None, None, None] * torch.tanh(raw_update)
|
| 764 |
+
|
| 765 |
+
log_gain = 0.15 * torch.tanh(
|
| 766 |
+
self.variance_mlp(pooled).reshape(
|
| 767 |
+
b, len(HORIZONS), len(GROUPS)
|
| 768 |
+
)
|
| 769 |
+
)
|
| 770 |
+
prediction = parent_prediction + update
|
| 771 |
+
if enable_variance:
|
| 772 |
+
prediction = self.apply_variance_gain(prediction, mask, log_gain)
|
| 773 |
+
else:
|
| 774 |
+
log_gain = torch.zeros_like(log_gain)
|
| 775 |
+
|
| 776 |
+
if disable_ber:
|
| 777 |
+
prediction = parent_prediction
|
| 778 |
+
update = torch.zeros_like(update)
|
| 779 |
+
log_gain = torch.zeros_like(log_gain)
|
| 780 |
+
|
| 781 |
+
diagnostics: Dict[str, torch.Tensor] = {
|
| 782 |
+
"parent_prediction": parent_prediction,
|
| 783 |
+
"update": update,
|
| 784 |
+
"atm_update": atm_update,
|
| 785 |
+
"boundary_update": bnd_update,
|
| 786 |
+
"vertical_update": vertical_update,
|
| 787 |
+
"interaction_update": interaction_update,
|
| 788 |
+
"gates": gates,
|
| 789 |
+
"caps": caps,
|
| 790 |
+
"log_gain": log_gain,
|
| 791 |
+
**parent_diag,
|
| 792 |
+
}
|
| 793 |
+
return prediction, diagnostics
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def load_parent(
|
| 797 |
+
assets_root: Path,
|
| 798 |
+
seed: int,
|
| 799 |
+
device: torch.device,
|
| 800 |
+
) -> FrozenA0Parent:
|
| 801 |
+
baseline = InternalProbe()
|
| 802 |
+
source_channels = {
|
| 803 |
+
key: len(SOURCE_VARIABLES[key]) + 2 for key in SOURCE_KEYS
|
| 804 |
+
}
|
| 805 |
+
adapter = A0ExternalResidualAdapter(source_channels)
|
| 806 |
+
baseline_ckpt = torch.load(
|
| 807 |
+
assets_root / "checkpoints" / "baseline" / f"seed_{seed}.pt",
|
| 808 |
+
map_location="cpu",
|
| 809 |
+
weights_only=False,
|
| 810 |
+
)
|
| 811 |
+
adapter_ckpt = torch.load(
|
| 812 |
+
assets_root / "checkpoints" / "all_required" / f"seed_{seed}.pt",
|
| 813 |
+
map_location="cpu",
|
| 814 |
+
weights_only=False,
|
| 815 |
+
)
|
| 816 |
+
baseline.load_state_dict(baseline_ckpt["model_state"], strict=True)
|
| 817 |
+
adapter.load_state_dict(adapter_ckpt["adapter_state"], strict=True)
|
| 818 |
+
parent = FrozenA0Parent(baseline, adapter).to(device)
|
| 819 |
+
parent.eval()
|
| 820 |
+
return parent
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def load_stats(path: Path) -> Tuple[np.ndarray, np.ndarray, Dict[str, Tuple[np.ndarray, np.ndarray]]]:
|
| 824 |
+
with np.load(path) as stats:
|
| 825 |
+
internal_mean = stats["internal_mean"].astype(np.float32)
|
| 826 |
+
internal_std = stats["internal_std"].astype(np.float32)
|
| 827 |
+
source_stats = {
|
| 828 |
+
key: (
|
| 829 |
+
stats[f"{key}_mean"].astype(np.float32),
|
| 830 |
+
stats[f"{key}_std"].astype(np.float32),
|
| 831 |
+
)
|
| 832 |
+
for key in SOURCE_KEYS
|
| 833 |
+
}
|
| 834 |
+
return internal_mean, internal_std, source_stats
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
def build_loaders(
|
| 838 |
+
windows: Sequence[WindowData],
|
| 839 |
+
stats_path: Path,
|
| 840 |
+
args: argparse.Namespace,
|
| 841 |
+
) -> Tuple[Dict[str, DataLoader], Dict[str, Any]]:
|
| 842 |
+
internal_mean, internal_std, source_stats = load_stats(stats_path)
|
| 843 |
+
loaders: Dict[str, DataLoader] = {}
|
| 844 |
+
split_meta: Dict[str, Any] = {}
|
| 845 |
+
for role in ["train", "validation", "test"]:
|
| 846 |
+
selected = [window for window in windows if window.role == role]
|
| 847 |
+
index = SequenceIndex(selected, args.history)
|
| 848 |
+
dataset = A1Dataset(index, internal_mean, internal_std, source_stats)
|
| 849 |
+
loaders[role] = DataLoader(
|
| 850 |
+
dataset,
|
| 851 |
+
batch_size=args.batch_size,
|
| 852 |
+
shuffle=(role == "train"),
|
| 853 |
+
num_workers=args.num_workers,
|
| 854 |
+
pin_memory=torch.cuda.is_available(),
|
| 855 |
+
drop_last=(role == "train" and len(dataset) >= args.batch_size),
|
| 856 |
+
)
|
| 857 |
+
split_meta[role] = {
|
| 858 |
+
"windows": [window.name for window in selected],
|
| 859 |
+
"samples": len(dataset),
|
| 860 |
+
}
|
| 861 |
+
return loaders, split_meta
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def batch_to_device(
|
| 865 |
+
batch: Mapping[str, torch.Tensor],
|
| 866 |
+
device: torch.device,
|
| 867 |
+
) -> Dict[str, torch.Tensor]:
|
| 868 |
+
return {
|
| 869 |
+
key: value.to(device, non_blocking=True)
|
| 870 |
+
if torch.is_tensor(value) else value
|
| 871 |
+
for key, value in batch.items()
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def parent_sources(batch: Mapping[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
|
| 876 |
+
return {key: batch[f"parent_{key}"] for key in SOURCE_KEYS}
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
def degrade_future(
|
| 880 |
+
atmosphere: torch.Tensor,
|
| 881 |
+
boundary: torch.Tensor,
|
| 882 |
+
mode: str,
|
| 883 |
+
seed: int,
|
| 884 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 885 |
+
b = atmosphere.shape[0]
|
| 886 |
+
device = atmosphere.device
|
| 887 |
+
dtype = atmosphere.dtype
|
| 888 |
+
if mode == "oracle":
|
| 889 |
+
return (
|
| 890 |
+
atmosphere,
|
| 891 |
+
boundary,
|
| 892 |
+
torch.full((b,), 0.95, device=device, dtype=dtype),
|
| 893 |
+
torch.full((b,), 0.95, device=device, dtype=dtype),
|
| 894 |
+
)
|
| 895 |
+
if mode == "history":
|
| 896 |
+
return (
|
| 897 |
+
atmosphere[:, :1].expand_as(atmosphere),
|
| 898 |
+
boundary[:, :1].expand_as(boundary),
|
| 899 |
+
torch.full((b,), 0.45, device=device, dtype=dtype),
|
| 900 |
+
torch.full((b,), 0.45, device=device, dtype=dtype),
|
| 901 |
+
)
|
| 902 |
+
if mode == "shuffled":
|
| 903 |
+
if b > 1:
|
| 904 |
+
order = torch.roll(torch.arange(b, device=device), shifts=1)
|
| 905 |
+
atmosphere = atmosphere[order]
|
| 906 |
+
boundary = boundary[order]
|
| 907 |
+
return (
|
| 908 |
+
atmosphere,
|
| 909 |
+
boundary,
|
| 910 |
+
torch.full((b,), 0.70, device=device, dtype=dtype),
|
| 911 |
+
torch.full((b,), 0.65, device=device, dtype=dtype),
|
| 912 |
+
)
|
| 913 |
+
if mode not in {"degraded", "train"}:
|
| 914 |
+
raise ValueError(mode)
|
| 915 |
+
|
| 916 |
+
# One-step lag: future forecast is not granted perfect phase.
|
| 917 |
+
atmosphere_lagged = torch.cat(
|
| 918 |
+
[atmosphere[:, :1], atmosphere[:, :-1]], dim=1
|
| 919 |
+
)
|
| 920 |
+
boundary_lagged = torch.cat(
|
| 921 |
+
[boundary[:, :1], boundary[:, :-1]], dim=1
|
| 922 |
+
)
|
| 923 |
+
generator = torch.Generator(device=device)
|
| 924 |
+
generator.manual_seed(int(seed))
|
| 925 |
+
atm_noise = torch.randn(
|
| 926 |
+
atmosphere_lagged.shape, generator=generator,
|
| 927 |
+
device=device, dtype=dtype,
|
| 928 |
+
) * 0.08
|
| 929 |
+
bnd_noise = torch.randn(
|
| 930 |
+
boundary_lagged.shape, generator=generator,
|
| 931 |
+
device=device, dtype=dtype,
|
| 932 |
+
) * 0.06
|
| 933 |
+
atmosphere_lagged = atmosphere_lagged + atm_noise
|
| 934 |
+
boundary_lagged = boundary_lagged + bnd_noise
|
| 935 |
+
if mode == "train":
|
| 936 |
+
# Training-only source dropout. Availability is represented through quality.
|
| 937 |
+
if random.random() < 0.10:
|
| 938 |
+
atmosphere_lagged = torch.zeros_like(atmosphere_lagged)
|
| 939 |
+
atm_quality = 0.20
|
| 940 |
+
else:
|
| 941 |
+
atm_quality = 0.78
|
| 942 |
+
if random.random() < 0.10:
|
| 943 |
+
boundary_lagged = torch.zeros_like(boundary_lagged)
|
| 944 |
+
bnd_quality = 0.20
|
| 945 |
+
else:
|
| 946 |
+
bnd_quality = 0.72
|
| 947 |
+
else:
|
| 948 |
+
atm_quality, bnd_quality = 0.78, 0.72
|
| 949 |
+
return (
|
| 950 |
+
atmosphere_lagged,
|
| 951 |
+
boundary_lagged,
|
| 952 |
+
torch.full((b,), atm_quality, device=device, dtype=dtype),
|
| 953 |
+
torch.full((b,), bnd_quality, device=device, dtype=dtype),
|
| 954 |
+
)
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
def masked_mse(
|
| 958 |
+
prediction: torch.Tensor,
|
| 959 |
+
target: torch.Tensor,
|
| 960 |
+
mask: torch.Tensor,
|
| 961 |
+
) -> torch.Tensor:
|
| 962 |
+
expanded = mask[:, None].expand_as(prediction)
|
| 963 |
+
return (
|
| 964 |
+
((prediction - target).square() * expanded).sum()
|
| 965 |
+
/ expanded.sum().clamp_min(1.0)
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def gradient_loss(
|
| 970 |
+
prediction: torch.Tensor,
|
| 971 |
+
target: torch.Tensor,
|
| 972 |
+
mask: torch.Tensor,
|
| 973 |
+
) -> torch.Tensor:
|
| 974 |
+
px = prediction[..., :, 1:] - prediction[..., :, :-1]
|
| 975 |
+
tx = target[..., :, 1:] - target[..., :, :-1]
|
| 976 |
+
py = prediction[..., 1:, :] - prediction[..., :-1, :]
|
| 977 |
+
ty = target[..., 1:, :] - target[..., :-1, :]
|
| 978 |
+
mx = mask[..., :, 1:] * mask[..., :, :-1]
|
| 979 |
+
my = mask[..., 1:, :] * mask[..., :-1, :]
|
| 980 |
+
mx = mx[:, None].expand_as(px)
|
| 981 |
+
my = my[:, None].expand_as(py)
|
| 982 |
+
return (
|
| 983 |
+
((px - tx).square() * mx).sum() / mx.sum().clamp_min(1.0)
|
| 984 |
+
+ ((py - ty).square() * my).sum() / my.sum().clamp_min(1.0)
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
def group_variance_loss(
|
| 989 |
+
prediction: torch.Tensor,
|
| 990 |
+
target: torch.Tensor,
|
| 991 |
+
mask: torch.Tensor,
|
| 992 |
+
) -> torch.Tensor:
|
| 993 |
+
"""Match spatial anomaly variance per horizon and physical variable group."""
|
| 994 |
+
losses = []
|
| 995 |
+
horizon_weights = [0.2, 0.4, 1.0]
|
| 996 |
+
spatial_mask = mask # [B,1,Y,X]
|
| 997 |
+
denominator = spatial_mask.sum(
|
| 998 |
+
dim=(-2, -1), keepdim=True
|
| 999 |
+
).clamp_min(1.0)
|
| 1000 |
+
for hi, weight in enumerate(horizon_weights):
|
| 1001 |
+
for indices in GROUPS.values():
|
| 1002 |
+
pred_group = prediction[:, hi, indices] # [B,G,Y,X]
|
| 1003 |
+
target_group = target[:, hi, indices]
|
| 1004 |
+
pred_mean = (
|
| 1005 |
+
(pred_group * spatial_mask).sum(
|
| 1006 |
+
dim=(-2, -1), keepdim=True
|
| 1007 |
+
) / denominator
|
| 1008 |
+
)
|
| 1009 |
+
target_mean = (
|
| 1010 |
+
(target_group * spatial_mask).sum(
|
| 1011 |
+
dim=(-2, -1), keepdim=True
|
| 1012 |
+
) / denominator
|
| 1013 |
+
)
|
| 1014 |
+
pred_variance = (
|
| 1015 |
+
((pred_group - pred_mean).square() * spatial_mask)
|
| 1016 |
+
.sum(dim=(-2, -1))
|
| 1017 |
+
/ denominator.squeeze(-1).squeeze(-1)
|
| 1018 |
+
)
|
| 1019 |
+
target_variance = (
|
| 1020 |
+
((target_group - target_mean).square() * spatial_mask)
|
| 1021 |
+
.sum(dim=(-2, -1))
|
| 1022 |
+
/ denominator.squeeze(-1).squeeze(-1)
|
| 1023 |
+
)
|
| 1024 |
+
pred_std = torch.sqrt(pred_variance.mean(dim=1) + 1e-6)
|
| 1025 |
+
target_std = torch.sqrt(target_variance.mean(dim=1) + 1e-6)
|
| 1026 |
+
losses.append(
|
| 1027 |
+
weight
|
| 1028 |
+
* (torch.log(pred_std) - torch.log(target_std))
|
| 1029 |
+
.square().mean()
|
| 1030 |
+
)
|
| 1031 |
+
return torch.stack(losses).mean()
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
def train_model(
|
| 1035 |
+
seed: int,
|
| 1036 |
+
parent: FrozenA0Parent,
|
| 1037 |
+
loaders: Mapping[str, DataLoader],
|
| 1038 |
+
args: argparse.Namespace,
|
| 1039 |
+
device: torch.device,
|
| 1040 |
+
output_dir: Path,
|
| 1041 |
+
) -> Tuple[OpenSystemBER, Dict[str, Any]]:
|
| 1042 |
+
seed_everything(seed)
|
| 1043 |
+
model = OpenSystemBER(
|
| 1044 |
+
copy.deepcopy(parent),
|
| 1045 |
+
internal_hidden=48,
|
| 1046 |
+
source_hidden=args.source_hidden,
|
| 1047 |
+
fusion_hidden=args.fusion_hidden,
|
| 1048 |
+
).to(device)
|
| 1049 |
+
|
| 1050 |
+
# Exact identity sentinel before any training.
|
| 1051 |
+
batch = batch_to_device(next(iter(loaders["validation"])), device)
|
| 1052 |
+
with torch.no_grad():
|
| 1053 |
+
atm, bnd, qa, qb = degrade_future(
|
| 1054 |
+
batch["future_atmosphere"], batch["future_boundary"],
|
| 1055 |
+
"oracle", seed,
|
| 1056 |
+
)
|
| 1057 |
+
initial, _ = model(
|
| 1058 |
+
batch["internal"], parent_sources(batch),
|
| 1059 |
+
atm, bnd, batch["current_vertical"], batch["mask"],
|
| 1060 |
+
qa, qb,
|
| 1061 |
+
)
|
| 1062 |
+
parent_pred, _, _ = model.parent(
|
| 1063 |
+
batch["internal"], parent_sources(batch)
|
| 1064 |
+
)
|
| 1065 |
+
identity_error = float((initial - parent_pred).abs().max())
|
| 1066 |
+
if identity_error > 5e-6:
|
| 1067 |
+
raise RuntimeError(
|
| 1068 |
+
f"A1 zero-initialized identity sentinel failed: {identity_error}"
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
trainable = [
|
| 1072 |
+
parameter for name, parameter in model.named_parameters()
|
| 1073 |
+
if not name.startswith("parent.")
|
| 1074 |
+
]
|
| 1075 |
+
optimizer = torch.optim.AdamW(
|
| 1076 |
+
trainable,
|
| 1077 |
+
lr=args.learning_rate,
|
| 1078 |
+
weight_decay=args.weight_decay,
|
| 1079 |
+
)
|
| 1080 |
+
best_state: Optional[Dict[str, torch.Tensor]] = None
|
| 1081 |
+
best_score = float("inf")
|
| 1082 |
+
best_epoch = -1
|
| 1083 |
+
logs = []
|
| 1084 |
+
|
| 1085 |
+
for epoch in range(1, args.epochs + 1):
|
| 1086 |
+
model.train()
|
| 1087 |
+
running = 0.0
|
| 1088 |
+
for step, raw_batch in enumerate(loaders["train"], 1):
|
| 1089 |
+
batch = batch_to_device(raw_batch, device)
|
| 1090 |
+
mode_draw = random.random()
|
| 1091 |
+
mode = "oracle" if mode_draw < 0.20 else (
|
| 1092 |
+
"history" if mode_draw < 0.30 else "train"
|
| 1093 |
+
)
|
| 1094 |
+
atm, bnd, qa, qb = degrade_future(
|
| 1095 |
+
batch["future_atmosphere"],
|
| 1096 |
+
batch["future_boundary"],
|
| 1097 |
+
mode,
|
| 1098 |
+
seed * 100000 + epoch * 1000 + step,
|
| 1099 |
+
)
|
| 1100 |
+
prediction, diagnostics = model(
|
| 1101 |
+
batch["internal"], parent_sources(batch),
|
| 1102 |
+
atm, bnd, batch["current_vertical"], batch["mask"],
|
| 1103 |
+
qa, qb,
|
| 1104 |
+
)
|
| 1105 |
+
target = batch["target"]
|
| 1106 |
+
parent_prediction = diagnostics["parent_prediction"]
|
| 1107 |
+
update = diagnostics["update"]
|
| 1108 |
+
residual_target = target - parent_prediction
|
| 1109 |
+
|
| 1110 |
+
loss_prediction = masked_mse(prediction, target, batch["mask"])
|
| 1111 |
+
loss_gradient = gradient_loss(prediction, target, batch["mask"])
|
| 1112 |
+
loss_residual = masked_mse(update, residual_target, batch["mask"])
|
| 1113 |
+
loss_variance = group_variance_loss(prediction, target, batch["mask"])
|
| 1114 |
+
update_ratio = (
|
| 1115 |
+
(update.square().mean() + 1e-12).sqrt()
|
| 1116 |
+
/ ((parent_prediction.square().mean() + 1e-12).sqrt() + 1e-6)
|
| 1117 |
+
)
|
| 1118 |
+
loss = (
|
| 1119 |
+
loss_prediction
|
| 1120 |
+
+ args.gradient_weight * loss_gradient
|
| 1121 |
+
+ args.residual_weight * loss_residual
|
| 1122 |
+
+ args.variance_weight * loss_variance
|
| 1123 |
+
+ args.update_regularization * update_ratio
|
| 1124 |
+
)
|
| 1125 |
+
if not torch.isfinite(loss):
|
| 1126 |
+
raise RuntimeError(
|
| 1127 |
+
f"Non-finite loss seed={seed} epoch={epoch} step={step}"
|
| 1128 |
+
)
|
| 1129 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1130 |
+
loss.backward()
|
| 1131 |
+
torch.nn.utils.clip_grad_norm_(trainable, args.grad_clip)
|
| 1132 |
+
optimizer.step()
|
| 1133 |
+
running += float(loss.detach())
|
| 1134 |
+
|
| 1135 |
+
validation = evaluate(
|
| 1136 |
+
model, loaders["validation"], device,
|
| 1137 |
+
mode="degraded", seed=seed + epoch * 10000,
|
| 1138 |
+
collect_samples=False,
|
| 1139 |
+
)
|
| 1140 |
+
variance_penalty = max(0.0, 0.80 - validation["variance_ratio_h12"]) ** 2
|
| 1141 |
+
score = (
|
| 1142 |
+
validation["rmse_h12"]
|
| 1143 |
+
+ 0.35 * validation["rmse_h4"]
|
| 1144 |
+
+ 0.15 * validation["rmse_h1"]
|
| 1145 |
+
+ args.selection_variance_weight * variance_penalty
|
| 1146 |
+
)
|
| 1147 |
+
row = {
|
| 1148 |
+
"seed": seed,
|
| 1149 |
+
"epoch": epoch,
|
| 1150 |
+
"train_loss": running / max(len(loaders["train"]), 1),
|
| 1151 |
+
"validation_score": score,
|
| 1152 |
+
**{key: value for key, value in validation.items() if not isinstance(value, list)},
|
| 1153 |
+
}
|
| 1154 |
+
logs.append(row)
|
| 1155 |
+
print(
|
| 1156 |
+
f"[A1 seed={seed}] epoch={epoch}/{args.epochs} "
|
| 1157 |
+
f"train={row['train_loss']:.6f} val={score:.6f} "
|
| 1158 |
+
f"72h={row['rmse_h12']:.6f} var72={row['variance_ratio_h12']:.4f}",
|
| 1159 |
+
flush=True,
|
| 1160 |
+
)
|
| 1161 |
+
if score < best_score:
|
| 1162 |
+
best_score = score
|
| 1163 |
+
best_epoch = epoch
|
| 1164 |
+
best_state = {
|
| 1165 |
+
key: value.detach().cpu().clone()
|
| 1166 |
+
for key, value in model.state_dict().items()
|
| 1167 |
+
if not key.startswith("parent.")
|
| 1168 |
+
}
|
| 1169 |
+
|
| 1170 |
+
if best_state is None:
|
| 1171 |
+
raise RuntimeError("No A1 checkpoint was selected")
|
| 1172 |
+
current = model.state_dict()
|
| 1173 |
+
current.update(best_state)
|
| 1174 |
+
model.load_state_dict(current, strict=True)
|
| 1175 |
+
checkpoint = output_dir / "checkpoints" / f"seed_{seed}.pt"
|
| 1176 |
+
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
| 1177 |
+
torch.save(
|
| 1178 |
+
{
|
| 1179 |
+
"a1_state": best_state,
|
| 1180 |
+
"seed": seed,
|
| 1181 |
+
"best_epoch": best_epoch,
|
| 1182 |
+
"validation_score": best_score,
|
| 1183 |
+
"identity_error": identity_error,
|
| 1184 |
+
},
|
| 1185 |
+
checkpoint,
|
| 1186 |
+
)
|
| 1187 |
+
pd.DataFrame(logs).to_csv(
|
| 1188 |
+
output_dir / "training" / f"seed_{seed}.csv", index=False
|
| 1189 |
+
)
|
| 1190 |
+
return model, {
|
| 1191 |
+
"seed": seed,
|
| 1192 |
+
"checkpoint": str(checkpoint),
|
| 1193 |
+
"best_epoch": best_epoch,
|
| 1194 |
+
"validation_score": best_score,
|
| 1195 |
+
"identity_error": identity_error,
|
| 1196 |
+
}
|
| 1197 |
+
|
| 1198 |
+
|
| 1199 |
+
@torch.no_grad()
|
| 1200 |
+
def evaluate(
|
| 1201 |
+
model: OpenSystemBER,
|
| 1202 |
+
loader: DataLoader,
|
| 1203 |
+
device: torch.device,
|
| 1204 |
+
mode: str,
|
| 1205 |
+
seed: int,
|
| 1206 |
+
collect_samples: bool = True,
|
| 1207 |
+
enable_atmosphere: bool = True,
|
| 1208 |
+
enable_boundary: bool = True,
|
| 1209 |
+
enable_vertical: bool = True,
|
| 1210 |
+
enable_variance: bool = True,
|
| 1211 |
+
disable_ber: bool = False,
|
| 1212 |
+
) -> Dict[str, Any]:
|
| 1213 |
+
model.eval()
|
| 1214 |
+
squared = {horizon: 0.0 for horizon in HORIZONS}
|
| 1215 |
+
count = {horizon: 0.0 for horizon in HORIZONS}
|
| 1216 |
+
pred_values: Dict[int, List[torch.Tensor]] = {horizon: [] for horizon in HORIZONS}
|
| 1217 |
+
target_values: Dict[int, List[torch.Tensor]] = {horizon: [] for horizon in HORIZONS}
|
| 1218 |
+
sample_rows: List[Dict[str, Any]] = []
|
| 1219 |
+
diagnostic_rows: List[Dict[str, Any]] = []
|
| 1220 |
+
group_accumulator: Dict[Tuple[int, str], List[float]] = {
|
| 1221 |
+
(horizon, group): [] for horizon in HORIZONS for group in GROUPS
|
| 1222 |
+
}
|
| 1223 |
+
|
| 1224 |
+
for step, raw_batch in enumerate(loader):
|
| 1225 |
+
batch = batch_to_device(raw_batch, device)
|
| 1226 |
+
atmosphere, boundary, qa, qb = degrade_future(
|
| 1227 |
+
batch["future_atmosphere"],
|
| 1228 |
+
batch["future_boundary"],
|
| 1229 |
+
mode,
|
| 1230 |
+
seed + step,
|
| 1231 |
+
)
|
| 1232 |
+
prediction, diagnostics = model(
|
| 1233 |
+
batch["internal"], parent_sources(batch),
|
| 1234 |
+
atmosphere, boundary, batch["current_vertical"], batch["mask"],
|
| 1235 |
+
qa, qb,
|
| 1236 |
+
enable_atmosphere=enable_atmosphere,
|
| 1237 |
+
enable_boundary=enable_boundary,
|
| 1238 |
+
enable_vertical=enable_vertical,
|
| 1239 |
+
enable_variance=enable_variance,
|
| 1240 |
+
disable_ber=disable_ber,
|
| 1241 |
+
)
|
| 1242 |
+
target = batch["target"]
|
| 1243 |
+
channels = prediction.shape[2]
|
| 1244 |
+
for hi, horizon in enumerate(HORIZONS):
|
| 1245 |
+
error = (prediction[:, hi] - target[:, hi]).square() * batch["mask"]
|
| 1246 |
+
denominator = (
|
| 1247 |
+
batch["mask"].flatten(1).sum(dim=1).clamp_min(1.0) * channels
|
| 1248 |
+
)
|
| 1249 |
+
per_sample_mse = error.flatten(1).sum(dim=1) / denominator
|
| 1250 |
+
squared[horizon] += float(error.sum())
|
| 1251 |
+
count[horizon] += float(batch["mask"].sum()) * channels
|
| 1252 |
+
pred_values[horizon].append(
|
| 1253 |
+
(prediction[:, hi] * batch["mask"]).flatten(1).cpu()
|
| 1254 |
+
)
|
| 1255 |
+
target_values[horizon].append(
|
| 1256 |
+
(target[:, hi] * batch["mask"]).flatten(1).cpu()
|
| 1257 |
+
)
|
| 1258 |
+
if collect_samples:
|
| 1259 |
+
for index, mse in zip(
|
| 1260 |
+
batch["sample_index"].cpu().tolist(),
|
| 1261 |
+
per_sample_mse.cpu().tolist(),
|
| 1262 |
+
):
|
| 1263 |
+
sample_rows.append({
|
| 1264 |
+
"sample_index": int(index),
|
| 1265 |
+
"horizon": horizon,
|
| 1266 |
+
"mse": float(mse),
|
| 1267 |
+
"rmse": math.sqrt(max(float(mse), 0.0)),
|
| 1268 |
+
})
|
| 1269 |
+
for group, indices in GROUPS.items():
|
| 1270 |
+
group_error = (
|
| 1271 |
+
(prediction[:, hi, indices] - target[:, hi, indices]).square()
|
| 1272 |
+
* batch["mask"]
|
| 1273 |
+
)
|
| 1274 |
+
group_denominator = (
|
| 1275 |
+
batch["mask"].flatten(1).sum(dim=1).clamp_min(1.0)
|
| 1276 |
+
* len(indices)
|
| 1277 |
+
)
|
| 1278 |
+
group_rmse = torch.sqrt(
|
| 1279 |
+
group_error.flatten(1).sum(dim=1) / group_denominator
|
| 1280 |
+
)
|
| 1281 |
+
group_accumulator[(horizon, group)].extend(
|
| 1282 |
+
group_rmse.cpu().tolist()
|
| 1283 |
+
)
|
| 1284 |
+
|
| 1285 |
+
update_ratio = (
|
| 1286 |
+
(diagnostics["update"].square().mean(dim=(2, 3, 4)) + 1e-12).sqrt()
|
| 1287 |
+
/ (
|
| 1288 |
+
(
|
| 1289 |
+
diagnostics["parent_prediction"]
|
| 1290 |
+
.square().mean(dim=(2, 3, 4))
|
| 1291 |
+
+ 1e-12
|
| 1292 |
+
).sqrt()
|
| 1293 |
+
+ 1e-6
|
| 1294 |
+
)
|
| 1295 |
+
)
|
| 1296 |
+
gates = diagnostics["gates"]
|
| 1297 |
+
log_gain = diagnostics["log_gain"]
|
| 1298 |
+
for bi in range(prediction.shape[0]):
|
| 1299 |
+
diagnostic_rows.append({
|
| 1300 |
+
"sample_index": int(batch["sample_index"][bi]),
|
| 1301 |
+
"atmosphere_quality": float(qa[bi]),
|
| 1302 |
+
"boundary_quality": float(qb[bi]),
|
| 1303 |
+
"update_ratio_h1": float(update_ratio[bi, 0]),
|
| 1304 |
+
"update_ratio_h4": float(update_ratio[bi, 1]),
|
| 1305 |
+
"update_ratio_h12": float(update_ratio[bi, 2]),
|
| 1306 |
+
"gate_atmosphere_h12": float(gates[bi, 2, 0]),
|
| 1307 |
+
"gate_boundary_h12": float(gates[bi, 2, 1]),
|
| 1308 |
+
"gate_vertical_h12": float(gates[bi, 2, 2]),
|
| 1309 |
+
"gate_interaction_h12": float(gates[bi, 2, 3]),
|
| 1310 |
+
"log_gain_abs_h12": float(log_gain[bi, 2].abs().mean()),
|
| 1311 |
+
})
|
| 1312 |
+
|
| 1313 |
+
metrics: Dict[str, Any] = {}
|
| 1314 |
+
for horizon in HORIZONS:
|
| 1315 |
+
metrics[f"rmse_h{horizon}"] = math.sqrt(
|
| 1316 |
+
squared[horizon] / max(count[horizon], 1.0)
|
| 1317 |
+
)
|
| 1318 |
+
prediction_flat = torch.cat(pred_values[horizon], dim=0)
|
| 1319 |
+
target_flat = torch.cat(target_values[horizon], dim=0)
|
| 1320 |
+
metrics[f"variance_ratio_h{horizon}"] = float(
|
| 1321 |
+
prediction_flat.var(unbiased=False)
|
| 1322 |
+
/ (target_flat.var(unbiased=False) + 1e-8)
|
| 1323 |
+
)
|
| 1324 |
+
for (horizon, group), values in group_accumulator.items():
|
| 1325 |
+
metrics[f"group_rmse_{group}_h{horizon}"] = float(np.mean(values))
|
| 1326 |
+
metrics["sample_rows"] = sample_rows
|
| 1327 |
+
metrics["diagnostic_rows"] = diagnostic_rows
|
| 1328 |
+
return metrics
|
| 1329 |
+
|
| 1330 |
+
|
| 1331 |
+
def paired_bootstrap(
|
| 1332 |
+
parent: np.ndarray,
|
| 1333 |
+
candidate: np.ndarray,
|
| 1334 |
+
replicates: int,
|
| 1335 |
+
seed: int,
|
| 1336 |
+
) -> Dict[str, float]:
|
| 1337 |
+
if len(parent) != len(candidate):
|
| 1338 |
+
raise ValueError("Paired arrays must have equal length")
|
| 1339 |
+
difference = candidate - parent
|
| 1340 |
+
generator = np.random.default_rng(seed)
|
| 1341 |
+
estimates = []
|
| 1342 |
+
for _ in range(replicates):
|
| 1343 |
+
indices = generator.integers(0, len(difference), len(difference))
|
| 1344 |
+
estimates.append(float(difference[indices].mean()))
|
| 1345 |
+
low, high = np.percentile(estimates, [2.5, 97.5])
|
| 1346 |
+
return {
|
| 1347 |
+
"mean_mse_difference": float(difference.mean()),
|
| 1348 |
+
"ci_low": float(low),
|
| 1349 |
+
"ci_high": float(high),
|
| 1350 |
+
"mse_gain_percent": float(
|
| 1351 |
+
100.0 * (parent.mean() - candidate.mean())
|
| 1352 |
+
/ max(parent.mean(), 1e-12)
|
| 1353 |
+
),
|
| 1354 |
+
"n": int(len(difference)),
|
| 1355 |
+
}
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
def runtime_audit(
|
| 1359 |
+
model: OpenSystemBER,
|
| 1360 |
+
loader: DataLoader,
|
| 1361 |
+
device: torch.device,
|
| 1362 |
+
seed: int,
|
| 1363 |
+
warmup: int = 10,
|
| 1364 |
+
repeats: int = 50,
|
| 1365 |
+
) -> Dict[str, float]:
|
| 1366 |
+
model.eval()
|
| 1367 |
+
batch = batch_to_device(next(iter(loader)), device)
|
| 1368 |
+
atmosphere, boundary, qa, qb = degrade_future(
|
| 1369 |
+
batch["future_atmosphere"], batch["future_boundary"],
|
| 1370 |
+
"degraded", seed,
|
| 1371 |
+
)
|
| 1372 |
+
|
| 1373 |
+
def execute() -> None:
|
| 1374 |
+
model(
|
| 1375 |
+
batch["internal"], parent_sources(batch),
|
| 1376 |
+
atmosphere, boundary, batch["current_vertical"],
|
| 1377 |
+
batch["mask"], qa, qb,
|
| 1378 |
+
)
|
| 1379 |
+
|
| 1380 |
+
with torch.no_grad():
|
| 1381 |
+
for _ in range(warmup):
|
| 1382 |
+
execute()
|
| 1383 |
+
if device.type == "cuda":
|
| 1384 |
+
torch.cuda.synchronize()
|
| 1385 |
+
start = time.perf_counter()
|
| 1386 |
+
for _ in range(repeats):
|
| 1387 |
+
execute()
|
| 1388 |
+
if device.type == "cuda":
|
| 1389 |
+
torch.cuda.synchronize()
|
| 1390 |
+
elapsed = time.perf_counter() - start
|
| 1391 |
+
return {
|
| 1392 |
+
"batch_size": int(batch["internal"].shape[0]),
|
| 1393 |
+
"mean_batch_ms": 1000.0 * elapsed / repeats,
|
| 1394 |
+
"mean_sample_ms": 1000.0 * elapsed / repeats / batch["internal"].shape[0],
|
| 1395 |
+
}
|
| 1396 |
+
|
| 1397 |
+
|
| 1398 |
+
def plot_summary(summary: pd.DataFrame, output_dir: Path) -> None:
|
| 1399 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 1400 |
+
table = summary[summary["horizon"] == 12].copy()
|
| 1401 |
+
plt.figure(figsize=(11, 5))
|
| 1402 |
+
plt.bar(table["mode"], table["rmse_gain_vs_a0_percent"])
|
| 1403 |
+
plt.axhline(0, linewidth=1)
|
| 1404 |
+
plt.ylabel("72 h RMSE gain over A0 parent (%)")
|
| 1405 |
+
plt.xticks(rotation=25, ha="right")
|
| 1406 |
+
plt.tight_layout()
|
| 1407 |
+
plt.savefig(output_dir / "S2A1_72h_RMSE_gain.png", dpi=180)
|
| 1408 |
+
plt.close()
|
| 1409 |
+
|
| 1410 |
+
plt.figure(figsize=(11, 5))
|
| 1411 |
+
plt.bar(table["mode"], table["variance_ratio"])
|
| 1412 |
+
plt.axhline(0.75, linewidth=1)
|
| 1413 |
+
plt.axhline(1.0, linewidth=1)
|
| 1414 |
+
plt.ylabel("72 h variance ratio")
|
| 1415 |
+
plt.xticks(rotation=25, ha="right")
|
| 1416 |
+
plt.tight_layout()
|
| 1417 |
+
plt.savefig(output_dir / "S2A1_72h_variance_ratio.png", dpi=180)
|
| 1418 |
+
plt.close()
|
| 1419 |
+
|
| 1420 |
+
|
| 1421 |
+
def package_output(output_dir: Path) -> Path:
|
| 1422 |
+
target = output_dir.parent / f"{output_dir.name}.zip"
|
| 1423 |
+
target.unlink(missing_ok=True)
|
| 1424 |
+
with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as archive:
|
| 1425 |
+
for path in output_dir.rglob("*"):
|
| 1426 |
+
if path.is_file():
|
| 1427 |
+
archive.write(path, path.relative_to(output_dir.parent))
|
| 1428 |
+
return target
|
| 1429 |
+
|
| 1430 |
+
|
| 1431 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 1432 |
+
parser = argparse.ArgumentParser(
|
| 1433 |
+
description="CIDM-v3 S2-A1 real-input BER qualification"
|
| 1434 |
+
)
|
| 1435 |
+
parser.add_argument("--cache_dir", default="/content/CIDM_v3_SCS_S2A0_Cache")
|
| 1436 |
+
parser.add_argument("--a0_zip", default="/content/CIDM_v3_SCS_V3_S2_A0.zip")
|
| 1437 |
+
parser.add_argument("--output_dir", default="/content/CIDM_v3_SCS_V3_S2_A1")
|
| 1438 |
+
parser.add_argument(
|
| 1439 |
+
"--hf_repo_id", default="wuff-mann/CIDM-v3-SCS-S2A0-Data"
|
| 1440 |
+
)
|
| 1441 |
+
parser.add_argument("--hf_token", default="")
|
| 1442 |
+
parser.add_argument("--history", type=int, default=4)
|
| 1443 |
+
parser.add_argument("--epochs", type=int, default=7)
|
| 1444 |
+
parser.add_argument("--batch_size", type=int, default=4)
|
| 1445 |
+
parser.add_argument("--num_workers", type=int, default=0)
|
| 1446 |
+
parser.add_argument("--source_hidden", type=int, default=24)
|
| 1447 |
+
parser.add_argument("--fusion_hidden", type=int, default=48)
|
| 1448 |
+
parser.add_argument("--learning_rate", type=float, default=2.5e-4)
|
| 1449 |
+
parser.add_argument("--weight_decay", type=float, default=1e-4)
|
| 1450 |
+
parser.add_argument("--gradient_weight", type=float, default=0.06)
|
| 1451 |
+
parser.add_argument("--residual_weight", type=float, default=0.10)
|
| 1452 |
+
parser.add_argument("--variance_weight", type=float, default=0.20)
|
| 1453 |
+
parser.add_argument("--selection_variance_weight", type=float, default=0.45)
|
| 1454 |
+
parser.add_argument("--update_regularization", type=float, default=0.005)
|
| 1455 |
+
parser.add_argument("--grad_clip", type=float, default=1.0)
|
| 1456 |
+
parser.add_argument(
|
| 1457 |
+
"--seeds", default="20260910,20260911,20260912"
|
| 1458 |
+
)
|
| 1459 |
+
parser.add_argument("--bootstrap_reps", type=int, default=1000)
|
| 1460 |
+
parser.add_argument("--synthetic_smoke", action="store_true")
|
| 1461 |
+
parser.add_argument("--smoke_time_steps", type=int, default=48)
|
| 1462 |
+
parser.add_argument("--smoke_height", type=int, default=16)
|
| 1463 |
+
parser.add_argument("--smoke_width", type=int, default=16)
|
| 1464 |
+
return parser
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
def create_synthetic_assets(args: argparse.Namespace) -> None:
|
| 1468 |
+
"""仅用于交付前执行链验证。"""
|
| 1469 |
+
cache = Path(args.cache_dir)
|
| 1470 |
+
prepared = cache / "prepared"
|
| 1471 |
+
prepared.mkdir(parents=True, exist_ok=True)
|
| 1472 |
+
generator = np.random.default_rng(20260920)
|
| 1473 |
+
for wi, spec in enumerate(WINDOWS):
|
| 1474 |
+
t = args.smoke_time_steps
|
| 1475 |
+
h = args.smoke_height
|
| 1476 |
+
w = args.smoke_width
|
| 1477 |
+
time_values = (
|
| 1478 |
+
np.datetime64("2023-01-01")
|
| 1479 |
+
+ np.arange(t) * np.timedelta64(6, "h")
|
| 1480 |
+
+ wi * np.timedelta64(100, "D")
|
| 1481 |
+
)
|
| 1482 |
+
internal = generator.normal(0, 1, (t, 16, h, w)).astype(np.float32)
|
| 1483 |
+
atmosphere = generator.normal(0, 1, (t, 9, h, w)).astype(np.float32)
|
| 1484 |
+
boundary = generator.normal(0, 1, (t, 10, h, w)).astype(np.float32)
|
| 1485 |
+
vertical = generator.normal(0, 1, (t, 10, h, w)).astype(np.float32)
|
| 1486 |
+
for index in range(1, t):
|
| 1487 |
+
internal[index] = (
|
| 1488 |
+
0.92 * internal[index - 1]
|
| 1489 |
+
+ 0.03 * atmosphere[index, :1]
|
| 1490 |
+
+ 0.03 * boundary[index, :1]
|
| 1491 |
+
+ 0.02 * vertical[index, :1]
|
| 1492 |
+
+ generator.normal(0, 0.05, internal[index].shape)
|
| 1493 |
+
)
|
| 1494 |
+
mask = np.ones((t, 1, h, w), np.float32)
|
| 1495 |
+
lat = np.linspace(0, 25, h, dtype=np.float32)
|
| 1496 |
+
lon = np.linspace(99, 123, w, dtype=np.float32)
|
| 1497 |
+
stamp = time_values.astype("datetime64[ns]").astype("int64")
|
| 1498 |
+
np.savez_compressed(
|
| 1499 |
+
prepared / f"{spec['name']}_cmems.npz",
|
| 1500 |
+
time=stamp, latitude=lat, longitude=lon,
|
| 1501 |
+
internal=internal, vertical=vertical,
|
| 1502 |
+
boundary=boundary, ocean_mask=mask,
|
| 1503 |
+
)
|
| 1504 |
+
np.savez_compressed(
|
| 1505 |
+
prepared / f"{spec['name']}_atmosphere_aligned.npz",
|
| 1506 |
+
time=stamp, atmosphere=atmosphere,
|
| 1507 |
+
)
|
| 1508 |
+
tide = np.zeros((t, 11, h, w), np.float32)
|
| 1509 |
+
river = np.zeros((t, 2, h, w), np.float32)
|
| 1510 |
+
events = np.zeros((t, 3, h, w), np.float32)
|
| 1511 |
+
np.savez_compressed(
|
| 1512 |
+
prepared / f"{spec['name']}_tide.npz",
|
| 1513 |
+
time=stamp, tide=tide,
|
| 1514 |
+
actual_spatial_tide=np.asarray([0], np.int8),
|
| 1515 |
+
)
|
| 1516 |
+
np.savez_compressed(
|
| 1517 |
+
prepared / f"{spec['name']}_river.npz",
|
| 1518 |
+
time=stamp, river=river,
|
| 1519 |
+
available=np.asarray([0], np.int8),
|
| 1520 |
+
)
|
| 1521 |
+
np.savez_compressed(
|
| 1522 |
+
prepared / f"{spec['name']}_events.npz",
|
| 1523 |
+
time=stamp, events=events,
|
| 1524 |
+
available=np.asarray([0], np.int8),
|
| 1525 |
+
)
|
| 1526 |
+
|
| 1527 |
+
|
| 1528 |
+
def main() -> None:
|
| 1529 |
+
args = build_parser().parse_args()
|
| 1530 |
+
seeds = [int(value) for value in args.seeds.split(",") if value.strip()]
|
| 1531 |
+
if not seeds:
|
| 1532 |
+
raise ValueError("At least one seed is required")
|
| 1533 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 1534 |
+
if not args.synthetic_smoke and device.type != "cuda":
|
| 1535 |
+
raise RuntimeError("Formal S2-A1 requires a CUDA GPU")
|
| 1536 |
+
torch.set_float32_matmul_precision("highest")
|
| 1537 |
+
|
| 1538 |
+
output_dir = Path(args.output_dir)
|
| 1539 |
+
if output_dir.exists():
|
| 1540 |
+
shutil.rmtree(output_dir)
|
| 1541 |
+
for subdir in [
|
| 1542 |
+
"training", "checkpoints", "evaluation",
|
| 1543 |
+
"audits", "figures", "lineage",
|
| 1544 |
+
]:
|
| 1545 |
+
(output_dir / subdir).mkdir(parents=True, exist_ok=True)
|
| 1546 |
+
|
| 1547 |
+
try:
|
| 1548 |
+
stage(1, 11, "从HF或本地缓存恢复S2-A0数据与父结果")
|
| 1549 |
+
if args.synthetic_smoke:
|
| 1550 |
+
create_synthetic_assets(args)
|
| 1551 |
+
# Smoke uses a supplied synthetic A0 package generated by the notebook/package test.
|
| 1552 |
+
hf_report = {"synthetic_smoke": True}
|
| 1553 |
+
else:
|
| 1554 |
+
hf_report = ensure_hf_assets(args)
|
| 1555 |
+
atomic_json(hf_report, output_dir / "audits" / "S2A1_HF_asset_audit.json")
|
| 1556 |
+
|
| 1557 |
+
stage(2, 11, "提取A0父链、归一化统计与三种子检查点")
|
| 1558 |
+
extracted = extract_a0_assets(
|
| 1559 |
+
Path(args.a0_zip), output_dir / "_a0_parent"
|
| 1560 |
+
)
|
| 1561 |
+
a0_verdict = json.loads(extracted["verdict"].read_text(encoding="utf-8"))
|
| 1562 |
+
a0_aggregate = json.loads(
|
| 1563 |
+
extracted["aggregate"].read_text(encoding="utf-8")
|
| 1564 |
+
)
|
| 1565 |
+
atomic_json(
|
| 1566 |
+
{"a0_verdict": a0_verdict, "a0_aggregate": a0_aggregate},
|
| 1567 |
+
output_dir / "lineage" / "S2A1_parent_lineage.json",
|
| 1568 |
+
)
|
| 1569 |
+
|
| 1570 |
+
stage(3, 11, "加载四季prepared数据并执行时间/形状审计")
|
| 1571 |
+
windows = [
|
| 1572 |
+
load_window(Path(args.cache_dir), spec) for spec in WINDOWS
|
| 1573 |
+
]
|
| 1574 |
+
loaders, split_meta = build_loaders(windows, extracted["stats"], args)
|
| 1575 |
+
atomic_json(split_meta, output_dir / "audits" / "S2A1_split_audit.json")
|
| 1576 |
+
shape_rows = []
|
| 1577 |
+
for window in windows:
|
| 1578 |
+
shape_rows.append({
|
| 1579 |
+
"window": window.name,
|
| 1580 |
+
"role": window.role,
|
| 1581 |
+
"time_steps": len(window.time),
|
| 1582 |
+
"internal_shape": str(tuple(window.internal.shape)),
|
| 1583 |
+
"atmosphere_shape": str(tuple(window.sources["atmosphere"].shape)),
|
| 1584 |
+
"boundary_shape": str(tuple(window.sources["boundary"].shape)),
|
| 1585 |
+
"vertical_shape": str(tuple(window.sources["vertical"].shape)),
|
| 1586 |
+
"finite": bool(
|
| 1587 |
+
np.isfinite(window.internal).all()
|
| 1588 |
+
and all(np.isfinite(value).all() for value in window.sources.values())
|
| 1589 |
+
),
|
| 1590 |
+
})
|
| 1591 |
+
pd.DataFrame(shape_rows).to_csv(
|
| 1592 |
+
output_dir / "audits" / "S2A1_data_shape_audit.csv", index=False
|
| 1593 |
+
)
|
| 1594 |
+
|
| 1595 |
+
stage(4, 11, "重建A0历史外部信息父模型与恒等哨兵")
|
| 1596 |
+
parents = {
|
| 1597 |
+
seed: load_parent(extracted["root"], seed, device)
|
| 1598 |
+
for seed in seeds
|
| 1599 |
+
}
|
| 1600 |
+
|
| 1601 |
+
stage(5, 11, "训练零初始化真实开放系统BER")
|
| 1602 |
+
models: Dict[int, OpenSystemBER] = {}
|
| 1603 |
+
training_records = []
|
| 1604 |
+
for seed in seeds:
|
| 1605 |
+
model, record = train_model(
|
| 1606 |
+
seed, parents[seed], loaders, args, device, output_dir
|
| 1607 |
+
)
|
| 1608 |
+
models[seed] = model
|
| 1609 |
+
training_records.append(record)
|
| 1610 |
+
pd.DataFrame(training_records).to_csv(
|
| 1611 |
+
output_dir / "S2A1_training_summary.csv", index=False
|
| 1612 |
+
)
|
| 1613 |
+
|
| 1614 |
+
stage(6, 11, "评估未来强迫、部署退化和来源消融")
|
| 1615 |
+
modes = {
|
| 1616 |
+
"a0_parent": dict(mode="degraded", disable_ber=True),
|
| 1617 |
+
"a1_fallback": dict(mode="oracle", disable_ber=True),
|
| 1618 |
+
"a1_degraded": dict(mode="degraded"),
|
| 1619 |
+
"a1_oracle": dict(mode="oracle"),
|
| 1620 |
+
"a1_history_only": dict(mode="history"),
|
| 1621 |
+
"a1_no_atmosphere": dict(mode="degraded", enable_atmosphere=False),
|
| 1622 |
+
"a1_no_boundary": dict(mode="degraded", enable_boundary=False),
|
| 1623 |
+
"a1_no_vertical": dict(mode="degraded", enable_vertical=False),
|
| 1624 |
+
"a1_no_variance": dict(mode="degraded", enable_variance=False),
|
| 1625 |
+
"a1_shuffled": dict(mode="shuffled"),
|
| 1626 |
+
}
|
| 1627 |
+
metric_rows = []
|
| 1628 |
+
sample_tables: Dict[Tuple[int, str], pd.DataFrame] = {}
|
| 1629 |
+
diagnostic_tables: Dict[Tuple[int, str], pd.DataFrame] = {}
|
| 1630 |
+
for seed in seeds:
|
| 1631 |
+
for mode_name, options in modes.items():
|
| 1632 |
+
metrics = evaluate(
|
| 1633 |
+
models[seed], loaders["test"], device,
|
| 1634 |
+
seed=seed * 1000 + sum(ord(char) for char in mode_name),
|
| 1635 |
+
collect_samples=True,
|
| 1636 |
+
**options,
|
| 1637 |
+
)
|
| 1638 |
+
sample_tables[(seed, mode_name)] = pd.DataFrame(
|
| 1639 |
+
metrics.pop("sample_rows")
|
| 1640 |
+
)
|
| 1641 |
+
diagnostic_tables[(seed, mode_name)] = pd.DataFrame(
|
| 1642 |
+
metrics.pop("diagnostic_rows")
|
| 1643 |
+
)
|
| 1644 |
+
metric_rows.append({
|
| 1645 |
+
"seed": seed,
|
| 1646 |
+
"mode": mode_name,
|
| 1647 |
+
**metrics,
|
| 1648 |
+
})
|
| 1649 |
+
metrics_table = pd.DataFrame(metric_rows)
|
| 1650 |
+
metrics_table.to_csv(
|
| 1651 |
+
output_dir / "evaluation" / "S2A1_seed_metrics.csv", index=False
|
| 1652 |
+
)
|
| 1653 |
+
|
| 1654 |
+
stage(7, 11, "配对Bootstrap、RMSE增益和方差恢复分析")
|
| 1655 |
+
summary_rows = []
|
| 1656 |
+
bootstrap_payload: Dict[str, Any] = {}
|
| 1657 |
+
parent_mean = {
|
| 1658 |
+
horizon: metrics_table[
|
| 1659 |
+
(metrics_table["mode"] == "a0_parent")
|
| 1660 |
+
][f"rmse_h{horizon}"].mean()
|
| 1661 |
+
for horizon in HORIZONS
|
| 1662 |
+
}
|
| 1663 |
+
for mode_name in modes:
|
| 1664 |
+
for horizon in HORIZONS:
|
| 1665 |
+
subset = metrics_table[metrics_table["mode"] == mode_name]
|
| 1666 |
+
rmse = float(subset[f"rmse_h{horizon}"].mean())
|
| 1667 |
+
variance = float(
|
| 1668 |
+
subset[f"variance_ratio_h{horizon}"].mean()
|
| 1669 |
+
)
|
| 1670 |
+
seed_gains = []
|
| 1671 |
+
parent_mse_all, candidate_mse_all = [], []
|
| 1672 |
+
for seed in seeds:
|
| 1673 |
+
parent_samples = sample_tables[(seed, "a0_parent")]
|
| 1674 |
+
candidate_samples = sample_tables[(seed, mode_name)]
|
| 1675 |
+
parent_mse = (
|
| 1676 |
+
parent_samples[parent_samples.horizon == horizon]
|
| 1677 |
+
.sort_values("sample_index").mse.to_numpy()
|
| 1678 |
+
)
|
| 1679 |
+
candidate_mse = (
|
| 1680 |
+
candidate_samples[candidate_samples.horizon == horizon]
|
| 1681 |
+
.sort_values("sample_index").mse.to_numpy()
|
| 1682 |
+
)
|
| 1683 |
+
seed_gains.append(
|
| 1684 |
+
100.0 * (
|
| 1685 |
+
metrics_table[
|
| 1686 |
+
(metrics_table["seed"] == seed)
|
| 1687 |
+
& (metrics_table["mode"] == "a0_parent")
|
| 1688 |
+
][f"rmse_h{horizon}"].iloc[0]
|
| 1689 |
+
- metrics_table[
|
| 1690 |
+
(metrics_table["seed"] == seed)
|
| 1691 |
+
& (metrics_table["mode"] == mode_name)
|
| 1692 |
+
][f"rmse_h{horizon}"].iloc[0]
|
| 1693 |
+
) / metrics_table[
|
| 1694 |
+
(metrics_table["seed"] == seed)
|
| 1695 |
+
& (metrics_table["mode"] == "a0_parent")
|
| 1696 |
+
][f"rmse_h{horizon}"].iloc[0]
|
| 1697 |
+
)
|
| 1698 |
+
parent_mse_all.append(parent_mse)
|
| 1699 |
+
candidate_mse_all.append(candidate_mse)
|
| 1700 |
+
bootstrap = paired_bootstrap(
|
| 1701 |
+
np.concatenate(parent_mse_all),
|
| 1702 |
+
np.concatenate(candidate_mse_all),
|
| 1703 |
+
args.bootstrap_reps,
|
| 1704 |
+
seeds[0] + horizon * 1000 + sum(ord(char) for char in mode_name),
|
| 1705 |
+
)
|
| 1706 |
+
bootstrap_payload[f"{mode_name}_h{horizon}"] = bootstrap
|
| 1707 |
+
summary_rows.append({
|
| 1708 |
+
"mode": mode_name,
|
| 1709 |
+
"horizon": horizon,
|
| 1710 |
+
"lead_hours": horizon * 6,
|
| 1711 |
+
"rmse": rmse,
|
| 1712 |
+
"variance_ratio": variance,
|
| 1713 |
+
"rmse_gain_vs_a0_percent": (
|
| 1714 |
+
100.0 * (parent_mean[horizon] - rmse)
|
| 1715 |
+
/ parent_mean[horizon]
|
| 1716 |
+
),
|
| 1717 |
+
"mse_gain_vs_a0_percent": bootstrap["mse_gain_percent"],
|
| 1718 |
+
"bootstrap_mse_difference_low": bootstrap["ci_low"],
|
| 1719 |
+
"bootstrap_mse_difference_high": bootstrap["ci_high"],
|
| 1720 |
+
"all_seed_rmse_gains_positive": bool(
|
| 1721 |
+
all(value > 0 for value in seed_gains)
|
| 1722 |
+
),
|
| 1723 |
+
"seed_rmse_gain_min": float(min(seed_gains)),
|
| 1724 |
+
"seed_rmse_gain_max": float(max(seed_gains)),
|
| 1725 |
+
})
|
| 1726 |
+
summary = pd.DataFrame(summary_rows)
|
| 1727 |
+
summary.to_csv(
|
| 1728 |
+
output_dir / "S2A1_counterfactual_summary.csv", index=False
|
| 1729 |
+
)
|
| 1730 |
+
atomic_json(
|
| 1731 |
+
bootstrap_payload, output_dir / "paired_bootstrap.json"
|
| 1732 |
+
)
|
| 1733 |
+
|
| 1734 |
+
stage(8, 11, "来源责任、变量组与不确定度单调性审计")
|
| 1735 |
+
group_columns = [
|
| 1736 |
+
column for column in metrics_table.columns
|
| 1737 |
+
if column.startswith("group_rmse_")
|
| 1738 |
+
]
|
| 1739 |
+
metrics_table[
|
| 1740 |
+
["seed", "mode"] + group_columns
|
| 1741 |
+
].to_csv(
|
| 1742 |
+
output_dir / "evaluation" / "S2A1_variable_group_summary.csv",
|
| 1743 |
+
index=False,
|
| 1744 |
+
)
|
| 1745 |
+
diagnostic_rows = []
|
| 1746 |
+
for (seed, mode_name), table in diagnostic_tables.items():
|
| 1747 |
+
row = {
|
| 1748 |
+
"seed": seed,
|
| 1749 |
+
"mode": mode_name,
|
| 1750 |
+
}
|
| 1751 |
+
for column in [
|
| 1752 |
+
"update_ratio_h1", "update_ratio_h4", "update_ratio_h12",
|
| 1753 |
+
"gate_atmosphere_h12", "gate_boundary_h12",
|
| 1754 |
+
"gate_vertical_h12", "gate_interaction_h12",
|
| 1755 |
+
"log_gain_abs_h12",
|
| 1756 |
+
]:
|
| 1757 |
+
row[column] = float(table[column].mean())
|
| 1758 |
+
diagnostic_rows.append(row)
|
| 1759 |
+
diagnostics = pd.DataFrame(diagnostic_rows)
|
| 1760 |
+
diagnostics.to_csv(
|
| 1761 |
+
output_dir / "evaluation" / "S2A1_BER_diagnostics.csv",
|
| 1762 |
+
index=False,
|
| 1763 |
+
)
|
| 1764 |
+
|
| 1765 |
+
stage(9, 11, "运行时审计与正式资格判决")
|
| 1766 |
+
runtime_rows = []
|
| 1767 |
+
for seed in seeds:
|
| 1768 |
+
row = runtime_audit(
|
| 1769 |
+
models[seed], loaders["test"], device, seed
|
| 1770 |
+
)
|
| 1771 |
+
row["seed"] = seed
|
| 1772 |
+
runtime_rows.append(row)
|
| 1773 |
+
runtime_table = pd.DataFrame(runtime_rows)
|
| 1774 |
+
runtime_table.to_csv(
|
| 1775 |
+
output_dir / "S2A1_runtime.csv", index=False
|
| 1776 |
+
)
|
| 1777 |
+
|
| 1778 |
+
def summary_value(mode: str, horizon: int, column: str) -> float:
|
| 1779 |
+
return float(
|
| 1780 |
+
summary[
|
| 1781 |
+
(summary["mode"] == mode)
|
| 1782 |
+
& (summary["horizon"] == horizon)
|
| 1783 |
+
][column].iloc[0]
|
| 1784 |
+
)
|
| 1785 |
+
|
| 1786 |
+
degraded_rmse_gain = summary_value(
|
| 1787 |
+
"a1_degraded", 12, "rmse_gain_vs_a0_percent"
|
| 1788 |
+
)
|
| 1789 |
+
degraded_var = summary_value(
|
| 1790 |
+
"a1_degraded", 12, "variance_ratio"
|
| 1791 |
+
)
|
| 1792 |
+
oracle_gain = summary_value(
|
| 1793 |
+
"a1_oracle", 12, "rmse_gain_vs_a0_percent"
|
| 1794 |
+
)
|
| 1795 |
+
no_atm_gain = summary_value(
|
| 1796 |
+
"a1_no_atmosphere", 12, "rmse_gain_vs_a0_percent"
|
| 1797 |
+
)
|
| 1798 |
+
no_bnd_gain = summary_value(
|
| 1799 |
+
"a1_no_boundary", 12, "rmse_gain_vs_a0_percent"
|
| 1800 |
+
)
|
| 1801 |
+
no_vert_gain = summary_value(
|
| 1802 |
+
"a1_no_vertical", 12, "rmse_gain_vs_a0_percent"
|
| 1803 |
+
)
|
| 1804 |
+
no_variance_rmse = summary_value(
|
| 1805 |
+
"a1_no_variance", 12, "rmse"
|
| 1806 |
+
)
|
| 1807 |
+
degraded_rmse = summary_value(
|
| 1808 |
+
"a1_degraded", 12, "rmse"
|
| 1809 |
+
)
|
| 1810 |
+
no_variance_var = summary_value(
|
| 1811 |
+
"a1_no_variance", 12, "variance_ratio"
|
| 1812 |
+
)
|
| 1813 |
+
shuffled_rmse = summary_value(
|
| 1814 |
+
"a1_shuffled", 12, "rmse"
|
| 1815 |
+
)
|
| 1816 |
+
parent_rmse = summary_value(
|
| 1817 |
+
"a0_parent", 12, "rmse"
|
| 1818 |
+
)
|
| 1819 |
+
bootstrap_upper = summary_value(
|
| 1820 |
+
"a1_degraded", 12, "bootstrap_mse_difference_high"
|
| 1821 |
+
)
|
| 1822 |
+
all_seed_positive = bool(
|
| 1823 |
+
summary[
|
| 1824 |
+
(summary["mode"] == "a1_degraded")
|
| 1825 |
+
& (summary["horizon"] == 12)
|
| 1826 |
+
]["all_seed_rmse_gains_positive"].iloc[0]
|
| 1827 |
+
)
|
| 1828 |
+
identity_max = max(
|
| 1829 |
+
record["identity_error"] for record in training_records
|
| 1830 |
+
)
|
| 1831 |
+
|
| 1832 |
+
# Marginal source utility: full should be better than the ablation.
|
| 1833 |
+
atm_marginal = 100.0 * (
|
| 1834 |
+
summary_value("a1_no_atmosphere", 12, "rmse")
|
| 1835 |
+
- degraded_rmse
|
| 1836 |
+
) / degraded_rmse
|
| 1837 |
+
bnd_marginal = 100.0 * (
|
| 1838 |
+
summary_value("a1_no_boundary", 12, "rmse")
|
| 1839 |
+
- degraded_rmse
|
| 1840 |
+
) / degraded_rmse
|
| 1841 |
+
vert_marginal = 100.0 * (
|
| 1842 |
+
summary_value("a1_no_vertical", 12, "rmse")
|
| 1843 |
+
- degraded_rmse
|
| 1844 |
+
) / degraded_rmse
|
| 1845 |
+
variance_improvement = degraded_var - no_variance_var
|
| 1846 |
+
variance_rmse_harm = 100.0 * (
|
| 1847 |
+
degraded_rmse - no_variance_rmse
|
| 1848 |
+
) / no_variance_rmse
|
| 1849 |
+
shuffled_harm = 100.0 * (
|
| 1850 |
+
shuffled_rmse - degraded_rmse
|
| 1851 |
+
) / degraded_rmse
|
| 1852 |
+
|
| 1853 |
+
checks = {
|
| 1854 |
+
"a0_parent_loaded_three_seeds": len(parents) == 3 and len(seeds) == 3,
|
| 1855 |
+
"zero_initialized_identity_lt_5e6": identity_max < 5e-6,
|
| 1856 |
+
"degraded_future_72h_rmse_gain_ge_0_5pct": degraded_rmse_gain >= 0.5,
|
| 1857 |
+
"degraded_future_72h_bootstrap_mse_positive": bootstrap_upper < 0,
|
| 1858 |
+
"all_three_degraded_72h_rmse_positive": all_seed_positive,
|
| 1859 |
+
"oracle_not_worse_than_degraded": oracle_gain >= degraded_rmse_gain,
|
| 1860 |
+
"variance_ratio_72h_0_75_to_1_10": 0.75 <= degraded_var <= 1.10,
|
| 1861 |
+
"variance_closure_improves_ratio_ge_0_02": variance_improvement >= 0.02,
|
| 1862 |
+
"variance_closure_rmse_harm_le_0_3pct": variance_rmse_harm <= 0.3,
|
| 1863 |
+
"atmosphere_has_positive_marginal_utility": atm_marginal > 0,
|
| 1864 |
+
"boundary_has_positive_marginal_utility": bnd_marginal > 0,
|
| 1865 |
+
"vertical_condition_has_positive_marginal_utility": vert_marginal > 0,
|
| 1866 |
+
"shuffled_future_is_worse": shuffled_harm > 0,
|
| 1867 |
+
"fallback_exactly_reproduces_a0": abs(
|
| 1868 |
+
summary_value("a1_fallback", 12, "rmse") - parent_rmse
|
| 1869 |
+
) < 1e-10,
|
| 1870 |
+
"mean_sample_runtime_lt_20ms": float(
|
| 1871 |
+
runtime_table["mean_sample_ms"].mean()
|
| 1872 |
+
) < 20.0,
|
| 1873 |
+
"all_metrics_finite": bool(
|
| 1874 |
+
np.isfinite(metrics_table.select_dtypes(include=[np.number]).to_numpy()).all()
|
| 1875 |
+
),
|
| 1876 |
+
}
|
| 1877 |
+
passed = sum(bool(value) for value in checks.values())
|
| 1878 |
+
if all(checks.values()):
|
| 1879 |
+
verdict_name = (
|
| 1880 |
+
"V3_S2_A1_REAL_INPUT_BER_AND_VARIANCE_RESTORATION_QUALIFIED"
|
| 1881 |
+
)
|
| 1882 |
+
elif passed >= 12 and checks[
|
| 1883 |
+
"degraded_future_72h_rmse_gain_ge_0_5pct"
|
| 1884 |
+
]:
|
| 1885 |
+
verdict_name = (
|
| 1886 |
+
"V3_S2_A1_REAL_INPUT_BER_AND_VARIANCE_RESTORATION_PARTIALLY_QUALIFIED"
|
| 1887 |
+
)
|
| 1888 |
+
else:
|
| 1889 |
+
verdict_name = (
|
| 1890 |
+
"V3_S2_A1_REAL_INPUT_BER_AND_VARIANCE_RESTORATION_NOT_YET_QUALIFIED"
|
| 1891 |
+
)
|
| 1892 |
+
aggregate = {
|
| 1893 |
+
"degraded_72h_rmse_gain_percent": degraded_rmse_gain,
|
| 1894 |
+
"degraded_72h_variance_ratio": degraded_var,
|
| 1895 |
+
"oracle_72h_rmse_gain_percent": oracle_gain,
|
| 1896 |
+
"atmosphere_marginal_utility_percent": atm_marginal,
|
| 1897 |
+
"boundary_marginal_utility_percent": bnd_marginal,
|
| 1898 |
+
"vertical_marginal_utility_percent": vert_marginal,
|
| 1899 |
+
"variance_ratio_improvement": variance_improvement,
|
| 1900 |
+
"variance_closure_rmse_harm_percent": variance_rmse_harm,
|
| 1901 |
+
"shuffled_future_harm_percent": shuffled_harm,
|
| 1902 |
+
"identity_error_max": identity_max,
|
| 1903 |
+
"mean_sample_runtime_ms": float(
|
| 1904 |
+
runtime_table["mean_sample_ms"].mean()
|
| 1905 |
+
),
|
| 1906 |
+
}
|
| 1907 |
+
verdict = {
|
| 1908 |
+
"automatic_verdict": verdict_name,
|
| 1909 |
+
"passed": passed,
|
| 1910 |
+
"total": len(checks),
|
| 1911 |
+
"checks": checks,
|
| 1912 |
+
"aggregate": aggregate,
|
| 1913 |
+
"next_stage_recommendation": (
|
| 1914 |
+
"Proceed to S2-A2 and integrate the qualified BER into the frozen S1-R3 CIDM core."
|
| 1915 |
+
if verdict_name
|
| 1916 |
+
== "V3_S2_A1_REAL_INPUT_BER_AND_VARIANCE_RESTORATION_QUALIFIED"
|
| 1917 |
+
else "Use the failed counterfactual gates to repair BER before CIDM-core integration."
|
| 1918 |
+
),
|
| 1919 |
+
}
|
| 1920 |
+
atomic_json(aggregate, output_dir / "S2A1_main_aggregate.json")
|
| 1921 |
+
atomic_json(verdict, output_dir / "S2A1_verdict.json")
|
| 1922 |
+
|
| 1923 |
+
stage(10, 11, "生成图表、报告和HF续接清单")
|
| 1924 |
+
plot_summary(summary, output_dir / "figures")
|
| 1925 |
+
report_lines = [
|
| 1926 |
+
"# V3-S2-A1 真实外部输入BER资格报告",
|
| 1927 |
+
"",
|
| 1928 |
+
f"自动判决:`{verdict_name}`",
|
| 1929 |
+
"",
|
| 1930 |
+
f"- 部署退化代理72小时RMSE增益:{degraded_rmse_gain:.4f}%",
|
| 1931 |
+
f"- Oracle未来强迫72小时RMSE增益:{oracle_gain:.4f}%",
|
| 1932 |
+
f"- 部署退化代理72小时方差比:{degraded_var:.4f}",
|
| 1933 |
+
f"- 大气边际效用:{atm_marginal:.4f}%",
|
| 1934 |
+
f"- 边界边际效用:{bnd_marginal:.4f}%",
|
| 1935 |
+
f"- 垂向条件边际效用:{vert_marginal:.4f}%",
|
| 1936 |
+
f"- 方差闭合提升:{variance_improvement:.4f}",
|
| 1937 |
+
f"- 打乱未来强迫损害:{shuffled_harm:.4f}%",
|
| 1938 |
+
"",
|
| 1939 |
+
"说明:Oracle使用未来再分析,仅表示外部信息上限;",
|
| 1940 |
+
"正式资格以加入时滞、噪声和质量通道的degraded_future为主。",
|
| 1941 |
+
]
|
| 1942 |
+
(
|
| 1943 |
+
output_dir / "实验V3S2A1_真实外部输入BER与方差恢复报告.md"
|
| 1944 |
+
).write_text("\n".join(report_lines), encoding="utf-8")
|
| 1945 |
+
atomic_json(
|
| 1946 |
+
{
|
| 1947 |
+
"source_dataset_repo": args.hf_repo_id,
|
| 1948 |
+
"source_paths": [
|
| 1949 |
+
"Cache/prepared/<window>_cmems.npz",
|
| 1950 |
+
"Cache/prepared/<window>_atmosphere_aligned.npz",
|
| 1951 |
+
"CIDM_v3_SCS_V3_S2_A0.zip",
|
| 1952 |
+
],
|
| 1953 |
+
"recommended_result_path": "Experiments/V3_S2_A1/",
|
| 1954 |
+
},
|
| 1955 |
+
output_dir / "S2A1_HF_handoff.json",
|
| 1956 |
+
)
|
| 1957 |
+
atomic_json(
|
| 1958 |
+
{
|
| 1959 |
+
"experiment": "CIDM_v3_SCS_V3_S2_A1",
|
| 1960 |
+
"created_at": dt.datetime.now().isoformat(),
|
| 1961 |
+
"device": str(device),
|
| 1962 |
+
"seeds": seeds,
|
| 1963 |
+
"arguments": vars(args),
|
| 1964 |
+
},
|
| 1965 |
+
output_dir / "S2A1_manifest.json",
|
| 1966 |
+
)
|
| 1967 |
+
|
| 1968 |
+
stage(11, 11, "结果打包")
|
| 1969 |
+
package = package_output(output_dir)
|
| 1970 |
+
print(json.dumps(verdict, ensure_ascii=False, indent=2), flush=True)
|
| 1971 |
+
print(f"[result] {package}", flush=True)
|
| 1972 |
+
except Exception:
|
| 1973 |
+
trace = traceback.format_exc()
|
| 1974 |
+
(output_dir / "failure_traceback.txt").write_text(
|
| 1975 |
+
trace, encoding="utf-8"
|
| 1976 |
+
)
|
| 1977 |
+
print(trace, flush=True)
|
| 1978 |
+
raise
|
| 1979 |
+
|
| 1980 |
+
|
| 1981 |
+
if __name__ == "__main__":
|
| 1982 |
+
main()
|