neural_lam.models.forecasters.graph_efm
=======================================

.. py:module:: neural_lam.models.forecasters.graph_efm

.. autoapi-nested-parse::

   Probabilistic forecaster training a Graph-EFM predictor via its ELBO.



Classes
-------

.. autoapisummary::

   neural_lam.models.forecasters.graph_efm.GraphEFMForecaster


Module Contents
---------------

.. py:class:: GraphEFMForecaster(predictor: neural_lam.models.step_predictors.graph.graph_efm.BaseGraphEFM, datastore: neural_lam.datastore.BaseDatastore, config: neural_lam.config.NeuralLAMConfig | None = None, kl_beta: float = 1.0, crps_weight: float = 0.0, crps_members: int = 2)

   Bases: :py:obj:`neural_lam.models.forecasters.probabilistic.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.

   Initialize the GraphEFMForecaster.

   :param predictor: 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.
   :type predictor: BaseGraphEFM
   :param datastore: The datastore providing grid metadata and boundary masks.
   :type datastore: BaseDatastore
   :param config: 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.
   :type config: NeuralLAMConfig or None
   :param crps_weight: Weight of fair CRPS computed from independent prior trajectories.
                       Default zero, disabling the additional sampling cost.
   :type crps_weight: float, optional
   :param crps_members: Number of prior trajectories for CRPS. Default two.
   :type crps_members: int, optional
   :param kl_beta: 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.
   :type kl_beta: float, default 1.0


   .. py:method:: 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]]

      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. The variational
      rollout advances on the predicted mean with boundary nodes
      overwritten by the true state.

      :param init_states: 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.
      :type init_states: torch.Tensor
      :param forcing_features: 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.
      :type forcing_features: torch.Tensor
      :param target_states: 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.
      :type target_states: torch.Tensor
      :param interior_mask_bool: Shape ``(num_grid_nodes,)``, boolean. ``True`` for interior
                                 nodes; passed as ``mask`` to ``metrics.nll`` so only interior
                                 nodes contribute to the likelihood.
      :type interior_mask_bool: torch.Tensor

      :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``).



   .. py:method:: sample_ensemble(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.

      :param init_states: Shape (B, 2, num_grid_nodes, num_state_vars). Initial states.
      :type init_states: torch.Tensor
      :param forcing_features: Shape (B, pred_steps, num_grid_nodes, num_windowed_forcing_vars).
      :type forcing_features: torch.Tensor
      :param boundary_states: Shape (B, pred_steps, num_grid_nodes, num_state_vars). Boundaries.
      :type boundary_states: torch.Tensor
      :param num_members: Number of independent prior trajectories, at least one.
      :type num_members: int
      :param graph_emb: Static graph embeddings shared with the variational rollout.
                        Computed once for all trajectories when omitted.
      :type graph_emb: dict[str, Any] or None, optional

      :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.



   .. py:attribute:: crps_members
      :value: 2



   .. py:attribute:: crps_weight
      :value: 0.0



   .. py:attribute:: kl_beta
      :value: 1.0



   .. py:attribute:: per_var_std
      :type:  torch.Tensor | None


   .. py:attribute:: predictor
      :type:  neural_lam.models.step_predictors.graph.graph_efm.BaseGraphEFM


