yzt15806542928 commited on
Commit
807a08b
·
verified ·
1 Parent(s): 26228d2

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ frameworks: PyTorch
3
+ language:
4
+ - en
5
+ license: apache-2.0
6
+ tags:
7
+ - OneScience
8
+ - Earth Science
9
+ - Weather Forecast
10
+ - Global Weather Forecast
11
+ - ERA5
12
+ - Neural ODE
13
+ tasks: []
14
+ datasets:
15
+ - OneScience/ERA5
16
+ ---
17
+ <p align="center">
18
+ <strong>
19
+ <span style="font-size: 30px;">ClimODE</span>
20
+ </strong>
21
+ </p>
22
+
23
+ # Model Introduction
24
+
25
+ ClimODE is a weather forecasting model proposed in 2024 by researchers from Aalto University and collaborating institutions.
26
+
27
+ Paper: ClimODE: Climate and Weather Forecasting with Physics-informed Neural ODEs
28
+
29
+ https://arxiv.org/abs/2404.10024
30
+
31
+ # Model Description
32
+
33
+ ClimODE is a physics-informed neural ordinary differential equation model for global, monthly-scale, and regional climate and weather forecasting. It represents atmospheric evolution as a continuous-time dynamical system and incorporates a transport-based physical inductive bias into the neural ODE.
34
+
35
+ # Use Cases
36
+
37
+ | Scenario | Description |
38
+ | :---: | :--- |
39
+ | Global weather forecasting | Train or evaluate ClimODE on ERA5 data following this project's five-variable protocol. |
40
+ | Local quick validation | Use synthetic ERA5 HDF5 data to check data loading, training, inference, evaluation, and visualization. |
41
+ | ModelScope / OneCode execution | Download the standalone model package, install dependencies, and run the scripts directly. |
42
+ | Multi-GPU training | Launch PyTorch DistributedDataParallel 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
+ - Training and inference require a GPU or DCU recognized by PyTorch. CPU can be used to generate synthetic data and inspect configuration, but cannot run the current training and inference scripts.
57
+ - Multi-GPU training uses the NCCL backend. Ensure that the device driver, communication libraries, and PyTorch version are compatible.
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/ClimODE --local-dir ./ClimODE
64
+ cd ClimODE
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
+
81
+ ```bash
82
+ # Please activate CONDA first
83
+ conda create -n onescience311 python=3.11 -y libstdcxx-ng=12 libgcc-ng=12 gcc_linux-64=12 gxx_linux-64=12
84
+ conda activate onescience311
85
+ # uv installation is supported
86
+ pip install onescience[earth-gpu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai
87
+ ```
88
+
89
+ ### Training Data Introduction
90
+
91
+ The OneScience community provides an ERA5 data slice for training. Download it and confirm that the paths in `conf/config.yaml` point to the downloaded data:
92
+
93
+ ```bash
94
+ hf download --repo-type dataset OneScience-Group/ERA5 --local-dir ./data
95
+ ```
96
+
97
+ ClimODE reads the five variables `z`, `t`, `t2m`, `u10`, and `v10`, regridding the source `721x1440` fields to the model's `32x64` grid. The source variable mapping is defined in `conf/config.yaml`.
98
+
99
+ ### Generate Synthetic Data
100
+
101
+ When real ERA5 data is unavailable, generate a full-resolution synthetic fixture for pipeline validation:
102
+
103
+ ```bash
104
+ python scripts/fake_data.py
105
+ ```
106
+
107
+ Synthetic data does not represent ERA5 and cannot reproduce the paper's metrics.
108
+
109
+ ### Training
110
+
111
+ Single GPU:
112
+
113
+ ```bash
114
+ python scripts/train.py
115
+ ```
116
+
117
+ Multi-GPU:
118
+
119
+ ```bash
120
+ torchrun --nproc_per_node=8 scripts/train.py
121
+ ```
122
+
123
+ The default checkpoint is saved to `data/checkpoints/model_bak.pth`.
124
+
125
+ ### Fine-tuning
126
+
127
+ To fine-tune from an existing checkpoint, pass an explicit checkpoint and mode:
128
+
129
+ ```bash
130
+ python scripts/train.py --mode finetune --checkpoint data/checkpoints/model_bak.pth
131
+ ```
132
+
133
+ An official pretrained checkpoint can be selected explicitly with `--use-pretrained --pretrained-checkpoint <path>`.
134
+
135
+ ### Training Weights
136
+
137
+ This repository provides a `weight/` directory for ClimODE checkpoints. The weight files will be uploaded soon and are expected to be available in the near future.
138
+
139
+ ### Inference
140
+
141
+ Inference reads `data/checkpoints/model_bak.pth` by default. If it is unavailable, pass `--checkpoint` explicitly:
142
+
143
+ ```bash
144
+ python scripts/inference.py
145
+ ```
146
+
147
+ Predictions, uncertainty estimates, and targets are written to `result/output/`.
148
+
149
+ ### Evaluation and Visualization
150
+
151
+ ```bash
152
+ python scripts/result.py
153
+ ```
154
+
155
+ The script computes latitude-weighted RMSE, ACC, and CRPS, and writes per-variable figures to `result/output/figures/`.
156
+
157
+ # Official OneScience Resources
158
+
159
+ | Platform | OneScience Main Repository | Skills Repository |
160
+ | --- | --- | --- |
161
+ | Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills |
162
+ | GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills |
163
+
164
+ # Citation and License
165
+
166
+ - This repository is a OneScience adaptation of the ClimODE paper and is not the official Aalto-QuML release.
conf/config.yaml ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ name: ClimODE
3
+ default_checkpoint: ./data/checkpoints/model_bak.pth
4
+ pretrained_checkpoint: ./weight/ClimODE_global.pt
5
+ input_channels: 5
6
+ input_height: 32
7
+ input_width: 64
8
+ solver: euler
9
+ atol: 0.005
10
+ rtol: 0.005
11
+ use_attention: true
12
+ use_uncertainty: true
13
+ use_positional_encoder: false
14
+ learning_rate: 0.0005
15
+ weight_decay: 0.00001
16
+ epochs: 10
17
+ checkpoint_dir: ./data/checkpoints
18
+
19
+ data:
20
+ data_dir: ./data
21
+ # ERA5Dataset receives this root and resolves data/<year>.h5 itself.
22
+ raw_data_dir: ./data/data
23
+ static_dir: ./data/static
24
+ output_dir: ./result/output
25
+ time_step_hours: 6
26
+ input_steps: 1
27
+ output_steps: 1
28
+ # ClimODE min-max normalization; ERA5Dataset's mean/std transform stays disabled.
29
+ normalize: true
30
+ # ClimODE uses the following order throughout the model and metrics.
31
+ variables: [z, t, t2m, u10, v10]
32
+ variable_sources:
33
+ z: geopotential_500
34
+ t: temperature_850
35
+ t2m: 2m_temperature
36
+ u10: 10m_u_component_of_wind
37
+ v10: 10m_v_component_of_wind
38
+ train_years: [2014, 2015]
39
+ val_years: [2016]
40
+ test_years: [2017]
41
+ raw_height: 721
42
+ raw_width: 1440
43
+ model_height: 32
44
+ model_width: 64
45
+ regrid_method: bilinear
46
+ stats_dir: ./data/static
47
+ static_file: ./data/static/constants.h5
48
+ dataloader:
49
+ batch_size: 8
50
+ num_workers: 0
51
+ pin_memory: false
52
+ drop_last: false
53
+ sequence_length: 8
54
+
55
+ velocity:
56
+ cache_dir: ./data/checkpoints/velocity
57
+ optimizer: Adam
58
+ learning_rate: 2.0
59
+ epochs: 200
60
+ smoothing_alpha: 1.0e-7
61
+ kernel_sigma: 1.0
62
+
63
+ training:
64
+ epochs: 10
65
+ finetune_epochs: 5
66
+ finetune_learning_rate: 0.00005
67
+ mode: scratch
68
+ seed: 42
69
+ ddp_backend: nccl
70
+ max_batches: null
71
+ log_file: ./result/train.jsonl
72
+
73
+ fake_data:
74
+ # The default is intentionally small in time but preserves the real ERA5 grid.
75
+ timesteps: 12
76
+ years: [2014, 2015, 2016, 2017]
77
+ height: 721
78
+ width: 1440
79
+ seed: 42
80
+ dtype: float32
81
+
82
+ runtime:
83
+ device: cuda
84
+ module: sghpc-mpi-gcc/26.3
85
+ conda_env: develop_base
86
+
87
+ output:
88
+ checkpoint_name: model_bak.pth
89
+ metrics_file: ./result/metrics.json
90
+ prediction_file: ./result/output/predictions.npy
91
+ figure_dir: ./result/output/figures
config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "ClimODE",
3
+ "model_type": "climode",
4
+ "architectures": [
5
+ "ClimODE",
6
+ "ClimateEncoderFreeUncertain"
7
+ ],
8
+ "framework": "PyTorch",
9
+ "domain": "atmosphere",
10
+ "task": "global-weather-forecasting-with-neural-odes",
11
+ "implementation": {
12
+ "entry_point": "model/climode.py",
13
+ "scope": "OneScience adapter of the physics-informed neural transport ODE with optional attention and probabilistic output; it is not an AutoModel-compatible Transformers implementation"
14
+ },
15
+ "architecture": {
16
+ "family": "physics-informed neural ODE with advective transport and convolutional velocity/noise networks",
17
+ "input_format": "BCHW",
18
+ "input_grid_shape": [
19
+ 32,
20
+ 64
21
+ ],
22
+ "input_channels": 5,
23
+ "output_channels": 5,
24
+ "time_step_hours": 6,
25
+ "solver": "euler",
26
+ "absolute_tolerance": 0.005,
27
+ "relative_tolerance": 0.005,
28
+ "use_attention": true,
29
+ "use_uncertainty": true,
30
+ "use_positional_encoder": false,
31
+ "resnet_repetitions": [
32
+ 5,
33
+ 3,
34
+ 2
35
+ ],
36
+ "resnet_hidden_channels": [
37
+ 128,
38
+ 64,
39
+ 10
40
+ ],
41
+ "history_frames_for_context": 3
42
+ },
43
+ "data": {
44
+ "dataset": "ERA5",
45
+ "source_grid_shape": [
46
+ 721,
47
+ 1440
48
+ ],
49
+ "model_grid_shape": [
50
+ 32,
51
+ 64
52
+ ],
53
+ "regrid_method": "bilinear with periodic longitude handling",
54
+ "variables": [
55
+ "z",
56
+ "t",
57
+ "t2m",
58
+ "u10",
59
+ "v10"
60
+ ],
61
+ "variable_sources": {
62
+ "z": "geopotential_500",
63
+ "t": "temperature_850",
64
+ "t2m": "2m_temperature",
65
+ "u10": "10m_u_component_of_wind",
66
+ "v10": "10m_v_component_of_wind"
67
+ },
68
+ "input_steps": 1,
69
+ "output_steps": 1,
70
+ "normalization": "ClimODE min-max normalization; source statistics are loaded from the configured static directory",
71
+ "uncertainty_output": "mean and standard deviation fields when use_uncertainty is enabled"
72
+ },
73
+ "configuration_sources": [
74
+ "conf/config.yaml",
75
+ "model/climode.py",
76
+ "scripts/data_loader.py",
77
+ "scripts/train.py"
78
+ ]
79
+ }
configuration.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "framework": "PyTorch",
3
+ "task": "weather_forecasting",
4
+ "model": "ClimODE",
5
+ "input_format": "BCHW",
6
+ "protocol": "weatherbench_era5_5_variable",
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/climode.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ClimODE's official global neural transport model.
2
+
3
+ The equations and layer layout follow Aalto-QuML/ClimODE. The small wrapper
4
+ at the bottom adds configuration-friendly construction and checkpoint loading;
5
+ the core ``ClimateEncoderFreeUncertain`` class intentionally keeps the
6
+ official state and tensor layout.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib
12
+ from pathlib import Path
13
+ import sys
14
+ from typing import Any, Sequence
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+
20
+ try:
21
+ from torchdiffeq import odeint as _torchdiffeq_odeint
22
+ except ImportError: # pragma: no cover - exercised when optional dependency is absent
23
+ _torchdiffeq_odeint = None
24
+
25
+
26
+ def _euler_odeint(func, y0: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
27
+ """Equivalent fixed-step Euler solver used only when torchdiffeq is absent."""
28
+
29
+ states = [y0]
30
+ for index in range(1, len(t)):
31
+ previous = states[-1]
32
+ dt = t[index] - t[index - 1]
33
+ states.append(previous + dt * func(t[index - 1], previous))
34
+ return torch.stack(states, dim=0)
35
+
36
+
37
+ def odeint(func, y0: torch.Tensor, t: torch.Tensor, method: str = "euler", **kwargs):
38
+ if _torchdiffeq_odeint is not None:
39
+ return _torchdiffeq_odeint(func, y0, t, method=method, **kwargs)
40
+ if method != "euler":
41
+ raise ImportError(
42
+ "torchdiffeq is required for solver=%r; install the official dependency."
43
+ % method
44
+ )
45
+ return _euler_odeint(func, y0, t)
46
+
47
+
48
+ class OptimVelocity(nn.Module):
49
+ """Learn the initial per-channel velocity used to start the ODE system."""
50
+
51
+ def __init__(self, num_years: int, height: int, width: int, out_channels: int = 5):
52
+ super().__init__()
53
+ self.out_channels = out_channels
54
+ self.v_x = nn.Parameter(
55
+ torch.randn(num_years, 1, out_channels, height, width)
56
+ )
57
+ self.v_y = nn.Parameter(
58
+ torch.randn(num_years, 1, out_channels, height, width)
59
+ )
60
+
61
+ def forward(self, data: torch.Tensor):
62
+ u_y = torch.gradient(data, dim=3)[0]
63
+ u_x = torch.gradient(data, dim=4)[0]
64
+ divergence = torch.gradient(self.v_y, dim=3)[0] + torch.gradient(
65
+ self.v_x, dim=4
66
+ )[0]
67
+ adv = self.v_x * u_x + self.v_y * u_y + data * divergence
68
+ return adv, self.v_x, self.v_y
69
+
70
+
71
+ class BoundaryPad(nn.Module):
72
+ """Reflect at the poles and wrap around the longitude seam."""
73
+
74
+ def forward(self, value: torch.Tensor) -> torch.Tensor:
75
+ return F.pad(F.pad(value, (0, 0, 1, 1), "reflect"), (1, 1, 0, 0), "circular")
76
+
77
+
78
+ class ResidualBlock(nn.Module):
79
+ def __init__(self, in_channels: int, out_channels: int):
80
+ super().__init__()
81
+ self.activation = nn.LeakyReLU(0.3)
82
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=0)
83
+ self.bn1 = nn.BatchNorm2d(out_channels)
84
+ self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=0)
85
+ self.bn2 = nn.BatchNorm2d(out_channels)
86
+ self.drop = nn.Dropout(p=0.1)
87
+ self.shortcut = (
88
+ nn.Conv2d(in_channels, out_channels, kernel_size=1)
89
+ if in_channels != out_channels
90
+ else nn.Identity()
91
+ )
92
+
93
+ def forward(self, value: torch.Tensor) -> torch.Tensor:
94
+ value_padded = F.pad(
95
+ F.pad(value, (0, 0, 1, 1), "reflect"), (1, 1, 0, 0), "circular"
96
+ )
97
+ hidden = self.activation(self.bn1(self.conv1(value_padded)))
98
+ hidden = F.pad(
99
+ F.pad(hidden, (0, 0, 1, 1), "reflect"), (1, 1, 0, 0), "circular"
100
+ )
101
+ hidden = self.activation(self.bn2(self.conv2(hidden)))
102
+ return self.drop(hidden) + self.shortcut(value)
103
+
104
+
105
+ class ClimateResNet2D(nn.Module):
106
+ def __init__(
107
+ self,
108
+ num_channels: int,
109
+ layers: Sequence[int],
110
+ hidden_size: Sequence[int],
111
+ ):
112
+ super().__init__()
113
+ if len(layers) != len(hidden_size):
114
+ raise ValueError("layers and hidden_size must have equal lengths")
115
+ self.layer_cnn = nn.ModuleList(
116
+ [nn.Sequential(*blocks_for_layer) for blocks_for_layer in self._split_blocks(layers, hidden_size, num_channels)]
117
+ )
118
+
119
+ @staticmethod
120
+ def _split_blocks(
121
+ layers: Sequence[int], hidden_size: Sequence[int], num_channels: int
122
+ ) -> list[list[nn.Module]]:
123
+ groups: list[list[nn.Module]] = []
124
+ in_channels = num_channels
125
+ for repetitions, out_channels in zip(layers, hidden_size):
126
+ group = [ResidualBlock(in_channels, out_channels)]
127
+ group.extend(
128
+ ResidualBlock(out_channels, out_channels)
129
+ for _ in range(1, int(repetitions))
130
+ )
131
+ groups.append(group)
132
+ in_channels = out_channels
133
+ return groups
134
+
135
+ def forward(self, value: torch.Tensor) -> torch.Tensor:
136
+ output = value.float()
137
+ for layer in self.layer_cnn:
138
+ output = layer(output)
139
+ return output
140
+
141
+
142
+ class SelfAttnConv(nn.Module):
143
+ """Official key-query-value attention convolution."""
144
+
145
+ def __init__(self, in_channels: int, out_channels: int):
146
+ super().__init__()
147
+ self.query = self._conv(in_channels, in_channels // 8, stride=1)
148
+ self.key = self._key_conv(in_channels, in_channels // 8, stride=2)
149
+ self.value = self._key_conv(in_channels, out_channels, stride=2)
150
+ self.post_map = nn.Sequential(
151
+ nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, padding=0)
152
+ )
153
+ self.out_ch = out_channels
154
+
155
+ @staticmethod
156
+ def _conv(n_in: int, n_out: int, stride: int) -> nn.Sequential:
157
+ return nn.Sequential(
158
+ BoundaryPad(),
159
+ nn.Conv2d(n_in, n_in // 2, kernel_size=3, stride=stride, padding=0),
160
+ nn.LeakyReLU(0.3),
161
+ BoundaryPad(),
162
+ nn.Conv2d(n_in // 2, n_out, kernel_size=3, stride=stride, padding=0),
163
+ nn.LeakyReLU(0.3),
164
+ BoundaryPad(),
165
+ nn.Conv2d(n_out, n_out, kernel_size=3, stride=stride, padding=0),
166
+ )
167
+
168
+ @staticmethod
169
+ def _key_conv(n_in: int, n_out: int, stride: int) -> nn.Sequential:
170
+ return nn.Sequential(
171
+ nn.Conv2d(n_in, n_in // 2, kernel_size=3, stride=stride, padding=0),
172
+ nn.LeakyReLU(0.3),
173
+ nn.Conv2d(n_in // 2, n_out, kernel_size=3, stride=stride, padding=0),
174
+ nn.LeakyReLU(0.3),
175
+ nn.Conv2d(n_out, n_out, kernel_size=3, stride=1, padding=0),
176
+ )
177
+
178
+ def forward(self, value: torch.Tensor) -> torch.Tensor:
179
+ size = value.size()
180
+ value = value.float()
181
+ query = self.query(value).flatten(-2, -1)
182
+ key = self.key(value).flatten(-2, -1)
183
+ val = self.value(value).flatten(-2, -1)
184
+ beta = F.softmax(torch.bmm(query.transpose(1, 2), key), dim=1)
185
+ output = torch.bmm(val, beta.transpose(1, 2))
186
+ output = output.view(-1, self.out_ch, size[-2], size[-1]).contiguous()
187
+ return self.post_map(output)
188
+
189
+
190
+ class ClimateEncoderFreeUncertain(nn.Module):
191
+ """Official global ``Climate_encoder_free_uncertain`` implementation."""
192
+
193
+ def __init__(
194
+ self,
195
+ num_channels: int = 5,
196
+ const_channels: int = 2,
197
+ out_types: int = 5,
198
+ method: str = "euler",
199
+ use_att: bool = True,
200
+ use_err: bool = True,
201
+ use_pos: bool = False,
202
+ ):
203
+ super().__init__()
204
+ self.layers = [5, 3, 2]
205
+ self.hidden = [128, 64, 2 * out_types]
206
+ input_channels = 30 + out_types * int(use_pos) + 34 * (1 - int(use_pos))
207
+ self.vel_f = ClimateResNet2D(input_channels, self.layers, self.hidden)
208
+ if use_att:
209
+ self.vel_att = SelfAttnConv(input_channels, 10)
210
+ self.gamma = nn.Parameter(torch.tensor([0.1]))
211
+
212
+ self.scales = num_channels
213
+ self.const_channel = const_channels
214
+ self.out_ch = out_types
215
+ self.past_samples: torch.Tensor | int = 0
216
+ self.const_info: torch.Tensor | int = 0
217
+ self.lat_map: torch.Tensor | int = 0
218
+ self.lon_map: torch.Tensor | int = 0
219
+ self.method = method
220
+ err_in = 9 + out_types * int(use_pos) + 34 * (1 - int(use_pos))
221
+ if use_err:
222
+ self.noise_net = ClimateResNet2D(err_in, [3, 2, 2], [128, 64, 2 * out_types])
223
+ if use_pos:
224
+ self.pos_enc = ClimateResNet2D(4, [2, 1, 1], [32, 16, out_types])
225
+ self.att = use_att
226
+ self.err = use_err
227
+ self.pos = use_pos
228
+ self.pos_feat: torch.Tensor | int = 0
229
+ self.lsm: torch.Tensor | int = 0
230
+ self.oro: torch.Tensor | int = 0
231
+
232
+ def update_param(self, params: Sequence[torch.Tensor]) -> None:
233
+ if len(params) != 4:
234
+ raise ValueError("update_param expects past_samples, constants, latitude, longitude")
235
+ self.past_samples, self.const_info, self.lat_map, self.lon_map = params
236
+
237
+ def _time_features(
238
+ self, t: torch.Tensor, height: int, width: int, batch_size: int
239
+ ) -> tuple[torch.Tensor, ...]:
240
+ t_emb = ((t * 100) % 24).view(1, 1, 1, 1).expand(batch_size, 1, height, width)
241
+ sin_t = torch.sin(torch.pi * t_emb / 12 - torch.pi / 2)
242
+ cos_t = torch.cos(torch.pi * t_emb / 12 - torch.pi / 2)
243
+ sin_season = torch.sin(torch.pi * t_emb / (12 * 365) - torch.pi / 2)
244
+ cos_season = torch.cos(torch.pi * t_emb / (12 * 365) - torch.pi / 2)
245
+ return t_emb, torch.cat([sin_t, cos_t], dim=1), torch.cat(
246
+ [sin_season, cos_season], dim=1
247
+ )
248
+
249
+ def pde(self, t: torch.Tensor, state: torch.Tensor) -> torch.Tensor:
250
+ height, width = state.shape[-2:]
251
+ ds = state[:, -self.out_ch :].view(-1, self.out_ch, height, width).float()
252
+ velocity = state[:, : 2 * self.out_ch].view(
253
+ -1, 2 * self.out_ch, height, width
254
+ ).float()
255
+ t_emb, day_emb, season_emb = self._time_features(
256
+ t, height, width, ds.shape[0]
257
+ )
258
+ ds_grad_x = torch.gradient(ds, dim=3)[0]
259
+ ds_grad_y = torch.gradient(ds, dim=2)[0]
260
+ nabla_u = torch.cat([ds_grad_x, ds_grad_y], dim=1)
261
+
262
+ if self.pos:
263
+ combined = torch.cat(
264
+ [t_emb / 24, day_emb, season_emb, nabla_u, velocity, ds, self.pos_feat],
265
+ dim=1,
266
+ )
267
+ else:
268
+ cos_lat, sin_lat = torch.cos(self.new_lat_map), torch.sin(self.new_lat_map)
269
+ cos_lon, sin_lon = torch.cos(self.new_lon_map), torch.sin(self.new_lon_map)
270
+ time_cyclic = torch.cat([day_emb, season_emb], dim=1)
271
+ pos_feats = torch.cat(
272
+ [
273
+ cos_lat,
274
+ cos_lon,
275
+ sin_lat,
276
+ sin_lon,
277
+ sin_lat * cos_lon,
278
+ sin_lat * sin_lon,
279
+ ],
280
+ dim=1,
281
+ )
282
+ pos_time = self.get_time_pos_embedding(time_cyclic, pos_feats)
283
+ combined = torch.cat(
284
+ [
285
+ t_emb / 24,
286
+ day_emb,
287
+ season_emb,
288
+ nabla_u,
289
+ velocity,
290
+ ds,
291
+ self.new_lat_map,
292
+ self.new_lon_map,
293
+ self.lsm,
294
+ self.oro,
295
+ pos_feats,
296
+ pos_time,
297
+ ],
298
+ dim=1,
299
+ )
300
+
301
+ dv = self.vel_f(combined)
302
+ if self.att:
303
+ dv = dv + self.gamma * self.vel_att(combined)
304
+ v_x = velocity[:, : self.out_ch]
305
+ v_y = velocity[:, self.out_ch :]
306
+ advection = v_x * ds_grad_x + v_y * ds_grad_y
307
+ advection = advection + ds * (
308
+ torch.gradient(v_x, dim=3)[0] + torch.gradient(v_y, dim=2)[0]
309
+ )
310
+ return torch.cat([dv, advection], dim=1)
311
+
312
+ @staticmethod
313
+ def get_time_pos_embedding(
314
+ time_features: torch.Tensor, position_features: torch.Tensor
315
+ ) -> torch.Tensor:
316
+ outputs = [feature.unsqueeze(1) * position_features for feature in time_features.unbind(1)]
317
+ return torch.cat(outputs, dim=1)
318
+
319
+ def noise_net_contrib(
320
+ self,
321
+ time: torch.Tensor,
322
+ pos_enc: torch.Tensor,
323
+ s_final: torch.Tensor,
324
+ height: int,
325
+ width: int,
326
+ ) -> tuple[torch.Tensor, torch.Tensor]:
327
+ t_emb = (time % 24).view(-1, 1, 1, 1, 1)
328
+ sin_t = torch.sin(torch.pi * t_emb / 12 - torch.pi / 2).expand(
329
+ len(s_final), s_final.shape[1], 1, height, width
330
+ )
331
+ cos_t = torch.cos(torch.pi * t_emb / 12 - torch.pi / 2).expand(
332
+ len(s_final), s_final.shape[1], 1, height, width
333
+ )
334
+ sin_season = torch.sin(torch.pi * t_emb / (12 * 365) - torch.pi / 2).expand(
335
+ len(s_final), s_final.shape[1], 1, height, width
336
+ )
337
+ cos_season = torch.cos(torch.pi * t_emb / (12 * 365) - torch.pi / 2).expand(
338
+ len(s_final), s_final.shape[1], 1, height, width
339
+ )
340
+ pos_rep = pos_enc.expand(len(s_final), s_final.shape[1], -1, height, width)
341
+ pos_rep = pos_rep.flatten(start_dim=0, end_dim=1)
342
+ time_cyclic = torch.cat([sin_t, cos_t, sin_season, cos_season], dim=2)
343
+ time_cyclic = time_cyclic.flatten(start_dim=0, end_dim=1)
344
+ pos_time = self.get_time_pos_embedding(time_cyclic, pos_rep[:, 2:-2])
345
+ combined = torch.cat(
346
+ [time_cyclic, s_final.flatten(start_dim=0, end_dim=1), pos_rep, pos_time],
347
+ dim=1,
348
+ )
349
+ final_out = self.noise_net(combined).view(
350
+ len(time), -1, 2 * self.out_ch, height, width
351
+ )
352
+ mean = s_final + final_out[:, :, : self.out_ch]
353
+ std = F.softplus(final_out[:, :, self.out_ch :])
354
+ return mean, std
355
+
356
+ def forward(
357
+ self,
358
+ time_steps: torch.Tensor,
359
+ data: torch.Tensor,
360
+ atol: float = 0.1,
361
+ rtol: float = 0.1,
362
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
363
+ if not isinstance(self.past_samples, torch.Tensor):
364
+ raise RuntimeError("Call update_param before forward")
365
+ height, width = self.past_samples.shape[-2:]
366
+ values = data.float().view(-1, self.out_ch, height, width)
367
+ final_data = torch.cat([self.past_samples, values], dim=1)
368
+ init_time = time_steps[0].item() * 6
369
+ final_time = time_steps[-1].item() * 6
370
+ steps_val = final_time - init_time
371
+
372
+ if self.pos:
373
+ lat_map = self.lat_map.unsqueeze(0) * torch.pi / 180
374
+ lon_map = self.lon_map.unsqueeze(0) * torch.pi / 180
375
+ pos_rep = torch.cat([lat_map.unsqueeze(0), lon_map.unsqueeze(0), self.const_info], dim=1)
376
+ self.pos_feat = self.pos_enc(pos_rep).expand(
377
+ values.shape[0], -1, values.shape[-2], values.shape[-1]
378
+ )
379
+ final_pos_enc = self.pos_feat
380
+ else:
381
+ self.oro = self.const_info[0, 0]
382
+ self.lsm = self.const_info[0, 1]
383
+ self.lsm = self.lsm.unsqueeze(0).expand(values.shape[0], -1, height, width)
384
+ self.oro = F.normalize(self.oro).unsqueeze(0).expand(values.shape[0], -1, height, width)
385
+ self.new_lat_map = self.lat_map.expand(values.shape[0], 1, height, width) * torch.pi / 180
386
+ self.new_lon_map = self.lon_map.expand(values.shape[0], 1, height, width) * torch.pi / 180
387
+ cos_lat, sin_lat = torch.cos(self.new_lat_map), torch.sin(self.new_lat_map)
388
+ cos_lon, sin_lon = torch.cos(self.new_lon_map), torch.sin(self.new_lon_map)
389
+ pos_feats = torch.cat(
390
+ [cos_lat, cos_lon, sin_lat, sin_lon, sin_lat * cos_lon, sin_lat * sin_lon],
391
+ dim=1,
392
+ )
393
+ final_pos_enc = torch.cat(
394
+ [self.new_lat_map, self.new_lon_map, pos_feats, self.lsm, self.oro], dim=1
395
+ )
396
+
397
+ integration_steps = max(int(steps_val) + 1, 1)
398
+ new_time_steps = torch.linspace(
399
+ init_time, final_time, steps=integration_steps, device=values.device
400
+ )
401
+ ode_time = 0.01 * new_time_steps.float()
402
+ final_result = odeint(
403
+ self.pde,
404
+ final_data,
405
+ ode_time,
406
+ method=self.method,
407
+ atol=atol,
408
+ rtol=rtol,
409
+ )
410
+ s_final = final_result[:, :, -self.out_ch :].view(
411
+ len(ode_time), -1, self.out_ch, height, width
412
+ )
413
+ sampled = s_final[0 : len(s_final) : 6]
414
+ if self.err:
415
+ mean, std = self.noise_net_contrib(
416
+ time_steps, final_pos_enc, sampled, height, width
417
+ )
418
+ return mean, std, sampled
419
+ return sampled, torch.zeros_like(sampled), sampled
420
+
421
+
422
+ class ClimODE(ClimateEncoderFreeUncertain):
423
+ """Configuration-friendly public model name."""
424
+
425
+ def __init__(
426
+ self,
427
+ num_channels: int = 5,
428
+ const_channels: int = 2,
429
+ out_types: int = 5,
430
+ method: str = "euler",
431
+ use_attention: bool = True,
432
+ use_uncertainty: bool = True,
433
+ use_positional_encoder: bool = False,
434
+ ):
435
+ super().__init__(
436
+ num_channels=num_channels,
437
+ const_channels=const_channels,
438
+ out_types=out_types,
439
+ method=method,
440
+ use_att=use_attention,
441
+ use_err=use_uncertainty,
442
+ use_pos=use_positional_encoder,
443
+ )
444
+
445
+
446
+ def _register_checkpoint_compat_modules() -> None:
447
+ """Expose legacy top-level module names used by official pickle files."""
448
+
449
+ for legacy_name, current_name in (
450
+ ("model_function", "model.model_function"),
451
+ ("model_utils", "model.model_utils"),
452
+ ):
453
+ module = importlib.import_module(current_name)
454
+ sys.modules.setdefault(legacy_name, module)
455
+
456
+
457
+ def load_checkpoint(path: str | Path, map_location: str | torch.device = "cpu") -> nn.Module:
458
+ """Load an official full-object checkpoint or a state-dict checkpoint."""
459
+
460
+ checkpoint_path = Path(path)
461
+ if not checkpoint_path.is_file():
462
+ raise FileNotFoundError(checkpoint_path)
463
+ _register_checkpoint_compat_modules()
464
+ try:
465
+ checkpoint = torch.load(checkpoint_path, map_location=map_location, weights_only=False)
466
+ except TypeError: # Older PyTorch does not expose weights_only.
467
+ checkpoint = torch.load(checkpoint_path, map_location=map_location)
468
+ if isinstance(checkpoint, nn.Module):
469
+ return checkpoint
470
+ model = ClimODE()
471
+ if isinstance(checkpoint, dict):
472
+ state_dict = checkpoint.get("state_dict", checkpoint.get("model", checkpoint))
473
+ else:
474
+ state_dict = checkpoint
475
+ model.load_state_dict(state_dict)
476
+ return model
477
+
478
+
479
+ # Names kept for the official checkpoint's pickle module/class references.
480
+ Climate_encoder_free_uncertain = ClimateEncoderFreeUncertain
481
+ Climate_ResNet_2D = ClimateResNet2D
482
+ Self_attn_conv = SelfAttnConv
483
+ boundarypad = BoundaryPad
model/model_function.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compatibility exports for the official ClimODE checkpoint pickle."""
2
+
3
+ from model.climode import (
4
+ ClimateEncoderFreeUncertain,
5
+ ClimateResNet2D,
6
+ Climate_encoder_free_uncertain,
7
+ Climate_ResNet_2D,
8
+ OptimVelocity,
9
+ SelfAttnConv,
10
+ Self_attn_conv,
11
+ )
12
+
13
+ __all__ = [
14
+ "Climate_encoder_free_uncertain",
15
+ "Climate_ResNet_2D",
16
+ "OptimVelocity",
17
+ "Self_attn_conv",
18
+ "ClimateEncoderFreeUncertain",
19
+ "ClimateResNet2D",
20
+ "SelfAttnConv",
21
+ ]
model/model_utils.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Compatibility exports for the official ClimODE checkpoint pickle."""
2
+
3
+ from model.climode import BoundaryPad, ResidualBlock, SelfAttnConv
4
+
5
+ boundarypad = BoundaryPad
6
+ Self_attn_conv = SelfAttnConv
7
+
8
+ __all__ = ["boundarypad", "ResidualBlock", "Self_attn_conv"]
scripts/data_loader.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OneScience ERA5Dataset adapter for ClimODE's 32x64 global grid."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Iterable, Sequence
7
+
8
+ import h5py
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from torch.utils.data import DataLoader, Dataset
13
+
14
+ try:
15
+ from onescience.datapipes.climate.era5 import ERA5Dataset
16
+ except ImportError as exc: # pragma: no cover - exercised only without OneScience
17
+ ERA5Dataset = None
18
+ _ERA5_IMPORT_ERROR = exc
19
+ else:
20
+ _ERA5_IMPORT_ERROR = None
21
+
22
+
23
+ OFFICIAL_VARIABLES = ("z", "t", "t2m", "u10", "v10")
24
+
25
+
26
+ def _require_era5dataset() -> None:
27
+ if ERA5Dataset is None:
28
+ raise ImportError(
29
+ "ClimODE data loading requires OneScience ERA5Dataset; "
30
+ "activate an environment containing onescience before running."
31
+ ) from _ERA5_IMPORT_ERROR
32
+
33
+
34
+ def _as_channel_vector(values: np.ndarray | torch.Tensor) -> torch.Tensor:
35
+ tensor = torch.as_tensor(values, dtype=torch.float32)
36
+ return tensor.reshape(-1)
37
+
38
+
39
+ def _regrid_periodic(frame: torch.Tensor, target_size: tuple[int, int]) -> torch.Tensor:
40
+ """Bilinearly sample [C,H,W] on WeatherBench cell centers."""
41
+
42
+ if frame.ndim != 3:
43
+ raise ValueError(f"Expected [C,H,W], got {tuple(frame.shape)}")
44
+ target_height, target_width = target_size
45
+ if frame.shape[-2:] == target_size:
46
+ return frame
47
+ periodic = torch.cat([frame, frame[..., :1]], dim=-1).unsqueeze(0)
48
+ latitude = torch.linspace(
49
+ 90.0 - 90.0 / target_height,
50
+ -90.0 + 90.0 / target_height,
51
+ target_height,
52
+ device=frame.device,
53
+ dtype=frame.dtype,
54
+ )
55
+ longitude = (
56
+ torch.arange(target_width, device=frame.device, dtype=frame.dtype)
57
+ * (360.0 / target_width)
58
+ )
59
+ lat2d, lon2d = torch.meshgrid(latitude, longitude, indexing="ij")
60
+ grid = torch.stack([lon2d / 180.0 - 1.0, -lat2d / 90.0], dim=-1)
61
+ return F.grid_sample(
62
+ periodic,
63
+ grid.unsqueeze(0),
64
+ mode="bilinear",
65
+ padding_mode="border",
66
+ align_corners=True,
67
+ )[0]
68
+
69
+
70
+ def _load_stats(stats_dir: str | Path, channels: int) -> tuple[torch.Tensor, torch.Tensor]:
71
+ stats_path = Path(stats_dir)
72
+ minimum = _as_channel_vector(np.load(stats_path / "min_values.npy"))
73
+ maximum = _as_channel_vector(np.load(stats_path / "max_values.npy"))
74
+ if minimum.numel() != channels or maximum.numel() != channels:
75
+ raise ValueError(
76
+ f"Expected {channels} channel statistics, got {minimum.numel()} and {maximum.numel()}"
77
+ )
78
+ if torch.any(maximum <= minimum):
79
+ raise ValueError("All max_values must be greater than min_values")
80
+ return minimum, maximum
81
+
82
+
83
+ def _normalize(frame: torch.Tensor, minimum: torch.Tensor, maximum: torch.Tensor) -> torch.Tensor:
84
+ scale = (maximum - minimum).clamp_min(torch.finfo(frame.dtype).eps)
85
+ return (frame - minimum[:, None, None]) / scale[:, None, None]
86
+
87
+
88
+ class ClimODEDataset(Dataset):
89
+ """Return three history frames and the following target frame.
90
+
91
+ The underlying annual files are always read by OneScience ``ERA5Dataset``.
92
+ No direct HDF5 field access is used here, which keeps the model adapter
93
+ compatible with the OneScience ERA5 contract.
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ data_dir: str | Path,
99
+ years: Sequence[int],
100
+ used_variables: Sequence[str] = OFFICIAL_VARIABLES,
101
+ stats_dir: str | Path | None = None,
102
+ model_size: tuple[int, int] = (32, 64),
103
+ normalize: bool = True,
104
+ input_steps: int = 1,
105
+ output_steps: int = 1,
106
+ ) -> None:
107
+ _require_era5dataset()
108
+ if tuple(used_variables) != OFFICIAL_VARIABLES:
109
+ raise ValueError(
110
+ "ClimODE requires the exact channel order ['z','t','t2m','u10','v10']"
111
+ )
112
+ if input_steps != 1 or output_steps != 1:
113
+ raise ValueError("The ClimODE adapter currently uses one input and one target step")
114
+ if len(years) == 0:
115
+ raise ValueError("At least one year is required")
116
+ # ``data_dir`` is the OneScience dataset root containing data/*.h5,
117
+ # rather than the nested data/ directory itself.
118
+ self.data_dir = Path(data_dir)
119
+ self.years = [int(year) for year in years]
120
+ self.variables = tuple(used_variables)
121
+ self.model_size = tuple(model_size)
122
+ self.normalize = normalize
123
+ self.era5 = ERA5Dataset(
124
+ dataset_dir=str(self.data_dir),
125
+ used_years=self.years,
126
+ used_variables=list(self.variables),
127
+ input_steps=1,
128
+ output_steps=1,
129
+ normalize=False,
130
+ )
131
+ if (self.era5.H, self.era5.W) != (721, 1440):
132
+ raise ValueError(
133
+ "ClimODE raw-data adapter expects (721,1440), "
134
+ f"got ({self.era5.H},{self.era5.W})"
135
+ )
136
+ self.samples_per_year = self.era5.samples_per_year
137
+ if self.samples_per_year < 3:
138
+ raise ValueError("Each year needs at least four frames for a three-frame history and target")
139
+ self.samples_per_year_with_history = self.samples_per_year - 2
140
+ self.minimum, self.maximum = (
141
+ _load_stats(stats_dir or self.data_dir / "static", len(self.variables))
142
+ if normalize
143
+ else (torch.zeros(len(self.variables)), torch.ones(len(self.variables)))
144
+ )
145
+
146
+ def __len__(self) -> int:
147
+ return len(self.years) * self.samples_per_year_with_history
148
+
149
+ def _frame(self, sample_index: int, target: bool = False) -> torch.Tensor:
150
+ invar, outvar, _, _, _ = self.era5[sample_index]
151
+ frame = outvar if target else invar
152
+ frame = _regrid_periodic(torch.as_tensor(frame, dtype=torch.float32), self.model_size)
153
+ if self.normalize:
154
+ frame = _normalize(frame, self.minimum, self.maximum)
155
+ return frame
156
+
157
+ def __getitem__(self, index: int) -> dict[str, torch.Tensor | int | str]:
158
+ if index < 0:
159
+ index += len(self)
160
+ if index < 0 or index >= len(self):
161
+ raise IndexError(index)
162
+ year_index = index // self.samples_per_year_with_history
163
+ local_index = index % self.samples_per_year_with_history
164
+ base = year_index * self.samples_per_year + local_index + 2
165
+ history = torch.stack([self._frame(base - 2), self._frame(base - 1), self._frame(base)])
166
+ target = self._frame(base, target=True)
167
+ return {
168
+ "history": history,
169
+ "input": history[-1],
170
+ "target": target,
171
+ "year": self.years[year_index],
172
+ "step_index": local_index + 2,
173
+ }
174
+
175
+
176
+ class ClimODESeriesDataset(Dataset):
177
+ """Official-style sequence batches with years as the inner batch axis.
178
+
179
+ Each item contains a contiguous sequence for every requested year. The
180
+ outer DataLoader should use ``batch_size=1``; the sequence length plays the
181
+ role of the official training batch of time points.
182
+ """
183
+
184
+ def __init__(
185
+ self,
186
+ data_dir: str | Path,
187
+ years: Sequence[int],
188
+ used_variables: Sequence[str] = OFFICIAL_VARIABLES,
189
+ stats_dir: str | Path | None = None,
190
+ model_size: tuple[int, int] = (32, 64),
191
+ sequence_length: int = 8,
192
+ normalize: bool = True,
193
+ ) -> None:
194
+ _require_era5dataset()
195
+ if tuple(used_variables) != OFFICIAL_VARIABLES:
196
+ raise ValueError("ClimODE requires the exact channel order ['z','t','t2m','u10','v10']")
197
+ if sequence_length < 1:
198
+ raise ValueError("sequence_length must be positive")
199
+ self.data_dir = Path(data_dir)
200
+ self.years = [int(year) for year in years]
201
+ self.variables = tuple(used_variables)
202
+ self.model_size = tuple(model_size)
203
+ self.sequence_length = int(sequence_length)
204
+ self.normalize = normalize
205
+ self.era5 = ERA5Dataset(
206
+ dataset_dir=str(self.data_dir),
207
+ used_years=self.years,
208
+ used_variables=list(self.variables),
209
+ input_steps=1,
210
+ output_steps=1,
211
+ normalize=False,
212
+ )
213
+ if (self.era5.H, self.era5.W) != (721, 1440):
214
+ raise ValueError(
215
+ "ClimODE raw-data adapter expects (721,1440), "
216
+ f"got ({self.era5.H},{self.era5.W})"
217
+ )
218
+ self.samples_per_year = self.era5.samples_per_year
219
+ self.frames_per_year = self.era5.T
220
+ first_start = 2
221
+ # The official DataLoader keeps its final, possibly shorter batch.
222
+ self.starts = list(range(first_start, self.frames_per_year, self.sequence_length))
223
+ if not self.starts:
224
+ raise ValueError(
225
+ f"Not enough frames ({self.era5.T}) for sequence_length={sequence_length} "
226
+ "and a three-frame history"
227
+ )
228
+ self.minimum, self.maximum = (
229
+ _load_stats(stats_dir or self.data_dir / "static", len(self.variables))
230
+ if normalize
231
+ else (torch.zeros(len(self.variables)), torch.ones(len(self.variables)))
232
+ )
233
+
234
+ def __len__(self) -> int:
235
+ return len(self.starts)
236
+
237
+ def _frame(self, year_index: int, frame_index: int) -> torch.Tensor:
238
+ if frame_index < 0 or frame_index >= self.frames_per_year:
239
+ raise IndexError(frame_index)
240
+ sample_index = year_index * self.samples_per_year + min(
241
+ frame_index, self.samples_per_year - 1
242
+ )
243
+ invar, outvar, _, _, _ = self.era5[sample_index]
244
+ # ERA5Dataset's final input index is T-2; its paired target is frame T-1.
245
+ frame = outvar if frame_index == self.frames_per_year - 1 else invar
246
+ frame = _regrid_periodic(torch.as_tensor(frame, dtype=torch.float32), self.model_size)
247
+ if self.normalize:
248
+ frame = _normalize(frame, self.minimum, self.maximum)
249
+ return frame
250
+
251
+ def __getitem__(self, index: int) -> dict[str, torch.Tensor | int]:
252
+ start = self.starts[index]
253
+ history_per_year = []
254
+ sequence_per_year = []
255
+ for year_index in range(len(self.years)):
256
+ history_per_year.append(
257
+ torch.stack(
258
+ [
259
+ self._frame(year_index, start - 2),
260
+ self._frame(year_index, start - 1),
261
+ self._frame(year_index, start),
262
+ ]
263
+ )
264
+ )
265
+ stop = min(start + self.sequence_length, self.frames_per_year)
266
+ sequence_per_year.append(
267
+ torch.stack(
268
+ [self._frame(year_index, step) for step in range(start, stop)]
269
+ )
270
+ )
271
+ stop = min(start + self.sequence_length, self.frames_per_year)
272
+ return {
273
+ "history": torch.stack(history_per_year, dim=0),
274
+ "observations": torch.stack(sequence_per_year, dim=1),
275
+ "time_steps": torch.arange(start, stop, dtype=torch.float32),
276
+ "sequence_index": index,
277
+ }
278
+
279
+
280
+ def load_constants(
281
+ static_file: str | Path,
282
+ expected_size: tuple[int, int] = (32, 64),
283
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
284
+ """Load [orography, lsm], latitude and longitude from constants.h5."""
285
+
286
+ with h5py.File(static_file, "r") as handle:
287
+ constants = torch.stack(
288
+ [
289
+ torch.as_tensor(handle["orography"][:], dtype=torch.float32),
290
+ torch.as_tensor(handle["lsm"][:], dtype=torch.float32),
291
+ ]
292
+ ).unsqueeze(0)
293
+ lat2d = torch.as_tensor(handle["lat2d"][:], dtype=torch.float32)
294
+ lon2d = torch.as_tensor(handle["lon2d"][:], dtype=torch.float32)
295
+ if tuple(constants.shape[-2:]) != expected_size:
296
+ raise ValueError(f"Static constants have shape {tuple(constants.shape[-2:])}")
297
+ return constants, lat2d, lon2d
298
+
299
+
300
+ def make_dataloader(
301
+ dataset: Dataset,
302
+ batch_size: int,
303
+ shuffle: bool,
304
+ num_workers: int = 0,
305
+ pin_memory: bool = False,
306
+ ) -> DataLoader:
307
+ return DataLoader(
308
+ dataset,
309
+ batch_size=batch_size,
310
+ shuffle=shuffle,
311
+ num_workers=num_workers,
312
+ pin_memory=pin_memory,
313
+ drop_last=False,
314
+ )
scripts/fake_data.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate small, deterministic ERA5-shaped HDF5 files for workflow checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ import h5py
10
+ import numpy as np
11
+ import yaml
12
+
13
+
14
+ VARIABLES = ("z", "t", "t2m", "u10", "v10")
15
+ ERA5_HEIGHT = 721
16
+ ERA5_WIDTH = 1440
17
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
18
+
19
+
20
+ def _parse_years(value: str | Iterable[int]) -> list[int]:
21
+ if isinstance(value, str):
22
+ return [int(item.strip()) for item in value.split(",") if item.strip()]
23
+ return [int(item) for item in value]
24
+
25
+
26
+ def _synthetic_frame(
27
+ step: int,
28
+ year: int,
29
+ lat: np.ndarray,
30
+ lon: np.ndarray,
31
+ ) -> np.ndarray:
32
+ """Create smooth fields with distinct scales for the five official channels."""
33
+
34
+ lat_rad = np.deg2rad(lat)[:, None]
35
+ lon_rad = np.deg2rad(lon)[None, :]
36
+ phase = 2.0 * np.pi * (step + (year % 100)) / 1460.0
37
+ spatial = np.sin(lat_rad) + 0.35 * np.cos(lon_rad) + 0.15 * np.sin(
38
+ 2.0 * lon_rad + phase
39
+ )
40
+ seasonal = np.cos(lat_rad) * np.sin(phase)
41
+
42
+ channels = np.stack(
43
+ [
44
+ 5000.0 + 300.0 * spatial + 20.0 * seasonal,
45
+ 260.0 + 12.0 * spatial + 2.0 * seasonal,
46
+ 280.0 + 18.0 * spatial + 3.0 * seasonal,
47
+ 4.0 * np.cos(lon_rad + phase) + 0.5 * spatial,
48
+ 3.0 * np.sin(lon_rad - phase) - 0.5 * spatial,
49
+ ],
50
+ axis=0,
51
+ )
52
+ return channels.astype(np.float32, copy=False)
53
+
54
+
55
+ def _write_static(static_dir: Path, height: int, width: int) -> None:
56
+ static_dir.mkdir(parents=True, exist_ok=True)
57
+ lat = np.linspace(
58
+ 90.0 - 90.0 / height,
59
+ -90.0 + 90.0 / height,
60
+ height,
61
+ dtype=np.float32,
62
+ )
63
+ lon = np.linspace(0.0, 360.0, width, endpoint=False, dtype=np.float32)
64
+ lat2d, lon2d = np.meshgrid(lat, lon, indexing="ij")
65
+ orography = (1200.0 * np.maximum(np.cos(np.deg2rad(lat2d)), 0.0)).astype(
66
+ np.float32
67
+ )
68
+ lsm = (np.cos(np.deg2rad(lat2d)) > 0.25).astype(np.float32)
69
+
70
+ with h5py.File(static_dir / "constants.h5", "w") as handle:
71
+ handle.create_dataset("orography", data=orography)
72
+ handle.create_dataset("lsm", data=lsm)
73
+ handle.create_dataset("lat2d", data=lat2d)
74
+ handle.create_dataset("lon2d", data=lon2d)
75
+ handle.attrs["variables"] = np.asarray(
76
+ ["orography", "lsm"], dtype=h5py.string_dtype()
77
+ )
78
+
79
+
80
+ def generate_data(
81
+ output_dir: str | Path,
82
+ years: Iterable[int],
83
+ timesteps: int,
84
+ height: int = ERA5_HEIGHT,
85
+ width: int = ERA5_WIDTH,
86
+ seed: int = 42,
87
+ overwrite: bool = False,
88
+ write_static: bool = True,
89
+ ) -> dict[str, list[float]]:
90
+ """Generate annual files and return per-channel global statistics."""
91
+
92
+ if timesteps < 4:
93
+ raise ValueError("timesteps must be at least 4 for a three-frame history")
94
+ if (height, width) != (ERA5_HEIGHT, ERA5_WIDTH):
95
+ raise ValueError(
96
+ "ClimODE virtual ERA5 data must use the raw shape "
97
+ f"({ERA5_HEIGHT}, {ERA5_WIDTH})"
98
+ )
99
+
100
+ root = Path(output_dir)
101
+ data_dir = root / "data"
102
+ static_dir = root / "static"
103
+ data_dir.mkdir(parents=True, exist_ok=True)
104
+ years = _parse_years(years)
105
+ lat = np.linspace(90.0, -90.0, height, dtype=np.float32)
106
+ lon = np.linspace(0.0, 360.0, width, endpoint=False, dtype=np.float32)
107
+ rng = np.random.default_rng(seed)
108
+ minimum = np.full(len(VARIABLES), np.inf, dtype=np.float64)
109
+ maximum = np.full(len(VARIABLES), -np.inf, dtype=np.float64)
110
+ total = np.zeros(len(VARIABLES), dtype=np.float64)
111
+ total_sq = np.zeros(len(VARIABLES), dtype=np.float64)
112
+ total_count = 0
113
+
114
+ for year in years:
115
+ path = data_dir / f"{year}.h5"
116
+ if path.exists() and not overwrite:
117
+ raise FileExistsError(f"Refusing to overwrite existing file: {path}")
118
+ with h5py.File(path, "w") as handle:
119
+ fields = handle.create_dataset(
120
+ "fields",
121
+ shape=(timesteps, len(VARIABLES), height, width),
122
+ dtype=np.float32,
123
+ chunks=(1, len(VARIABLES), height, width),
124
+ )
125
+ fields.attrs["variables"] = np.asarray(
126
+ VARIABLES, dtype=h5py.string_dtype()
127
+ )
128
+ fields.attrs["time_step"] = 6
129
+ for step in range(timesteps):
130
+ frame = _synthetic_frame(step, year, lat, lon)
131
+ # A tiny deterministic per-frame perturbation keeps years distinct
132
+ # without materializing another 20 MB random tensor per frame.
133
+ frame += np.float32(rng.normal(0.0, 1.0e-3))
134
+ fields[step] = frame
135
+ flat = frame.reshape(len(VARIABLES), -1).astype(np.float64)
136
+ minimum = np.minimum(minimum, flat.min(axis=1))
137
+ maximum = np.maximum(maximum, flat.max(axis=1))
138
+ total += flat.sum(axis=1)
139
+ total_sq += np.square(flat).sum(axis=1)
140
+ total_count += flat.shape[1]
141
+
142
+ # Placeholders are replaced with statistics over every requested year.
143
+ handle.create_dataset("global_means", shape=(1, len(VARIABLES), 1, 1), dtype=np.float32)
144
+ handle.create_dataset("global_stds", shape=(1, len(VARIABLES), 1, 1), dtype=np.float32)
145
+
146
+ means = (total / total_count).astype(np.float32)
147
+ variances = np.maximum(
148
+ total_sq / total_count - means.astype(np.float64) ** 2, 1.0e-12
149
+ )
150
+ stds = np.sqrt(variances).astype(np.float32)
151
+ for year in years:
152
+ with h5py.File(data_dir / f"{year}.h5", "r+") as handle:
153
+ handle["global_means"][:] = means.reshape(1, -1, 1, 1)
154
+ handle["global_stds"][:] = stds.reshape(1, -1, 1, 1)
155
+
156
+ static_height, static_width = 32, 64
157
+ if write_static:
158
+ _write_static(static_dir, static_height, static_width)
159
+ np.save(static_dir / "min_values.npy", minimum.astype(np.float32))
160
+ np.save(static_dir / "max_values.npy", maximum.astype(np.float32))
161
+ return {"min": minimum.tolist(), "max": maximum.tolist()}
162
+
163
+
164
+ def _load_config(path: Path) -> dict:
165
+ with path.open("r", encoding="utf-8") as handle:
166
+ return yaml.safe_load(handle)
167
+
168
+
169
+ def _resolve(path: str | Path) -> Path:
170
+ value = Path(path)
171
+ return value if value.is_absolute() else PROJECT_ROOT / value
172
+
173
+
174
+ def main() -> None:
175
+ parser = argparse.ArgumentParser(description=__doc__)
176
+ parser.add_argument(
177
+ "--config", type=Path, default=PROJECT_ROOT / "conf/config.yaml"
178
+ )
179
+ parser.add_argument("--output-dir", type=Path, default=None)
180
+ parser.add_argument("--years", type=str, default=None, help="Comma-separated years")
181
+ parser.add_argument("--timesteps", type=int, default=None)
182
+ parser.add_argument("--height", type=int, default=None)
183
+ parser.add_argument("--width", type=int, default=None)
184
+ parser.add_argument("--seed", type=int, default=None)
185
+ parser.add_argument("--overwrite", action="store_true")
186
+ args = parser.parse_args()
187
+ config_path = _resolve(args.config)
188
+ config = _load_config(config_path) if config_path.exists() else {}
189
+ fake = config.get("fake_data", {})
190
+ output_dir = _resolve(
191
+ args.output_dir or config.get("data", {}).get("data_dir", "./data")
192
+ )
193
+ years = _parse_years(args.years) if args.years else fake.get("years", [2006, 2016, 2017])
194
+ stats = generate_data(
195
+ output_dir=output_dir,
196
+ years=years,
197
+ timesteps=(
198
+ args.timesteps
199
+ if args.timesteps is not None
200
+ else fake.get("timesteps", 8)
201
+ ),
202
+ height=(
203
+ args.height
204
+ if args.height is not None
205
+ else fake.get("height", ERA5_HEIGHT)
206
+ ),
207
+ width=(
208
+ args.width
209
+ if args.width is not None
210
+ else fake.get("width", ERA5_WIDTH)
211
+ ),
212
+ seed=args.seed if args.seed is not None else fake.get("seed", 42),
213
+ overwrite=args.overwrite,
214
+ )
215
+ print(f"Generated years={years} under {Path(output_dir).resolve()}")
216
+ print(f"min={stats['min']}")
217
+ print(f"max={stats['max']}")
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main()
scripts/inference.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run ClimODE global forecasts and save machine-readable outputs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import torch
12
+ import yaml
13
+ from torch.utils.data import DataLoader
14
+
15
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
16
+ if str(PROJECT_ROOT) not in sys.path:
17
+ sys.path.insert(0, str(PROJECT_ROOT))
18
+
19
+ from model.climode import load_checkpoint
20
+ from scripts.data_loader import ClimODESeriesDataset, load_constants
21
+ from scripts.metrics import evaluate, save_metrics
22
+ from scripts.velocity import fit_velocity_cache, load_velocity_cache
23
+
24
+
25
+ def _load_config(path: Path) -> dict:
26
+ with path.open("r", encoding="utf-8") as handle:
27
+ return yaml.safe_load(handle)
28
+
29
+
30
+ def _parse_years(value: str | None, fallback: list[int]) -> list[int]:
31
+ if value is None:
32
+ return list(fallback)
33
+ years = [int(item.strip()) for item in value.split(",") if item.strip()]
34
+ if not years:
35
+ raise ValueError("year override must contain at least one integer")
36
+ return years
37
+
38
+
39
+ def _device(value: str | None) -> torch.device:
40
+ if value:
41
+ return torch.device(value)
42
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
43
+
44
+
45
+ def _resolve(path: str | Path) -> Path:
46
+ value = Path(path)
47
+ return value if value.is_absolute() else PROJECT_ROOT / value
48
+
49
+
50
+ def main() -> None:
51
+ parser = argparse.ArgumentParser(description=__doc__)
52
+ parser.add_argument("--config", type=Path, default=PROJECT_ROOT / "conf/config.yaml")
53
+ parser.add_argument("--checkpoint", type=Path, default=None)
54
+ parser.add_argument("--device", type=str, default=None)
55
+ parser.add_argument("--test-years", type=str, default=None)
56
+ parser.add_argument("--sequence-length", type=int, default=None)
57
+ parser.add_argument("--max-samples", type=int, default=None)
58
+ parser.add_argument("--velocity-epochs", type=int, default=None)
59
+ parser.add_argument("--velocity-cache", type=Path, default=None)
60
+ parser.add_argument("--data-dir", type=Path, default=None, help="Override data.data_dir")
61
+ parser.add_argument("--stats-dir", type=Path, default=None, help="Override data.stats_dir")
62
+ parser.add_argument("--static-file", type=Path, default=None, help="Override data.static_file")
63
+ parser.add_argument("--output-dir", type=Path, default=None)
64
+ args = parser.parse_args()
65
+ args.config = _resolve(args.config)
66
+ args.checkpoint = _resolve(args.checkpoint) if args.checkpoint is not None else None
67
+ args.velocity_cache = (
68
+ _resolve(args.velocity_cache) if args.velocity_cache is not None else None
69
+ )
70
+ args.data_dir = _resolve(args.data_dir) if args.data_dir is not None else None
71
+ args.stats_dir = _resolve(args.stats_dir) if args.stats_dir is not None else None
72
+ args.static_file = _resolve(args.static_file) if args.static_file is not None else None
73
+ args.output_dir = _resolve(args.output_dir) if args.output_dir is not None else None
74
+ config = _load_config(args.config)
75
+ data_cfg, model_cfg, vel_cfg = config["data"], config["model"], config["velocity"]
76
+ root = _resolve(args.data_dir or data_cfg["data_dir"])
77
+ stats_dir = _resolve(args.stats_dir or data_cfg.get("stats_dir", root / "static"))
78
+ test_years = _parse_years(args.test_years, data_cfg["test_years"])
79
+ sequence_length = args.sequence_length or data_cfg.get("sequence_length", 8)
80
+ dataset = ClimODESeriesDataset(
81
+ root,
82
+ test_years,
83
+ stats_dir=stats_dir,
84
+ model_size=(data_cfg["model_height"], data_cfg["model_width"]),
85
+ sequence_length=sequence_length,
86
+ normalize=data_cfg.get("normalize", True),
87
+ )
88
+ loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0)
89
+ static_file = _resolve(args.static_file or data_cfg["static_file"])
90
+ constants, lat, lon = load_constants(
91
+ static_file, (data_cfg["model_height"], data_cfg["model_width"])
92
+ )
93
+ device = _device(args.device)
94
+ constants = constants.to(device)
95
+ lat_device, lon_device = lat.unsqueeze(0).to(device), lon.unsqueeze(0).to(device)
96
+
97
+ velocity_root = _resolve(vel_cfg["cache_dir"])
98
+ velocity_path = args.velocity_cache or (velocity_root / "test.pt")
99
+ if velocity_path.is_file():
100
+ velocity = load_velocity_cache(velocity_path, len(dataset))
101
+ else:
102
+ velocity = fit_velocity_cache(
103
+ dataset,
104
+ constants,
105
+ lat,
106
+ lon,
107
+ velocity_path,
108
+ epochs=args.velocity_epochs if args.velocity_epochs is not None else vel_cfg["epochs"],
109
+ learning_rate=vel_cfg["learning_rate"],
110
+ smoothing_alpha=vel_cfg["smoothing_alpha"],
111
+ kernel_sigma=vel_cfg["kernel_sigma"],
112
+ )
113
+
114
+ checkpoint_path = args.checkpoint
115
+ if checkpoint_path is None:
116
+ checkpoint_path = _resolve(model_cfg["default_checkpoint"])
117
+ if not checkpoint_path.is_file():
118
+ pretrained = _resolve(model_cfg["pretrained_checkpoint"])
119
+ if pretrained.is_file():
120
+ checkpoint_path = pretrained
121
+ if checkpoint_path is None or not checkpoint_path.is_file():
122
+ raise FileNotFoundError(
123
+ "No checkpoint found; pass --checkpoint or provide model.default_checkpoint"
124
+ )
125
+ model = load_checkpoint(checkpoint_path, map_location="cpu").to(device).eval()
126
+ predictions, uncertainties, targets = [], [], []
127
+ with torch.no_grad():
128
+ for sample_index, batch in enumerate(loader):
129
+ if args.max_samples is not None and sample_index >= args.max_samples:
130
+ break
131
+ observations = batch["observations"].squeeze(0).to(device)
132
+ time_steps = batch["time_steps"].squeeze(0).to(device)
133
+ initial = observations[0].unsqueeze(1)
134
+ model.update_param([velocity[sample_index].to(device), constants, lat_device, lon_device])
135
+ mean, std, _ = model(
136
+ time_steps,
137
+ initial,
138
+ atol=model_cfg["atol"],
139
+ rtol=model_cfg["rtol"],
140
+ )
141
+ # Index 0 is the analysis state used to initialize the ODE. Official
142
+ # evaluation starts at index 1, corresponding to a six-hour lead.
143
+ if mean.shape[0] > 1:
144
+ predictions.append(mean[1:].detach().cpu().numpy())
145
+ uncertainties.append(std[1:].detach().cpu().numpy())
146
+ targets.append(observations[1:].detach().cpu().numpy())
147
+ if not predictions:
148
+ raise RuntimeError("No test samples were processed")
149
+
150
+ valid_lengths = np.asarray([item.shape[0] for item in predictions], dtype=np.int64)
151
+ max_lead = int(valid_lengths.max())
152
+
153
+ def _pad(items: list[np.ndarray]) -> np.ndarray:
154
+ shape = (len(items), max_lead) + tuple(items[0].shape[1:])
155
+ padded = np.full(shape, np.nan, dtype=np.float32)
156
+ for index, item in enumerate(items):
157
+ padded[index, : item.shape[0]] = item
158
+ return padded
159
+
160
+ pred_array = _pad(predictions)
161
+ std_array = _pad(uncertainties)
162
+ target_array = _pad(targets)
163
+ scale = (dataset.maximum - dataset.minimum).numpy().reshape(1, 1, 1, 5, 1, 1)
164
+ offset = dataset.minimum.numpy().reshape(1, 1, 1, 5, 1, 1)
165
+ pred_physical = pred_array * scale + offset
166
+ target_physical = target_array * scale + offset
167
+ std_physical = std_array * scale
168
+ output_dir = args.output_dir or _resolve(data_cfg["output_dir"])
169
+ output_dir.mkdir(parents=True, exist_ok=True)
170
+ np.save(output_dir / "predictions.npy", pred_array)
171
+ np.save(output_dir / "std.npy", std_array)
172
+ np.save(output_dir / "targets.npy", target_array)
173
+ np.save(output_dir / "valid_lengths.npy", valid_lengths)
174
+ metrics = evaluate(
175
+ pred_physical,
176
+ target_physical,
177
+ lat.numpy(),
178
+ std_physical,
179
+ crps_predictions=pred_array,
180
+ crps_targets=target_array,
181
+ crps_std=std_array,
182
+ valid_lengths=valid_lengths,
183
+ )
184
+ metrics["checkpoint"] = str(checkpoint_path)
185
+ metrics["outputs_normalized"] = True
186
+ metrics_path = _resolve(config["output"]["metrics_file"])
187
+ if args.output_dir is not None:
188
+ metrics_path = output_dir.parent / "metrics.json"
189
+ save_metrics(metrics, metrics_path)
190
+ manifest = {
191
+ "checkpoint": str(checkpoint_path),
192
+ "samples": int(pred_array.shape[0]),
193
+ "shape": list(pred_array.shape),
194
+ "valid_lengths": valid_lengths.tolist(),
195
+ "variables": ["z", "t", "t2m", "u10", "v10"],
196
+ "output_dir": str(output_dir),
197
+ "metrics": str(metrics_path),
198
+ }
199
+ (output_dir / "inference_manifest.json").write_text(
200
+ json.dumps(manifest, indent=2), encoding="utf-8"
201
+ )
202
+ print(json.dumps(manifest))
203
+
204
+
205
+ if __name__ == "__main__":
206
+ main()
scripts/metrics.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ClimODE evaluation metrics and output serialization helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ from typing import Sequence
9
+
10
+ import numpy as np
11
+
12
+ try:
13
+ from scipy.special import erf as _erf
14
+ except ImportError: # pragma: no cover - only used in minimal environments
15
+ _erf = np.vectorize(math.erf)
16
+
17
+
18
+ VARIABLES = ("z", "t", "t2m", "u10", "v10")
19
+
20
+
21
+ def latitude_weights(lat2d: np.ndarray) -> np.ndarray:
22
+ lat = np.asarray(lat2d, dtype=np.float64)
23
+ if lat.ndim == 2:
24
+ lat = lat[:, 0]
25
+ weights = np.cos(np.deg2rad(lat))
26
+ weights = weights / np.mean(weights)
27
+ return weights[:, None]
28
+
29
+
30
+ def _check_arrays(
31
+ predictions: np.ndarray,
32
+ targets: np.ndarray,
33
+ std: np.ndarray | None,
34
+ valid_lengths: Sequence[int] | None = None,
35
+ ) -> None:
36
+ if predictions.shape != targets.shape:
37
+ raise ValueError(f"predictions {predictions.shape} != targets {targets.shape}")
38
+ if predictions.ndim != 6:
39
+ raise ValueError("Expected [samples, lead, years, channels, height, width]")
40
+ if predictions.shape[3] != len(VARIABLES):
41
+ raise ValueError(f"Expected {len(VARIABLES)} channels, got {predictions.shape[3]}")
42
+ if std is not None and std.shape != predictions.shape:
43
+ raise ValueError(f"std {std.shape} != predictions {predictions.shape}")
44
+ if valid_lengths is not None:
45
+ lengths = np.asarray(valid_lengths, dtype=np.int64)
46
+ if lengths.shape != (predictions.shape[0],):
47
+ raise ValueError(f"valid_lengths {lengths.shape} != ({predictions.shape[0]},)")
48
+ if np.any(lengths < 1) or np.any(lengths > predictions.shape[1]):
49
+ raise ValueError("valid_lengths must be within the lead dimension")
50
+
51
+
52
+ def _lead_mask(
53
+ predictions: np.ndarray,
54
+ valid_lengths: Sequence[int] | None,
55
+ ) -> np.ndarray:
56
+ lengths = (
57
+ np.full(predictions.shape[0], predictions.shape[1], dtype=np.int64)
58
+ if valid_lengths is None
59
+ else np.asarray(valid_lengths, dtype=np.int64)
60
+ )
61
+ return (np.arange(predictions.shape[1])[None, :] < lengths[:, None]).reshape(
62
+ predictions.shape[0], predictions.shape[1], 1, 1, 1, 1
63
+ )
64
+
65
+
66
+ def _weighted_mean(values: np.ndarray, weights: np.ndarray) -> np.ndarray:
67
+ # values: [N,L,Y,K,H,W], weights: [H,1]
68
+ weighted = values * weights[None, None, None, None, :, :]
69
+ return weighted.mean(axis=(-1, -2))
70
+
71
+
72
+ def latitude_weighted_rmse(
73
+ predictions: np.ndarray,
74
+ targets: np.ndarray,
75
+ lat2d: np.ndarray,
76
+ valid_lengths: Sequence[int] | None = None,
77
+ ) -> np.ndarray:
78
+ weights = latitude_weights(lat2d)
79
+ error = np.square(np.nan_to_num(predictions - targets, nan=0.0))
80
+ per_field = np.sqrt(_weighted_mean(error, weights))
81
+ valid = _lead_mask(predictions, valid_lengths)[..., 0, 0, 0, 0]
82
+ valid_fields = np.broadcast_to(valid[:, :, None, None], per_field.shape)
83
+ return (per_field * valid_fields).sum(axis=(0, 2)) / np.maximum(
84
+ valid_fields.sum(axis=(0, 2)), 1.0
85
+ )
86
+
87
+
88
+ def anomaly_correlation(
89
+ predictions: np.ndarray,
90
+ targets: np.ndarray,
91
+ lat2d: np.ndarray,
92
+ valid_lengths: Sequence[int] | None = None,
93
+ ) -> np.ndarray:
94
+ weights = latitude_weights(lat2d)
95
+ valid = _lead_mask(predictions, valid_lengths)
96
+ valid_broadcast = np.broadcast_to(valid, targets.shape)
97
+ target_clean = np.nan_to_num(targets, nan=0.0)
98
+ valid_count = valid_broadcast.sum(axis=(0, 1))
99
+ # Official evaluation uses one test-set climatology for each year/channel/grid.
100
+ climatology = (target_clean * valid_broadcast).sum(axis=(0, 1)) / np.maximum(
101
+ valid_count, 1.0
102
+ )
103
+ pred_anomaly = np.nan_to_num(predictions, nan=0.0) - climatology[None, None]
104
+ target_anomaly = target_clean - climatology[None, None]
105
+ pred_anomaly -= pred_anomaly.mean(axis=(-1, -2), keepdims=True)
106
+ target_anomaly -= target_anomaly.mean(axis=(-1, -2), keepdims=True)
107
+ weighted_mask = weights[None, None, None, None] * valid
108
+ numerator = (pred_anomaly * target_anomaly * weighted_mask).sum(axis=(-1, -2))
109
+ pred_norm = np.sqrt((np.square(pred_anomaly) * weighted_mask).sum(axis=(-1, -2)))
110
+ target_norm = np.sqrt((np.square(target_anomaly) * weighted_mask).sum(axis=(-1, -2)))
111
+ per_field = numerator / np.maximum(pred_norm * target_norm, 1.0e-12)
112
+ valid_fields = np.broadcast_to(valid[..., 0, 0], per_field.shape)
113
+ return (per_field * valid_fields).sum(axis=(0, 2)) / np.maximum(
114
+ valid_fields.sum(axis=(0, 2)), 1.0
115
+ )
116
+
117
+
118
+ def _normal_crps(
119
+ observations: np.ndarray,
120
+ means: np.ndarray,
121
+ scales: np.ndarray,
122
+ ) -> np.ndarray:
123
+ """Closed-form CRPS for a Gaussian predictive distribution."""
124
+
125
+ scales = np.maximum(np.asarray(scales, dtype=np.float64), 1.0e-6)
126
+ z = (np.asarray(observations, dtype=np.float64) - means) / scales
127
+ phi = np.exp(-0.5 * np.square(z)) / math.sqrt(2.0 * math.pi)
128
+ cdf = 0.5 * (1.0 + _erf(z / math.sqrt(2.0)))
129
+ return scales * (z * (2.0 * cdf - 1.0) + 2.0 * phi - 1.0 / math.sqrt(math.pi))
130
+
131
+
132
+ def gaussian_crps(
133
+ predictions: np.ndarray,
134
+ targets: np.ndarray,
135
+ std: np.ndarray,
136
+ valid_lengths: Sequence[int] | None = None,
137
+ ) -> np.ndarray:
138
+ values = np.nan_to_num(_normal_crps(targets, predictions, std), nan=0.0)
139
+ mask = np.broadcast_to(_lead_mask(predictions, valid_lengths), values.shape)
140
+ return (values * mask).sum(axis=(0, 2, 4, 5)) / np.maximum(
141
+ mask.sum(axis=(0, 2, 4, 5)), 1.0
142
+ )
143
+
144
+
145
+ def evaluate(
146
+ predictions: np.ndarray,
147
+ targets: np.ndarray,
148
+ lat2d: np.ndarray,
149
+ std: np.ndarray | None = None,
150
+ crps_predictions: np.ndarray | None = None,
151
+ crps_targets: np.ndarray | None = None,
152
+ crps_std: np.ndarray | None = None,
153
+ valid_lengths: Sequence[int] | None = None,
154
+ ) -> dict:
155
+ _check_arrays(predictions, targets, std, valid_lengths)
156
+ result = {
157
+ "variables": list(VARIABLES),
158
+ "lead_times_hours": [6 * (index + 1) for index in range(predictions.shape[1])],
159
+ "rmse": latitude_weighted_rmse(predictions, targets, lat2d, valid_lengths).tolist(),
160
+ "acc": anomaly_correlation(predictions, targets, lat2d, valid_lengths).tolist(),
161
+ "rmse_space": "physical",
162
+ "acc_space": "physical",
163
+ }
164
+ if std is not None:
165
+ result["crps"] = gaussian_crps(
166
+ crps_predictions if crps_predictions is not None else predictions,
167
+ crps_targets if crps_targets is not None else targets,
168
+ crps_std if crps_std is not None else std,
169
+ valid_lengths,
170
+ ).tolist()
171
+ result["crps_space"] = "normalized" if crps_predictions is not None else "physical"
172
+ result["crps_implementation"] = "closed_form_gaussian"
173
+ return result
174
+
175
+
176
+ def save_metrics(metrics: dict, path: str | Path) -> None:
177
+ output = Path(path)
178
+ output.parent.mkdir(parents=True, exist_ok=True)
179
+ output.write_text(json.dumps(metrics, indent=2), encoding="utf-8")
scripts/result.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute metrics and render ClimODE forecast maps from saved outputs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import yaml
12
+
13
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
14
+ if str(PROJECT_ROOT) not in sys.path:
15
+ sys.path.insert(0, str(PROJECT_ROOT))
16
+
17
+ from scripts.metrics import evaluate, save_metrics
18
+
19
+
20
+ def _resolve(path: str | Path) -> Path:
21
+ value = Path(path)
22
+ return value if value.is_absolute() else PROJECT_ROOT / value
23
+
24
+
25
+ def main() -> None:
26
+ parser = argparse.ArgumentParser(description=__doc__)
27
+ parser.add_argument("--config", type=Path, default=PROJECT_ROOT / "conf/config.yaml")
28
+ parser.add_argument("--predictions", type=Path, default=None)
29
+ parser.add_argument("--targets", type=Path, default=None)
30
+ parser.add_argument("--std", type=Path, default=None)
31
+ parser.add_argument("--output-dir", type=Path, default=None)
32
+ parser.add_argument("--stats-dir", type=Path, default=None)
33
+ parser.add_argument("--static-file", type=Path, default=None)
34
+ parser.add_argument("--sample", type=int, default=0)
35
+ parser.add_argument("--lead", type=int, default=0)
36
+ args = parser.parse_args()
37
+ with args.config.open("r", encoding="utf-8") as handle:
38
+ config = yaml.safe_load(handle)
39
+ output_dir = args.output_dir or _resolve(config["data"]["output_dir"])
40
+ predictions = np.load(args.predictions or output_dir / "predictions.npy")
41
+ targets = np.load(args.targets or output_dir / "targets.npy")
42
+ std_path = args.std or output_dir / "std.npy"
43
+ std = np.load(std_path) if std_path.is_file() else None
44
+ lengths_path = output_dir / "valid_lengths.npy"
45
+ valid_lengths = np.load(lengths_path) if lengths_path.is_file() else None
46
+ static_file = _resolve(args.static_file or config["data"]["static_file"])
47
+ import h5py
48
+
49
+ with h5py.File(static_file, "r") as handle:
50
+ lat2d = handle["lat2d"][:]
51
+ stats_dir = _resolve(
52
+ args.stats_dir
53
+ or config["data"].get("stats_dir", Path(config["data"]["data_dir"]) / "static")
54
+ )
55
+ minimum = np.load(stats_dir / "min_values.npy").reshape(1, 1, 1, 5, 1, 1)
56
+ maximum = np.load(stats_dir / "max_values.npy").reshape(1, 1, 1, 5, 1, 1)
57
+ scale = maximum - minimum
58
+ metrics = evaluate(
59
+ predictions * scale + minimum,
60
+ targets * scale + minimum,
61
+ lat2d,
62
+ std * scale if std is not None else None,
63
+ crps_predictions=predictions if std is not None else None,
64
+ crps_targets=targets if std is not None else None,
65
+ crps_std=std,
66
+ valid_lengths=valid_lengths,
67
+ )
68
+ metrics_path = output_dir.parent / "metrics.json"
69
+ save_metrics(metrics, metrics_path)
70
+
71
+ figure_dir = output_dir / "figures"
72
+ figure_dir.mkdir(parents=True, exist_ok=True)
73
+ try:
74
+ import matplotlib
75
+
76
+ matplotlib.use("Agg")
77
+ import matplotlib.pyplot as plt
78
+ except ImportError as exc:
79
+ raise RuntimeError("Visualization requires matplotlib in the active environment") from exc
80
+
81
+ if not 0 <= args.sample < predictions.shape[0]:
82
+ raise IndexError(f"sample must be in [0,{predictions.shape[0] - 1}]")
83
+ if not 0 <= args.lead < predictions.shape[1]:
84
+ raise IndexError(f"lead must be in [0,{predictions.shape[1] - 1}]")
85
+ if valid_lengths is not None and args.lead >= int(valid_lengths[args.sample]):
86
+ raise IndexError(
87
+ f"lead {args.lead} is padding for sample {args.sample}; "
88
+ f"valid length is {int(valid_lengths[args.sample])}"
89
+ )
90
+ names = ["z", "t", "t2m", "u10", "v10"]
91
+ for channel, name in enumerate(names):
92
+ prediction = predictions[args.sample, args.lead, 0, channel]
93
+ target = targets[args.sample, args.lead, 0, channel]
94
+ difference = prediction - target
95
+ figure, axes = plt.subplots(1, 3, figsize=(12, 3.4), constrained_layout=True)
96
+ for axis, image, title in zip(
97
+ axes,
98
+ (prediction, target, difference),
99
+ ("prediction", "target", "difference"),
100
+ ):
101
+ cmap = "RdBu_r" if title == "difference" else "viridis"
102
+ plot = axis.imshow(image, cmap=cmap, origin="upper", aspect="auto")
103
+ axis.set_title(title)
104
+ axis.set_xlabel("longitude index")
105
+ axis.set_ylabel("latitude index")
106
+ figure.colorbar(plot, ax=axis, shrink=0.8)
107
+ figure.suptitle(f"ClimODE {name}, lead={(args.lead + 1) * 6} h")
108
+ figure.savefig(figure_dir / f"{name}_lead_{(args.lead + 1) * 6:03d}h.png", dpi=150)
109
+ plt.close(figure)
110
+ print(json.dumps({"metrics": str(metrics_path), "figures": str(figure_dir)}))
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
scripts/train.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train or fine-tune ClimODE with OneScience ERA5 data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import random
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torch.distributed as dist
15
+ import torch.nn as nn
16
+ import yaml
17
+ from torch.nn.parallel import DistributedDataParallel
18
+ from torch.utils.data import DataLoader
19
+ from torch.utils.data.distributed import DistributedSampler
20
+
21
+ # Allow ``python scripts/train.py`` to resolve project-local packages.
22
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
23
+ if str(PROJECT_ROOT) not in sys.path:
24
+ sys.path.insert(0, str(PROJECT_ROOT))
25
+
26
+ from model.climode import ClimODE, load_checkpoint
27
+ from scripts.data_loader import ClimODESeriesDataset, load_constants
28
+ from scripts.velocity import fit_velocity_cache, load_velocity_cache
29
+
30
+
31
+ def set_seed(seed: int) -> None:
32
+ random.seed(seed)
33
+ np.random.seed(seed)
34
+ torch.manual_seed(seed)
35
+ if torch.cuda.is_available():
36
+ torch.cuda.manual_seed_all(seed)
37
+ torch.backends.cudnn.deterministic = True
38
+ torch.backends.cudnn.benchmark = False
39
+
40
+
41
+ def _device(value: str | None) -> torch.device:
42
+ if value:
43
+ return torch.device(value)
44
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
45
+
46
+
47
+ def _init_distributed(backend: str) -> tuple[bool, int, int]:
48
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
49
+ if world_size == 1:
50
+ return False, 0, 1
51
+ if not dist.is_initialized():
52
+ dist.init_process_group(backend=backend)
53
+ return True, dist.get_rank(), world_size
54
+
55
+
56
+ def _nll(mean: torch.Tensor, std: torch.Tensor, truth: torch.Tensor, var_coeff: float) -> torch.Tensor:
57
+ distribution = torch.distributions.Normal(mean, 1.0e-3 + std)
58
+ return (-distribution.log_prob(truth)).mean() + var_coeff * (std.square()).sum()
59
+
60
+
61
+ def _load_yaml(path: Path) -> dict:
62
+ with path.open("r", encoding="utf-8") as handle:
63
+ return yaml.safe_load(handle)
64
+
65
+
66
+ def _resolve(path: str | Path) -> Path:
67
+ value = Path(path)
68
+ return value if value.is_absolute() else PROJECT_ROOT / value
69
+
70
+
71
+ def _parse_years(value: str | None, fallback: list[int]) -> list[int]:
72
+ if value is None:
73
+ return list(fallback)
74
+ years = [int(item.strip()) for item in value.split(",") if item.strip()]
75
+ if not years:
76
+ raise ValueError("year override must contain at least one integer")
77
+ return years
78
+
79
+
80
+ def _model_from_args(config: dict, args: argparse.Namespace, device: torch.device) -> nn.Module:
81
+ model_cfg = config["model"]
82
+ use_pretrained = bool(getattr(args, "use_pretrained", False))
83
+ pretrained_checkpoint = getattr(args, "pretrained_checkpoint", None)
84
+ if args.mode == "resume":
85
+ checkpoint = args.checkpoint or _resolve(model_cfg["default_checkpoint"])
86
+ model = load_checkpoint(checkpoint, map_location="cpu")
87
+ elif args.mode == "finetune" or use_pretrained:
88
+ checkpoint = args.checkpoint
89
+ if checkpoint is None and (use_pretrained or pretrained_checkpoint is not None):
90
+ checkpoint = pretrained_checkpoint or model_cfg.get("pretrained_checkpoint")
91
+ if checkpoint is None:
92
+ raise ValueError(
93
+ "finetune requires --checkpoint, or explicitly pass "
94
+ "--use-pretrained [--pretrained-checkpoint PATH]"
95
+ )
96
+ checkpoint = _resolve(checkpoint)
97
+ if not checkpoint.is_file():
98
+ raise FileNotFoundError(f"Checkpoint not found: {checkpoint}")
99
+ model = load_checkpoint(checkpoint, map_location="cpu")
100
+ else:
101
+ model = ClimODE(
102
+ num_channels=5,
103
+ const_channels=2,
104
+ out_types=5,
105
+ method=args.solver or model_cfg.get("solver", "euler"),
106
+ use_attention=model_cfg.get("use_attention", True),
107
+ use_uncertainty=model_cfg.get("use_uncertainty", True),
108
+ use_positional_encoder=model_cfg.get("use_positional_encoder", False),
109
+ )
110
+ return model.to(device)
111
+
112
+
113
+ def _run_epoch(
114
+ model,
115
+ loader,
116
+ velocity,
117
+ constants,
118
+ lat,
119
+ lon,
120
+ device,
121
+ optimizer,
122
+ var_coeff,
123
+ max_batches,
124
+ atol,
125
+ rtol,
126
+ ):
127
+ training = optimizer is not None
128
+ model.train(training)
129
+ total = 0.0
130
+ count = 0
131
+ for batch_index, batch in enumerate(loader):
132
+ if max_batches is not None and batch_index >= max_batches:
133
+ break
134
+ observations = batch["observations"].squeeze(0).to(device)
135
+ time_steps = batch["time_steps"].squeeze(0).to(device)
136
+ sequence_index = int(batch["sequence_index"].item())
137
+ past_velocity = velocity[sequence_index].to(device)
138
+ target = observations
139
+ initial = observations[0].unsqueeze(1)
140
+ model_core = model.module if isinstance(model, DistributedDataParallel) else model
141
+ model_core.update_param([past_velocity, constants, lat, lon])
142
+ if training:
143
+ optimizer.zero_grad(set_to_none=True)
144
+ with torch.set_grad_enabled(training):
145
+ mean, std, _ = model(time_steps, initial, atol=atol, rtol=rtol)
146
+ loss = _nll(mean, std, target, var_coeff)
147
+ loss = loss + 0.001 * sum(parameter.square().sum() for parameter in model.parameters())
148
+ if training:
149
+ loss.backward()
150
+ optimizer.step()
151
+ total += float(loss.detach())
152
+ count += 1
153
+ if dist.is_initialized():
154
+ totals = torch.tensor([total, float(count)], dtype=torch.float64, device=device)
155
+ dist.all_reduce(totals, op=dist.ReduceOp.SUM)
156
+ total, count = float(totals[0].item()), int(totals[1].item())
157
+ return total / max(count, 1), count
158
+
159
+
160
+ def _prepare_velocity(
161
+ dataset,
162
+ constants: torch.Tensor,
163
+ lat: torch.Tensor,
164
+ lon: torch.Tensor,
165
+ path: Path,
166
+ epochs: int,
167
+ learning_rate: float,
168
+ smoothing_alpha: float,
169
+ kernel_sigma: float,
170
+ distributed: bool,
171
+ rank: int,
172
+ ) -> torch.Tensor:
173
+ """Build a split cache once, then let every DDP rank read the same result."""
174
+
175
+ if path.is_file():
176
+ return load_velocity_cache(path, len(dataset))
177
+ if distributed:
178
+ if rank == 0:
179
+ fit_velocity_cache(
180
+ dataset,
181
+ constants,
182
+ lat,
183
+ lon,
184
+ path,
185
+ epochs=epochs,
186
+ learning_rate=learning_rate,
187
+ smoothing_alpha=smoothing_alpha,
188
+ kernel_sigma=kernel_sigma,
189
+ )
190
+ dist.barrier()
191
+ return load_velocity_cache(path, len(dataset))
192
+ return fit_velocity_cache(
193
+ dataset,
194
+ constants,
195
+ lat,
196
+ lon,
197
+ path,
198
+ epochs=epochs,
199
+ learning_rate=learning_rate,
200
+ smoothing_alpha=smoothing_alpha,
201
+ kernel_sigma=kernel_sigma,
202
+ )
203
+
204
+
205
+ def main() -> None:
206
+ parser = argparse.ArgumentParser(description=__doc__)
207
+ parser.add_argument(
208
+ "--config", type=Path, default=PROJECT_ROOT / "conf/config.yaml"
209
+ )
210
+ parser.add_argument("--mode", choices=["scratch", "finetune", "resume"], default=None)
211
+ parser.add_argument("--checkpoint", type=Path, default=None)
212
+ parser.add_argument(
213
+ "--use-pretrained",
214
+ action="store_true",
215
+ help="Explicitly initialize from the official pretrained checkpoint",
216
+ )
217
+ parser.add_argument(
218
+ "--pretrained-checkpoint",
219
+ type=Path,
220
+ default=None,
221
+ help="Override model.pretrained_checkpoint when --use-pretrained is set",
222
+ )
223
+ parser.add_argument("--solver", choices=["euler", "rk4", "dopri5", "dopri8", "midpoint"], default=None)
224
+ parser.add_argument("--epochs", type=int, default=None)
225
+ parser.add_argument("--sequence-length", type=int, default=None)
226
+ parser.add_argument("--velocity-epochs", type=int, default=None)
227
+ parser.add_argument("--velocity-cache", type=Path, default=None)
228
+ parser.add_argument("--data-dir", type=Path, default=None, help="Override data.data_dir")
229
+ parser.add_argument("--stats-dir", type=Path, default=None, help="Override data.stats_dir")
230
+ parser.add_argument("--static-file", type=Path, default=None, help="Override data.static_file")
231
+ parser.add_argument("--checkpoint-dir", type=Path, default=None)
232
+ parser.add_argument("--log-file", type=Path, default=None)
233
+ parser.add_argument("--device", type=str, default=None)
234
+ parser.add_argument("--max-batches", type=int, default=None)
235
+ parser.add_argument("--seed", type=int, default=None)
236
+ parser.add_argument("--train-years", type=str, default=None, help="Comma-separated year override")
237
+ parser.add_argument("--val-years", type=str, default=None, help="Comma-separated year override")
238
+ args = parser.parse_args()
239
+ args.config = _resolve(args.config)
240
+ args.checkpoint = _resolve(args.checkpoint) if args.checkpoint is not None else None
241
+ args.pretrained_checkpoint = (
242
+ _resolve(args.pretrained_checkpoint)
243
+ if args.pretrained_checkpoint is not None
244
+ else None
245
+ )
246
+ args.data_dir = _resolve(args.data_dir) if args.data_dir is not None else None
247
+ args.stats_dir = _resolve(args.stats_dir) if args.stats_dir is not None else None
248
+ args.static_file = _resolve(args.static_file) if args.static_file is not None else None
249
+ args.velocity_cache = (
250
+ _resolve(args.velocity_cache) if args.velocity_cache is not None else None
251
+ )
252
+ args.checkpoint_dir = (
253
+ _resolve(args.checkpoint_dir) if args.checkpoint_dir is not None else None
254
+ )
255
+ args.log_file = _resolve(args.log_file) if args.log_file is not None else None
256
+ config = _load_yaml(args.config)
257
+ model_cfg, data_cfg, vel_cfg, train_cfg = config["model"], config["data"], config["velocity"], config["training"]
258
+ args.mode = args.mode or train_cfg.get("mode", "scratch")
259
+ if args.mode == "resume" and args.use_pretrained:
260
+ raise ValueError("--use-pretrained cannot be combined with --mode resume")
261
+ if (
262
+ args.pretrained_checkpoint is not None
263
+ and args.mode not in {"finetune"}
264
+ and not args.use_pretrained
265
+ ):
266
+ raise ValueError(
267
+ "--pretrained-checkpoint requires --use-pretrained or "
268
+ "--mode finetune"
269
+ )
270
+ if args.mode == "scratch" and args.checkpoint is not None:
271
+ raise ValueError(
272
+ "--checkpoint is ignored in scratch mode; use --mode resume or "
273
+ "--mode finetune explicitly"
274
+ )
275
+ if args.use_pretrained and args.mode == "scratch":
276
+ args.mode = "finetune"
277
+ args.solver = args.solver or model_cfg.get("solver", "euler")
278
+ args.sequence_length = args.sequence_length or data_cfg.get("sequence_length", 8)
279
+ args.velocity_epochs = args.velocity_epochs if args.velocity_epochs is not None else vel_cfg.get("epochs", 200)
280
+ args.max_batches = args.max_batches if args.max_batches is not None else train_cfg.get("max_batches")
281
+ set_seed(args.seed if args.seed is not None else train_cfg.get("seed", 42))
282
+ distributed, rank, world_size = _init_distributed(train_cfg.get("ddp_backend", "nccl"))
283
+ device = _device(args.device)
284
+ if distributed and device.type == "cuda":
285
+ device = torch.device("cuda", int(os.environ.get("LOCAL_RANK", "0")))
286
+ if device.type == "cuda":
287
+ if device.index is None:
288
+ device = torch.device("cuda", 0)
289
+ torch.cuda.set_device(device)
290
+
291
+ root = _resolve(args.data_dir or data_cfg["data_dir"])
292
+ stats_dir = _resolve(args.stats_dir or data_cfg.get("stats_dir", root / "static"))
293
+ train_set = ClimODESeriesDataset(
294
+ root,
295
+ _parse_years(args.train_years, data_cfg["train_years"]),
296
+ stats_dir=stats_dir,
297
+ model_size=(data_cfg["model_height"], data_cfg["model_width"]),
298
+ sequence_length=args.sequence_length,
299
+ normalize=data_cfg.get("normalize", True),
300
+ )
301
+ val_set = ClimODESeriesDataset(
302
+ root,
303
+ _parse_years(args.val_years, data_cfg["val_years"]),
304
+ stats_dir=stats_dir,
305
+ model_size=(data_cfg["model_height"], data_cfg["model_width"]),
306
+ sequence_length=args.sequence_length,
307
+ normalize=data_cfg.get("normalize", True),
308
+ )
309
+ train_sampler = DistributedSampler(train_set, shuffle=True) if distributed else None
310
+ val_sampler = DistributedSampler(val_set, shuffle=False) if distributed else None
311
+ train_loader = DataLoader(train_set, batch_size=1, sampler=train_sampler, shuffle=train_sampler is None, num_workers=data_cfg["dataloader"]["num_workers"])
312
+ val_loader = DataLoader(val_set, batch_size=1, sampler=val_sampler, shuffle=False, num_workers=data_cfg["dataloader"]["num_workers"])
313
+ static_file = _resolve(args.static_file or data_cfg["static_file"])
314
+ constants, lat, lon = load_constants(static_file, (data_cfg["model_height"], data_cfg["model_width"]))
315
+ constants, lat, lon = constants.to(device), lat.unsqueeze(0).to(device), lon.unsqueeze(0).to(device)
316
+
317
+ # Relative paths follow the project working directory, matching the
318
+ # config/checkpoint conventions used by the reference earth projects.
319
+ velocity_root = _resolve(vel_cfg["cache_dir"])
320
+ velocity_path = args.velocity_cache or (velocity_root / "train.pt")
321
+ train_velocity = _prepare_velocity(
322
+ train_set,
323
+ constants,
324
+ lat.squeeze(0).cpu(),
325
+ lon.squeeze(0).cpu(),
326
+ velocity_path,
327
+ epochs=args.velocity_epochs,
328
+ learning_rate=vel_cfg["learning_rate"],
329
+ smoothing_alpha=vel_cfg["smoothing_alpha"],
330
+ kernel_sigma=vel_cfg["kernel_sigma"],
331
+ distributed=distributed,
332
+ rank=rank,
333
+ )
334
+ val_velocity_path = velocity_path.with_name("val.pt")
335
+ val_velocity = _prepare_velocity(
336
+ val_set,
337
+ constants,
338
+ lat.squeeze(0).cpu(),
339
+ lon.squeeze(0).cpu(),
340
+ val_velocity_path,
341
+ epochs=args.velocity_epochs,
342
+ learning_rate=vel_cfg["learning_rate"],
343
+ smoothing_alpha=vel_cfg["smoothing_alpha"],
344
+ kernel_sigma=vel_cfg["kernel_sigma"],
345
+ distributed=distributed,
346
+ rank=rank,
347
+ )
348
+
349
+ model = _model_from_args(config, args, device)
350
+ if distributed:
351
+ model = DistributedDataParallel(model, device_ids=[device.index] if device.type == "cuda" else None)
352
+ lr = train_cfg.get("finetune_learning_rate", 5.0e-5) if args.mode == "finetune" else model_cfg.get("learning_rate", 5.0e-4)
353
+ optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=model_cfg.get("weight_decay", 1.0e-5))
354
+ epochs = args.epochs or (train_cfg.get("finetune_epochs", 40) if args.mode == "finetune" else train_cfg.get("epochs", 300))
355
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, epochs)
356
+ start_epoch = 0
357
+ if args.mode == "resume":
358
+ resume_path = args.checkpoint or _resolve(model_cfg["default_checkpoint"])
359
+ try:
360
+ resume = torch.load(resume_path, map_location="cpu", weights_only=True)
361
+ except TypeError:
362
+ resume = torch.load(resume_path, map_location="cpu")
363
+ state = resume.get("model", resume.get("state_dict"))
364
+ (model.module if isinstance(model, DistributedDataParallel) else model).load_state_dict(state)
365
+ if "optimizer" in resume:
366
+ optimizer.load_state_dict(resume["optimizer"])
367
+ if "scheduler" in resume:
368
+ scheduler.load_state_dict(resume["scheduler"])
369
+ start_epoch = int(resume.get("epoch", -1)) + 1
370
+
371
+ checkpoint_dir = _resolve(args.checkpoint_dir or model_cfg["checkpoint_dir"])
372
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
373
+ log_path = _resolve(args.log_file or train_cfg.get("log_file", "./result/train.jsonl"))
374
+ log_path.parent.mkdir(parents=True, exist_ok=True)
375
+ best_val = float("inf")
376
+ for epoch in range(start_epoch, epochs):
377
+ if train_sampler is not None:
378
+ train_sampler.set_epoch(epoch)
379
+ var_coeff = 1.0e-3 if epoch == 0 else 2.0 * scheduler.get_last_lr()[0]
380
+ train_loss, train_count = _run_epoch(
381
+ model, train_loader, train_velocity, constants, lat, lon, device,
382
+ optimizer, var_coeff, args.max_batches, model_cfg["atol"], model_cfg["rtol"]
383
+ )
384
+ with torch.no_grad():
385
+ val_loss, val_count = _run_epoch(
386
+ model, val_loader, val_velocity, constants, lat, lon, device,
387
+ None, var_coeff, args.max_batches, model_cfg["atol"], model_cfg["rtol"]
388
+ )
389
+ scheduler.step()
390
+ record = {"epoch": epoch, "train_loss": train_loss, "val_loss": val_loss, "train_batches": train_count, "val_batches": val_count, "lr": scheduler.get_last_lr()[0]}
391
+ if rank == 0:
392
+ with log_path.open("a", encoding="utf-8") as handle:
393
+ handle.write(json.dumps(record) + "\n")
394
+ if val_loss < best_val:
395
+ best_val = val_loss
396
+ torch.save({"model": (model.module if isinstance(model, DistributedDataParallel) else model).state_dict(), "optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict(), "epoch": epoch}, checkpoint_dir / "model_bak.pth")
397
+ print(json.dumps(record))
398
+ if distributed:
399
+ dist.destroy_process_group()
400
+
401
+
402
+ if __name__ == "__main__":
403
+ main()
scripts/velocity.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Initial velocity fitting and cache management for ClimODE training."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.optim as optim
12
+
13
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
14
+ if str(PROJECT_ROOT) not in sys.path:
15
+ sys.path.insert(0, str(PROJECT_ROOT))
16
+
17
+ from model.climode import OptimVelocity
18
+
19
+ try:
20
+ from torchcubicspline import NaturalCubicSpline, natural_cubic_spline_coeffs
21
+ except ImportError: # pragma: no cover - dependency is optional for tiny smoke tests
22
+ NaturalCubicSpline = None
23
+ natural_cubic_spline_coeffs = None
24
+
25
+
26
+ def _time_derivative(history: torch.Tensor, interval_hours: float = 6.0) -> torch.Tensor:
27
+ """Estimate the derivative at the final history point.
28
+
29
+ The cubic-spline path is identical to the official implementation. The
30
+ finite-difference fallback is only for environments without the optional
31
+ package and is explicitly reported to the caller.
32
+ """
33
+
34
+ if history.ndim != 5:
35
+ raise ValueError(f"Expected history [N,3,K,H,W], got {tuple(history.shape)}")
36
+ if natural_cubic_spline_coeffs is not None:
37
+ times = torch.arange(3, device=history.device, dtype=history.dtype) * interval_hours
38
+ values = history.permute(1, 0, 2, 3, 4)
39
+ coeffs = natural_cubic_spline_coeffs(times, values)
40
+ spline = NaturalCubicSpline(coeffs)
41
+ return spline.derivative(times[-1])
42
+ return (3.0 * history[:, 2] - 4.0 * history[:, 1] + history[:, 0]) / (2.0 * interval_hours)
43
+
44
+
45
+ def build_rbf_kernel(
46
+ lat2d: torch.Tensor,
47
+ lon2d: torch.Tensor,
48
+ sigma: float = 1.0,
49
+ ) -> torch.Tensor:
50
+ coords = torch.stack([lat2d.reshape(-1), lon2d.reshape(-1)], dim=1).float()
51
+ distances = torch.cdist(coords, coords).square()
52
+ kernel = torch.exp(-distances / (2.0 * sigma * sigma))
53
+ return torch.linalg.inv(kernel)
54
+
55
+
56
+ def optimize_velocity(
57
+ history: torch.Tensor,
58
+ current: torch.Tensor,
59
+ kernel_inv: torch.Tensor,
60
+ epochs: int = 200,
61
+ learning_rate: float = 2.0,
62
+ smoothing_alpha: float = 1.0e-7,
63
+ ) -> torch.Tensor:
64
+ """Fit [N,2K,H,W] velocities using the official penalized objective."""
65
+
66
+ if current.ndim != 4:
67
+ raise ValueError(f"Expected current [N,K,H,W], got {tuple(current.shape)}")
68
+ num_years, channels, height, width = current.shape
69
+ model = OptimVelocity(num_years, height, width, channels).to(current.device)
70
+ optimizer = optim.Adam(model.parameters(), lr=learning_rate)
71
+ delta_u = _time_derivative(history)
72
+ best_loss = float("inf")
73
+ best_velocity = None
74
+ for _ in range(max(int(epochs), 1)):
75
+ optimizer.zero_grad(set_to_none=True)
76
+ out, vx, vy = model(current.unsqueeze(1))
77
+ vx_flat = vx.view(num_years, channels, -1, 1)
78
+ vy_flat = vy.view(num_years, channels, -1, 1)
79
+ kernel = kernel_inv.to(current.device).expand(num_years, channels, -1, -1)
80
+ smooth_x = torch.matmul(torch.matmul(vx_flat.transpose(2, 3), kernel), vx_flat).mean()
81
+ smooth_y = torch.matmul(torch.matmul(vy_flat.transpose(2, 3), kernel), vy_flat).mean()
82
+ loss = nn.functional.mse_loss(out.squeeze(1), delta_u) + smoothing_alpha * (smooth_x + smooth_y)
83
+ loss.backward()
84
+ optimizer.step()
85
+ if float(loss.detach()) < best_loss:
86
+ best_loss = float(loss.detach())
87
+ best_velocity = torch.cat([vx.detach(), vy.detach()], dim=2).squeeze(1).clone()
88
+ if best_velocity is None:
89
+ raise RuntimeError("Velocity optimization produced no result")
90
+ return best_velocity
91
+
92
+
93
+ def fit_velocity_cache(
94
+ dataset,
95
+ constants: torch.Tensor,
96
+ lat2d: torch.Tensor,
97
+ lon2d: torch.Tensor,
98
+ output_path: str | Path,
99
+ epochs: int = 200,
100
+ learning_rate: float = 2.0,
101
+ smoothing_alpha: float = 1.0e-7,
102
+ kernel_sigma: float = 1.0,
103
+ ) -> torch.Tensor:
104
+ del constants # Kept in the signature to make the training handoff explicit.
105
+ kernel_inv = build_rbf_kernel(lat2d, lon2d, kernel_sigma)
106
+ velocities = []
107
+ for index in range(len(dataset)):
108
+ item = dataset[index]
109
+ history = item["history"].float()
110
+ current = item["observations"][0].float()
111
+ velocities.append(
112
+ optimize_velocity(
113
+ history,
114
+ current,
115
+ kernel_inv,
116
+ epochs=epochs,
117
+ learning_rate=learning_rate,
118
+ smoothing_alpha=smoothing_alpha,
119
+ )
120
+ )
121
+ result = torch.stack(velocities)
122
+ path = Path(output_path)
123
+ path.parent.mkdir(parents=True, exist_ok=True)
124
+ torch.save({"velocity": result, "starts": dataset.starts, "years": dataset.years}, path)
125
+ return result
126
+
127
+
128
+ def load_velocity_cache(path: str | Path, expected_length: int | None = None) -> torch.Tensor:
129
+ try:
130
+ checkpoint = torch.load(path, map_location="cpu", weights_only=True)
131
+ except TypeError: # PyTorch before weights_only support.
132
+ checkpoint = torch.load(path, map_location="cpu")
133
+ velocity = checkpoint["velocity"] if isinstance(checkpoint, dict) else checkpoint
134
+ if expected_length is not None and len(velocity) != expected_length:
135
+ raise ValueError(f"Velocity cache length {len(velocity)} != dataset length {expected_length}")
136
+ return velocity.float()
weight/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+ placeholder for external ClimODE checkpoints