Upload folder using huggingface_hub
Browse filesFiles changed (10)
- .gitattributes+41-9
- README.mdAdded+147
- conf/config.yamlAdded+192
- configuration.jsonAdded+1
- model/stormer.pyAdded+722
- scripts/fake_data.pyAdded+270
- scripts/inference.pyAdded+274
- scripts/result.pyAdded+351
- scripts/train.pyAdded+525
- weight/.gitkeepAdded
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bin.* filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zstandard filter=lfs diff=lfs merge=lfs -text*.tfevents* filter=lfs diff=lfs merge=lfs -text*.db* filter=lfs diff=lfs merge=lfs -text*.ark* filter=lfs diff=lfs merge=lfs -text**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.gguf* filter=lfs diff=lfs merge=lfs -text*.ggml filter=lfs diff=lfs merge=lfs -text*.llamafile* filter=lfs diff=lfs merge=lfs -text*.pt2 filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.m4a filter=lfs diff=lfs merge=lfs -text*.aac filter=lfs diff=lfs merge=lfs -text*.opus filter=lfs diff=lfs merge=lfs -text*.mp4 filter=lfs diff=lfs merge=lfs -text*.mov filter=lfs diff=lfs merge=lfs -text*.avi filter=lfs diff=lfs merge=lfs -text*.mkv filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text*.obj filter=lfs diff=lfs merge=lfs -text*.glb filter=lfs diff=lfs merge=lfs -text*.gltf filter=lfs diff=lfs merge=lfs -text*.ply filter=lfs diff=lfs merge=lfs -text*.stl filter=lfs diff=lfs merge=lfs -text*.fbx filter=lfs diff=lfs merge=lfs -text/weight/ filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147---datasets:- OneScience/ERA5frameworks:- ""language:- enlicense: mittags:- OneScience- Earth Science- ERA5- Medium-Range Weather Forecasting- ViTtasks: []---<p align="center"> <strong> <span style="font-size: 30px;">Stormer</span> </strong></p>
# Model Overview
Stormer was jointly developed by researchers at Argonne National Laboratory and the University of California, Los Angeles (UCLA). Its core paper was published at NeurIPS 2024, a leading conference in artificial intelligence.
Paper: *Scaling Transformer Neural Networks for Skillful and Reliable Medium-Range Weather Forecasting*
https://arxiv.org/abs/2312.03876
# Model Description
Stormer uses a standard Vision Transformer architecture and provides a streamlined deep learning model for medium-range weather forecasting.
# Use Cases
| Use Case | Description || :---: | :--- || Weather forecasting training | Train Stormer on ERA5 data in HDF5 format. || Quick local validation | Use synthetic data to validate data loading, model training and inference, and visualization of inference results. || ModelScope/OneCode execution | Download the standalone model package, install its dependencies, and run the included scripts directly. || Multi-GPU training | Launch multi-process training with `torchrun`. |
# Usage
## 1. Using OneCode
Use the OneCode online environment for an intelligent, one-click AI4S development experience:
[Try one-click AI4S development with OneCode](https://web-2069360198568017922-iaaj.ksai.scnet.cn:58043/home)
## 2. Manual Setup
**Hardware Requirements**
- A GPU or DCU is recommended.- A CPU can be used for import checks and connectivity validation with a minimal configuration, but full training and inference will be slow.- DCU users must install DTK in advance. DTK 25.04.2 or later is recommended; alternatively, use the OneScience-recommended version compatible with your cluster.
### Download the Model Package
```bashhf download --model OneScience-Group/Stormer --local-dir ./Stormercd Stormer```
### Set Up the Runtime Environment
**DCU Environment**
```bash# Activate DTK and conda first.conda create -n onescience311 python=3.11 -yconda activate onescience311# Installation with uv is also supported.pip install onescience[earth-dcu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai```
**GPU Environment**
```bash# Activate conda first.conda create -n onescience311 python=3.11 -y libstdcxx-ng=12 libgcc-ng=12 gcc_linux-64=12 gxx_linux-64=12conda activate onescience311# Installation with uv is also supported.pip install onescience[earth-gpu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai```
### Training Data
The OneScience community provides ERA5 data for training. Because of file-size constraints, the repository currently contains a self-contained data slice. Download the data with the following command and ensure that the data path in `conf/config.yaml` is configured correctly:
```bashhf download --dataset OneScience-Group/ERA5 --local-dir ./data```
### Training
Single GPU:
```bashpython scripts/train.py```
Multiple GPUs:
```bashtorchrun --nproc_per_node=8 scripts/train.py```
Training saves the `model_bak.pth` checkpoint under `data/checkpoints/`.
### Pre-trained Weights
This repository will provide weights trained on ERA5 reanalysis data in the `weights/` directory. The weight files are being prepared and will be uploaded soon.
### Inference
```bashpython scripts/inference.py```
By default, inference loads `data/checkpoints/model_bak.pth`, and results are saved to `result/output/`.
### Evaluation and Visualization
```bashpython scripts/result.py```
# Official OneScience Resources
| Platform | OneScience Main Repository | Skills Repository || --- | --- | --- || Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills || GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills |
# Citation and License
- This repository is a reproduction of the original Stormer paper.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192model:
start_epoch: 0 max_epoch: 100 lr: 5e-4 beta_1: 0.9 beta_2: 0.95 weight_decay: 1e-5 warmup_epochs: 10 warmup_start_lr: 1e-8 eta_min: 1e-8
# Stormer architecture params in_img_size: [128, 256] # 1.40625° resolution (lat, lon) patch_size: 2 hidden_size: 1024 depth: 24 num_heads: 16 mlp_ratio: 4.0
# Training strategy list_train_intervals: [6, 12, 24] # hours, randomly chosen per batch steps: 1 # number of autoregressive rollout steps val_lead_times: [6, 72] # lead times for validation (hours) data_freq: 6 # data frequency (hours)
checkpoint_dir: "./data/checkpoints" patience: 50
# Normalization constants directory (official Stormer .npz files) normalize_dir: "./data/normalize/"
# 整个数据读取流程datapipe: name: "ERA5" task: "weather_forecasting"
# dataset设定 dataset: type: "hdf5" data_dir: './data/' # "$ONESCIENCE_DATASETS_DIR/ERA5/newh5/"
train_time: [2000, 2001] val_time: [2002] test_time: [2003] img_size: [128, 256] verbose: true cache: false
# Stormer variables: 4 surface + 5 × 13 pressure levels = 69 variables channels: # Surface variables (4) - "2m_temperature" - "10m_u_component_of_wind" - "10m_v_component_of_wind" - "mean_sea_level_pressure"
# Geopotential at 13 pressure levels - "geopotential_50" - "geopotential_100" - "geopotential_150" - "geopotential_200" - "geopotential_250" - "geopotential_300" - "geopotential_400" - "geopotential_500" - "geopotential_600" - "geopotential_700" - "geopotential_850" - "geopotential_925" - "geopotential_1000"
# U component of wind at 13 pressure levels - "u_component_of_wind_50" - "u_component_of_wind_100" - "u_component_of_wind_150" - "u_component_of_wind_200" - "u_component_of_wind_250" - "u_component_of_wind_300" - "u_component_of_wind_400" - "u_component_of_wind_500" - "u_component_of_wind_600" - "u_component_of_wind_700" - "u_component_of_wind_850" - "u_component_of_wind_925" - "u_component_of_wind_1000"
# V component of wind at 13 pressure levels - "v_component_of_wind_50" - "v_component_of_wind_100" - "v_component_of_wind_150" - "v_component_of_wind_200" - "v_component_of_wind_250" - "v_component_of_wind_300" - "v_component_of_wind_400" - "v_component_of_wind_500" - "v_component_of_wind_600" - "v_component_of_wind_700" - "v_component_of_wind_850" - "v_component_of_wind_925" - "v_component_of_wind_1000"
# Temperature at 13 pressure levels - "temperature_50" - "temperature_100" - "temperature_150" - "temperature_200" - "temperature_250" - "temperature_300" - "temperature_400" - "temperature_500" - "temperature_600" - "temperature_700" - "temperature_850" - "temperature_925" - "temperature_1000"
# Specific humidity at 13 pressure levels - "specific_humidity_50" - "specific_humidity_100" - "specific_humidity_150" - "specific_humidity_200" - "specific_humidity_250" - "specific_humidity_300" - "specific_humidity_400" - "specific_humidity_500" - "specific_humidity_600" - "specific_humidity_700" - "specific_humidity_850" - "specific_humidity_925" - "specific_humidity_1000"
# Short names for evaluation variables: - "t2m" # 2m temperature - "u10" # 10m U wind component - "v10" # 10m V wind component - "msl" # Mean sea level pressure - "z500" # Geopotential at 500 hPa - "t850" # Temperature at 850 hPa
# 时间配置 time_range: ["2000-01-01", "2020-12-31"] time_steps: 1 time_res: 6
# 空间配置 spatial_resolution: [1.40625, 1.40625]
# 采样配置 num_samples: -1 # -1 表示使用全部数据 shuffle: true random_seed: 42
# 领域特定配置 extra: levels: [500, 850, 1000] lat_range: [-90, 90] lon_range: [0, 360]
# 数据转换配置 transforms: - type: "Normalize" params: mean: [0.0, 0.0, 288.0, 101325.0, 50000.0, 270.0] std: [5.0, 5.0, 15.0, 1000.0, 5000.0, 10.0] keys: ["input", "target"]
- type: "ToTensor" params: keys: null # null表示转换所有numpy数组
# DataLoader配置 dataloader: mask_dtype: "float32" batch_size: 1 num_workers: 1 pin_memory: true drop_last: true shuffle: false # 使用sampler时设为false prefetch_factor: 2 persistent_workers: true
# 分布式配置 distributed: enabled: true sampler: "DistributedSampler" rank: 0 world_size: 4 shuffle: true seed: 42 drop_last: true1{"framework":"Pytorch","task":"other"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722"""Stormer: A Transformer-based Global Weather Forecasting Model.
Reference:- "Stormer: A Transformer-based Data-driven Model for Global Weather Forecasting"- Official repo: https://github.com/microsoft/stormer
This implementation:- Removes dependency on xformers (replaced with torch.nn.functional.scaled_dot_product_attention)- Removes dependency on timm (PatchEmbed, Mlp, trunc_normal_ reimplemented)- Compatible with onescience framework- Follows official code logic and precision exactly"""
import mathimport numpy as npfrom dataclasses import dataclassfrom functools import lru_cache
import torchimport torch.nn as nnimport torch.nn.functional as F
from onescience.models.meta import ModelMetaData
# ============================================================================# Constants (fields that should not be predicted — output zero diff)# ============================================================================
# These are invariant/constant fields in the WeatherBench2 dataset.# Stormer's 69 atmospheric variables do NOT include any of these,# but we define them for completeness if the variable set is extended.CONSTANTS = [ "anisotropy_of_sub_gridscale_orography", "orography", "land_sea_mask", "slt", "lattitude", "longitude", "angle_of_sub_gridscale_orography", "geopotential_at_surface", "high_vegetation_cover", "lake_cover", "lake_depth", "low_vegetation_cover", "slope_of_sub_gridscale_orography", "soil_type", "standard_deviation_of_filtered_subgrid_orography", "standard_deviation_of_orography", "type_of_high_vegetation", "type_of_low_vegetation",]
# ============================================================================# Model metadata for onescience framework# ============================================================================
@dataclassclass MetaData(ModelMetaData): name: str = "Stormer" jit: bool = False cuda_graphs: bool = True amp: bool = True amp_cpu: bool = None amp_gpu: bool = None onnx_cpu: bool = False onnx_gpu: bool = True onnx_runtime: bool = True var_dim: int = 1 func_torch: bool = False auto_grad: bool = False
# ============================================================================# Utility functions (replacing timm dependencies)# ============================================================================
def _trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): """Truncated normal initialization (replaces timm's trunc_normal_).
Operates on tensor.data to avoid issues with requires_grad=True parameters. """ def norm_cdf(x): return (1. + math.erf(x / math.sqrt(2.))) / 2.
# Work on .data to avoid in-place operation errors on grad-enabled tensors t = tensor.data if hasattr(tensor, 'data') else tensor
if mean < a - 2 * std or mean > b + 2 * std: import warnings warnings.warn("mean is more than 2 std from [a, b] in trunc_normal_. " "The distribution of values may be incorrect.", stacklevel=2)
l = norm_cdf((a - mean) / std) u = norm_cdf((b - mean) / std)
t.uniform_(2 * l - 1, 2 * u - 1) t.erfinv_() t.mul_(std * math.sqrt(2.)) t.add_(mean) t.clamp_(min=a, max=b)
def trunc_normal_(tensor, std=0.02): """Drop-in replacement for timm's trunc_normal_.""" _trunc_normal_(tensor, mean=0., std=std, a=-2., b=2.)
# ============================================================================# Basic building blocks (replacing timm dependencies)# ============================================================================
class Mlp(nn.Module): """MLP with GELU activation (replaces timm's Mlp).""" def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x
class PatchEmbed(nn.Module): """2D Image to Patch Embedding (replaces timm's PatchEmbed).
Splits image into patches and embeds each patch via Conv2d. """ def __init__(self, patch_size=2, in_chans=1, embed_dim=1024): super().__init__() self.patch_size = (patch_size, patch_size) if isinstance(patch_size, int) else patch_size self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=self.patch_size, stride=self.patch_size) self.num_patches = None # set externally after init
def forward(self, x): B, C, H, W = x.shape x = self.proj(x) # B, D, H/p, W/p x = x.flatten(2).transpose(1, 2) # B, L, D return x
# ============================================================================# Position embedding utilities (from official Stormer pos_embed.py)# ============================================================================
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): """1D sine-cosine position embedding from grid positions.""" assert embed_dim % 2 == 0 omega = np.arange(embed_dim // 2, dtype=float) omega /= embed_dim / 2.0 omega = 1.0 / 10000 ** omega # (D/2,)
pos = pos.reshape(-1) # (M,) out = np.einsum("m,d->md", pos, omega) # (M, D/2)
emb_sin = np.sin(out) emb_cos = np.cos(out) emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) return emb
def get_2d_sincos_pos_embed(embed_dim, grid_size_h, grid_size_w, cls_token=False): """2D sine-cosine position embedding.""" grid_h = np.arange(grid_size_h, dtype=np.float32) grid_w = np.arange(grid_size_w, dtype=np.float32) grid = np.meshgrid(grid_w, grid_h) # w goes first grid = np.stack(grid, axis=0) grid = grid.reshape([2, 1, grid_size_h, grid_size_w])
assert embed_dim % 2 == 0 emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
if cls_token: emb = np.concatenate([np.zeros([1, embed_dim]), emb], axis=0) return emb
# ============================================================================# Chunked attention (replaces FlashAttention / mem-efficient SDPA)# ============================================================================
def _chunked_attention(q, k, v, scale, chunk_size=1024): """Query-chunked scaled dot-product attention.
Processes queries in chunks to limit peak memory to O(chunk_size × N) instead of O(N × N). This works around: - FlashAttention library not being available on DCU/HIP - OOM from materializing the full N×N attention matrix
Args: q: (B, num_heads, N, head_dim) k: (B, num_heads, N, head_dim) v: (B, num_heads, N, head_dim) scale: attention scale factor chunk_size: number of query tokens per chunk
Returns: (B, num_heads, N, head_dim) """ B, H, N, D = q.shape out = torch.empty_like(q)
for chunk_start in range(0, N, chunk_size): chunk_end = min(chunk_start + chunk_size, N) q_chunk = q[:, :, chunk_start:chunk_end] # (B, H, chunk, D)
# Attention scores: (B, H, chunk, N) attn = torch.matmul(q_chunk, k.transpose(-2, -1)) * scale attn = F.softmax(attn, dim=-1)
# Weighted sum: (B, H, chunk, D) out[:, :, chunk_start:chunk_end] = torch.matmul(attn, v)
return out
# ============================================================================# adaLN-Zero modulation and timestep embedding# ============================================================================
def modulate(x, shift, scale): """Adaptive layer norm modulation: x * (1 + scale) + shift.""" return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
class TimestepEmbedder(nn.Module): """Embeds scalar timesteps (time intervals) into vector representations.""" def __init__(self, hidden_size): super().__init__() self.mlp = nn.Linear(1, hidden_size)
def forward(self, t): return self.mlp(t.unsqueeze(-1))
# ============================================================================# Memory-efficient attention (replacing xformers)# ============================================================================
class MemEffAttention(nn.Module): """Multi-head attention with memory-efficient chunked implementation.
Uses query-chunked attention to avoid materializing the full N×N attention matrix, working around both FlashAttention library unavailability and OOM issues on memory-constrained hardware. """
def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = False, proj_bias: bool = True, attn_drop: float = 0.0, proj_drop: float = 0.0, chunk_size: int = 1024, ) -> None: super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.chunk_size = chunk_size
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim, bias=proj_bias) self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, attn_bias=None): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
# Replace xformers.ops.unbind with torch.unbind q, k, v = torch.unbind(qkv, dim=2)
# Transpose to (B, num_heads, N, head_dim) q = q.permute(0, 2, 1, 3) # B, num_heads, N, head_dim k = k.permute(0, 2, 1, 3) v = v.permute(0, 2, 1, 3)
# Query-chunked attention: avoids N×N matrix and FlashAttention dep x = _chunked_attention(q, k, v, self.scale, self.chunk_size)
x = x.permute(0, 2, 1, 3).reshape(B, N, C)
x = self.proj(x) x = self.proj_drop(x) return x
# ============================================================================# adaLN-Zero Transformer Block# ============================================================================
class Block(nn.Module): """A transformer block with adaptive layer norm zero (adaLN-Zero) conditioning."""
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs): super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = MemEffAttention( hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs ) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) mlp_hidden_dim = int(hidden_size * mlp_ratio) approx_gelu = lambda: nn.GELU(approximate="tanh") self.mlp = Mlp( in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0, ) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True), )
def forward(self, x, c): shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( self.adaLN_modulation(c).chunk(6, dim=1) ) x = x + gate_msa.unsqueeze(1) * self.attn( modulate(self.norm1(x), shift_msa, scale_msa) ) x = x + gate_mlp.unsqueeze(1) * self.mlp( modulate(self.norm2(x), shift_mlp, scale_mlp) ) return x
# ============================================================================# Final prediction layer# ============================================================================
class FinalLayer(nn.Module): """Final layer with adaLN modulation, maps embeddings to pixel outputs."""
def __init__(self, hidden_size, patch_size, out_channels): super().__init__() self.norm_final = nn.Identity() self.linear = nn.Linear( hidden_size, patch_size * patch_size * out_channels, bias=True ) self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True), )
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
# ============================================================================# Weather Embedding: variable tokenization + aggregation# ============================================================================
class WeatherEmbedding(nn.Module): """Variable-specific patch embedding with cross-attention aggregation.
Each variable gets its own PatchEmbed. Variable tokens are aggregated via a learnable query + single-layer cross-attention. """
def __init__( self, variables, img_size, patch_size=2, embed_dim=1024, num_heads=16, ): super().__init__()
self.img_size = img_size self.patch_size = patch_size self.variables = variables
# Variable tokenization: separate embedding layer for each input variable self.token_embeds = nn.ModuleList([ PatchEmbed(patch_size, 1, embed_dim) for _ in range(len(variables)) ]) self.num_patches = (img_size[0] // patch_size) * (img_size[1] // patch_size)
# Variable embedding to denote which variable each token belongs to self.channel_embed, self.channel_map = self._create_var_embedding(embed_dim)
# Variable aggregation: learnable query + single-layer cross attention self.channel_query = nn.Parameter( torch.zeros(1, 1, embed_dim), requires_grad=True ) self.channel_agg = nn.MultiheadAttention( embed_dim, num_heads, batch_first=True )
# Positional embedding self.pos_embed = nn.Parameter( torch.zeros(1, self.num_patches, embed_dim), requires_grad=True )
self.initialize_weights()
def _create_var_embedding(self, dim): var_embed = nn.Parameter( torch.zeros(1, len(self.variables), dim), requires_grad=True ) var_map = {var: idx for idx, var in enumerate(self.variables)} return var_embed, var_map
@lru_cache(maxsize=None) def get_var_ids(self, vars, device): ids = np.array([self.channel_map[var] for var in vars]) return torch.from_numpy(ids).to(device)
def get_var_emb(self, var_emb, vars): ids = self.get_var_ids(tuple(vars), var_emb.device) return var_emb[:, ids, :]
def initialize_weights(self): # Initialize pos_emb and var_emb with sinusoidal encodings pos_embed = get_2d_sincos_pos_embed( self.pos_embed.shape[-1], int(self.img_size[0] / self.patch_size), int(self.img_size[1] / self.patch_size), cls_token=False, ) self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
channel_embed = get_1d_sincos_pos_embed_from_grid( self.channel_embed.shape[-1], np.arange(len(self.variables)) ) self.channel_embed.data.copy_( torch.from_numpy(channel_embed).float().unsqueeze(0) )
# Token embedding layers for i in range(len(self.token_embeds)): w = self.token_embeds[i].proj.weight.data _trunc_normal_(w.view([w.shape[0], -1]), std=0.02)
# Initialize nn.Linear and nn.LayerNorm self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0)
def aggregate_variables(self, x: torch.Tensor): """Aggregate variable tokens via cross-attention.
Args: x: (B, V, L, D) Returns: (B, L, D) """ b, _, l, _ = x.shape x = torch.einsum("bvld->blvd", x) x = x.flatten(0, 1) # B*L, V, D
var_query = self.channel_query.repeat_interleave(x.shape[0], dim=0) x, _ = self.channel_agg(var_query, x, x) # B*L, D x = x.squeeze()
x = x.unflatten(dim=0, sizes=(b, l)) # B, L, D return x
def forward(self, x: torch.Tensor, variables): """Forward pass of weather embedding.
Args: x: (B, V, H, W) input weather state variables: list of variable names Returns: (B, L, D) aggregated token embeddings """ if isinstance(variables, list): variables = tuple(variables)
# Tokenize each variable separately embeds = [] var_ids = self.get_var_ids(variables, x.device)
for i in range(len(var_ids)): idx = var_ids[i] embed_variable = self.token_embeds[idx](x[:, i: i + 1]) # B, L, D embeds.append(embed_variable)
x = torch.stack(embeds, dim=1) # B, V, L, D
# Add variable embedding and position embedding var_embed = self.get_var_emb(self.channel_embed, list(variables)) x = x + var_embed.unsqueeze(2) x = x + self.pos_embed.unsqueeze(1)
# Variable aggregation x = self.aggregate_variables(x) # B, L, D
return x
# ============================================================================# Main Stormer Model# ============================================================================
class Stormer(nn.Module): """Stormer: A Transformer-based Global Weather Forecasting Model.
This model predicts weather state differences (deltas) over a given time interval, conditioned on that interval via adaLN-Zero.
Args: in_img_size (tuple): Input spatial dimensions (H, W). variables (list): List of variable name strings. patch_size (int): Patch size for tokenization. Default: 2. hidden_size (int): Hidden dimension throughout the model. Default: 1024. depth (int): Number of transformer blocks. Default: 24. num_heads (int): Number of attention heads. Default: 16. mlp_ratio (float): MLP hidden dim ratio. Default: 4.0. """
def __init__( self, in_img_size, variables, patch_size=2, hidden_size=1024, depth=24, num_heads=16, mlp_ratio=4.0, ): super().__init__()
# Pad height if not divisible by patch_size self.pad_size = 0 if in_img_size[0] % patch_size != 0: self.pad_size = patch_size - in_img_size[0] % patch_size in_img_size = (in_img_size[0] + self.pad_size, in_img_size[1])
self.in_img_size = in_img_size self.variables = variables self.patch_size = patch_size
# Embedding self.embedding = WeatherEmbedding( variables=variables, img_size=in_img_size, patch_size=patch_size, embed_dim=hidden_size, num_heads=num_heads, ) self.embed_norm_layer = nn.LayerNorm(hidden_size)
# Interval embedding self.t_embedder = TimestepEmbedder(hidden_size)
# Backbone self.blocks = nn.ModuleList([ Block(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth) ])
# Prediction layer self.head = FinalLayer(hidden_size, patch_size, len(variables))
self.initialize_weights()
def initialize_weights(self): """Initialize model weights following official implementation."""
def _basic_init(module): if isinstance(module, nn.Linear): trunc_normal_(module.weight, std=0.02) if module.bias is not None: nn.init.constant_(module.bias, 0)
self.apply(_basic_init)
# Initialize timestep embedding MLP trunc_normal_(self.t_embedder.mlp.weight, std=0.02)
# Zero-out adaLN modulation layers in blocks for block in self.blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# Zero-out final layer adaLN and linear nn.init.constant_(self.head.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.head.adaLN_modulation[-1].bias, 0) nn.init.constant_(self.head.linear.weight, 0) nn.init.constant_(self.head.linear.bias, 0)
def replace_constant(self, yhat, out_variables): """Zero out predicted diffs for constant/invariant variables.
Following the official Stormer implementation, constant fields (like land_sea_mask, orography, etc.) should have zero prediction since they don't change over time.
Args: yhat: (B, V, H, W) predicted diffs out_variables: list of variable names Returns: yhat with constant channels set to zero """ for i in range(yhat.shape[1]): if out_variables[i] in CONSTANTS: yhat[:, i] = 0.0 return yhat
def unpatchify(self, x: torch.Tensor, h=None, w=None): """Convert patch tokens back to image space.
Args: x: (B, L, V * patch_size**2) h, w: optional height/width override Returns: imgs: (B, V, H, W) """ p = self.patch_size v = len(self.variables) h = self.in_img_size[0] // p if h is None else h // p w = self.in_img_size[1] // p if w is None else w // p assert h * w == x.shape[1], f"Token count mismatch: {h}*{w} != {x.shape[1]}"
x = x.reshape(shape=(x.shape[0], h, w, p, p, v)) x = torch.einsum("nhwpqv->nvhpwq", x) imgs = x.reshape(shape=(x.shape[0], v, h * p, w * p)) return imgs
def pad(self, x: torch.Tensor): """Pad input height to be divisible by patch_size.""" h = x.shape[-2] if h % self.patch_size != 0: pad_size = self.patch_size - h % self.patch_size padded_x = F.pad(x, (0, 0, pad_size, 0), 'constant', 0) else: padded_x = x pad_size = 0 return padded_x, pad_size
def forward(self, x, variables, time_interval, use_checkpoint=False): """Forward pass of Stormer.
Args: x: (B, V, H, W) input weather state (normalized) variables: list of variable name strings time_interval: (B,) or scalar, time interval in hours, will be divided by 10 use_checkpoint: if True, apply gradient checkpointing to each block (saves memory during training, trades compute for memory)
Returns: (B, V, H_original, W) predicted difference (delta) in normalized space """ # Normalize time interval to [0.6, 1.2, 2.4] range for [6, 12, 24] hours if not isinstance(time_interval, torch.Tensor): time_interval = torch.tensor([time_interval], device=x.device, dtype=x.dtype) time_interval = time_interval / 10.0
# Pad input height if needed (for patch_size alignment) if self.pad_size > 0: x = F.pad(x, (0, 0, self.pad_size, 0), 'constant', 0)
# Embedding (optionally checkpointed — most memory-intensive after blocks) if use_checkpoint and self.training: x = torch.utils.checkpoint.checkpoint( self._do_embed, x, variables, use_reentrant=False, ) else: x = self._do_embed(x, variables)
# Time interval embedding time_interval_emb = self.t_embedder(time_interval)
# Transformer backbone for block in self.blocks: if use_checkpoint and self.training: x = torch.utils.checkpoint.checkpoint( block, x, time_interval_emb, use_reentrant=False, ) else: x = block(x, time_interval_emb)
# Prediction head (no checkpoint needed — small) x = self.head(x, time_interval_emb) x = self.unpatchify(x)
# Crop back to original height if self.pad_size > 0: x = x[:, :, self.pad_size:]
return x
def _do_embed(self, x, variables): """Embedding step (extracted for checkpointing).""" x = self.embedding(x, variables) # B, L, D x = self.embed_norm_layer(x) return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270"""Generate synthetic ERA5 data and normalization files for Stormer pipeline.
Creates:1. HDF5 data files (lightweight, chunked with zero fill)2. Static/invariant files (geopotential, land_sea_mask, lat, lon, etc.)3. Normalization constants matching official Stormer format: - normalize_mean.npz, normalize_std.npz (input normalization, 109+ vars) - normalize_diff_mean_{t}.npz, normalize_diff_std_{t}.npz (diff normalization)
Expected output structure: data/ ├── data/ │ ├── {year}.h5 │ └── ... ├── static/ │ ├── geopotential.nc, land_sea_mask.nc │ ├── land_mask.npy, soil_type.npy, topography.npy │ ├── lat.npy, lon.npy └── normalize/ ├── normalize_mean.npz, normalize_std.npz └── normalize_diff_mean_{6,12,24}.npz, normalize_diff_std_{6,12,24}.npz"""
import osimport sysfrom pathlib import Path
root_path = Path(__file__).parent.parentsys.path.append(str(root_path))
import h5pyimport numpy as npimport xarray as xr
from onescience.utils.YParams import YParams
# Stormer data dimensions:# T=20 gives 120hrs (5 days) per year — enough for 72h lead time validationDATASET_DIMS = {"T": 20, "H": 128, "W": 256, "time_step": 6}
# Full variable list from WeatherBench2 (109 vars) — used for normalization filesWB2_ALL_VARS = [ # Surface "2m_temperature", "10m_u_component_of_wind", "10m_v_component_of_wind", "mean_sea_level_pressure", # Geopotential at pressure levels "geopotential_50", "geopotential_100", "geopotential_150", "geopotential_200", "geopotential_250", "geopotential_300", "geopotential_400", "geopotential_500", "geopotential_600", "geopotential_700", "geopotential_850", "geopotential_925", "geopotential_1000", # U wind "u_component_of_wind_50", "u_component_of_wind_100", "u_component_of_wind_150", "u_component_of_wind_200", "u_component_of_wind_250", "u_component_of_wind_300", "u_component_of_wind_400", "u_component_of_wind_500", "u_component_of_wind_600", "u_component_of_wind_700", "u_component_of_wind_850", "u_component_of_wind_925", "u_component_of_wind_1000", # V wind "v_component_of_wind_50", "v_component_of_wind_100", "v_component_of_wind_150", "v_component_of_wind_200", "v_component_of_wind_250", "v_component_of_wind_300", "v_component_of_wind_400", "v_component_of_wind_500", "v_component_of_wind_600", "v_component_of_wind_700", "v_component_of_wind_850", "v_component_of_wind_925", "v_component_of_wind_1000", # Temperature "temperature_50", "temperature_100", "temperature_150", "temperature_200", "temperature_250", "temperature_300", "temperature_400", "temperature_500", "temperature_600", "temperature_700", "temperature_850", "temperature_925", "temperature_1000", # Specific humidity "specific_humidity_50", "specific_humidity_100", "specific_humidity_150", "specific_humidity_200", "specific_humidity_250", "specific_humidity_300", "specific_humidity_400", "specific_humidity_500", "specific_humidity_600", "specific_humidity_700", "specific_humidity_850", "specific_humidity_925", "specific_humidity_1000", # Additional WB2 variables (for normalization compatibility) "angle_of_sub_gridscale_orography", "anisotropy_of_sub_gridscale_orography", "geopotential_at_surface", "high_vegetation_cover", "lake_cover", "lake_depth", "land_sea_mask", "low_vegetation_cover", "orography", "slope_of_sub_gridscale_orography", "soil_type", "standard_deviation_of_filtered_subgrid_orography", "standard_deviation_of_orography", "type_of_high_vegetation", "type_of_low_vegetation", "mean_surface_latent_heat_flux", "mean_surface_net_long_wave_radiation_flux", "mean_surface_net_short_wave_radiation_flux", "mean_surface_sensible_heat_flux", "mean_top_downward_short_wave_radiation_flux", "mean_top_net_long_wave_radiation_flux", "mean_top_net_short_wave_radiation_flux", "skin_temperature", "snow_depth", "10m_wind_speed", "surface_pressure", "toa_incident_solar_radiation", "total_precipitation_6hr", "total_column_water_vapour", "total_cloud_cover", "sea_ice_cover", "sea_surface_temperature", "vertical_velocity_50", "vertical_velocity_100", "vertical_velocity_150", "vertical_velocity_200", "vertical_velocity_250", "vertical_velocity_300", "vertical_velocity_400", "vertical_velocity_500", "vertical_velocity_600", "vertical_velocity_700", "vertical_velocity_850", "vertical_velocity_925", "vertical_velocity_1000",]
def generate_fake_h5(data_dir, var_names, years, dims): """Generate HDF5 files with random values for pipeline validation.
Writes actual random data (N(0, 1) per variable) to ensure non-zero training loss for verifying gradient flow. """ os.makedirs(os.path.join(data_dir, "data"), exist_ok=True) T, C = dims["T"], len(var_names) H, W = dims["H"], dims["W"]
for year in years: path = os.path.join(data_dir, "data", f"{year}.h5")
# Generate random data with per-variable mean=0, std=1 rng = np.random.default_rng(42 + year) fields = rng.normal(0, 1, (T, C, H, W)).astype(np.float32)
# Add temporal correlation so consecutive frames are similar # (simple AR(1): smooth the time dimension) for t in range(1, T): fields[t] = 0.7 * fields[t-1] + 0.3 * fields[t]
# Per-variable means/stds means = fields.mean(axis=(0, 2, 3), keepdims=True).reshape(1, C, 1, 1) stds = fields.std(axis=(0, 2, 3), keepdims=True).reshape(1, C, 1, 1) stds = np.maximum(stds, 0.01) # avoid division by zero
with h5py.File(path, "w") as f: ds = f.create_dataset( "fields", data=fields, dtype="float32", chunks=(1, C, H, W), ) ds.attrs["variables"] = var_names ds.attrs["time_step"] = dims["time_step"] f.create_dataset("global_means", data=means) f.create_dataset("global_stds", data=stds)
size_mb = os.path.getsize(path) / 1024 / 1024 print(f" {year}.h5 shape=({T},{C},{H},{W}) " f"size={size_mb:.1f}MB logical={T*C*H*W*4/1024**3:.1f}GB")
def get_static(data_dir): """Generate synthetic static/invariant data files.""" os.makedirs(data_dir, exist_ok=True)
H, W = DATASET_DIMS["H"], DATASET_DIMS["W"]
# Geopotential at surface ds = xr.Dataset( data_vars={ "z": (("valid_time", "latitude", "longitude"), np.random.rand(1, H, W).astype(np.float32)) }, coords={ "valid_time": ["2015-12-31"], "latitude": np.linspace(90, -90, H, dtype=np.float64), "longitude": np.linspace(0, 359.75, W, dtype=np.float64), "number": 0, "expver": "", }, attrs={ "GRIB_centre": "ecmf", "Conventions": "CF-1.7", "institution": "European Centre for Medium-Range Weather Forecasts", "history": "Generated for Stormer onescience", } ) ds.to_netcdf(f"{data_dir}/geopotential.nc")
# Land-sea mask ds_lsm = xr.Dataset( data_vars={ "lsm": (("valid_time", "latitude", "longitude"), np.random.rand(1, H, W).astype(np.float32)) }, coords={ "valid_time": ["2015-12-31"], "latitude": np.linspace(90, -90, H, dtype=np.float64), "longitude": np.linspace(0, 359.75, W, dtype=np.float64), "number": 0, "expver": "", }, ) ds_lsm.to_netcdf(f"{data_dir}/land_sea_mask.nc")
# Static numpy arrays arr = np.random.randn(H, W).astype(np.float32) np.save(f'{data_dir}/land_mask.npy', arr) np.save(f'{data_dir}/soil_type.npy', arr) np.save(f'{data_dir}/topography.npy', arr)
# Latitude/longitude arrays lat = np.linspace(90, -90, H, dtype=np.float32) np.save(f'{data_dir}/lat.npy', lat) lon = np.linspace(0, 359.75, W, dtype=np.float32) np.save(f'{data_dir}/lon.npy', lon)
print(f"✅ Static data generated in {data_dir}")
def generate_normalization_files(normalize_dir, all_vars, stormer_vars): """Generate normalization .npz files matching official Stormer format.
Creates files for ALL 109+ WB2 variables (for compatibility with official normalization loading code), plus diff normalization for intervals [6, 12, 24].
For fake data: input mean=0, std=1; diff mean=0, diff_std scales with interval. """ os.makedirs(normalize_dir, exist_ok=True)
# ---- Input normalization ---- # mean = 0, std = 1 for all variables (fake zero-mean unit-variance data) inp_mean = {v: np.array([0.0], dtype=np.float32) for v in all_vars} inp_std = {v: np.array([1.0], dtype=np.float32) for v in all_vars}
np.savez(os.path.join(normalize_dir, "normalize_mean.npz"), **inp_mean) np.savez(os.path.join(normalize_dir, "normalize_std.npz"), **inp_std) print(f" normalize_mean.npz: {len(inp_mean)} vars") print(f" normalize_std.npz: {len(inp_std)} vars")
# ---- Diff normalization for each interval ---- # diff_std scales with sqrt(interval) (diffusion-like behavior in atmosphere) for interval in [6, 12, 24]: scale = np.sqrt(interval / 6.0) # 6h→1.0, 12h→1.414, 24h→2.0 diff_mean = {v: np.array([0.0], dtype=np.float32) for v in all_vars} diff_std = {v: np.array([scale], dtype=np.float32) for v in all_vars}
np.savez(os.path.join(normalize_dir, f"normalize_diff_mean_{interval}.npz"), **diff_mean) np.savez(os.path.join(normalize_dir, f"normalize_diff_std_{interval}.npz"), **diff_std) print(f" normalize_diff_*_{interval}.npz: {len(diff_std)} vars (scale={scale:.3f})")
print(f"✅ Normalization files generated in {normalize_dir}")
if __name__ == "__main__": cfg_datapipe = YParams(os.path.join(str(root_path), "conf/config.yaml"), "datapipe") cfg_model = YParams(os.path.join(str(root_path), "conf/config.yaml"), "model")
data_dir = cfg_datapipe.dataset.data_dir
# Safety: refuse to overwrite real data paths if data_dir.startswith("/public/") or data_dir.startswith("/work2/") or data_dir.startswith("/work/"): print("❌ 请检查 config,确保 data_dir 指向本地测试路径而非生产路径。") sys.exit(1)
years = (cfg_datapipe.dataset.train_time + cfg_datapipe.dataset.val_time + cfg_datapipe.dataset.test_time) stormer_vars = cfg_datapipe.dataset.channels
# 1. Generate fake HDF5 data print(f"\n📂 Generating fake HDF5: {len(years)} years, {len(stormer_vars)} variables...") generate_fake_h5(data_dir, stormer_vars, years, DATASET_DIMS)
# 2. Generate static files static_dir = os.path.join(data_dir, "static") print(f"\n📂 Generating static files...") get_static(static_dir)
# 3. Generate normalization files normalize_dir = cfg_model.normalize_dir print(f"\n📂 Generating normalization files...") generate_normalization_files(normalize_dir, WB2_ALL_VARS, stormer_vars)
print(f"\n✅ All fake datasets generated successfully.") print(f" Data dir: {data_dir}") print(f" Norm dir: {normalize_dir}") print(f" Variables: {len(stormer_vars)} (Stormer) / {len(WB2_ALL_VARS)} (WB2 full)") print(f" Years: {years}") print(f" Resolution: {DATASET_DIMS['H']}×{DATASET_DIMS['W']} (1.40625°)")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274"""Stormer Inference Script — Matching Official Implementation.
Performs autoregressive weather forecasting following the officialforward_validation logic exactly:
For each step: norm_diff = model(x_norm, interval) # predict in diff-normalized space raw_diff = reverse_diff_transform(norm_diff) # → original space pred_raw = reverse_inp_transform(x_norm) + raw_diff # → original value x_norm = inp_transform(pred_raw) # re-normalize for next step
Each target lead time uses all compatible base intervals [6, 12, 24],then ensemble-averages the predictions.
Usage: python scripts/inference.py"""
import torchimport osimport sysimport warningsfrom pathlib import Path
# Suppress warnings from external librarieswarnings.filterwarnings("ignore", category=UserWarning, module="apex")warnings.filterwarnings("ignore", message=".*DtypeTensor constructors.*")
root_path = Path(__file__).parent.parentsys.path.append(str(root_path))
import globimport numpy as npimport h5pyfrom tqdm import tqdmfrom model.stormer import Stormer, CONSTANTSfrom onescience.utils.YParams import YParamsfrom onescience.datapipes.climate import ERA5Datapipe
# ============================================================================# Normalization utilities (same as train.py)# ============================================================================
class Normalize: """Per-variable normalization: y = (x - mean) / std."""
def __init__(self, mean, std, device='cpu'): self.mean = mean.view(1, -1, 1, 1).to(device) self.std = std.view(1, -1, 1, 1).to(device)
def __call__(self, x): if x.dim() == 3: x = x.unsqueeze(0) return ((x - self.mean) / self.std).squeeze(0) return (x - self.mean) / self.std
def get_reverse_transform(transform): """Return the inverse of a Normalize transform.""" mean = transform.mean.view(-1) std = transform.std.view(-1) std_rev = 1.0 / std mean_rev = -mean * std_rev return Normalize(mean_rev, std_rev, device=transform.mean.device)
def load_normalization_stats(normalize_dir, variables, device): """Load official Stormer normalization constants.""" # Input normalization mean_dict = dict(np.load(os.path.join(normalize_dir, "normalize_mean.npz"))) std_dict = dict(np.load(os.path.join(normalize_dir, "normalize_std.npz")))
inp_mean = np.concatenate([mean_dict[v] for v in variables], axis=0) inp_std = np.concatenate([std_dict[v] for v in variables], axis=0)
inp_mean_t = torch.from_numpy(inp_mean).float() inp_std_t = torch.from_numpy(inp_std).float()
inp_transform = Normalize(inp_mean_t, inp_std_t, device) reverse_inp_transform = get_reverse_transform(inp_transform)
# Diff normalization for each interval reverse_diff_transform = {} for interval in [6, 12, 24]: dmean_dict = dict(np.load( os.path.join(normalize_dir, f"normalize_diff_mean_{interval}.npz"))) dstd_dict = dict(np.load( os.path.join(normalize_dir, f"normalize_diff_std_{interval}.npz")))
dmean = np.concatenate([dmean_dict[v] for v in variables], axis=0) dstd = np.concatenate([dstd_dict[v] for v in variables], axis=0)
dmean_t = torch.from_numpy(dmean).float() dstd_t = torch.from_numpy(dstd).float()
diff_transform = Normalize(dmean_t, dstd_t, device) reverse_diff_transform[interval] = get_reverse_transform(diff_transform)
return inp_transform, reverse_inp_transform, reverse_diff_transform
def _replace_constant(yhat, out_variables): """Zero out diffs for constant/invariant variables.""" for i in range(yhat.shape[1]): if out_variables[i] in CONSTANTS: yhat[:, i] = 0.0 return yhat
def get_stats(data_dir, channels): """Read normalization statistics from HDF5 (for denormalizing output).""" h5_files = sorted(glob.glob(os.path.join(data_dir, "data", "*.h5"))) with h5py.File(h5_files[0], "r") as f: ds = f["fields"] all_variables = [ v.decode() if isinstance(v, bytes) else v for v in ds.attrs["variables"] ] mu = f["global_means"][:] std = f["global_stds"][:]
channel_indices = [all_variables.index(v) for v in channels] means = mu[:, channel_indices, :, :] stds = std[:, channel_indices, :, :] return means, stds
# ============================================================================# Inference# ============================================================================
def autoregressive_rollout(model, x, variables, interval, steps, device, inp_transform, reverse_inp_transform, reverse_diff_transform): """Autoregressive rollout matching official forward_validation.
Args: model: Stormer model x: (1, V, H, W) initial state in INPUT-NORMALIZED space variables: list of variable names interval: base interval in hours steps: number of autoregressive steps device: torch device
Returns: x: (1, V, H, W) final predicted state in INPUT-NORMALIZED space """ interval_tensor = torch.tensor([interval], device=device, dtype=torch.float32)
for _ in range(steps): # Predict diff in diff-normalized space norm_diff = model(x, variables, interval_tensor) norm_diff = _replace_constant(norm_diff, variables)
# Convert diff from diff-normalized → original space raw_diff = reverse_diff_transform[interval](norm_diff)
# Convert input from input-normalized → original space pred_raw = reverse_inp_transform(x) + raw_diff
# Re-normalize for next step x = inp_transform(pred_raw)
return x
if __name__ == "__main__": current_path = os.getcwd() sys.path.append(current_path)
# Config config_file_path = os.path.join(current_path, "conf/config.yaml") cfg = YParams(config_file_path, "model") cfg_data = YParams(config_file_path, "datapipe")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"Using device: {device}")
variables = cfg_data.dataset.channels
# Load normalization stats normalize_dir = cfg.normalize_dir (inp_transform, reverse_inp_transform, reverse_diff_transform) = load_normalization_stats( normalize_dir, variables, device) print(f"✅ Normalization stats loaded from {normalize_dir}")
# Load HDF5 stats for final output denormalization means, stds = get_stats(cfg_data.dataset.data_dir, variables)
# DataLoader for test set (raw single steps) datapipe = ERA5Datapipe( dataset_dir=cfg_data.dataset.data_dir, used_variables=variables, used_years=cfg_data.dataset.test_time, distributed=False, batch_size=1, num_workers=4, input_steps=1, output_steps=1, normalize=False, # Raw data — we apply official normalization ) test_dataloader, _ = datapipe.get_dataloader("test")
# Load model ckpt_path = f"{cfg.checkpoint_dir}/model_bak.pth" if not os.path.exists(ckpt_path): raise FileNotFoundError( f"❌ Checkpoint not found at {ckpt_path}. " "Please train the model first." )
ckpt = torch.load(ckpt_path, map_location=device, weights_only=False) model = Stormer( in_img_size=cfg.in_img_size, variables=variables, patch_size=cfg.patch_size, hidden_size=cfg.hidden_size, depth=cfg.depth, num_heads=cfg.num_heads, mlp_ratio=cfg.mlp_ratio, ).to(device)
model.load_state_dict(ckpt["model_state_dict"]) model.eval() print(f"✅ Model loaded from {ckpt_path}")
list_intervals = cfg.list_train_intervals val_lead_times = cfg.val_lead_times
os.makedirs('result/output/', exist_ok=True) print(f"\n📂 Predictions will be saved to './result/output/'")
with torch.no_grad(): for data in tqdm(test_dataloader, desc="Inferring test set", unit="batch"): invar = data[0].to(device, dtype=torch.float32).squeeze(0) # (C, H, W) raw filename = data[4][-1][0] # time_index
# Normalize input with official stats x_norm = inp_transform(invar).unsqueeze(0) # (1, V, H, W)
for lead_time in val_lead_times: all_preds = []
for interval in list_intervals: if lead_time % interval == 0: steps = lead_time // interval pred_norm = autoregressive_rollout( model, x_norm, variables, interval, steps, device, inp_transform, reverse_inp_transform, reverse_diff_transform, ) all_preds.append(pred_norm)
if all_preds: ensemble_pred_norm = torch.stack(all_preds, dim=0).mean(0) else: interval = list_intervals[0] steps = lead_time // interval ensemble_pred_norm = autoregressive_rollout( model, x_norm, variables, interval, steps, device, inp_transform, reverse_inp_transform, reverse_diff_transform, )
# Denormalize: pred_raw = reverse_inp(pred_norm) pred_raw = reverse_inp_transform(ensemble_pred_norm).cpu().numpy()
# Save save_name = f"{filename}_lead{lead_time}h" np.save(f"result/output/{save_name}.npy", pred_raw)
print(f"✅ Inference complete. Results saved to './result/output/'")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351"""Stormer Result Evaluation and Visualization.
Computes per-channel RMSE and ACC (Anomaly Correlation Coefficient)for model predictions against ground truth at the corresponding lead times.
Usage: python scripts/result.py"""
import numpy as npimport matplotlib.pyplot as pltimport osimport sysfrom pathlib import Path
root_path = Path(__file__).parent.parentsys.path.append(str(root_path))
import globimport h5pyfrom datetime import datetime, timedeltafrom tqdm import tqdmfrom onescience.utils.YParams import YParamsfrom matplotlib import rcParams
rcParams['mathtext.fontset'] = 'stix'rcParams['axes.linewidth'] = 0.9rcParams['xtick.major.width'] = 0.9rcParams['ytick.major.width'] = 0.9
def get_metadata(data_dir, channels): """Read variable names and time_step from HDF5 attrs.""" h5_files = sorted(glob.glob(os.path.join(data_dir, "data", "*.h5"))) with h5py.File(h5_files[0], "r") as f: ds = f["fields"] all_variables = [ v.decode() if isinstance(v, bytes) else v for v in ds.attrs["variables"] ] time_step = int(ds.attrs["time_step"])
channel_indices = [all_variables.index(v) for v in channels]
# Find all prediction files (now include lead time suffix) total_files = [f for f in os.listdir('./result/output/') if f.endswith('.npy')] total_files.sort() return total_files, channel_indices, time_step
def filename_to_datetime(filename_base): """Convert YYYYMMDDHH base filename to datetime.""" return datetime.strptime(filename_base, "%Y%m%d%H")
def parse_pred_filename(filename): """Parse prediction filename like '2003010206_lead72h.npy'.
Returns: base_time: datetime of input time lead_hours: lead time in hours """ name = filename.replace('.npy', '') parts = name.split('_lead') base_str = parts[0] lead_str = parts[1].replace('h', '') base_time = datetime.strptime(base_str, "%Y%m%d%H") lead_hours = int(lead_str) return base_time, lead_hours
def get_ground_truth(data_dir, target_time, channel_indices, time_step): """Load ground truth from HDF5 at the target datetime.
Args: data_dir: path to data directory containing data/*.h5 files target_time: datetime of the target time step channel_indices: indices of desired channels time_step: hours between consecutive frames
Returns: label: (C, H, W) numpy array, or None if not found """ year = target_time.year year_start = datetime(year, 1, 1) hours_since_year_start = (target_time - year_start).total_seconds() / 3600 t_idx = int(hours_since_year_start / time_step)
h5_path = os.path.join(data_dir, 'data', f'{year}.h5') if not os.path.exists(h5_path): # Try next/last year (for year boundary) for adj_year in [year - 1, year + 1]: alt_path = os.path.join(data_dir, 'data', f'{adj_year}.h5') if os.path.exists(alt_path): h5_path = alt_path if adj_year < year: # Target is early in year, data from previous year prev_start = datetime(adj_year, 1, 1) year_len = int((datetime(adj_year + 1, 1, 1) - prev_start).total_seconds() / 3600) t_idx = year_len // time_step + int( (target_time - datetime(year, 1, 1)).total_seconds() / 3600 / time_step ) break else: return None
try: with h5py.File(h5_path, "r") as f: T_total = f["fields"].shape[0] if t_idx >= T_total or t_idx < 0: return None label = f["fields"][t_idx] # [C_total, H, W] label = label[channel_indices] # [C_selected, H, W] return label except Exception: return None
def compute_metrics(total_files, channel_indices, time_step, data_dir, clim_mean): """Compute per-channel RMSE and ACC.""" n_channels = len(channel_indices)
if os.path.exists('./result/rmse.npy') and os.path.exists('./result/acc.npy'): print("📂 Loading cached metrics...") return np.load('./result/rmse.npy'), np.load('./result/acc.npy')
clim_mean = clim_mean[0, :, :, :] # (C, H, W)
channel_rmse = np.zeros(n_channels) acc_numerator = np.zeros(n_channels) acc_pred_sq = np.zeros(n_channels) acc_label_sq = np.zeros(n_channels) valid_count = 0
for file in tqdm(total_files, unit="files", desc="Computing metrics"): base_time, lead_hours = parse_pred_filename(file) target_time = base_time + timedelta(hours=lead_hours)
# Load ground truth at target time label = get_ground_truth(data_dir, target_time, channel_indices, time_step) if label is None: continue
# Load prediction pred = np.load(f'result/output/{file}').squeeze() # (C, H, W)
if pred.shape != label.shape: # Handle shape mismatch if pred.ndim == 4: pred = pred[0] if pred.shape != label.shape: continue
# RMSE channel_rmse += np.sqrt(np.mean((label - pred) ** 2, axis=(1, 2)))
# ACC (Anomaly Correlation Coefficient) label_anom = label - clim_mean pred_anom = pred - clim_mean acc_numerator += np.sum(pred_anom * label_anom, axis=(1, 2)) acc_pred_sq += np.sum(pred_anom ** 2, axis=(1, 2)) acc_label_sq += np.sum(label_anom ** 2, axis=(1, 2))
valid_count += 1
if valid_count == 0: print("⚠️ No valid predictions found.") return np.zeros(n_channels), np.zeros(n_channels)
channel_rmse /= valid_count channel_acc = acc_numerator / (np.sqrt(acc_pred_sq * acc_label_sq) + 1e-8)
np.save('./result/rmse.npy', channel_rmse) np.save('./result/acc.npy', channel_acc) return channel_rmse, channel_acc
def show_result_table(channels, channel_rmse, channel_acc): """Print formatted RMSE/ACC table.""" w = 40 print(f"\n┌{'─' * (w + 2)}┬{'─' * 14}┬{'─' * 14}┐") print(f"│ {'Channel':<{w}} │ {'RMSE':>12} │ {'ACC':>12} │") print(f"├{'─' * (w + 2)}┼{'─' * 14}┼{'─' * 14}┤")
# Show first 10 + key vars, then average display_idx = list(range(min(10, len(channels)))) # Add key vars if not in first 10 for key in ['geopotential_500', 'temperature_850', '2m_temperature']: if key in channels: idx = channels.index(key) if idx not in display_idx: display_idx.append(idx)
for i in display_idx: ch = channels[i] print(f"│ {ch:<{w}} │ {channel_rmse[i]:>12.4f} │ {channel_acc[i]:>12.4f} │") print(f"├{'─' * (w + 2)}┼{'─' * 14}┼{'─' * 14}┤") print(f"│ {'Average':<{w}} │ {np.mean(channel_rmse):>12.4f} │ {np.mean(channel_acc):>12.4f} │") print(f"└{'─' * (w + 2)}┴{'─' * 14}┴{'─' * 14}┘")
def plot_prediction(label, pred, var, filename): """Plot truth, prediction, and difference for a single variable.""" fig, axes = plt.subplots(1, 3, figsize=(15, 4))
xtick_labels = ['180°W', '90°W', '0°', '90°E', '180°E'] ytick_labels = ['90°S', '45°S', '0°', '45°N', '90°N'] xticks = np.linspace(0, label.shape[-1] - 1, 5) yticks = np.linspace(0, label.shape[-2] - 1, 5)
vmin = min(label.min(), pred.min()) vmax = max(label.max(), pred.max()) diff = label - pred rmse = np.sqrt(np.mean(diff ** 2)) diff_abs_max = np.abs(diff).max()
plot_configs = [ {'data': label, 'title': 'Truth', 'cmap': 'viridis', 'vmin': vmin, 'vmax': vmax}, {'data': pred, 'title': 'Prediction', 'cmap': 'viridis', 'vmin': vmin, 'vmax': vmax}, {'data': diff, 'title': f'Difference (RMSE={rmse:.2f})', 'cmap': 'RdBu_r', 'vmin': -diff_abs_max, 'vmax': diff_abs_max}, ]
for ax, cfg in zip(axes, plot_configs): im = ax.imshow(cfg['data'], cmap=cfg['cmap'], vmin=cfg['vmin'], vmax=cfg['vmax']) ax.set_title(cfg['title'], fontsize=12, pad=4) ax.set_xlabel('Longitude') ax.set_ylabel('Latitude') ax.set_xticks(xticks) ax.set_xticklabels(xtick_labels) ax.set_yticks(yticks) ax.set_yticklabels(ytick_labels) plt.colorbar(im, ax=ax, orientation='horizontal')
fig.suptitle(var, fontsize=14, fontweight='bold', y=0.98) plt.savefig(filename, dpi=300, bbox_inches='tight') plt.close()
def plot_loss_curves(train_loss, valid_loss): """Plot training and validation loss curves.""" mask = ~(np.isnan(train_loss) | np.isnan(valid_loss)) train_loss = train_loss[mask] valid_loss = valid_loss[mask]
if len(train_loss) == 0: print("⚠️ No loss data to plot.") return
fig, ax = plt.subplots(figsize=(5, 3.5)) colors = {'train': '#2563EB', 'valid': '#EA580C'} epochs = np.arange(1, len(train_loss) + 1)
ax.plot(epochs, train_loss, color=colors['train'], linewidth=1.5, label='Train') ax.plot(epochs, valid_loss, color=colors['valid'], linewidth=1.5, label='Valid', linestyle='--')
min_idx = np.argmin(valid_loss) ax.scatter(epochs[min_idx], valid_loss[min_idx], color=colors['valid'], s=40, zorder=5, edgecolors='white') ax.annotate(f'Best: {valid_loss[min_idx]:.3f}', xy=(epochs[min_idx], valid_loss[min_idx]), xytext=(10, 10), textcoords='offset points', fontsize=8, color=colors['valid'], arrowprops=dict(arrowstyle='-', color=colors['valid'], lw=0.5))
ax.set(xlabel='Epoch', ylabel='Loss', xlim=(0, len(train_loss) + 1)) ax.legend(frameon=False, loc='upper right') ax.grid(True, linestyle='--', alpha=0.3) ax.spines[['top', 'right']].set_visible(False)
plt.tight_layout() plt.savefig('./result/loss.png', dpi=300, bbox_inches='tight') plt.close() print("✅ Loss curves saved to './result/loss.png'")
if __name__ == "__main__": current_path = os.getcwd() sys.path.append(current_path) config_file_path = os.path.join(current_path, 'conf/config.yaml') cfg = YParams(config_file_path, 'model') cfg_data = YParams(config_file_path, "datapipe")
os.makedirs('./result/', exist_ok=True)
# ---- Plot loss curves ---- train_loss_file = f"{cfg.checkpoint_dir}/trloss.npy" valid_loss_file = f"{cfg.checkpoint_dir}/valoss.npy" if os.path.exists(train_loss_file) and os.path.exists(valid_loss_file): train_loss = np.load(train_loss_file) valid_loss = np.load(valid_loss_file) plot_loss_curves(train_loss, valid_loss) else: print("⚠️ Loss files not found — skipping loss plot.")
# ---- Compute metrics ---- data_dir = cfg_data.dataset.data_dir total_files, channel_indices, time_step = get_metadata( data_dir, cfg_data.dataset.channels )
if len(total_files) == 0: print("⚠️ No prediction files in './result/output/' — skipping metrics.") sys.exit(0)
# Load climate mean for ACC h5_files = sorted(glob.glob(os.path.join(data_dir, "data", "*.h5"))) with h5py.File(h5_files[0], "r") as f: mu = f["global_means"][:] clim_mean = mu[:, channel_indices, :, :]
channel_rmse, channel_acc = compute_metrics( total_files, channel_indices, time_step, data_dir, clim_mean ) show_result_table(cfg_data.dataset.channels, channel_rmse, channel_acc)
# ---- Plot example predictions ---- test_year = cfg_data.dataset.test_time[0] eg_files = [f for f in total_files if f.startswith(f'{test_year}')][:3]
key_vars = ['2m_temperature', 'geopotential_500', 'temperature_500'] available_vars = [v for v in key_vars if v in cfg_data.dataset.channels] channel_index_map = {v: cfg_data.dataset.channels.index(v) for v in available_vars}
if eg_files: print(f"\n📊 Plotting example predictions for: {available_vars}") for file in eg_files: base_time, lead_hours = parse_pred_filename(file) target_time = base_time + timedelta(hours=lead_hours)
label = get_ground_truth(data_dir, target_time, channel_indices, time_step) if label is None: print(f" ⚠️ No ground truth for {file}") continue
pred = np.load(f'result/output/{file}').squeeze() if pred.ndim == 4: pred = pred[0]
for var in available_vars: idx = channel_index_map[var] out_file = f'./result/{file[:-4]}_{var}.png' if pred.shape == label.shape: plot_prediction(label[idx], pred[idx], var, out_file) print(f' ✅ {out_file}')
print("\n✅ Evaluation complete.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525"""Stormer Training Script — Matching Official Implementation.
Training follows the official Stormer approach exactly:1. Input x(t) is normalized with inp_transform (N(0,1) per variable)2. Model predicts Δx in DIFF-NORMALIZED space3. Ground truth: Δx_gt = diff_transform[Δt](raw_out - raw_in)4. Loss: L1 between pred_diff and gt_diff (both in diff-normalized space)5. Autoregressive rollout with: norm_diff → raw_diff → original → re-normalize
Supports:- Single GPU: python scripts/train.py- Multi-GPU: torchrun --nproc_per_node=N scripts/train.py- Cluster (slurm): sbatch work_slurm.sh"""
import torchimport torch.distributed as distimport torch.nn as nnimport osimport sysimport warningsfrom pathlib import Path
# Suppress warnings from external libraries (apex, etc.)warnings.filterwarnings("ignore", category=UserWarning, module="apex")warnings.filterwarnings("ignore", message=".*DtypeTensor constructors.*")
root_path = Path(__file__).parent.parentsys.path.append(str(root_path))
import numpy as npimport loggingimport timeimport random
from torch.nn.parallel import DistributedDataParallelfrom model.stormer import Stormerfrom onescience.datapipes.climate import ERA5Datapipefrom onescience.utils.YParams import YParams
try: from apex import optimizers HAS_APEX = Trueexcept ImportError: HAS_APEX = False
# ============================================================================# Normalization utilities# ============================================================================
class Normalize: """Per-variable normalization: y = (x - mean) / std.
Replaces torchvision.transforms.Normalize to avoid dependency. """
def __init__(self, mean, std): # mean, std: (V,) tensors self.mean = mean.view(1, -1, 1, 1) self.std = std.view(1, -1, 1, 1)
def __call__(self, x): # x: (B, V, H, W) or (V, H, W) if x.dim() == 3: x = x.unsqueeze(0) return ((x - self.mean) / self.std).squeeze(0) return (x - self.mean) / self.std
def get_reverse_transform(transform): """Return the inverse of a Normalize transform.""" mean = transform.mean.view(-1) std = transform.std.view(-1) std_rev = 1.0 / std mean_rev = -mean * std_rev return Normalize(mean_rev, std_rev)
def load_normalization_stats(normalize_dir, variables): """Load official Stormer normalization constants.
Returns: inp_transform: Normalize for input fields reverse_inp_transform: inverse of inp_transform diff_transform: dict {interval: Normalize} for diff fields reverse_diff_transform: dict {interval: Normalize} inverse """ # Input normalization mean_dict = dict(np.load(os.path.join(normalize_dir, "normalize_mean.npz"))) std_dict = dict(np.load(os.path.join(normalize_dir, "normalize_std.npz")))
inp_mean = np.concatenate([mean_dict[v] for v in variables], axis=0) inp_std = np.concatenate([std_dict[v] for v in variables], axis=0)
inp_mean_t = torch.from_numpy(inp_mean).float() inp_std_t = torch.from_numpy(inp_std).float()
inp_transform = Normalize(inp_mean_t, inp_std_t) reverse_inp_transform = get_reverse_transform(inp_transform)
# Diff normalization for each interval diff_transform = {} reverse_diff_transform = {} for interval in [6, 12, 24]: dmean_dict = dict(np.load( os.path.join(normalize_dir, f"normalize_diff_mean_{interval}.npz"))) dstd_dict = dict(np.load( os.path.join(normalize_dir, f"normalize_diff_std_{interval}.npz")))
dmean = np.concatenate([dmean_dict[v] for v in variables], axis=0) dstd = np.concatenate([dstd_dict[v] for v in variables], axis=0)
dmean_t = torch.from_numpy(dmean).float() dstd_t = torch.from_numpy(dstd).float()
diff_transform[interval] = Normalize(dmean_t, dstd_t) reverse_diff_transform[interval] = get_reverse_transform( diff_transform[interval])
return (inp_transform, reverse_inp_transform, diff_transform, reverse_diff_transform)
# ============================================================================# Training# ============================================================================
def main(): logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger()
# ============================================================ # Config # ============================================================ config_file_path = os.path.join(current_path, "conf/config.yaml") cfg = YParams(config_file_path, "model") cfg_data = YParams(config_file_path, "datapipe")
# ============================================================ # Distributed setup # ============================================================ cfg.world_size = 1 if "WORLD_SIZE" in os.environ: cfg.world_size = int(os.environ["WORLD_SIZE"])
world_rank = 0 local_rank = 0 if cfg.world_size > 1: dist.init_process_group(backend="nccl", init_method="env://") local_rank = int(os.environ["LOCAL_RANK"]) world_rank = dist.get_rank()
# ============================================================ # Load normalization stats # ============================================================ normalize_dir = cfg.normalize_dir variables = cfg_data.dataset.channels
(inp_transform, reverse_inp_transform, diff_transform, reverse_diff_transform) = load_normalization_stats( normalize_dir, variables)
# Move transforms to device for key in diff_transform: diff_transform[key].mean = diff_transform[key].mean.to(local_rank) diff_transform[key].std = diff_transform[key].std.to(local_rank) reverse_diff_transform[key].mean = reverse_diff_transform[key].mean.to(local_rank) reverse_diff_transform[key].std = reverse_diff_transform[key].std.to(local_rank) inp_transform.mean = inp_transform.mean.to(local_rank) inp_transform.std = inp_transform.std.to(local_rank) reverse_inp_transform.mean = reverse_inp_transform.mean.to(local_rank) reverse_inp_transform.std = reverse_inp_transform.std.to(local_rank)
# ============================================================ # DataLoader — get RAW data (normalize=False since we apply # official normalization manually) # ============================================================ max_output_steps = max(cfg.list_train_intervals) // cfg.data_freq # 24/6 = 4
datapipe = ERA5Datapipe( dataset_dir=cfg_data.dataset.data_dir, used_variables=variables, used_years=cfg_data.dataset.train_time, distributed=dist.is_initialized(), input_steps=1, output_steps=max_output_steps, normalize=False, # Raw data — apply official normalization manually batch_size=cfg_data.dataloader.batch_size, num_workers=cfg_data.dataloader.num_workers, ) train_dataloader, train_sampler = datapipe.get_dataloader("train")
# Validation: use output_steps=1 (6h) to avoid negative samples_per_year # with T=10 fake data (10-1-12+1 < 0 for output_steps=12) val_datapipe = ERA5Datapipe( dataset_dir=cfg_data.dataset.data_dir, used_variables=variables, used_years=cfg_data.dataset.val_time, distributed=dist.is_initialized(), input_steps=1, output_steps=1, normalize=False, batch_size=cfg_data.dataloader.batch_size, num_workers=cfg_data.dataloader.num_workers, ) val_dataloader, val_sampler = val_datapipe.get_dataloader("valid")
# ============================================================ # Model # ============================================================ model = Stormer( in_img_size=cfg.in_img_size, variables=variables, patch_size=cfg.patch_size, hidden_size=cfg.hidden_size, depth=cfg.depth, num_heads=cfg.num_heads, mlp_ratio=cfg.mlp_ratio, ).to(local_rank)
# Mixed precision: FP16 autocast + GradScaler (matches official precision=16) use_amp = (local_rank >= 0) # enable AMP when GPU/DCU available scaler = torch.amp.GradScaler('cuda', enabled=use_amp)
# Optimizer — matching official: separate weight decay for embedding params decay = [] no_decay = [] for name, m in model.named_parameters(): if "channel_embed" in name or "pos_embed" in name: no_decay.append(m) else: decay.append(m)
if HAS_APEX: optimizer = optimizers.FusedAdam( [{"params": decay, "lr": cfg.lr, "betas": (cfg.beta_1, cfg.beta_2), "weight_decay": cfg.weight_decay}, {"params": no_decay, "lr": cfg.lr, "betas": (cfg.beta_1, cfg.beta_2), "weight_decay": 0}] ) else: optimizer = torch.optim.AdamW( [{"params": decay, "lr": cfg.lr, "betas": (cfg.beta_1, cfg.beta_2), "weight_decay": cfg.weight_decay}, {"params": no_decay, "lr": cfg.lr, "betas": (cfg.beta_1, cfg.beta_2), "weight_decay": 0}] )
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, factor=0.2, patience=5, mode="min" )
# Latitude-weighted L1 loss lat_path = os.path.join(cfg_data.dataset.data_dir, "static", "lat.npy") if os.path.exists(lat_path): lat = np.load(lat_path) else: lat = np.linspace(90, -90, cfg.in_img_size[0]) loss_obj = _LatWeightedL1Loss(lat, local_rank)
# ============================================================ # Training state # ============================================================ os.makedirs(cfg.checkpoint_dir, exist_ok=True) train_loss_file = f"{cfg.checkpoint_dir}/trloss.npy" valid_loss_file = f"{cfg.checkpoint_dir}/valoss.npy" best_valid_loss = 1.0e6 best_loss_epoch = 0 train_losses = np.empty((0,), dtype=np.float32) valid_losses = np.empty((0,), dtype=np.float32)
if world_rank == 0: total_params = sum(p.numel() for p in model.parameters()) print("\n" + "-" * 50) print(f"📂 Stormer params: {total_params:,} " f"({total_params / 1e6:.2f}M, {total_params / 1e9:.2f}B)") print(f" Resolution: {cfg.in_img_size}") print(f" Patch size: {cfg.patch_size}, Hidden: {cfg.hidden_size}") print(f" Depth: {cfg.depth}, Heads: {cfg.num_heads}") print(f" Variables: {len(variables)}") print(f" Intervals: {cfg.list_train_intervals}") print(f" Norm dir: {normalize_dir}") print("-" * 50 + "\n")
# Load checkpoint if os.path.exists(f"{cfg.checkpoint_dir}/model_bak.pth"): if world_rank == 0: print(f"✅ Found checkpoint, resuming training...") ckpt = torch.load( f"{cfg.checkpoint_dir}/model_bak.pth", map_location=f'cuda:{local_rank}', weights_only=False, ) model.load_state_dict(ckpt["model_state_dict"]) optimizer.load_state_dict(ckpt["optimizer_state_dict"]) scheduler.load_state_dict(ckpt["scheduler_state_dict"]) best_valid_loss = ckpt["best_valid_loss"] best_loss_epoch = ckpt["best_loss_epoch"] if os.path.exists(train_loss_file): train_losses = np.load(train_loss_file) if os.path.exists(valid_loss_file): valid_losses = np.load(valid_loss_file)
# DDP if cfg.world_size > 1: model = DistributedDataParallel( model, device_ids=[local_rank], output_device=local_rank, find_unused_parameters=True, )
if world_rank == 0: logger.info("Starting Stormer training...")
# ============================================================ # Training loop # ============================================================ for epoch in range(cfg.start_epoch, cfg.max_epoch): if dist.is_initialized(): train_sampler.set_epoch(epoch) val_sampler.set_epoch(epoch)
# ---- Train ---- model.train() train_loss = 0 start_time = time.time()
for j, data in enumerate(train_dataloader): # ERA5Dataset (normalize=False): # DataLoader adds batch dim → need to squeeze(batch_size=1) # invar: (B, C, H, W) → squeeze → (C, H, W) raw at time t # outvar: (B, T_out, C, H, W) → squeeze → (T_out, C, H, W) raw future invar = data[0].to(local_rank, dtype=torch.float32).squeeze(0) outvar = data[1].to(local_rank, dtype=torch.float32).squeeze(0)
# Randomly select training interval chosen_interval = random.choice(cfg.list_train_intervals) step_idx = chosen_interval // cfg.data_freq - 1 # 6→0, 12→1, 24→3
# ---- Forward pass following official forward_train logic ---- # Step 1: Normalize input: (C,H,W) → (V,H,W) → unsqueeze → (1,V,H,W) x = inp_transform(invar).unsqueeze(0) # (1, V, H, W)
# Step 2: Compute ground truth diff in DIFF-NORMALIZED space # raw_diff = outvar[step_idx] - invar (both raw, step_idx on time dim) raw_diff = outvar[step_idx] - invar # (V, H, W) gt_norm_diff = diff_transform[chosen_interval](raw_diff) # (V, H, W)
# Step 3: Model forward with AMP + gradient checkpointing interval_tensor = torch.tensor( [chosen_interval], device=local_rank, dtype=torch.float32 ) with torch.amp.autocast('cuda', enabled=use_amp, dtype=torch.float16): pred_norm_diff = model( x, variables, interval_tensor, use_checkpoint=True, ) # (1, V, H, W) pred_norm_diff = _replace_constant(pred_norm_diff.float(), variables)
# Step 4: Loss in diff-normalized space gt_norm_diff = gt_norm_diff.unsqueeze(0) # (1, V, H, W) loss = loss_obj(pred_norm_diff, gt_norm_diff)
optimizer.zero_grad() scaler.scale(loss).backward() scaler.step(optimizer) scaler.update()
train_loss += loss.item()
if world_rank == 0: elapsed = time.time() - start_time logger.info( f'Train: Epoch {epoch}-{j+1}/{len(train_dataloader)} ' f'[cost {int(elapsed // 60):02}:{int(elapsed % 60):02}] ' f'[{elapsed/(j+1):.02f}s/batch] ' f'interval={chosen_interval}h ' f'loss:{train_loss / (j+1):.04f}' )
train_loss /= len(train_dataloader)
# ---- Validation ---- model.eval() valid_loss = 0 val_start = time.time()
with torch.no_grad(): for j, data in enumerate(val_dataloader): # Squeeze batch dim (batch_size=1) invar = data[0].to(local_rank, dtype=torch.float32).squeeze(0) outvar = data[1].to(local_rank, dtype=torch.float32).squeeze(0)
# Use 6h interval for validation (simple next-step) val_interval = 6 target_frame = outvar[0] # t+6h
# Same forward logic as training x = inp_transform(invar).unsqueeze(0) raw_diff = target_frame - invar gt_norm_diff = diff_transform[val_interval](raw_diff)
interval_tensor = torch.tensor( [val_interval], device=local_rank, dtype=torch.float32 ) with torch.amp.autocast('cuda', enabled=use_amp, dtype=torch.float16): pred_norm_diff = model( x, variables, interval_tensor, use_checkpoint=False, ) pred_norm_diff = _replace_constant(pred_norm_diff.float(), variables)
gt_norm_diff = gt_norm_diff.unsqueeze(0) loss = loss_obj(pred_norm_diff, gt_norm_diff)
if cfg.world_size > 1: loss_tensor = loss.detach().to(local_rank) dist.all_reduce(loss_tensor) loss = loss_tensor.item() / cfg.world_size valid_loss += loss else: valid_loss += loss.item()
if world_rank == 0: logger.info( f'Valid: Epoch {epoch}-{j+1}/{len(val_dataloader)} ' f'[{(time.time()-val_start)/(j+1):.02f}s/batch] ' f'loss:{valid_loss / (j+1):.04f}' )
valid_loss /= len(val_dataloader)
# ---- Checkpoint & Early stopping ---- is_save_ckp = False if valid_loss < best_valid_loss: best_valid_loss = valid_loss best_loss_epoch = epoch if world_rank == 0: save_checkpoint( model, optimizer, scheduler, best_valid_loss, best_loss_epoch, cfg.checkpoint_dir ) is_save_ckp = True
scheduler.step(valid_loss)
if world_rank == 0: logger.info( f"Epoch [{epoch + 1}/{cfg.max_epoch}], " f"Train Loss: {train_loss:.4f}, " f"Valid Loss: {valid_loss:.4f}, " f"Best loss at Epoch: {best_loss_epoch + 1}" + (", saving checkpoint" if is_save_ckp else "") ) train_losses = np.append(train_losses, train_loss) valid_losses = np.append(valid_losses, valid_loss) np.save(train_loss_file, train_losses) np.save(valid_loss_file, valid_losses)
if epoch - best_loss_epoch > cfg.patience: if world_rank == 0: print(f"Loss has not decreased in {cfg.patience} epochs, stopping.") break
# ============================================================================# Helper: zero out constant variable predictions# ============================================================================
from model.stormer import CONSTANTS
def _replace_constant(yhat, out_variables): """Zero out diffs for constant/invariant variables.""" for i in range(yhat.shape[1]): if out_variables[i] in CONSTANTS: yhat[:, i] = 0.0 return yhat
# ============================================================================# Latitude-weighted L1 Loss# ============================================================================
class _LatWeightedL1Loss(nn.Module): """Latitude-weighted L1 loss."""
def __init__(self, lat, device): super().__init__() w_lat = np.cos(np.deg2rad(lat)) w_lat = w_lat / w_lat.mean() self.w_lat = torch.from_numpy(w_lat).float().to(device).unsqueeze(0).unsqueeze(-1)
def forward(self, pred, target): error = torch.abs(pred - target) # (B, V, H, W) weighted = error * self.w_lat.unsqueeze(1) # (B, V, H, W) return weighted.mean()
# ============================================================================# Checkpoint utilities# ============================================================================
def save_checkpoint(model, optimizer, scheduler, best_valid_loss, best_loss_epoch, model_path): model_to_save = model.module if hasattr(model, "module") else model state = { "model_state_dict": model_to_save.state_dict(), "optimizer_state_dict": optimizer.state_dict(), "scheduler_state_dict": scheduler.state_dict(), "best_valid_loss": best_valid_loss, "best_loss_epoch": best_loss_epoch, } torch.save(state, f"{model_path}/model.pth") os.system(f"cp {model_path}/model.pth {model_path}/model_bak.pth")
if __name__ == "__main__": current_path = os.getcwd() sys.path.append(current_path) main().gitattributes+41-9
README.mdAdded+147
conf/config.yamlAdded+192
configuration.jsonAdded+1
model/stormer.pyAdded+722
scripts/fake_data.pyAdded+270
scripts/inference.pyAdded+274
scripts/result.pyAdded+351
scripts/train.pyAdded+525
weight/.gitkeepAdded