neural_lam.models.forecasters.deterministic#
Forecasters trained by scoring a single deterministic forecast.
Classes#
Forecaster whose |
|
Auto-regressive forecaster trained by scoring its single rollout. |
Module Contents#
- class neural_lam.models.forecasters.deterministic.BaseDeterministicForecaster(datastore: neural_lam.datastore.BaseDatastore, config: neural_lam.config.NeuralLAMConfig | None = None, loss: str = 'wmse')[source]#
Bases:
neural_lam.models.forecasters.base.BaseForecasterForecaster whose
forwardis deterministic, trained by scoring it.Repeating a call returns the same forecast, so one call is the whole forecast; contrast
BaseProbabilisticForecaster, which samples a fresh one each call. How that forecast is produced stays open,forwardbeing inherited abstract; seeDeterministicARForecasterfor the auto-regressive one.compute_training_lossproduces one forecast and scores it withself.loss, andcompute_loss_from_forecastapplies the same scoring rule to an already-produced forecast for reporting.Set up the scoring rule and the constant
pred_stdfallback.- Parameters:
datastore (BaseDatastore) – The datastore providing the state standardization statistics used to compute
per_var_std.config (NeuralLAMConfig or None, optional) – Configuration used to compute the constant per-variable std substituted for
pred_stdwhen the forecast carries no std of its own. Needed only whenlossis a scoring rule that uses a std; without it in that casecompute_loss_from_forecastandcompute_training_lossraiseValueErrorvia_resolve_pred_std. Forecasters used purely for inference can always omit it. DefaultNone.loss (str, optional) – The scoring rule (from
neural_lam.metrics) applied bycompute_training_loss, stored asself.loss. Default"wmse".
- compute_loss_from_forecast(prediction: torch.Tensor, target_states: torch.Tensor, pred_std: torch.Tensor | None, mask: torch.Tensor | None = None, average_grid: bool = True, sum_vars: bool = True) torch.Tensor[source]#
Apply this forecaster’s scoring rule to an already-produced forecast.
Resolves
pred_stdvia_resolve_pred_std(substitutingself.per_var_stdwhenNoneandself.lossneeds one), then appliesself.loss. Used to report the loss on a forecast the caller already has, at a reduction of its choosing, without recomputing it.Only the loss goes through here. Metrics unrelated to the training objective depend on nothing but the shapes of the three tensors below, so callers compute those directly from
neural_lam.metrics.- Parameters:
prediction (torch.Tensor) – Shape
(..., num_grid_nodes, num_state_vars). Forecast to score.target_states (torch.Tensor) – Shape
(..., num_grid_nodes, num_state_vars). True states to score against. Dims: same asprediction.pred_std (torch.Tensor or None) – Shape
(..., num_grid_nodes, num_state_vars), orNone. Predicted standard deviation forprediction;Nonewhen the forecast carries no std, in which caseself.per_var_stdis substituted ifself.lossneeds a std at all (see_resolve_pred_stdfor when this raises instead).mask (torch.Tensor or None, optional) – Shape
(num_grid_nodes,), boolean. Forwarded toself.loss.average_grid (bool, optional) – Forwarded to
self.loss. DefaultTrue.sum_vars (bool, optional) – Forwarded to
self.loss. DefaultTrue.
- Returns:
The scoring rule’s output; shape depends on
average_gridandsum_vars(seeneural_lam.metrics).- Return type:
- Raises:
ValueError – If
pred_stdisNone,self.lossneeds one and noper_var_stdfallback is available; see_resolve_pred_std.
- compute_training_loss(init_states: torch.Tensor, forcing_features: torch.Tensor, target_states: torch.Tensor, interior_mask_bool: torch.Tensor) tuple[torch.Tensor, dict[str, torch.Tensor]][source]#
Score a single forecast with
self.loss.Produces one forecast over every predicted step, scores it against the target states on interior nodes and averages over batch and time. Callers that already hold a forecast should score that one with
compute_loss_from_forecastrather than producing another here.- 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 forecast from. Dims:Bis batch size,2is the time index ([X_{t-1}, X_t]),num_grid_nodesis the number of spatial nodes, andnum_state_varsis the state feature dimension.forcing_features (torch.Tensor) – Shape
(B, pred_steps, num_grid_nodes, num_forcing_vars). External forcings provided at each predicted step. Dims:Bis batch size,pred_stepsis the number of predicted steps,num_grid_nodesis the number of spatial nodes, andnum_forcing_varsis the forcing feature dimension (already concatenated past/current/future windows).target_states (torch.Tensor) – Shape
(B, pred_steps, num_grid_nodes, num_state_vars). True states at each predicted step, used both as the prediction targets and to overwrite boundary nodes while forecasting. Dims: same as the prediction.interior_mask_bool (torch.Tensor) – Shape
(num_grid_nodes,), boolean.Truefor interior nodes; passed asmasktoself.lossso that only interior nodes are scored.
- Returns:
batch_loss (torch.Tensor) – Scalar. The scoring rule applied to the forecast, averaged over batch and time.
loss_components (dict of {str: torch.Tensor}) – Empty; the deterministic objective has no separate components.
- Raises:
ValueError – If
self.lossneeds a std, the forecast carries none of its own and noper_var_stdfallback is available; see_resolve_pred_std.
Notes
Customize the deterministic objective by overriding
compute_loss_from_forecast.DeterministicForecastingModulecalls that method directly for its per-step training, validation and test losses. Overriding onlycompute_training_lossdoes not change those losses.
- loss#
- per_var_std: torch.Tensor | None#
- class neural_lam.models.forecasters.deterministic.DeterministicARForecaster(predictor: neural_lam.models.step_predictors.base.StepPredictor, datastore: neural_lam.datastore.BaseDatastore, config: neural_lam.config.NeuralLAMConfig | None = None, loss: str = 'wmse', gradient_checkpointing: bool = False)[source]#
Bases:
BaseDeterministicForecasterAuto-regressive forecaster trained by scoring its single rollout.
Produces its forecast by unrolling a
StepPredictor; the training objective is the oneBaseDeterministicForecastersupplies.Initialize the DeterministicARForecaster.
- Parameters:
predictor (StepPredictor) – The predictor to use for each AR step.
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_stdwhenpredictordoes not output its own. Needed only whenlossis a scoring rule that uses a std; without it in that casecompute_loss_from_forecastandcompute_training_lossraiseValueError. Forecasters used purely for inference (forward) can always omit it.loss (str, default "wmse") – The scoring rule (from
neural_lam.metrics) applied bycompute_training_loss.gradient_checkpointing (bool, default False) – If True and in training mode, wrap each predictor call in
torch.utils.checkpointso its activations are recomputed in the backward pass instead of stored. Lowers peak memory when unrolling more than one step, at the cost of extra compute.
- forward(init_states: torch.Tensor, forcing_features: torch.Tensor, boundary_states: torch.Tensor) tuple[torch.Tensor, torch.Tensor | None][source]#
Unroll one auto-regressive forecast.
- 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.forcing_features (torch.Tensor) – Shape
(B, pred_steps, num_grid_nodes, num_forcing_vars). Forcing features for each predicted step;pred_stepsdefines the rollout length.boundary_states (torch.Tensor) – Shape
(B, pred_steps, num_grid_nodes, num_state_vars). True state values used ONLY to overwrite boundary nodes at each AR step.
- Returns:
prediction (torch.Tensor) – Shape
(B, pred_steps, num_grid_nodes, num_state_vars). Stacked per-step forecasts. Dims: same asboundary_states.pred_std (torch.Tensor or None) – Shape
(B, pred_steps, num_grid_nodes, num_state_vars)when the wrapped predictor outputs an std, otherwiseNone. Dims: same asprediction.
- predictor#