From 54fe32519aae6a6bca65ada8e61f935e2430d573 Mon Sep 17 00:00:00 2001
From: Jeevant Prakhar Singh
Date: Sat, 25 Jul 2026 09:15:44 +0530
Subject: [PATCH 01/41] Add Graph-EFM training and ensemble forecasting
Train hierarchical and flat Graph-EFM models through the merged probabilistic
interfaces with a Gaussian ELBO and optional fair CRPS from prior trajectories.
Wire configuration, model selection, and checkpoint restoration into the current
training pipeline, preserving increment rescaling and clamping.
Add numerical objective, gradient, training, checkpoint, and configuration tests,
and document the model settings using the repository's docstring conventions.
---
CHANGELOG.md | 4 +
README.md | 38 ++
neural_lam/config.py | 55 ++
neural_lam/models/__init__.py | 10 +-
neural_lam/models/forecasters/__init__.py | 1 +
neural_lam/models/forecasters/graph_efm.py | 262 ++++++++
neural_lam/models/latent/base_decoder.py | 4 +-
.../models/step_predictors/graph/graph_efm.py | 164 +++--
neural_lam/train_model.py | 150 ++++-
tests/test_graph_efm_model.py | 612 ++++++++++++++++++
tests/test_graph_efm_objective.py | 172 +++++
11 files changed, 1414 insertions(+), 58 deletions(-)
create mode 100644 neural_lam/models/forecasters/graph_efm.py
create mode 100644 tests/test_graph_efm_model.py
create mode 100644 tests/test_graph_efm_objective.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c2bc0799..6d27db59b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Add Graph-EFM forecaster training with Gaussian ELBO and optional fair CRPS,
+ probabilistic configuration, CLI assembly and checkpoint loading.
+ [\#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
diff --git a/README.md b/README.md
index 6e330ab74..3e622f9b2 100644
--- a/README.md
+++ b/README.md
@@ -64,6 +64,44 @@ Still, some restrictions are inevitable:
+## Graph-EFM ensemble forecasting
+
+Use `--model graph_efm` with a hierarchical graph, or `--model graph_efm_ms`
+with a flat multiscale graph. Both train with a target-conditioned Gaussian
+negative ELBO and sample forecasts from the latent prior at evaluation time.
+The `--loss` option selects the deterministic models' objective; Graph-EFM
+always uses a Gaussian likelihood, including its log-standard-deviation term.
+Without `--output_std`, observation scales come from the datastore's one-step
+difference statistics and configured feature weights.
+
+Add this optional section alongside `datastores` in the experiment YAML:
+
+```yaml
+probabilistic:
+ latent_dim: 64
+ prior_layers: 2
+ encoder_layers: 2
+ decoder_layers: 4
+ learn_prior: true
+ prior_dist: isotropic
+ kl_beta: 1.0
+ crps_weight: 0.0
+ crps_members: 2
+ eval_ensemble_size: 5
+```
+
+Omit `latent_dim` to use `--hidden_dim`. Layer counts control same-level message
+passing for hierarchical graphs and mesh processing for flat graphs.
+A positive `crps_weight` adds fair sample CRPS from `crps_members` independent
+prior trajectories (at least two), separately from the posterior ELBO rollout.
+Both objectives sum over forecast steps and state variables; likelihood and
+CRPS use interior grid nodes, while KL sums over latent mesh nodes.
+Setting `kl_beta: 0` skips the prior in the posterior rollout; CRPS, when enabled,
+still trains the prior. Validation and testing use `eval_ensemble_size` members
+and report ensemble-mean RMSE; validation checkpoints monitor `val_mean_loss`,
+the same objective used for training. Ensemble plotting and further ensemble
+verification metrics are separate follow-ups.
+
# Installing Neural-LAM
When installing `neural-lam` you have a choice of either installing directly with `pip` or using the `uv` package manager.
diff --git a/neural_lam/config.py b/neural_lam/config.py
index ea3762275..58596a693 100644
--- a/neural_lam/config.py
+++ b/neural_lam/config.py
@@ -122,6 +122,55 @@ class TrainingConfig:
)
+@dataclasses.dataclass
+class ProbabilisticConfig:
+ """
+ Configuration for the probabilistic (Graph-EFM) models.
+
+ Only used when training or evaluating a probabilistic model
+ (``--model graph_efm``/``graph_efm_ms``); ignored otherwise. Every field
+ has a default, so the ``probabilistic`` config section may be omitted
+ entirely for deterministic models.
+
+ Attributes
+ ----------
+ latent_dim : int, optional
+ Dimensionality of the latent variable at each latent-carrying mesh
+ node. Defaults to the model's ``hidden_dim`` when None.
+ prior_layers : int
+ Number of on-mesh GNN layers in the prior.
+ encoder_layers : int
+ Number of on-mesh GNN layers in the variational encoder.
+ decoder_layers : int
+ Number of on-mesh GNN layers in the latent decoder.
+ learn_prior : bool
+ If True, the prior is a learned encoder conditioned on the previous
+ state; if False, a constant ``Normal(0, 1)`` prior is used.
+ prior_dist : str
+ Output distribution of the prior: ``"isotropic"`` or ``"diagonal"``.
+ kl_beta : float
+ Weight of the KL term in the ELBO. When 0, the prior and KL are not
+ computed in the posterior rollout; CRPS can still train the prior.
+ crps_weight : float
+ Weight of the optional fair CRPS objective from prior trajectories.
+ crps_members : int
+ Number of independent prior trajectories for CRPS, at least two.
+ eval_ensemble_size : int
+ Number of ensemble members sampled during validation and testing.
+ """
+
+ 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"
+ kl_beta: float = 1.0
+ eval_ensemble_size: int = 5
+ crps_weight: float = 0.0
+ crps_members: int = 2
+
+
@dataclasses.dataclass
class NeuralLAMConfig(dataclass_wizard.JSONWizard, dataclass_wizard.YAMLWizard):
"""
@@ -142,11 +191,17 @@ class NeuralLAMConfig(dataclass_wizard.JSONWizard, dataclass_wizard.YAMLWizard):
training : TrainingConfig
Configuration for training the model, including loss function and
feature-weighting strategy. Defaults to ``TrainingConfig()``.
+ probabilistic : ProbabilisticConfig
+ Graph-EFM architecture, objective, and evaluation settings.
"""
datastores: dict[str, DatastoreSelection]
training: TrainingConfig = dataclasses.field(default_factory=TrainingConfig)
+ probabilistic: ProbabilisticConfig = dataclasses.field(
+ default_factory=ProbabilisticConfig
+ )
+
class _(dataclass_wizard.JSONWizard.Meta):
"""
Define the configuration class as a JSON wizard class.
diff --git a/neural_lam/models/__init__.py b/neural_lam/models/__init__.py
index 39ad8c44a..00a9e1b16 100644
--- a/neural_lam/models/__init__.py
+++ b/neural_lam/models/__init__.py
@@ -7,6 +7,7 @@
BaseDeterministicForecaster,
DeterministicARForecaster,
)
+from .forecasters.graph_efm import GraphEFMForecaster
from .forecasters.probabilistic import (
BaseProbabilisticARForecaster,
BaseProbabilisticForecaster,
@@ -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,
}
diff --git a/neural_lam/models/forecasters/__init__.py b/neural_lam/models/forecasters/__init__.py
index 4929e04aa..bf1a11a87 100644
--- a/neural_lam/models/forecasters/__init__.py
+++ b/neural_lam/models/forecasters/__init__.py
@@ -9,6 +9,7 @@
BaseDeterministicForecaster,
DeterministicARForecaster,
)
+from .graph_efm import GraphEFMForecaster
from .probabilistic import (
BaseProbabilisticARForecaster,
BaseProbabilisticForecaster,
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
new file mode 100644
index 000000000..9dc7fc28e
--- /dev/null
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -0,0 +1,262 @@
+"""Probabilistic forecaster training a Graph-EFM predictor via its ELBO."""
+
+# Third-party
+import torch
+
+# Local
+from ... import metrics
+from ...config import NeuralLAMConfig
+from ...datastore import BaseDatastore
+from ...loss_weighting import get_per_var_std
+from ..step_predictors.graph.graph_efm import BaseGraphEFM
+from .probabilistic import BaseProbabilisticARForecaster
+
+
+class GraphEFMForecaster(BaseProbabilisticARForecaster):
+ """
+ Auto-regressive ensemble forecaster for Graph-EFM step predictors.
+
+ Wraps a :class:`BaseGraphEFM` predictor (hierarchical ``GraphEFM`` or
+ flat ``GraphEFMMultiScale``), a latent-variable model consisting of a
+ conditional prior, a variational encoder and a latent decoder. Forecast
+ sampling (``forward``, ``sample_ensemble``) is inherited from
+ :class:`BaseProbabilisticARForecaster`: each predictor call samples the
+ prior and decodes, so unrolling produces one stochastic trajectory and
+ stacking several gives an ensemble.
+
+ This class supplies the training objective the base class leaves
+ abstract: the evidence lower bound (ELBO). ``compute_training_loss``
+ runs a variational rollout in which, at each step, the latent is drawn
+ from the encoder (conditioned on the target), and accumulates a
+ reconstruction likelihood term and a KL term between the encoder and the
+ prior. The Gaussian likelihood, the constant per-variable std
+ fallback ``self.per_var_std`` and the boundary/interior masks all live
+ on the forecaster; the predictor only
+ provides the network building blocks.
+ """
+
+ def __init__(
+ self,
+ predictor: BaseGraphEFM,
+ datastore: BaseDatastore,
+ config: NeuralLAMConfig | None = None,
+ kl_beta: float = 1.0,
+ crps_weight: float = 0.0,
+ crps_members: int = 2,
+ ) -> None:
+ """
+ Initialize the GraphEFMForecaster.
+
+ Parameters
+ ----------
+ predictor : BaseGraphEFM
+ The Graph-EFM step predictor to use for each step. Each
+ ``forward`` call samples the prior and decodes; the encoder,
+ prior and decoder sub-models are also used directly by
+ ``compute_training_loss`` to assemble the ELBO.
+ datastore : BaseDatastore
+ The datastore providing grid metadata and boundary masks.
+ config : NeuralLAMConfig or None
+ Configuration used to compute the constant per-variable std
+ substituted for ``pred_std`` when ``predictor`` does not output
+ its own. Required for
+ training when the predictor's ``output_std`` is False, since the
+ likelihood term then needs the fallback std.
+ crps_weight : float, optional
+ Weight of fair CRPS computed from independent prior trajectories.
+ Default zero, disabling the additional sampling cost.
+ crps_members : int, optional
+ Number of prior trajectories for CRPS. Default two.
+ kl_beta : float, default 1.0
+ Weight of the KL term in the ELBO. When ``0`` the prior and KL
+ are not computed at all (pure auto-encoder training); the prior
+ network then receives gradients only if CRPS is enabled.
+ """
+ super().__init__(predictor, datastore)
+ if not torch.isfinite(torch.tensor(kl_beta)) or kl_beta < 0:
+ raise ValueError("kl_beta must be finite and nonnegative")
+ if not torch.isfinite(torch.tensor(crps_weight)) or crps_weight < 0:
+ raise ValueError("crps_weight must be finite and nonnegative")
+ if crps_members < 2:
+ raise ValueError("crps_members must be at least two")
+ self.kl_beta = kl_beta
+ self.crps_weight = crps_weight
+ self.crps_members = crps_members
+ self.register_buffer(
+ "per_var_std",
+ get_per_var_std(config, datastore) if config is not None else None,
+ persistent=False,
+ )
+
+ predictor: BaseGraphEFM
+ per_var_std: torch.Tensor | None
+
+ def compute_training_loss(
+ self,
+ init_states: torch.Tensor,
+ forcing_features: torch.Tensor,
+ target_states: torch.Tensor,
+ interior_mask_bool: torch.Tensor,
+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
+ """
+ Compute the ELBO training objective for one batch.
+
+ Unrolls a variational rollout over the full forecast: at each step
+ the grid, graph and target are embedded, the latent is drawn from
+ the encoder (variational posterior), the decoder reconstructs the
+ next-state mean, and a reconstruction likelihood term is
+ accumulated. When ``kl_beta`` is positive a KL term between the
+ encoder and the prior is accumulated too. Both terms are summed over
+ the rollout and averaged over the batch; the loss is
+ ``-likelihood + kl_beta * kl + crps_weight * crps``.
+ CRPS is
+ summed over interior nodes, variables and time, like the likelihood,
+ and averaged over the batch. The rollout advances on the
+ predicted mean with boundary nodes overwritten by the true state.
+
+ Parameters
+ ----------
+ init_states : torch.Tensor
+ Shape ``(B, 2, num_grid_nodes, num_state_vars)``. The two initial
+ states ``[X_{t-1}, X_t]`` used to start the rollout from. Dims:
+ ``B`` is batch size, ``2`` is the time index (``[X_{t-1}, X_t]``),
+ ``num_grid_nodes`` is the number of spatial nodes, and
+ ``num_state_vars`` is the state feature dimension.
+ forcing_features : torch.Tensor
+ Shape ``(B, pred_steps, num_grid_nodes,
+ num_windowed_forcing_vars)``.
+ External forcings provided at each predicted step. Dims: ``B``
+ is batch size, ``pred_steps`` is the rollout length,
+ ``num_grid_nodes`` is the number of spatial nodes, and
+ ``num_windowed_forcing_vars`` includes the concatenated
+ past/current/future forcing windows.
+ target_states : torch.Tensor
+ Shape ``(B, pred_steps, num_grid_nodes, num_state_vars)``. True
+ states at each predicted step, used as the encoder conditioning
+ and reconstruction target and to overwrite boundary nodes during
+ the rollout. Dims: same as the prediction.
+ interior_mask_bool : torch.Tensor
+ Shape ``(num_grid_nodes,)``, boolean. ``True`` for interior
+ nodes; passed as ``mask`` to ``metrics.nll`` so only interior
+ nodes contribute to the likelihood.
+
+ Returns
+ -------
+ batch_loss : torch.Tensor
+ Scalar. Negative weighted ELBO plus optional fair CRPS.
+ loss_components : dict of {str: torch.Tensor}
+ Scalar ELBO diagnostics to log: ``"elbo_likelihood"`` always,
+ plus ``"elbo_kl"`` and ``"elbo"`` when ``kl_beta > 0``, and
+ ``"crps"`` when ``crps_weight > 0``.
+
+ Raises
+ ------
+ ValueError
+ If the predictor does not output its own std and no
+ ``per_var_std`` fallback is available (this forecaster was
+ constructed without ``config``).
+ """
+ predictor = self.predictor
+
+ prev_prev_state = init_states[:, 0]
+ prev_state = init_states[:, 1]
+ pred_steps = forcing_features.shape[1]
+ compute_kl = self.kl_beta > 0
+
+ # The graph embedding depends only on static features, so it is
+ # constant across the rollout and computed once here.
+ graph_emb = predictor.embedd_graph(init_states.shape[0])
+
+ likelihood_terms = []
+ kl_terms = []
+
+ for i in range(pred_steps):
+ forcing = forcing_features[:, i]
+ target_state = target_states[:, i]
+
+ # Posterior latent (conditioned on target), reconstruction, and
+ # -- when a KL term is needed -- the prior, in one predictor call.
+ prior_dist, posterior_dist, pred_mean, pred_std = (
+ predictor.posterior_step(
+ prev_state,
+ prev_prev_state,
+ forcing,
+ target_state,
+ graph_emb,
+ compute_prior=compute_kl,
+ )
+ )
+ if pred_std is None:
+ pred_std = self.per_var_std
+ if pred_std is None:
+ raise ValueError(
+ "Graph-EFM likelihood requires config or output_std"
+ )
+
+ # Reconstruction likelihood, summed over interior grid and vars
+ entry_likelihoods = -metrics.nll(
+ pred_mean,
+ target_state,
+ pred_std,
+ mask=interior_mask_bool,
+ average_grid=False,
+ sum_vars=False,
+ ) # (B, num_interior_grid_nodes, num_state_vars)
+ likelihood_terms.append(torch.sum(entry_likelihoods, dim=(1, 2)))
+
+ if compute_kl:
+ assert prior_dist is not None
+ kl_terms.append(
+ torch.sum(
+ torch.distributions.kl_divergence(
+ posterior_dist, prior_dist
+ ),
+ dim=(1, 2),
+ )
+ ) # (B,)
+
+ # Advance the rollout on the predicted mean, boundary overwritten
+ new_state = (
+ self.boundary_mask * target_state
+ + self.interior_mask * pred_mean
+ )
+ prev_prev_state = prev_state
+ prev_state = new_state
+
+ # Sum each term over the rollout, then average over the batch
+ mean_likelihood = torch.mean(
+ torch.sum(torch.stack(likelihood_terms, dim=1), dim=1)
+ )
+ loss_components = {"elbo_likelihood": mean_likelihood}
+
+ if compute_kl:
+ mean_kl = torch.mean(torch.sum(torch.stack(kl_terms, dim=1), dim=1))
+ batch_loss = -mean_likelihood + self.kl_beta * mean_kl
+ loss_components["elbo_kl"] = mean_kl
+ loss_components["elbo"] = mean_likelihood - mean_kl
+ else:
+ batch_loss = -mean_likelihood
+
+ if self.crps_weight > 0:
+ ensemble, _ = self.sample_ensemble(
+ init_states, forcing_features, target_states, self.crps_members
+ )
+ # Fair CRPS uses independent prior trajectories.
+ first = (ensemble - target_states.unsqueeze(1)).abs().mean(dim=1)
+ ordered = ensemble.sort(dim=1).values
+ ranks = torch.arange(
+ 1,
+ self.crps_members + 1,
+ device=ensemble.device,
+ dtype=ensemble.dtype,
+ ).view(1, -1, 1, 1, 1)
+ spread = ((2 * ranks - self.crps_members - 1) * ordered).sum(dim=1)
+ entry_crps = first - spread / (
+ self.crps_members * (self.crps_members - 1)
+ )
+ crps = (
+ entry_crps[:, :, interior_mask_bool].sum(dim=(1, 2, 3)).mean()
+ )
+ batch_loss = batch_loss + self.crps_weight * crps
+ loss_components["crps"] = crps
+ return batch_loss, loss_components
diff --git a/neural_lam/models/latent/base_decoder.py b/neural_lam/models/latent/base_decoder.py
index 375e1cbfa..f625b63c0 100644
--- a/neural_lam/models/latent/base_decoder.py
+++ b/neural_lam/models/latent/base_decoder.py
@@ -153,7 +153,7 @@ def forward(
Shape ``(B, num_grid_nodes, num_state_vars)`` when
``output_std`` is True, otherwise None. Predicted std of the
next state, obtained from the output parameter map through a
- softplus.
+ softplus with a positive floor to prevent numerical underflow.
"""
latent_emb = self.latent_embedder(latent_samples)
@@ -176,7 +176,7 @@ def forward(
# parameters), then map the latter through a softplus to get
# positive std values.
mean_delta, std_raw = state_params.chunk(2, dim=-1)
- pred_std = nn.functional.softplus(std_raw)
+ pred_std = nn.functional.softplus(std_raw) + 1e-4
else:
mean_delta = state_params
pred_std = None
diff --git a/neural_lam/models/step_predictors/graph/graph_efm.py b/neural_lam/models/step_predictors/graph/graph_efm.py
index b02a76468..d77cc411c 100644
--- a/neural_lam/models/step_predictors/graph/graph_efm.py
+++ b/neural_lam/models/step_predictors/graph/graph_efm.py
@@ -3,7 +3,7 @@
graphs."""
# Standard library
-from typing import Any, Dict, Optional
+from typing import Any
# Third-party
import torch
@@ -60,7 +60,7 @@ def __init__(
graph_name: str,
hidden_dim: int = 64,
hidden_layers: int = 1,
- latent_dim: Optional[int] = None,
+ latent_dim: int | None = None,
learn_prior: bool = True,
prior_dist: str = "isotropic",
prior_layers: int = 2,
@@ -68,8 +68,8 @@ def __init__(
num_past_forcing_steps: int = 1,
num_future_forcing_steps: int = 1,
output_std: bool = False,
- output_clamping_lower: Optional[Dict[str, float]] = None,
- output_clamping_upper: Optional[Dict[str, float]] = None,
+ output_clamping_lower: dict[str, float] | None = None,
+ output_clamping_upper: dict[str, float] | None = None,
) -> None:
"""
Set up the graph-type independent parts of the predictor.
@@ -364,14 +364,14 @@ def embedd_mesh(self, batch_size: int) -> dict[str, Any]:
"""
raise NotImplementedError("embedd_mesh not implemented")
- def embedd_grid_and_graph(
+ def embedd_grid(
self,
prev_state: torch.Tensor,
prev_prev_state: torch.Tensor,
forcing: torch.Tensor,
- ) -> tuple[torch.Tensor, dict[str, Any]]:
+ ) -> torch.Tensor:
"""
- Embed the grid (states up to t-1) and the full graph.
+ Embed the grid states and forcing before a prediction.
Parameters
----------
@@ -386,8 +386,6 @@ def embedd_grid_and_graph(
-------
grid_emb : torch.Tensor
Shape ``(B, num_grid_nodes, hidden_dim)``. Grid embedding.
- graph_emb : dict
- Edge/mesh embeddings, each entry of shape ``(B, *, hidden_dim)``.
"""
batch_size = prev_state.shape[0]
@@ -404,10 +402,21 @@ def embedd_grid_and_graph(
grid_emb = self.grid_prev_embedder(grid_features)
# (B, num_grid_nodes, hidden_dim)
- # Graph embedding. NOTE: this block depends only on static graph
- # features, so it is constant across an autoregressive rollout. It is
- # kept as a self-contained block so a future embedd_graph()/
- # embedd_grid() split (hoisting it out of the AR loop) is mechanical.
+ return grid_emb
+
+ def embedd_graph(self, batch_size: int) -> dict[str, Any]:
+ """Embed static graph features once for an autoregressive rollout.
+
+ Parameters
+ ----------
+ batch_size : int
+ Number of samples to expand the embeddings to.
+
+ Returns
+ -------
+ dict[str, Any]
+ Node and edge embeddings with batch and hidden dimensions.
+ """
graph_emb = {
"g2m": self.expand_to_batch(
self.g2m_embedder(self.g2m_features), batch_size
@@ -418,14 +427,107 @@ def embedd_grid_and_graph(
}
graph_emb.update(self.embedd_mesh(batch_size))
- return grid_emb, graph_emb
+ return graph_emb
+
+ def posterior_step(
+ self,
+ prev_state: torch.Tensor,
+ prev_prev_state: torch.Tensor,
+ forcing: torch.Tensor,
+ target_state: torch.Tensor,
+ graph_emb: dict[str, Any] | None = None,
+ compute_prior: bool = True,
+ ) -> tuple[
+ torch.distributions.Normal | None,
+ torch.distributions.Normal,
+ torch.Tensor,
+ torch.Tensor | None,
+ ]:
+ """Sample a training step from the target-conditioned posterior.
+
+ Parameters
+ ----------
+ prev_state : torch.Tensor
+ Shape ``(B, num_grid_nodes, num_state_vars)``. Previous state.
+ prev_prev_state : torch.Tensor
+ Shape as ``prev_state``. State preceding the previous state.
+ forcing : torch.Tensor
+ Shape ``(B, num_grid_nodes, num_windowed_forcing_vars)``.
+ target_state : torch.Tensor
+ Shape as ``prev_state``. Posterior conditioning target.
+ graph_emb : dict[str, Any] or None, optional
+ Static graph embeddings from ``embedd_graph``. Computed from
+ the predictor buffers when omitted.
+ compute_prior : bool, optional
+ Compute the prior for the KL term. Default True.
+
+ Returns
+ -------
+ prior : torch.distributions.Normal or None
+ Conditional prior, omitted when ``compute_prior`` is False.
+ posterior : torch.distributions.Normal
+ Target-conditioned latent distribution.
+ prediction : torch.Tensor
+ Shape as ``prev_state``. Rescaled and clamped decoder mean.
+ pred_std : torch.Tensor or None
+ Shape as ``prev_state``. Conditional observation std, if enabled.
+ """
+ if graph_emb is None:
+ graph_emb = self.embedd_graph(prev_state.shape[0])
+ grid_emb = self.embedd_grid(prev_state, prev_prev_state, forcing)
+ target_emb = self.embedd_grid_with_target(
+ prev_state, prev_prev_state, forcing, target_state
+ )
+ assert isinstance(self.encoder, torch.nn.Module)
+ posterior = self.encoder(target_emb, graph_emb=graph_emb)
+ prior = (
+ self.prior_model(grid_emb, graph_emb=graph_emb)
+ if compute_prior
+ else None
+ )
+ mean, std = self.decode_state(
+ grid_emb, posterior.rsample(), graph_emb, prev_state
+ )
+ return prior, posterior, mean, std
+
+ def decode_state(
+ self,
+ grid_emb: torch.Tensor,
+ latent: torch.Tensor,
+ graph_emb: dict[str, Any],
+ prev_state: torch.Tensor,
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Decode a latent sample into a rescaled, clamped state.
+
+ Parameters
+ ----------
+ grid_emb : torch.Tensor
+ Shape ``(B, num_grid_nodes, hidden_dim)``. Embedded grid.
+ latent : torch.Tensor
+ Shape ``(B, num_mesh_nodes, latent_dim)``. Latent sample.
+ graph_emb : dict[str, Any]
+ Static graph embeddings.
+ prev_state : torch.Tensor
+ Shape ``(B, num_grid_nodes, num_state_vars)``. Previous state.
+
+ Returns
+ -------
+ prediction : torch.Tensor
+ Shape as ``prev_state``. Next-state mean.
+ pred_std : torch.Tensor or None
+ Shape as ``prev_state``. Observation std, if enabled.
+ """
+ assert isinstance(self.decoder, torch.nn.Module)
+ mean_delta, pred_std = self.decoder(grid_emb, latent, graph_emb)
+ increment = mean_delta * self.diff_std + self.diff_mean
+ return self.get_clamped_new_state(increment, prev_state), pred_std
def forward(
self,
prev_state: torch.Tensor,
prev_prev_state: torch.Tensor,
forcing: torch.Tensor,
- ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
"""
Sample one time step prediction: embed features, sample the latent
from the prior, decode, and return the predicted next state. The
@@ -451,9 +553,9 @@ def forward(
``output_std`` is True, otherwise None.
"""
# embed all features
- grid_prev_emb, graph_emb = self.embedd_grid_and_graph(
- prev_state, prev_prev_state, forcing
- )
+ grid_prev_emb = self.embedd_grid(prev_state, prev_prev_state, forcing)
+
+ graph_emb = self.embedd_graph(prev_state.shape[0])
# Compute prior
prior_dist = self.prior_model(
@@ -464,19 +566,9 @@ def forward(
latent_samples = prior_dist.rsample()
# (B, num_mesh_nodes, latent_dim)
- # Decode the latent into a state increment, rescale it with the
- # one-step difference statistics, then add it onto prev_state (X_t)
- # and clamp to the valid range (a no-op when no clamping limits are
- # configured), as for the deterministic models.
- assert isinstance(self.decoder, torch.nn.Module)
- mean_delta, pred_std = self.decoder(
- grid_prev_emb, latent_samples, graph_emb
+ return self.decode_state(
+ grid_prev_emb, latent_samples, graph_emb, prev_state
)
- rescaled_mean_delta = mean_delta * self.diff_std + self.diff_mean
- pred_mean = self.get_clamped_new_state(rescaled_mean_delta, prev_state)
- # (B, num_grid_nodes, num_state_vars)
-
- return pred_mean, pred_std
class GraphEFM(BaseGraphEFM):
@@ -502,7 +594,7 @@ def __init__(
graph_name: str = "hierarchical",
hidden_dim: int = 64,
hidden_layers: int = 1,
- latent_dim: Optional[int] = None,
+ latent_dim: int | None = None,
prior_intra_level_layers: int = 2,
encoder_intra_level_layers: int = 2,
decoder_intra_level_layers: int = 4,
@@ -513,8 +605,8 @@ def __init__(
g2m_gnn_type: str = "InteractionNet",
m2g_gnn_type: str = "InteractionNet",
output_std: bool = False,
- output_clamping_lower: Optional[Dict[str, float]] = None,
- output_clamping_upper: Optional[Dict[str, float]] = None,
+ output_clamping_lower: dict[str, float] | None = None,
+ output_clamping_upper: dict[str, float] | None = None,
) -> None:
"""
Build the mesh embedders and the hierarchical encoder/decoder
@@ -824,7 +916,7 @@ def __init__(
graph_name: str = "multiscale",
hidden_dim: int = 64,
hidden_layers: int = 1,
- latent_dim: Optional[int] = None,
+ latent_dim: int | None = None,
prior_m2m_layers: int = 2,
encoder_m2m_layers: int = 2,
decoder_m2m_layers: int = 4,
@@ -835,8 +927,8 @@ def __init__(
g2m_gnn_type: str = "InteractionNet",
m2g_gnn_type: str = "InteractionNet",
output_std: bool = False,
- output_clamping_lower: Optional[Dict[str, float]] = None,
- output_clamping_upper: Optional[Dict[str, float]] = None,
+ output_clamping_lower: dict[str, float] | None = None,
+ output_clamping_upper: dict[str, float] | None = None,
) -> None:
"""
Build the mesh embedders and the flat-graph encoder/decoder latent
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index d26668f27..4fcdcb049 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -29,6 +29,7 @@
ModelConfig,
NeuralLAMConfig,
OutputClamping,
+ ProbabilisticConfig,
TrainingConfig,
TrainRunConfig,
UniformFeatureWeighting,
@@ -38,10 +39,16 @@
from .gnn_layers import GNN_TYPES
from .models import (
MODELS,
+ BaseForecaster,
BaseHiGraphModel,
DeterministicARForecaster,
DeterministicForecastingModule,
+ GraphEFM,
+ GraphEFMForecaster,
+ GraphEFMMultiScale,
+ ProbabilisticForecastingModule,
)
+from .models.modules.base import BaseForecastingModule
from .weather_dataset import WeatherDataModule
if hasattr(torch.serialization, "add_safe_globals"):
@@ -51,6 +58,7 @@
DatastoreSelection,
ManualStateFeatureWeighting,
NeuralLAMConfig,
+ ProbabilisticConfig,
OutputClamping,
TrainingConfig,
UniformFeatureWeighting,
@@ -98,8 +106,51 @@ def build_predictor(
subclasses, gating on the class hierarchy so that future hierarchical
models are covered without maintaining a model-name list. GNN type
arguments fall back to ``InteractionNet`` for checkpoints saved before
- those CLI flags existed.
+ those CLI flags existed. Graph-EFM uses its probabilistic configuration
+ for latent dimensions and encoder/decoder depths.
+
+ Parameters
+ ----------
+ predictor_class : type
+ Step predictor class selected from ``MODELS``.
+ args : Namespace
+ Architecture and forcing-window arguments.
+ config : NeuralLAMConfig
+ Output clamping and Graph-EFM settings.
+ datastore : BaseDatastore
+ Grid features, graph location and standardization statistics.
+
+ Returns
+ -------
+ StepPredictor
+ Predictor configured for its graph family.
"""
+ if issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)):
+ prob = config.probabilistic
+ prefix = (
+ "intra_level" if issubclass(predictor_class, GraphEFM) else "m2m"
+ )
+ layers = {
+ f"{part}_{prefix}_layers": getattr(prob, f"{part}_layers")
+ for part in ("prior", "encoder", "decoder")
+ }
+ return predictor_class(
+ datastore=datastore,
+ graph_name=args.graph,
+ hidden_dim=args.hidden_dim,
+ hidden_layers=args.hidden_layers,
+ latent_dim=prob.latent_dim,
+ learn_prior=prob.learn_prior,
+ prior_dist=prob.prior_dist,
+ num_past_forcing_steps=args.num_past_forcing_steps,
+ num_future_forcing_steps=args.num_future_forcing_steps,
+ output_std=args.output_std,
+ output_clamping_lower=config.training.output_clamping.lower,
+ output_clamping_upper=config.training.output_clamping.upper,
+ g2m_gnn_type=getattr(args, "g2m_gnn_type", "InteractionNet"),
+ m2g_gnn_type=getattr(args, "m2g_gnn_type", "InteractionNet"),
+ **layers,
+ )
kwargs = dict(
datastore=datastore,
graph_name=args.graph,
@@ -125,6 +176,67 @@ def build_predictor(
return predictor_class(**kwargs)
+def build_forecaster_module(
+ args: Namespace,
+ config: NeuralLAMConfig,
+ datastore: BaseDatastore,
+ predictor: Any,
+) -> tuple[
+ BaseForecaster,
+ type[BaseForecastingModule],
+ dict[str, Any],
+ str,
+]:
+ """Select the forecaster and Lightning module for a predictor.
+
+ Parameters
+ ----------
+ args : Namespace
+ Run arguments, including the deterministic loss selection.
+ config : NeuralLAMConfig
+ Architecture and training objective settings.
+ datastore : BaseDatastore
+ Grid metadata and standardization statistics.
+ predictor : StepPredictor
+ Predictor created by ``build_predictor``.
+
+ Returns
+ -------
+ forecaster : BaseForecaster
+ Deterministic rollout or Graph-EFM variational forecaster.
+ module_class : type
+ Lightning module matching the forecast family.
+ module_kwargs : dict[str, Any]
+ Additional module settings, including evaluation ensemble size.
+ monitor : str
+ Validation objective used for checkpoint selection.
+ """
+ if isinstance(predictor, (GraphEFM, GraphEFMMultiScale)):
+ prob = config.probabilistic
+ forecaster = GraphEFMForecaster(
+ predictor,
+ datastore,
+ config=config,
+ kl_beta=prob.kl_beta,
+ crps_weight=prob.crps_weight,
+ crps_members=prob.crps_members,
+ )
+ return (
+ forecaster,
+ ProbabilisticForecastingModule,
+ {"eval_ensemble_size": prob.eval_ensemble_size},
+ "val_mean_loss",
+ )
+ return (
+ DeterministicARForecaster(
+ predictor, datastore, config=config, loss=args.loss
+ ),
+ DeterministicForecastingModule,
+ {},
+ "val_mean_loss",
+ )
+
+
class AdaptiveHelpFormatter(ArgumentDefaultsHelpFormatter):
"""``--help`` formatter that scales the column width to the terminal."""
@@ -145,9 +257,9 @@ def load_forecasting_module_from_checkpoint(
config: NeuralLAMConfig,
datastore: BaseDatastore,
datastore_boundary: BaseDatastore | None = None,
-) -> DeterministicForecastingModule:
+) -> BaseForecastingModule:
"""
- Reconstruct a DeterministicForecastingModule from a checkpoint without
+ Reconstruct a forecasting module from a checkpoint without
requiring the caller to know the original architecture kwargs.
The checkpoint must have been saved with args in hyper_parameters (i.e.
@@ -168,17 +280,17 @@ def load_forecasting_module_from_checkpoint(
Returns
-------
- DeterministicForecastingModule
+ DeterministicForecastingModule or ProbabilisticForecastingModule
The restored module.
"""
ckpt = torch.load(ckpt_path, weights_only=False)
args = ckpt["hyper_parameters"]["args"]
predictor_class = MODELS[args.model]
predictor = build_predictor(predictor_class, args, config, datastore)
- forecaster = DeterministicARForecaster(
- predictor, datastore, config=config, loss=args.loss
+ forecaster, module_class, _, _ = build_forecaster_module(
+ args, config, datastore, predictor
)
- return DeterministicForecastingModule.load_from_checkpoint(
+ return module_class.load_from_checkpoint(
ckpt_path,
forecaster=forecaster,
datastore=datastore,
@@ -354,7 +466,8 @@ def build_parser() -> ArgumentParser:
"--loss",
type=str,
default="wmse",
- help="Loss function to use, see metric.py",
+ help="Deterministic loss function, see metrics.py. Graph-EFM uses "
+ "a Gaussian likelihood and its probabilistic config objective.",
)
train_group.add_argument(
"--lr", type=float, default=1e-3, help="learning rate"
@@ -678,11 +791,11 @@ def fit(
f"The {model_config.model} model cannot be trained. Run with "
"--eval to evaluate a baseline."
)
- forecaster = DeterministicARForecaster(
- predictor, datastore, config=config, loss=train_config.loss
+ forecaster, module_class, module_kwargs, val_monitor = (
+ build_forecaster_module(hparams, config, datastore, predictor)
)
- model = DeterministicForecastingModule(
+ model = module_class(
forecaster=forecaster,
config=config,
datastore=datastore,
@@ -696,6 +809,7 @@ def fit(
metrics_watch=train_config.metrics_watch,
var_leads_metrics_watch=train_config.var_leads_metrics_watch,
args=hparams,
+ **module_kwargs,
)
prefix = f"eval-{train_config.eval}-" if train_config.eval else "train-"
@@ -721,7 +835,7 @@ def fit(
val_checkpoint = pl.callbacks.ModelCheckpoint(
dirpath=os.path.join(run_dir, "checkpoints"),
filename="min_val_loss",
- monitor="val_mean_loss",
+ monitor=val_monitor,
mode="min",
save_top_k=1,
save_on_train_epoch_end=False,
@@ -739,7 +853,17 @@ def fit(
max_epochs=train_config.epochs,
deterministic=True,
default_root_dir=run_dir,
- strategy="auto",
+ strategy=(
+ "ddp_find_unused_parameters_true"
+ if isinstance(forecaster, GraphEFMForecaster)
+ and (
+ compute_config.num_nodes > 1
+ or (isinstance(devices, list) and len(devices) > 1)
+ or (isinstance(devices, int) and devices > 1)
+ or (devices == "auto" and torch.cuda.device_count() > 1)
+ )
+ else "auto"
+ ),
accelerator=device_name,
num_nodes=compute_config.num_nodes,
devices=devices,
diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py
new file mode 100644
index 000000000..b5d9496be
--- /dev/null
+++ b/tests/test_graph_efm_model.py
@@ -0,0 +1,612 @@
+"""Integration tests for the full Graph-EFM model.
+
+Exercises the pieces that turn the Graph-EFM single-step predictors into a
+trainable model: the ``GraphEFMForecaster`` ELBO objective, its inherited
+ensemble sampling, the ``ProbabilisticForecastingModule`` wrapping, and the
+config-aware assembly path in ``train_model`` (``build_predictor`` /
+``build_forecaster_module``). Predictors are built on the real example
+datastore with a freshly created graph, mirroring
+``tests/test_graph_efm_predictor.py``.
+"""
+
+# Standard library
+from argparse import Namespace
+from pathlib import Path
+
+# Third-party
+import pytest
+import torch
+
+# First-party
+from neural_lam import config as nlconfig
+from neural_lam.create_graph import create_graph_from_datastore
+from neural_lam.models import (
+ GraphEFM,
+ GraphEFMForecaster,
+ GraphEFMMultiScale,
+ ProbabilisticForecastingModule,
+)
+from neural_lam.train_model import build_forecaster_module, build_predictor
+from tests.conftest import init_datastore_example
+
+pytestmark = pytest.mark.requires_real_data
+
+NUM_PAST_FORCING_STEPS = 1
+NUM_FUTURE_FORCING_STEPS = 1
+
+
+def _datastore_and_config(graph_name):
+ """
+ Build the example datastore + config and ensure ``graph_name`` exists.
+
+ Parameters
+ ----------
+ graph_name : str
+ Graph directory name; ``"hierarchical"`` builds a multi-level graph,
+ anything else a flat one.
+
+ Returns
+ -------
+ datastore : BaseDatastore
+ The example ``mdp`` datastore.
+ config : NeuralLAMConfig
+ A configuration selecting that datastore.
+ """
+ datastore = init_datastore_example("mdp")
+ config = nlconfig.NeuralLAMConfig(
+ datastores={
+ "interior": nlconfig.DatastoreSelection(
+ kind=datastore.SHORT_NAME, config_path=str(datastore.root_path)
+ )
+ }
+ )
+
+ hierarchical = graph_name == "hierarchical"
+ n_max_levels = 3 if hierarchical else 1
+ graph_dir_path = Path(datastore.root_path) / "graph" / graph_name
+ if not graph_dir_path.exists():
+ create_graph_from_datastore(
+ datastore=datastore,
+ output_root_path=str(graph_dir_path),
+ hierarchical=hierarchical,
+ n_max_levels=n_max_levels,
+ )
+ return datastore, config
+
+
+def _build_predictor(datastore, graph_name, output_std=False):
+ """
+ Construct a small Graph-EFM predictor for ``graph_name``.
+
+ Parameters
+ ----------
+ datastore : BaseDatastore
+ Datastore to build the predictor on.
+ graph_name : str
+ Graph directory name selecting the flat vs hierarchical variant.
+ output_std : bool, default False
+ Whether the decoder outputs its own std.
+
+ Returns
+ -------
+ BaseGraphEFM
+ The constructed predictor.
+ """
+ if graph_name == "hierarchical":
+ predictor_class = GraphEFM
+ layer_kwargs = {
+ "prior_intra_level_layers": 1,
+ "encoder_intra_level_layers": 1,
+ "decoder_intra_level_layers": 1,
+ }
+ else:
+ predictor_class = GraphEFMMultiScale
+ layer_kwargs = {
+ "prior_m2m_layers": 1,
+ "encoder_m2m_layers": 1,
+ "decoder_m2m_layers": 1,
+ }
+ return predictor_class(
+ datastore=datastore,
+ graph_name=graph_name,
+ hidden_dim=4,
+ hidden_layers=1,
+ latent_dim=4,
+ learn_prior=True,
+ prior_dist="isotropic",
+ num_past_forcing_steps=NUM_PAST_FORCING_STEPS,
+ num_future_forcing_steps=NUM_FUTURE_FORCING_STEPS,
+ output_std=output_std,
+ **layer_kwargs,
+ )
+
+
+def _example_batch(datastore, predictor, batch_size=2, pred_steps=3):
+ """
+ Build a synthetic ``(init_states, forcing_features, target_states)`` batch.
+
+ Parameters
+ ----------
+ datastore : BaseDatastore
+ Datastore providing variable counts.
+ predictor : BaseGraphEFM
+ Predictor providing the grid node count.
+ batch_size : int, default 2
+ Number of samples in the batch.
+ pred_steps : int, default 3
+ Rollout length.
+
+ Returns
+ -------
+ init_states : torch.Tensor
+ Shape ``(B, 2, num_grid_nodes, d_state)``.
+ forcing_features : torch.Tensor
+ Shape ``(B, pred_steps, num_grid_nodes, d_forcing)``.
+ target_states : torch.Tensor
+ Shape ``(B, pred_steps, num_grid_nodes, d_state)``.
+ """
+ num_grid_nodes = predictor.num_grid_nodes
+ d_state = datastore.get_num_data_vars(category="state")
+ d_forcing = datastore.get_num_data_vars(category="forcing") * (
+ NUM_PAST_FORCING_STEPS + NUM_FUTURE_FORCING_STEPS + 1
+ )
+ torch.manual_seed(0)
+ init_states = torch.randn(batch_size, 2, num_grid_nodes, d_state)
+ forcing_features = torch.randn(
+ batch_size, pred_steps, num_grid_nodes, d_forcing
+ )
+ target_states = torch.randn(batch_size, pred_steps, num_grid_nodes, d_state)
+ return init_states, forcing_features, target_states
+
+
+@pytest.mark.parametrize("graph_name", ["1level", "hierarchical"])
+def test_forecaster_forward_and_ensemble_shapes(graph_name):
+ """The forecaster unrolls a prior-sampled rollout and stacks members into
+ an ensemble of the documented shape."""
+ datastore, config = _datastore_and_config(graph_name)
+ predictor = _build_predictor(datastore, graph_name)
+ forecaster = GraphEFMForecaster(predictor, datastore, config=config)
+
+ B, pred_steps, num_members = 2, 3, 4
+ init_states, forcing_features, target_states = _example_batch(
+ datastore, predictor, batch_size=B, pred_steps=pred_steps
+ )
+ d_state = target_states.shape[-1]
+ num_grid_nodes = predictor.num_grid_nodes
+
+ prediction, pred_std = forecaster(
+ init_states, forcing_features, target_states
+ )
+ assert prediction.shape == (B, pred_steps, num_grid_nodes, d_state)
+ assert pred_std is None # output_std=False predictor
+
+ ensemble, per_member_std = forecaster.sample_ensemble(
+ init_states, forcing_features, target_states, num_members=num_members
+ )
+ assert ensemble.shape == (
+ B,
+ num_members,
+ pred_steps,
+ num_grid_nodes,
+ d_state,
+ )
+ assert per_member_std is None
+ # Members carry independent latent samples
+ assert not torch.allclose(ensemble[:, 0], ensemble[:, 1])
+
+
+@pytest.mark.parametrize("graph_name", ["1level", "hierarchical"])
+def test_predictor_posterior_step_contract(graph_name):
+ """Posterior training reuses graph embeddings and can skip the prior."""
+ datastore, _ = _datastore_and_config(graph_name)
+ predictor = _build_predictor(datastore, graph_name)
+ init_states, forcing_features, target_states = _example_batch(
+ datastore, predictor, batch_size=2, pred_steps=1
+ )
+ prev_prev_state, prev_state = init_states[:, 0], init_states[:, 1]
+ forcing, target_state = forcing_features[:, 0], target_states[:, 0]
+ d_state = target_state.shape[-1]
+ num_grid_nodes = predictor.num_grid_nodes
+
+ graph_emb = predictor.embedd_graph(2)
+ assert {"g2m", "m2g", "mesh"} <= set(graph_emb)
+
+ pred_mean, pred_std = predictor(prev_state, prev_prev_state, forcing)
+ assert pred_mean.shape == (2, num_grid_nodes, d_state)
+ assert pred_std is None
+
+ # Training path with KL: both distributions present
+ prior, posterior, _, _ = predictor.posterior_step(
+ prev_state,
+ prev_prev_state,
+ forcing,
+ target_state,
+ graph_emb,
+ compute_prior=True,
+ )
+ assert prior is not None
+ assert posterior is not None
+
+ # Training path without KL: prior skipped
+ prior, posterior, _, _ = predictor.posterior_step(
+ prev_state,
+ prev_prev_state,
+ forcing,
+ target_state,
+ graph_emb,
+ compute_prior=False,
+ )
+ assert prior is None
+ assert posterior is not None
+
+
+def test_predictor_clamps_predicted_mean():
+ """With output clamping configured for a feature, Graph-EFM keeps the
+ predicted mean for that feature within the configured bounds, clamping it
+ like the deterministic models do."""
+ datastore, _ = _datastore_and_config("1level")
+ state_names = datastore.get_vars_names(category="state")
+ lower, upper = -0.5, 0.5
+ predictor = GraphEFMMultiScale(
+ datastore=datastore,
+ graph_name="1level",
+ hidden_dim=4,
+ hidden_layers=1,
+ latent_dim=4,
+ prior_m2m_layers=1,
+ encoder_m2m_layers=1,
+ decoder_m2m_layers=1,
+ output_clamping_lower={state_names[0]: lower},
+ output_clamping_upper={state_names[0]: upper},
+ )
+ # The first state feature has a two-sided (sigmoid) clamp registered
+ assert predictor.clamp_lower_upper_idx.tolist() == [0]
+ lower_n = (lower - predictor.state_mean[0]) / predictor.state_std[0]
+ upper_n = (upper - predictor.state_mean[0]) / predictor.state_std[0]
+
+ B = 2
+ num_grid_nodes = predictor.num_grid_nodes
+ d_state = len(state_names)
+ d_forcing = datastore.get_num_data_vars(category="forcing") * (
+ NUM_PAST_FORCING_STEPS + NUM_FUTURE_FORCING_STEPS + 1
+ )
+ torch.manual_seed(0)
+ prev_state = torch.randn(B, num_grid_nodes, d_state)
+ # The current value of the clamped feature must be within its bounds so
+ # the inverse clamp is finite; the midpoint is a safe choice.
+ prev_state[..., 0] = (lower_n + upper_n) / 2
+ prev_prev_state = torch.randn(B, num_grid_nodes, d_state)
+ forcing = torch.randn(B, num_grid_nodes, d_forcing)
+
+ pred_mean, _ = predictor(prev_state, prev_prev_state, forcing)
+
+ clamped_feature = pred_mean[..., 0]
+ assert torch.all(clamped_feature > lower_n)
+ assert torch.all(clamped_feature < upper_n)
+
+
+def test_hierarchical_zero_intra_level_layers_runs():
+ """A hierarchical GraphEFM with no intra-level layers uses an empty m2m
+ placeholder; forward must still run (regression for m2m handling)."""
+ datastore, _ = _datastore_and_config("hierarchical")
+ predictor = GraphEFM(
+ datastore=datastore,
+ graph_name="hierarchical",
+ hidden_dim=4,
+ hidden_layers=1,
+ latent_dim=4,
+ prior_intra_level_layers=0,
+ encoder_intra_level_layers=0,
+ decoder_intra_level_layers=0,
+ )
+ assert not predictor.embedd_m2m
+
+ B = 2
+ num_grid_nodes = predictor.num_grid_nodes
+ d_state = datastore.get_num_data_vars(category="state")
+ d_forcing = datastore.get_num_data_vars(category="forcing") * (
+ NUM_PAST_FORCING_STEPS + NUM_FUTURE_FORCING_STEPS + 1
+ )
+ torch.manual_seed(0)
+ prev_state = torch.randn(B, num_grid_nodes, d_state)
+ prev_prev_state = torch.randn(B, num_grid_nodes, d_state)
+ forcing = torch.randn(B, num_grid_nodes, d_forcing)
+
+ pred_mean, _ = predictor(prev_state, prev_prev_state, forcing)
+ assert pred_mean.shape == (B, num_grid_nodes, d_state)
+
+
+@pytest.mark.parametrize("graph_name", ["1level", "hierarchical"])
+def test_elbo_training_loss_gradient_flow(graph_name):
+ """compute_training_loss returns a finite scalar ELBO with likelihood/KL
+ components, and gradients flow back into the predictor."""
+ datastore, config = _datastore_and_config(graph_name)
+ predictor = _build_predictor(datastore, graph_name)
+ forecaster = GraphEFMForecaster(
+ predictor, datastore, config=config, kl_beta=1.0
+ )
+
+ init_states, forcing_features, target_states = _example_batch(
+ datastore, predictor
+ )
+ interior_mask_bool = forecaster.interior_mask[0, :, 0].to(torch.bool)
+
+ torch.manual_seed(0)
+ batch_loss, loss_components = forecaster.compute_training_loss(
+ init_states,
+ forcing_features,
+ target_states,
+ interior_mask_bool=interior_mask_bool,
+ )
+
+ assert batch_loss.shape == ()
+ assert torch.isfinite(batch_loss)
+ assert set(loss_components) == {"elbo_likelihood", "elbo_kl", "elbo"}
+ assert (loss_components["elbo_kl"] >= 0).all()
+
+ batch_loss.backward()
+ grads = [p.grad for p in predictor.parameters() if p.grad is not None]
+ assert grads, "no gradients reached the predictor"
+ assert any(torch.any(g != 0) for g in grads)
+
+
+@pytest.mark.parametrize("graph_name", ["1level", "hierarchical"])
+def test_elbo_kl_beta_zero_skips_kl(graph_name):
+ """With kl_beta=0 the loss is the negative likelihood alone and no KL
+ component is reported (pure auto-encoder training)."""
+ datastore, config = _datastore_and_config(graph_name)
+ predictor = _build_predictor(datastore, graph_name)
+ forecaster = GraphEFMForecaster(
+ predictor, datastore, config=config, kl_beta=0.0
+ )
+
+ init_states, forcing_features, target_states = _example_batch(
+ datastore, predictor
+ )
+ interior_mask_bool = forecaster.interior_mask[0, :, 0].to(torch.bool)
+
+ torch.manual_seed(0)
+ batch_loss, loss_components = forecaster.compute_training_loss(
+ init_states,
+ forcing_features,
+ target_states,
+ interior_mask_bool=interior_mask_bool,
+ )
+
+ assert set(loss_components) == {"elbo_likelihood"}
+ torch.testing.assert_close(batch_loss, -loss_components["elbo_likelihood"])
+ batch_loss.backward() # still differentiable
+
+
+@pytest.mark.requires_training
+def test_module_training_and_validation_steps():
+ """The ProbabilisticForecastingModule delegates training to the forecaster
+ ELBO and scores an ensemble mean during validation."""
+ datastore, config = _datastore_and_config("1level")
+ predictor = _build_predictor(datastore, "1level")
+ forecaster = GraphEFMForecaster(
+ predictor, datastore, config=config, kl_beta=1.0
+ )
+ model = ProbabilisticForecastingModule(
+ forecaster=forecaster,
+ config=config,
+ datastore=datastore,
+ eval_ensemble_size=2,
+ )
+
+ B, pred_steps = 2, 3
+ init_states, forcing_features, target_states = _example_batch(
+ datastore, predictor, batch_size=B, pred_steps=pred_steps
+ )
+ batch_times = torch.zeros(B, pred_steps)
+ batch = (init_states, target_states, forcing_features, None, batch_times)
+
+ torch.manual_seed(0)
+ train_loss = model.training_step(batch)
+ assert train_loss.shape == ()
+ assert torch.isfinite(train_loss)
+
+ model.validation_step(batch, 0)
+ (entry_mses,) = model.val_metrics["ens_mse"]
+ d_state = target_states.shape[-1]
+ assert entry_mses.shape == (B, pred_steps, d_state)
+ assert torch.all(torch.isfinite(entry_mses))
+
+
+@pytest.mark.parametrize(
+ "model_name, predictor_class, graph_name",
+ [
+ ("graph_efm", GraphEFM, "hierarchical"),
+ ("graph_efm_ms", GraphEFMMultiScale, "1level"),
+ ],
+)
+def test_train_model_assembly_selects_probabilistic_path(
+ model_name, predictor_class, graph_name
+):
+ """train_model's build_predictor/build_forecaster_module route the
+ graph_efm* models through the probabilistic assembly, reading the
+ Graph-EFM hyperparameters from the ``probabilistic`` config section and
+ producing the right predictor, forecaster, module class and checkpoint
+ monitor."""
+ datastore, _ = _datastore_and_config(graph_name)
+ config = nlconfig.NeuralLAMConfig(
+ datastores={
+ "interior": nlconfig.DatastoreSelection(
+ kind=datastore.SHORT_NAME, config_path=str(datastore.root_path)
+ )
+ },
+ probabilistic=nlconfig.ProbabilisticConfig(
+ latent_dim=4,
+ prior_layers=1,
+ encoder_layers=1,
+ decoder_layers=1,
+ kl_beta=0.5,
+ eval_ensemble_size=3,
+ ),
+ )
+ args = Namespace(
+ model=model_name,
+ graph=graph_name,
+ hidden_dim=4,
+ hidden_layers=1,
+ num_past_forcing_steps=NUM_PAST_FORCING_STEPS,
+ num_future_forcing_steps=NUM_FUTURE_FORCING_STEPS,
+ output_std=False,
+ g2m_gnn_type="InteractionNet",
+ m2g_gnn_type="InteractionNet",
+ loss="mse",
+ )
+
+ predictor = build_predictor(predictor_class, args, config, datastore)
+ assert isinstance(predictor, predictor_class)
+ # Hyperparameters came from config.probabilistic, not the CLI args
+ assert predictor.latent_dim == 4
+
+ forecaster, module_class, module_kwargs, val_monitor = (
+ build_forecaster_module(args, config, datastore, predictor)
+ )
+ assert isinstance(forecaster, GraphEFMForecaster)
+ assert forecaster.kl_beta == 0.5
+ assert module_class is ProbabilisticForecastingModule
+ assert module_kwargs == {"eval_ensemble_size": 3}
+ assert val_monitor == "val_mean_loss"
+
+
+@pytest.mark.requires_training
+@pytest.mark.parametrize(
+ "graph_name,output_std",
+ [
+ ("1level", False),
+ ("1level", True),
+ ("hierarchical", False),
+ ],
+)
+def test_training_checkpoint_round_trip(graph_name, output_std, tmp_path):
+ """Train both graph families and reload their checkpoints."""
+ # Third-party
+ import pytorch_lightning as pl
+ from torch.utils.data import DataLoader, TensorDataset
+
+ # First-party
+ from neural_lam.train_model import load_forecasting_module_from_checkpoint
+
+ datastore, config = _datastore_and_config(graph_name)
+ config.probabilistic = nlconfig.ProbabilisticConfig(
+ latent_dim=4,
+ prior_layers=1,
+ encoder_layers=1,
+ decoder_layers=1,
+ crps_weight=0.1,
+ eval_ensemble_size=2,
+ )
+ args = Namespace(
+ model="graph_efm" if graph_name == "hierarchical" else "graph_efm_ms",
+ graph=graph_name,
+ hidden_dim=4,
+ hidden_layers=1,
+ num_past_forcing_steps=1,
+ num_future_forcing_steps=1,
+ output_std=output_std,
+ loss="wmse",
+ )
+ predictor = build_predictor(
+ GraphEFM if graph_name == "hierarchical" else GraphEFMMultiScale,
+ args,
+ config,
+ datastore,
+ )
+ forecaster, module_class, module_kwargs, _ = build_forecaster_module(
+ args,
+ config,
+ datastore,
+ predictor,
+ )
+ model = module_class(
+ forecaster,
+ config,
+ datastore,
+ args=args,
+ **module_kwargs,
+ )
+ initial, forcing, target = _example_batch(datastore, predictor, 2, 2)
+ dataset = TensorDataset(
+ initial,
+ target,
+ forcing,
+ torch.empty(2, 2, predictor.num_grid_nodes, 0),
+ torch.zeros(2, 2),
+ )
+ trainer = pl.Trainer(
+ accelerator="cpu",
+ devices=1,
+ max_steps=1,
+ logger=False,
+ enable_checkpointing=False,
+ enable_progress_bar=False,
+ enable_model_summary=False,
+ num_sanity_val_steps=0,
+ )
+ trainer.fit(model, train_dataloaders=DataLoader(dataset, batch_size=2))
+ assert trainer.global_step == 1
+ checkpoint = tmp_path / "graph_efm.ckpt"
+ trainer.save_checkpoint(checkpoint)
+ restored = load_forecasting_module_from_checkpoint(
+ str(checkpoint), config, datastore
+ )
+ assert isinstance(restored, ProbabilisticForecastingModule)
+ assert restored.eval_ensemble_size == 2
+ torch.manual_seed(4)
+ expected, expected_std = model.forecaster(initial, forcing, target)
+ torch.manual_seed(4)
+ actual, actual_std = restored.forecaster(initial, forcing, target)
+ torch.testing.assert_close(actual, expected)
+ if output_std:
+ torch.testing.assert_close(actual_std, expected_std)
+
+
+def test_posterior_and_prior_share_increment_rescaling(monkeypatch):
+ """Prior and posterior sampling share increment rescaling."""
+ datastore, _ = _datastore_and_config("1level")
+ predictor = _build_predictor(datastore, "1level", output_std=True)
+ initial, forcing, target = _example_batch(datastore, predictor, 2, 1)
+ previous = initial[:, 1]
+ monkeypatch.setattr(
+ predictor.decoder,
+ "forward",
+ lambda *args: (
+ torch.ones_like(previous),
+ torch.full_like(previous, 0.5),
+ ),
+ )
+ predictor.diff_mean.fill_(2.0)
+ predictor.diff_std.fill_(3.0)
+ prediction, std = predictor(previous, initial[:, 0], forcing[:, 0])
+ _, _, posterior_prediction, posterior_std = predictor.posterior_step(
+ previous,
+ initial[:, 0],
+ forcing[:, 0],
+ target[:, 0],
+ )
+ torch.testing.assert_close(prediction, previous + 5)
+ torch.testing.assert_close(posterior_prediction, previous + 5)
+ torch.testing.assert_close(std, posterior_std)
+
+
+def test_decoder_std_remains_positive_for_large_negative_logits():
+ """Decoder underflow cannot produce zero Gaussian observation scales."""
+ datastore, _ = _datastore_and_config("1level")
+ predictor = _build_predictor(datastore, "1level", output_std=True)
+ num_vars = datastore.get_num_data_vars("state")
+ linear = torch.nn.Linear(4, 2 * num_vars)
+ with torch.no_grad():
+ linear.weight.zero_()
+ linear.bias.zero_()
+ linear.bias[num_vars:] = -1000
+ predictor.decoder.param_map = linear
+ initial, forcing, _ = _example_batch(datastore, predictor, 2, 1)
+ prediction, std = predictor(initial[:, 1], initial[:, 0], forcing[:, 0])
+ assert torch.all(std > 0)
+ nll = -torch.distributions.Normal(prediction, std).log_prob(prediction)
+ assert torch.isfinite(nll).all()
+ nll.sum().backward()
+ assert torch.isfinite(linear.bias.grad).all()
diff --git a/tests/test_graph_efm_objective.py b/tests/test_graph_efm_objective.py
new file mode 100644
index 000000000..ce605d0bf
--- /dev/null
+++ b/tests/test_graph_efm_objective.py
@@ -0,0 +1,172 @@
+"""Exact objective regressions independent of graph construction and data."""
+
+# Standard library
+from unittest.mock import Mock
+
+# Third-party
+import pytest
+import torch
+from torch import nn
+from torch.distributions import Normal
+
+# First-party
+from neural_lam.models.forecasters.graph_efm import GraphEFMForecaster
+from tests.dummy_datastore import DummyDatastore
+
+
+class ObjectivePredictor(nn.Module):
+ """Expose known Gaussian distributions for objective tests."""
+
+ predicts_std = True
+
+ def __init__(self):
+ super().__init__()
+ self.mean = nn.Parameter(torch.tensor(0.25))
+ self.log_std = nn.Parameter(torch.tensor(0.0))
+ self.states = []
+ self.prior_flags = []
+
+ def embedd_graph(self, batch_size):
+ return {}
+
+ def posterior_step(
+ self, prev, prev_prev, forcing, target, graph, compute_prior=True
+ ):
+ self.states.append(prev.detach().clone())
+ self.prior_flags.append(compute_prior)
+ shape = (prev.shape[0], 2, 1)
+ posterior = Normal(self.mean.expand(shape), torch.ones(shape))
+ prior = (
+ Normal(torch.zeros(shape), torch.ones(shape))
+ if compute_prior
+ else None
+ )
+ return (
+ prior,
+ posterior,
+ self.mean.expand_as(prev),
+ self.log_std.exp().expand_as(prev),
+ )
+
+
+@pytest.fixture
+def objective():
+ datastore = DummyDatastore(n_grid_points=25)
+ predictor = ObjectivePredictor()
+ forecaster = GraphEFMForecaster(predictor, datastore, kl_beta=0.3)
+ mask = forecaster.interior_mask[0, :, 0].bool()
+ init = torch.zeros(2, 2, 25, 5)
+ forcing = torch.zeros(2, 3, 25, 6)
+ target = torch.ones(2, 3, 25, 5)
+ return forecaster, predictor, mask, init, forcing, target
+
+
+def test_gaussian_elbo_and_boundary_rollout(objective):
+ forecaster, predictor, mask, init, forcing, target = objective
+ loss, logs = forecaster.compute_training_loss(init, forcing, target, mask)
+ expected_nll = -Normal(torch.tensor(0.25), torch.tensor(1.0)).log_prob(
+ torch.tensor(1.0)
+ )
+ expected_nll = expected_nll * mask.sum() * 5 * 3
+ expected_kl = torch.tensor(0.5 * 0.25**2 * 2 * 3)
+ torch.testing.assert_close(loss, expected_nll + 0.3 * expected_kl)
+ torch.testing.assert_close(logs["elbo_kl"], expected_kl)
+ assert len(predictor.states) == 3
+ torch.testing.assert_close(
+ predictor.states[1][:, ~mask], target[:, 0, ~mask]
+ )
+ torch.testing.assert_close(
+ predictor.states[1][:, mask], torch.full_like(target[:, 0, mask], 0.25)
+ )
+ loss.backward()
+ assert predictor.mean.grad.abs() > 0
+ assert predictor.log_std.grad > 0
+
+
+@pytest.mark.parametrize("members", [2, 5])
+def test_crps_matches_pairwise_fair_estimator(objective, members):
+ forecaster, predictor, mask, init, forcing, target = objective
+ forecaster.kl_beta = 0
+ forecaster.crps_weight = 0.7
+ forecaster.crps_members = members
+ torch.manual_seed(7)
+ ensemble = torch.randn(2, members, 3, 25, 5, requires_grad=True)
+ forecaster.sample_ensemble = Mock(return_value=(ensemble, None))
+ loss, logs = forecaster.compute_training_loss(init, forcing, target, mask)
+ first = (ensemble - target.unsqueeze(1)).abs().mean(1)
+ pairwise = (ensemble.unsqueeze(2) - ensemble.unsqueeze(1)).abs().sum((1, 2))
+ expected = first - pairwise / (2 * members * (members - 1))
+ expected = expected[:, :, mask].sum((1, 2, 3)).mean()
+ torch.testing.assert_close(logs["crps"], expected)
+ torch.testing.assert_close(loss, -logs["elbo_likelihood"] + 0.7 * expected)
+ assert not any(predictor.prior_flags)
+ forecaster.sample_ensemble.assert_called_once_with(
+ init, forcing, target, members
+ )
+ loss.backward()
+ assert ensemble.grad.abs().sum() > 0
+
+
+def test_zero_crps_skips_prior_trajectories(objective):
+ forecaster, predictor, mask, init, forcing, target = objective
+ forecaster.kl_beta = 0
+ forecaster.sample_ensemble = Mock(
+ side_effect=AssertionError("unexpected sampling")
+ )
+ forecaster.compute_training_loss(init, forcing, target, mask)
+ assert not any(predictor.prior_flags)
+ forecaster.sample_ensemble.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"kl_beta": -1},
+ {"kl_beta": float("nan")},
+ {"crps_weight": -1},
+ {"crps_weight": float("inf")},
+ {"crps_members": 1},
+ ],
+)
+def test_invalid_objective_settings(kwargs):
+ with pytest.raises(ValueError, match="must be"):
+ GraphEFMForecaster(
+ ObjectivePredictor(), DummyDatastore(n_grid_points=25), **kwargs
+ )
+
+
+def test_probabilistic_yaml_round_trip():
+ """Optional Graph-EFM settings survive experiment configuration loading."""
+ # First-party
+ from neural_lam.config import NeuralLAMConfig, ProbabilisticConfig
+
+ config = NeuralLAMConfig.from_yaml("""
+ datastores:
+ interior:
+ kind: mdp
+ config_path: danra.yaml
+ probabilistic:
+ latent_dim: 8
+ prior_layers: 1
+ encoder_layers: 2
+ decoder_layers: 3
+ learn_prior: false
+ prior_dist: diagonal
+ kl_beta: 0.5
+ crps_weight: 0.2
+ crps_members: 4
+ eval_ensemble_size: 6
+ """)
+ assert config.probabilistic == ProbabilisticConfig(
+ latent_dim=8,
+ prior_layers=1,
+ encoder_layers=2,
+ decoder_layers=3,
+ learn_prior=False,
+ prior_dist="diagonal",
+ kl_beta=0.5,
+ crps_weight=0.2,
+ crps_members=4,
+ eval_ensemble_size=6,
+ )
+ assert NeuralLAMConfig.from_yaml(config.to_yaml()) == config
From ec06d632bfb2a48d58f5516c1c4714dfd07f7b90 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Tue, 3 Nov 2026 19:43:49 +0530
Subject: [PATCH 02/41] Fix Graph-EFM checkpoint reconstruction and scoring
reuse
Restore probabilistic architecture settings from checkpoints, share fair CRPS scoring, and warn about ignored deterministic options. Name Graph-EFM runs using configured layer depths, simplify module assembly, and allow callers to reuse graph embeddings.
---
CHANGELOG.md | 2 +
neural_lam/metrics.py | 61 +++++++
neural_lam/models/forecasters/graph_efm.py | 22 +--
.../models/step_predictors/graph/graph_efm.py | 8 +-
neural_lam/train_model.py | 54 ++++--
tests/test_ensemble_metrics.py | 62 +++++++
tests/test_graph_efm_model.py | 165 +++++++++++++++++-
7 files changed, 340 insertions(+), 34 deletions(-)
create mode 100644 tests/test_ensemble_metrics.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d27db59b..06b651cf1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add Graph-EFM forecaster training with Gaussian ELBO and optional fair CRPS,
probabilistic configuration, CLI assembly and checkpoint loading.
+ Restore saved probabilistic settings, share fair CRPS scoring, warn about
+ ignored CLI options and name runs using Graph-EFM layer counts.
[\#712](https://github.com/mllam/neural-lam/pull/712) @Sir-Sloth-The-Lazy
- Add deterministic and probabilistic forecaster/module interfaces with
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 340060f05..b786f620b 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -393,6 +393,67 @@ def crps_gauss(
)
+def crps_ens_fair(
+ ensemble: torch.Tensor,
+ target: torch.Tensor,
+ mask: torch.Tensor | None = None,
+ average_grid: bool = True,
+ sum_vars: bool = True,
+ ens_dim: int = 1,
+) -> torch.Tensor:
+ """Compute fair CRPS from independent ensemble samples.
+
+ Uses sorted ranks to compute the pairwise spread term with memory
+ linear in the number of members. Gradients are retained for training.
+
+ Parameters
+ ----------
+ ensemble : 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 independent members are required.
+ target : torch.Tensor
+ Shape ``(..., num_grid_nodes, num_state_vars)``. Ground truth.
+ 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 ``ensemble``. Default 1.
+
+ Returns
+ -------
+ torch.Tensor
+ CRPS with the ensemble dimension removed, reduced according to
+ ``mask``, ``average_grid`` and ``sum_vars`` as for ``nll``.
+
+ Raises
+ ------
+ ValueError
+ If there are fewer than two members.
+ """
+ num_members = ensemble.shape[ens_dim]
+ if num_members < 2:
+ raise ValueError("Fair CRPS requires at least two ensemble members")
+ first = (ensemble - target.unsqueeze(ens_dim)).abs().mean(dim=ens_dim)
+ ordered = ensemble.sort(dim=ens_dim).values
+ rank_shape = [1] * ensemble.ndim
+ rank_shape[ens_dim] = num_members
+ ranks = torch.arange(
+ 1,
+ num_members + 1,
+ device=ensemble.device,
+ dtype=ensemble.dtype,
+ ).view(rank_shape)
+ spread = ((2 * ranks - num_members - 1) * ordered).sum(dim=ens_dim)
+ entry_crps = first - spread / (num_members * (num_members - 1))
+ return mask_and_reduce_metric(
+ entry_crps, mask=mask, average_grid=average_grid, sum_vars=sum_vars
+ )
+
+
DEFINED_METRICS: dict[str, Callable[..., torch.Tensor]] = {
"mse": mse,
"mae": mae,
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
index 9dc7fc28e..13d353b78 100644
--- a/neural_lam/models/forecasters/graph_efm.py
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -241,22 +241,14 @@ def compute_training_loss(
ensemble, _ = self.sample_ensemble(
init_states, forcing_features, target_states, self.crps_members
)
- # Fair CRPS uses independent prior trajectories.
- first = (ensemble - target_states.unsqueeze(1)).abs().mean(dim=1)
- ordered = ensemble.sort(dim=1).values
- ranks = torch.arange(
- 1,
- self.crps_members + 1,
- device=ensemble.device,
- dtype=ensemble.dtype,
- ).view(1, -1, 1, 1, 1)
- spread = ((2 * ranks - self.crps_members - 1) * ordered).sum(dim=1)
- entry_crps = first - spread / (
- self.crps_members * (self.crps_members - 1)
- )
- crps = (
- entry_crps[:, :, interior_mask_bool].sum(dim=(1, 2, 3)).mean()
+ entry_crps = metrics.crps_ens_fair(
+ ensemble,
+ target_states,
+ mask=interior_mask_bool,
+ average_grid=False,
+ sum_vars=False,
)
+ crps = entry_crps.sum(dim=(1, 2, 3)).mean()
batch_loss = batch_loss + self.crps_weight * crps
loss_components["crps"] = crps
return batch_loss, loss_components
diff --git a/neural_lam/models/step_predictors/graph/graph_efm.py b/neural_lam/models/step_predictors/graph/graph_efm.py
index d77cc411c..bde2b523c 100644
--- a/neural_lam/models/step_predictors/graph/graph_efm.py
+++ b/neural_lam/models/step_predictors/graph/graph_efm.py
@@ -527,6 +527,7 @@ def forward(
prev_state: torch.Tensor,
prev_prev_state: torch.Tensor,
forcing: torch.Tensor,
+ graph_emb: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""
Sample one time step prediction: embed features, sample the latent
@@ -542,6 +543,10 @@ def forward(
Shape ``(B, num_grid_nodes, num_state_vars)``. ``X_{t-1}``.
forcing : torch.Tensor
Shape ``(B, num_grid_nodes, num_windowed_forcing_vars)``.
+ graph_emb : dict[str, Any] or None, optional
+ Static embeddings from ``embedd_graph``. Reuse within one
+ rollout to avoid embedding the graph at each step. Computed
+ on demand when omitted; no embeddings persist across batches.
Returns
-------
@@ -555,7 +560,8 @@ def forward(
# embed all features
grid_prev_emb = self.embedd_grid(prev_state, prev_prev_state, forcing)
- graph_emb = self.embedd_graph(prev_state.shape[0])
+ if graph_emb is None:
+ graph_emb = self.embedd_graph(prev_state.shape[0])
# Compute prior
prior_dist = self.prior_model(
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index 4fcdcb049..6cb81e321 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -126,6 +126,24 @@ def build_predictor(
Predictor configured for its graph family.
"""
if issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)):
+ defaults = ModelConfig()
+ ignored = {
+ name: getattr(defaults, name)
+ for name in (
+ "processor_layers",
+ "mesh_aggr",
+ "mesh_up_gnn_type",
+ "mesh_down_gnn_type",
+ )
+ }
+ ignored["loss"] = TrainRunConfig().loss
+ for name, default in ignored.items():
+ if getattr(args, name, default) != default:
+ logger.warning(
+ "--{} has no effect for Graph-EFM; use the "
+ "probabilistic configuration section instead.",
+ name,
+ )
prob = config.probabilistic
prefix = (
"intra_level" if issubclass(predictor_class, GraphEFM) else "m2m"
@@ -185,7 +203,6 @@ def build_forecaster_module(
BaseForecaster,
type[BaseForecastingModule],
dict[str, Any],
- str,
]:
"""Select the forecaster and Lightning module for a predictor.
@@ -208,8 +225,6 @@ def build_forecaster_module(
Lightning module matching the forecast family.
module_kwargs : dict[str, Any]
Additional module settings, including evaluation ensemble size.
- monitor : str
- Validation objective used for checkpoint selection.
"""
if isinstance(predictor, (GraphEFM, GraphEFMMultiScale)):
prob = config.probabilistic
@@ -225,7 +240,6 @@ def build_forecaster_module(
forecaster,
ProbabilisticForecastingModule,
{"eval_ensemble_size": prob.eval_ensemble_size},
- "val_mean_loss",
)
return (
DeterministicARForecaster(
@@ -233,7 +247,6 @@ def build_forecaster_module(
),
DeterministicForecastingModule,
{},
- "val_mean_loss",
)
@@ -264,7 +277,9 @@ def load_forecasting_module_from_checkpoint(
The checkpoint must have been saved with args in hyper_parameters (i.e.
created via train_model.main), so that model class and architecture kwargs
- can be recovered automatically.
+ can be recovered automatically. Graph-EFM probabilistic settings are
+ restored from the saved config, falling back to the supplied config
+ only for checkpoints without those settings.
Parameters
----------
@@ -286,8 +301,16 @@ def load_forecasting_module_from_checkpoint(
ckpt = torch.load(ckpt_path, weights_only=False)
args = ckpt["hyper_parameters"]["args"]
predictor_class = MODELS[args.model]
+ is_graph_efm = issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale))
+ if is_graph_efm:
+ saved_config = ckpt["hyper_parameters"].get("config")
+ saved_probabilistic = getattr(saved_config, "probabilistic", None)
+ if saved_probabilistic is not None:
+ config = dataclasses.replace(
+ config, probabilistic=saved_probabilistic
+ )
predictor = build_predictor(predictor_class, args, config, datastore)
- forecaster, module_class, _, _ = build_forecaster_module(
+ forecaster, module_class, _ = build_forecaster_module(
args, config, datastore, predictor
)
return module_class.load_from_checkpoint(
@@ -296,6 +319,7 @@ def load_forecasting_module_from_checkpoint(
datastore=datastore,
datastore_boundary=datastore_boundary,
weights_only=False,
+ **({"config": config} if is_graph_efm else {}),
)
@@ -791,8 +815,8 @@ def fit(
f"The {model_config.model} model cannot be trained. Run with "
"--eval to evaluate a baseline."
)
- forecaster, module_class, module_kwargs, val_monitor = (
- build_forecaster_module(hparams, config, datastore, predictor)
+ forecaster, module_class, module_kwargs = build_forecaster_module(
+ hparams, config, datastore, predictor
)
model = module_class(
@@ -816,9 +840,17 @@ def fit(
if logging_config.logger_run_name:
run_name = logging_config.logger_run_name
else:
+ if isinstance(forecaster, GraphEFMForecaster):
+ prob = config.probabilistic
+ layers = (
+ f"p{prob.prior_layers}-e{prob.encoder_layers}"
+ f"-d{prob.decoder_layers}"
+ )
+ else:
+ layers = str(model_config.processor_layers)
run_name = (
f"{prefix}{model_config.model}-"
- f"{model_config.processor_layers}x{model_config.hidden_dim}-"
+ f"{layers}x{model_config.hidden_dim}-"
f"{time.strftime('%m_%d_%H')}-{random_run_id:04d}"
)
@@ -835,7 +867,7 @@ def fit(
val_checkpoint = pl.callbacks.ModelCheckpoint(
dirpath=os.path.join(run_dir, "checkpoints"),
filename="min_val_loss",
- monitor=val_monitor,
+ monitor="val_mean_loss",
mode="min",
save_top_k=1,
save_on_train_epoch_end=False,
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
new file mode 100644
index 000000000..ef1f04389
--- /dev/null
+++ b/tests/test_ensemble_metrics.py
@@ -0,0 +1,62 @@
+"""Numerical and reduction checks for reusable fair ensemble CRPS."""
+
+# Third-party
+import pytest
+import torch
+
+# First-party
+from neural_lam.metrics import crps_ens_fair, mask_and_reduce_metric
+
+
+@pytest.mark.parametrize("members", [2, 3, 5])
+@pytest.mark.parametrize("ens_dim", [0, 1, -4])
+@pytest.mark.parametrize(
+ "average_grid,sum_vars",
+ [
+ (False, False),
+ (False, True),
+ (True, False),
+ (True, True),
+ ],
+)
+@pytest.mark.parametrize("masked", [False, True])
+def test_fair_crps_matches_pairwise_reductions(
+ members,
+ ens_dim,
+ average_grid,
+ sum_vars,
+ masked,
+):
+ """Sorted scoring matches pairwise scoring for every supported reduction."""
+ torch.manual_seed(6)
+ ensemble = torch.randn(2, members, 3, 4, 2, dtype=torch.float64)
+ target = torch.randn(2, 3, 4, 2, dtype=torch.float64)
+ mask = torch.tensor([True, False, True, False]) if masked else None
+ first = (ensemble - target.unsqueeze(1)).abs().mean(dim=1)
+ pairs = (ensemble.unsqueeze(2) - ensemble.unsqueeze(1)).abs().sum((1, 2))
+ expected = first - pairs / (2 * members * (members - 1))
+ expected = mask_and_reduce_metric(expected, mask, average_grid, sum_vars)
+ actual = crps_ens_fair(
+ ensemble.movedim(1, ens_dim),
+ target,
+ mask=mask,
+ average_grid=average_grid,
+ sum_vars=sum_vars,
+ ens_dim=ens_dim,
+ )
+ torch.testing.assert_close(actual, expected)
+
+
+def test_fair_crps_retains_gradients():
+ """Ensemble objectives can differentiate through reusable scoring."""
+ ensemble = torch.tensor([[[[0.0]], [[2.0]], [[3.0]]]], requires_grad=True)
+ target = torch.tensor([[[1.0]]])
+ crps_ens_fair(ensemble, target).sum().backward()
+ assert torch.isfinite(ensemble.grad).all()
+ assert ensemble.grad.abs().sum() > 0
+
+
+@pytest.mark.parametrize("members", [0, 1])
+def test_fair_crps_rejects_insufficient_members(members):
+ with pytest.raises(ValueError, match="at least two"):
+ crps_ens_fair(torch.zeros(2, members, 4, 3), torch.zeros(2, 4, 3))
diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py
index b5d9496be..9337f0ac3 100644
--- a/tests/test_graph_efm_model.py
+++ b/tests/test_graph_efm_model.py
@@ -462,14 +462,13 @@ def test_train_model_assembly_selects_probabilistic_path(
# Hyperparameters came from config.probabilistic, not the CLI args
assert predictor.latent_dim == 4
- forecaster, module_class, module_kwargs, val_monitor = (
- build_forecaster_module(args, config, datastore, predictor)
+ forecaster, module_class, module_kwargs = build_forecaster_module(
+ args, config, datastore, predictor
)
assert isinstance(forecaster, GraphEFMForecaster)
assert forecaster.kl_beta == 0.5
assert module_class is ProbabilisticForecastingModule
assert module_kwargs == {"eval_ensemble_size": 3}
- assert val_monitor == "val_mean_loss"
@pytest.mark.requires_training
@@ -492,10 +491,10 @@ def test_training_checkpoint_round_trip(graph_name, output_std, tmp_path):
datastore, config = _datastore_and_config(graph_name)
config.probabilistic = nlconfig.ProbabilisticConfig(
- latent_dim=4,
+ latent_dim=8,
prior_layers=1,
encoder_layers=1,
- decoder_layers=1,
+ decoder_layers=2,
crps_weight=0.1,
eval_ensemble_size=2,
)
@@ -515,7 +514,7 @@ def test_training_checkpoint_round_trip(graph_name, output_std, tmp_path):
config,
datastore,
)
- forecaster, module_class, module_kwargs, _ = build_forecaster_module(
+ forecaster, module_class, module_kwargs = build_forecaster_module(
args,
config,
datastore,
@@ -550,9 +549,26 @@ def test_training_checkpoint_round_trip(graph_name, output_std, tmp_path):
assert trainer.global_step == 1
checkpoint = tmp_path / "graph_efm.ckpt"
trainer.save_checkpoint(checkpoint)
+ caller_config = nlconfig.NeuralLAMConfig(datastores=config.datastores)
restored = load_forecasting_module_from_checkpoint(
- str(checkpoint), config, datastore
+ str(checkpoint), caller_config, datastore
+ )
+ assert caller_config.probabilistic == nlconfig.ProbabilisticConfig()
+ assert restored.forecaster.predictor.latent_dim == 8
+ for name, value in model.state_dict().items():
+ torch.testing.assert_close(restored.state_dict()[name], value)
+
+ # Older checkpoints may not contain experiment configuration.
+ saved = torch.load(checkpoint, weights_only=False)
+ del saved["hyper_parameters"]["config"]
+ legacy_checkpoint = tmp_path / "legacy_graph_efm.ckpt"
+ torch.save(saved, legacy_checkpoint)
+ legacy_restored = load_forecasting_module_from_checkpoint(
+ str(legacy_checkpoint), config, datastore
)
+ for name, value in model.state_dict().items():
+ torch.testing.assert_close(legacy_restored.state_dict()[name], value)
+
assert isinstance(restored, ProbabilisticForecastingModule)
assert restored.eval_ensemble_size == 2
torch.manual_seed(4)
@@ -610,3 +626,138 @@ def test_decoder_std_remains_positive_for_large_negative_logits():
assert torch.isfinite(nll).all()
nll.sum().backward()
assert torch.isfinite(linear.bias.grad).all()
+
+
+@pytest.mark.parametrize("graph_name", ["1level", "hierarchical"])
+def test_forward_reuses_optional_graph_embedding(graph_name, monkeypatch):
+ """Supplied graph embeddings preserve samples and avoid recomputation."""
+ # Standard library
+ from unittest.mock import Mock
+
+ datastore, _ = _datastore_and_config(graph_name)
+ predictor = _build_predictor(datastore, graph_name)
+ initial, forcing, _ = _example_batch(datastore, predictor, 2, 2)
+ torch.manual_seed(9)
+ expected, _ = predictor(initial[:, 1], initial[:, 0], forcing[:, 0])
+ embed = Mock(wraps=predictor.embedd_graph)
+ monkeypatch.setattr(predictor, "embedd_graph", embed)
+ graph_emb = predictor.embedd_graph(2)
+ torch.manual_seed(9)
+ actual, _ = predictor(
+ initial[:, 1], initial[:, 0], forcing[:, 0], graph_emb=graph_emb
+ )
+ torch.testing.assert_close(actual, expected)
+ prediction, _ = predictor(
+ actual, initial[:, 1], forcing[:, 1], graph_emb=graph_emb
+ )
+ prediction.sum().backward()
+ embed.assert_called_once_with(2)
+ assert predictor.grid_prev_embedder[0].weight.grad is not None
+ assert predictor.g2m_embedder[0].weight.grad is not None
+
+
+@pytest.mark.parametrize(
+ "model_name,predictor_class,graph_name",
+ [
+ ("graph_efm", GraphEFM, "hierarchical"),
+ ("graph_efm_ms", GraphEFMMultiScale, "1level"),
+ ],
+)
+@pytest.mark.parametrize(
+ "flag,value",
+ [
+ ("processor_layers", 7),
+ ("mesh_aggr", "mean"),
+ ("mesh_up_gnn_type", "PropagationNet"),
+ ("mesh_down_gnn_type", "PropagationNet"),
+ ("loss", "nll"),
+ (None, None),
+ ],
+)
+def test_ignored_graph_efm_options_warn(
+ model_name,
+ predictor_class,
+ graph_name,
+ flag,
+ value,
+ monkeypatch,
+):
+ """Report non-default deterministic options for Graph-EFM."""
+ # Standard library
+ from unittest.mock import Mock
+
+ # First-party
+ from neural_lam import train_model
+
+ datastore, config = _datastore_and_config(graph_name)
+ args = train_model.build_parser().parse_args(
+ ["--config_path", "unused.yaml"]
+ )
+ args.model = model_name
+ args.graph = graph_name
+ args.hidden_dim = 4
+ if flag is not None:
+ setattr(args, flag, value)
+ warning = Mock()
+ monkeypatch.setattr(train_model.logger, "warning", warning)
+ build_predictor(predictor_class, args, config, datastore)
+ if flag is None:
+ warning.assert_not_called()
+ else:
+ warning.assert_called_once()
+ assert warning.call_args.args[1] == flag
+ assert "has no effect" in warning.call_args.args[0]
+
+
+@pytest.mark.parametrize(
+ "model_name,graph_name",
+ [
+ ("graph_efm", "hierarchical"),
+ ("graph_efm_ms", "1level"),
+ ],
+)
+def test_graph_efm_run_name_uses_configured_layers(
+ model_name,
+ graph_name,
+ monkeypatch,
+ tmp_path,
+):
+ """Default run names identify actual prior, encoder and decoder depths."""
+ # First-party
+ from neural_lam import train_model
+
+ datastore, config = _datastore_and_config(graph_name)
+ config.probabilistic = nlconfig.ProbabilisticConfig(
+ prior_layers=1,
+ encoder_layers=2,
+ decoder_layers=3,
+ )
+ names = []
+
+ def capture_logger(**kwargs):
+ names.append(kwargs["run_name"])
+ raise RuntimeError("stop before trainer")
+
+ monkeypatch.setattr(
+ train_model.utils, "setup_training_logger", capture_logger
+ )
+ with pytest.raises(RuntimeError, match="stop before trainer"):
+ train_model.fit(
+ model_config=nlconfig.ModelConfig(
+ model=model_name,
+ graph=graph_name,
+ hidden_dim=4,
+ ),
+ train_config=nlconfig.TrainRunConfig(
+ ar_steps_train=1,
+ ar_steps_eval=1,
+ val_steps_to_log=[1],
+ train_steps_to_log=[1],
+ ),
+ data_config=nlconfig.DataConfig(),
+ compute_config=nlconfig.ComputeConfig(devices=1),
+ logging_config=nlconfig.LoggingConfig(runs_root=str(tmp_path)),
+ config=config,
+ datastore=datastore,
+ )
+ assert names[0].startswith(f"train-{model_name}-p1-e2-d3x4-")
From 4d15e919d715f5cdfa6809ee9c97b605fbb00ac8 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Tue, 3 Nov 2026 19:56:07 +0530
Subject: [PATCH 03/41] Restore Graph-EFM checkpoint settings in CLI runs
Share probabilistic config restoration between the checkpoint helper
and fit so evaluation and resumed training build the saved architecture.
Warn on conflicting explicit YAML settings and preserve the legacy
fallback when checkpoint configuration is unavailable.
Add dummy-data CLI regressions for both graph families and document
checkpoint precedence.
---
CHANGELOG.md | 1 +
README.md | 3 +
neural_lam/train_model.py | 56 +++++++++-
tests/test_graph_efm_model.py | 205 ++++++++++++++++++++++++++++++++++
4 files changed, 259 insertions(+), 6 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 06b651cf1..c9235c60a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
probabilistic configuration, CLI assembly and checkpoint loading.
Restore saved probabilistic settings, share fair CRPS scoring, warn about
ignored CLI options and name runs using Graph-EFM layer counts.
+ Honor saved probabilistic settings in CLI evaluation and resumed training.
[\#712](https://github.com/mllam/neural-lam/pull/712) @Sir-Sloth-The-Lazy
- Add deterministic and probabilistic forecaster/module interfaces with
diff --git a/README.md b/README.md
index 3e622f9b2..3301c926d 100644
--- a/README.md
+++ b/README.md
@@ -74,6 +74,9 @@ always uses a Gaussian likelihood, including its log-standard-deviation term.
Without `--output_std`, observation scales come from the datastore's one-step
difference statistics and configured feature weights.
+When loading a checkpoint for evaluation or resumed training, its saved
+probabilistic settings take precedence over the current YAML section.
+
Add this optional section alongside `datastores` in the experiment YAML:
```yaml
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index 6cb81e321..7657231a2 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -15,6 +15,7 @@
# for logging the model:
import pytorch_lightning as pl
import torch
+import yaml
from lightning_fabric.utilities import seed
from loguru import logger
@@ -265,6 +266,32 @@ def __init__(self, prog: str) -> None:
)
+def _restore_probabilistic_config(
+ ckpt_hparams: dict[str, Any],
+ config: NeuralLAMConfig,
+) -> NeuralLAMConfig:
+ """Restore saved Graph-EFM settings without mutating the caller's config.
+
+ Parameters
+ ----------
+ ckpt_hparams : dict[str, Any]
+ Hyperparameters read from a model checkpoint.
+ config : NeuralLAMConfig
+ Current experiment configuration, used for legacy checkpoints.
+
+ Returns
+ -------
+ NeuralLAMConfig
+ Configuration with the saved probabilistic settings, or ``config``
+ unchanged if the checkpoint does not contain those settings.
+ """
+ saved_config = ckpt_hparams.get("config")
+ saved_probabilistic = getattr(saved_config, "probabilistic", None)
+ if saved_probabilistic is None:
+ return config
+ return dataclasses.replace(config, probabilistic=saved_probabilistic)
+
+
def load_forecasting_module_from_checkpoint(
ckpt_path: str,
config: NeuralLAMConfig,
@@ -303,12 +330,7 @@ def load_forecasting_module_from_checkpoint(
predictor_class = MODELS[args.model]
is_graph_efm = issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale))
if is_graph_efm:
- saved_config = ckpt["hyper_parameters"].get("config")
- saved_probabilistic = getattr(saved_config, "probabilistic", None)
- if saved_probabilistic is not None:
- config = dataclasses.replace(
- config, probabilistic=saved_probabilistic
- )
+ config = _restore_probabilistic_config(ckpt["hyper_parameters"], config)
predictor = build_predictor(predictor_class, args, config, datastore)
forecaster, module_class, _ = build_forecaster_module(
args, config, datastore, predictor
@@ -663,6 +685,9 @@ def fit(
"""
Run training or evaluation using strongly-typed configuration dataclasses.
+ When loading Graph-EFM weights, the checkpoint's probabilistic settings
+ take precedence over the current experiment configuration.
+
Parameters
----------
model_config : ModelConfig
@@ -808,6 +833,25 @@ def fit(
# Build predictor and forecaster externally, then inject into
# DeterministicForecastingModule
predictor_class = MODELS[model_config.model]
+ if train_config.load and issubclass(
+ predictor_class, (GraphEFM, GraphEFMMultiScale)
+ ):
+ ckpt_hparams = torch.load(train_config.load, weights_only=False).get(
+ "hyper_parameters", {}
+ )
+ restored_config = _restore_probabilistic_config(ckpt_hparams, config)
+ if config.probabilistic != restored_config.probabilistic:
+ has_probabilistic_section = True
+ if config_path is not None and Path(config_path).is_file():
+ with open(config_path, encoding="utf-8") as config_file:
+ raw_config = yaml.safe_load(config_file) or {}
+ has_probabilistic_section = "probabilistic" in raw_config
+ if has_probabilistic_section:
+ logger.warning(
+ "The checkpoint's probabilistic settings take precedence "
+ "over the current Graph-EFM configuration."
+ )
+ config = restored_config
predictor = build_predictor(predictor_class, hparams, config, datastore)
if not train_config.eval and not predictor.trainable:
diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py
index 9337f0ac3..e2bee96cf 100644
--- a/tests/test_graph_efm_model.py
+++ b/tests/test_graph_efm_model.py
@@ -761,3 +761,208 @@ def capture_logger(**kwargs):
datastore=datastore,
)
assert names[0].startswith(f"train-{model_name}-p1-e2-d3x4-")
+
+
+@pytest.fixture(scope="module", params=["1level", "hierarchical"])
+def cli_graph_efm_checkpoint(request, tmp_path_factory):
+ """Save a one-step dummy-data model with non-default latent settings."""
+ # Third-party
+ import pytorch_lightning as pl
+ from torch.utils.data import DataLoader, TensorDataset
+
+ # First-party
+ from neural_lam import api, train_model
+ from tests.dummy_datastore import DummyDatastore
+
+ graph_name = request.param
+ datastore = DummyDatastore(n_grid_points=100, n_timesteps=15)
+ graph_kwargs = (
+ {"level_refinement_factor": 2, "mesh_grid_distance_ratio": 1.5}
+ if graph_name == "hierarchical"
+ else {}
+ )
+ api.create_graph(
+ datastore=datastore,
+ name=graph_name,
+ archetype="hierarchical" if graph_name == "hierarchical" else "keisler",
+ **graph_kwargs,
+ )
+ config = nlconfig.NeuralLAMConfig(
+ datastores={
+ "main": nlconfig.DatastoreSelection(
+ kind=datastore.SHORT_NAME,
+ config_path=str(datastore.root_path),
+ )
+ },
+ probabilistic=nlconfig.ProbabilisticConfig(
+ latent_dim=8,
+ prior_layers=1,
+ encoder_layers=1,
+ decoder_layers=2,
+ eval_ensemble_size=2,
+ ),
+ )
+ model_name = "graph_efm" if graph_name == "hierarchical" else "graph_efm_ms"
+ args = train_model.build_parser().parse_args(
+ [
+ "--config_path",
+ "unused.yaml",
+ "--model",
+ model_name,
+ "--graph",
+ graph_name,
+ "--hidden_dim",
+ "4",
+ ]
+ )
+ predictor = build_predictor(
+ train_model.MODELS[model_name], args, config, datastore
+ )
+ forecaster, module_class, module_kwargs = build_forecaster_module(
+ args,
+ config,
+ datastore,
+ predictor,
+ )
+ model = module_class(
+ forecaster, config, datastore, args=args, **module_kwargs
+ )
+ initial, forcing, target = _example_batch(datastore, predictor, 2, 1)
+ dataset = TensorDataset(
+ initial,
+ target,
+ forcing,
+ torch.empty(2, 1, predictor.num_grid_nodes, 0),
+ torch.zeros(2, 1),
+ )
+ trainer = pl.Trainer(
+ accelerator="cpu",
+ devices=1,
+ max_steps=1,
+ logger=False,
+ enable_checkpointing=False,
+ enable_progress_bar=False,
+ enable_model_summary=False,
+ num_sanity_val_steps=0,
+ )
+ trainer.fit(model, train_dataloaders=DataLoader(dataset, batch_size=2))
+ assert trainer.global_step == 1
+ checkpoint = tmp_path_factory.mktemp(f"cli_{model_name}") / "source.ckpt"
+ trainer.save_checkpoint(checkpoint)
+ return datastore, config, checkpoint, model_name, graph_name
+
+
+@pytest.mark.requires_training
+@pytest.mark.parametrize(
+ "mode,section",
+ [
+ ("test", "different"),
+ ("test", "equal"),
+ ("test", "omitted"),
+ ("test", "legacy"),
+ (None, "different"),
+ ],
+)
+def test_cli_restores_probabilistic_checkpoint_settings(
+ cli_graph_efm_checkpoint,
+ mode,
+ section,
+ monkeypatch,
+ tmp_path,
+):
+ """CLI evaluation and resume build models with checkpoint architecture."""
+ # Standard library
+ from unittest.mock import Mock
+
+ # Third-party
+ import yaml
+
+ # First-party
+ from neural_lam import train_model
+
+ datastore, saved_config, checkpoint, model_name, graph_name = (
+ cli_graph_efm_checkpoint
+ )
+ caller_config = nlconfig.NeuralLAMConfig(
+ datastores=saved_config.datastores,
+ probabilistic=(
+ saved_config.probabilistic
+ if section in {"equal", "legacy"}
+ else nlconfig.ProbabilisticConfig()
+ ),
+ )
+ if section == "legacy":
+ saved = torch.load(checkpoint, weights_only=False)
+ del saved["hyper_parameters"]["config"]
+ checkpoint = tmp_path / "legacy.ckpt"
+ torch.save(saved, checkpoint)
+ raw_config = yaml.safe_load(caller_config.to_yaml())
+ if section == "omitted":
+ del raw_config["probabilistic"]
+ config_path = tmp_path / "experiment.yaml"
+ config_path.write_text(yaml.safe_dump(raw_config))
+
+ real_trainer = train_model.pl.Trainer
+ trainers = []
+
+ def build_test_trainer(**kwargs):
+ trainer = real_trainer(
+ **kwargs,
+ limit_train_batches=1,
+ limit_val_batches=1,
+ limit_test_batches=1,
+ enable_progress_bar=False,
+ enable_model_summary=False,
+ )
+ trainers.append(trainer)
+ return trainer
+
+ warning = Mock()
+ monkeypatch.setattr(train_model.pl, "Trainer", build_test_trainer)
+ monkeypatch.setattr(train_model.logger, "warning", warning)
+ (tmp_path / "loaded").mkdir()
+ result = train_model.fit(
+ model_config=nlconfig.ModelConfig(
+ model=model_name,
+ graph=graph_name,
+ hidden_dim=4,
+ ),
+ train_config=nlconfig.TrainRunConfig(
+ epochs=2,
+ batch_size=2,
+ ar_steps_train=1,
+ ar_steps_eval=1,
+ val_steps_to_log=[1],
+ num_sanity_val_steps=0,
+ eval=mode,
+ load=str(checkpoint),
+ ),
+ data_config=nlconfig.DataConfig(num_workers=0),
+ compute_config=nlconfig.ComputeConfig(devices=1),
+ logging_config=nlconfig.LoggingConfig(
+ runs_root=str(tmp_path), logger_run_name="loaded"
+ ),
+ config=caller_config,
+ datastore=datastore,
+ config_path=str(config_path),
+ )
+ evaluated = trainers[0].lightning_module
+ assert evaluated.forecaster.predictor.latent_dim == 8
+ assert evaluated.hparams.config.probabilistic == saved_config.probabilistic
+ assert result.checkpoint_path is not None
+ if section == "different":
+ warning.assert_called_once()
+ assert (
+ "checkpoint's probabilistic settings take precedence"
+ in warning.call_args.args[0]
+ )
+ else:
+ warning.assert_not_called()
+ if mode == "test":
+ source_weights = torch.load(checkpoint, weights_only=False)[
+ "state_dict"
+ ]
+ for name, value in evaluated.state_dict().items():
+ torch.testing.assert_close(value, source_weights[name])
+ else:
+ assert trainers[0].global_step > 1
From 7df387ffc309c9ae6476a78b6a766e55dffeee72 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:48 +0530
Subject: [PATCH 04/41] Clarify the variational posterior approximation
The encoder approximates the target-conditioned posterior rather than computing the true posterior; name and document that distinction.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503670176
---
neural_lam/models/forecasters/graph_efm.py | 4 ++--
neural_lam/models/step_predictors/graph/graph_efm.py | 12 ++++++------
2 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
index 13d353b78..15f7ebe24 100644
--- a/neural_lam/models/forecasters/graph_efm.py
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -176,7 +176,7 @@ def compute_training_loss(
# Posterior latent (conditioned on target), reconstruction, and
# -- when a KL term is needed -- the prior, in one predictor call.
- prior_dist, posterior_dist, pred_mean, pred_std = (
+ prior_dist, var_posterior_dist, pred_mean, pred_std = (
predictor.posterior_step(
prev_state,
prev_prev_state,
@@ -209,7 +209,7 @@ def compute_training_loss(
kl_terms.append(
torch.sum(
torch.distributions.kl_divergence(
- posterior_dist, prior_dist
+ var_posterior_dist, prior_dist
),
dim=(1, 2),
)
diff --git a/neural_lam/models/step_predictors/graph/graph_efm.py b/neural_lam/models/step_predictors/graph/graph_efm.py
index bde2b523c..edc4e8d3c 100644
--- a/neural_lam/models/step_predictors/graph/graph_efm.py
+++ b/neural_lam/models/step_predictors/graph/graph_efm.py
@@ -443,7 +443,7 @@ def posterior_step(
torch.Tensor,
torch.Tensor | None,
]:
- """Sample a training step from the target-conditioned posterior.
+ """Sample a training step from the variational posterior approximation.
Parameters
----------
@@ -465,8 +465,8 @@ def posterior_step(
-------
prior : torch.distributions.Normal or None
Conditional prior, omitted when ``compute_prior`` is False.
- posterior : torch.distributions.Normal
- Target-conditioned latent distribution.
+ var_posterior : torch.distributions.Normal
+ Target-conditioned variational approximation given by the encoder.
prediction : torch.Tensor
Shape as ``prev_state``. Rescaled and clamped decoder mean.
pred_std : torch.Tensor or None
@@ -479,16 +479,16 @@ def posterior_step(
prev_state, prev_prev_state, forcing, target_state
)
assert isinstance(self.encoder, torch.nn.Module)
- posterior = self.encoder(target_emb, graph_emb=graph_emb)
+ var_posterior = self.encoder(target_emb, graph_emb=graph_emb)
prior = (
self.prior_model(grid_emb, graph_emb=graph_emb)
if compute_prior
else None
)
mean, std = self.decode_state(
- grid_emb, posterior.rsample(), graph_emb, prev_state
+ grid_emb, var_posterior.rsample(), graph_emb, prev_state
)
- return prior, posterior, mean, std
+ return prior, var_posterior, mean, std
def decode_state(
self,
From 5e61b79057c56379570ba78a86e3861b608e5728 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:49 +0530
Subject: [PATCH 05/41] Describe the Graph-EFM training objective directly
Replace the forecaster ownership boilerplate with the variational reconstruction, KL and optional prior-sampled CRPS objective.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503727158
---
neural_lam/models/forecasters/graph_efm.py | 22 ++++++++--------------
1 file changed, 8 insertions(+), 14 deletions(-)
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
index 15f7ebe24..f13a0621c 100644
--- a/neural_lam/models/forecasters/graph_efm.py
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -19,20 +19,14 @@ class GraphEFMForecaster(BaseProbabilisticARForecaster):
Wraps a :class:`BaseGraphEFM` predictor (hierarchical ``GraphEFM`` or
flat ``GraphEFMMultiScale``), a latent-variable model consisting of a
conditional prior, a variational encoder and a latent decoder. Forecast
- sampling (``forward``, ``sample_ensemble``) is inherited from
- :class:`BaseProbabilisticARForecaster`: each predictor call samples the
- prior and decodes, so unrolling produces one stochastic trajectory and
- stacking several gives an ensemble.
-
- This class supplies the training objective the base class leaves
- abstract: the evidence lower bound (ELBO). ``compute_training_loss``
- runs a variational rollout in which, at each step, the latent is drawn
- from the encoder (conditioned on the target), and accumulates a
- reconstruction likelihood term and a KL term between the encoder and the
- prior. The Gaussian likelihood, the constant per-variable std
- fallback ``self.per_var_std`` and the boundary/interior masks all live
- on the forecaster; the predictor only
- provides the network building blocks.
+ sampling draws from the latent prior and decodes each step. Unrolling
+ produces one stochastic trajectory; stacking independent trajectories
+ gives an ensemble. Static graph embeddings are shared across members.
+
+ ``compute_training_loss`` runs a variational rollout with latents drawn
+ from the target-conditioned encoder, accumulating a reconstruction
+ likelihood and KL term against the prior. Optional fair CRPS uses at
+ least two separate trajectories sampled from the prior.
"""
def __init__(
From 7c749241d651a8a79d84abe204adab0d62303b96 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:49 +0530
Subject: [PATCH 06/41] Document the independent prior rollouts used by CRPS
The CRPS samples come from separate prior trajectories, not the target-conditioned variational rollout; clarify the extra sampling cost.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503742219
---
neural_lam/models/forecasters/graph_efm.py | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
index f13a0621c..cd02625cd 100644
--- a/neural_lam/models/forecasters/graph_efm.py
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -103,7 +103,8 @@ def compute_training_loss(
encoder and the prior is accumulated too. Both terms are summed over
the rollout and averaged over the batch; the loss is
``-likelihood + kl_beta * kl + crps_weight * crps``.
- CRPS is
+ Fair CRPS uses at least two additional prior trajectories, independent
+ of the variational posterior rollout. It is
summed over interior nodes, variables and time, like the likelihood,
and averaged over the batch. The rollout advances on the
predicted mean with boundary nodes overwritten by the true state.
From bfa7e086eb6345c5ab358d6d8b4c4bc59389a955 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:50 +0530
Subject: [PATCH 07/41] Reuse static graph embeddings across prior trajectories
CRPS and ensemble sampling recomputed static graph embeddings at every step; compute them once per batch and share them with independent prior rollouts while retaining gradients.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503759889
---
.../models/forecasters/autoregressive.py | 13 ++--
neural_lam/models/forecasters/graph_efm.py | 66 ++++++++++++++++++-
tests/test_graph_efm_objective.py | 33 +++++++++-
3 files changed, 105 insertions(+), 7 deletions(-)
diff --git a/neural_lam/models/forecasters/autoregressive.py b/neural_lam/models/forecasters/autoregressive.py
index 59ad6d8b2..3b312ba74 100644
--- a/neural_lam/models/forecasters/autoregressive.py
+++ b/neural_lam/models/forecasters/autoregressive.py
@@ -1,14 +1,17 @@
"""Auto-regressive unrolling of a step predictor into a full forecast."""
+# Standard library
+from collections.abc import Callable
+
# Third-party
import torch
-# Local
-from ..step_predictors.base import StepPredictor
-
def unroll_forecast(
- predictor: StepPredictor,
+ predictor: Callable[
+ [torch.Tensor, torch.Tensor, torch.Tensor],
+ tuple[torch.Tensor, torch.Tensor | None],
+ ],
init_states: torch.Tensor,
forcing_features: torch.Tensor,
boundary_states: torch.Tensor,
@@ -29,7 +32,7 @@ def unroll_forecast(
Parameters
----------
- predictor : StepPredictor
+ predictor : callable
The predictor advancing the state one time step, applied once per
predicted step. A predictor that samples its output makes each call
to this function an independent trajectory.
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
index cd02625cd..97a08b5d3 100644
--- a/neural_lam/models/forecasters/graph_efm.py
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -1,5 +1,9 @@
"""Probabilistic forecaster training a Graph-EFM predictor via its ELBO."""
+# Standard library
+from functools import partial
+from typing import Any
+
# Third-party
import torch
@@ -9,6 +13,7 @@
from ...datastore import BaseDatastore
from ...loss_weighting import get_per_var_std
from ..step_predictors.graph.graph_efm import BaseGraphEFM
+from .autoregressive import unroll_forecast
from .probabilistic import BaseProbabilisticARForecaster
@@ -234,7 +239,11 @@ def compute_training_loss(
if self.crps_weight > 0:
ensemble, _ = self.sample_ensemble(
- init_states, forcing_features, target_states, self.crps_members
+ init_states,
+ forcing_features,
+ target_states,
+ self.crps_members,
+ graph_emb=graph_emb,
)
entry_crps = metrics.crps_ens_fair(
ensemble,
@@ -247,3 +256,58 @@ def compute_training_loss(
batch_loss = batch_loss + self.crps_weight * crps
loss_components["crps"] = crps
return batch_loss, loss_components
+
+ def sample_ensemble(
+ self,
+ init_states: torch.Tensor,
+ forcing_features: torch.Tensor,
+ boundary_states: torch.Tensor,
+ num_members: int,
+ graph_emb: dict[str, Any] | None = None,
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Sample independent prior trajectories using one graph embedding.
+
+ Parameters
+ ----------
+ init_states : torch.Tensor
+ Shape (B, 2, num_grid_nodes, num_state_vars). Initial states.
+ forcing_features : torch.Tensor
+ Shape (B, pred_steps, num_grid_nodes, num_windowed_forcing_vars).
+ boundary_states : torch.Tensor
+ Shape (B, pred_steps, num_grid_nodes, num_state_vars). Boundaries.
+ num_members : int
+ Number of independent prior trajectories, at least one.
+ graph_emb : dict[str, Any] or None, optional
+ Static graph embeddings shared with the variational rollout.
+ Computed once for all trajectories when omitted.
+
+ Returns
+ -------
+ ensemble : torch.Tensor
+ Shape (B, num_members, pred_steps, num_grid_nodes, num_state_vars).
+ per_member_std : torch.Tensor or None
+ Conditional observation scales with the same shape, if enabled.
+
+ Raises
+ ------
+ ValueError
+ If num_members is less than one.
+ """
+ if num_members < 1:
+ raise ValueError("num_members must be at least 1")
+ if graph_emb is None:
+ graph_emb = self.predictor.embedd_graph(init_states.shape[0])
+ samples = [
+ unroll_forecast(
+ partial(self.predictor, graph_emb=graph_emb),
+ init_states,
+ forcing_features,
+ boundary_states,
+ self.boundary_mask,
+ self.interior_mask,
+ )
+ for _ in range(num_members)
+ ]
+ ensemble = torch.stack([sample[0] for sample in samples], dim=1)
+ scales = [sample[1] for sample in samples if sample[1] is not None]
+ return ensemble, torch.stack(scales, dim=1) if scales else None
diff --git a/tests/test_graph_efm_objective.py b/tests/test_graph_efm_objective.py
index ce605d0bf..fd065ec71 100644
--- a/tests/test_graph_efm_objective.py
+++ b/tests/test_graph_efm_objective.py
@@ -25,8 +25,11 @@ def __init__(self):
self.log_std = nn.Parameter(torch.tensor(0.0))
self.states = []
self.prior_flags = []
+ self.graphs = []
+ self.embedding_calls = 0
def embedd_graph(self, batch_size):
+ self.embedding_calls += 1
return {}
def posterior_step(
@@ -48,6 +51,12 @@ def posterior_step(
self.log_std.exp().expand_as(prev),
)
+ def forward(self, prev, prev_prev, forcing, graph_emb=None):
+ self.graphs.append(graph_emb)
+ return self.mean + torch.randn_like(prev), self.log_std.exp().expand_as(
+ prev
+ )
+
@pytest.fixture
def objective():
@@ -101,7 +110,7 @@ def test_crps_matches_pairwise_fair_estimator(objective, members):
torch.testing.assert_close(loss, -logs["elbo_likelihood"] + 0.7 * expected)
assert not any(predictor.prior_flags)
forecaster.sample_ensemble.assert_called_once_with(
- init, forcing, target, members
+ init, forcing, target, members, graph_emb={}
)
loss.backward()
assert ensemble.grad.abs().sum() > 0
@@ -170,3 +179,25 @@ def test_probabilistic_yaml_round_trip():
eval_ensemble_size=6,
)
assert NeuralLAMConfig.from_yaml(config.to_yaml()) == config
+
+
+def test_crps_reuses_graph_across_independent_prior_trajectories(objective):
+ """Training embeds once for both variational and all prior rollouts."""
+ forecaster, predictor, mask, init, forcing, target = objective
+ forecaster.crps_weight = 1
+ forecaster.crps_members = 3
+ loss, _ = forecaster.compute_training_loss(init, forcing, target, mask)
+ assert predictor.embedding_calls == 1
+ assert len(predictor.graphs) == 3 * forcing.shape[1]
+ assert all(graph is predictor.graphs[0] for graph in predictor.graphs)
+ loss.backward()
+ assert predictor.mean.grad.abs() > 0
+
+
+def test_prior_ensemble_caches_embeddings_without_caching_samples(objective):
+ """Evaluation also shares embeddings while drawing distinct members."""
+ forecaster, predictor, mask, init, forcing, target = objective
+ ensemble, _ = forecaster.sample_ensemble(init, forcing, target, 2)
+ assert predictor.embedding_calls == 1
+ assert not torch.equal(ensemble[:, 0, :, mask], ensemble[:, 1, :, mask])
+ torch.testing.assert_close(ensemble[:, 0, :, ~mask], target[:, :, ~mask])
From d9bf4374bb2fb74cc2c0097da9cbbbee28961325 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:50 +0530
Subject: [PATCH 08/41] Match the original Graph-EFM CRPS loss reduction
Summing CRPS over grid points and forecast steps changed the meaning of the paper's tuning weights; average those dimensions and the batch while summing variables.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503782846
---
neural_lam/models/forecasters/graph_efm.py | 14 +++++++-------
tests/test_graph_efm_objective.py | 2 +-
2 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
index 97a08b5d3..7d224985b 100644
--- a/neural_lam/models/forecasters/graph_efm.py
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -109,10 +109,10 @@ def compute_training_loss(
the rollout and averaged over the batch; the loss is
``-likelihood + kl_beta * kl + crps_weight * crps``.
Fair CRPS uses at least two additional prior trajectories, independent
- of the variational posterior rollout. It is
- summed over interior nodes, variables and time, like the likelihood,
- and averaged over the batch. The rollout advances on the
- predicted mean with boundary nodes overwritten by the true state.
+ of the variational posterior rollout. It sums variables and averages
+ over interior grid nodes, forecast steps and batch. The variational
+ rollout advances on the predicted mean with boundary nodes
+ overwritten by the true state.
Parameters
----------
@@ -249,10 +249,10 @@ def compute_training_loss(
ensemble,
target_states,
mask=interior_mask_bool,
- average_grid=False,
- sum_vars=False,
+ average_grid=True,
+ sum_vars=True,
)
- crps = entry_crps.sum(dim=(1, 2, 3)).mean()
+ crps = entry_crps.mean()
batch_loss = batch_loss + self.crps_weight * crps
loss_components["crps"] = crps
return batch_loss, loss_components
diff --git a/tests/test_graph_efm_objective.py b/tests/test_graph_efm_objective.py
index fd065ec71..4f8d61c69 100644
--- a/tests/test_graph_efm_objective.py
+++ b/tests/test_graph_efm_objective.py
@@ -105,7 +105,7 @@ def test_crps_matches_pairwise_fair_estimator(objective, members):
first = (ensemble - target.unsqueeze(1)).abs().mean(1)
pairwise = (ensemble.unsqueeze(2) - ensemble.unsqueeze(1)).abs().sum((1, 2))
expected = first - pairwise / (2 * members * (members - 1))
- expected = expected[:, :, mask].sum((1, 2, 3)).mean()
+ expected = expected[:, :, mask].sum(-1).mean()
torch.testing.assert_close(logs["crps"], expected)
torch.testing.assert_close(loss, -logs["elbo_likelihood"] + 0.7 * expected)
assert not any(predictor.prior_flags)
From f75e0c31e68b27663eb1cbf7389391bfc7ab1473 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:50 +0530
Subject: [PATCH 09/41] Generalize ensemble CRPS and simplify two-member
scoring
Expose empirical, fair and almost-fair CRPS variants from the approach in #226, preserving the fair training API and using the correctly normalized direct pair difference for two members.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503798959
---
neural_lam/metrics.py | 121 ++++++++++++++++++++++++++++-----
tests/test_ensemble_metrics.py | 63 ++++++++++++++++-
2 files changed, 166 insertions(+), 18 deletions(-)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index b786f620b..b1e499726 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -393,25 +393,29 @@ def crps_gauss(
)
-def crps_ens_fair(
+def crps_ens(
ensemble: torch.Tensor,
target: torch.Tensor,
mask: torch.Tensor | None = None,
average_grid: bool = True,
sum_vars: bool = True,
ens_dim: int = 1,
+ estimator: str = "unbiased",
+ afc_alpha: float | None = None,
) -> torch.Tensor:
- """Compute fair CRPS from independent ensemble samples.
+ """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. Gradients are retained for training.
+ linear in the number of members, with a direct two-member formula.
+ Gradients are retained for training.
Parameters
----------
ensemble : 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 independent members are required.
+ num_state_vars)``. Fair and almost-fair estimation require at least
+ two independent members.
target : torch.Tensor
Shape ``(..., num_grid_nodes, num_state_vars)``. Ground truth.
mask : torch.Tensor or None, optional
@@ -422,6 +426,13 @@ def crps_ens_fair(
Sum over state variables. Default True.
ens_dim : int, optional
Ensemble dimension in ``ensemble``. Default 1.
+ estimator : str, optional
+ "biased" scores the empirical ensemble distribution; "unbiased"
+ (default) estimates the generating distribution's CRPS fairly.
+ "almost-fair" interpolates using afc_alpha.
+ afc_alpha : float or None, optional
+ For almost-fair estimation, a finite value from 0 (biased) to 1
+ (unbiased). Required only for the almost-fair estimator.
Returns
-------
@@ -432,28 +443,104 @@ def crps_ens_fair(
Raises
------
ValueError
- If there are fewer than two members.
+ If the estimator, alpha or number of members is invalid.
"""
+ if estimator not in {"biased", "unbiased", "almost-fair"}:
+ raise ValueError(f"Unknown CRPS estimator: {estimator}")
+ if estimator == "almost-fair" and (
+ afc_alpha is None or not 0 <= afc_alpha <= 1
+ ):
+ raise ValueError("afc_alpha must be finite and between 0 and 1")
num_members = ensemble.shape[ens_dim]
- if num_members < 2:
+ if num_members < 1 or (num_members < 2 and estimator != "biased"):
raise ValueError("Fair CRPS requires at least two ensemble members")
+ if num_members == 1:
+ return mask_and_reduce_metric(
+ (ensemble.squeeze(ens_dim) - target).abs(),
+ mask=mask,
+ average_grid=average_grid,
+ sum_vars=sum_vars,
+ )
first = (ensemble - target.unsqueeze(ens_dim)).abs().mean(dim=ens_dim)
- ordered = ensemble.sort(dim=ens_dim).values
- rank_shape = [1] * ensemble.ndim
- rank_shape[ens_dim] = num_members
- ranks = torch.arange(
- 1,
- num_members + 1,
- device=ensemble.device,
- dtype=ensemble.dtype,
- ).view(rank_shape)
- spread = ((2 * ranks - num_members - 1) * ordered).sum(dim=ens_dim)
- entry_crps = first - spread / (num_members * (num_members - 1))
+ if num_members == 2:
+ spread = (
+ ensemble.select(ens_dim, 0) - ensemble.select(ens_dim, 1)
+ ).abs() / 2
+ else:
+ ordered = ensemble.sort(dim=ens_dim).values
+ rank_shape = [1] * ensemble.ndim
+ rank_shape[ens_dim] = num_members
+ ranks = torch.arange(
+ 1,
+ num_members + 1,
+ device=ensemble.device,
+ dtype=ensemble.dtype,
+ ).view(rank_shape)
+ spread = ((2 * ranks - num_members - 1) * ordered).sum(dim=ens_dim)
+ spread = spread / (num_members * (num_members - 1))
+ if estimator == "biased":
+ spread = spread * (num_members - 1) / num_members
+ elif estimator == "almost-fair":
+ assert afc_alpha is not None
+ spread = spread * (num_members - 1 + afc_alpha) / num_members
+ entry_crps = first - spread
return mask_and_reduce_metric(
entry_crps, mask=mask, average_grid=average_grid, sum_vars=sum_vars
)
+def crps_ens_fair(
+ ensemble: torch.Tensor,
+ target: torch.Tensor,
+ mask: torch.Tensor | None = None,
+ average_grid: bool = True,
+ sum_vars: bool = True,
+ ens_dim: int = 1,
+) -> torch.Tensor:
+ """Compute fair CRPS from independent ensemble samples.
+
+ 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.
+
+ Parameters
+ ----------
+ ensemble : 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 independent members are required.
+ target : torch.Tensor
+ Shape ``(..., num_grid_nodes, num_state_vars)``. Ground truth.
+ 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 ``ensemble``. Default 1.
+
+ Returns
+ -------
+ torch.Tensor
+ CRPS with the ensemble dimension removed, reduced according to
+ ``mask``, ``average_grid`` and ``sum_vars`` as for ``nll``.
+
+ Raises
+ ------
+ ValueError
+ If there are fewer than two members.
+ """
+ return crps_ens(
+ ensemble,
+ target,
+ mask=mask,
+ average_grid=average_grid,
+ sum_vars=sum_vars,
+ ens_dim=ens_dim,
+ )
+
+
DEFINED_METRICS: dict[str, Callable[..., torch.Tensor]] = {
"mse": mse,
"mae": mae,
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index ef1f04389..14e322a89 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -5,7 +5,7 @@
import torch
# First-party
-from neural_lam.metrics import crps_ens_fair, mask_and_reduce_metric
+from neural_lam.metrics import crps_ens, crps_ens_fair, mask_and_reduce_metric
@pytest.mark.parametrize("members", [2, 3, 5])
@@ -60,3 +60,64 @@ def test_fair_crps_retains_gradients():
def test_fair_crps_rejects_insufficient_members(members):
with pytest.raises(ValueError, match="at least two"):
crps_ens_fair(torch.zeros(2, members, 4, 3), torch.zeros(2, 4, 3))
+
+
+@pytest.mark.parametrize("members", [2, 5])
+@pytest.mark.parametrize(
+ "estimator,alpha",
+ [
+ ("biased", None),
+ ("unbiased", None),
+ ("almost-fair", 0.0),
+ ("almost-fair", 0.4),
+ ("almost-fair", 1.0),
+ ],
+)
+def test_general_crps_estimators(members, estimator, alpha):
+ """Every estimator agrees with its pairwise definition and gradients."""
+ torch.manual_seed(8)
+ ensemble = torch.randn(2, members, 3, 2, requires_grad=True)
+ target = torch.randn(2, 3, 2)
+ first = (ensemble - target.unsqueeze(1)).abs().mean(1)
+ pairs = (ensemble.unsqueeze(2) - ensemble.unsqueeze(1)).abs().sum((1, 2))
+ factor = {
+ "biased": 1 / members,
+ "unbiased": 1 / (members - 1),
+ "almost-fair": (members - 1 + (alpha or 0)) / (members * (members - 1)),
+ }[estimator]
+ expected = first - pairs * factor / (2 * members)
+ actual = crps_ens(
+ ensemble,
+ target,
+ average_grid=False,
+ sum_vars=False,
+ estimator=estimator,
+ afc_alpha=alpha,
+ )
+ torch.testing.assert_close(actual, expected)
+ actual.sum().backward()
+ assert torch.isfinite(ensemble.grad).all()
+
+
+@pytest.mark.parametrize("alpha", [None, -1, 2, float("nan"), float("inf")])
+def test_almost_fair_crps_rejects_invalid_alpha(alpha):
+ with pytest.raises(ValueError, match="afc_alpha"):
+ crps_ens(
+ torch.zeros(1, 2, 3, 2),
+ torch.zeros(1, 3, 2),
+ estimator="almost-fair",
+ afc_alpha=alpha,
+ )
+
+
+def test_empirical_crps_single_member_is_mae():
+ ensemble = torch.tensor([[[[1.0, 4.0]]]])
+ target = torch.tensor([[[2.0, 2.0]]])
+ torch.testing.assert_close(
+ crps_ens(ensemble, target, estimator="biased"), torch.tensor([3.0])
+ )
+
+
+def test_unknown_crps_estimator():
+ with pytest.raises(ValueError, match="Unknown CRPS estimator"):
+ crps_ens(torch.zeros(1, 2, 3, 2), torch.zeros(1, 3, 2), estimator="bad")
From c3b7e901f27a78b912075b98178e539ee4b541e6 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:51 +0530
Subject: [PATCH 10/41] Extract distributed strategy selection into a utility
Move device-list, automatic-device and multi-node detection out of trainer construction so unused-parameter handling is reusable and independently testable.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503719478
---
neural_lam/train_model.py | 14 ++++--------
neural_lam/utils/__init__.py | 2 ++
neural_lam/utils/distributed.py | 38 +++++++++++++++++++++++++++++++++
3 files changed, 44 insertions(+), 10 deletions(-)
create mode 100644 neural_lam/utils/distributed.py
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index 7657231a2..27c61d932 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -929,16 +929,10 @@ def fit(
max_epochs=train_config.epochs,
deterministic=True,
default_root_dir=run_dir,
- strategy=(
- "ddp_find_unused_parameters_true"
- if isinstance(forecaster, GraphEFMForecaster)
- and (
- compute_config.num_nodes > 1
- or (isinstance(devices, list) and len(devices) > 1)
- or (isinstance(devices, int) and devices > 1)
- or (devices == "auto" and torch.cuda.device_count() > 1)
- )
- else "auto"
+ strategy=utils.training_strategy(
+ devices,
+ compute_config.num_nodes,
+ find_unused_parameters=isinstance(forecaster, GraphEFMForecaster),
),
accelerator=device_name,
num_nodes=compute_config.num_nodes,
diff --git a/neural_lam/utils/__init__.py b/neural_lam/utils/__init__.py
index f996044f1..3e65c4cb8 100644
--- a/neural_lam/utils/__init__.py
+++ b/neural_lam/utils/__init__.py
@@ -2,6 +2,7 @@
# Local
from .buffer_list import BufferList
+from .distributed import training_strategy
from .graph import (
compute_grid_input_dim,
load_and_register_graph,
@@ -43,6 +44,7 @@
"make_gnn_seq",
"make_mlp",
"setup_training_logger",
+ "training_strategy",
"zero_index_edge_index",
"zero_index_g2m",
"zero_index_m2g",
diff --git a/neural_lam/utils/distributed.py b/neural_lam/utils/distributed.py
new file mode 100644
index 000000000..062e19506
--- /dev/null
+++ b/neural_lam/utils/distributed.py
@@ -0,0 +1,38 @@
+"""Utilities for distributed training configuration."""
+
+# Third-party
+import torch
+
+
+def training_strategy(
+ devices: int | str | list[int],
+ num_nodes: int,
+ *,
+ find_unused_parameters: bool = False,
+) -> str:
+ """Select unused-parameter detection only for distributed training.
+
+ Parameters
+ ----------
+ devices : int or str or list[int]
+ Lightning device count, device indices, or auto selection.
+ num_nodes : int
+ Number of distributed nodes.
+ find_unused_parameters : bool, optional
+ Whether the training objective leaves some model parameters unused.
+
+ Returns
+ -------
+ str
+ DDP with unused-parameter detection when requested and distributed;
+ otherwise Lightning's auto strategy.
+ """
+ distributed = (
+ num_nodes > 1
+ or (isinstance(devices, list) and len(devices) > 1)
+ or (isinstance(devices, int) and devices > 1)
+ or (devices == "auto" and torch.cuda.device_count() > 1)
+ )
+ if distributed and find_unused_parameters:
+ return "ddp_find_unused_parameters_true"
+ return "auto"
From 7192dbbcdbf46efd76ab287a5f0bef56e4ee41c1 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:51 +0530
Subject: [PATCH 11/41] Limit unused-parameter detection to zero-KL warm-up
Graph-EFM trains all networks when KL is enabled; only request DDP unused-parameter detection during zero-KL training and only when multiple devices or nodes are used.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503774409
---
neural_lam/train_model.py | 5 ++++-
tests/test_graph_efm_objective.py | 35 +++++++++++++++++++++++++++++++
2 files changed, 39 insertions(+), 1 deletion(-)
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index 27c61d932..647ce0c4d 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -932,7 +932,10 @@ def fit(
strategy=utils.training_strategy(
devices,
compute_config.num_nodes,
- find_unused_parameters=isinstance(forecaster, GraphEFMForecaster),
+ find_unused_parameters=(
+ isinstance(forecaster, GraphEFMForecaster)
+ and forecaster.kl_beta == 0
+ ),
),
accelerator=device_name,
num_nodes=compute_config.num_nodes,
diff --git a/tests/test_graph_efm_objective.py b/tests/test_graph_efm_objective.py
index 4f8d61c69..121e5ff18 100644
--- a/tests/test_graph_efm_objective.py
+++ b/tests/test_graph_efm_objective.py
@@ -201,3 +201,38 @@ def test_prior_ensemble_caches_embeddings_without_caching_samples(objective):
assert predictor.embedding_calls == 1
assert not torch.equal(ensemble[:, 0, :, mask], ensemble[:, 1, :, mask])
torch.testing.assert_close(ensemble[:, 0, :, ~mask], target[:, :, ~mask])
+
+
+@pytest.mark.parametrize(
+ "devices,num_nodes,distributed",
+ [
+ (1, 1, False),
+ ([0], 1, False),
+ (2, 1, True),
+ ([0, 1], 1, True),
+ (1, 2, True),
+ ("auto", 1, True),
+ ],
+)
+@pytest.mark.parametrize("kl_beta", [0, 1])
+def test_graph_efm_training_strategy(
+ objective, monkeypatch, devices, num_nodes, distributed, kl_beta
+):
+ """Unused-parameter detection is confined to distributed warm-up."""
+ # First-party
+ from neural_lam.utils import training_strategy
+
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ forecaster = objective[0]
+ forecaster.kl_beta = kl_beta
+ expected = (
+ "ddp_find_unused_parameters_true"
+ if distributed and kl_beta == 0
+ else "auto"
+ )
+ assert (
+ training_strategy(
+ devices, num_nodes, find_unused_parameters=forecaster.kl_beta == 0
+ )
+ == expected
+ )
From dbe3bdaf461136aec2133b9ad58bb853a905344f Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:25:52 +0530
Subject: [PATCH 12/41] Move Graph-EFM settings from experiment YAML to CLI
options
Architecture, objective and ensemble-size settings belonged to a special YAML section unlike other models; expose them through argparse and the existing typed run configs instead.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503791413
---
neural_lam/config.py | 84 +++++---------
neural_lam/train_model.py | 146 ++++++++++++++---------
tests/test_graph_efm_model.py | 185 ++++--------------------------
tests/test_graph_efm_objective.py | 57 ---------
4 files changed, 143 insertions(+), 329 deletions(-)
diff --git a/neural_lam/config.py b/neural_lam/config.py
index 58596a693..497aecd73 100644
--- a/neural_lam/config.py
+++ b/neural_lam/config.py
@@ -122,55 +122,6 @@ class TrainingConfig:
)
-@dataclasses.dataclass
-class ProbabilisticConfig:
- """
- Configuration for the probabilistic (Graph-EFM) models.
-
- Only used when training or evaluating a probabilistic model
- (``--model graph_efm``/``graph_efm_ms``); ignored otherwise. Every field
- has a default, so the ``probabilistic`` config section may be omitted
- entirely for deterministic models.
-
- Attributes
- ----------
- latent_dim : int, optional
- Dimensionality of the latent variable at each latent-carrying mesh
- node. Defaults to the model's ``hidden_dim`` when None.
- prior_layers : int
- Number of on-mesh GNN layers in the prior.
- encoder_layers : int
- Number of on-mesh GNN layers in the variational encoder.
- decoder_layers : int
- Number of on-mesh GNN layers in the latent decoder.
- learn_prior : bool
- If True, the prior is a learned encoder conditioned on the previous
- state; if False, a constant ``Normal(0, 1)`` prior is used.
- prior_dist : str
- Output distribution of the prior: ``"isotropic"`` or ``"diagonal"``.
- kl_beta : float
- Weight of the KL term in the ELBO. When 0, the prior and KL are not
- computed in the posterior rollout; CRPS can still train the prior.
- crps_weight : float
- Weight of the optional fair CRPS objective from prior trajectories.
- crps_members : int
- Number of independent prior trajectories for CRPS, at least two.
- eval_ensemble_size : int
- Number of ensemble members sampled during validation and testing.
- """
-
- 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"
- kl_beta: float = 1.0
- eval_ensemble_size: int = 5
- crps_weight: float = 0.0
- crps_members: int = 2
-
-
@dataclasses.dataclass
class NeuralLAMConfig(dataclass_wizard.JSONWizard, dataclass_wizard.YAMLWizard):
"""
@@ -191,17 +142,11 @@ class NeuralLAMConfig(dataclass_wizard.JSONWizard, dataclass_wizard.YAMLWizard):
training : TrainingConfig
Configuration for training the model, including loss function and
feature-weighting strategy. Defaults to ``TrainingConfig()``.
- probabilistic : ProbabilisticConfig
- Graph-EFM architecture, objective, and evaluation settings.
"""
datastores: dict[str, DatastoreSelection]
training: TrainingConfig = dataclasses.field(default_factory=TrainingConfig)
- probabilistic: ProbabilisticConfig = dataclasses.field(
- default_factory=ProbabilisticConfig
- )
-
class _(dataclass_wizard.JSONWizard.Meta):
"""
Define the configuration class as a JSON wizard class.
@@ -350,6 +295,16 @@ 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 or None
+ Graph-EFM mesh depths; defaults to 2, 2 and 4 respectively.
+ learn_prior : bool or None
+ Learn the Graph-EFM prior; defaults to True.
+ prior_dist : str or None
+ Graph-EFM prior covariance, isotropic (default) or diagonal.
+
+ Unset Graph-EFM options inherit checkpoint values when loading.
"""
model: str = "graph_lam"
@@ -363,6 +318,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 | None = None
+ encoder_layers: int | None = None
+ decoder_layers: int | None = None
+ learn_prior: bool | None = None
+ prior_dist: str | None = None
@dataclasses.dataclass
@@ -372,6 +333,15 @@ class TrainRunConfig:
Attributes
----------
+ kl_beta : float or None
+ Graph-EFM KL weight; defaults to 1.0.
+ crps_weight : float or None
+ Graph-EFM fair CRPS weight; defaults to 0.0.
+ crps_members : int or None
+ Independent prior trajectories for fair CRPS; defaults to 2.
+ eval_ensemble_size : int or None
+ Graph-EFM evaluation ensemble size; defaults to 5.
+ Unset Graph-EFM options inherit checkpoint values when loading.
epochs : int, default 200
Number of training epochs.
batch_size : int, default 4
@@ -408,6 +378,10 @@ class TrainRunConfig:
Whether to create animation GIFs during evaluation.
"""
+ kl_beta: float | None = None
+ crps_weight: float | None = None
+ crps_members: int | None = None
+ eval_ensemble_size: int | None = None
epochs: int = 200
batch_size: int = 4
ar_steps_train: int = 1
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index 647ce0c4d..db4caf538 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -7,7 +7,12 @@
import random
import shutil
import time
-from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, Namespace
+from argparse import (
+ ArgumentDefaultsHelpFormatter,
+ ArgumentParser,
+ BooleanOptionalAction,
+ Namespace,
+)
from pathlib import Path
from typing import Any, cast
@@ -15,7 +20,6 @@
# for logging the model:
import pytorch_lightning as pl
import torch
-import yaml
from lightning_fabric.utilities import seed
from loguru import logger
@@ -30,7 +34,6 @@
ModelConfig,
NeuralLAMConfig,
OutputClamping,
- ProbabilisticConfig,
TrainingConfig,
TrainRunConfig,
UniformFeatureWeighting,
@@ -59,7 +62,6 @@
DatastoreSelection,
ManualStateFeatureWeighting,
NeuralLAMConfig,
- ProbabilisticConfig,
OutputClamping,
TrainingConfig,
UniformFeatureWeighting,
@@ -107,8 +109,7 @@ def build_predictor(
subclasses, gating on the class hierarchy so that future hierarchical
models are covered without maintaining a model-name list. GNN type
arguments fall back to ``InteractionNet`` for checkpoints saved before
- those CLI flags existed. Graph-EFM uses its probabilistic configuration
- for latent dimensions and encoder/decoder depths.
+ those CLI flags existed. Graph-EFM delegates to its own builder.
Parameters
----------
@@ -117,7 +118,7 @@ def build_predictor(
args : Namespace
Architecture and forcing-window arguments.
config : NeuralLAMConfig
- Output clamping and Graph-EFM settings.
+ Output clamping settings.
datastore : BaseDatastore
Grid features, graph location and standardization statistics.
@@ -142,13 +143,11 @@ def build_predictor(
if getattr(args, name, default) != default:
logger.warning(
"--{} has no effect for Graph-EFM; use the "
- "probabilistic configuration section instead.",
+ "Graph-EFM CLI options instead.",
name,
)
- prob = config.probabilistic
- prefix = (
- "intra_level" if issubclass(predictor_class, GraphEFM) else "m2m"
- )
+ prob = resolve_graph_efm_args(args)
+ prefix = "intra_level" if issubclass(predictor_class, GraphEFM) else "m2m"
layers = {
f"{part}_{prefix}_layers": getattr(prob, f"{part}_layers")
for part in ("prior", "encoder", "decoder")
@@ -228,7 +227,7 @@ def build_forecaster_module(
Additional module settings, including evaluation ensemble size.
"""
if isinstance(predictor, (GraphEFM, GraphEFMMultiScale)):
- prob = config.probabilistic
+ prob = resolve_graph_efm_args(args)
forecaster = GraphEFMForecaster(
predictor,
datastore,
@@ -266,30 +265,44 @@ def __init__(self, prog: str) -> None:
)
-def _restore_probabilistic_config(
- ckpt_hparams: dict[str, Any],
- config: NeuralLAMConfig,
-) -> NeuralLAMConfig:
- """Restore saved Graph-EFM settings without mutating the caller's config.
+GRAPH_EFM_DEFAULTS = {
+ "latent_dim": None,
+ "prior_layers": 2,
+ "encoder_layers": 2,
+ "decoder_layers": 4,
+ "learn_prior": True,
+ "prior_dist": "isotropic",
+ "kl_beta": 1.0,
+ "crps_weight": 0.0,
+ "crps_members": 2,
+ "eval_ensemble_size": 5,
+}
+
+
+def resolve_graph_efm_args(
+ args: Namespace, saved_args: Namespace | None = None
+) -> Namespace:
+ """Resolve Graph-EFM options, preferring explicit values to saved ones.
Parameters
----------
- ckpt_hparams : dict[str, Any]
- Hyperparameters read from a model checkpoint.
- config : NeuralLAMConfig
- Current experiment configuration, used for legacy checkpoints.
+ args : Namespace
+ Current CLI or API options. None means unspecified.
+ saved_args : Namespace or None, optional
+ Checkpoint arguments supplying defaults for unspecified options.
Returns
-------
- NeuralLAMConfig
- Configuration with the saved probabilistic settings, or ``config``
- unchanged if the checkpoint does not contain those settings.
+ Namespace
+ A copy with Graph-EFM options resolved to saved or initial defaults.
"""
- saved_config = ckpt_hparams.get("config")
- saved_probabilistic = getattr(saved_config, "probabilistic", None)
- if saved_probabilistic is None:
- return config
- return dataclasses.replace(config, probabilistic=saved_probabilistic)
+ resolved = vars(args).copy()
+ for name, default in GRAPH_EFM_DEFAULTS.items():
+ value = getattr(args, name, None)
+ if value is None:
+ value = getattr(saved_args, name, None)
+ resolved[name] = default if value is None else value
+ return Namespace(**resolved)
def load_forecasting_module_from_checkpoint(
@@ -304,9 +317,8 @@ def load_forecasting_module_from_checkpoint(
The checkpoint must have been saved with args in hyper_parameters (i.e.
created via train_model.main), so that model class and architecture kwargs
- can be recovered automatically. Graph-EFM probabilistic settings are
- restored from the saved config, falling back to the supplied config
- only for checkpoints without those settings.
+ can be recovered automatically. Graph-EFM architecture and objective options
+ are restored from the saved arguments.
Parameters
----------
@@ -330,7 +342,7 @@ def load_forecasting_module_from_checkpoint(
predictor_class = MODELS[args.model]
is_graph_efm = issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale))
if is_graph_efm:
- config = _restore_probabilistic_config(ckpt["hyper_parameters"], config)
+ args = resolve_graph_efm_args(args)
predictor = build_predictor(predictor_class, args, config, datastore)
forecaster, module_class, _ = build_forecaster_module(
args, config, datastore, predictor
@@ -490,6 +502,43 @@ def build_parser() -> ArgumentParser:
"hard-codes its mesh-down GNN type",
)
+ efm_group = parser.add_argument_group("Graph-EFM Options")
+ for name in (
+ "latent_dim",
+ "prior_layers",
+ "encoder_layers",
+ "decoder_layers",
+ ):
+ efm_group.add_argument(
+ f"--{name}",
+ type=int,
+ help=f"Graph-EFM {name.replace('_', ' ')}; inherits checkpoint "
+ f"value when loading, otherwise {GRAPH_EFM_DEFAULTS[name]}",
+ )
+ efm_group.add_argument(
+ "--learn_prior",
+ action=BooleanOptionalAction,
+ default=None,
+ help="Learn the latent prior (default True); inherits checkpoint value",
+ )
+ efm_group.add_argument(
+ "--prior_dist",
+ choices=["isotropic", "diagonal"],
+ help="Prior covariance (default isotropic); inherits checkpoint value",
+ )
+ for name, arg_type in (
+ ("kl_beta", float),
+ ("crps_weight", float),
+ ("crps_members", int),
+ ("eval_ensemble_size", int),
+ ):
+ efm_group.add_argument(
+ f"--{name}",
+ type=arg_type,
+ help=f"Graph-EFM {name.replace('_', ' ')}; inherits checkpoint "
+ f"value when loading, otherwise {GRAPH_EFM_DEFAULTS[name]}",
+ )
+
# Training options
train_group = parser.add_argument_group("Training Options")
train_group.add_argument(
@@ -513,7 +562,7 @@ def build_parser() -> ArgumentParser:
type=str,
default="wmse",
help="Deterministic loss function, see metrics.py. Graph-EFM uses "
- "a Gaussian likelihood and its probabilistic config objective.",
+ "a Gaussian likelihood with --kl_beta and --crps_weight.",
)
train_group.add_argument(
"--lr", type=float, default=1e-3, help="learning rate"
@@ -685,8 +734,8 @@ def fit(
"""
Run training or evaluation using strongly-typed configuration dataclasses.
- When loading Graph-EFM weights, the checkpoint's probabilistic settings
- take precedence over the current experiment configuration.
+ Unspecified Graph-EFM options inherit checkpoint arguments when loading;
+ explicit options override them to support staged training.
Parameters
----------
@@ -833,25 +882,8 @@ def fit(
# Build predictor and forecaster externally, then inject into
# DeterministicForecastingModule
predictor_class = MODELS[model_config.model]
- if train_config.load and issubclass(
- predictor_class, (GraphEFM, GraphEFMMultiScale)
- ):
- ckpt_hparams = torch.load(train_config.load, weights_only=False).get(
- "hyper_parameters", {}
- )
- restored_config = _restore_probabilistic_config(ckpt_hparams, config)
- if config.probabilistic != restored_config.probabilistic:
- has_probabilistic_section = True
- if config_path is not None and Path(config_path).is_file():
- with open(config_path, encoding="utf-8") as config_file:
- raw_config = yaml.safe_load(config_file) or {}
- has_probabilistic_section = "probabilistic" in raw_config
- if has_probabilistic_section:
- logger.warning(
- "The checkpoint's probabilistic settings take precedence "
- "over the current Graph-EFM configuration."
- )
- config = restored_config
+ if issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)):
+ hparams = resolve_graph_efm_args(hparams)
predictor = build_predictor(predictor_class, hparams, config, datastore)
if not train_config.eval and not predictor.trainable:
@@ -885,7 +917,7 @@ def fit(
run_name = logging_config.logger_run_name
else:
if isinstance(forecaster, GraphEFMForecaster):
- prob = config.probabilistic
+ prob = hparams
layers = (
f"p{prob.prior_layers}-e{prob.encoder_layers}"
f"-d{prob.decoder_layers}"
diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py
index e2bee96cf..f162238c4 100644
--- a/tests/test_graph_efm_model.py
+++ b/tests/test_graph_efm_model.py
@@ -423,27 +423,8 @@ def test_module_training_and_validation_steps():
def test_train_model_assembly_selects_probabilistic_path(
model_name, predictor_class, graph_name
):
- """train_model's build_predictor/build_forecaster_module route the
- graph_efm* models through the probabilistic assembly, reading the
- Graph-EFM hyperparameters from the ``probabilistic`` config section and
- producing the right predictor, forecaster, module class and checkpoint
- monitor."""
- datastore, _ = _datastore_and_config(graph_name)
- config = nlconfig.NeuralLAMConfig(
- datastores={
- "interior": nlconfig.DatastoreSelection(
- kind=datastore.SHORT_NAME, config_path=str(datastore.root_path)
- )
- },
- probabilistic=nlconfig.ProbabilisticConfig(
- latent_dim=4,
- prior_layers=1,
- encoder_layers=1,
- decoder_layers=1,
- kl_beta=0.5,
- eval_ensemble_size=3,
- ),
- )
+ """CLI options assemble the probabilistic predictor and module."""
+ datastore, config = _datastore_and_config(graph_name)
args = Namespace(
model=model_name,
graph=graph_name,
@@ -454,12 +435,17 @@ def test_train_model_assembly_selects_probabilistic_path(
output_std=False,
g2m_gnn_type="InteractionNet",
m2g_gnn_type="InteractionNet",
- loss="mse",
+ loss="wmse",
+ latent_dim=4,
+ prior_layers=1,
+ encoder_layers=1,
+ decoder_layers=1,
+ kl_beta=0.5,
+ eval_ensemble_size=3,
)
predictor = build_predictor(predictor_class, args, config, datastore)
assert isinstance(predictor, predictor_class)
- # Hyperparameters came from config.probabilistic, not the CLI args
assert predictor.latent_dim == 4
forecaster, module_class, module_kwargs = build_forecaster_module(
@@ -490,14 +476,6 @@ def test_training_checkpoint_round_trip(graph_name, output_std, tmp_path):
from neural_lam.train_model import load_forecasting_module_from_checkpoint
datastore, config = _datastore_and_config(graph_name)
- config.probabilistic = nlconfig.ProbabilisticConfig(
- latent_dim=8,
- prior_layers=1,
- encoder_layers=1,
- decoder_layers=2,
- crps_weight=0.1,
- eval_ensemble_size=2,
- )
args = Namespace(
model="graph_efm" if graph_name == "hierarchical" else "graph_efm_ms",
graph=graph_name,
@@ -507,6 +485,12 @@ def test_training_checkpoint_round_trip(graph_name, output_std, tmp_path):
num_future_forcing_steps=1,
output_std=output_std,
loss="wmse",
+ latent_dim=8,
+ prior_layers=1,
+ encoder_layers=1,
+ decoder_layers=2,
+ crps_weight=0.1,
+ eval_ensemble_size=2,
)
predictor = build_predictor(
GraphEFM if graph_name == "hierarchical" else GraphEFMMultiScale,
@@ -553,7 +537,6 @@ def test_training_checkpoint_round_trip(graph_name, output_std, tmp_path):
restored = load_forecasting_module_from_checkpoint(
str(checkpoint), caller_config, datastore
)
- assert caller_config.probabilistic == nlconfig.ProbabilisticConfig()
assert restored.forecaster.predictor.latent_dim == 8
for name, value in model.state_dict().items():
torch.testing.assert_close(restored.state_dict()[name], value)
@@ -727,11 +710,6 @@ def test_graph_efm_run_name_uses_configured_layers(
from neural_lam import train_model
datastore, config = _datastore_and_config(graph_name)
- config.probabilistic = nlconfig.ProbabilisticConfig(
- prior_layers=1,
- encoder_layers=2,
- decoder_layers=3,
- )
names = []
def capture_logger(**kwargs):
@@ -747,6 +725,9 @@ def capture_logger(**kwargs):
model=model_name,
graph=graph_name,
hidden_dim=4,
+ prior_layers=1,
+ encoder_layers=2,
+ decoder_layers=3,
),
train_config=nlconfig.TrainRunConfig(
ar_steps_train=1,
@@ -794,13 +775,6 @@ def cli_graph_efm_checkpoint(request, tmp_path_factory):
config_path=str(datastore.root_path),
)
},
- probabilistic=nlconfig.ProbabilisticConfig(
- latent_dim=8,
- prior_layers=1,
- encoder_layers=1,
- decoder_layers=2,
- eval_ensemble_size=2,
- ),
)
model_name = "graph_efm" if graph_name == "hierarchical" else "graph_efm_ms"
args = train_model.build_parser().parse_args(
@@ -815,6 +789,13 @@ def cli_graph_efm_checkpoint(request, tmp_path_factory):
"4",
]
)
+ args.latent_dim = 8
+ args.prior_layers = 1
+ args.encoder_layers = 1
+ args.decoder_layers = 2
+ args.eval_ensemble_size = 2
+ args.kl_beta = 0
+ args.crps_weight = 0
predictor = build_predictor(
train_model.MODELS[model_name], args, config, datastore
)
@@ -850,119 +831,3 @@ def cli_graph_efm_checkpoint(request, tmp_path_factory):
checkpoint = tmp_path_factory.mktemp(f"cli_{model_name}") / "source.ckpt"
trainer.save_checkpoint(checkpoint)
return datastore, config, checkpoint, model_name, graph_name
-
-
-@pytest.mark.requires_training
-@pytest.mark.parametrize(
- "mode,section",
- [
- ("test", "different"),
- ("test", "equal"),
- ("test", "omitted"),
- ("test", "legacy"),
- (None, "different"),
- ],
-)
-def test_cli_restores_probabilistic_checkpoint_settings(
- cli_graph_efm_checkpoint,
- mode,
- section,
- monkeypatch,
- tmp_path,
-):
- """CLI evaluation and resume build models with checkpoint architecture."""
- # Standard library
- from unittest.mock import Mock
-
- # Third-party
- import yaml
-
- # First-party
- from neural_lam import train_model
-
- datastore, saved_config, checkpoint, model_name, graph_name = (
- cli_graph_efm_checkpoint
- )
- caller_config = nlconfig.NeuralLAMConfig(
- datastores=saved_config.datastores,
- probabilistic=(
- saved_config.probabilistic
- if section in {"equal", "legacy"}
- else nlconfig.ProbabilisticConfig()
- ),
- )
- if section == "legacy":
- saved = torch.load(checkpoint, weights_only=False)
- del saved["hyper_parameters"]["config"]
- checkpoint = tmp_path / "legacy.ckpt"
- torch.save(saved, checkpoint)
- raw_config = yaml.safe_load(caller_config.to_yaml())
- if section == "omitted":
- del raw_config["probabilistic"]
- config_path = tmp_path / "experiment.yaml"
- config_path.write_text(yaml.safe_dump(raw_config))
-
- real_trainer = train_model.pl.Trainer
- trainers = []
-
- def build_test_trainer(**kwargs):
- trainer = real_trainer(
- **kwargs,
- limit_train_batches=1,
- limit_val_batches=1,
- limit_test_batches=1,
- enable_progress_bar=False,
- enable_model_summary=False,
- )
- trainers.append(trainer)
- return trainer
-
- warning = Mock()
- monkeypatch.setattr(train_model.pl, "Trainer", build_test_trainer)
- monkeypatch.setattr(train_model.logger, "warning", warning)
- (tmp_path / "loaded").mkdir()
- result = train_model.fit(
- model_config=nlconfig.ModelConfig(
- model=model_name,
- graph=graph_name,
- hidden_dim=4,
- ),
- train_config=nlconfig.TrainRunConfig(
- epochs=2,
- batch_size=2,
- ar_steps_train=1,
- ar_steps_eval=1,
- val_steps_to_log=[1],
- num_sanity_val_steps=0,
- eval=mode,
- load=str(checkpoint),
- ),
- data_config=nlconfig.DataConfig(num_workers=0),
- compute_config=nlconfig.ComputeConfig(devices=1),
- logging_config=nlconfig.LoggingConfig(
- runs_root=str(tmp_path), logger_run_name="loaded"
- ),
- config=caller_config,
- datastore=datastore,
- config_path=str(config_path),
- )
- evaluated = trainers[0].lightning_module
- assert evaluated.forecaster.predictor.latent_dim == 8
- assert evaluated.hparams.config.probabilistic == saved_config.probabilistic
- assert result.checkpoint_path is not None
- if section == "different":
- warning.assert_called_once()
- assert (
- "checkpoint's probabilistic settings take precedence"
- in warning.call_args.args[0]
- )
- else:
- warning.assert_not_called()
- if mode == "test":
- source_weights = torch.load(checkpoint, weights_only=False)[
- "state_dict"
- ]
- for name, value in evaluated.state_dict().items():
- torch.testing.assert_close(value, source_weights[name])
- else:
- assert trainers[0].global_step > 1
diff --git a/tests/test_graph_efm_objective.py b/tests/test_graph_efm_objective.py
index 121e5ff18..a663f6d5f 100644
--- a/tests/test_graph_efm_objective.py
+++ b/tests/test_graph_efm_objective.py
@@ -144,63 +144,6 @@ def test_invalid_objective_settings(kwargs):
)
-def test_probabilistic_yaml_round_trip():
- """Optional Graph-EFM settings survive experiment configuration loading."""
- # First-party
- from neural_lam.config import NeuralLAMConfig, ProbabilisticConfig
-
- config = NeuralLAMConfig.from_yaml("""
- datastores:
- interior:
- kind: mdp
- config_path: danra.yaml
- probabilistic:
- latent_dim: 8
- prior_layers: 1
- encoder_layers: 2
- decoder_layers: 3
- learn_prior: false
- prior_dist: diagonal
- kl_beta: 0.5
- crps_weight: 0.2
- crps_members: 4
- eval_ensemble_size: 6
- """)
- assert config.probabilistic == ProbabilisticConfig(
- latent_dim=8,
- prior_layers=1,
- encoder_layers=2,
- decoder_layers=3,
- learn_prior=False,
- prior_dist="diagonal",
- kl_beta=0.5,
- crps_weight=0.2,
- crps_members=4,
- eval_ensemble_size=6,
- )
- assert NeuralLAMConfig.from_yaml(config.to_yaml()) == config
-
-
-def test_crps_reuses_graph_across_independent_prior_trajectories(objective):
- """Training embeds once for both variational and all prior rollouts."""
- forecaster, predictor, mask, init, forcing, target = objective
- forecaster.crps_weight = 1
- forecaster.crps_members = 3
- loss, _ = forecaster.compute_training_loss(init, forcing, target, mask)
- assert predictor.embedding_calls == 1
- assert len(predictor.graphs) == 3 * forcing.shape[1]
- assert all(graph is predictor.graphs[0] for graph in predictor.graphs)
- loss.backward()
- assert predictor.mean.grad.abs() > 0
-
-
-def test_prior_ensemble_caches_embeddings_without_caching_samples(objective):
- """Evaluation also shares embeddings while drawing distinct members."""
- forecaster, predictor, mask, init, forcing, target = objective
- ensemble, _ = forecaster.sample_ensemble(init, forcing, target, 2)
- assert predictor.embedding_calls == 1
- assert not torch.equal(ensemble[:, 0, :, mask], ensemble[:, 1, :, mask])
- torch.testing.assert_close(ensemble[:, 0, :, ~mask], target[:, :, ~mask])
@pytest.mark.parametrize(
From 8f0dfb35efaf0cd0a758350147d9caa8aede71d6 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:26:15 +0530
Subject: [PATCH 13/41] Allow checkpoint objective overrides between training
stages
Restoring saved probabilistic settings unconditionally prevented changing KL and CRPS weights for the next stage; inherit only unspecified Graph-EFM options and preserve explicit overrides, including zero.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503824841
---
neural_lam/train_model.py | 11 +++-
tests/test_graph_efm_model.py | 93 +++++++++++++++++++++++++++++++
tests/test_graph_efm_objective.py | 39 +++++++++++++
3 files changed, 142 insertions(+), 1 deletion(-)
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index db4caf538..21427ac22 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -882,7 +882,16 @@ def fit(
# Build predictor and forecaster externally, then inject into
# DeterministicForecastingModule
predictor_class = MODELS[model_config.model]
- if issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)):
+ if train_config.load and issubclass(
+ predictor_class, (GraphEFM, GraphEFMMultiScale)
+ ):
+ saved_args = (
+ torch.load(train_config.load, weights_only=False)
+ .get("hyper_parameters", {})
+ .get("args")
+ )
+ hparams = resolve_graph_efm_args(hparams, saved_args)
+ elif issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)):
hparams = resolve_graph_efm_args(hparams)
predictor = build_predictor(predictor_class, hparams, config, datastore)
diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py
index f162238c4..cccc4b677 100644
--- a/tests/test_graph_efm_model.py
+++ b/tests/test_graph_efm_model.py
@@ -831,3 +831,96 @@ def cli_graph_efm_checkpoint(request, tmp_path_factory):
checkpoint = tmp_path_factory.mktemp(f"cli_{model_name}") / "source.ckpt"
trainer.save_checkpoint(checkpoint)
return datastore, config, checkpoint, model_name, graph_name
+
+
+@pytest.mark.requires_training
+@pytest.mark.parametrize(
+ "mode,kl_beta,crps_weight",
+ [("test", None, None), (None, 1.0, 0.1), (None, 0.0, 0.0)],
+)
+def test_cli_restores_probabilistic_checkpoint_settings(
+ cli_graph_efm_checkpoint,
+ mode,
+ kl_beta,
+ crps_weight,
+ monkeypatch,
+ tmp_path,
+):
+ """CLI evaluation and resume build models with checkpoint architecture."""
+ # Standard library
+ from unittest.mock import Mock
+
+ # First-party
+ from neural_lam import train_model
+
+ datastore, saved_config, checkpoint, model_name, graph_name = (
+ cli_graph_efm_checkpoint
+ )
+ caller_config = nlconfig.NeuralLAMConfig(datastores=saved_config.datastores)
+ config_path = tmp_path / "experiment.yaml"
+ config_path.write_text(caller_config.to_yaml())
+
+ real_trainer = train_model.pl.Trainer
+ trainers = []
+
+ def build_test_trainer(**kwargs):
+ trainer = real_trainer(
+ **kwargs,
+ limit_train_batches=1,
+ limit_val_batches=1,
+ limit_test_batches=1,
+ enable_progress_bar=False,
+ enable_model_summary=False,
+ )
+ trainers.append(trainer)
+ return trainer
+
+ warning = Mock()
+ monkeypatch.setattr(train_model.pl, "Trainer", build_test_trainer)
+ monkeypatch.setattr(train_model.logger, "warning", warning)
+ (tmp_path / "loaded").mkdir()
+ result = train_model.fit(
+ model_config=nlconfig.ModelConfig(
+ model=model_name,
+ graph=graph_name,
+ hidden_dim=4,
+ ),
+ train_config=nlconfig.TrainRunConfig(
+ epochs=2,
+ batch_size=2,
+ ar_steps_train=1,
+ ar_steps_eval=1,
+ val_steps_to_log=[1],
+ num_sanity_val_steps=0,
+ eval=mode,
+ load=str(checkpoint),
+ kl_beta=kl_beta,
+ crps_weight=crps_weight,
+ ),
+ data_config=nlconfig.DataConfig(num_workers=0),
+ compute_config=nlconfig.ComputeConfig(devices=1),
+ logging_config=nlconfig.LoggingConfig(
+ runs_root=str(tmp_path), logger_run_name="loaded"
+ ),
+ config=caller_config,
+ datastore=datastore,
+ config_path=str(config_path),
+ )
+ evaluated = trainers[0].lightning_module
+ assert evaluated.forecaster.predictor.latent_dim == 8
+ assert evaluated.forecaster.kl_beta == (0 if kl_beta is None else kl_beta)
+ assert evaluated.forecaster.crps_weight == (
+ 0 if crps_weight is None else crps_weight
+ )
+ assert evaluated.eval_ensemble_size == 2
+ assert evaluated.hparams.args.latent_dim == 8
+ assert result.checkpoint_path is not None
+ warning.assert_not_called()
+ if mode == "test":
+ source_weights = torch.load(checkpoint, weights_only=False)[
+ "state_dict"
+ ]
+ for name, value in evaluated.state_dict().items():
+ torch.testing.assert_close(value, source_weights[name])
+ else:
+ assert trainers[0].global_step > 1
diff --git a/tests/test_graph_efm_objective.py b/tests/test_graph_efm_objective.py
index a663f6d5f..23ab9410e 100644
--- a/tests/test_graph_efm_objective.py
+++ b/tests/test_graph_efm_objective.py
@@ -179,3 +179,42 @@ def test_graph_efm_training_strategy(
)
== expected
)
+
+
+def test_graph_efm_cli_options_and_checkpoint_overrides():
+ """Stage changes override saved weights, including explicit zeros."""
+ # First-party
+ from neural_lam.train_model import build_parser, resolve_graph_efm_args
+
+ parser = build_parser()
+ saved = parser.parse_args(
+ [
+ "--config_path",
+ "unused.yaml",
+ "--latent_dim",
+ "8",
+ "--kl_beta",
+ "1",
+ "--crps_weight",
+ "0.2",
+ "--no-learn_prior",
+ ]
+ )
+ current = parser.parse_args(
+ [
+ "--config_path",
+ "unused.yaml",
+ "--kl_beta",
+ "0",
+ "--crps_weight",
+ "0",
+ "--learn_prior",
+ ]
+ )
+ resolved = resolve_graph_efm_args(current, saved)
+ assert resolved.latent_dim == 8
+ assert resolved.kl_beta == 0
+ assert resolved.crps_weight == 0
+ assert resolved.learn_prior is True
+ assert resolved.crps_members == 2
+ assert current.latent_dim is None
From d011c1bd1c2afb69ba25b730c7bba73beb0b3e39 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:26:15 +0530
Subject: [PATCH 14/41] Separate Graph-EFM predictor construction
The generic predictor builder mixed deterministic GNN arguments with Graph-EFM latent and layer settings; delegate Graph-EFM construction to a dedicated helper.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503805051
---
neural_lam/train_model.py | 109 ++++++++++++++++++++++++--------------
1 file changed, 69 insertions(+), 40 deletions(-)
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index 21427ac22..fb5409cd4 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -96,6 +96,73 @@ def example_plots(self, example_i: int) -> Path:
return self.plot_dir / f"example_plots_{example_i}"
+def build_graph_efm_predictor(
+ predictor_class: type,
+ args: Namespace,
+ config: NeuralLAMConfig,
+ datastore: BaseDatastore,
+) -> Any:
+ """Instantiate a Graph-EFM predictor from CLI architecture options.
+
+ Parameters
+ ----------
+ predictor_class : type
+ Hierarchical or multiscale Graph-EFM predictor class.
+ args : Namespace
+ Architecture and forcing-window options.
+ config : NeuralLAMConfig
+ Output clamping configuration.
+ datastore : BaseDatastore
+ Graph features and standardization statistics.
+
+ Returns
+ -------
+ BaseGraphEFM
+ Configured Graph-EFM predictor.
+ """
+ defaults = ModelConfig()
+ ignored = {
+ name: getattr(defaults, name)
+ for name in (
+ "processor_layers",
+ "mesh_aggr",
+ "mesh_up_gnn_type",
+ "mesh_down_gnn_type",
+ )
+ }
+ ignored["loss"] = TrainRunConfig().loss
+ for name, default in ignored.items():
+ if getattr(args, name, default) != default:
+ logger.warning(
+ "--{} has no effect for Graph-EFM; use the "
+ "Graph-EFM CLI options instead.",
+ name,
+ )
+ prob = resolve_graph_efm_args(args)
+ prefix = "intra_level" if issubclass(predictor_class, GraphEFM) else "m2m"
+ layers = {
+ f"{part}_{prefix}_layers": getattr(prob, f"{part}_layers")
+ for part in ("prior", "encoder", "decoder")
+ }
+ return predictor_class(
+ datastore=datastore,
+ graph_name=args.graph,
+ hidden_dim=args.hidden_dim,
+ hidden_layers=args.hidden_layers,
+ latent_dim=prob.latent_dim,
+ learn_prior=prob.learn_prior,
+ prior_dist=prob.prior_dist,
+ num_past_forcing_steps=args.num_past_forcing_steps,
+ num_future_forcing_steps=args.num_future_forcing_steps,
+ output_std=args.output_std,
+ output_clamping_lower=config.training.output_clamping.lower,
+ output_clamping_upper=config.training.output_clamping.upper,
+ g2m_gnn_type=getattr(args, "g2m_gnn_type", "InteractionNet"),
+ m2g_gnn_type=getattr(args, "m2g_gnn_type", "InteractionNet"),
+ **layers,
+ )
+
+
def build_predictor(
predictor_class: type,
args: Namespace,
@@ -128,46 +195,8 @@ def build_predictor(
Predictor configured for its graph family.
"""
if issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)):
- defaults = ModelConfig()
- ignored = {
- name: getattr(defaults, name)
- for name in (
- "processor_layers",
- "mesh_aggr",
- "mesh_up_gnn_type",
- "mesh_down_gnn_type",
- )
- }
- ignored["loss"] = TrainRunConfig().loss
- for name, default in ignored.items():
- if getattr(args, name, default) != default:
- logger.warning(
- "--{} has no effect for Graph-EFM; use the "
- "Graph-EFM CLI options instead.",
- name,
- )
- prob = resolve_graph_efm_args(args)
- prefix = "intra_level" if issubclass(predictor_class, GraphEFM) else "m2m"
- layers = {
- f"{part}_{prefix}_layers": getattr(prob, f"{part}_layers")
- for part in ("prior", "encoder", "decoder")
- }
- return predictor_class(
- datastore=datastore,
- graph_name=args.graph,
- hidden_dim=args.hidden_dim,
- hidden_layers=args.hidden_layers,
- latent_dim=prob.latent_dim,
- learn_prior=prob.learn_prior,
- prior_dist=prob.prior_dist,
- num_past_forcing_steps=args.num_past_forcing_steps,
- num_future_forcing_steps=args.num_future_forcing_steps,
- output_std=args.output_std,
- output_clamping_lower=config.training.output_clamping.lower,
- output_clamping_upper=config.training.output_clamping.upper,
- g2m_gnn_type=getattr(args, "g2m_gnn_type", "InteractionNet"),
- m2g_gnn_type=getattr(args, "m2g_gnn_type", "InteractionNet"),
- **layers,
+ return build_graph_efm_predictor(
+ predictor_class, args, config, datastore
)
kwargs = dict(
datastore=datastore,
From d4e14f9d261207a9b23206b6f1552e626c20e8f4 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:26:15 +0530
Subject: [PATCH 15/41] Name the forecaster builder for what it constructs
The helper constructs a forecaster and selects a Lightning module class without instantiating that module; rename it to build_forecaster to avoid implying otherwise.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503814734
---
neural_lam/train_model.py | 6 +-
tests/test_graph_efm_model.py | 10 ++--
tests/test_graph_efm_objective.py | 92 +++++++++++++++++++------------
3 files changed, 64 insertions(+), 44 deletions(-)
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index fb5409cd4..2d05d860c 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -223,7 +223,7 @@ def build_predictor(
return predictor_class(**kwargs)
-def build_forecaster_module(
+def build_forecaster(
args: Namespace,
config: NeuralLAMConfig,
datastore: BaseDatastore,
@@ -373,7 +373,7 @@ def load_forecasting_module_from_checkpoint(
if is_graph_efm:
args = resolve_graph_efm_args(args)
predictor = build_predictor(predictor_class, args, config, datastore)
- forecaster, module_class, _ = build_forecaster_module(
+ forecaster, module_class, _ = build_forecaster(
args, config, datastore, predictor
)
return module_class.load_from_checkpoint(
@@ -929,7 +929,7 @@ def fit(
f"The {model_config.model} model cannot be trained. Run with "
"--eval to evaluate a baseline."
)
- forecaster, module_class, module_kwargs = build_forecaster_module(
+ forecaster, module_class, module_kwargs = build_forecaster(
hparams, config, datastore, predictor
)
diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py
index cccc4b677..d220221cc 100644
--- a/tests/test_graph_efm_model.py
+++ b/tests/test_graph_efm_model.py
@@ -4,7 +4,7 @@
trainable model: the ``GraphEFMForecaster`` ELBO objective, its inherited
ensemble sampling, the ``ProbabilisticForecastingModule`` wrapping, and the
config-aware assembly path in ``train_model`` (``build_predictor`` /
-``build_forecaster_module``). Predictors are built on the real example
+``build_forecaster``). Predictors are built on the real example
datastore with a freshly created graph, mirroring
``tests/test_graph_efm_predictor.py``.
"""
@@ -26,7 +26,7 @@
GraphEFMMultiScale,
ProbabilisticForecastingModule,
)
-from neural_lam.train_model import build_forecaster_module, build_predictor
+from neural_lam.train_model import build_forecaster, build_predictor
from tests.conftest import init_datastore_example
pytestmark = pytest.mark.requires_real_data
@@ -448,7 +448,7 @@ def test_train_model_assembly_selects_probabilistic_path(
assert isinstance(predictor, predictor_class)
assert predictor.latent_dim == 4
- forecaster, module_class, module_kwargs = build_forecaster_module(
+ forecaster, module_class, module_kwargs = build_forecaster(
args, config, datastore, predictor
)
assert isinstance(forecaster, GraphEFMForecaster)
@@ -498,7 +498,7 @@ def test_training_checkpoint_round_trip(graph_name, output_std, tmp_path):
config,
datastore,
)
- forecaster, module_class, module_kwargs = build_forecaster_module(
+ forecaster, module_class, module_kwargs = build_forecaster(
args,
config,
datastore,
@@ -799,7 +799,7 @@ def cli_graph_efm_checkpoint(request, tmp_path_factory):
predictor = build_predictor(
train_model.MODELS[model_name], args, config, datastore
)
- forecaster, module_class, module_kwargs = build_forecaster_module(
+ forecaster, module_class, module_kwargs = build_forecaster(
args,
config,
datastore,
diff --git a/tests/test_graph_efm_objective.py b/tests/test_graph_efm_objective.py
index 23ab9410e..e833b7b7a 100644
--- a/tests/test_graph_efm_objective.py
+++ b/tests/test_graph_efm_objective.py
@@ -144,6 +144,43 @@ def test_invalid_objective_settings(kwargs):
)
+def test_graph_efm_cli_options_and_checkpoint_overrides():
+ """Stage changes override saved weights, including explicit zeros."""
+ # First-party
+ from neural_lam.train_model import build_parser, resolve_graph_efm_args
+
+ parser = build_parser()
+ saved = parser.parse_args(
+ [
+ "--config_path",
+ "unused.yaml",
+ "--latent_dim",
+ "8",
+ "--kl_beta",
+ "1",
+ "--crps_weight",
+ "0.2",
+ "--no-learn_prior",
+ ]
+ )
+ current = parser.parse_args(
+ [
+ "--config_path",
+ "unused.yaml",
+ "--kl_beta",
+ "0",
+ "--crps_weight",
+ "0",
+ "--learn_prior",
+ ]
+ )
+ resolved = resolve_graph_efm_args(current, saved)
+ assert resolved.latent_dim == 8
+ assert resolved.kl_beta == 0
+ assert resolved.crps_weight == 0
+ assert resolved.learn_prior is True
+ assert resolved.crps_members == 2
+ assert current.latent_dim is None
@pytest.mark.parametrize(
@@ -181,40 +218,23 @@ def test_graph_efm_training_strategy(
)
-def test_graph_efm_cli_options_and_checkpoint_overrides():
- """Stage changes override saved weights, including explicit zeros."""
- # First-party
- from neural_lam.train_model import build_parser, resolve_graph_efm_args
+def test_crps_reuses_graph_across_independent_prior_trajectories(objective):
+ """Training embeds once for both variational and all prior rollouts."""
+ forecaster, predictor, mask, init, forcing, target = objective
+ forecaster.crps_weight = 1
+ forecaster.crps_members = 3
+ loss, _ = forecaster.compute_training_loss(init, forcing, target, mask)
+ assert predictor.embedding_calls == 1
+ assert len(predictor.graphs) == 3 * forcing.shape[1]
+ assert all(graph is predictor.graphs[0] for graph in predictor.graphs)
+ loss.backward()
+ assert predictor.mean.grad.abs() > 0
- parser = build_parser()
- saved = parser.parse_args(
- [
- "--config_path",
- "unused.yaml",
- "--latent_dim",
- "8",
- "--kl_beta",
- "1",
- "--crps_weight",
- "0.2",
- "--no-learn_prior",
- ]
- )
- current = parser.parse_args(
- [
- "--config_path",
- "unused.yaml",
- "--kl_beta",
- "0",
- "--crps_weight",
- "0",
- "--learn_prior",
- ]
- )
- resolved = resolve_graph_efm_args(current, saved)
- assert resolved.latent_dim == 8
- assert resolved.kl_beta == 0
- assert resolved.crps_weight == 0
- assert resolved.learn_prior is True
- assert resolved.crps_members == 2
- assert current.latent_dim is None
+
+def test_prior_ensemble_caches_embeddings_without_caching_samples(objective):
+ """Evaluation also shares embeddings while drawing distinct members."""
+ forecaster, predictor, mask, init, forcing, target = objective
+ ensemble, _ = forecaster.sample_ensemble(init, forcing, target, 2)
+ assert predictor.embedding_calls == 1
+ assert not torch.equal(ensemble[:, 0, :, mask], ensemble[:, 1, :, mask])
+ torch.testing.assert_close(ensemble[:, 0, :, ~mask], target[:, :, ~mask])
From cb888e1171f2029a0a68b04c59ae25b73c92d359 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:26:16 +0530
Subject: [PATCH 16/41] Condense the Graph-EFM changelog entry
Replace the implementation-history paragraph with one feature summary in the Added section.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503829351
---
CHANGELOG.md | 6 +-----
1 file changed, 1 insertion(+), 5 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c9235c60a..86ae870e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,11 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
-- Add Graph-EFM forecaster training with Gaussian ELBO and optional fair CRPS,
- probabilistic configuration, CLI assembly and checkpoint loading.
- Restore saved probabilistic settings, share fair CRPS scoring, warn about
- ignored CLI options and name runs using Graph-EFM layer counts.
- Honor saved probabilistic settings in CLI evaluation and resumed training.
+- Add Graph-EFM ensemble forecasting with variational training and fair CRPS
[\#712](https://github.com/mllam/neural-lam/pull/712) @Sir-Sloth-The-Lazy
- Add deterministic and probabilistic forecaster/module interfaces with
From d4ed06a73e150a2f714c34947fc7757fd01cc21a Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:26:16 +0530
Subject: [PATCH 17/41] Document Graph-EFM alongside the supported models
Move Graph-EFM into the model guide, explain its ensemble objective, and provide the paper's MEPS training curriculum with CLI stage and checkpoint examples.
Review: https://github.com/mllam/neural-lam/pull/712#discussion_r4503836189
---
README.md | 107 +++++++++++++++++++++++++++++++++---------------------
1 file changed, 66 insertions(+), 41 deletions(-)
diff --git a/README.md b/README.md
index 3301c926d..8cecab15b 100644
--- a/README.md
+++ b/README.md
@@ -64,47 +64,6 @@ Still, some restrictions are inevitable:
-## Graph-EFM ensemble forecasting
-
-Use `--model graph_efm` with a hierarchical graph, or `--model graph_efm_ms`
-with a flat multiscale graph. Both train with a target-conditioned Gaussian
-negative ELBO and sample forecasts from the latent prior at evaluation time.
-The `--loss` option selects the deterministic models' objective; Graph-EFM
-always uses a Gaussian likelihood, including its log-standard-deviation term.
-Without `--output_std`, observation scales come from the datastore's one-step
-difference statistics and configured feature weights.
-
-When loading a checkpoint for evaluation or resumed training, its saved
-probabilistic settings take precedence over the current YAML section.
-
-Add this optional section alongside `datastores` in the experiment YAML:
-
-```yaml
-probabilistic:
- latent_dim: 64
- prior_layers: 2
- encoder_layers: 2
- decoder_layers: 4
- learn_prior: true
- prior_dist: isotropic
- kl_beta: 1.0
- crps_weight: 0.0
- crps_members: 2
- eval_ensemble_size: 5
-```
-
-Omit `latent_dim` to use `--hidden_dim`. Layer counts control same-level message
-passing for hierarchical graphs and mesh processing for flat graphs.
-A positive `crps_weight` adds fair sample CRPS from `crps_members` independent
-prior trajectories (at least two), separately from the posterior ELBO rollout.
-Both objectives sum over forecast steps and state variables; likelihood and
-CRPS use interior grid nodes, while KL sums over latent mesh nodes.
-Setting `kl_beta: 0` skips the prior in the posterior rollout; CRPS, when enabled,
-still trains the prior. Validation and testing use `eval_ensemble_size` members
-and report ensemble-mean RMSE; validation checkpoints monitor `val_mean_loss`,
-the same objective used for training. Ensemble plotting and further ensemble
-verification metrics are separate follow-ups.
-
# Installing Neural-LAM
When installing `neural-lam` you have a choice of either installing directly with `pip` or using the `uv` package manager.
@@ -590,6 +549,72 @@ 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.
+
+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 |
+
+Fair CRPS uses separate prior trajectories, independent of the variational
+rollout. It sums over variables and averages over interior grid nodes,
+forecast steps and batch. The likelihood sums over interior grid nodes,
+variables and forecast steps; KL sums over latent mesh nodes and steps.
+Both variational terms are averaged over the batch.
+
+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 \
+ --model graph_efm --graph hierarchical --load \
+ --kl_beta 1 --crps_weight 0 --ar_steps_train 1 --lr 1e-3 --epochs 400
+```
+
+Unspecified Graph-EFM options inherit saved checkpoint arguments; explicit
+values, including zero, override them. Keep architecture options consistent
+with the checkpoint. Lightning resumes the epoch counter, so `--epochs` is
+the cumulative target (400 after the first two stages above).
+Omit `--restore_opt` to reset the optimizer and apply the new learning rate;
+include it to resume optimizer state within a stage. Validation checkpoints
+monitor `val_mean_loss`, the training objective; evaluation reports
+ensemble-mean RMSE.
+
### Persistence
A trivial baseline model that returns the previous state unchanged at each step (`--model persistence`). Since it has no learnable parameters, it must be evaluated directly without training (e.g. `--eval val` or `--eval test`).
From 887346437022eb68227e11bb76af1704b6b2b274 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:41:25 +0530
Subject: [PATCH 18/41] Preserve CRPS metric API and single-member reductions
Accept and ignore pred_std in the shared positional slot, including vector scales, and warn before reducing a single-member CRPS to MAE without dropping masking or variable reductions. Keep the fair training wrapper strict about requiring two members.
Port the reviewed behavior from #226.
Review: https://github.com/mllam/neural-lam/pull/226#discussion_r3483089708
---
neural_lam/metrics.py | 17 +++++++++++++++--
tests/test_ensemble_metrics.py | 30 +++++++++++++++++++++++++++---
2 files changed, 42 insertions(+), 5 deletions(-)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index b1e499726..f17ae6589 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -2,6 +2,7 @@
# Standard library
import inspect
+import warnings
from collections.abc import Callable
# Third-party
@@ -396,6 +397,7 @@ def crps_gauss(
def crps_ens(
ensemble: torch.Tensor,
target: torch.Tensor,
+ pred_std: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
average_grid: bool = True,
sum_vars: bool = True,
@@ -418,6 +420,8 @@ def crps_ens(
two independent members.
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
@@ -452,9 +456,13 @@ def crps_ens(
):
raise ValueError("afc_alpha must be finite and between 0 and 1")
num_members = ensemble.shape[ens_dim]
- if num_members < 1 or (num_members < 2 and estimator != "biased"):
- raise ValueError("Fair CRPS requires at least two ensemble members")
+ if num_members < 1:
+ raise ValueError("CRPS requires at least one ensemble member")
if num_members == 1:
+ warnings.warn(
+ "CRPS received a single ensemble member; falling back to MAE.",
+ stacklevel=2,
+ )
return mask_and_reduce_metric(
(ensemble.squeeze(ens_dim) - target).abs(),
mask=mask,
@@ -492,6 +500,7 @@ def crps_ens(
def crps_ens_fair(
ensemble: torch.Tensor,
target: torch.Tensor,
+ pred_std: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
average_grid: bool = True,
sum_vars: bool = True,
@@ -511,6 +520,8 @@ def crps_ens_fair(
num_state_vars)``. At least two independent 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
@@ -531,6 +542,8 @@ def crps_ens_fair(
ValueError
If there are fewer than two members.
"""
+ if ensemble.shape[ens_dim] < 2:
+ raise ValueError("Fair CRPS requires at least two ensemble members")
return crps_ens(
ensemble,
target,
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index 14e322a89..afb1235b9 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -113,11 +113,35 @@ def test_almost_fair_crps_rejects_invalid_alpha(alpha):
def test_empirical_crps_single_member_is_mae():
ensemble = torch.tensor([[[[1.0, 4.0]]]])
target = torch.tensor([[[2.0, 2.0]]])
- torch.testing.assert_close(
- crps_ens(ensemble, target, estimator="biased"), torch.tensor([3.0])
- )
+ with pytest.warns(UserWarning, match="single ensemble member"):
+ actual = crps_ens(ensemble, target, estimator="biased")
+ torch.testing.assert_close(actual, torch.tensor([3.0]))
def test_unknown_crps_estimator():
with pytest.raises(ValueError, match="Unknown CRPS estimator"):
crps_ens(torch.zeros(1, 2, 3, 2), torch.zeros(1, 3, 2), estimator="bad")
+
+
+@pytest.mark.parametrize("sum_vars", [False, True])
+@pytest.mark.parametrize("estimator", ["unbiased", "biased", "almost-fair"])
+def test_single_member_crps_warns_and_preserves_mask_and_variables(
+ sum_vars, estimator
+):
+ ensemble = torch.arange(12.0).reshape(1, 1, 2, 3, 2)
+ target = torch.ones(1, 2, 3, 2)
+ mask = torch.tensor([True, False, True])
+ with pytest.warns(UserWarning, match="single ensemble member"):
+ actual = crps_ens(
+ ensemble,
+ target,
+ torch.tensor([1.0, 2.0]),
+ mask=mask,
+ sum_vars=sum_vars,
+ estimator=estimator,
+ afc_alpha=0.95,
+ )
+ expected = mask_and_reduce_metric(
+ (ensemble[:, 0] - target).abs(), mask, True, sum_vars
+ )
+ torch.testing.assert_close(actual, expected)
From 9ef25e665eac864d8f668d6f7eca67d660056114 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:41:26 +0530
Subject: [PATCH 19/41] Register named ensemble CRPS variants for metric lookup
Make fair, biased and almost-fair CRPS (alpha 0.95) available through get_metric using the standard pred/target/pred_std interface. Reject ensemble metrics as deterministic losses and validate the prediction layout to avoid silently scoring the wrong axis.
Build on #226 by @shauryam2807.
Review: https://github.com/mllam/neural-lam/pull/226#discussion_r3330355456
---
neural_lam/metrics.py | 83 ++++++++++++++-----
.../models/forecasters/deterministic.py | 10 +++
tests/test_ensemble_metrics.py | 48 +++++++++++
tests/test_probabilistic_objectives.py | 3 +
4 files changed, 122 insertions(+), 22 deletions(-)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index f17ae6589..8af9066b2 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -4,6 +4,7 @@
import inspect
import warnings
from collections.abc import Callable
+from functools import partial
# Third-party
import torch
@@ -395,7 +396,7 @@ def crps_gauss(
def crps_ens(
- ensemble: torch.Tensor,
+ pred: torch.Tensor,
target: torch.Tensor,
pred_std: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
@@ -409,15 +410,16 @@ def crps_ens(
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.
+ Gradients are retained for training. The almost-fair variant follows
+ Lang et al. (2024), AIFS: https://arxiv.org/abs/2412.15832.
Parameters
----------
- ensemble : torch.Tensor
+ 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)``. Fair and almost-fair estimation require at least
- two independent members.
+ two independent members. A single member warns and returns MAE.
target : torch.Tensor
Shape ``(..., num_grid_nodes, num_state_vars)``. Ground truth.
pred_std : torch.Tensor or None, optional
@@ -429,7 +431,7 @@ def crps_ens(
sum_vars : bool, optional
Sum over state variables. Default True.
ens_dim : int, optional
- Ensemble dimension in ``ensemble``. Default 1.
+ Ensemble dimension in ``pred``. Default 1.
estimator : str, optional
"biased" scores the empirical ensemble distribution; "unbiased"
(default) estimates the generating distribution's CRPS fairly.
@@ -437,7 +439,6 @@ def crps_ens(
afc_alpha : float or None, optional
For almost-fair estimation, a finite value from 0 (biased) to 1
(unbiased). Required only for the almost-fair estimator.
-
Returns
-------
torch.Tensor
@@ -447,7 +448,7 @@ def crps_ens(
Raises
------
ValueError
- If the estimator, alpha or number of members is invalid.
+ If the estimator, alpha, ensemble layout are invalid.
"""
if estimator not in {"biased", "unbiased", "almost-fair"}:
raise ValueError(f"Unknown CRPS estimator: {estimator}")
@@ -455,7 +456,16 @@ def crps_ens(
afc_alpha is None or not 0 <= afc_alpha <= 1
):
raise ValueError("afc_alpha must be finite and between 0 and 1")
- num_members = ensemble.shape[ens_dim]
+ 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")
+ 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 < 1:
raise ValueError("CRPS requires at least one ensemble member")
if num_members == 1:
@@ -464,25 +474,23 @@ def crps_ens(
stacklevel=2,
)
return mask_and_reduce_metric(
- (ensemble.squeeze(ens_dim) - target).abs(),
+ (pred.squeeze(ens_dim) - target).abs(),
mask=mask,
average_grid=average_grid,
sum_vars=sum_vars,
)
- first = (ensemble - target.unsqueeze(ens_dim)).abs().mean(dim=ens_dim)
+ first = (pred - target.unsqueeze(ens_dim)).abs().mean(dim=ens_dim)
if num_members == 2:
- spread = (
- ensemble.select(ens_dim, 0) - ensemble.select(ens_dim, 1)
- ).abs() / 2
+ spread = (pred.select(ens_dim, 0) - pred.select(ens_dim, 1)).abs() / 2
else:
- ordered = ensemble.sort(dim=ens_dim).values
- rank_shape = [1] * ensemble.ndim
+ 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=ensemble.device,
- dtype=ensemble.dtype,
+ 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))
@@ -498,7 +506,7 @@ def crps_ens(
def crps_ens_fair(
- ensemble: torch.Tensor,
+ pred: torch.Tensor,
target: torch.Tensor,
pred_std: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
@@ -514,7 +522,7 @@ def crps_ens_fair(
Parameters
----------
- ensemble : torch.Tensor
+ 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 independent members are required.
@@ -529,7 +537,7 @@ def crps_ens_fair(
sum_vars : bool, optional
Sum over state variables. Default True.
ens_dim : int, optional
- Ensemble dimension in ``ensemble``. Default 1.
+ Ensemble dimension in ``pred``. Default 1.
Returns
-------
@@ -542,10 +550,10 @@ def crps_ens_fair(
ValueError
If there are fewer than two members.
"""
- if ensemble.shape[ens_dim] < 2:
+ if pred.shape[ens_dim] < 2:
raise ValueError("Fair CRPS requires at least two ensemble members")
return crps_ens(
- ensemble,
+ pred,
target,
mask=mask,
average_grid=average_grid,
@@ -554,6 +562,19 @@ def crps_ens_fair(
)
+crps_ens_biased = partial(crps_ens, estimator="biased")
+crps_ens_almost_fair = partial(
+ crps_ens, estimator="almost-fair", afc_alpha=0.95
+)
+
+ENSEMBLE_METRICS: dict[str, Callable[..., torch.Tensor]] = {
+ "crps_ens": crps_ens,
+ "crps_ens_fair": crps_ens_fair,
+ "crps_ens_biased": crps_ens_biased,
+ "crps_ens_almost_fair": crps_ens_almost_fair,
+}
+
+
DEFINED_METRICS: dict[str, Callable[..., torch.Tensor]] = {
"mse": mse,
"mae": mae,
@@ -561,6 +582,7 @@ def crps_ens_fair(
"wmae": wmae,
"nll": nll,
"crps_gauss": crps_gauss,
+ **ENSEMBLE_METRICS,
}
@@ -586,3 +608,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()
diff --git a/neural_lam/models/forecasters/deterministic.py b/neural_lam/models/forecasters/deterministic.py
index fa48d6d31..eda47a34f 100644
--- a/neural_lam/models/forecasters/deterministic.py
+++ b/neural_lam/models/forecasters/deterministic.py
@@ -57,9 +57,19 @@ def __init__(
The scoring rule (from ``neural_lam.metrics``) applied by
``compute_training_loss``, stored as ``self.loss``. Default
``"wmse"``.
+
+ Raises
+ ------
+ ValueError
+ If loss names a metric requiring an ensemble of predictions.
"""
super().__init__(datastore=datastore)
self.loss = metrics.get_metric(loss)
+ if metrics.requires_ensemble(self.loss):
+ raise ValueError(
+ f"{loss} requires ensemble predictions; use a probabilistic "
+ "forecaster rather than a deterministic loss."
+ )
# Whether the fallback is needed is settled per call in
# _resolve_pred_std
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index afb1235b9..d8cd1d685 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -123,6 +123,41 @@ def test_unknown_crps_estimator():
crps_ens(torch.zeros(1, 2, 3, 2), torch.zeros(1, 3, 2), estimator="bad")
+@pytest.mark.parametrize(
+ "metric_name,kwargs",
+ [
+ ("crps_ens_fair", {"estimator": "unbiased"}),
+ ("crps_ens_biased", {"estimator": "biased"}),
+ (
+ "crps_ens_almost_fair",
+ {"estimator": "almost-fair", "afc_alpha": 0.95},
+ ),
+ ],
+)
+def test_registered_crps_variants_follow_shared_metric_api(metric_name, kwargs):
+ # First-party
+ from neural_lam.metrics import (
+ get_metric,
+ requires_ensemble,
+ requires_pred_std,
+ )
+
+ ensemble = torch.tensor([[[[0.0, 1.0]], [[2.0, 4.0]], [[6.0, 9.0]]]])
+ target = torch.tensor([[[1.0, 3.0]]])
+ metric = get_metric(metric_name)
+ assert requires_ensemble(metric)
+ assert not requires_pred_std(metric)
+ torch.testing.assert_close(
+ metric(
+ pred=ensemble,
+ target=target,
+ pred_std=torch.tensor([0.1, 2.0]),
+ sum_vars=False,
+ ),
+ crps_ens(ensemble, target, sum_vars=False, **kwargs),
+ )
+
+
@pytest.mark.parametrize("sum_vars", [False, True])
@pytest.mark.parametrize("estimator", ["unbiased", "biased", "almost-fair"])
def test_single_member_crps_warns_and_preserves_mask_and_variables(
@@ -145,3 +180,16 @@ def test_single_member_crps_warns_and_preserves_mask_and_variables(
(ensemble[:, 0] - target).abs(), mask, True, sum_vars
)
torch.testing.assert_close(actual, expected)
+
+
+def test_deterministic_forecaster_rejects_ensemble_loss():
+ # First-party
+ from neural_lam.models import DeterministicARForecaster
+ from tests.dummy_datastore import DummyDatastore
+
+ with pytest.raises(ValueError, match="requires ensemble predictions"):
+ DeterministicARForecaster(
+ torch.nn.Identity(),
+ DummyDatastore(n_grid_points=25),
+ loss="crps_ens",
+ )
diff --git a/tests/test_probabilistic_objectives.py b/tests/test_probabilistic_objectives.py
index df13d0fd2..d649ffd87 100644
--- a/tests/test_probabilistic_objectives.py
+++ b/tests/test_probabilistic_objectives.py
@@ -10,6 +10,7 @@
mae,
mse,
nll,
+ requires_ensemble,
requires_pred_std,
wmae,
wmse,
@@ -94,6 +95,8 @@ def test_pred_std_requirement_matches_declaration(metric_name):
metric = get_metric(metric_name)
pred, target = _single_residual_case()
+ if requires_ensemble(metric):
+ pred = pred.unsqueeze(1).expand(-1, 2, -1, -1, -1)
if requires_pred_std(metric):
with pytest.raises(TypeError, match="pred_std"):
metric(pred, target)
From c30eabc60fb420e08bccdec92d7850c9dffb2e0e Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:41:26 +0530
Subject: [PATCH 20/41] Add configurable differentiable CRPS chunking
Limit temporary scoring allocations by splitting a caller-selected batch, forecast-step or spatial dimension. Default to unchunked scoring, preserve gradients, and keep masking and reduction after reassembly. Values and gradients match unchunked scoring for every estimator.
Refs #226.
Review: https://github.com/mllam/neural-lam/pull/226#issuecomment-4877588545
Review: https://github.com/mllam/neural-lam/pull/226#issuecomment-4903056451
---
neural_lam/metrics.py | 56 +++++++++++++++++++++++++++++++++-
tests/test_ensemble_metrics.py | 56 ++++++++++++++++++++++++++++++++++
2 files changed, 111 insertions(+), 1 deletion(-)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 8af9066b2..4bf24175e 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -405,6 +405,9 @@ def crps_ens(
ens_dim: int = 1,
estimator: str = "unbiased",
afc_alpha: float | None = None,
+ *,
+ chunk_size: int | None = None,
+ chunk_dim: int = 0,
) -> torch.Tensor:
"""Compute ensemble CRPS with empirical, fair or almost-fair estimation.
@@ -439,6 +442,15 @@ def crps_ens(
afc_alpha : float or None, optional
For almost-fair estimation, a finite value from 0 (biased) to 1
(unbiased). Required only for the almost-fair estimator.
+ 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
@@ -448,7 +460,7 @@ def crps_ens(
Raises
------
ValueError
- If the estimator, alpha, ensemble layout are invalid.
+ If the estimator, alpha, ensemble layout or chunk settings are invalid.
"""
if estimator not in {"biased", "unbiased", "almost-fair"}:
raise ValueError(f"Unknown CRPS estimator: {estimator}")
@@ -465,6 +477,34 @@ def crps_ens(
raise ValueError(
"CRPS target shape must match predictions without ens_dim"
)
+ 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")
+ target_dim = chunk_dim - int(chunk_dim > ens_dim)
+ entries = [
+ crps_ens(
+ member_chunk,
+ target_chunk,
+ average_grid=False,
+ sum_vars=False,
+ ens_dim=ens_dim,
+ estimator=estimator,
+ 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
+ )
num_members = pred.shape[ens_dim]
if num_members < 1:
raise ValueError("CRPS requires at least one ensemble member")
@@ -513,6 +553,9 @@ def crps_ens_fair(
average_grid: bool = True,
sum_vars: bool = True,
ens_dim: int = 1,
+ *,
+ chunk_size: int | None = None,
+ chunk_dim: int = 0,
) -> torch.Tensor:
"""Compute fair CRPS from independent ensemble samples.
@@ -539,6 +582,15 @@ def crps_ens_fair(
ens_dim : int, optional
Ensemble dimension in ``pred``. Default 1.
+ 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
@@ -559,6 +611,8 @@ def crps_ens_fair(
average_grid=average_grid,
sum_vars=sum_vars,
ens_dim=ens_dim,
+ chunk_size=chunk_size,
+ chunk_dim=chunk_dim,
)
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index d8cd1d685..2e93fad28 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -193,3 +193,59 @@ def test_deterministic_forecaster_rejects_ensemble_loss():
DummyDatastore(n_grid_points=25),
loss="crps_ens",
)
+
+
+@pytest.mark.parametrize("members", [2, 5, 12])
+@pytest.mark.parametrize("chunk_dim", [0, 2, -2])
+@pytest.mark.parametrize(
+ "estimator,alpha",
+ [("unbiased", None), ("biased", None), ("almost-fair", 0.95)],
+)
+def test_chunked_crps_matches_values_and_gradients(
+ members, chunk_dim, estimator, alpha
+):
+ torch.manual_seed(12)
+ ensemble = torch.randn(
+ 3, members, 4, 5, 2, dtype=torch.float64, requires_grad=True
+ )
+ target = torch.randn(3, 4, 5, 2, dtype=torch.float64)
+ mask = torch.tensor([True, False, True, False, True])
+ kwargs = dict(
+ mask=mask,
+ average_grid=True,
+ sum_vars=False,
+ estimator=estimator,
+ afc_alpha=alpha,
+ )
+ expected = crps_ens(ensemble, target, **kwargs)
+ actual = crps_ens(
+ ensemble, target, chunk_size=2, chunk_dim=chunk_dim, **kwargs
+ )
+ torch.testing.assert_close(actual, expected)
+ expected_grad = torch.autograd.grad(expected.sum(), ensemble)[0]
+ actual_grad = torch.autograd.grad(actual.sum(), ensemble)[0]
+ torch.testing.assert_close(actual_grad, expected_grad)
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"chunk_size": 0},
+ {"chunk_size": -1},
+ {"chunk_size": 1, "chunk_dim": 1},
+ {"chunk_size": 1, "chunk_dim": 5},
+ ],
+)
+def test_crps_rejects_invalid_chunks(kwargs):
+ with pytest.raises(ValueError, match="chunk_"):
+ crps_ens(torch.zeros(2, 3, 4, 5, 2), torch.zeros(2, 4, 5, 2), **kwargs)
+
+
+def test_fair_crps_chunking_supports_reordered_ensemble_axis():
+ ensemble = torch.randn(3, 2, 4, 5, 2)
+ target = torch.randn(2, 4, 5, 2)
+ expected = crps_ens_fair(ensemble, target, ens_dim=0)
+ actual = crps_ens_fair(
+ ensemble, target, ens_dim=0, chunk_size=2, chunk_dim=2
+ )
+ torch.testing.assert_close(actual, expected)
From 0eb4b0f92b813c6d8863a8679ed1f2ee487d8f99 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:41:26 +0530
Subject: [PATCH 21/41] Port unbiased ensemble variance from PR 226
Add spread_squared with Bessel correction, the shared metric signature, interior masking and variable reductions. Reject ensembles with fewer than two members and verify values, dimensions and gradients.
Absorb the spread metric work from #226 by @shauryam2807 into #712.
---
neural_lam/metrics.py | 57 ++++++++++++++++++++++++++++++++++
tests/test_ensemble_metrics.py | 51 ++++++++++++++++++++++++++++++
2 files changed, 108 insertions(+)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 4bf24175e..aad19c9e8 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -616,6 +616,62 @@ def crps_ens_fair(
)
+def spread_squared(
+ 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,
+) -> torch.Tensor:
+ """Compute unbiased ensemble variance before any spatial reduction.
+
+ Uses Bessel's correction, dividing by S - 1. To report ensemble spread,
+ take the square root after averaging variance over grid and samples.
+ Conditional observation scales are not part of the sampled ensemble's
+ spread and are ignored here.
+
+ Parameters
+ ----------
+ pred : torch.Tensor
+ Shape (B, S, pred_steps, num_grid_nodes, num_state_vars), with the
+ ensemble dimension at ens_dim. At least two members are required.
+ target : torch.Tensor
+ Unused; accepted for compatibility with the shared metric interface.
+ 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 interior 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.
+
+ Returns
+ -------
+ torch.Tensor
+ Ensemble variance with the ensemble axis removed, reduced with
+ mask_and_reduce_metric like the other metrics.
+
+ Raises
+ ------
+ ValueError
+ If the ensemble dimension is invalid or has fewer than two members.
+ """
+ if not -pred.ndim <= ens_dim < pred.ndim:
+ raise ValueError("ens_dim is outside the prediction dimensions")
+ if pred.shape[ens_dim] < 2:
+ raise ValueError(
+ "spread_squared requires at least two ensemble members"
+ )
+ return mask_and_reduce_metric(
+ pred.var(dim=ens_dim, unbiased=True), mask, average_grid, sum_vars
+ )
+
+
crps_ens_biased = partial(crps_ens, estimator="biased")
crps_ens_almost_fair = partial(
crps_ens, estimator="almost-fair", afc_alpha=0.95
@@ -626,6 +682,7 @@ def crps_ens_fair(
"crps_ens_fair": crps_ens_fair,
"crps_ens_biased": crps_ens_biased,
"crps_ens_almost_fair": crps_ens_almost_fair,
+ "spread_squared": spread_squared,
}
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index 2e93fad28..529ecc6a8 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -249,3 +249,54 @@ def test_fair_crps_chunking_supports_reordered_ensemble_axis():
ensemble, target, ens_dim=0, chunk_size=2, chunk_dim=2
)
torch.testing.assert_close(actual, expected)
+
+
+@pytest.mark.parametrize(
+ "average_grid,sum_vars",
+ [(False, False), (True, False), (False, True), (True, True)],
+)
+@pytest.mark.parametrize("ens_dim", [0, 1, -4])
+def test_spread_squared_matches_unbiased_variance(
+ average_grid, sum_vars, ens_dim
+):
+ # First-party
+ from neural_lam.metrics import get_metric, spread_squared
+
+ torch.manual_seed(10)
+ ensemble = torch.randn(2, 4, 3, 5, 2, requires_grad=True)
+ target = torch.zeros(2, 3, 5, 2)
+ mask = torch.tensor([True, False, True, False, True])
+ expected = mask_and_reduce_metric(
+ ensemble.var(1), mask, average_grid, sum_vars
+ )
+ actual = get_metric("spread_squared")(
+ ensemble.movedim(1, ens_dim),
+ target,
+ torch.tensor([0.1, 200.0]),
+ mask=mask,
+ average_grid=average_grid,
+ sum_vars=sum_vars,
+ ens_dim=ens_dim,
+ )
+ torch.testing.assert_close(actual, expected)
+ actual.sum().backward()
+ assert torch.isfinite(ensemble.grad).all()
+ assert ensemble.grad.abs().sum() > 0
+ assert get_metric("spread_squared") is spread_squared
+
+
+@pytest.mark.parametrize("members", [0, 1])
+def test_spread_squared_requires_multiple_members(members):
+ # First-party
+ from neural_lam.metrics import spread_squared
+
+ with pytest.raises(ValueError, match="at least two"):
+ spread_squared(
+ torch.zeros(2, members, 3, 5, 2), torch.zeros(2, 3, 5, 2)
+ )
+
+
+@pytest.mark.parametrize("kwargs", [{}, {"ens_dim": 5}])
+def test_crps_rejects_invalid_ensemble_layout(kwargs):
+ with pytest.raises(ValueError, match="ens_dim|ensemble dimension"):
+ crps_ens(torch.zeros(2, 3, 4, 5, 2), torch.zeros(2, 3, 4, 2), **kwargs)
From 1d6d973c7c20fad4264a5a52e39317e2fcd61f00 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:41:27 +0530
Subject: [PATCH 22/41] Evaluate Graph-EFM with CRPS and ensemble spread
Score one evaluation ensemble with mean error, fair CRPS and unbiased variance on interior nodes. Convert averaged variance to spread only after sample aggregation, then restore physical units so reported spread is comparable with RMSE. Preserve single-member mean-error evaluation.
Refs #226 and #712.
---
neural_lam/models/modules/base.py | 3 +
neural_lam/models/modules/probabilistic.py | 70 ++++++-----
tests/test_ensemble_evaluation.py | 129 +++++++++++++++++++++
3 files changed, 172 insertions(+), 30 deletions(-)
create mode 100644 tests/test_ensemble_evaluation.py
diff --git a/neural_lam/models/modules/base.py b/neural_lam/models/modules/base.py
index 3eb3d8de8..de2f0854a 100644
--- a/neural_lam/models/modules/base.py
+++ b/neural_lam/models/modules/base.py
@@ -964,6 +964,9 @@ def aggregate_and_plot_metrics(
if "mse" in metric_name:
metric_tensor_averaged = torch.sqrt(metric_tensor_averaged)
metric_name = metric_name.replace("mse", "rmse")
+ elif metric_name == "spread_squared":
+ metric_tensor_averaged = torch.sqrt(metric_tensor_averaged)
+ metric_name = "spread"
da_state_stats = self.datastore.get_standardization_dataarray(
"state"
diff --git a/neural_lam/models/modules/probabilistic.py b/neural_lam/models/modules/probabilistic.py
index fbd852bde..965ff6b72 100644
--- a/neural_lam/models/modules/probabilistic.py
+++ b/neural_lam/models/modules/probabilistic.py
@@ -22,9 +22,9 @@ class ProbabilisticForecastingModule(BaseForecastingModule):
Training is inherited unchanged from ``BaseForecastingModule``: the
wrapped forecaster assembles its own training loss. Validation and
testing are ensemble based instead of deterministic: an ensemble is
- sampled through ``forecaster.sample_ensemble`` and its mean scored per
- lead time and variable, with validation additionally reporting the
- forecaster's own objective. The module makes no assumption on how the
+ sampled through ``forecaster.sample_ensemble`` and scored with
+ ensemble-mean RMSE, fair CRPS and spread per lead time and variable,
+ with validation also reporting the forecaster's own objective. The module makes no assumption on how the
members are produced, only that repeated sampling is what an ensemble
is made of.
"""
@@ -66,8 +66,9 @@ def __init__(
Datastore providing grid metadata and data access.
eval_ensemble_size : int
Number of ensemble members sampled during validation and
- testing. Keyword-only and required: how many members to draw is
- a choice this module cannot sensibly default.
+ testing. At least two are needed for fair CRPS and spread;
+ single-member evaluation reports only ensemble-mean error.
+ Keyword-only and required.
datastore_boundary : BaseDatastore, optional
Boundary forcing datastore, used for its standardization
statistics.
@@ -129,28 +130,28 @@ def __init__(
# replaces, so both end up saved.
self.save_hyperparameters({"eval_ensemble_size": eval_ensemble_size})
self.eval_ensemble_size = eval_ensemble_size
- self.val_metrics = {"ens_mse": []}
- self.test_metrics = {"ens_mse": []}
+ metric_names = ["ens_mse"]
+ if eval_ensemble_size > 1:
+ metric_names.extend(("crps_ens", "spread_squared"))
+ self.val_metrics = {name: [] for name in metric_names}
+ self.test_metrics = {name: [] for name in metric_names}
def _ensemble_step(
self,
batch: Batch,
- ) -> torch.Tensor:
+ ) -> dict[str, torch.Tensor]:
"""
- Sample an ensemble and compute the per-variable MSE of its mean.
+ Score an ensemble with mean error, fair CRPS and ensemble variance.
- Shared by ``validation_step`` and ``test_step``: samples
- ``self.eval_ensemble_size`` members and scores the ensemble mean
- with plain (unweighted) MSE on interior nodes. Only the squared
- errors are computed here; ``aggregate_and_plot_metrics`` reduces
- them to a per-lead per-variable RMSE once per epoch, since the
- square root has to be taken after averaging over every sample
- rather than per batch.
+ Validation and testing share one sampled ensemble. Every metric is
+ computed on interior nodes per lead time and variable. Fair CRPS
+ and variance require at least two members; single-member evaluation
+ reports only mean error. Epoch aggregation takes the square roots
+ of mean squared error and variance after sample averaging and
+ rescales all metrics to the variables' physical units.
- This is a diagnostic metric, not the training loss: it always
- scores the ensemble mean with plain MSE, regardless of what
- objective ``compute_training_loss`` actually trains on. The
- objective itself is logged by ``_log_objective``.
+ The forecaster's training objective is logged separately by
+ _log_objective, since its sampling procedure may differ.
Parameters
----------
@@ -159,9 +160,9 @@ def _ensemble_step(
Returns
-------
- torch.Tensor
- Per-variable ensemble-mean MSE, shape
- ``(B, pred_steps, num_state_vars)``, for epoch-end aggregation.
+ dict[str, torch.Tensor]
+ Per-variable metrics, each with shape
+ (B, pred_steps, num_state_vars), for epoch-end aggregation.
"""
init_states, target_states, forcing_features, _boundary, _ = batch
ensemble, _ = self.forecaster.sample_ensemble(
@@ -179,7 +180,16 @@ def _ensemble_step(
sum_vars=False,
) # (B, pred_steps, num_state_vars)
- return entry_mses
+ values = {"ens_mse": entry_mses}
+ if self.eval_ensemble_size > 1:
+ for name in ("crps_ens", "spread_squared"):
+ values[name] = metrics.get_metric(name)(
+ ensemble,
+ target_states,
+ mask=self.interior_mask_bool,
+ sum_vars=False,
+ )
+ return values
def _log_objective(
self,
@@ -230,7 +240,7 @@ def validation_step(
Logs the forecaster's objective as ``val_mean_loss``, scores the
ensemble mean against the target states (see ``_ensemble_step``) and
- collects per-variable ensemble-mean MSE for epoch-end aggregation.
+ collects error, fair CRPS and variance for epoch-end aggregation.
Parameters
----------
@@ -243,8 +253,8 @@ def validation_step(
# and one for computing ensemble metrics. Required as computing loss
# might not involve making a forecast the same way as during inference.
self._log_objective(batch)
- entry_mses = self._ensemble_step(batch)
- self.val_metrics["ens_mse"].append(entry_mses)
+ for name, values in self._ensemble_step(batch).items():
+ self.val_metrics[name].append(values)
def test_step(
self,
@@ -255,7 +265,7 @@ def test_step(
Perform a single ensemble test step.
Scores the ensemble mean against the target states (see
- ``_ensemble_step``) and collects per-variable ensemble-mean MSE for
+ ``_ensemble_step``) and collects error, fair CRPS and variance for
epoch-end aggregation.
Parameters
@@ -265,8 +275,8 @@ def test_step(
batch_idx : int
The index of the batch.
"""
- entry_mses = self._ensemble_step(batch)
- self.test_metrics["ens_mse"].append(entry_mses)
+ for name, values in self._ensemble_step(batch).items():
+ self.test_metrics[name].append(values)
def on_test_epoch_end(self) -> None:
"""
diff --git a/tests/test_ensemble_evaluation.py b/tests/test_ensemble_evaluation.py
new file mode 100644
index 000000000..2d9c03f5f
--- /dev/null
+++ b/tests/test_ensemble_evaluation.py
@@ -0,0 +1,129 @@
+"""Ensemble scoring and epoch reduction without external forecast data."""
+
+# Standard library
+from unittest.mock import MagicMock, Mock
+
+# Third-party
+import pytest
+import torch
+
+# First-party
+from neural_lam.config import NeuralLAMConfig
+from neural_lam.models import ProbabilisticForecastingModule
+from tests.dummy_datastore import DummyDatastore
+from tests.test_probabilistic_forecaster import (
+ ConcreteProbabilisticARForecaster,
+ NoisyStepPredictor,
+)
+
+
+@pytest.fixture
+def evaluation():
+ datastore = DummyDatastore(n_grid_points=25)
+ config = NeuralLAMConfig(datastores={})
+ forecaster = ConcreteProbabilisticARForecaster(
+ NoisyStepPredictor(datastore), datastore, config=config
+ )
+ model = ProbabilisticForecastingModule(
+ forecaster, config, datastore, eval_ensemble_size=3
+ )
+ torch.manual_seed(2)
+ init = torch.randn(2, 2, 25, 5)
+ target = torch.randn(2, 4, 25, 5)
+ forcing = torch.randn(2, 4, 25, 2)
+ ensemble = torch.randn(2, 3, 4, 25, 5)
+ mask = model.interior_mask_bool
+ ensemble[:, :, :, ~mask] = 1e6
+ forecaster.sample_ensemble = Mock(
+ return_value=(ensemble, torch.full_like(ensemble, 500))
+ )
+ forecaster.compute_training_loss = Mock(
+ return_value=(torch.tensor(0.0), {})
+ )
+ model.log_dict = Mock()
+ return model, (init, target, forcing, None, torch.zeros(2, 4)), ensemble
+
+
+@pytest.mark.parametrize("phase", ["val", "test"])
+def test_evaluation_scores_one_ensemble_on_interior_nodes(evaluation, phase):
+ model, batch, ensemble = evaluation
+ target = batch[1]
+ mask = model.interior_mask_bool
+ if phase == "val":
+ model.validation_step(batch, 0)
+ collected = model.val_metrics
+ else:
+ model.test_step(batch, 0)
+ collected = model.test_metrics
+ assert set(collected) == {"ens_mse", "crps_ens", "spread_squared"}
+ expected_mse = (ensemble.mean(1) - target).square()[:, :, mask].mean(-2)
+ first = (ensemble - target.unsqueeze(1)).abs().mean(1)
+ pairs = (ensemble.unsqueeze(2) - ensemble.unsqueeze(1)).abs().sum((1, 2))
+ expected_crps = (first - pairs / 12)[:, :, mask].mean(-2)
+ expected_variance = ensemble.var(1)[:, :, mask].mean(-2)
+ for name, expected in {
+ "ens_mse": expected_mse,
+ "crps_ens": expected_crps,
+ "spread_squared": expected_variance,
+ }.items():
+ torch.testing.assert_close(collected[name][0], expected)
+ assert collected[name][0].shape == (2, 4, 5)
+ model.forecaster.sample_ensemble.assert_called_once()
+
+
+@pytest.mark.parametrize("prefix", ["val", "test"])
+def test_epoch_metrics_root_after_averaging_and_restore_units(
+ evaluation, prefix
+):
+ model, _, _ = evaluation
+ trainer = MagicMock(
+ is_global_zero=True, sanity_checking=False, current_epoch=0
+ )
+ model._trainer = trainer
+ model.all_gather_cat = lambda values: values
+ captured = {}
+
+ def capture(values, phase, name):
+ captured[f"{phase}_{name}"] = values
+ return {}
+
+ model.create_metric_log_dict = capture
+ # Unequal batches must weight individual examples, not batch means.
+ squared_values = [torch.ones(1, 2, 5), torch.full((2, 2, 5), 9.0)]
+ model.aggregate_and_plot_metrics(
+ {
+ "ens_mse": squared_values,
+ "spread_squared": squared_values,
+ "crps_ens": squared_values,
+ },
+ prefix,
+ )
+ state_std = torch.tensor(
+ model.datastore.get_standardization_dataarray("state").state_std.values,
+ dtype=torch.float32,
+ )
+ mean = torch.full((2, 5), 19 / 3)
+ torch.testing.assert_close(
+ captured[f"{prefix}_ens_rmse"], mean.sqrt() * state_std
+ )
+ torch.testing.assert_close(
+ captured[f"{prefix}_spread"], mean.sqrt() * state_std
+ )
+ torch.testing.assert_close(captured[f"{prefix}_crps_ens"], mean * state_std)
+
+
+def test_single_member_evaluation_keeps_mean_error(evaluation):
+ model, batch, ensemble = evaluation
+ model = ProbabilisticForecastingModule(
+ model.forecaster,
+ model.hparams.config,
+ model.datastore,
+ eval_ensemble_size=1,
+ )
+ model.log_dict = Mock()
+ model.forecaster.sample_ensemble = Mock(
+ return_value=(ensemble[:, :1], None)
+ )
+ model.validation_step(batch, 0)
+ assert set(model.val_metrics) == {"ens_mse"}
+ assert torch.isfinite(model.val_metrics["ens_mse"][0]).all()
From 00712401d2fcd43c3fb957755b78afeefbf0d8f7 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 16 Nov 2026 11:41:27 +0530
Subject: [PATCH 23/41] Document ensemble verification metrics with Graph-EFM
training
Describe the shared CRPS objective and evaluation metrics, metric lookup variants, watched metric names, physical scaling and optional scoring chunks. Extend the existing #712 changelog entry to cover ensemble spread.
Refs #226 and #712.
---
CHANGELOG.md | 2 +-
README.md | 33 ++++++++++++++++++++--
neural_lam/models/modules/probabilistic.py | 6 ++--
3 files changed, 35 insertions(+), 6 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 86ae870e1..8fa6eeaec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
-- Add Graph-EFM ensemble forecasting with variational training and fair CRPS
+- Add Graph-EFM ensemble forecasting with variational training, CRPS and spread
[\#712](https://github.com/mllam/neural-lam/pull/712) @Sir-Sloth-The-Lazy
- Add deterministic and probabilistic forecaster/module interfaces with
diff --git a/README.md b/README.md
index 8cecab15b..0754142a5 100644
--- a/README.md
+++ b/README.md
@@ -613,7 +613,36 @@ the cumulative target (400 after the first two stages above).
Omit `--restore_opt` to reset the optimizer and apply the new learning rate;
include it to resume optimizer state within a stage. Validation checkpoints
monitor `val_mean_loss`, the training objective; evaluation reports
-ensemble-mean RMSE.
+ensemble-mean RMSE, fair CRPS and ensemble spread for each forecast step
+and variable, computed from the same prior ensemble on interior nodes.
+Spread is the square root of unbiased ensemble variance after averaging
+across grid points and samples; CRPS and spread are reported in the state
+variables' physical units. At least two evaluation members are required for
+CRPS and spread; single-member evaluation reports only mean error.
+Use `val_crps_ens`, `test_crps_ens`, `val_spread` or `test_spread` with
+`--metrics_watch` and `--var_leads_metrics_watch` to log selected variables
+and lead times. Testing also saves the metric heatmaps and CSV values.
+
+The shared metric API exposes `crps_ens`, `crps_ens_fair`,
+`crps_ens_biased`, `crps_ens_almost_fair` (alpha 0.95), and `spread_squared`.
+Graph-EFM uses the same fair CRPS implementation for its training objective.
+All metrics follow `(B, S, pred_steps, num_grid_nodes, num_state_vars)`,
+preserve gradients and use the shared grid mask and variable reductions.
+`pred_std` is accepted for API compatibility but does not affect these
+sample-based metrics. Fair CRPS and variance require at least two members;
+the general `crps_ens` function warns and falls back to MAE for one member.
+
+For large forecasts, CRPS supports optional chunking without changing its
+value or gradients. Choose `chunk_dim=0` for batches or `chunk_dim=2` for
+forecast steps; `chunk_size=None` (default) disables chunking:
+
+```python
+from neural_lam.metrics import crps_ens
+
+scores = crps_ens(
+ ensemble, target, sum_vars=False, chunk_size=4, chunk_dim=2
+)
+```
### Persistence
A trivial baseline model that returns the previous state unchanged at each step (`--model persistence`). Since it has no learnable parameters, it must be evaluated directly without training (e.g. `--eval val` or `--eval test`).
@@ -708,7 +737,7 @@ nn.Module
├── GraphLatentDecoder
└── HiGraphLatentDecoder
```
-The `--model` values listed under [Train Models](#train-models) select the step predictor. `GraphEFM` and `GraphEFMMultiScale` are implemented but not yet selectable this way.
+The `--model` values listed under [Train Models](#train-models) select the step predictor. `graph_efm` and `graph_efm_ms` select the Graph-EFM predictors.
The building blocks these are assembled from are also `torch.nn.Module` subclasses:
```
diff --git a/neural_lam/models/modules/probabilistic.py b/neural_lam/models/modules/probabilistic.py
index 965ff6b72..8557c45df 100644
--- a/neural_lam/models/modules/probabilistic.py
+++ b/neural_lam/models/modules/probabilistic.py
@@ -24,9 +24,9 @@ class ProbabilisticForecastingModule(BaseForecastingModule):
testing are ensemble based instead of deterministic: an ensemble is
sampled through ``forecaster.sample_ensemble`` and scored with
ensemble-mean RMSE, fair CRPS and spread per lead time and variable,
- with validation also reporting the forecaster's own objective. The module makes no assumption on how the
- members are produced, only that repeated sampling is what an ensemble
- is made of.
+ with validation also reporting the forecaster's own objective. The
+ module makes no assumption on how members are produced, only that
+ repeated sampling is what an ensemble is made of.
"""
# The wrapped forecaster's forward must sample, so that repeating it
From 6a5b0b0ad2b3cab0930d1690c7aebb3a5f7abe71 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:16:33 +0530
Subject: [PATCH 24/41] Reuse base ensemble sampling for Graph-EFM
---
neural_lam/models/forecasters/graph_efm.py | 18 ++++-----
.../models/forecasters/probabilistic.py | 37 +++++++++++++++++--
2 files changed, 41 insertions(+), 14 deletions(-)
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
index 7d224985b..cd91ed5ef 100644
--- a/neural_lam/models/forecasters/graph_efm.py
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -293,21 +293,17 @@ def sample_ensemble(
ValueError
If num_members is less than one.
"""
- if num_members < 1:
- raise ValueError("num_members must be at least 1")
- if graph_emb is None:
+ if graph_emb is None and num_members > 0:
graph_emb = self.predictor.embedd_graph(init_states.shape[0])
- samples = [
- unroll_forecast(
+ return self._sample_ensemble(
+ num_members,
+ partial(
+ unroll_forecast,
partial(self.predictor, graph_emb=graph_emb),
init_states,
forcing_features,
boundary_states,
self.boundary_mask,
self.interior_mask,
- )
- for _ in range(num_members)
- ]
- ensemble = torch.stack([sample[0] for sample in samples], dim=1)
- scales = [sample[1] for sample in samples if sample[1] is not None]
- return ensemble, torch.stack(scales, dim=1) if scales else None
+ ),
+ )
diff --git a/neural_lam/models/forecasters/probabilistic.py b/neural_lam/models/forecasters/probabilistic.py
index 491aabbf1..0e8a54a14 100644
--- a/neural_lam/models/forecasters/probabilistic.py
+++ b/neural_lam/models/forecasters/probabilistic.py
@@ -1,6 +1,8 @@
"""Forecasters that sample their forecast from a predictive distribution."""
# Standard library
+from collections.abc import Callable
+from functools import partial
# Third-party
import torch
@@ -88,6 +90,37 @@ def sample_ensemble(
others), when the forecaster predicts an std, otherwise
``None``. Dims: same as ``ensemble``.
+ Raises
+ ------
+ ValueError
+ If ``num_members`` is less than 1.
+ """
+ return self._sample_ensemble(
+ num_members,
+ partial(self, init_states, forcing_features, boundary_states),
+ )
+
+ @staticmethod
+ def _sample_ensemble(
+ num_members: int,
+ sample_member: Callable[[], tuple[torch.Tensor, torch.Tensor | None]],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Sample and stack an ensemble along the dimension after batch.
+
+ Parameters
+ ----------
+ num_members : int
+ Number of forecasts to sample, at least one.
+ sample_member : callable
+ Draw one forecast and its optional predicted standard deviation.
+
+ Returns
+ -------
+ ensemble : torch.Tensor
+ The sampled forecasts stacked along the ensemble dimension.
+ per_member_std : torch.Tensor or None
+ Predicted standard deviations stacked the same way, if available.
+
Raises
------
ValueError
@@ -101,9 +134,7 @@ def sample_ensemble(
member_list = []
member_std_list = []
for _ in range(num_members):
- prediction, pred_std = self(
- init_states, forcing_features, boundary_states
- )
+ prediction, pred_std = sample_member()
member_list.append(prediction)
if pred_std is not None:
member_std_list.append(pred_std)
From 633330d5a622a6720181e0676ec4009ccec83613 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:05 +0530
Subject: [PATCH 25/41] Defer ensemble spread to a separate change
---
CHANGELOG.md | 2 +-
README.md | 16 +++---
neural_lam/metrics.py | 57 ----------------------
neural_lam/models/modules/base.py | 3 --
neural_lam/models/modules/probabilistic.py | 33 ++++++-------
tests/test_ensemble_evaluation.py | 8 +--
tests/test_ensemble_metrics.py | 45 -----------------
7 files changed, 25 insertions(+), 139 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8fa6eeaec..fec7eaf0d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
-- Add Graph-EFM ensemble forecasting with variational training, CRPS and spread
+- 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
diff --git a/README.md b/README.md
index 0754142a5..9691468d0 100644
--- a/README.md
+++ b/README.md
@@ -613,23 +613,21 @@ the cumulative target (400 after the first two stages above).
Omit `--restore_opt` to reset the optimizer and apply the new learning rate;
include it to resume optimizer state within a stage. Validation checkpoints
monitor `val_mean_loss`, the training objective; evaluation reports
-ensemble-mean RMSE, fair CRPS and ensemble spread for each forecast step
-and variable, computed from the same prior ensemble on interior nodes.
-Spread is the square root of unbiased ensemble variance after averaging
-across grid points and samples; CRPS and spread are reported in the state
-variables' physical units. At least two evaluation members are required for
-CRPS and spread; single-member evaluation reports only mean error.
-Use `val_crps_ens`, `test_crps_ens`, `val_spread` or `test_spread` with
+ensemble-mean RMSE and fair CRPS for each forecast step and variable,
+computed from the same prior ensemble on interior nodes. Both are reported
+in the state variables' physical units. At least two evaluation members
+are required for CRPS. Single-member evaluation reports only mean error.
+Use `val_crps_ens` or `test_crps_ens` with
`--metrics_watch` and `--var_leads_metrics_watch` to log selected variables
and lead times. Testing also saves the metric heatmaps and CSV values.
The shared metric API exposes `crps_ens`, `crps_ens_fair`,
-`crps_ens_biased`, `crps_ens_almost_fair` (alpha 0.95), and `spread_squared`.
+`crps_ens_biased` and `crps_ens_almost_fair` (alpha 0.95).
Graph-EFM uses the same fair CRPS implementation for its training objective.
All metrics follow `(B, S, pred_steps, num_grid_nodes, num_state_vars)`,
preserve gradients and use the shared grid mask and variable reductions.
`pred_std` is accepted for API compatibility but does not affect these
-sample-based metrics. Fair CRPS and variance require at least two members;
+sample-based metrics. Fair CRPS requires at least two members;
the general `crps_ens` function warns and falls back to MAE for one member.
For large forecasts, CRPS supports optional chunking without changing its
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index aad19c9e8..4bf24175e 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -616,62 +616,6 @@ def crps_ens_fair(
)
-def spread_squared(
- 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,
-) -> torch.Tensor:
- """Compute unbiased ensemble variance before any spatial reduction.
-
- Uses Bessel's correction, dividing by S - 1. To report ensemble spread,
- take the square root after averaging variance over grid and samples.
- Conditional observation scales are not part of the sampled ensemble's
- spread and are ignored here.
-
- Parameters
- ----------
- pred : torch.Tensor
- Shape (B, S, pred_steps, num_grid_nodes, num_state_vars), with the
- ensemble dimension at ens_dim. At least two members are required.
- target : torch.Tensor
- Unused; accepted for compatibility with the shared metric interface.
- 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 interior 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.
-
- Returns
- -------
- torch.Tensor
- Ensemble variance with the ensemble axis removed, reduced with
- mask_and_reduce_metric like the other metrics.
-
- Raises
- ------
- ValueError
- If the ensemble dimension is invalid or has fewer than two members.
- """
- if not -pred.ndim <= ens_dim < pred.ndim:
- raise ValueError("ens_dim is outside the prediction dimensions")
- if pred.shape[ens_dim] < 2:
- raise ValueError(
- "spread_squared requires at least two ensemble members"
- )
- return mask_and_reduce_metric(
- pred.var(dim=ens_dim, unbiased=True), mask, average_grid, sum_vars
- )
-
-
crps_ens_biased = partial(crps_ens, estimator="biased")
crps_ens_almost_fair = partial(
crps_ens, estimator="almost-fair", afc_alpha=0.95
@@ -682,7 +626,6 @@ def spread_squared(
"crps_ens_fair": crps_ens_fair,
"crps_ens_biased": crps_ens_biased,
"crps_ens_almost_fair": crps_ens_almost_fair,
- "spread_squared": spread_squared,
}
diff --git a/neural_lam/models/modules/base.py b/neural_lam/models/modules/base.py
index de2f0854a..3eb3d8de8 100644
--- a/neural_lam/models/modules/base.py
+++ b/neural_lam/models/modules/base.py
@@ -964,9 +964,6 @@ def aggregate_and_plot_metrics(
if "mse" in metric_name:
metric_tensor_averaged = torch.sqrt(metric_tensor_averaged)
metric_name = metric_name.replace("mse", "rmse")
- elif metric_name == "spread_squared":
- metric_tensor_averaged = torch.sqrt(metric_tensor_averaged)
- metric_name = "spread"
da_state_stats = self.datastore.get_standardization_dataarray(
"state"
diff --git a/neural_lam/models/modules/probabilistic.py b/neural_lam/models/modules/probabilistic.py
index 8557c45df..fe6992e55 100644
--- a/neural_lam/models/modules/probabilistic.py
+++ b/neural_lam/models/modules/probabilistic.py
@@ -23,7 +23,7 @@ class ProbabilisticForecastingModule(BaseForecastingModule):
wrapped forecaster assembles its own training loss. Validation and
testing are ensemble based instead of deterministic: an ensemble is
sampled through ``forecaster.sample_ensemble`` and scored with
- ensemble-mean RMSE, fair CRPS and spread per lead time and variable,
+ ensemble-mean RMSE and fair CRPS per lead time and variable,
with validation also reporting the forecaster's own objective. The
module makes no assumption on how members are produced, only that
repeated sampling is what an ensemble is made of.
@@ -66,7 +66,7 @@ def __init__(
Datastore providing grid metadata and data access.
eval_ensemble_size : int
Number of ensemble members sampled during validation and
- testing. At least two are needed for fair CRPS and spread;
+ testing. At least two are needed for fair CRPS;
single-member evaluation reports only ensemble-mean error.
Keyword-only and required.
datastore_boundary : BaseDatastore, optional
@@ -132,7 +132,7 @@ def __init__(
self.eval_ensemble_size = eval_ensemble_size
metric_names = ["ens_mse"]
if eval_ensemble_size > 1:
- metric_names.extend(("crps_ens", "spread_squared"))
+ metric_names.append("crps_ens")
self.val_metrics = {name: [] for name in metric_names}
self.test_metrics = {name: [] for name in metric_names}
@@ -141,14 +141,14 @@ def _ensemble_step(
batch: Batch,
) -> dict[str, torch.Tensor]:
"""
- Score an ensemble with mean error, fair CRPS and ensemble variance.
+ Score an ensemble with mean error and fair CRPS.
Validation and testing share one sampled ensemble. Every metric is
computed on interior nodes per lead time and variable. Fair CRPS
- and variance require at least two members; single-member evaluation
- reports only mean error. Epoch aggregation takes the square roots
- of mean squared error and variance after sample averaging and
- rescales all metrics to the variables' physical units.
+ requires at least two members; single-member evaluation reports
+ only mean error. Epoch aggregation takes the square root of mean
+ squared error after sample averaging and rescales both metrics
+ to the variables' physical units.
The forecaster's training objective is logged separately by
_log_objective, since its sampling procedure may differ.
@@ -182,13 +182,12 @@ def _ensemble_step(
values = {"ens_mse": entry_mses}
if self.eval_ensemble_size > 1:
- for name in ("crps_ens", "spread_squared"):
- values[name] = metrics.get_metric(name)(
- ensemble,
- target_states,
- mask=self.interior_mask_bool,
- sum_vars=False,
- )
+ values["crps_ens"] = metrics.crps_ens_fair(
+ ensemble,
+ target_states,
+ mask=self.interior_mask_bool,
+ sum_vars=False,
+ )
return values
def _log_objective(
@@ -240,7 +239,7 @@ def validation_step(
Logs the forecaster's objective as ``val_mean_loss``, scores the
ensemble mean against the target states (see ``_ensemble_step``) and
- collects error, fair CRPS and variance for epoch-end aggregation.
+ collects error and fair CRPS for epoch-end aggregation.
Parameters
----------
@@ -265,7 +264,7 @@ def test_step(
Perform a single ensemble test step.
Scores the ensemble mean against the target states (see
- ``_ensemble_step``) and collects error, fair CRPS and variance for
+ ``_ensemble_step``) and collects error and fair CRPS for
epoch-end aggregation.
Parameters
diff --git a/tests/test_ensemble_evaluation.py b/tests/test_ensemble_evaluation.py
index 2d9c03f5f..a04b8c71b 100644
--- a/tests/test_ensemble_evaluation.py
+++ b/tests/test_ensemble_evaluation.py
@@ -55,16 +55,14 @@ def test_evaluation_scores_one_ensemble_on_interior_nodes(evaluation, phase):
else:
model.test_step(batch, 0)
collected = model.test_metrics
- assert set(collected) == {"ens_mse", "crps_ens", "spread_squared"}
+ assert set(collected) == {"ens_mse", "crps_ens"}
expected_mse = (ensemble.mean(1) - target).square()[:, :, mask].mean(-2)
first = (ensemble - target.unsqueeze(1)).abs().mean(1)
pairs = (ensemble.unsqueeze(2) - ensemble.unsqueeze(1)).abs().sum((1, 2))
expected_crps = (first - pairs / 12)[:, :, mask].mean(-2)
- expected_variance = ensemble.var(1)[:, :, mask].mean(-2)
for name, expected in {
"ens_mse": expected_mse,
"crps_ens": expected_crps,
- "spread_squared": expected_variance,
}.items():
torch.testing.assert_close(collected[name][0], expected)
assert collected[name][0].shape == (2, 4, 5)
@@ -93,7 +91,6 @@ def capture(values, phase, name):
model.aggregate_and_plot_metrics(
{
"ens_mse": squared_values,
- "spread_squared": squared_values,
"crps_ens": squared_values,
},
prefix,
@@ -106,9 +103,6 @@ def capture(values, phase, name):
torch.testing.assert_close(
captured[f"{prefix}_ens_rmse"], mean.sqrt() * state_std
)
- torch.testing.assert_close(
- captured[f"{prefix}_spread"], mean.sqrt() * state_std
- )
torch.testing.assert_close(captured[f"{prefix}_crps_ens"], mean * state_std)
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index 529ecc6a8..e699756d9 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -251,51 +251,6 @@ def test_fair_crps_chunking_supports_reordered_ensemble_axis():
torch.testing.assert_close(actual, expected)
-@pytest.mark.parametrize(
- "average_grid,sum_vars",
- [(False, False), (True, False), (False, True), (True, True)],
-)
-@pytest.mark.parametrize("ens_dim", [0, 1, -4])
-def test_spread_squared_matches_unbiased_variance(
- average_grid, sum_vars, ens_dim
-):
- # First-party
- from neural_lam.metrics import get_metric, spread_squared
-
- torch.manual_seed(10)
- ensemble = torch.randn(2, 4, 3, 5, 2, requires_grad=True)
- target = torch.zeros(2, 3, 5, 2)
- mask = torch.tensor([True, False, True, False, True])
- expected = mask_and_reduce_metric(
- ensemble.var(1), mask, average_grid, sum_vars
- )
- actual = get_metric("spread_squared")(
- ensemble.movedim(1, ens_dim),
- target,
- torch.tensor([0.1, 200.0]),
- mask=mask,
- average_grid=average_grid,
- sum_vars=sum_vars,
- ens_dim=ens_dim,
- )
- torch.testing.assert_close(actual, expected)
- actual.sum().backward()
- assert torch.isfinite(ensemble.grad).all()
- assert ensemble.grad.abs().sum() > 0
- assert get_metric("spread_squared") is spread_squared
-
-
-@pytest.mark.parametrize("members", [0, 1])
-def test_spread_squared_requires_multiple_members(members):
- # First-party
- from neural_lam.metrics import spread_squared
-
- with pytest.raises(ValueError, match="at least two"):
- spread_squared(
- torch.zeros(2, members, 3, 5, 2), torch.zeros(2, 3, 5, 2)
- )
-
-
@pytest.mark.parametrize("kwargs", [{}, {"ens_dim": 5}])
def test_crps_rejects_invalid_ensemble_layout(kwargs):
with pytest.raises(ValueError, match="ens_dim|ensemble dimension"):
From e57b341acf36bfb87288535b1598bb9d5d9ff4b2 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:44 +0530
Subject: [PATCH 26/41] Use consistent fair and unfair CRPS names
---
README.md | 2 +-
neural_lam/metrics.py | 16 ++++++++--------
tests/test_ensemble_metrics.py | 18 +++++++++---------
3 files changed, 18 insertions(+), 18 deletions(-)
diff --git a/README.md b/README.md
index 9691468d0..408476c45 100644
--- a/README.md
+++ b/README.md
@@ -622,7 +622,7 @@ Use `val_crps_ens` or `test_crps_ens` with
and lead times. Testing also saves the metric heatmaps and CSV values.
The shared metric API exposes `crps_ens`, `crps_ens_fair`,
-`crps_ens_biased` and `crps_ens_almost_fair` (alpha 0.95).
+`crps_ens_unfair` and `crps_ens_almost_fair` (alpha 0.95).
Graph-EFM uses the same fair CRPS implementation for its training objective.
All metrics follow `(B, S, pred_steps, num_grid_nodes, num_state_vars)`,
preserve gradients and use the shared grid mask and variable reductions.
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 4bf24175e..1f99e787b 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -403,7 +403,7 @@ def crps_ens(
average_grid: bool = True,
sum_vars: bool = True,
ens_dim: int = 1,
- estimator: str = "unbiased",
+ estimator: str = "fair",
afc_alpha: float | None = None,
*,
chunk_size: int | None = None,
@@ -436,12 +436,12 @@ def crps_ens(
ens_dim : int, optional
Ensemble dimension in ``pred``. Default 1.
estimator : str, optional
- "biased" scores the empirical ensemble distribution; "unbiased"
+ "unfair" scores the empirical ensemble distribution; "fair"
(default) estimates the generating distribution's CRPS fairly.
"almost-fair" interpolates using afc_alpha.
afc_alpha : float or None, optional
- For almost-fair estimation, a finite value from 0 (biased) to 1
- (unbiased). Required only for the almost-fair estimator.
+ For almost-fair estimation, a finite value from 0 (unfair) to 1
+ (fair). Required only for the almost-fair estimator.
chunk_size : int or None, optional
Maximum entries along chunk_dim per scoring call. None disables
chunking. Smaller chunks reduce peak temporary memory; gradients
@@ -462,7 +462,7 @@ def crps_ens(
ValueError
If the estimator, alpha, ensemble layout or chunk settings are invalid.
"""
- if estimator not in {"biased", "unbiased", "almost-fair"}:
+ if estimator not in {"unfair", "fair", "almost-fair"}:
raise ValueError(f"Unknown CRPS estimator: {estimator}")
if estimator == "almost-fair" and (
afc_alpha is None or not 0 <= afc_alpha <= 1
@@ -534,7 +534,7 @@ def crps_ens(
).view(rank_shape)
spread = ((2 * ranks - num_members - 1) * ordered).sum(dim=ens_dim)
spread = spread / (num_members * (num_members - 1))
- if estimator == "biased":
+ if estimator == "unfair":
spread = spread * (num_members - 1) / num_members
elif estimator == "almost-fair":
assert afc_alpha is not None
@@ -616,7 +616,7 @@ def crps_ens_fair(
)
-crps_ens_biased = partial(crps_ens, estimator="biased")
+crps_ens_unfair = partial(crps_ens, estimator="unfair")
crps_ens_almost_fair = partial(
crps_ens, estimator="almost-fair", afc_alpha=0.95
)
@@ -624,7 +624,7 @@ def crps_ens_fair(
ENSEMBLE_METRICS: dict[str, Callable[..., torch.Tensor]] = {
"crps_ens": crps_ens,
"crps_ens_fair": crps_ens_fair,
- "crps_ens_biased": crps_ens_biased,
+ "crps_ens_unfair": crps_ens_unfair,
"crps_ens_almost_fair": crps_ens_almost_fair,
}
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index e699756d9..a5799f0bd 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -66,8 +66,8 @@ def test_fair_crps_rejects_insufficient_members(members):
@pytest.mark.parametrize(
"estimator,alpha",
[
- ("biased", None),
- ("unbiased", None),
+ ("unfair", None),
+ ("fair", None),
("almost-fair", 0.0),
("almost-fair", 0.4),
("almost-fair", 1.0),
@@ -81,8 +81,8 @@ def test_general_crps_estimators(members, estimator, alpha):
first = (ensemble - target.unsqueeze(1)).abs().mean(1)
pairs = (ensemble.unsqueeze(2) - ensemble.unsqueeze(1)).abs().sum((1, 2))
factor = {
- "biased": 1 / members,
- "unbiased": 1 / (members - 1),
+ "unfair": 1 / members,
+ "fair": 1 / (members - 1),
"almost-fair": (members - 1 + (alpha or 0)) / (members * (members - 1)),
}[estimator]
expected = first - pairs * factor / (2 * members)
@@ -114,7 +114,7 @@ def test_empirical_crps_single_member_is_mae():
ensemble = torch.tensor([[[[1.0, 4.0]]]])
target = torch.tensor([[[2.0, 2.0]]])
with pytest.warns(UserWarning, match="single ensemble member"):
- actual = crps_ens(ensemble, target, estimator="biased")
+ actual = crps_ens(ensemble, target, estimator="unfair")
torch.testing.assert_close(actual, torch.tensor([3.0]))
@@ -126,8 +126,8 @@ def test_unknown_crps_estimator():
@pytest.mark.parametrize(
"metric_name,kwargs",
[
- ("crps_ens_fair", {"estimator": "unbiased"}),
- ("crps_ens_biased", {"estimator": "biased"}),
+ ("crps_ens_fair", {"estimator": "fair"}),
+ ("crps_ens_unfair", {"estimator": "unfair"}),
(
"crps_ens_almost_fair",
{"estimator": "almost-fair", "afc_alpha": 0.95},
@@ -159,7 +159,7 @@ def test_registered_crps_variants_follow_shared_metric_api(metric_name, kwargs):
@pytest.mark.parametrize("sum_vars", [False, True])
-@pytest.mark.parametrize("estimator", ["unbiased", "biased", "almost-fair"])
+@pytest.mark.parametrize("estimator", ["fair", "unfair", "almost-fair"])
def test_single_member_crps_warns_and_preserves_mask_and_variables(
sum_vars, estimator
):
@@ -199,7 +199,7 @@ def test_deterministic_forecaster_rejects_ensemble_loss():
@pytest.mark.parametrize("chunk_dim", [0, 2, -2])
@pytest.mark.parametrize(
"estimator,alpha",
- [("unbiased", None), ("biased", None), ("almost-fair", 0.95)],
+ [("fair", None), ("unfair", None), ("almost-fair", 0.95)],
)
def test_chunked_crps_matches_values_and_gradients(
members, chunk_dim, estimator, alpha
From edbe5cea897b26e93afcbb00aac8625333b95231 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:48 +0530
Subject: [PATCH 27/41] Select ensemble CRPS variants with alpha
---
neural_lam/metrics.py | 34 +++++--------------
tests/test_ensemble_metrics.py | 62 +++++++++-------------------------
2 files changed, 25 insertions(+), 71 deletions(-)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 1f99e787b..77e61966d 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -403,9 +403,8 @@ def crps_ens(
average_grid: bool = True,
sum_vars: bool = True,
ens_dim: int = 1,
- estimator: str = "fair",
- afc_alpha: float | None = None,
*,
+ afc_alpha: float = 1.0,
chunk_size: int | None = None,
chunk_dim: int = 0,
) -> torch.Tensor:
@@ -435,13 +434,9 @@ def crps_ens(
Sum over state variables. Default True.
ens_dim : int, optional
Ensemble dimension in ``pred``. Default 1.
- estimator : str, optional
- "unfair" scores the empirical ensemble distribution; "fair"
- (default) estimates the generating distribution's CRPS fairly.
- "almost-fair" interpolates using afc_alpha.
- afc_alpha : float or None, optional
- For almost-fair estimation, a finite value from 0 (unfair) to 1
- (fair). Required only for the almost-fair estimator.
+ 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
@@ -460,13 +455,9 @@ def crps_ens(
Raises
------
ValueError
- If the estimator, alpha, ensemble layout or chunk settings are invalid.
+ If alpha, ensemble layout or chunk settings are invalid.
"""
- if estimator not in {"unfair", "fair", "almost-fair"}:
- raise ValueError(f"Unknown CRPS estimator: {estimator}")
- if estimator == "almost-fair" and (
- afc_alpha is None or not 0 <= afc_alpha <= 1
- ):
+ 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")
@@ -493,7 +484,6 @@ def crps_ens(
average_grid=False,
sum_vars=False,
ens_dim=ens_dim,
- estimator=estimator,
afc_alpha=afc_alpha,
)
for member_chunk, target_chunk in zip(
@@ -534,11 +524,7 @@ def crps_ens(
).view(rank_shape)
spread = ((2 * ranks - num_members - 1) * ordered).sum(dim=ens_dim)
spread = spread / (num_members * (num_members - 1))
- if estimator == "unfair":
- spread = spread * (num_members - 1) / num_members
- elif estimator == "almost-fair":
- assert afc_alpha is not None
- spread = spread * (num_members - 1 + afc_alpha) / num_members
+ spread = spread * ((num_members - 1 + afc_alpha) / num_members)
entry_crps = first - spread
return mask_and_reduce_metric(
entry_crps, mask=mask, average_grid=average_grid, sum_vars=sum_vars
@@ -616,10 +602,8 @@ def crps_ens_fair(
)
-crps_ens_unfair = partial(crps_ens, estimator="unfair")
-crps_ens_almost_fair = partial(
- crps_ens, estimator="almost-fair", afc_alpha=0.95
-)
+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,
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index a5799f0bd..b9cb85895 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -63,35 +63,21 @@ def test_fair_crps_rejects_insufficient_members(members):
@pytest.mark.parametrize("members", [2, 5])
-@pytest.mark.parametrize(
- "estimator,alpha",
- [
- ("unfair", None),
- ("fair", None),
- ("almost-fair", 0.0),
- ("almost-fair", 0.4),
- ("almost-fair", 1.0),
- ],
-)
-def test_general_crps_estimators(members, estimator, alpha):
+@pytest.mark.parametrize("alpha", [0.0, 0.4, 1.0])
+def test_general_crps_estimators(members, alpha):
"""Every estimator agrees with its pairwise definition and gradients."""
torch.manual_seed(8)
ensemble = torch.randn(2, members, 3, 2, requires_grad=True)
target = torch.randn(2, 3, 2)
first = (ensemble - target.unsqueeze(1)).abs().mean(1)
pairs = (ensemble.unsqueeze(2) - ensemble.unsqueeze(1)).abs().sum((1, 2))
- factor = {
- "unfair": 1 / members,
- "fair": 1 / (members - 1),
- "almost-fair": (members - 1 + (alpha or 0)) / (members * (members - 1)),
- }[estimator]
+ factor = (members - 1 + alpha) / (members * (members - 1))
expected = first - pairs * factor / (2 * members)
actual = crps_ens(
ensemble,
target,
average_grid=False,
sum_vars=False,
- estimator=estimator,
afc_alpha=alpha,
)
torch.testing.assert_close(actual, expected)
@@ -99,13 +85,12 @@ def test_general_crps_estimators(members, estimator, alpha):
assert torch.isfinite(ensemble.grad).all()
-@pytest.mark.parametrize("alpha", [None, -1, 2, float("nan"), float("inf")])
+@pytest.mark.parametrize("alpha", [-1, 2, float("nan"), float("inf")])
def test_almost_fair_crps_rejects_invalid_alpha(alpha):
with pytest.raises(ValueError, match="afc_alpha"):
crps_ens(
torch.zeros(1, 2, 3, 2),
torch.zeros(1, 3, 2),
- estimator="almost-fair",
afc_alpha=alpha,
)
@@ -114,27 +99,19 @@ def test_empirical_crps_single_member_is_mae():
ensemble = torch.tensor([[[[1.0, 4.0]]]])
target = torch.tensor([[[2.0, 2.0]]])
with pytest.warns(UserWarning, match="single ensemble member"):
- actual = crps_ens(ensemble, target, estimator="unfair")
+ actual = crps_ens(ensemble, target, afc_alpha=0.0)
torch.testing.assert_close(actual, torch.tensor([3.0]))
-def test_unknown_crps_estimator():
- with pytest.raises(ValueError, match="Unknown CRPS estimator"):
- crps_ens(torch.zeros(1, 2, 3, 2), torch.zeros(1, 3, 2), estimator="bad")
-
-
@pytest.mark.parametrize(
- "metric_name,kwargs",
+ "metric_name,alpha",
[
- ("crps_ens_fair", {"estimator": "fair"}),
- ("crps_ens_unfair", {"estimator": "unfair"}),
- (
- "crps_ens_almost_fair",
- {"estimator": "almost-fair", "afc_alpha": 0.95},
- ),
+ ("crps_ens_fair", 1.0),
+ ("crps_ens_unfair", 0.0),
+ ("crps_ens_almost_fair", 0.95),
],
)
-def test_registered_crps_variants_follow_shared_metric_api(metric_name, kwargs):
+def test_registered_crps_variants_follow_shared_metric_api(metric_name, alpha):
# First-party
from neural_lam.metrics import (
get_metric,
@@ -154,14 +131,14 @@ def test_registered_crps_variants_follow_shared_metric_api(metric_name, kwargs):
pred_std=torch.tensor([0.1, 2.0]),
sum_vars=False,
),
- crps_ens(ensemble, target, sum_vars=False, **kwargs),
+ crps_ens(ensemble, target, sum_vars=False, afc_alpha=alpha),
)
@pytest.mark.parametrize("sum_vars", [False, True])
-@pytest.mark.parametrize("estimator", ["fair", "unfair", "almost-fair"])
+@pytest.mark.parametrize("alpha", [0.0, 0.95, 1.0])
def test_single_member_crps_warns_and_preserves_mask_and_variables(
- sum_vars, estimator
+ sum_vars, alpha
):
ensemble = torch.arange(12.0).reshape(1, 1, 2, 3, 2)
target = torch.ones(1, 2, 3, 2)
@@ -173,8 +150,7 @@ def test_single_member_crps_warns_and_preserves_mask_and_variables(
torch.tensor([1.0, 2.0]),
mask=mask,
sum_vars=sum_vars,
- estimator=estimator,
- afc_alpha=0.95,
+ afc_alpha=alpha,
)
expected = mask_and_reduce_metric(
(ensemble[:, 0] - target).abs(), mask, True, sum_vars
@@ -197,13 +173,8 @@ def test_deterministic_forecaster_rejects_ensemble_loss():
@pytest.mark.parametrize("members", [2, 5, 12])
@pytest.mark.parametrize("chunk_dim", [0, 2, -2])
-@pytest.mark.parametrize(
- "estimator,alpha",
- [("fair", None), ("unfair", None), ("almost-fair", 0.95)],
-)
-def test_chunked_crps_matches_values_and_gradients(
- members, chunk_dim, estimator, alpha
-):
+@pytest.mark.parametrize("alpha", [0.0, 0.95, 1.0])
+def test_chunked_crps_matches_values_and_gradients(members, chunk_dim, alpha):
torch.manual_seed(12)
ensemble = torch.randn(
3, members, 4, 5, 2, dtype=torch.float64, requires_grad=True
@@ -214,7 +185,6 @@ def test_chunked_crps_matches_values_and_gradients(
mask=mask,
average_grid=True,
sum_vars=False,
- estimator=estimator,
afc_alpha=alpha,
)
expected = crps_ens(ensemble, target, **kwargs)
From df406cb9b74803fdac10ce9849519ff41f40b859 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:50 +0530
Subject: [PATCH 28/41] Validate CRPS member counts before chunking
---
neural_lam/metrics.py | 28 ++++++++++++++--------------
1 file changed, 14 insertions(+), 14 deletions(-)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 77e61966d..3c087dba0 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -468,6 +468,20 @@ def crps_ens(
raise ValueError(
"CRPS target shape must match predictions without ens_dim"
)
+ num_members = pred.shape[ens_dim]
+ if num_members < 1:
+ raise ValueError("CRPS requires at least one ensemble member")
+ if num_members == 1:
+ warnings.warn(
+ "CRPS received a single ensemble member; falling back to MAE.",
+ stacklevel=2,
+ )
+ return mask_and_reduce_metric(
+ (pred.squeeze(ens_dim) - target).abs(),
+ mask=mask,
+ average_grid=average_grid,
+ sum_vars=sum_vars,
+ )
if chunk_size is not None:
if chunk_size < 1:
raise ValueError("chunk_size must be positive")
@@ -495,20 +509,6 @@ def crps_ens(
return mask_and_reduce_metric(
torch.cat(entries, dim=target_dim), mask, average_grid, sum_vars
)
- num_members = pred.shape[ens_dim]
- if num_members < 1:
- raise ValueError("CRPS requires at least one ensemble member")
- if num_members == 1:
- warnings.warn(
- "CRPS received a single ensemble member; falling back to MAE.",
- stacklevel=2,
- )
- return mask_and_reduce_metric(
- (pred.squeeze(ens_dim) - target).abs(),
- mask=mask,
- average_grid=average_grid,
- sum_vars=sum_vars,
- )
first = (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
From f983efe95948ab4b7ced93c77180b3ae2a22020a Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:51 +0530
Subject: [PATCH 29/41] Require two members for every CRPS variant
---
README.md | 3 +-
neural_lam/metrics.py | 91 ++--------------------------------
tests/test_ensemble_metrics.py | 48 ++++++------------
3 files changed, 20 insertions(+), 122 deletions(-)
diff --git a/README.md b/README.md
index 408476c45..0be5ef605 100644
--- a/README.md
+++ b/README.md
@@ -627,8 +627,7 @@ Graph-EFM uses the same fair CRPS implementation for its training objective.
All metrics follow `(B, S, pred_steps, num_grid_nodes, num_state_vars)`,
preserve gradients and use the shared grid mask and variable reductions.
`pred_std` is accepted for API compatibility but does not affect these
-sample-based metrics. Fair CRPS requires at least two members;
-the general `crps_ens` function warns and falls back to MAE for one member.
+sample-based metrics. Ensemble CRPS requires at least two members.
For large forecasts, CRPS supports optional chunking without changing its
value or gradients. Choose `chunk_dim=0` for batches or `chunk_dim=2` for
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 3c087dba0..db8de8057 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -2,7 +2,6 @@
# Standard library
import inspect
-import warnings
from collections.abc import Callable
from functools import partial
@@ -420,8 +419,7 @@ def crps_ens(
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)``. Fair and almost-fair estimation require at least
- two independent members. A single member warns and returns MAE.
+ 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
@@ -469,19 +467,8 @@ def crps_ens(
"CRPS target shape must match predictions without ens_dim"
)
num_members = pred.shape[ens_dim]
- if num_members < 1:
- raise ValueError("CRPS requires at least one ensemble member")
- if num_members == 1:
- warnings.warn(
- "CRPS received a single ensemble member; falling back to MAE.",
- stacklevel=2,
- )
- return mask_and_reduce_metric(
- (pred.squeeze(ens_dim) - target).abs(),
- mask=mask,
- average_grid=average_grid,
- sum_vars=sum_vars,
- )
+ 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")
@@ -531,77 +518,7 @@ def crps_ens(
)
-def crps_ens_fair(
- 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,
- *,
- chunk_size: int | None = None,
- chunk_dim: int = 0,
-) -> torch.Tensor:
- """Compute fair CRPS from independent ensemble samples.
-
- 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.
-
- 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 independent 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.
-
- 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 there are fewer than two members.
- """
- if pred.shape[ens_dim] < 2:
- raise ValueError("Fair CRPS requires at least two ensemble members")
- return crps_ens(
- pred,
- target,
- mask=mask,
- average_grid=average_grid,
- sum_vars=sum_vars,
- ens_dim=ens_dim,
- chunk_size=chunk_size,
- chunk_dim=chunk_dim,
- )
-
-
+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)
diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py
index b9cb85895..d65292901 100644
--- a/tests/test_ensemble_metrics.py
+++ b/tests/test_ensemble_metrics.py
@@ -57,9 +57,22 @@ def test_fair_crps_retains_gradients():
@pytest.mark.parametrize("members", [0, 1])
-def test_fair_crps_rejects_insufficient_members(members):
+@pytest.mark.parametrize("chunk_size", [None, 1])
+@pytest.mark.parametrize(
+ "metric_name",
+ ["crps_ens", "crps_ens_fair", "crps_ens_unfair", "crps_ens_almost_fair"],
+)
+def test_crps_rejects_insufficient_members(members, chunk_size, metric_name):
+ # First-party
+ from neural_lam.metrics import get_metric
+
+ metric = get_metric(metric_name)
with pytest.raises(ValueError, match="at least two"):
- crps_ens_fair(torch.zeros(2, members, 4, 3), torch.zeros(2, 4, 3))
+ metric(
+ torch.zeros(2, members, 4, 3),
+ torch.zeros(2, 4, 3),
+ chunk_size=chunk_size,
+ )
@pytest.mark.parametrize("members", [2, 5])
@@ -95,14 +108,6 @@ def test_almost_fair_crps_rejects_invalid_alpha(alpha):
)
-def test_empirical_crps_single_member_is_mae():
- ensemble = torch.tensor([[[[1.0, 4.0]]]])
- target = torch.tensor([[[2.0, 2.0]]])
- with pytest.warns(UserWarning, match="single ensemble member"):
- actual = crps_ens(ensemble, target, afc_alpha=0.0)
- torch.testing.assert_close(actual, torch.tensor([3.0]))
-
-
@pytest.mark.parametrize(
"metric_name,alpha",
[
@@ -135,29 +140,6 @@ def test_registered_crps_variants_follow_shared_metric_api(metric_name, alpha):
)
-@pytest.mark.parametrize("sum_vars", [False, True])
-@pytest.mark.parametrize("alpha", [0.0, 0.95, 1.0])
-def test_single_member_crps_warns_and_preserves_mask_and_variables(
- sum_vars, alpha
-):
- ensemble = torch.arange(12.0).reshape(1, 1, 2, 3, 2)
- target = torch.ones(1, 2, 3, 2)
- mask = torch.tensor([True, False, True])
- with pytest.warns(UserWarning, match="single ensemble member"):
- actual = crps_ens(
- ensemble,
- target,
- torch.tensor([1.0, 2.0]),
- mask=mask,
- sum_vars=sum_vars,
- afc_alpha=alpha,
- )
- expected = mask_and_reduce_metric(
- (ensemble[:, 0] - target).abs(), mask, True, sum_vars
- )
- torch.testing.assert_close(actual, expected)
-
-
def test_deterministic_forecaster_rejects_ensemble_loss():
# First-party
from neural_lam.models import DeterministicARForecaster
From d091935d02a1aef067a82fa9853d2a3ae8cfe7e1 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:53 +0530
Subject: [PATCH 30/41] Explain CRPS ensemble axis normalization
---
neural_lam/metrics.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index db8de8057..7acf66f64 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -461,6 +461,7 @@ def crps_ens(
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(
From 5d059b5307f2f4e6820f6097eedfd16dfbe8d072 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:55 +0530
Subject: [PATCH 31/41] Explain CRPS chunk axis mapping
---
neural_lam/metrics.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 7acf66f64..da91aae52 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -478,7 +478,9 @@ def crps_ens(
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,
From eb224fcd7081a1dd10eb9b21df76121dba048b5b Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:57 +0530
Subject: [PATCH 32/41] Name the CRPS mean member error
---
neural_lam/metrics.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index da91aae52..0f7d29fb8 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -499,7 +499,9 @@ def crps_ens(
return mask_and_reduce_metric(
torch.cat(entries, dim=target_dim), mask, average_grid, sum_vars
)
- first = (pred - target.unsqueeze(ens_dim)).abs().mean(dim=ens_dim)
+ 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:
@@ -515,7 +517,7 @@ def crps_ens(
spread = ((2 * ranks - num_members - 1) * ordered).sum(dim=ens_dim)
spread = spread / (num_members * (num_members - 1))
spread = spread * ((num_members - 1 + afc_alpha) / num_members)
- entry_crps = first - spread
+ entry_crps = mean_member_error - spread
return mask_and_reduce_metric(
entry_crps, mask=mask, average_grid=average_grid, sum_vars=sum_vars
)
From 7c207cb0fa04478426ce8bef888a2d54e5cb4ee7 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:17:58 +0530
Subject: [PATCH 33/41] Explain the sorted CRPS pairwise reduction
---
neural_lam/metrics.py | 3 +++
1 file changed, 3 insertions(+)
diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py
index 0f7d29fb8..6fa6de069 100644
--- a/neural_lam/metrics.py
+++ b/neural_lam/metrics.py
@@ -505,6 +505,8 @@ def crps_ens(
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
@@ -516,6 +518,7 @@ def crps_ens(
).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(
From 9bdc0c384615e6a4cd74741b240cc26467841473 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:18:32 +0530
Subject: [PATCH 34/41] Reject unsupported classes in the Graph-EFM predictor
builder
---
neural_lam/train_model.py | 15 ++++++++++++++-
1 file changed, 14 insertions(+), 1 deletion(-)
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index 2d05d860c..abac298a9 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -119,7 +119,21 @@ def build_graph_efm_predictor(
-------
BaseGraphEFM
Configured Graph-EFM predictor.
+
+ Raises
+ ------
+ ValueError
+ If the predictor class is not a supported Graph-EFM variant.
"""
+ if issubclass(predictor_class, GraphEFM):
+ prefix = "intra_level"
+ elif issubclass(predictor_class, GraphEFMMultiScale):
+ prefix = "m2m"
+ else:
+ raise ValueError(
+ f"Unsupported Graph-EFM predictor: {predictor_class.__name__}"
+ )
+
defaults = ModelConfig()
ignored = {
name: getattr(defaults, name)
@@ -139,7 +153,6 @@ def build_graph_efm_predictor(
name,
)
prob = resolve_graph_efm_args(args)
- prefix = "intra_level" if issubclass(predictor_class, GraphEFM) else "m2m"
layers = {
f"{part}_{prefix}_layers": getattr(prob, f"{part}_layers")
for part in ("prior", "encoder", "decoder")
From d796ab3706adc073405b14d059d41c9c540f37c5 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:19:42 +0530
Subject: [PATCH 35/41] Use current run settings when loading Graph-EFM
checkpoints
---
README.md | 6 +-
neural_lam/config.py | 35 ++++++------
neural_lam/train_model.py | 93 ++++++++-----------------------
tests/test_graph_efm_model.py | 19 ++++---
tests/test_graph_efm_objective.py | 37 ++++--------
5 files changed, 65 insertions(+), 125 deletions(-)
diff --git a/README.md b/README.md
index 0be5ef605..d01d9498c 100644
--- a/README.md
+++ b/README.md
@@ -606,9 +606,9 @@ python -m neural_lam.train_model --config_path \
--kl_beta 1 --crps_weight 0 --ar_steps_train 1 --lr 1e-3 --epochs 400
```
-Unspecified Graph-EFM options inherit saved checkpoint arguments; explicit
-values, including zero, override them. Keep architecture options consistent
-with the checkpoint. Lightning resumes the epoch counter, so `--epochs` is
+The current run's options apply when loading a checkpoint. Repeat any
+non-default architecture options used to train it. Lightning resumes the
+epoch counter, so `--epochs` is
the cumulative target (400 after the first two stages above).
Omit `--restore_opt` to reset the optimizer and apply the new learning rate;
include it to resume optimizer state within a stage. Validation checkpoints
diff --git a/neural_lam/config.py b/neural_lam/config.py
index 497aecd73..e12ff9fae 100644
--- a/neural_lam/config.py
+++ b/neural_lam/config.py
@@ -297,14 +297,12 @@ class ModelConfig:
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 or None
+ prior_layers, encoder_layers, decoder_layers : int
Graph-EFM mesh depths; defaults to 2, 2 and 4 respectively.
- learn_prior : bool or None
+ learn_prior : bool, default True
Learn the Graph-EFM prior; defaults to True.
- prior_dist : str or None
+ prior_dist : str, default "isotropic"
Graph-EFM prior covariance, isotropic (default) or diagonal.
-
- Unset Graph-EFM options inherit checkpoint values when loading.
"""
model: str = "graph_lam"
@@ -319,11 +317,11 @@ class ModelConfig:
mesh_up_gnn_type: str = "InteractionNet"
mesh_down_gnn_type: str = "InteractionNet"
latent_dim: int | None = None
- prior_layers: int | None = None
- encoder_layers: int | None = None
- decoder_layers: int | None = None
- learn_prior: bool | None = None
- prior_dist: str | None = None
+ prior_layers: int = 2
+ encoder_layers: int = 2
+ decoder_layers: int = 4
+ learn_prior: bool = True
+ prior_dist: str = "isotropic"
@dataclasses.dataclass
@@ -333,15 +331,14 @@ class TrainRunConfig:
Attributes
----------
- kl_beta : float or None
+ kl_beta : float, default 1.0
Graph-EFM KL weight; defaults to 1.0.
- crps_weight : float or None
+ crps_weight : float, default 0.0
Graph-EFM fair CRPS weight; defaults to 0.0.
- crps_members : int or None
+ crps_members : int, default 2
Independent prior trajectories for fair CRPS; defaults to 2.
- eval_ensemble_size : int or None
+ eval_ensemble_size : int, default 5
Graph-EFM evaluation ensemble size; defaults to 5.
- Unset Graph-EFM options inherit checkpoint values when loading.
epochs : int, default 200
Number of training epochs.
batch_size : int, default 4
@@ -378,10 +375,10 @@ class TrainRunConfig:
Whether to create animation GIFs during evaluation.
"""
- kl_beta: float | None = None
- crps_weight: float | None = None
- crps_members: int | None = None
- eval_ensemble_size: int | None = None
+ kl_beta: float = 1.0
+ crps_weight: float = 0.0
+ crps_members: int = 2
+ eval_ensemble_size: int = 5
epochs: int = 200
batch_size: int = 4
ar_steps_train: int = 1
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index abac298a9..521865679 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -152,9 +152,10 @@ def build_graph_efm_predictor(
"Graph-EFM CLI options instead.",
name,
)
- prob = resolve_graph_efm_args(args)
layers = {
- f"{part}_{prefix}_layers": getattr(prob, f"{part}_layers")
+ f"{part}_{prefix}_layers": getattr(
+ args, f"{part}_layers", getattr(defaults, f"{part}_layers")
+ )
for part in ("prior", "encoder", "decoder")
}
return predictor_class(
@@ -162,9 +163,9 @@ def build_graph_efm_predictor(
graph_name=args.graph,
hidden_dim=args.hidden_dim,
hidden_layers=args.hidden_layers,
- latent_dim=prob.latent_dim,
- learn_prior=prob.learn_prior,
- prior_dist=prob.prior_dist,
+ latent_dim=getattr(args, "latent_dim", defaults.latent_dim),
+ learn_prior=getattr(args, "learn_prior", defaults.learn_prior),
+ prior_dist=getattr(args, "prior_dist", defaults.prior_dist),
num_past_forcing_steps=args.num_past_forcing_steps,
num_future_forcing_steps=args.num_future_forcing_steps,
output_std=args.output_std,
@@ -269,19 +270,23 @@ def build_forecaster(
Additional module settings, including evaluation ensemble size.
"""
if isinstance(predictor, (GraphEFM, GraphEFMMultiScale)):
- prob = resolve_graph_efm_args(args)
+ defaults = TrainRunConfig()
forecaster = GraphEFMForecaster(
predictor,
datastore,
config=config,
- kl_beta=prob.kl_beta,
- crps_weight=prob.crps_weight,
- crps_members=prob.crps_members,
+ kl_beta=getattr(args, "kl_beta", defaults.kl_beta),
+ crps_weight=getattr(args, "crps_weight", defaults.crps_weight),
+ crps_members=getattr(args, "crps_members", defaults.crps_members),
)
return (
forecaster,
ProbabilisticForecastingModule,
- {"eval_ensemble_size": prob.eval_ensemble_size},
+ {
+ "eval_ensemble_size": getattr(
+ args, "eval_ensemble_size", defaults.eval_ensemble_size
+ )
+ },
)
return (
DeterministicARForecaster(
@@ -307,46 +312,6 @@ def __init__(self, prog: str) -> None:
)
-GRAPH_EFM_DEFAULTS = {
- "latent_dim": None,
- "prior_layers": 2,
- "encoder_layers": 2,
- "decoder_layers": 4,
- "learn_prior": True,
- "prior_dist": "isotropic",
- "kl_beta": 1.0,
- "crps_weight": 0.0,
- "crps_members": 2,
- "eval_ensemble_size": 5,
-}
-
-
-def resolve_graph_efm_args(
- args: Namespace, saved_args: Namespace | None = None
-) -> Namespace:
- """Resolve Graph-EFM options, preferring explicit values to saved ones.
-
- Parameters
- ----------
- args : Namespace
- Current CLI or API options. None means unspecified.
- saved_args : Namespace or None, optional
- Checkpoint arguments supplying defaults for unspecified options.
-
- Returns
- -------
- Namespace
- A copy with Graph-EFM options resolved to saved or initial defaults.
- """
- resolved = vars(args).copy()
- for name, default in GRAPH_EFM_DEFAULTS.items():
- value = getattr(args, name, None)
- if value is None:
- value = getattr(saved_args, name, None)
- resolved[name] = default if value is None else value
- return Namespace(**resolved)
-
-
def load_forecasting_module_from_checkpoint(
ckpt_path: str,
config: NeuralLAMConfig,
@@ -383,8 +348,6 @@ def load_forecasting_module_from_checkpoint(
args = ckpt["hyper_parameters"]["args"]
predictor_class = MODELS[args.model]
is_graph_efm = issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale))
- if is_graph_efm:
- args = resolve_graph_efm_args(args)
predictor = build_predictor(predictor_class, args, config, datastore)
forecaster, module_class, _ = build_forecaster(
args, config, datastore, predictor
@@ -554,19 +517,20 @@ def build_parser() -> ArgumentParser:
efm_group.add_argument(
f"--{name}",
type=int,
- help=f"Graph-EFM {name.replace('_', ' ')}; inherits checkpoint "
- f"value when loading, otherwise {GRAPH_EFM_DEFAULTS[name]}",
+ default=getattr(ModelConfig, name),
+ help=f"Graph-EFM {name.replace('_', ' ')}",
)
efm_group.add_argument(
"--learn_prior",
action=BooleanOptionalAction,
- default=None,
- help="Learn the latent prior (default True); inherits checkpoint value",
+ default=ModelConfig.learn_prior,
+ help="Learn the latent prior",
)
efm_group.add_argument(
"--prior_dist",
choices=["isotropic", "diagonal"],
- help="Prior covariance (default isotropic); inherits checkpoint value",
+ default=ModelConfig.prior_dist,
+ help="Prior covariance",
)
for name, arg_type in (
("kl_beta", float),
@@ -577,8 +541,8 @@ def build_parser() -> ArgumentParser:
efm_group.add_argument(
f"--{name}",
type=arg_type,
- help=f"Graph-EFM {name.replace('_', ' ')}; inherits checkpoint "
- f"value when loading, otherwise {GRAPH_EFM_DEFAULTS[name]}",
+ default=getattr(TrainRunConfig, name),
+ help=f"Graph-EFM {name.replace('_', ' ')}",
)
# Training options
@@ -924,17 +888,6 @@ def fit(
# Build predictor and forecaster externally, then inject into
# DeterministicForecastingModule
predictor_class = MODELS[model_config.model]
- if train_config.load and issubclass(
- predictor_class, (GraphEFM, GraphEFMMultiScale)
- ):
- saved_args = (
- torch.load(train_config.load, weights_only=False)
- .get("hyper_parameters", {})
- .get("args")
- )
- hparams = resolve_graph_efm_args(hparams, saved_args)
- elif issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)):
- hparams = resolve_graph_efm_args(hparams)
predictor = build_predictor(predictor_class, hparams, config, datastore)
if not train_config.eval and not predictor.trainable:
diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py
index d220221cc..6607d98b3 100644
--- a/tests/test_graph_efm_model.py
+++ b/tests/test_graph_efm_model.py
@@ -836,9 +836,9 @@ def cli_graph_efm_checkpoint(request, tmp_path_factory):
@pytest.mark.requires_training
@pytest.mark.parametrize(
"mode,kl_beta,crps_weight",
- [("test", None, None), (None, 1.0, 0.1), (None, 0.0, 0.0)],
+ [("test", 1.0, 0.0), (None, 1.0, 0.1), (None, 0.0, 0.0)],
)
-def test_cli_restores_probabilistic_checkpoint_settings(
+def test_loading_graph_efm_uses_current_run_settings(
cli_graph_efm_checkpoint,
mode,
kl_beta,
@@ -846,7 +846,7 @@ def test_cli_restores_probabilistic_checkpoint_settings(
monkeypatch,
tmp_path,
):
- """CLI evaluation and resume build models with checkpoint architecture."""
+ """Evaluation and resume load weights using the current run settings."""
# Standard library
from unittest.mock import Mock
@@ -884,6 +884,10 @@ def build_test_trainer(**kwargs):
model=model_name,
graph=graph_name,
hidden_dim=4,
+ latent_dim=8,
+ prior_layers=1,
+ encoder_layers=1,
+ decoder_layers=2,
),
train_config=nlconfig.TrainRunConfig(
epochs=2,
@@ -908,11 +912,12 @@ def build_test_trainer(**kwargs):
)
evaluated = trainers[0].lightning_module
assert evaluated.forecaster.predictor.latent_dim == 8
- assert evaluated.forecaster.kl_beta == (0 if kl_beta is None else kl_beta)
- assert evaluated.forecaster.crps_weight == (
- 0 if crps_weight is None else crps_weight
+ assert evaluated.forecaster.kl_beta == kl_beta
+ assert evaluated.forecaster.crps_weight == crps_weight
+ assert (
+ evaluated.eval_ensemble_size
+ == nlconfig.TrainRunConfig().eval_ensemble_size
)
- assert evaluated.eval_ensemble_size == 2
assert evaluated.hparams.args.latent_dim == 8
assert result.checkpoint_path is not None
warning.assert_not_called()
diff --git a/tests/test_graph_efm_objective.py b/tests/test_graph_efm_objective.py
index e833b7b7a..7711e534e 100644
--- a/tests/test_graph_efm_objective.py
+++ b/tests/test_graph_efm_objective.py
@@ -144,26 +144,13 @@ def test_invalid_objective_settings(kwargs):
)
-def test_graph_efm_cli_options_and_checkpoint_overrides():
- """Stage changes override saved weights, including explicit zeros."""
+def test_graph_efm_cli_options_preserve_zero_and_false():
+ """Graph-EFM flags use run config defaults and accept explicit zeros."""
# First-party
- from neural_lam.train_model import build_parser, resolve_graph_efm_args
+ from neural_lam.config import ModelConfig, TrainRunConfig
+ from neural_lam.train_model import build_parser
- parser = build_parser()
- saved = parser.parse_args(
- [
- "--config_path",
- "unused.yaml",
- "--latent_dim",
- "8",
- "--kl_beta",
- "1",
- "--crps_weight",
- "0.2",
- "--no-learn_prior",
- ]
- )
- current = parser.parse_args(
+ args = build_parser().parse_args(
[
"--config_path",
"unused.yaml",
@@ -171,16 +158,14 @@ def test_graph_efm_cli_options_and_checkpoint_overrides():
"0",
"--crps_weight",
"0",
- "--learn_prior",
+ "--no-learn_prior",
]
)
- resolved = resolve_graph_efm_args(current, saved)
- assert resolved.latent_dim == 8
- assert resolved.kl_beta == 0
- assert resolved.crps_weight == 0
- assert resolved.learn_prior is True
- assert resolved.crps_members == 2
- assert current.latent_dim is None
+ assert args.kl_beta == 0
+ assert args.crps_weight == 0
+ assert args.learn_prior is False
+ assert args.prior_layers == ModelConfig().prior_layers
+ assert args.crps_members == TrainRunConfig().crps_members
@pytest.mark.parametrize(
From b9b86b758e957bb0062b99dd439592bfb559e033 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:20:24 +0530
Subject: [PATCH 36/41] Allow unused parameters only during learned-prior
warm-up
---
neural_lam/train_model.py | 6 +++++-
tests/test_graph_efm_model.py | 8 +++++++-
2 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index 521865679..3777782bc 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -968,9 +968,13 @@ def fit(
strategy=utils.training_strategy(
devices,
compute_config.num_nodes,
+ # The learned prior receives gradients through KL or CRPS.
find_unused_parameters=(
- isinstance(forecaster, GraphEFMForecaster)
+ not train_config.eval
+ and isinstance(forecaster, GraphEFMForecaster)
+ and model_config.learn_prior
and forecaster.kl_beta == 0
+ and forecaster.crps_weight == 0
),
),
accelerator=device_name,
diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py
index 6607d98b3..4c479854a 100644
--- a/tests/test_graph_efm_model.py
+++ b/tests/test_graph_efm_model.py
@@ -836,7 +836,7 @@ def cli_graph_efm_checkpoint(request, tmp_path_factory):
@pytest.mark.requires_training
@pytest.mark.parametrize(
"mode,kl_beta,crps_weight",
- [("test", 1.0, 0.0), (None, 1.0, 0.1), (None, 0.0, 0.0)],
+ [("test", 1.0, 0.0), (None, 1.0, 0.1), (None, 0.0, 0.1), (None, 0.0, 0.0)],
)
def test_loading_graph_efm_uses_current_run_settings(
cli_graph_efm_checkpoint,
@@ -876,6 +876,8 @@ def build_test_trainer(**kwargs):
return trainer
warning = Mock()
+ strategy = Mock(wraps=train_model.utils.training_strategy)
+ monkeypatch.setattr(train_model.utils, "training_strategy", strategy)
monkeypatch.setattr(train_model.pl, "Trainer", build_test_trainer)
monkeypatch.setattr(train_model.logger, "warning", warning)
(tmp_path / "loaded").mkdir()
@@ -921,6 +923,10 @@ def build_test_trainer(**kwargs):
assert evaluated.hparams.args.latent_dim == 8
assert result.checkpoint_path is not None
warning.assert_not_called()
+ expect_unused_prior = mode is None and kl_beta == 0 and crps_weight == 0
+ strategy.assert_called_once_with(
+ 1, 1, find_unused_parameters=expect_unused_prior
+ )
if mode == "test":
source_weights = torch.load(checkpoint, weights_only=False)[
"state_dict"
From 5afe8fdbeb780677b5bd00884e62a23ec3d8079b Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:20:36 +0530
Subject: [PATCH 37/41] Trim objective reduction details from the Graph-EFM
README
---
README.md | 6 ------
1 file changed, 6 deletions(-)
diff --git a/README.md b/README.md
index d01d9498c..0e32fab6c 100644
--- a/README.md
+++ b/README.md
@@ -580,12 +580,6 @@ Graph-EFM options are CLI arguments:
| `--crps_members` | 2 | Independent prior trajectories for fair CRPS (at least two) |
| `--eval_ensemble_size` | 5 | Members sampled during validation and testing |
-Fair CRPS uses separate prior trajectories, independent of the variational
-rollout. It sums over variables and averages over interior grid nodes,
-forecast steps and batch. The likelihood sums over interior grid nodes,
-variables and forecast steps; KL sums over latent mesh nodes and steps.
-Both variational terms are averaged over the batch.
-
A starting curriculum is the hierarchical MEPS schedule from
[Table 13 of the paper](https://arxiv.org/html/2406.04759v2#A9.T13):
From 1451a55243f887b78e9c107970403e447f436b1b Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Sat, 28 Nov 2026 12:20:39 +0530
Subject: [PATCH 38/41] Keep the Graph-EFM README focused on training and use
---
README.md | 38 ++++----------------------------------
1 file changed, 4 insertions(+), 34 deletions(-)
diff --git a/README.md b/README.md
index 0e32fab6c..55c5af20a 100644
--- a/README.md
+++ b/README.md
@@ -600,40 +600,10 @@ python -m neural_lam.train_model --config_path \
--kl_beta 1 --crps_weight 0 --ar_steps_train 1 --lr 1e-3 --epochs 400
```
-The current run's options apply when loading a checkpoint. Repeat any
-non-default architecture options used to train it. Lightning resumes the
-epoch counter, so `--epochs` is
-the cumulative target (400 after the first two stages above).
-Omit `--restore_opt` to reset the optimizer and apply the new learning rate;
-include it to resume optimizer state within a stage. Validation checkpoints
-monitor `val_mean_loss`, the training objective; evaluation reports
-ensemble-mean RMSE and fair CRPS for each forecast step and variable,
-computed from the same prior ensemble on interior nodes. Both are reported
-in the state variables' physical units. At least two evaluation members
-are required for CRPS. Single-member evaluation reports only mean error.
-Use `val_crps_ens` or `test_crps_ens` with
-`--metrics_watch` and `--var_leads_metrics_watch` to log selected variables
-and lead times. Testing also saves the metric heatmaps and CSV values.
-
-The shared metric API exposes `crps_ens`, `crps_ens_fair`,
-`crps_ens_unfair` and `crps_ens_almost_fair` (alpha 0.95).
-Graph-EFM uses the same fair CRPS implementation for its training objective.
-All metrics follow `(B, S, pred_steps, num_grid_nodes, num_state_vars)`,
-preserve gradients and use the shared grid mask and variable reductions.
-`pred_std` is accepted for API compatibility but does not affect these
-sample-based metrics. Ensemble CRPS requires at least two members.
-
-For large forecasts, CRPS supports optional chunking without changing its
-value or gradients. Choose `chunk_dim=0` for batches or `chunk_dim=2` for
-forecast steps; `chunk_size=None` (default) disables chunking:
-
-```python
-from neural_lam.metrics import crps_ens
-
-scores = crps_ens(
- ensemble, target, sum_vars=False, chunk_size=4, chunk_dim=2
-)
-```
+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`). Since it has no learnable parameters, it must be evaluated directly without training (e.g. `--eval val` or `--eval test`).
From c3a28629156c3f0d565d38c18af823e4f215a9a2 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 30 Nov 2026 21:25:55 +0530
Subject: [PATCH 39/41] Preserve positional training configuration settings
---
neural_lam/config.py | 24 ++++++++++++------------
1 file changed, 12 insertions(+), 12 deletions(-)
diff --git a/neural_lam/config.py b/neural_lam/config.py
index 3741bd79d..e9d2fdce6 100644
--- a/neural_lam/config.py
+++ b/neural_lam/config.py
@@ -331,14 +331,6 @@ class TrainRunConfig:
Attributes
----------
- 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, default 200
Number of training epochs.
batch_size : int, default 4
@@ -377,12 +369,16 @@ 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.
"""
- kl_beta: float = 1.0
- crps_weight: float = 0.0
- crps_members: int = 2
- eval_ensemble_size: int = 5
epochs: int = 200
batch_size: int = 4
ar_steps_train: int = 1
@@ -405,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
From 19d893ac6eb00cef9205100739bbc3bc41bcee69 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 30 Nov 2026 22:00:24 +0530
Subject: [PATCH 40/41] Allow variable weights in the Graph-EFM CRPS training
loss
---
docs/user-guide/training.md | 6 +++
neural_lam/config.py | 3 ++
neural_lam/models/forecasters/graph_efm.py | 44 +++++++++++++++++++---
neural_lam/train_model.py | 11 ++++++
4 files changed, 59 insertions(+), 5 deletions(-)
diff --git a/docs/user-guide/training.md b/docs/user-guide/training.md
index e88e11fd6..19431369c 100644
--- a/docs/user-guide/training.md
+++ b/docs/user-guide/training.md
@@ -83,8 +83,14 @@ Graph-EFM options are CLI arguments:
| `--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) |
+| `--crps_use_feature_weights` | off | Weight training CRPS by `training.state_feature_weighting` |
| `--eval_ensemble_size` | 5 | Members sampled during validation and testing |
+Training CRPS sums variable scores by default, as in the Graph-EFM paper.
+With `--crps_use_feature_weights`, it sums the scores after applying the
+configured weights. Uniform weighting then averages the variables, so
+adjust `--crps_weight` if you want to keep the same overall scale.
+
A starting curriculum is the hierarchical MEPS schedule from
[Table 13 of the paper](https://arxiv.org/html/2406.04759v2#A9.T13):
diff --git a/neural_lam/config.py b/neural_lam/config.py
index e9d2fdce6..3d64e2bb8 100644
--- a/neural_lam/config.py
+++ b/neural_lam/config.py
@@ -377,6 +377,8 @@ class TrainRunConfig:
Independent prior trajectories for fair CRPS; defaults to 2.
eval_ensemble_size : int, default 5
Graph-EFM evaluation ensemble size; defaults to 5.
+ crps_use_feature_weights : bool, default False
+ Apply configured state feature weights to Graph-EFM training CRPS.
"""
epochs: int = 200
@@ -405,6 +407,7 @@ class TrainRunConfig:
crps_weight: float = 0.0
crps_members: int = 2
eval_ensemble_size: int = 5
+ crps_use_feature_weights: bool = False
@dataclasses.dataclass
diff --git a/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py
index cd91ed5ef..80139b42b 100644
--- a/neural_lam/models/forecasters/graph_efm.py
+++ b/neural_lam/models/forecasters/graph_efm.py
@@ -11,7 +11,7 @@
from ... import metrics
from ...config import NeuralLAMConfig
from ...datastore import BaseDatastore
-from ...loss_weighting import get_per_var_std
+from ...loss_weighting import get_per_var_std, get_state_feature_weighting
from ..step_predictors.graph.graph_efm import BaseGraphEFM
from .autoregressive import unroll_forecast
from .probabilistic import BaseProbabilisticARForecaster
@@ -42,6 +42,7 @@ def __init__(
kl_beta: float = 1.0,
crps_weight: float = 0.0,
crps_members: int = 2,
+ crps_use_feature_weights: bool = False,
) -> None:
"""
Initialize the GraphEFMForecaster.
@@ -70,6 +71,15 @@ def __init__(
Weight of the KL term in the ELBO. When ``0`` the prior and KL
are not computed at all (pure auto-encoder training); the prior
network then receives gradients only if CRPS is enabled.
+ crps_use_feature_weights : bool, default False
+ Use the configured state feature weights when summing the CRPS
+ training loss over variables. Requires ``config``.
+
+ Raises
+ ------
+ ValueError
+ If an objective setting is invalid or the CRPS feature weights
+ are enabled without a config or contain invalid values.
"""
super().__init__(predictor, datastore)
if not torch.isfinite(torch.tensor(kl_beta)) or kl_beta < 0:
@@ -81,6 +91,25 @@ def __init__(
self.kl_beta = kl_beta
self.crps_weight = crps_weight
self.crps_members = crps_members
+
+ crps_feature_weights = None
+ if crps_use_feature_weights:
+ if config is None:
+ raise ValueError("CRPS feature weights require a config")
+ crps_feature_weights = torch.tensor(
+ get_state_feature_weighting(config, datastore),
+ dtype=torch.float32,
+ )
+ if (
+ not torch.isfinite(crps_feature_weights).all()
+ or (crps_feature_weights < 0).any()
+ ):
+ raise ValueError(
+ "CRPS feature weights must be finite and nonnegative"
+ )
+ self.register_buffer(
+ "crps_feature_weights", crps_feature_weights, persistent=False
+ )
self.register_buffer(
"per_var_std",
get_per_var_std(config, datastore) if config is not None else None,
@@ -89,6 +118,7 @@ def __init__(
predictor: BaseGraphEFM
per_var_std: torch.Tensor | None
+ crps_feature_weights: torch.Tensor | None
def compute_training_loss(
self,
@@ -110,9 +140,10 @@ def compute_training_loss(
``-likelihood + kl_beta * kl + crps_weight * crps``.
Fair CRPS uses at least two additional prior trajectories, independent
of the variational posterior rollout. It sums variables and averages
- over interior grid nodes, forecast steps and batch. The variational
- rollout advances on the predicted mean with boundary nodes
- overwritten by the true state.
+ over interior grid nodes, forecast steps and batch. When configured,
+ it applies the feature weights before summing the variable axis.
+ The variational rollout advances on the predicted mean with boundary
+ nodes overwritten by the true state.
Parameters
----------
@@ -245,13 +276,16 @@ def compute_training_loss(
self.crps_members,
graph_emb=graph_emb,
)
+ feature_weights = self.crps_feature_weights
entry_crps = metrics.crps_ens_fair(
ensemble,
target_states,
mask=interior_mask_bool,
average_grid=True,
- sum_vars=True,
+ sum_vars=feature_weights is None,
)
+ if feature_weights is not None:
+ entry_crps = (entry_crps * feature_weights).sum(dim=-1)
crps = entry_crps.mean()
batch_loss = batch_loss + self.crps_weight * crps
loss_components["crps"] = crps
diff --git a/neural_lam/train_model.py b/neural_lam/train_model.py
index c091a0b57..8dd6d832d 100644
--- a/neural_lam/train_model.py
+++ b/neural_lam/train_model.py
@@ -283,6 +283,11 @@ def build_forecaster(
kl_beta=getattr(args, "kl_beta", defaults.kl_beta),
crps_weight=getattr(args, "crps_weight", defaults.crps_weight),
crps_members=getattr(args, "crps_members", defaults.crps_members),
+ crps_use_feature_weights=getattr(
+ args,
+ "crps_use_feature_weights",
+ defaults.crps_use_feature_weights,
+ ),
)
return (
forecaster,
@@ -554,6 +559,12 @@ def build_parser() -> ArgumentParser:
help=f"Graph-EFM {name.replace('_', ' ')}",
)
+ efm_group.add_argument(
+ "--crps_use_feature_weights",
+ action="store_true",
+ help="Apply configured state feature weights to training CRPS",
+ )
+
# Training options
train_group = parser.add_argument_group("Training Options")
train_group.add_argument(
From b6305a2b18fe773ffc8ab4789ddfe8872280e1a8 Mon Sep 17 00:00:00 2001
From: Jeevant
Date: Mon, 30 Nov 2026 22:11:31 +0530
Subject: [PATCH 41/41] Record Graph-EFM CRPS variable weighting in the
changelog
---
CHANGELOG.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3ec7ba176..eee3a62c4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Allow configured variable weights in the Graph-EFM CRPS training loss
+ [\#921](https://github.com/mllam/neural-lam/pull/921) @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