Skip to content

Base Model

samudra.models.base

BaseModel(in_channels, out_channels, input_steps, last_kernel_size, pad, gradient_detach_interval, residual=None)

Bases: Module

Abstract base model for neural ocean emulators.

Provides shared functionality for all ocean emulator models, including residual prediction, ocean masking, and gradient detaching for multi-step autoregressive rollouts.

Source code in src/samudra/models/base.py
def __init__(
    self,
    in_channels,
    out_channels,
    input_steps,
    last_kernel_size,
    pad,
    gradient_detach_interval: int,
    residual: ResidualHead | None = None,
) -> None:
    super().__init__()
    assert last_kernel_size % 2 != 0, "Cannot use even kernel sizes!"
    self.in_channels = in_channels
    self.out_channels = out_channels
    self.N_pad = int((last_kernel_size - 1) / 2)
    self.pad: str = pad
    if input_steps < 1:
        raise ValueError(f"input_steps must be positive, got {input_steps}")
    self.input_steps = input_steps
    self.gradient_detach_interval = gradient_detach_interval
    # None predicts full states; a head predicts increments on the input.
    self.residual = residual

loss_coordinates(prognostic, prediction, label)

The prediction and label in the units the network predicts.

These are the residual head's increments, or the states themselves without a head. Training and validation losses compare these.

Source code in src/samudra/models/base.py
def loss_coordinates(
    self, prognostic: Prognostic, prediction: Prognostic, label: Prognostic
) -> tuple[Prognostic, Prognostic]:
    """The prediction and label in the units the network predicts.

    These are the residual head's increments, or the states themselves
    without a head. Training and validation losses compare these.
    """
    if self.residual is None:
        return prediction, label
    return (
        self.residual.increments(prognostic, prediction, prediction),
        self.residual.increments(prognostic, prediction, label),
    )

samudra.models.residual

Residual prediction: the network predicts increments on the input state.

ResidualHead(*, scale, output_steps, scale_kind='none')

Bases: Module

Turns a network's output into next states, as one-step increments.

Each output step is an increment on the step before it, starting from the newest input: z1 = x[t] + q * d1, z2 = z1 + q * d2, with gradients flowing through z1. q has one value per variable: ones when scale_kind is none, or each variable's typical one-step change (from the data, like the normalization statistics) when it is increment_rms, so the network emits unit-scale increments.

The network's outputs d are the head's coordinates, and training compares them with the label expressed in the same coordinates (:meth:increments), whatever the loss. With q of ones that equals a loss on states, since the anchors cancel in the error.

The head saves its scale kind and scale with the model's state, and loading a state saved by a different head raises, naming the model.residual setting the checkpoint was trained with. BaseModel handles checkpoints with no head, or from before heads were recorded.

Source code in src/samudra/models/residual.py
def __init__(
    self,
    *,
    scale: Float[torch.Tensor, " var"],
    output_steps: int,
    scale_kind: ResidualScale = "none",
) -> None:
    super().__init__()
    if scale_kind == "none" and not bool((scale == 1).all()):
        raise ValueError("An unscaled residual head needs a scale of ones")
    if output_steps < 1:
        raise ValueError(f"output_steps must be positive, got {output_steps}")
    self.output_steps = output_steps
    self.scale_kind = scale_kind
    self.scale: torch.Tensor
    self.register_buffer("scale", scale.float(), persistent=False)

increments(prognostic, prediction, states)

states in the head's coordinates, the units the network predicts.

Each step is an increment, in units of q, on the step before it in prediction (the newest input for the first step), so for the prediction itself these are the network's outputs.

Source code in src/samudra/models/residual.py
def increments(
    self, prognostic: Prognostic, prediction: Prognostic, states: Prognostic
) -> Prognostic:
    """``states`` in the head's coordinates, the units the network predicts.

    Each step is an increment, in units of ``q``, on the step before it in
    ``prediction`` (the newest input for the first step), so for the
    prediction itself these are the network's outputs.
    """
    n_var = self.scale.numel()
    anchors = torch.cat((prognostic[:, -n_var:], prediction[:, :-n_var]), dim=1)
    return (states - anchors) / self._step_scale()

residual_config_yaml(scale_kind)

The model.residual setting that builds a head, for error messages.

Source code in src/samudra/models/residual.py
def residual_config_yaml(scale_kind: ResidualScale) -> str:
    """The ``model.residual`` setting that builds a head, for error messages."""
    if scale_kind == "none":
        return "`model.residual: true`"
    return f"`model.residual: {{scale: {scale_kind}}}`"