Skip to content
Open
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Cache static mesh and edge feature embeddings across autoregressive rollout steps in `ARForecaster` for `GraphLAM` and hierarchical graph models [\#817](https://github.com/mllam/neural-lam/pull/817) @Sharkyii

- Add the `hello_world_danra.py` marimo tutorial (prepare the DANRA example data, build a graph, train and evaluate `graph_lam` on CPU, all through `neural_lam.api`), executed at docs build time so the docs page shows its outputs; `train_model` now exits non-zero on errors (`@logger.catch(reraise=True)`) [\#577](https://github.com/mllam/neural-lam/pull/577) @Sharkyii

- Add a high-level programmatic Python API (`neural_lam.api`) exposing typed keyword-only `train`, `evaluate` and `create_graph` functions; `train` and `evaluate` return a `Run` handle with the run's checkpoint and plot paths. The training CLI now parses into the typed run config dataclasses (`ModelConfig`, `TrainRunConfig`, `DataConfig`, `ComputeConfig`, `LoggingConfig`) and calls the same `neural_lam.train_model.fit` [\#715](https://github.com/mllam/neural-lam/pull/715) @GiGiKoneti
Expand Down
16 changes: 13 additions & 3 deletions neural_lam/models/forecasters/autoregressive.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,23 @@ def forward(
pred_std_list = []
pred_steps = forcing_features.shape[1]

static_embeddings = self.predictor.embed_static_features()

for i in range(pred_steps):
forcing = forcing_features[:, i]
boundary_state = boundary_states[:, i]

pred_state, pred_std = self.predictor(
prev_state, prev_prev_state, forcing
)
if static_embeddings is not None:
pred_state, pred_std = self.predictor(
prev_state,
prev_prev_state,
forcing,
static_embeddings=static_embeddings,
)
else:
pred_state, pred_std = self.predictor(
prev_state, prev_prev_state, forcing
)
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
Comment on lines +116 to +132

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks unnecessary, why can't static_embedding just be fed directly when it is None? If this does not work for some reason with the checkpoint, pls add a comment to clarify.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Predictors that return None from embed_static_features() (such as PersistencePredictor, BaseGraphEFM, and TrainableStepPredictor) do not accept static_embeddings in forward(), so passing static_embeddings=None raises TypeError


# Overwrite boundary with true state using ARForecaster's mask
new_state = (
Expand Down
15 changes: 15 additions & 0 deletions neural_lam/models/step_predictors/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# Standard library
from abc import ABC, abstractmethod
from typing import Any

# Third-party
import torch
Expand Down Expand Up @@ -151,12 +152,26 @@ def expand_to_batch(self, x: torch.Tensor, batch_size: int) -> torch.Tensor:
"""
return x.unsqueeze(0).expand(batch_size, -1, -1)

def embed_static_features(self) -> Any | None:
"""
Embed static features (e.g. mesh and edge attributes) to be reused
across autoregressive rollout steps.
Comment thread
Sharkyii marked this conversation as resolved.
Resolved

Returns
-------
Any or None
Precomputed static embeddings, or ``None`` if the predictor has
no static features to embed.
"""
return None

@abstractmethod
def forward(
self,
prev_state: torch.Tensor,
prev_prev_state: torch.Tensor,
forcing: torch.Tensor,
static_embeddings: Any | None = None,
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""
Advance the state by one step:
Expand Down
57 changes: 47 additions & 10 deletions neural_lam/models/step_predictors/graph/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Base class for graph-based step predictors."""

# Standard library
from typing import Any

# Third-party
import torch
Expand Down Expand Up @@ -204,7 +205,38 @@ def embedd_mesh_nodes(self) -> torch.Tensor:
"""
raise NotImplementedError("embedd_mesh_nodes not implemented")

def process_step(self, mesh_rep: torch.Tensor) -> torch.Tensor:
def embed_static_processor_features(self) -> Any | None:
"""
Embed static features specific to the processor step.

Returns
-------
Any or None
Processor-specific static embeddings, or ``None`` if none.
"""
return None

def embed_static_features(
self,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, Any]:
"""
Embed all static mesh and edge features once for reuse across
autoregressive rollout steps.

Returns
-------
tuple
Tuple of ``(mesh_emb, g2m_emb, m2g_emb, processor_emb)``.
"""
mesh_emb = self.embedd_mesh_nodes()
g2m_emb = self.g2m_embedder(self.g2m_features)
m2g_emb = self.m2g_embedder(self.m2g_features)
processor_emb = self.embed_static_processor_features()
return (mesh_emb, g2m_emb, m2g_emb, processor_emb)

def process_step(
self, mesh_rep: torch.Tensor, processor_embeddings: Any | None = None
) -> torch.Tensor:
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
"""
Process the mesh representation in the encode-process-decode
framework, running one or more message-passing steps.
Expand All @@ -216,6 +248,9 @@ def process_step(self, mesh_rep: torch.Tensor) -> torch.Tensor:
representations. Dims: ``B`` is batch size,
``num_mesh_nodes`` is the number of mesh nodes, and ``hidden_dim``
is the hidden dimension.
processor_embeddings : Any or None, optional
Precomputed static embeddings for the processor. If ``None``,
they will be computed on the fly.
Comment thread
Sharkyii marked this conversation as resolved.
Resolved

Returns
-------
Expand All @@ -230,6 +265,9 @@ def forward(
prev_state: torch.Tensor,
prev_prev_state: torch.Tensor,
forcing: torch.Tensor,
static_embeddings: (
tuple[torch.Tensor, torch.Tensor, torch.Tensor, Any] | None
) = None,
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""
Advance the state by one step using the encode-process-decode
Expand Down Expand Up @@ -282,17 +320,14 @@ def forward(
dim=-1,
)

# Embed all features
# Embed grid features
grid_emb = self.grid_embedder(
grid_features
) # (B, num_grid_nodes, hidden_dim)
g2m_emb = self.g2m_embedder(
self.g2m_features
) # (num_edges, hidden_dim)
m2g_emb = self.m2g_embedder(
self.m2g_features
) # (num_edges, hidden_dim)
mesh_emb = self.embedd_mesh_nodes()

if static_embeddings is None:
static_embeddings = self.embed_static_features()
mesh_emb, g2m_emb, m2g_emb, processor_emb = static_embeddings

# Map from grid to mesh
mesh_emb_expanded = self.expand_to_batch(
Expand All @@ -310,7 +345,9 @@ def forward(
) # (B, num_grid_nodes, hidden_dim)

# Run processor step
mesh_rep = self.process_step(mesh_rep)
mesh_rep = self.process_step(
mesh_rep, processor_embeddings=processor_emb
)

# Map back from mesh to grid
m2g_emb_expanded = self.expand_to_batch(m2g_emb, batch_size)
Expand Down
3 changes: 3 additions & 0 deletions neural_lam/models/step_predictors/graph/graph_efm.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,7 @@ def forward(
prev_state: torch.Tensor,
prev_prev_state: torch.Tensor,
forcing: torch.Tensor,
static_embeddings: Any | None = None,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
"""
Sample one time step prediction: embed features, sample the latent
Expand All @@ -440,6 +441,8 @@ def forward(
Shape ``(B, num_grid_nodes, d_state)``. ``X_{t-1}``.
forcing : torch.Tensor
Shape ``(B, num_grid_nodes, d_forcing)``.
static_embeddings : Any | None, optional
Precomputed static embeddings (currently unused in GraphEFM).

Returns
-------
Expand Down
28 changes: 22 additions & 6 deletions neural_lam/models/step_predictors/graph/graph_lam.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,22 @@ def embedd_mesh_nodes(self) -> torch.Tensor:
self.mesh_static_features
) # (num_mesh_nodes, hidden_dim)

def process_step(self, mesh_rep: torch.Tensor) -> torch.Tensor:
def embed_static_processor_features(self) -> torch.Tensor:
"""
Embed static m2m edge features for the flat mesh processor.

Returns
-------
torch.Tensor
Embedded m2m edge features of shape ``(num_edges, hidden_dim)``.
"""
return self.m2m_embedder(self.m2m_features)

def process_step(
self,
mesh_rep: torch.Tensor,
processor_embeddings: torch.Tensor | None = None,
) -> torch.Tensor:
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
"""
Process the mesh representation through the flat message-passing
processor (all nodes at a single level).
Expand All @@ -166,20 +181,21 @@ def process_step(self, mesh_rep: torch.Tensor) -> torch.Tensor:
representations. Dims: ``B`` is batch size, ``num_mesh_nodes`` is
the number of mesh nodes, and ``hidden_dim`` is the hidden
dimension.
processor_embeddings : torch.Tensor or None, optional
Precomputed embedded m2m edge features. If ``None``, will be
computed on the fly.
Comment thread
Sharkyii marked this conversation as resolved.
Resolved

Returns
-------
torch.Tensor
Shape ``(B, num_mesh_nodes, hidden_dim)``. Updated mesh node
representations. Dims: same as ``mesh_rep``.
"""
# Embed m2m here first
batch_size = mesh_rep.shape[0]
m2m_emb = self.m2m_embedder(
self.m2m_features
) # (num_edges, hidden_dim)
if processor_embeddings is None:
processor_embeddings = self.embed_static_processor_features()
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
m2m_emb_expanded = self.expand_to_batch(
m2m_emb, batch_size
processor_embeddings, batch_size
) # (B, num_edges, hidden_dim)

mesh_rep, _ = self.processor(
Expand Down
96 changes: 78 additions & 18 deletions neural_lam/models/step_predictors/graph/hierarchical.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,63 @@ def embedd_mesh_nodes(self) -> torch.Tensor:
"""
return self.mesh_embedders[0](self.mesh_static_features[0])

def process_step(self, mesh_rep: torch.Tensor) -> torch.Tensor:
def embed_static_processor_features(
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
self,
) -> tuple[
list[torch.Tensor],
list[torch.Tensor],
list[torch.Tensor],
list[torch.Tensor],
]:
"""
Embed static node and edge features for hierarchical processor levels.

Returns
-------
tuple
Tuple of lists
``(mesh_emb_levels, mesh_same_rep, mesh_up_rep, mesh_down_rep)``.
"""
mesh_emb_levels = [
emb(node_static_features)
for emb, node_static_features in zip(
self.mesh_embedders[1:],
self.mesh_static_features[1:],
)
]
mesh_same_rep = [
emb(edge_feat)
for emb, edge_feat in zip(
self.mesh_same_embedders, self.m2m_features
)
]
mesh_up_rep = [
emb(edge_feat)
for emb, edge_feat in zip(
self.mesh_up_embedders, self.mesh_up_features
)
]
mesh_down_rep = [
emb(edge_feat)
for emb, edge_feat in zip(
self.mesh_down_embedders, self.mesh_down_features
)
]
return (mesh_emb_levels, mesh_same_rep, mesh_up_rep, mesh_down_rep)

def process_step(
self,
mesh_rep: torch.Tensor,
processor_embeddings: (
tuple[
list[torch.Tensor],
list[torch.Tensor],
list[torch.Tensor],
list[torch.Tensor],
]
| None
) = None,
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
) -> torch.Tensor:
"""
Process the mesh representation across all hierarchy levels,
implementing the full init-process-readout cycle.
Expand All @@ -195,6 +251,9 @@ def process_step(self, mesh_rep: torch.Tensor) -> torch.Tensor:
node representations from the encoder. Dims: ``B`` is batch
size, ``num_mesh_nodes[0]`` is the number of nodes at
level 0, and ``hidden_dim`` is the hidden dimension.
processor_embeddings : tuple or None, optional
Precomputed static embeddings for the hierarchical processor.
If ``None``, will be computed on the fly.
Comment thread
Sharkyii marked this conversation as resolved.
Resolved

Returns
-------
Expand All @@ -204,36 +263,37 @@ def process_step(self, mesh_rep: torch.Tensor) -> torch.Tensor:
"""
batch_size = mesh_rep.shape[0]

if processor_embeddings is None:
processor_embeddings = self.embed_static_processor_features()

(
mesh_emb_levels_raw,
mesh_same_rep_raw,
mesh_up_rep_raw,
mesh_down_rep_raw,
) = processor_embeddings
Comment thread
Sharkyii marked this conversation as resolved.
Resolved

# EMBED REMAINING MESH NODES (levels >= 1) -
# Create list of mesh node representations for each level,
# each of size (B, num_mesh_nodes[l], hidden_dim)
mesh_rep_levels = [mesh_rep] + [
self.expand_to_batch(emb(node_static_features), batch_size)
for emb, node_static_features in zip(
self.mesh_embedders[1:],
self.mesh_static_features[1:],
)
self.expand_to_batch(node_emb, batch_size)
for node_emb in mesh_emb_levels_raw
]

# - EMBED EDGES -
# Embed edges, expand with batch dimension
mesh_same_rep = [
self.expand_to_batch(emb(edge_feat), batch_size)
for emb, edge_feat in zip(
self.mesh_same_embedders, self.m2m_features
)
self.expand_to_batch(edge_emb, batch_size)
for edge_emb in mesh_same_rep_raw
]
mesh_up_rep = [
self.expand_to_batch(emb(edge_feat), batch_size)
for emb, edge_feat in zip(
self.mesh_up_embedders, self.mesh_up_features
)
self.expand_to_batch(edge_emb, batch_size)
for edge_emb in mesh_up_rep_raw
]
mesh_down_rep = [
self.expand_to_batch(emb(edge_feat), batch_size)
for emb, edge_feat in zip(
self.mesh_down_embedders, self.mesh_down_features
)
self.expand_to_batch(edge_emb, batch_size)
for edge_emb in mesh_down_rep_raw
]
Comment thread
Sharkyii marked this conversation as resolved.
Resolved

# - MESH INIT. -
Expand Down
6 changes: 6 additions & 0 deletions neural_lam/models/step_predictors/persistence.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
"""Persistence baseline step predictor."""

# Standard library
from typing import Any

# Third-party
import torch
from loguru import logger
Expand Down Expand Up @@ -63,6 +66,7 @@ def forward(
prev_state: torch.Tensor,
prev_prev_state: torch.Tensor,
forcing: torch.Tensor,
static_embeddings: Any | None = None,
Comment thread
Sharkyii marked this conversation as resolved.
Resolved
) -> tuple[torch.Tensor, None]:
"""
Return the previous state as the prediction.
Expand All @@ -78,6 +82,8 @@ def forward(
forcing : torch.Tensor
Shape ``(B, num_grid_nodes, num_forcing_vars)``.
External forcings (unused).
static_embeddings : Any | None, optional
Precomputed static embeddings (unused).

Returns
-------
Expand Down
Loading
Loading