yzt15806542928 commited on
Commit
9191802
·
verified ·
1 Parent(s): a1991b2

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ frameworks: PyTorch
3
+ language:
4
+ - en
5
+ license: apache-2.0
6
+ tags:
7
+ - OneScience
8
+ - Earth Science
9
+ - Weather Forecast
10
+ - Medium-Range Weather Forecast
11
+ - ERA5
12
+ - FuXi
13
+ tasks: []
14
+ datasets:
15
+ - OneScience/ERA5
16
+ ---
17
+ <p align="center">
18
+ <strong>
19
+ <span style="font-size: 30px;">FuXi_v21</span>
20
+ </strong>
21
+ </p>
22
+
23
+ # Model Introduction
24
+
25
+ FuXi 2.1 is a global deterministic machine-learning weather forecast model developed by Fudan University in collaboration with the Shanghai Artificial Intelligence Laboratory (SAIS). Its theoretical basis remains the original FuXi paper.
26
+
27
+ Paper: FuXi: A cascade machine learning forecasting system for 15-day global weather forecast
28
+
29
+ https://arxiv.org/abs/2306.12873
30
+
31
+ # Model Description
32
+
33
+ The model addresses the excessive smoothing often observed in AI weather forecasts. It aims to produce clearer and more detailed forecast fields, improving the detection of extreme events such as heavy precipitation and strong winds without degrading conventional metrics such as root mean square error (RMSE).
34
+
35
+ # Use Cases
36
+
37
+ | Scenario | Description |
38
+ | :---: | :--- |
39
+ | Global weather forecast training | Train FuXi v2.1 with C85 ERA5 data in HDF5 format. |
40
+ | Local quick validation | Use synthetic HDF5 data to check data loading, training, inference, and visualization of inference results. |
41
+ | ModelScope / OneCode execution | Download the standalone model package, install dependencies, and run the scripts directly. |
42
+ | Multi-GPU training | Run distributed data-parallel training with `torchrun`. |
43
+
44
+ # Usage Guide
45
+
46
+ ## 1. OneCode Usage
47
+
48
+ Experience intelligent one-click AI4S programming through the OneCode online environment:
49
+
50
+ [Click to Experience Intelligent One-Click AI4S Programming](https://web-2069360198568017922-iaaj.ksai.scnet.cn:58043/home)
51
+
52
+ ## 2. Manual Installation and Usage
53
+
54
+ **Hardware Requirements**
55
+
56
+ - A GPU or DCU is recommended.
57
+ - CPU can be used for import and small-scale connectivity verification; full training and inference will be slow.
58
+ - DCU users must install DTK in advance. DTK 25.04.2 or above, or the OneScience recommended version matching your cluster, is recommended.
59
+
60
+ ### Download the Model Package
61
+
62
+ ```bash
63
+ hf download OneScience-Group/FuXi_v21 --local-dir ./FuXi_v21
64
+ cd FuXi_v21
65
+ ```
66
+
67
+ ### Install the Runtime Environment
68
+
69
+ **DCU Environment**
70
+
71
+ ```bash
72
+ # Please activate DTK and CONDA first
73
+ conda create -n onescience311 python=3.11 -y
74
+ conda activate onescience311
75
+ # uv installation is supported
76
+ pip install onescience[earth-dcu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai
77
+ ```
78
+
79
+ **GPU Environment**
80
+ ```bash
81
+ # Please activate CONDA first
82
+ conda create -n onescience311 python=3.11 -y libstdcxx-ng=12 libgcc-ng=12 gcc_linux-64=12 gxx_linux-64=12
83
+ conda activate onescience311
84
+ # uv installation is supported
85
+ pip install onescience[earth-gpu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai
86
+ ```
87
+
88
+ ### Training Data Introduction
89
+
90
+ The training entry point uses the OneScience `ERA5Dataset`. The data root is specified by `paths.data_root` in `conf/config.yaml`. The OneScience community provides a data slice for interface validation and training:
91
+
92
+ ```bash
93
+ hf download --repo-type dataset OneScience-Group/ERA5 --local-dir ./data
94
+ ```
95
+
96
+ ### Generate Synthetic Data
97
+
98
+ Real HDF5 files must contain a `fields` dataset, C85 variable attributes, six-hour intervals, and normalization statistics. When real data is unavailable, generate protocol-compatible synthetic files:
99
+
100
+ ```bash
101
+ python scripts/fake_data.py
102
+ ```
103
+
104
+ ### Training
105
+
106
+ Single GPU:
107
+
108
+ ```bash
109
+ python scripts/train.py
110
+ ```
111
+
112
+ Multi-GPU:
113
+
114
+ ```bash
115
+ torchrun --nproc_per_node=8 scripts/train.py
116
+ ```
117
+
118
+ Training checkpoints are saved to `data/checkpoint/model_bak.pth` by default, and metrics are saved to `output/training/metrics.json`.
119
+
120
+ ### Training Weights
121
+
122
+ This repository provides weights trained on ERA5 reanalysis data in the `weight/` folder. The weight files will be uploaded soon and are expected to be available in the near future.
123
+
124
+ ### Inference
125
+
126
+ ```bash
127
+ python scripts/inference.py
128
+ ```
129
+
130
+ Inference results are saved to `output/inference/forecast.nc` by default.
131
+
132
+ ### Evaluation and Visualization
133
+
134
+ ```bash
135
+ python scripts/result.py
136
+ ```
137
+
138
+ The default output is `figures/fuxi21_t2m.png`.
139
+
140
+ # Official OneScience Resources
141
+
142
+ | Platform | OneScience Main Repository | Skills Repository |
143
+ | --- | --- | --- |
144
+ | Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills |
145
+ | GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills |
146
+
147
+ # Citation and License
148
+
149
+ - This project is an unofficial forward-graph reproduction of FuXi v2.1. It does not represent official weights or training recipes released by Fudan University.
150
+ - This adapted repository is distributed under Apache License 2.0 metadata. ERA5 data, OneScience, and the upstream FuXi implementation remain subject to their respective official licenses and terms of use.
conf/config.yaml ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ protocol: non_official_protocol
2
+ seed: 42
3
+
4
+ paths:
5
+ data_root: data
6
+ static_root: data/static
7
+ checkpoint: data/checkpoint/model_bak.pth
8
+ training_metrics: output/training/metrics.json
9
+ inference_output: output/inference/forecast.nc
10
+ visualization_output: figures/fuxi21_t2m.png
11
+
12
+ data:
13
+ input_steps: 2
14
+ output_steps: 1
15
+ time_step_hours: 6
16
+ grid_size: [721, 1440]
17
+ crop_size: null
18
+ num_workers: 0
19
+ splits:
20
+ train:
21
+ years: [2021,2022]
22
+ time_steps: 10
23
+ val:
24
+ years: [2023]
25
+ time_steps: 10
26
+ inference:
27
+ years: [2024]
28
+ time_steps: 10
29
+ hdf5:
30
+ chunks: [1, 1, 64, 64]
31
+ compression: gzip
32
+ compression_level: 1
33
+
34
+ variables:
35
+ pressure_levels: [50, 100, 150, 200, 250, 300, 400, 500, 600, 700, 850, 925, 1000]
36
+ pressure: [z, t, u, v, q]
37
+ surface: [msl, t2m, d2m, sst, ws10m, ws100m, u10m, v10m, u100m, v100m, lcc, mcc, hcc, tcc, ssr, ssrd, fdir, ttr, tcw, tp]
38
+ diagnostic: [ssr, ssrd, fdir, ttr, tp]
39
+ mapping:
40
+ pressure_order: variable_major
41
+ pressure_name: "{variable}{level}"
42
+ surface_name: "{variable}"
43
+ source_dataset: fields
44
+ units: source_native
45
+ transform: identity
46
+
47
+ model:
48
+ profile: full
49
+ static_fields_file: data/static/static_fields.npy
50
+ channel_mask_file: data/static/channel_mask.npy
51
+ activation_checkpointing: true
52
+ profiles:
53
+ full:
54
+ grid_size: [721, 1440]
55
+ patch_size: 6
56
+ embed_dim: 1536
57
+ depth: 30
58
+ num_heads: 24
59
+ mlp_dim: 4096
60
+ window_size: 20
61
+ smoke:
62
+ grid_size: [13, 12]
63
+ patch_size: 6
64
+ embed_dim: 32
65
+ depth: 2
66
+ num_heads: 4
67
+ mlp_dim: 64
68
+ window_size: 2
69
+
70
+ training:
71
+ device: auto
72
+ epochs: 5
73
+ batch_size: 1
74
+ precision: fp32
75
+ distributed_strategy: ddp
76
+ fsdp_sharding: full_shard
77
+ gradient_accumulation_steps: 1
78
+ optimizer: AdamW
79
+ learning_rate: 0.0001
80
+ min_learning_rate: 0.000001
81
+ weight_decay: 0.01
82
+ scheduler: CosineAnnealingLR
83
+ gradient_clip_norm: 1.0
84
+ channel_weights: null
85
+ checkpoint_mode: scratch
86
+ load_checkpoint: null
87
+ save_checkpoint: data/checkpoint/model_bak.pth
88
+
89
+ inference:
90
+ device: auto
91
+ checkpoint: data/checkpoint/model_bak.pth
92
+ split: inference
93
+ steps: 1
94
+ zero_diagnostic_feedback: false
95
+ output_file: output/inference/forecast.nc
96
+
97
+ visualization:
98
+ input_file: output/inference/forecast.nc
99
+ output_file: figures/fuxi21_t2m.png
100
+ channel: t2m
101
+ cmap: coolwarm
config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "FuXi v2.1",
3
+ "model_type": "fuxi_v21",
4
+ "architectures": [
5
+ "FuXi21"
6
+ ],
7
+ "framework": "PyTorch",
8
+ "domain": "atmosphere",
9
+ "task": "global-medium-range-weather-forecasting",
10
+ "implementation": {
11
+ "entry_point": "model/FuXi21.py",
12
+ "scope": "trainable forward-graph reconstruction with full-resolution and smoke profiles"
13
+ },
14
+ "architecture": {
15
+ "family": "windowed Transformer with rotary attention and PixelShuffle decoder",
16
+ "grid_shape": [
17
+ 721,
18
+ 1440
19
+ ],
20
+ "input_channels": 85,
21
+ "output_channels": 85,
22
+ "static_channels": 6,
23
+ "patch_size": 6,
24
+ "embedding_size": 1536,
25
+ "depth": 30,
26
+ "attention_heads": 24,
27
+ "mlp_size": 4096,
28
+ "window_size": 20,
29
+ "activation": "SiLU/GELU"
30
+ },
31
+ "data": {
32
+ "dataset": "ERA5",
33
+ "spatial_resolution_degrees": 0.25,
34
+ "time_step_hours": 6,
35
+ "input_steps": 2,
36
+ "pressure_levels_hpa": [
37
+ 50,
38
+ 100,
39
+ 150,
40
+ 200,
41
+ 250,
42
+ 300,
43
+ 400,
44
+ 500,
45
+ 600,
46
+ 700,
47
+ 850,
48
+ 925,
49
+ 1000
50
+ ],
51
+ "protocol": "non_official_protocol"
52
+ },
53
+ "configuration_sources": [
54
+ "conf/config.yaml",
55
+ "model/FuXi21.py"
56
+ ]
57
+ }
configuration.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "framework": "PyTorch",
3
+ "task": "weather_forecasting",
4
+ "model": "FuXi_v21",
5
+ "input_format": "BTCHW",
6
+ "protocol": "non_official_protocol",
7
+ "default_config": "conf/config.yaml",
8
+ "train": "scripts/train.py",
9
+ "inference": "scripts/inference.py",
10
+ "evaluation": "scripts/result.py",
11
+ "visualization": "scripts/result.py"
12
+ }
model/FuXi21.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trainable FuXi 2.1 forward-graph reconstruction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from torch.utils.checkpoint import checkpoint as activation_checkpoint
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from torch import nn
11
+
12
+
13
+ DIAGNOSTIC_INDICES = (79, 80, 81, 82, 84)
14
+
15
+
16
+ class UnbiasedNorm(nn.Module):
17
+ """Layer normalization matching the PT2 graph's unbiased variance."""
18
+
19
+ def __init__(self, dim: int, conditioned: bool = False, eps: float = 1e-6) -> None:
20
+ super().__init__()
21
+ self.eps = eps
22
+ self.weight = nn.Parameter(torch.ones(dim))
23
+ self.conditioned = conditioned
24
+ self.scale_shift = nn.Sequential(nn.SiLU(), nn.Linear(dim, 2 * dim)) if conditioned else None
25
+
26
+ def forward(self, x: torch.Tensor, condition: torch.Tensor | None = None) -> torch.Tensor:
27
+ variance, mean = torch.var_mean(x, dim=-1, correction=1, keepdim=True)
28
+ x = (x - mean) * torch.rsqrt(variance + self.eps) * self.weight
29
+ if self.scale_shift is not None:
30
+ if condition is None:
31
+ raise ValueError("condition is required by conditioned normalization")
32
+ scale, shift = self.scale_shift(condition).chunk(2, dim=-1)
33
+ x = x * (1 + scale[:, None, :]) + shift[:, None, :]
34
+ return x
35
+
36
+
37
+ def _rope_frequencies(height: int, width: int, head_dim: int) -> tuple[torch.Tensor, torch.Tensor]:
38
+ if head_dim % 2:
39
+ raise ValueError("head_dim must be even for rotary embeddings")
40
+ y, x = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij")
41
+ positions = (y * width + x).flatten().float()
42
+ frequencies = 1.0 / (10000 ** (torch.arange(0, head_dim, 2).float() / head_dim))
43
+ angles = positions[:, None] * frequencies[None, :]
44
+ return angles.cos(), angles.sin()
45
+
46
+
47
+ def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
48
+ even, odd = x[..., 0::2], x[..., 1::2]
49
+ cos = cos[None, :, None, :].to(dtype=x.dtype, device=x.device)
50
+ sin = sin[None, :, None, :].to(dtype=x.dtype, device=x.device)
51
+ return torch.stack((even * cos - odd * sin, even * sin + odd * cos), dim=-1).flatten(-2)
52
+
53
+
54
+ def _window_partition(x: torch.Tensor, window: int) -> torch.Tensor:
55
+ batch, height, width, channels = x.shape
56
+ return x.view(batch, height // window, window, width // window, window, channels).permute(0, 1, 3, 2, 4, 5).reshape(-1, window * window, channels)
57
+
58
+
59
+ def _window_reverse(x: torch.Tensor, batch: int, height: int, width: int, window: int) -> torch.Tensor:
60
+ return x.view(batch, height // window, width // window, window, window, -1).permute(0, 1, 3, 2, 4, 5).reshape(batch, height, width, -1)
61
+
62
+
63
+ def _shift_mask(height: int, width: int, window: int) -> torch.Tensor:
64
+ shift = window // 2
65
+ labels = torch.zeros(1, height, width, 1)
66
+ h_slices = (slice(0, -window), slice(-window, -shift), slice(-shift, None))
67
+ w_slices = (slice(0, -window), slice(-window, -shift), slice(-shift, None))
68
+ index = 0
69
+ for h_slice in h_slices:
70
+ for w_slice in w_slices:
71
+ labels[:, h_slice, w_slice] = index
72
+ index += 1
73
+ labels = _window_partition(labels, window).squeeze(-1)
74
+ mask = labels[:, None, :] - labels[:, :, None]
75
+ return mask.masked_fill(mask != 0, float("-inf")).masked_fill(mask == 0, 0.0)
76
+
77
+
78
+ class HeadGatedWindowAttention(nn.Module):
79
+ def __init__(self, dim: int, num_heads: int, window: int, grid_size: tuple[int, int], shifted: bool) -> None:
80
+ super().__init__()
81
+ if dim % num_heads:
82
+ raise ValueError("dim must be divisible by num_heads")
83
+ self.num_heads = num_heads
84
+ self.head_dim = dim // num_heads
85
+ self.window = window
86
+ self.grid_size = grid_size
87
+ self.shifted = shifted
88
+ self.wq = nn.Linear(dim, num_heads * (self.head_dim + 1), bias=False)
89
+ self.wk = nn.Linear(dim, dim, bias=False)
90
+ self.wv = nn.Linear(dim, dim, bias=False)
91
+ self.wo = nn.Linear(dim, dim, bias=False)
92
+ cos, sin = _rope_frequencies(*grid_size, self.head_dim)
93
+ self.register_buffer("freqs_cos", cos, persistent=False)
94
+ self.register_buffer("freqs_sin", sin, persistent=False)
95
+ self.register_buffer("attention_mask", _shift_mask(*grid_size, window) if shifted else None, persistent=False)
96
+
97
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
98
+ batch, tokens, channels = x.shape
99
+ height, width = self.grid_size
100
+ qg = self.wq(x).view(batch, tokens, self.num_heads, self.head_dim + 1)
101
+ q, gate = qg[..., : self.head_dim], qg[..., -1:].sigmoid()
102
+ k = self.wk(x).view(batch, tokens, self.num_heads, self.head_dim)
103
+ v = self.wv(x).view(batch, tokens, self.num_heads, self.head_dim)
104
+ q = _apply_rope(q, self.freqs_cos, self.freqs_sin).reshape(batch, height, width, channels)
105
+ k = _apply_rope(k, self.freqs_cos, self.freqs_sin).reshape(batch, height, width, channels)
106
+ v = v.reshape(batch, height, width, channels)
107
+ gate = gate.reshape(batch, height, width, self.num_heads, 1)
108
+
109
+ if self.shifted:
110
+ shift = self.window // 2
111
+ q, k, v, gate = [torch.roll(item, shifts=(-shift, -shift), dims=(1, 2)) for item in (q, k, v, gate)]
112
+ q, k, v = [_window_partition(item, self.window).view(-1, self.window**2, self.num_heads, self.head_dim).transpose(1, 2) for item in (q, k, v)]
113
+ gate = _window_partition(gate.flatten(-2), self.window).view(-1, self.window**2, self.num_heads, 1).transpose(1, 2)
114
+ scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
115
+ if self.attention_mask is not None:
116
+ windows = self.attention_mask.shape[0]
117
+ scores = scores.view(batch, windows, self.num_heads, self.window**2, self.window**2)
118
+ scores = scores + self.attention_mask[None, :, None].to(scores)
119
+ scores = scores.flatten(0, 1)
120
+ output = torch.matmul(scores.softmax(dim=-1), v) * gate
121
+ output = output.transpose(1, 2).reshape(-1, self.window**2, channels)
122
+ output = _window_reverse(output, batch, height, width, self.window)
123
+ if self.shifted:
124
+ output = torch.roll(output, shifts=(self.window // 2, self.window // 2), dims=(1, 2))
125
+ return self.wo(output.reshape(batch, tokens, channels))
126
+
127
+
128
+ class FuXi21Block(nn.Module):
129
+ def __init__(self, dim: int, mlp_dim: int, num_heads: int, window: int, grid_size: tuple[int, int], shifted: bool) -> None:
130
+ super().__init__()
131
+ self.adaln = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim))
132
+ self.norm1 = UnbiasedNorm(dim)
133
+ self.attn = HeadGatedWindowAttention(dim, num_heads, window, grid_size, shifted)
134
+ self.norm2 = UnbiasedNorm(dim)
135
+ self.w1 = nn.Linear(dim, mlp_dim, bias=False)
136
+ self.w2 = nn.Linear(mlp_dim, dim, bias=False)
137
+ self.w3 = nn.Linear(dim, mlp_dim, bias=False)
138
+
139
+ def forward(self, x: torch.Tensor, condition: torch.Tensor) -> torch.Tensor:
140
+ attn_scale, attn_shift, attn_gate, mlp_scale, mlp_shift, mlp_gate = self.adaln(condition).chunk(6, dim=-1)
141
+ normalized = self.norm1(x) * (1 + attn_scale[:, None]) + attn_shift[:, None]
142
+ x = x + attn_gate[:, None] * self.attn(normalized)
143
+ normalized = self.norm2(x) * (1 + mlp_scale[:, None]) + mlp_shift[:, None]
144
+ mlp = self.w2(F.silu(self.w1(normalized)) * self.w3(normalized))
145
+ return x + mlp_gate[:, None] * mlp
146
+
147
+
148
+ class PixelShuffleHead(nn.Module):
149
+ def __init__(self, dim: int, output_channels: int) -> None:
150
+ super().__init__()
151
+ self.conv1 = nn.Conv2d(dim, 2 * dim, 3, padding=1)
152
+ self.conv2 = nn.Conv2d(dim // 2, output_channels * 9, 3, padding=1)
153
+
154
+ def forward(self, x: torch.Tensor, output_size: tuple[int, int]) -> torch.Tensor:
155
+ x = F.pad(x, (0, 0, 0, 1), mode="replicate")
156
+ x = F.gelu(F.pixel_shuffle(self.conv1(x), 2))
157
+ x = F.pixel_shuffle(self.conv2(x), 3)
158
+ return x[..., : output_size[0], : output_size[1]]
159
+
160
+
161
+ class FuXi21(nn.Module):
162
+ """Randomly initialized, trainable reconstruction of the FuXi 2.1 PT2 forward graph.
163
+
164
+ The defaults reproduce the recovered architecture; reduced dimensions and grids
165
+ are intended for smoke tests.
166
+ """
167
+
168
+ def __init__(
169
+ self,
170
+ static_fields: torch.Tensor,
171
+ channel_mask: torch.Tensor,
172
+ grid_size: tuple[int, int] = (721, 1440),
173
+ embed_dim: int = 1536,
174
+ depth: int = 30,
175
+ num_heads: int = 24,
176
+ mlp_dim: int = 4096,
177
+ patch_size: int = 6,
178
+ window_size: int = 20,
179
+ activation_checkpointing: bool = False,
180
+ ) -> None:
181
+ super().__init__()
182
+ height, width = grid_size
183
+ token_grid = (height // patch_size, width // patch_size)
184
+ if patch_size != 6:
185
+ raise ValueError("The recovered PixelShuffle decoder requires patch_size=6")
186
+ if any(size % window_size for size in token_grid):
187
+ raise ValueError(f"token grid {token_grid} must be divisible by window_size={window_size}")
188
+ if static_fields.shape != (6, height, width):
189
+ raise ValueError(f"static_fields must have shape {(6, height, width)}, got {tuple(static_fields.shape)}")
190
+ if channel_mask.shape != (85, height, width):
191
+ raise ValueError(f"channel_mask must have shape {(85, height, width)}, got {tuple(channel_mask.shape)}")
192
+ if embed_dim % 4:
193
+ raise ValueError("embed_dim must be divisible by 4 for the PixelShuffle heads")
194
+
195
+ self.grid_size = grid_size
196
+ self.token_grid = token_grid
197
+ self.activation_checkpointing = activation_checkpointing
198
+ self.register_buffer("static_fields", static_fields.detach().float())
199
+ self.register_buffer("channel_mask", channel_mask.detach().float())
200
+ self.patch_embed = nn.Conv2d(170, embed_dim, patch_size, stride=patch_size)
201
+ self.patch_norm = UnbiasedNorm(embed_dim)
202
+ self.const_embed = nn.Conv2d(6, embed_dim, patch_size, stride=patch_size)
203
+ self.const_norm = UnbiasedNorm(embed_dim)
204
+ self.joint_embed_layer = nn.Sequential(nn.Linear(384, embed_dim), nn.SiLU(), nn.Linear(embed_dim, embed_dim))
205
+ self.layers = nn.ModuleList(
206
+ FuXi21Block(embed_dim, mlp_dim, num_heads, window_size, token_grid, bool(index % 2))
207
+ for index in range(depth)
208
+ )
209
+ self.norm_layer = UnbiasedNorm(embed_dim, conditioned=True)
210
+ self.pressure_head = nn.ConvTranspose2d(embed_dim, 65, 9, stride=6, padding=1)
211
+ self.surface_head = PixelShuffleHead(embed_dim, 15)
212
+ self.derived_head = PixelShuffleHead(embed_dim, 5)
213
+ self.register_buffer("scatter_idx", torch.tensor([*range(79), 83, 79, 80, 81, 82, 84]), persistent=False)
214
+ self.reset_parameters()
215
+
216
+ @classmethod
217
+ def smoke(
218
+ cls,
219
+ static_fields: torch.Tensor | None = None,
220
+ channel_mask: torch.Tensor | None = None,
221
+ ) -> "FuXi21":
222
+ static_fields = torch.zeros(6, 13, 12) if static_fields is None else static_fields
223
+ channel_mask = torch.ones(85, 13, 12) if channel_mask is None else channel_mask
224
+ return cls(
225
+ static_fields,
226
+ channel_mask,
227
+ grid_size=(13, 12),
228
+ embed_dim=32,
229
+ depth=2,
230
+ num_heads=4,
231
+ mlp_dim=64,
232
+ window_size=2,
233
+ )
234
+
235
+ def reset_parameters(self) -> None:
236
+ for module in self.modules():
237
+ if isinstance(module, nn.Linear):
238
+ nn.init.trunc_normal_(module.weight, std=0.02)
239
+ if module.bias is not None:
240
+ nn.init.zeros_(module.bias)
241
+ elif isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)):
242
+ nn.init.xavier_uniform_(module.weight)
243
+ if module.bias is not None:
244
+ nn.init.zeros_(module.bias)
245
+ for block in self.layers:
246
+ nn.init.zeros_(block.adaln[-1].weight)
247
+ nn.init.zeros_(block.adaln[-1].bias)
248
+ nn.init.zeros_(self.norm_layer.scale_shift[-1].weight)
249
+ nn.init.zeros_(self.norm_layer.scale_shift[-1].bias)
250
+ for head in (self.pressure_head, self.surface_head.conv2, self.derived_head.conv2):
251
+ nn.init.trunc_normal_(head.weight, std=1e-3)
252
+
253
+ @staticmethod
254
+ def _time_embedding(value: torch.Tensor, periodic: bool) -> torch.Tensor:
255
+ frequency = torch.arange(64, device=value.device, dtype=value.dtype)
256
+ if periodic:
257
+ angles = 2 * math.pi * value.reshape(-1, 1) * frequency
258
+ else:
259
+ angles = value.reshape(-1, 1) / (10000 ** (frequency / 64))
260
+ return torch.cat((angles.sin(), angles.cos()), dim=-1)
261
+
262
+ def forward(self, state: torch.Tensor, step: torch.Tensor, hour: torch.Tensor, doy: torch.Tensor) -> torch.Tensor:
263
+ expected = (2, 85, *self.grid_size)
264
+ if tuple(state.shape[1:]) != expected:
265
+ raise ValueError(f"state must have shape (B, {expected}), got {tuple(state.shape)}")
266
+ state = torch.nan_to_num(state)
267
+ state = state.clone()
268
+ state[:, :, DIAGNOSTIC_INDICES] = 0
269
+ state = state * self.channel_mask
270
+ previous = state[:, -1]
271
+ batch = state.shape[0]
272
+
273
+ x = self.patch_embed(state.reshape(batch, 170, *self.grid_size)).flatten(2).transpose(1, 2)
274
+ x = self.patch_norm(x)
275
+ const = self.const_embed(self.static_fields[None].expand(batch, -1, -1, -1)).flatten(2).transpose(1, 2)
276
+ x = x + self.const_norm(const)
277
+ time_features = torch.cat(
278
+ (self._time_embedding(step, False), self._time_embedding(hour, True), self._time_embedding(doy, True)), dim=-1
279
+ )
280
+ condition = self.joint_embed_layer(time_features)
281
+ for layer in self.layers:
282
+ if self.training and self.activation_checkpointing:
283
+ x = activation_checkpoint(layer, x, condition, use_reentrant=False)
284
+ else:
285
+ x = layer(x, condition)
286
+ x = self.norm_layer(x, condition).transpose(1, 2).reshape(batch, -1, *self.token_grid)
287
+
288
+ pressure = self.pressure_head(x)[..., : self.grid_size[0], : self.grid_size[1]]
289
+ surface = self.surface_head(x, self.grid_size)
290
+ derived = self.derived_head(x, self.grid_size)
291
+ grouped = torch.cat((pressure, surface, derived), dim=1)
292
+ prediction = torch.empty_like(grouped)
293
+ prediction[:, self.scatter_idx] = grouped
294
+ return torch.stack((previous, prediction), dim=1)
295
+
296
+ @property
297
+ def trainable(self) -> bool:
298
+ return True
scripts/build_static.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build project-defined FuXi static fields and C85 validity mask from scratch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+
7
+ import numpy as np
8
+
9
+ from common import load_config, resolve_path
10
+ from variables import c85_from_config
11
+
12
+
13
+ def build_static_fields(height: int, width: int) -> np.ndarray:
14
+ latitude = np.deg2rad(np.linspace(90.0, -90.0, height, dtype=np.float32))[:, None]
15
+ longitude = np.deg2rad(np.arange(width, dtype=np.float32) * (360.0 / width))[None, :]
16
+ lat = np.broadcast_to(latitude, (height, width))
17
+ lon = np.broadcast_to(longitude, (height, width))
18
+ geopotential = np.zeros_like(lat)
19
+ land_sea = np.ones_like(lat)
20
+ return np.stack((geopotential, land_sea, np.cos(lat), np.sin(lat), np.cos(lon), np.sin(lon)))
21
+
22
+
23
+ def build_channel_mask(channels: list[str], height: int, width: int) -> np.ndarray:
24
+ # The reconstruction has no external missing-channel metadata; all C85 fields are valid.
25
+ return np.ones((len(channels), height, width), dtype=np.float32)
26
+
27
+
28
+ def ensure_static_resources(cfg: dict, force: bool = False) -> tuple:
29
+ channels, _ = c85_from_config(cfg)
30
+ profile = cfg["model"]["profiles"]["full"]
31
+ height, width = profile["grid_size"]
32
+ static_path = resolve_path(cfg["model"]["static_fields_file"], cfg)
33
+ mask_path = resolve_path(cfg["model"]["channel_mask_file"], cfg)
34
+ static_path.parent.mkdir(parents=True, exist_ok=True)
35
+ mask_path.parent.mkdir(parents=True, exist_ok=True)
36
+ if force or not static_path.is_file():
37
+ np.save(static_path, build_static_fields(height, width))
38
+ if force or not mask_path.is_file():
39
+ np.save(mask_path, build_channel_mask(channels, height, width))
40
+ return static_path, mask_path
41
+
42
+
43
+ def main() -> None:
44
+ parser = argparse.ArgumentParser(description=__doc__)
45
+ parser.add_argument("--config", default="conf/config.yaml")
46
+ args = parser.parse_args()
47
+ cfg = load_config(args.config)
48
+ static_path, mask_path = ensure_static_resources(cfg, force=True)
49
+ print(f"Saved from-scratch static resources to {static_path} and {mask_path}")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
scripts/common.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import yaml
7
+
8
+
9
+ ROOT = Path(__file__).resolve().parents[1]
10
+ if str(ROOT) not in sys.path:
11
+ sys.path.insert(0, str(ROOT))
12
+
13
+
14
+ def load_config(path: str | Path) -> dict:
15
+ path = Path(path)
16
+ with path.open("r", encoding="utf-8") as handle:
17
+ config = yaml.safe_load(handle)
18
+ config["_config_dir"] = str(path.resolve().parent)
19
+ return config
20
+
21
+
22
+ def resolve_path(value: str, config: dict) -> Path:
23
+ path = Path(value).expanduser()
24
+ if path.is_absolute():
25
+ return path
26
+ return (Path(config["_config_dir"]).parent / path).resolve()
scripts/fake_data.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Create an ERA5-style HDF5 dataset consumable by OneScience ERA5Dataset."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ import h5py
9
+ import numpy as np
10
+
11
+ from common import load_config, resolve_path
12
+ from variables import c85_from_config
13
+
14
+
15
+ def create_year(
16
+ path: Path,
17
+ year: int,
18
+ steps: int,
19
+ height: int,
20
+ width: int,
21
+ channels: list[str],
22
+ time_step_hours: int,
23
+ hdf5_config: dict,
24
+ ) -> None:
25
+ path.parent.mkdir(parents=True, exist_ok=True)
26
+ with h5py.File(path, "w") as handle:
27
+ fields = handle.create_dataset(
28
+ "fields",
29
+ shape=(steps, len(channels), height, width),
30
+ dtype="float32",
31
+ chunks=tuple(min(size, limit) for size, limit in zip((steps, len(channels), height, width), hdf5_config["chunks"])),
32
+ fillvalue=0.0,
33
+ compression=hdf5_config["compression"],
34
+ compression_opts=hdf5_config["compression_level"],
35
+ )
36
+ fields.attrs["variables"] = np.asarray(channels, dtype=h5py.string_dtype("utf-8"))
37
+ fields.attrs["time_step"] = time_step_hours
38
+ fields.attrs["year"] = year
39
+ lat = np.linspace(90.0, -90.0, height, dtype=np.float32)[:, None]
40
+ lon = np.arange(width, dtype=np.float32)[None, :] * (360.0 / width)
41
+ t2m_index = channels.index("t2m")
42
+ for step in range(steps):
43
+ fields[step, t2m_index] = (
44
+ np.cos(np.deg2rad(lat)) * np.cos(np.deg2rad(lon + step * 15.0))
45
+ )
46
+ handle.create_dataset("global_means", data=np.zeros((1, len(channels), 1, 1), dtype=np.float32))
47
+ handle.create_dataset("global_stds", data=np.ones((1, len(channels), 1, 1), dtype=np.float32))
48
+
49
+
50
+ def main() -> None:
51
+ parser = argparse.ArgumentParser()
52
+ parser.add_argument("--config", default="conf/config.yaml")
53
+ args = parser.parse_args()
54
+ cfg = load_config(args.config)
55
+ data_cfg = cfg["data"]
56
+ channels, _ = c85_from_config(cfg)
57
+ root = resolve_path(cfg["paths"]["data_root"], cfg)
58
+ generated_years = set()
59
+ for split, split_cfg in data_cfg["splits"].items():
60
+ for year in split_cfg["years"]:
61
+ if year in generated_years:
62
+ raise ValueError(f"Year {year} is assigned to more than one data split")
63
+ generated_years.add(year)
64
+ create_year(
65
+ root / "data" / f"{year}.h5",
66
+ year,
67
+ split_cfg["time_steps"],
68
+ *data_cfg["grid_size"],
69
+ channels,
70
+ data_cfg["time_step_hours"],
71
+ data_cfg["hdf5"],
72
+ )
73
+ print(f"Created ERA5-compatible yearly datasets at {root / 'data'}")
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
scripts/inference.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Autoregressive inference using a project-produced FuXi 2.1 checkpoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from datetime import datetime, timedelta
7
+
8
+ import numpy as np
9
+ import torch
10
+ import xarray as xr
11
+ from onescience.datapipes.climate.era5 import ERA5Dataset
12
+
13
+ from common import load_config, resolve_path
14
+ from model.FuXi21 import FuXi21
15
+ from variables import c85_from_config
16
+
17
+
18
+ CHECKPOINT_FORMAT = "fuxi21_reconstructed_checkpoint_v1"
19
+
20
+
21
+ def select_device(requested: str) -> torch.device:
22
+ if requested not in {"auto", "cpu", "cuda"}:
23
+ raise ValueError("inference.device must be auto, cpu, or cuda")
24
+ if requested == "cuda" or (requested == "auto" and torch.cuda.is_available()):
25
+ if not torch.cuda.is_available():
26
+ raise RuntimeError("inference.device=cuda, but no CUDA/HIP device is available")
27
+ return torch.device("cuda")
28
+ return torch.device("cpu")
29
+
30
+
31
+ def load_array(path_value: str | None, cfg: dict, shape: tuple[int, ...], name: str) -> torch.Tensor:
32
+ if path_value is None:
33
+ raise ValueError(f"model.{name}_file is required outside the smoke profile")
34
+ path = resolve_path(path_value, cfg)
35
+ value = torch.from_numpy(np.load(path)).float()
36
+ if tuple(value.shape) != shape:
37
+ raise ValueError(f"{name} must have shape {shape}, got {tuple(value.shape)}")
38
+ return value
39
+
40
+
41
+ def build_model(cfg: dict) -> FuXi21:
42
+ model_cfg = cfg["model"]
43
+ profile_name = model_cfg["profile"]
44
+ profile = model_cfg["profiles"][profile_name]
45
+ height, width = profile["grid_size"]
46
+ if profile_name == "smoke":
47
+ static_fields = torch.zeros(6, height, width)
48
+ channel_mask = torch.ones(85, height, width)
49
+ else:
50
+ static_fields = load_array(model_cfg["static_fields_file"], cfg, (6, height, width), "static_fields")
51
+ channel_mask = load_array(model_cfg["channel_mask_file"], cfg, (85, height, width), "channel_mask")
52
+ return FuXi21(
53
+ static_fields,
54
+ channel_mask,
55
+ activation_checkpointing=False,
56
+ **profile,
57
+ )
58
+
59
+
60
+ def temporal_features(valid_time: datetime, step: int, device: torch.device) -> tuple[torch.Tensor, ...]:
61
+ return (
62
+ torch.tensor([step], device=device, dtype=torch.float32),
63
+ torch.tensor([(valid_time.hour * 60 + valid_time.minute) / 1440], device=device),
64
+ torch.tensor([min(365, valid_time.timetuple().tm_yday) / 365], device=device),
65
+ )
66
+
67
+
68
+ def main() -> None:
69
+ parser = argparse.ArgumentParser(description=__doc__)
70
+ parser.add_argument("--config", default="conf/config.yaml")
71
+ parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default=None)
72
+ parser.add_argument("--preflight-only", action="store_true")
73
+ args = parser.parse_args()
74
+ cfg = load_config(args.config)
75
+ if cfg.get("protocol") != "non_official_protocol":
76
+ raise ValueError("Inference config must declare protocol: non_official_protocol")
77
+
78
+ infer_cfg = cfg["inference"]
79
+ channels, diagnostics = c85_from_config(cfg)
80
+ checkpoint_path = resolve_path(infer_cfg["checkpoint"], cfg)
81
+ if not checkpoint_path.is_file():
82
+ raise FileNotFoundError(f"Project checkpoint not found: {checkpoint_path}")
83
+ device = select_device(args.device or infer_cfg["device"])
84
+ checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=True)
85
+ if checkpoint.get("format") != CHECKPOINT_FORMAT:
86
+ raise ValueError(f"Checkpoint must use format {CHECKPOINT_FORMAT}")
87
+ if checkpoint.get("protocol") != "non_official_protocol":
88
+ raise ValueError("Checkpoint protocol must be non_official_protocol")
89
+ if checkpoint.get("model_profile") != cfg["model"]["profile"]:
90
+ raise ValueError("Checkpoint model profile does not match the configured model profile")
91
+ if args.preflight_only:
92
+ print(f"checkpoint={checkpoint_path}, profile={checkpoint['model_profile']}, device={device}")
93
+ return
94
+
95
+ model = build_model(cfg).to(device)
96
+ model.load_state_dict(checkpoint["model"])
97
+ model.eval()
98
+ split = infer_cfg["split"]
99
+ split_cfg = cfg["data"]["splits"][split]
100
+ dataset = ERA5Dataset(
101
+ dataset_dir=str(resolve_path(cfg["paths"]["data_root"], cfg)),
102
+ used_years=split_cfg["years"],
103
+ used_variables=channels,
104
+ input_steps=cfg["data"]["input_steps"],
105
+ output_steps=cfg["data"]["output_steps"],
106
+ normalize=True,
107
+ )
108
+ state, _, _, _, time_index = dataset[0]
109
+ crop_size = cfg["data"]["crop_size"]
110
+ if crop_size is not None:
111
+ state = state[..., : crop_size[0], : crop_size[1]]
112
+ state = state.unsqueeze(0).to(device)
113
+ valid_time = datetime.strptime(time_index[-1], "%Y%m%d%H")
114
+ interval = timedelta(hours=cfg["data"]["time_step_hours"])
115
+ diagnostic_indices = [channels.index(name) for name in diagnostics]
116
+ forecasts = []
117
+ valid_times = []
118
+ for step in range(infer_cfg["steps"]):
119
+ with torch.inference_mode():
120
+ state = model(state, *temporal_features(valid_time, step, device))
121
+ forecasts.append(state[:, -1].float().cpu().numpy()[0])
122
+ valid_times.append(np.datetime64(valid_time))
123
+ if infer_cfg["zero_diagnostic_feedback"]:
124
+ state[:, -1, diagnostic_indices] = 0
125
+ valid_time += interval
126
+
127
+ height, width = forecasts[0].shape[-2:]
128
+ output_path = resolve_path(infer_cfg["output_file"], cfg)
129
+ output_path.parent.mkdir(parents=True, exist_ok=True)
130
+ xr.DataArray(
131
+ np.stack(forecasts),
132
+ dims=("time", "channel", "lat", "lon"),
133
+ coords={
134
+ "time": valid_times,
135
+ "channel": channels,
136
+ "lat": np.linspace(90, -90, height),
137
+ "lon": np.arange(width) * (360 / width),
138
+ },
139
+ attrs={"checkpoint_format": CHECKPOINT_FORMAT, "protocol": cfg["protocol"]},
140
+ name="forecast",
141
+ ).to_netcdf(output_path)
142
+ print(f"Saved {len(forecasts)} forecast step(s) to {output_path}")
143
+
144
+
145
+ if __name__ == "__main__":
146
+ main()
scripts/result.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+
6
+ import matplotlib.pyplot as plt
7
+ import xarray as xr
8
+
9
+ from common import load_config, resolve_path
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument("--config", default="conf/config.yaml")
15
+ parser.add_argument("--input", default=None)
16
+ parser.add_argument("--channel", default=None)
17
+ args = parser.parse_args()
18
+ cfg = load_config(args.config)
19
+ viz = cfg["visualization"]
20
+ source = Path(args.input) if args.input else resolve_path(viz["input_file"], cfg)
21
+ channel = args.channel or viz["channel"]
22
+ data = xr.open_dataarray(source).sel(channel=channel)
23
+ if "time" in data.dims:
24
+ data = data.isel(time=-1)
25
+ output = resolve_path(viz["output_file"], cfg)
26
+ output.parent.mkdir(parents=True, exist_ok=True)
27
+ fig, ax = plt.subplots(figsize=(12, 5), constrained_layout=True)
28
+ image = ax.pcolormesh(data.lon, data.lat, data, shading="auto", cmap=viz["cmap"])
29
+ valid_time = str(data.time.values) if "time" in data.coords else ""
30
+ ax.set(title=f"FuXi 2.1 {channel} | {valid_time}", xlabel="Longitude", ylabel="Latitude")
31
+ fig.colorbar(image, ax=ax, label=channel)
32
+ fig.savefig(output, dpi=160)
33
+ plt.close(fig)
34
+ print(f"Saved visualization to {output}")
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()
scripts/train.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Non-official from-scratch training baseline for the FuXi 2.1 reconstruction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import random
9
+ from contextlib import nullcontext
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import torch
15
+ import torch.distributed as dist
16
+ from onescience.datapipes.climate.era5 import ERA5Dataset
17
+ from torch.nn.parallel import DistributedDataParallel
18
+ from torch.utils.data import DataLoader
19
+ from torch.utils.data.distributed import DistributedSampler
20
+
21
+ from common import load_config, resolve_path
22
+ from build_static import ensure_static_resources
23
+ from model.FuXi21 import FuXi21
24
+ from variables import c85_from_config
25
+
26
+ try:
27
+ from torch.distributed.fsdp import (
28
+ FullStateDictConfig,
29
+ FullyShardedDataParallel,
30
+ ShardingStrategy,
31
+ StateDictType,
32
+ )
33
+ except ImportError: # pragma: no cover - depends on the installed torch build
34
+ FullyShardedDataParallel = None
35
+ FullStateDictConfig = None
36
+ ShardingStrategy = None
37
+ StateDictType = None
38
+
39
+
40
+ def setup_distributed(device: torch.device) -> tuple[bool, int, int, int]:
41
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
42
+ distributed = world_size > 1
43
+ if distributed:
44
+ dist.init_process_group(backend="nccl" if device.type == "cuda" else "gloo")
45
+ rank = dist.get_rank() if distributed else 0
46
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
47
+ return distributed, rank, local_rank, world_size
48
+
49
+
50
+ def select_device(requested: str, local_rank: int) -> torch.device:
51
+ if requested not in {"auto", "cpu", "cuda"}:
52
+ raise ValueError("training.device must be auto, cpu, or cuda")
53
+ use_accelerator = requested == "cuda" or (requested == "auto" and torch.cuda.is_available())
54
+ if use_accelerator:
55
+ if not torch.cuda.is_available():
56
+ raise RuntimeError("training.device=cuda, but no CUDA/HIP device is available")
57
+ if local_rank >= torch.cuda.device_count():
58
+ raise RuntimeError(
59
+ f"LOCAL_RANK={local_rank} exceeds {torch.cuda.device_count()} visible CUDA/HIP device(s); "
60
+ "use one process per visible device or --device cpu for DDP logic testing"
61
+ )
62
+ torch.cuda.set_device(local_rank)
63
+ return torch.device("cuda", local_rank)
64
+ return torch.device("cpu")
65
+
66
+
67
+ def seed_everything(seed: int, rank: int) -> None:
68
+ seed += rank
69
+ random.seed(seed)
70
+ np.random.seed(seed)
71
+ torch.manual_seed(seed)
72
+ if torch.cuda.is_available():
73
+ torch.cuda.manual_seed_all(seed)
74
+
75
+
76
+ def load_array(path_value: str | None, cfg: dict, expected_shape: tuple[int, ...], name: str) -> torch.Tensor:
77
+ if path_value is None:
78
+ raise ValueError(f"model.{name}_file is required outside the smoke profile")
79
+ path = resolve_path(path_value, cfg)
80
+ if not path.is_file():
81
+ raise FileNotFoundError(f"{name} file not found: {path}")
82
+ value = torch.from_numpy(np.load(path)).float()
83
+ if tuple(value.shape) != expected_shape:
84
+ raise ValueError(f"{name} must have shape {expected_shape}, got {tuple(value.shape)}")
85
+ return value
86
+
87
+
88
+ def build_model(cfg: dict) -> FuXi21:
89
+ model_cfg = cfg["model"]
90
+ profile_name = model_cfg["profile"]
91
+ profile = model_cfg["profiles"][profile_name]
92
+ height, width = profile["grid_size"]
93
+ if profile_name == "smoke":
94
+ static_fields = torch.zeros(6, height, width)
95
+ channel_mask = torch.ones(85, height, width)
96
+ else:
97
+ static_fields = load_array(model_cfg["static_fields_file"], cfg, (6, height, width), "static_fields")
98
+ channel_mask = load_array(model_cfg["channel_mask_file"], cfg, (85, height, width), "channel_mask")
99
+ return FuXi21(
100
+ static_fields=static_fields,
101
+ channel_mask=channel_mask,
102
+ activation_checkpointing=cfg["model"].get("activation_checkpointing", False),
103
+ **profile,
104
+ )
105
+
106
+
107
+ def wrap_distributed_model(model: FuXi21, cfg: dict, device: torch.device, local_rank: int):
108
+ strategy = cfg["training"].get("distributed_strategy", "ddp")
109
+ if strategy == "ddp":
110
+ return DistributedDataParallel(model, device_ids=[local_rank] if device.type == "cuda" else None)
111
+ if strategy != "fsdp":
112
+ raise ValueError("training.distributed_strategy must be ddp or fsdp")
113
+ if FullyShardedDataParallel is None:
114
+ raise RuntimeError("This PyTorch build does not provide torch.distributed.fsdp")
115
+ if device.type == "cpu":
116
+ raise RuntimeError("FSDP training requires an accelerator device")
117
+ sharding = cfg["training"].get("fsdp_sharding", "full_shard")
118
+ if sharding != "full_shard":
119
+ raise ValueError("Only fsdp_sharding=full_shard is currently supported")
120
+ return FullyShardedDataParallel(
121
+ model,
122
+ device_id=device,
123
+ sharding_strategy=ShardingStrategy.FULL_SHARD,
124
+ use_orig_params=True,
125
+ )
126
+
127
+
128
+ def is_fsdp(model) -> bool:
129
+ return FullyShardedDataParallel is not None and isinstance(model, FullyShardedDataParallel)
130
+
131
+
132
+ def unwrap_model(model):
133
+ if isinstance(model, DistributedDataParallel) or is_fsdp(model):
134
+ return model.module
135
+ return model
136
+
137
+
138
+ def build_loader(cfg: dict, split: str, distributed: bool, train: bool):
139
+ data_cfg = cfg["data"]
140
+ channels, _ = c85_from_config(cfg)
141
+ split_cfg = data_cfg["splits"][split]
142
+ dataset_root = resolve_path(cfg["paths"]["data_root"], cfg)
143
+ dataset = ERA5Dataset(
144
+ dataset_dir=str(dataset_root),
145
+ used_years=split_cfg["years"],
146
+ used_variables=channels,
147
+ input_steps=data_cfg["input_steps"],
148
+ output_steps=data_cfg["output_steps"],
149
+ normalize=True,
150
+ )
151
+ sampler = DistributedSampler(dataset, shuffle=train) if distributed else None
152
+ loader = DataLoader(
153
+ dataset,
154
+ batch_size=cfg["training"]["batch_size"],
155
+ shuffle=train and sampler is None,
156
+ sampler=sampler,
157
+ num_workers=data_cfg["num_workers"],
158
+ pin_memory=torch.cuda.is_available(),
159
+ drop_last=train and distributed,
160
+ )
161
+ return loader, sampler
162
+
163
+
164
+ def crop_batch(inputs: torch.Tensor, targets: torch.Tensor, crop_size: list[int] | None):
165
+ if crop_size is None:
166
+ return inputs, targets
167
+ height, width = crop_size
168
+ return inputs[..., :height, :width], targets[..., :height, :width]
169
+
170
+
171
+ def temporal_features(time_index, device: torch.device) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
172
+ target_times = time_index[-1]
173
+ if isinstance(target_times, str):
174
+ target_times = [target_times]
175
+ parsed = [datetime.strptime(value, "%Y%m%d%H") for value in target_times]
176
+ step = torch.zeros(len(parsed), device=device)
177
+ hour = torch.tensor([(value.hour * 60 + value.minute) / 1440 for value in parsed], device=device)
178
+ doy = torch.tensor([min(365, value.timetuple().tm_yday) / 365 for value in parsed], device=device)
179
+ return step, hour, doy
180
+
181
+
182
+ def weighted_mse(prediction: torch.Tensor, target: torch.Tensor, channel_weights: torch.Tensor) -> torch.Tensor:
183
+ latitude = torch.linspace(90, -90, prediction.shape[-2], device=prediction.device, dtype=prediction.dtype)
184
+ area = latitude.deg2rad().cos().clamp_min(0)
185
+ area = area / area.mean()
186
+ weights = channel_weights.to(prediction).view(1, -1, 1, 1) * area.view(1, 1, -1, 1)
187
+ return ((prediction - target).square() * weights).mean()
188
+
189
+
190
+ def autocast_context(device: torch.device, precision: str):
191
+ if precision == "fp32":
192
+ return nullcontext()
193
+ if precision != "bf16":
194
+ raise ValueError("training.precision must be fp32 or bf16")
195
+ return torch.autocast(device_type=device.type, dtype=torch.bfloat16)
196
+
197
+
198
+ def run_epoch(model, loader, optimizer, device, cfg, channel_weights, train: bool) -> float:
199
+ model.train(train)
200
+ total_loss = torch.zeros((), device=device)
201
+ total_samples = torch.zeros((), device=device)
202
+ clip_norm = cfg["training"]["gradient_clip_norm"]
203
+ accumulation_steps = max(1, int(cfg["training"].get("gradient_accumulation_steps", 1)))
204
+ if train:
205
+ optimizer.zero_grad(set_to_none=True)
206
+ for batch_index, (inputs, targets, _, _, time_index) in enumerate(loader):
207
+ inputs, targets = crop_batch(inputs, targets, cfg["data"]["crop_size"])
208
+ inputs = inputs.to(device, non_blocking=True)
209
+ targets = targets.to(device, non_blocking=True)
210
+ if targets.ndim == 5:
211
+ targets = targets[:, 0]
212
+ temporal = temporal_features(time_index, device)
213
+ with torch.set_grad_enabled(train), autocast_context(device, cfg["training"]["precision"]):
214
+ prediction = model(inputs, *temporal)[:, -1]
215
+ loss = weighted_mse(prediction, targets, channel_weights)
216
+ if train:
217
+ (loss / accumulation_steps).backward()
218
+ if (batch_index + 1) % accumulation_steps == 0:
219
+ torch.nn.utils.clip_grad_norm_(model.parameters(), clip_norm)
220
+ optimizer.step()
221
+ optimizer.zero_grad(set_to_none=True)
222
+ batch_size = inputs.shape[0]
223
+ total_loss += loss.detach() * batch_size
224
+ total_samples += batch_size
225
+ if train and len(loader) % accumulation_steps:
226
+ torch.nn.utils.clip_grad_norm_(model.parameters(), clip_norm)
227
+ optimizer.step()
228
+ optimizer.zero_grad(set_to_none=True)
229
+ if dist.is_initialized():
230
+ dist.all_reduce(total_loss)
231
+ dist.all_reduce(total_samples)
232
+ return (total_loss / total_samples).item()
233
+
234
+
235
+ def checkpoint_state(model, optimizer, scheduler, epoch: int, cfg: dict) -> dict:
236
+ if is_fsdp(model):
237
+ state_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
238
+ with FullyShardedDataParallel.state_dict_type(model, StateDictType.FULL_STATE_DICT, state_config):
239
+ model_state = model.state_dict()
240
+ optimizer_state = FullyShardedDataParallel.optim_state_dict(model, optimizer)
241
+ else:
242
+ model_state = unwrap_model(model).state_dict()
243
+ optimizer_state = optimizer.state_dict()
244
+ return {
245
+ "format": "fuxi21_reconstructed_checkpoint_v1",
246
+ "protocol": cfg["protocol"],
247
+ "model": model_state,
248
+ "optimizer": optimizer_state,
249
+ "scheduler": scheduler.state_dict(),
250
+ "epoch": epoch,
251
+ "model_profile": cfg["model"]["profile"],
252
+ "model_config": cfg["model"]["profiles"][cfg["model"]["profile"]],
253
+ "distributed_strategy": cfg["training"].get("distributed_strategy", "ddp"),
254
+ }
255
+
256
+
257
+ def load_checkpoint(path: Path, mode: str, model, optimizer, scheduler, device: torch.device) -> int:
258
+ state = torch.load(path, map_location=device, weights_only=True)
259
+ if state.get("format") != "fuxi21_reconstructed_checkpoint_v1":
260
+ raise ValueError("Only checkpoints produced by this reconstruction can be loaded")
261
+ if is_fsdp(model):
262
+ state_config = FullStateDictConfig(offload_to_cpu=False, rank0_only=False)
263
+ with FullyShardedDataParallel.state_dict_type(model, StateDictType.FULL_STATE_DICT, state_config):
264
+ model.load_state_dict(state["model"])
265
+ else:
266
+ unwrap_model(model).load_state_dict(state["model"])
267
+ if mode == "resume":
268
+ if is_fsdp(model):
269
+ optimizer_state = FullyShardedDataParallel.optim_state_dict_to_load(
270
+ model, optimizer, state["optimizer"]
271
+ )
272
+ optimizer.load_state_dict(optimizer_state)
273
+ else:
274
+ optimizer.load_state_dict(state["optimizer"])
275
+ scheduler.load_state_dict(state["scheduler"])
276
+ return int(state["epoch"]) + 1
277
+ if mode == "initialize":
278
+ return 0
279
+ raise ValueError("checkpoint_mode must be scratch, initialize, or resume")
280
+
281
+
282
+ def main() -> None:
283
+ parser = argparse.ArgumentParser(description=__doc__)
284
+ parser.add_argument("--config", default="conf/config.yaml")
285
+ parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default=None)
286
+ parser.add_argument("--dry-run", action="store_true", help="Run one train and validation batch without saving")
287
+ args = parser.parse_args()
288
+ cfg = load_config(args.config)
289
+ if cfg.get("protocol") != "non_official_protocol":
290
+ raise ValueError("Training config must declare protocol: non_official_protocol")
291
+
292
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
293
+ device = select_device(args.device or cfg["training"]["device"], local_rank)
294
+ distributed, rank, local_rank, _ = setup_distributed(device)
295
+ seed_everything(cfg["seed"], rank)
296
+ if cfg["model"]["profile"] == "full":
297
+ if rank == 0:
298
+ ensure_static_resources(cfg)
299
+ if distributed:
300
+ dist.barrier()
301
+ model = build_model(cfg).to(device)
302
+ if distributed:
303
+ model = wrap_distributed_model(model, cfg, device, local_rank)
304
+ train_years = set(cfg["data"]["splits"]["train"]["years"])
305
+ val_years = set(cfg["data"]["splits"]["val"]["years"])
306
+ if train_years & val_years:
307
+ raise ValueError("train and val years must be disjoint")
308
+ train_loader, train_sampler = build_loader(cfg, "train", distributed, True)
309
+ val_loader, _ = build_loader(cfg, "val", distributed, False)
310
+
311
+ train_cfg = cfg["training"]
312
+ if train_cfg["optimizer"] != "AdamW" or train_cfg["scheduler"] != "CosineAnnealingLR":
313
+ raise ValueError("This baseline supports optimizer=AdamW and scheduler=CosineAnnealingLR")
314
+ optimizer = torch.optim.AdamW(model.parameters(), lr=train_cfg["learning_rate"], weight_decay=train_cfg["weight_decay"])
315
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
316
+ optimizer, T_max=train_cfg["epochs"], eta_min=train_cfg["min_learning_rate"]
317
+ )
318
+ channel_weights = train_cfg["channel_weights"]
319
+ channel_weights = torch.ones(85) if channel_weights is None else torch.tensor(channel_weights, dtype=torch.float32)
320
+ if channel_weights.shape != (85,) or torch.any(channel_weights <= 0):
321
+ raise ValueError("training.channel_weights must contain 85 positive values")
322
+ channel_weights = channel_weights / channel_weights.mean()
323
+
324
+ start_epoch = 0
325
+ checkpoint = train_cfg["load_checkpoint"]
326
+ mode = train_cfg["checkpoint_mode"]
327
+ if checkpoint is not None:
328
+ path = resolve_path(checkpoint, cfg)
329
+ start_epoch = load_checkpoint(path, mode, model, optimizer, scheduler, device)
330
+ elif mode != "scratch":
331
+ raise ValueError(f"checkpoint is required for checkpoint_mode={mode}")
332
+
333
+ checkpoint_path = resolve_path(train_cfg["save_checkpoint"], cfg)
334
+ metrics_path = resolve_path(cfg["paths"]["training_metrics"], cfg)
335
+ if rank == 0 and not args.dry_run:
336
+ checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
337
+ metrics_path.parent.mkdir(parents=True, exist_ok=True)
338
+ history = []
339
+ end_epoch = min(train_cfg["epochs"], start_epoch + 1) if args.dry_run else train_cfg["epochs"]
340
+ for epoch in range(start_epoch, end_epoch):
341
+ if train_sampler is not None:
342
+ train_sampler.set_epoch(epoch)
343
+ train_loss = run_epoch(model, train_loader, optimizer, device, cfg, channel_weights, True)
344
+ val_loss = run_epoch(model, val_loader, optimizer, device, cfg, channel_weights, False)
345
+ scheduler.step()
346
+ record = {"epoch": epoch, "train_loss": train_loss, "val_loss": val_loss, "learning_rate": scheduler.get_last_lr()[0]}
347
+ history.append(record)
348
+ state = None
349
+ if not args.dry_run:
350
+ # FSDP state-dict collection is collective; every rank must enter it.
351
+ state = checkpoint_state(model, optimizer, scheduler, epoch, cfg)
352
+ if rank == 0:
353
+ print(json.dumps(record))
354
+ if not args.dry_run:
355
+ torch.save(state, checkpoint_path)
356
+ metrics_path.write_text(json.dumps(history, indent=2) + "\n", encoding="utf-8")
357
+ if distributed:
358
+ dist.destroy_process_group()
359
+
360
+
361
+ if __name__ == "__main__":
362
+ main()
scripts/variables.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ PRESSURE_LEVELS = [50, 100, 150, 200, 250, 300, 400, 500, 600, 700, 850, 925, 1000]
4
+ PRESSURE_VARIABLES = ["z", "t", "u", "v", "q"]
5
+ SURFACE_VARIABLES = [
6
+ "msl", "t2m", "d2m", "sst", "ws10m", "ws100m", "u10m", "v10m",
7
+ "u100m", "v100m", "lcc", "mcc", "hcc", "tcc", "ssr", "ssrd",
8
+ "fdir", "ttr", "tcw", "tp",
9
+ ]
10
+ C85_CHANNEL_NAMES = [f"{name}{level}" for name in PRESSURE_VARIABLES for level in PRESSURE_LEVELS]
11
+ C85_CHANNEL_NAMES += SURFACE_VARIABLES
12
+ DIAGNOSTIC_CHANNELS = ["ssr", "ssrd", "fdir", "ttr", "tp"]
13
+
14
+ assert len(C85_CHANNEL_NAMES) == 85
15
+
16
+
17
+ def c85_from_config(config: dict) -> tuple[list[str], list[str]]:
18
+ """Build and validate the fixed C85 channel contract from configuration."""
19
+ variables = config["variables"]
20
+ mapping = variables["mapping"]
21
+ if mapping != {
22
+ "pressure_order": "variable_major",
23
+ "pressure_name": "{variable}{level}",
24
+ "surface_name": "{variable}",
25
+ "source_dataset": "fields",
26
+ "units": "source_native",
27
+ "transform": "identity",
28
+ }:
29
+ raise ValueError("variables.mapping must preserve the C85 source and ordering contract")
30
+ channels = [
31
+ mapping["pressure_name"].format(variable=name, level=level)
32
+ for name in variables["pressure"]
33
+ for level in variables["pressure_levels"]
34
+ ]
35
+ channels.extend(mapping["surface_name"].format(variable=name) for name in variables["surface"])
36
+ diagnostics = list(variables["diagnostic"])
37
+ if channels != C85_CHANNEL_NAMES:
38
+ raise ValueError("Configured variables do not match the required C85 channel order")
39
+ if diagnostics != DIAGNOSTIC_CHANNELS:
40
+ raise ValueError("Configured diagnostic variables do not match the required C85 contract")
41
+ return channels, diagnostics
weight/.gitkeep ADDED
File without changes