Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
54fe325
Add Graph-EFM training and ensemble forecasting
Sir-Sloth-The-Lazy Jul 25, 2026
ec06d63
Fix Graph-EFM checkpoint reconstruction and scoring reuse
Sir-Sloth-The-Lazy Nov 3, 2026
4d15e91
Restore Graph-EFM checkpoint settings in CLI runs
Sir-Sloth-The-Lazy Nov 3, 2026
7df387f
Clarify the variational posterior approximation
Sir-Sloth-The-Lazy Nov 16, 2026
5e61b79
Describe the Graph-EFM training objective directly
Sir-Sloth-The-Lazy Nov 16, 2026
7c74924
Document the independent prior rollouts used by CRPS
Sir-Sloth-The-Lazy Nov 16, 2026
bfa7e08
Reuse static graph embeddings across prior trajectories
Sir-Sloth-The-Lazy Nov 16, 2026
d9bf437
Match the original Graph-EFM CRPS loss reduction
Sir-Sloth-The-Lazy Nov 16, 2026
f75e0c3
Generalize ensemble CRPS and simplify two-member scoring
Sir-Sloth-The-Lazy Nov 16, 2026
c3b7e90
Extract distributed strategy selection into a utility
Sir-Sloth-The-Lazy Nov 16, 2026
7192dbb
Limit unused-parameter detection to zero-KL warm-up
Sir-Sloth-The-Lazy Nov 16, 2026
dbe3bda
Move Graph-EFM settings from experiment YAML to CLI options
Sir-Sloth-The-Lazy Nov 16, 2026
8f0dfb3
Allow checkpoint objective overrides between training stages
Sir-Sloth-The-Lazy Nov 16, 2026
d011c1b
Separate Graph-EFM predictor construction
Sir-Sloth-The-Lazy Nov 16, 2026
d4e14f9
Name the forecaster builder for what it constructs
Sir-Sloth-The-Lazy Nov 16, 2026
cb888e1
Condense the Graph-EFM changelog entry
Sir-Sloth-The-Lazy Nov 16, 2026
d4ed06a
Document Graph-EFM alongside the supported models
Sir-Sloth-The-Lazy Nov 16, 2026
8873464
Preserve CRPS metric API and single-member reductions
Sir-Sloth-The-Lazy Nov 16, 2026
9ef25e6
Register named ensemble CRPS variants for metric lookup
Sir-Sloth-The-Lazy Nov 16, 2026
c30eabc
Add configurable differentiable CRPS chunking
Sir-Sloth-The-Lazy Nov 16, 2026
0eb4b0f
Port unbiased ensemble variance from PR 226
Sir-Sloth-The-Lazy Nov 16, 2026
1d6d973
Evaluate Graph-EFM with CRPS and ensemble spread
Sir-Sloth-The-Lazy Nov 16, 2026
0071240
Document ensemble verification metrics with Graph-EFM training
Sir-Sloth-The-Lazy Nov 16, 2026
6a5b0b0
Reuse base ensemble sampling for Graph-EFM
Sir-Sloth-The-Lazy Nov 28, 2026
633330d
Defer ensemble spread to a separate change
Sir-Sloth-The-Lazy Nov 28, 2026
e57b341
Use consistent fair and unfair CRPS names
Sir-Sloth-The-Lazy Nov 28, 2026
edbe5ce
Select ensemble CRPS variants with alpha
Sir-Sloth-The-Lazy Nov 28, 2026
df406cb
Validate CRPS member counts before chunking
Sir-Sloth-The-Lazy Nov 28, 2026
f983efe
Require two members for every CRPS variant
Sir-Sloth-The-Lazy Nov 28, 2026
d091935
Explain CRPS ensemble axis normalization
Sir-Sloth-The-Lazy Nov 28, 2026
5d059b5
Explain CRPS chunk axis mapping
Sir-Sloth-The-Lazy Nov 28, 2026
eb224fc
Name the CRPS mean member error
Sir-Sloth-The-Lazy Nov 28, 2026
7c207cb
Explain the sorted CRPS pairwise reduction
Sir-Sloth-The-Lazy Nov 28, 2026
9bdc0c3
Reject unsupported classes in the Graph-EFM predictor builder
Sir-Sloth-The-Lazy Nov 28, 2026
d796ab3
Use current run settings when loading Graph-EFM checkpoints
Sir-Sloth-The-Lazy Nov 28, 2026
b9b86b7
Allow unused parameters only during learned-prior warm-up
Sir-Sloth-The-Lazy Nov 28, 2026
5afe8fd
Trim objective reduction details from the Graph-EFM README
Sir-Sloth-The-Lazy Nov 28, 2026
1451a55
Keep the Graph-EFM README focused on training and use
Sir-Sloth-The-Lazy Nov 28, 2026
4b1e2bf
Merge main into the Graph-EFM branch
Sir-Sloth-The-Lazy Nov 30, 2026
c3a2862
Preserve positional training configuration settings
Sir-Sloth-The-Lazy Nov 30, 2026
eae52fb
Support gradient checkpointing in Graph-EFM
Sir-Sloth-The-Lazy Nov 30, 2026
ff7b31c
Record Graph-EFM gradient checkpointing in the changelog
Sir-Sloth-The-Lazy Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Support gradient checkpointing for Graph-EFM training rollouts
[\#920](https://github.com/mllam/neural-lam/pull/920) @Sir-Sloth-The-Lazy

- Add Graph-EFM ensemble forecasting with variational training and CRPS
[\#712](https://github.com/mllam/neural-lam/pull/712) @Sir-Sloth-The-Lazy

- Add deterministic and probabilistic forecaster/module interfaces with
shared autoregressive unrolling and forecaster-owned training objectives.
[\#700](https://github.com/mllam/neural-lam/pull/700) @Sir-Sloth-The-Lazy
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Models, graphs, and data are kept independent so each component can be swapped w
<img src="https://raw.githubusercontent.com/mllam/neural-lam/main/figures/neural_lam_setup.png" width="600"/>
</p>

The three implemented architectures are Graph-LAM (flat), Hi-LAM (hierarchical), and Hi-LAM-Parallel.
Implemented architectures include Graph-LAM (flat), Hi-LAM (hierarchical), Hi-LAM-Parallel, and Graph-EFM (hierarchical and flat multiscale).
Global forecasting is available on a [separate branch](https://github.com/mllam/neural-lam/tree/prob_model_global) ([planned to be merged](https://github.com/mllam/neural-lam/issues/63)).

# Installing Neural-LAM
Expand Down Expand Up @@ -111,7 +111,7 @@ nn.Module
└── HiGraphLatentDecoder
```
The `--model` values listed in the [training guide](https://mllam.github.io/neural-lam/user-guide/training.html) select the step predictor.
`GraphEFM` and `GraphEFMMultiScale` are implemented but not yet selectable this way.
`graph_efm` and `graph_efm_ms` select the Graph-EFM predictors.

The building blocks these are assembled from are also `torch.nn.Module` subclasses:
```
Expand Down
62 changes: 61 additions & 1 deletion docs/user-guide/training.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ A few of the key ones are outlined below:
* `--ar_steps_train`: Number of time steps to unroll for when making predictions and computing the loss
* `--ar_steps_eval`: Number of time steps to unroll for during validation steps
* `--loss`: Which of the loss functions in `neural_lam/metrics.py` to train on
* `--gradient_checkpointing`: Recompute the activations of each autoregressive step in the backward pass instead of storing them, lowers peak memory when `--ar_steps_train` > 1 at the cost of extra compute
* `--gradient_checkpointing`: Recompute autoregressive step activations in the backward pass to reduce peak memory at the cost of extra compute.

Checkpoints of trained models are stored under `runs/<run-name>/checkpoints/`, alongside Lightning and logger outputs for the same run.
The implemented models are:
Expand Down Expand Up @@ -54,6 +54,66 @@ To train Hi-LAM-Parallel use
python -m neural_lam.train_model --model hi_lam_parallel --graph hierarchical ...
```

### Graph-EFM

Graph-EFM is a latent-variable ensemble forecasting model that generates
spatially coherent weather scenarios with one network pass per forecast step.
Use `--model graph_efm --graph hierarchical` for a hierarchical mesh or
`--model graph_efm_ms --graph multiscale` for a flat multiscale mesh.
The [Graph-EFM paper](https://arxiv.org/abs/2406.04759) describes the model
and its staged training procedure.

The variational objective combines a Gaussian reconstruction likelihood with
`--kl_beta` times the KL divergence between the target-conditioned variational
encoder and latent prior. `--loss` applies to deterministic models;
Graph-EFM always uses Gaussian negative log likelihood. Use `--output_std`
to learn observation scales; otherwise they come from one-step difference
statistics and configured feature weights.

Use `--gradient_checkpointing` to reduce activation memory when training
Graph-EFM. It recomputes steps in both the variational rollout and the prior
rollouts used by CRPS during the backward pass.

Graph-EFM options are CLI arguments:

| Option | Default | Purpose |
| --- | --- | --- |
| `--latent_dim` | `--hidden_dim` | Latent size at each latent mesh node |
| `--prior_layers` | 2 | Prior mesh depth |
| `--encoder_layers` | 2 | Variational encoder mesh depth |
| `--decoder_layers` | 4 | Decoder mesh depth |
| `--learn_prior` / `--no-learn_prior` | learned | Learned or standard normal prior |
| `--prior_dist` | isotropic | Isotropic or diagonal prior covariance |
| `--kl_beta` | 1.0 | KL weight; zero skips the prior in the variational rollout |
| `--crps_weight` | 0.0 | Fair CRPS weight; zero disables extra rollouts |
| `--crps_members` | 2 | Independent prior trajectories for fair CRPS (at least two) |
| `--eval_ensemble_size` | 5 | Members sampled during validation and testing |

A starting curriculum is the hierarchical MEPS schedule from
[Table 13 of the paper](https://arxiv.org/html/2406.04759v2#A9.T13):

| Stage | Epochs in stage | Learning rate | Rollout steps | KL weight | CRPS weight |
| --- | --- | --- | --- | --- | --- |
| Autoencoder warm-up | 300 | 1e-3 | 1 | 0 | 0 |
| Learn prior | 100 | 1e-3 | 1 | 1 | 0 |
| Longer rollouts | 200 | 5e-4 | 4 | 1 | 0 |
| Calibrate ensembles | 50 | 5e-4 | 4 | 1 | 1e6 |
| Extend lead time | 100 | 5e-4 | 6 | 1 | 1e6 |

Tune these weights for your dataset and observation scales. To change stage,
load the previous checkpoint and set the new objective and rollout options:

```bash
python -m neural_lam.train_model --config_path <config> \
--model graph_efm --graph hierarchical --load <warmup.ckpt> \
--kl_beta 1 --crps_weight 0 --ar_steps_train 1 --lr 1e-3 --epochs 400
```

Repeat the checkpoint's non-default architecture options when using
`--load`. Set `--epochs` to the cumulative target (400 after the first
two stages above). Omit `--restore_opt` when starting a new stage with
a different learning rate.

### Persistence

A trivial baseline model that returns the previous state unchanged at each step (`--model persistence`).
Expand Down
26 changes: 26 additions & 0 deletions neural_lam/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,14 @@ class ModelConfig:
GNN layer type for upward mesh message passing.
mesh_down_gnn_type : str, default "InteractionNet"
GNN layer type for downward mesh message passing.
latent_dim : int or None
Graph-EFM latent size; defaults to hidden_dim.
prior_layers, encoder_layers, decoder_layers : int
Graph-EFM mesh depths; defaults to 2, 2 and 4 respectively.
learn_prior : bool, default True
Learn the Graph-EFM prior; defaults to True.
prior_dist : str, default "isotropic"
Graph-EFM prior covariance, isotropic (default) or diagonal.
"""

model: str = "graph_lam"
Expand All @@ -308,6 +316,12 @@ class ModelConfig:
m2g_gnn_type: str = "InteractionNet"
mesh_up_gnn_type: str = "InteractionNet"
mesh_down_gnn_type: str = "InteractionNet"
latent_dim: int | None = None
prior_layers: int = 2
encoder_layers: int = 2
decoder_layers: int = 4
learn_prior: bool = True
prior_dist: str = "isotropic"


@dataclasses.dataclass
Expand Down Expand Up @@ -355,6 +369,14 @@ class TrainRunConfig:
Whether to recompute the activations of each autoregressive training
step in the backward pass instead of storing them. Lowers peak memory
when ``ar_steps_train > 1``, at the cost of extra compute.
kl_beta : float, default 1.0
Graph-EFM KL weight; defaults to 1.0.
crps_weight : float, default 0.0
Graph-EFM fair CRPS weight; defaults to 0.0.
crps_members : int, default 2
Independent prior trajectories for fair CRPS; defaults to 2.
eval_ensemble_size : int, default 5
Graph-EFM evaluation ensemble size; defaults to 5.
"""

epochs: int = 200
Expand All @@ -379,6 +401,10 @@ class TrainRunConfig:
n_example_pred: int = 1
create_gif: bool = False
gradient_checkpointing: bool = False
kl_beta: float = 1.0
crps_weight: float = 0.0
crps_members: int = 2
eval_ensemble_size: int = 5


@dataclasses.dataclass
Expand Down
163 changes: 163 additions & 0 deletions neural_lam/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Standard library
import inspect
from collections.abc import Callable
from functools import partial

# Third-party
import torch
Expand Down Expand Up @@ -393,13 +394,158 @@ def crps_gauss(
)


def crps_ens(
pred: torch.Tensor,
target: torch.Tensor,
pred_std: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
average_grid: bool = True,
sum_vars: bool = True,
ens_dim: int = 1,
*,
afc_alpha: float = 1.0,
chunk_size: int | None = None,
chunk_dim: int = 0,
) -> torch.Tensor:
"""Compute ensemble CRPS with empirical, fair or almost-fair estimation.

Uses sorted ranks to compute the pairwise spread term with memory
linear in the number of members, with a direct two-member formula.
Gradients are retained for training. The almost-fair variant follows
Lang et al. (2024), AIFS: https://arxiv.org/abs/2412.15832.

Parameters
----------
pred : torch.Tensor
Target shape with an additional ensemble dimension of size ``S``
at ``ens_dim``, normally ``(B, S, pred_steps, num_grid_nodes,
num_state_vars)``. At least two ensemble members are required.
target : torch.Tensor
Shape ``(..., num_grid_nodes, num_state_vars)``. Ground truth.
pred_std : torch.Tensor or None, optional
Unused; accepted for compatibility with the shared metric interface.
mask : torch.Tensor or None, optional
Shape ``(num_grid_nodes,)``. Boolean mask selecting grid nodes.
average_grid : bool, optional
Average over selected grid nodes. Default True.
sum_vars : bool, optional
Sum over state variables. Default True.
ens_dim : int, optional
Ensemble dimension in ``pred``. Default 1.
afc_alpha : float, optional
Interpolates from empirical (unfair) CRPS at 0 to fair CRPS
at 1 (default). Intermediate values give almost-fair CRPS.
chunk_size : int or None, optional
Maximum entries along chunk_dim per scoring call. None disables
chunking. Smaller chunks reduce peak temporary memory; gradients
remain available to callers using CRPS for training.
chunk_dim : int, optional
Dimension in pred to chunk, excluding ens_dim. Defaults to
batch dimension 0; use 2 for forecast steps in (B, S, T, N, F).
Negative dimension indices are supported.

Returns
-------
torch.Tensor
CRPS with the ensemble dimension removed, reduced according to
``mask``, ``average_grid`` and ``sum_vars`` as for ``nll``.

Raises
------
ValueError
If alpha, ensemble layout or chunk settings are invalid.
"""
if not 0 <= afc_alpha <= 1:
raise ValueError("afc_alpha must be finite and between 0 and 1")
if pred.ndim != target.ndim + 1:
raise ValueError("CRPS predictions require an extra ensemble dimension")
if not -pred.ndim <= ens_dim < pred.ndim:
raise ValueError("ens_dim is outside the prediction dimensions")
# Normalize negative axes so shape slicing and axis comparisons agree.
ens_dim %= pred.ndim
if pred.shape[:ens_dim] + pred.shape[ens_dim + 1 :] != target.shape:
raise ValueError(
"CRPS target shape must match predictions without ens_dim"
)
num_members = pred.shape[ens_dim]
if num_members < 2:
raise ValueError("CRPS requires at least two ensemble members")
if chunk_size is not None:
if chunk_size < 1:
raise ValueError("chunk_size must be positive")
if not -pred.ndim <= chunk_dim < pred.ndim:
raise ValueError("chunk_dim is outside the prediction dimensions")
chunk_dim %= pred.ndim
if chunk_dim == ens_dim:
raise ValueError("chunk_dim must differ from ens_dim")
# The target omits the ensemble axis, shifting any later axes left.
target_dim = chunk_dim - int(chunk_dim > ens_dim)
# Reassemble the per-entry scores before masking or reducing axes.
entries = [
crps_ens(
member_chunk,
target_chunk,
average_grid=False,
sum_vars=False,
ens_dim=ens_dim,
afc_alpha=afc_alpha,
)
for member_chunk, target_chunk in zip(
pred.split(chunk_size, dim=chunk_dim),
target.split(chunk_size, dim=target_dim),
strict=True,
)
]
return mask_and_reduce_metric(
torch.cat(entries, dim=target_dim), mask, average_grid, sum_vars
)
mean_member_error = (
(pred - target.unsqueeze(ens_dim)).abs().mean(dim=ens_dim)
)
if num_members == 2:
spread = (pred.select(ens_dim, 0) - pred.select(ens_dim, 1)).abs() / 2
else:
# Each sorted value appears positively in rank - 1 pair differences
# and negatively in num_members - rank pair differences.
ordered = pred.sort(dim=ens_dim).values
rank_shape = [1] * pred.ndim
rank_shape[ens_dim] = num_members
ranks = torch.arange(
1,
num_members + 1,
device=pred.device,
dtype=pred.dtype,
).view(rank_shape)
spread = ((2 * ranks - num_members - 1) * ordered).sum(dim=ens_dim)
spread = spread / (num_members * (num_members - 1))
# Alpha blends the fair and empirical normalizations of the pair term.
spread = spread * ((num_members - 1 + afc_alpha) / num_members)
entry_crps = mean_member_error - spread
return mask_and_reduce_metric(
entry_crps, mask=mask, average_grid=average_grid, sum_vars=sum_vars
)


crps_ens_fair = partial(crps_ens, afc_alpha=1.0)
crps_ens_unfair = partial(crps_ens, afc_alpha=0.0)
crps_ens_almost_fair = partial(crps_ens, afc_alpha=0.95)

ENSEMBLE_METRICS: dict[str, Callable[..., torch.Tensor]] = {
"crps_ens": crps_ens,
"crps_ens_fair": crps_ens_fair,
"crps_ens_unfair": crps_ens_unfair,
"crps_ens_almost_fair": crps_ens_almost_fair,
}


DEFINED_METRICS: dict[str, Callable[..., torch.Tensor]] = {
"mse": mse,
"mae": mae,
"wmse": wmse,
"wmae": wmae,
"nll": nll,
"crps_gauss": crps_gauss,
**ENSEMBLE_METRICS,
}


Expand All @@ -425,3 +571,20 @@ def requires_pred_std(metric: Callable[..., torch.Tensor]) -> bool:
"""
pred_std_param = inspect.signature(metric).parameters["pred_std"]
return pred_std_param.default is inspect.Parameter.empty


def requires_ensemble(metric: Callable[..., torch.Tensor]) -> bool:
"""Return whether a registered metric scores an ensemble of forecasts.

Parameters
----------
metric : callable
A function returned by get_metric.

Returns
-------
bool
True for registered ensemble metrics, which require predictions
with shape (B, S, pred_steps, num_grid_nodes, num_state_vars).
"""
return metric in ENSEMBLE_METRICS.values()
10 changes: 3 additions & 7 deletions neural_lam/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
BaseDeterministicForecaster,
DeterministicARForecaster,
)
from .forecasters.graph_efm import GraphEFMForecaster
from .forecasters.probabilistic import (
BaseProbabilisticARForecaster,
BaseProbabilisticForecaster,
Expand All @@ -23,16 +24,11 @@
from .step_predictors.graph.hierarchical import BaseHiGraphModel
from .step_predictors.persistence import PersistencePredictor

# NOTE: GraphEFM/GraphEFMMultiScale are intentionally NOT registered in
# MODELS yet.
# ``train_model.build_predictor`` instantiates the chosen model with a fixed
# deterministic kwarg set -- datastore-first, no ``config``, and with
# ``mesh_aggr`` -- whereas the Graph-EFM models require ``config`` (for their
# per_var_std weighting) and take no ``mesh_aggr``.
# Registering them requires making ``build_predictor`` config-aware.
MODELS = {
"graph_lam": GraphLAM,
"hi_lam": HiLAM,
"hi_lam_parallel": HiLAMParallel,
"persistence": PersistencePredictor,
"graph_efm": GraphEFM,
"graph_efm_ms": GraphEFMMultiScale,
}
1 change: 1 addition & 0 deletions neural_lam/models/forecasters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
BaseDeterministicForecaster,
DeterministicARForecaster,
)
from .graph_efm import GraphEFMForecaster
from .probabilistic import (
BaseProbabilisticARForecaster,
BaseProbabilisticForecaster,
Expand Down
Loading
Loading