diff --git a/CHANGELOG.md b/CHANGELOG.md index fbcba99be..eee3a62c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ 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 + - 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 5ae11940d..944daf74e 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Models, graphs, and data are kept independent so each component can be swapped w

-The three implemented architectures are Graph-LAM (flat), Hi-LAM (hierarchical), and Hi-LAM-Parallel. +Implemented architectures include Graph-LAM (flat), Hi-LAM (hierarchical), Hi-LAM-Parallel, and Graph-EFM (hierarchical and flat multiscale). Global forecasting is available on a [separate branch](https://github.com/mllam/neural-lam/tree/prob_model_global) ([planned to be merged](https://github.com/mllam/neural-lam/issues/63)). # Installing Neural-LAM @@ -111,7 +111,7 @@ nn.Module └── HiGraphLatentDecoder ``` The `--model` values listed in the [training guide](https://mllam.github.io/neural-lam/user-guide/training.html) select the step predictor. -`GraphEFM` and `GraphEFMMultiScale` are implemented but not yet selectable this way. +`graph_efm` and `graph_efm_ms` select the Graph-EFM predictors. The building blocks these are assembled from are also `torch.nn.Module` subclasses: ``` diff --git a/docs/user-guide/training.md b/docs/user-guide/training.md index e8d5ed59c..19431369c 100644 --- a/docs/user-guide/training.md +++ b/docs/user-guide/training.md @@ -14,7 +14,7 @@ A few of the key ones are outlined below: * `--ar_steps_train`: Number of time steps to unroll for when making predictions and computing the loss * `--ar_steps_eval`: Number of time steps to unroll for during validation steps * `--loss`: Which of the loss functions in `neural_lam/metrics.py` to train on -* `--gradient_checkpointing`: Recompute the activations of each autoregressive step in the backward pass instead of storing them, lowers peak memory when `--ar_steps_train` > 1 at the cost of extra compute +* `--gradient_checkpointing`: For deterministic models, recompute autoregressive step activations in the backward pass to reduce peak memory at the cost of extra compute. Checkpoints of trained models are stored under `runs//checkpoints/`, alongside Lightning and logger outputs for the same run. The implemented models are: @@ -54,6 +54,68 @@ 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) | +| `--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): + +| 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 +``` + +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`). diff --git a/neural_lam/config.py b/neural_lam/config.py index 37d2abfab..3d64e2bb8 100644 --- a/neural_lam/config.py +++ b/neural_lam/config.py @@ -295,6 +295,14 @@ class ModelConfig: GNN layer type for upward mesh message passing. mesh_down_gnn_type : str, default "InteractionNet" GNN layer type for downward mesh message passing. + latent_dim : int or None + Graph-EFM latent size; defaults to hidden_dim. + prior_layers, encoder_layers, decoder_layers : int + Graph-EFM mesh depths; defaults to 2, 2 and 4 respectively. + learn_prior : bool, default True + Learn the Graph-EFM prior; defaults to True. + prior_dist : str, default "isotropic" + Graph-EFM prior covariance, isotropic (default) or diagonal. """ model: str = "graph_lam" @@ -308,6 +316,12 @@ class ModelConfig: m2g_gnn_type: str = "InteractionNet" mesh_up_gnn_type: str = "InteractionNet" mesh_down_gnn_type: str = "InteractionNet" + latent_dim: int | None = None + prior_layers: int = 2 + encoder_layers: int = 2 + decoder_layers: int = 4 + learn_prior: bool = True + prior_dist: str = "isotropic" @dataclasses.dataclass @@ -355,6 +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. + crps_use_feature_weights : bool, default False + Apply configured state feature weights to Graph-EFM training CRPS. """ epochs: int = 200 @@ -379,6 +403,11 @@ 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 + crps_use_feature_weights: bool = False @dataclasses.dataclass diff --git a/neural_lam/metrics.py b/neural_lam/metrics.py index 340060f05..6fa6de069 100644 --- a/neural_lam/metrics.py +++ b/neural_lam/metrics.py @@ -3,6 +3,7 @@ # Standard library import inspect from collections.abc import Callable +from functools import partial # Third-party import torch @@ -393,6 +394,150 @@ def crps_gauss( ) +def crps_ens( + pred: torch.Tensor, + target: torch.Tensor, + pred_std: torch.Tensor | None = None, + mask: torch.Tensor | None = None, + average_grid: bool = True, + sum_vars: bool = True, + ens_dim: int = 1, + *, + afc_alpha: float = 1.0, + chunk_size: int | None = None, + chunk_dim: int = 0, +) -> torch.Tensor: + """Compute ensemble CRPS with empirical, fair or almost-fair estimation. + + Uses sorted ranks to compute the pairwise spread term with memory + linear in the number of members, with a direct two-member formula. + Gradients are retained for training. The almost-fair variant follows + Lang et al. (2024), AIFS: https://arxiv.org/abs/2412.15832. + + Parameters + ---------- + pred : torch.Tensor + Target shape with an additional ensemble dimension of size ``S`` + at ``ens_dim``, normally ``(B, S, pred_steps, num_grid_nodes, + num_state_vars)``. At least two ensemble members are required. + target : torch.Tensor + Shape ``(..., num_grid_nodes, num_state_vars)``. Ground truth. + pred_std : torch.Tensor or None, optional + Unused; accepted for compatibility with the shared metric interface. + mask : torch.Tensor or None, optional + Shape ``(num_grid_nodes,)``. Boolean mask selecting grid nodes. + average_grid : bool, optional + Average over selected grid nodes. Default True. + sum_vars : bool, optional + Sum over state variables. Default True. + ens_dim : int, optional + Ensemble dimension in ``pred``. Default 1. + afc_alpha : float, optional + Interpolates from empirical (unfair) CRPS at 0 to fair CRPS + at 1 (default). Intermediate values give almost-fair CRPS. + chunk_size : int or None, optional + Maximum entries along chunk_dim per scoring call. None disables + chunking. Smaller chunks reduce peak temporary memory; gradients + remain available to callers using CRPS for training. + chunk_dim : int, optional + Dimension in pred to chunk, excluding ens_dim. Defaults to + batch dimension 0; use 2 for forecast steps in (B, S, T, N, F). + Negative dimension indices are supported. + + Returns + ------- + torch.Tensor + CRPS with the ensemble dimension removed, reduced according to + ``mask``, ``average_grid`` and ``sum_vars`` as for ``nll``. + + Raises + ------ + ValueError + If alpha, ensemble layout or chunk settings are invalid. + """ + if not 0 <= afc_alpha <= 1: + raise ValueError("afc_alpha must be finite and between 0 and 1") + if pred.ndim != target.ndim + 1: + raise ValueError("CRPS predictions require an extra ensemble dimension") + if not -pred.ndim <= ens_dim < pred.ndim: + raise ValueError("ens_dim is outside the prediction dimensions") + # Normalize negative axes so shape slicing and axis comparisons agree. + ens_dim %= pred.ndim + if pred.shape[:ens_dim] + pred.shape[ens_dim + 1 :] != target.shape: + raise ValueError( + "CRPS target shape must match predictions without ens_dim" + ) + num_members = pred.shape[ens_dim] + if num_members < 2: + raise ValueError("CRPS requires at least two ensemble members") + if chunk_size is not None: + if chunk_size < 1: + raise ValueError("chunk_size must be positive") + if not -pred.ndim <= chunk_dim < pred.ndim: + raise ValueError("chunk_dim is outside the prediction dimensions") + chunk_dim %= pred.ndim + if chunk_dim == ens_dim: + raise ValueError("chunk_dim must differ from ens_dim") + # The target omits the ensemble axis, shifting any later axes left. + target_dim = chunk_dim - int(chunk_dim > ens_dim) + # Reassemble the per-entry scores before masking or reducing axes. + entries = [ + crps_ens( + member_chunk, + target_chunk, + average_grid=False, + sum_vars=False, + ens_dim=ens_dim, + afc_alpha=afc_alpha, + ) + for member_chunk, target_chunk in zip( + pred.split(chunk_size, dim=chunk_dim), + target.split(chunk_size, dim=target_dim), + strict=True, + ) + ] + return mask_and_reduce_metric( + torch.cat(entries, dim=target_dim), mask, average_grid, sum_vars + ) + mean_member_error = ( + (pred - target.unsqueeze(ens_dim)).abs().mean(dim=ens_dim) + ) + if num_members == 2: + spread = (pred.select(ens_dim, 0) - pred.select(ens_dim, 1)).abs() / 2 + else: + # Each sorted value appears positively in rank - 1 pair differences + # and negatively in num_members - rank pair differences. + ordered = pred.sort(dim=ens_dim).values + rank_shape = [1] * pred.ndim + rank_shape[ens_dim] = num_members + ranks = torch.arange( + 1, + num_members + 1, + device=pred.device, + dtype=pred.dtype, + ).view(rank_shape) + spread = ((2 * ranks - num_members - 1) * ordered).sum(dim=ens_dim) + spread = spread / (num_members * (num_members - 1)) + # Alpha blends the fair and empirical normalizations of the pair term. + spread = spread * ((num_members - 1 + afc_alpha) / num_members) + entry_crps = mean_member_error - spread + return mask_and_reduce_metric( + entry_crps, mask=mask, average_grid=average_grid, sum_vars=sum_vars + ) + + +crps_ens_fair = partial(crps_ens, afc_alpha=1.0) +crps_ens_unfair = partial(crps_ens, afc_alpha=0.0) +crps_ens_almost_fair = partial(crps_ens, afc_alpha=0.95) + +ENSEMBLE_METRICS: dict[str, Callable[..., torch.Tensor]] = { + "crps_ens": crps_ens, + "crps_ens_fair": crps_ens_fair, + "crps_ens_unfair": crps_ens_unfair, + "crps_ens_almost_fair": crps_ens_almost_fair, +} + + DEFINED_METRICS: dict[str, Callable[..., torch.Tensor]] = { "mse": mse, "mae": mae, @@ -400,6 +545,7 @@ def crps_gauss( "wmae": wmae, "nll": nll, "crps_gauss": crps_gauss, + **ENSEMBLE_METRICS, } @@ -425,3 +571,20 @@ def requires_pred_std(metric: Callable[..., torch.Tensor]) -> bool: """ pred_std_param = inspect.signature(metric).parameters["pred_std"] return pred_std_param.default is inspect.Parameter.empty + + +def requires_ensemble(metric: Callable[..., torch.Tensor]) -> bool: + """Return whether a registered metric scores an ensemble of forecasts. + + Parameters + ---------- + metric : callable + A function returned by get_metric. + + Returns + ------- + bool + True for registered ensemble metrics, which require predictions + with shape (B, S, pred_steps, num_grid_nodes, num_state_vars). + """ + return metric in ENSEMBLE_METRICS.values() 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/autoregressive.py b/neural_lam/models/forecasters/autoregressive.py index 76bf5499e..87b75afda 100644 --- a/neural_lam/models/forecasters/autoregressive.py +++ b/neural_lam/models/forecasters/autoregressive.py @@ -1,15 +1,18 @@ """Auto-regressive unrolling of a step predictor into a full forecast.""" +# Standard library +from collections.abc import Callable + # Third-party import torch import torch.utils.checkpoint -# 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, @@ -31,7 +34,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/deterministic.py b/neural_lam/models/forecasters/deterministic.py index 73515009a..d4bc9ffe1 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/neural_lam/models/forecasters/graph_efm.py b/neural_lam/models/forecasters/graph_efm.py new file mode 100644 index 000000000..80139b42b --- /dev/null +++ b/neural_lam/models/forecasters/graph_efm.py @@ -0,0 +1,343 @@ +"""Probabilistic forecaster training a Graph-EFM predictor via its ELBO.""" + +# Standard library +from functools import partial +from typing import Any + +# Third-party +import torch + +# Local +from ... import metrics +from ...config import NeuralLAMConfig +from ...datastore import BaseDatastore +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 + + +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 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__( + self, + predictor: BaseGraphEFM, + datastore: BaseDatastore, + config: NeuralLAMConfig | None = None, + kl_beta: float = 1.0, + crps_weight: float = 0.0, + crps_members: int = 2, + crps_use_feature_weights: bool = False, + ) -> 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. + 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: + 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 + + 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, + persistent=False, + ) + + predictor: BaseGraphEFM + per_var_std: torch.Tensor | None + crps_feature_weights: 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``. + 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. 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 + ---------- + 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, var_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( + var_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, + 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=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 + 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 graph_emb is None and num_members > 0: + graph_emb = self.predictor.embedd_graph(init_states.shape[0]) + 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, + ), + ) 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) 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/modules/probabilistic.py b/neural_lam/models/modules/probabilistic.py index fbd852bde..fe6992e55 100644 --- a/neural_lam/models/modules/probabilistic.py +++ b/neural_lam/models/modules/probabilistic.py @@ -22,11 +22,11 @@ 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 - members are produced, only that repeated sampling is what an ensemble - is made of. + sampled through ``forecaster.sample_ensemble`` and scored with + 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. """ # The wrapped forecaster's forward must sample, so that repeating it @@ -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; + 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.append("crps_ens") + 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 and fair CRPS. - 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 + 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. - 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,15 @@ 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: + values["crps_ens"] = metrics.crps_ens_fair( + ensemble, + target_states, + mask=self.interior_mask_bool, + sum_vars=False, + ) + return values def _log_objective( self, @@ -230,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 per-variable ensemble-mean MSE for epoch-end aggregation. + collects error and fair CRPS for epoch-end aggregation. Parameters ---------- @@ -243,8 +252,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 +264,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 and fair CRPS for epoch-end aggregation. Parameters @@ -265,8 +274,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/neural_lam/models/step_predictors/graph/graph_efm.py b/neural_lam/models/step_predictors/graph/graph_efm.py index b02a76468..edc4e8d3c 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,108 @@ 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 variational posterior approximation. + + 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. + 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 + 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) + 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, var_posterior.rsample(), graph_emb, prev_state + ) + return prior, var_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]]: + graph_emb: dict[str, Any] | None = None, + ) -> 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 @@ -440,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 ------- @@ -451,9 +558,10 @@ 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) + + if graph_emb is None: + graph_emb = self.embedd_graph(prev_state.shape[0]) # Compute prior prior_dist = self.prior_model( @@ -464,19 +572,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 +600,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 +611,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 +922,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 +933,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 bf883f395..8dd6d832d 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 @@ -38,10 +43,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"): @@ -85,6 +96,87 @@ 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. + + 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) + 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, + ) + layers = { + f"{part}_{prefix}_layers": getattr( + args, f"{part}_layers", getattr(defaults, 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=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, + 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, @@ -98,8 +190,28 @@ 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 delegates to its own builder. + + Parameters + ---------- + predictor_class : type + Step predictor class selected from ``MODELS``. + args : Namespace + Architecture and forcing-window arguments. + config : NeuralLAMConfig + Output clamping settings. + datastore : BaseDatastore + Grid features, graph location and standardization statistics. + + Returns + ------- + StepPredictor + Predictor configured for its graph family. """ + if issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)): + return build_graph_efm_predictor( + predictor_class, args, config, datastore + ) kwargs = dict( datastore=datastore, graph_name=args.graph, @@ -125,6 +237,80 @@ def build_predictor( return predictor_class(**kwargs) +def build_forecaster( + args: Namespace, + config: NeuralLAMConfig, + datastore: BaseDatastore, + predictor: Any, +) -> tuple[ + BaseForecaster, + type[BaseForecastingModule], + dict[str, Any], +]: + """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. + """ + gradient_checkpointing = getattr(args, "gradient_checkpointing", False) + if isinstance(predictor, (GraphEFM, GraphEFMMultiScale)): + if gradient_checkpointing: + logger.warning( + "--gradient_checkpointing has no effect for Graph-EFM." + ) + defaults = TrainRunConfig() + forecaster = GraphEFMForecaster( + predictor, + datastore, + config=config, + 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, + ProbabilisticForecastingModule, + { + "eval_ensemble_size": getattr( + args, "eval_ensemble_size", defaults.eval_ensemble_size + ) + }, + ) + return ( + DeterministicARForecaster( + predictor, + datastore, + config=config, + loss=args.loss, + gradient_checkpointing=gradient_checkpointing, + ), + DeterministicForecastingModule, + {}, + ) + + class AdaptiveHelpFormatter(ArgumentDefaultsHelpFormatter): """``--help`` formatter that scales the column width to the terminal.""" @@ -145,14 +331,15 @@ 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. created via train_model.main), so that model class and architecture kwargs - can be recovered automatically. + can be recovered automatically. Graph-EFM architecture and objective options + are restored from the saved arguments. Parameters ---------- @@ -168,22 +355,24 @@ 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] + is_graph_efm = issubclass(predictor_class, (GraphEFM, GraphEFMMultiScale)) predictor = build_predictor(predictor_class, args, config, datastore) - forecaster = DeterministicARForecaster( - predictor, datastore, config=config, loss=args.loss + forecaster, module_class, _ = build_forecaster( + args, config, datastore, predictor ) - return DeterministicForecastingModule.load_from_checkpoint( + return module_class.load_from_checkpoint( ckpt_path, forecaster=forecaster, datastore=datastore, datastore_boundary=datastore_boundary, weights_only=False, + **({"config": config} if is_graph_efm else {}), ) @@ -332,6 +521,50 @@ 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, + default=getattr(ModelConfig, name), + help=f"Graph-EFM {name.replace('_', ' ')}", + ) + efm_group.add_argument( + "--learn_prior", + action=BooleanOptionalAction, + default=ModelConfig.learn_prior, + help="Learn the latent prior", + ) + efm_group.add_argument( + "--prior_dist", + choices=["isotropic", "diagonal"], + default=ModelConfig.prior_dist, + help="Prior covariance", + ) + 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, + default=getattr(TrainRunConfig, name), + 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( @@ -354,7 +587,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 with --kl_beta and --crps_weight.", ) train_group.add_argument( "--lr", type=float, default=1e-3, help="learning rate" @@ -376,9 +610,9 @@ def build_parser() -> ArgumentParser: "--gradient_checkpointing", action="store_true", help=( - "If set, recompute the activations of each autoregressive step " - "in the backward pass instead of storing them. Lowers peak " - "memory when --ar_steps_train > 1, at the cost of extra compute." + "For deterministic models, recompute autoregressive step " + "activations in the backward pass to reduce peak memory at " + "the cost of extra compute." ), ) @@ -535,6 +769,9 @@ def fit( """ Run training or evaluation using strongly-typed configuration dataclasses. + Training and evaluation use the current run configuration. When loading + a checkpoint, use architecture settings that match its saved weights. + Parameters ---------- model_config : ModelConfig @@ -683,8 +920,6 @@ def fit( **dataclasses.asdict(logging_config), ) - # Build predictor and forecaster externally, then inject into - # DeterministicForecastingModule predictor_class = MODELS[model_config.model] predictor = build_predictor(predictor_class, hparams, config, datastore) @@ -693,15 +928,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, - gradient_checkpointing=train_config.gradient_checkpointing, + forecaster, module_class, module_kwargs = build_forecaster( + hparams, config, datastore, predictor ) - model = DeterministicForecastingModule( + model = module_class( forecaster=forecaster, config=config, datastore=datastore, @@ -715,15 +946,24 @@ 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-" if logging_config.logger_run_name: run_name = logging_config.logger_run_name else: + if isinstance(forecaster, GraphEFMForecaster): + prob = hparams + 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}" ) @@ -758,7 +998,18 @@ def fit( max_epochs=train_config.epochs, deterministic=True, default_root_dir=run_dir, - strategy="auto", + strategy=utils.training_strategy( + devices, + compute_config.num_nodes, + # The learned prior receives gradients through KL or CRPS. + find_unused_parameters=( + 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, num_nodes=compute_config.num_nodes, devices=devices, 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" diff --git a/tests/test_ensemble_evaluation.py b/tests/test_ensemble_evaluation.py new file mode 100644 index 000000000..a04b8c71b --- /dev/null +++ b/tests/test_ensemble_evaluation.py @@ -0,0 +1,123 @@ +"""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"} + 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) + for name, expected in { + "ens_mse": expected_mse, + "crps_ens": expected_crps, + }.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, + "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}_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() diff --git a/tests/test_ensemble_metrics.py b/tests/test_ensemble_metrics.py new file mode 100644 index 000000000..d65292901 --- /dev/null +++ b/tests/test_ensemble_metrics.py @@ -0,0 +1,209 @@ +"""Numerical and reduction checks for reusable fair ensemble CRPS.""" + +# Third-party +import pytest +import torch + +# First-party +from neural_lam.metrics import crps_ens, 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]) +@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"): + metric( + torch.zeros(2, members, 4, 3), + torch.zeros(2, 4, 3), + chunk_size=chunk_size, + ) + + +@pytest.mark.parametrize("members", [2, 5]) +@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 = (members - 1 + alpha) / (members * (members - 1)) + expected = first - pairs * factor / (2 * members) + actual = crps_ens( + ensemble, + target, + average_grid=False, + sum_vars=False, + afc_alpha=alpha, + ) + torch.testing.assert_close(actual, expected) + actual.sum().backward() + assert torch.isfinite(ensemble.grad).all() + + +@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), + afc_alpha=alpha, + ) + + +@pytest.mark.parametrize( + "metric_name,alpha", + [ + ("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, alpha): + # 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, afc_alpha=alpha), + ) + + +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", + ) + + +@pytest.mark.parametrize("members", [2, 5, 12]) +@pytest.mark.parametrize("chunk_dim", [0, 2, -2]) +@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 + ) + 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, + 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) + + +@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) diff --git a/tests/test_graph_efm_model.py b/tests/test_graph_efm_model.py new file mode 100644 index 000000000..4c479854a --- /dev/null +++ b/tests/test_graph_efm_model.py @@ -0,0 +1,937 @@ +"""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``). 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, 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 +): + """CLI options assemble the probabilistic predictor and module.""" + datastore, config = _datastore_and_config(graph_name) + 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="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) + assert predictor.latent_dim == 4 + + forecaster, module_class, module_kwargs = build_forecaster( + 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} + + +@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) + 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", + 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, + args, + config, + datastore, + ) + forecaster, module_class, module_kwargs = build_forecaster( + 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) + caller_config = nlconfig.NeuralLAMConfig(datastores=config.datastores) + restored = load_forecasting_module_from_checkpoint( + str(checkpoint), caller_config, datastore + ) + 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) + 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() + + +@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) + 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, + prior_layers=1, + encoder_layers=2, + decoder_layers=3, + ), + 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-") + + +@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), + ) + }, + ) + 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", + ] + ) + 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 + ) + forecaster, module_class, module_kwargs = build_forecaster( + 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,kl_beta,crps_weight", + [("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, + mode, + kl_beta, + crps_weight, + monkeypatch, + tmp_path, +): + """Evaluation and resume load weights using the current run settings.""" + # 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() + 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() + result = train_model.fit( + model_config=nlconfig.ModelConfig( + 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, + 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 == kl_beta + assert evaluated.forecaster.crps_weight == crps_weight + assert ( + evaluated.eval_ensemble_size + == nlconfig.TrainRunConfig().eval_ensemble_size + ) + 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" + ] + 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 new file mode 100644 index 000000000..7711e534e --- /dev/null +++ b/tests/test_graph_efm_objective.py @@ -0,0 +1,225 @@ +"""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 = [] + self.graphs = [] + self.embedding_calls = 0 + + def embedd_graph(self, batch_size): + self.embedding_calls += 1 + 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), + ) + + 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(): + 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).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, graph_emb={} + ) + 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_graph_efm_cli_options_preserve_zero_and_false(): + """Graph-EFM flags use run config defaults and accept explicit zeros.""" + # First-party + from neural_lam.config import ModelConfig, TrainRunConfig + from neural_lam.train_model import build_parser + + args = build_parser().parse_args( + [ + "--config_path", + "unused.yaml", + "--kl_beta", + "0", + "--crps_weight", + "0", + "--no-learn_prior", + ] + ) + 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( + "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 + ) + + +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]) 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)