neural_lam.models.modules.base#

Abstract Lightning module shared by deterministic and probabilistic forecasting modules.

Attributes#

Classes#

BaseForecastingModule

Abstract Lightning module wrapping a BaseForecaster.

Module Contents#

class neural_lam.models.modules.base.BaseForecastingModule(forecaster: neural_lam.models.forecasters.base.BaseForecaster, config: neural_lam.config.NeuralLAMConfig, datastore: neural_lam.datastore.base.BaseDatastore, datastore_boundary: neural_lam.datastore.base.BaseDatastore | None = None, lr: float = 0.001, restore_opt: bool = False, n_example_pred: int = 1, create_gif: bool = False, val_steps_to_log: list[int] | None = None, train_steps_to_log: list[int] | None = None, metrics_watch: list[str] | None = None, var_leads_metrics_watch: dict[int, list[int]] | None = None, args: Any | None = None)[source]#

Bases: pytorch_lightning.LightningModule, abc.ABC

Abstract Lightning module wrapping a BaseForecaster.

Owns everything that does not depend on whether the wrapped forecaster produces a single deterministic forecast or samples an ensemble: batch standardization, the training loop, optimizer configuration, checkpoint compatibility, and the plotting/aggregation helpers used by validation and testing. Producing one forecast (common_step) belongs here too, since every forecaster shares the forward contract. What differs is what a subclass evaluates: one forecast, or an ensemble sampled from repeated calls. validation_step, test_step and on_test_epoch_end therefore stay abstract; concrete subclasses implement them independently (see DeterministicForecastingModule and ProbabilisticForecastingModule) rather than overriding one another.

Initialize the BaseForecastingModule.

Parameters:
  • forecaster (BaseForecaster) – The forecaster model to use for predictions. Owns the training objective (compute_training_loss); this module and its subclasses never compute a loss themselves, only inject shared inputs (e.g. the interior mask) and log what the forecaster returns.

  • config (NeuralLAMConfig) – Configuration object for the neural LAM model.

  • datastore (BaseDatastore) – Datastore providing grid metadata and data access.

  • datastore_boundary (BaseDatastore, optional) – Boundary forcing datastore, used for its standardization statistics.

  • lr (float, default 1e-3) – Learning rate for the optimizer.

  • restore_opt (bool, default False) – Whether to restore optimizer state from checkpoint.

  • n_example_pred (int, default 1) – Number of example predictions to plot during testing.

  • create_gif (bool, default False) – Whether to create GIFs of example predictions.

  • val_steps_to_log (list of int, optional) – Specific rollout steps to log during validation/testing.

  • train_steps_to_log (list of int, optional) – Specific predicted steps to log during training. Only has an effect for a forecaster whose objective decomposes per step; this class’s training_step logs the aggregate train_loss alone (see its docstring for why).

  • metrics_watch (list of str, optional) – List of metrics to watch and log specifically.

  • var_leads_metrics_watch (dict of {int: list of int}, optional) – Mapping from variable index to a list of rollout steps to log individually for the configured metrics.

  • args (argparse.Namespace, optional) – Pre-refactor ARModel checkpoint hyperparameters. When provided, attributes on args take precedence over the corresponding explicit kwargs (lr, restore_opt, n_example_pred, create_gif, val_steps_to_log, train_steps_to_log, metrics_watch, var_leads_metrics_watch) so legacy checkpoints round-trip through load_from_checkpoint correctly.

aggregate_and_plot_metrics(metrics_dict: dict[str, list[torch.Tensor]], prefix: str) → None[source]#

Aggregate metrics from all GPUs and plot them.

Parameters:
  • metrics_dict (dict) – Dictionary of metrics lists.

  • prefix (str) – Prefix for the log names.

all_gather_cat(tensor_to_gather: torch.Tensor) → torch.Tensor[source]#

Gather tensors from all GPUs and concatenate them.

Parameters:

tensor_to_gather (torch.Tensor) – The tensor to gather from all processes.

Returns:

The concatenated tensor from all processes.

Return type:

torch.Tensor

common_step(batch: Batch) → tuple[torch.Tensor, torch.Tensor, torch.Tensor | None, torch.Tensor][source]#

Produce one forecast for the batch.

Every forecaster shares the forward contract, so this works for a probabilistic forecaster too; there it returns a single sample rather than a whole ensemble (see BaseProbabilisticForecaster.sample_ensemble).

Parameters:

batch (tuple) – The batch of data containing initial states, target states, forcing features, boundary forcing features, and batch times.

Returns:

A tuple containing prediction, target states, predicted standard deviation, and batch times.

Return type:

tuple

configure_optimizers() → torch.optim.Optimizer[source]#

Configure the optimizers and learning rate schedulers.

Returns:

The configured optimizer.

Return type:

torch.optim.Optimizer

create_metric_log_dict(metric_tensor: torch.Tensor, prefix: str, metric_name: str) → dict[str, Any][source]#

Create a dictionary of metrics to log.

Parameters:
  • metric_tensor (torch.Tensor) – The metric values.

  • prefix (str) – Prefix for the log names (e.g., ‘val’, ‘test’).

  • metric_name (str) – The name of the metric.

Returns:

Dictionary of logged metrics and figures.

Return type:

dict

on_after_batch_transfer(batch: Batch, dataloader_idx: int) → Batch[source]#

Standardize a batch on-device after transfer to the accelerator.

Lightning calls this for every train/val/test/predict batch. WeatherDataset returns unstandardized state, forcing and boundary; all three are normalized here so the work runs on the accelerator. Forcing and boundary share the same feature-major (feature, window) stacking, so per-feature mean/std are tiled once and cached.

Parameters:
  • batch (Batch) – (init_states, target_states, forcing, boundary, target_times) as returned by the dataloader.

  • dataloader_idx (int) – Index of the dataloader the batch comes from.

Returns:

The batch with state, forcing and boundary standardized.

Return type:

Batch

on_load_checkpoint(checkpoint: dict[str, Any]) → None[source]#

Perform actions when loading a checkpoint. Handles backward compatibility for older checkpoints.

Parameters:

checkpoint (dict) – The loaded checkpoint dictionary.

abstract on_test_epoch_end() → None[source]#

Perform actions at the end of the test epoch.

Concrete subclasses must at least aggregate and plot self.test_metrics (typically via aggregate_and_plot_metrics) and reset any epoch-scoped state they accumulate during test_step.

on_validation_epoch_end() → None[source]#

Perform actions at the end of the validation epoch. Aggregates and plots validation metrics.

plot_examples(batch: Batch, n_examples: int, split: str, prediction: torch.Tensor) → None[source]#

Plot example predictions.

Parameters:
  • batch (tuple) – The batch of data.

  • n_examples (int) – Number of examples to plot.

  • split (str) – The data split.

  • prediction (torch.Tensor) – The model predictions.

abstract test_step(batch: Batch, batch_idx: int) → None[source]#

Perform a single test step.

Concrete subclasses must both score the batch and populate the test_metrics they created, which their on_test_epoch_end aggregates.

Kept abstract for the same reason as validation_step: the LightningModule definition is a no-op stub rather than an abstract method, so omitting it would silently skip testing instead of failing at construction.

Parameters:
  • batch (tuple) – The batch of data.

  • batch_idx (int) – The index of the batch.

training_step(batch: Batch) → torch.Tensor[source]#

Perform a single training step.

The training objective is fully assembled by the wrapped forecaster, which owns its own scoring rule; this method injects the interior mask, then logs the loss and any loss components the forecaster returns.

This general implementation logs only the scalar objective, since compute_training_loss returns only a scalar: a forecaster’s objective (e.g. an ELBO) need not decompose over predicted steps, so there is no per-step tensor to select from with train_steps_to_log. Subclasses whose forecaster does expose such a decomposition override this to log the breakdown as well; see DeterministicForecastingModule.training_step.

Parameters:

batch (tuple) – The batch of data.

Returns:

The computed loss for the training step.

Return type:

torch.Tensor

abstract validation_step(batch: Batch, batch_idx: int) → None[source]#

Perform a single validation step.

Concrete subclasses must both score the batch and populate the val_metrics they created, which on_validation_epoch_end below aggregates.

Kept abstract even though LightningModule defines this method: that definition is a no-op stub, not an abstract method, so without this declaration a subclass that omitted it would instantiate happily and silently skip validation. Declaring it abstract turns that into a TypeError at construction.

Parameters:
  • batch (tuple) – The batch of data.

  • batch_idx (int) – The index of the batch.

boundary_mean: torch.Tensor | None#
boundary_mean_tiled: torch.Tensor | None#
boundary_std: torch.Tensor | None#
boundary_std_tiled: torch.Tensor | None#
create_gif = False#
datastore#
datastore_boundary = None#
forcing_mean: torch.Tensor | None#
forcing_mean_tiled: torch.Tensor | None#
forcing_std: torch.Tensor | None#
forcing_std_tiled: torch.Tensor | None#
forecaster#
interior_mask_bool: torch.Tensor#
matched_metrics: set#
n_example_pred = 1#
per_var_std: torch.Tensor | None#
plotted_examples = 0#
restore_opt = False#
state_mean: torch.Tensor#
state_std: torch.Tensor#
test_metrics: dict[str, list[torch.Tensor]]#
val_metrics: dict[str, list[torch.Tensor]]#
neural_lam.models.modules.base.Batch#