Skip to content

Configuration

Overview

Configuration is defined by config.py and values are stored in YAML files within the src/samudra/configs/ directory. Configuration files can include other configuration files using the !include directive.

Each configuration file is associated with a Pydantic model — you can generate JSON schemas for them with uv run src/samudra/config_schema.py (which is run automatically in pre-commit). To associate a configuration file with a Pydantic model, generate the JSON schema (if it doesn't already exist) and then add this line to the top of the config file:

# yaml-language-server: $schema=path/to/schema.json

This is what the config_schema.py script uses to determine which model to validate against, and also enables autocomplete/type checking in VS Code via the YAML extension.

Command Line Configuration

The train and eval modules accept the configuration file as a positional argument. You can override arbitrary keys on the command line — see --help for details. When overriding an object (as opposed to a single scalar value) via the command line, you can either supply JSON like --data '{"key": "value"}' or a YAML file with a leading @ symbol: --data @src/samudra/configs/data/file.yaml.

Training runs create a YAML file in the checkpoint directory with the final configuration used which you can use to reproduce the run by passing to train e.g. uv run -m samudra.train path/to/config.yaml.

Data locations

Each data source reads its data from data_location, plus the statistics stores for that data: its means and standard deviations. Samudra opens them together as one xarray.DataTree per source, with the data at the root and one child per statistic. The stores stay separate on disk.

By default the statistics stores are found by the release's naming convention. For OM4 and CM4, a data store <stem>.zarr has its means in <stem>_means.zarr and its stds in <stem>_stds.zarr, in the same directory. For LLC, the statistics are embedded in the data store itself. Set data_means_location or data_stds_location to read a statistic from somewhere else:

sources:
  - type: om4
    data_location: om4_onedeg/OM4.zarr  # means: om4_onedeg/OM4_means.zarr, stds: om4_onedeg/OM4_stds.zarr
  - type: om4
    data_location: data.zarr
    data_means_location: means.nc       # explicit locations override the convention
    data_stds_location: stds.nc

The scaled residual head (model.residual.scale: increment_rms, below) needs one more statistic: the increment RMS, each channel's root-mean-square one-step change over wet cells, written by ocean_preprocessing.make_norm_datasets beside the means and stds. A source reads it from data_increment_rms_location when that is set. Otherwise it reads <stem>_increment_rms.zarr only when the training or eval config needs it. LLC sources don't support it. To add the store beside an existing dataset without rewriting its means and stds, run python -m ocean_preprocessing.make_norm_datasets <data store> --statistics increment_rms, over the interval the means and stds were computed over (--start, --end; the command reads it from those stores when they record it).

Every one of these is a location, which can be written two ways:

  • A relative string (e.g. OM4.zarr). It is resolved against experiment.data_root, so the same data config works against a local copy or a bucket just by changing the root: --experiment.data_root /scratch/om4 or a structured root in the config.
  • A structured, absolute location with an explicit type. This ignores data_root and points at exactly one place. Two types are supported:
# Read a Zarr store directly from S3 (or an S3-compatible endpoint like OSN).
data_location:
  type: s3
  endpoint_url: "https://nyu1.osn.mghpcc.org"  # omit for AWS S3
  anon: true                                   # read a public bucket without credentials
  bucket: m2lines-pubs
  path: Samudra/v2026-09/om4_twodeg/OM4.zarr

# Read a Zarr/NetCDF store from an absolute local path.
data_location:
  type: local
  path: /scratch/om4/OM4.zarr

For a signed request (anon: false, the default) credentials come from the environment (the usual AWS_* variables); the config never carries secrets. Set anon: true to read a public bucket — such as the open datasets on OSN — with no credentials at all, which also avoids a stale AWS_ACCESS_KEY_ID being rejected by a non-AWS endpoint.

src/samudra/configs/data/om4_demo.yaml is a ready-made source that streams the public 2° OM4 dataset from OSN over S3 with no local download and no credentials. Because its locations are absolute, experiment.data_root is unused and can be omitted entirely. The same --data flag works across train, eval, and viz — for viz it names the ground-truth source (groundtruth_location defaults to the source's data_location):

samudra train samudra_om4/train.yaml --data @data/om4_demo.yaml
samudra eval  samudra_om4/eval.yaml  --data @data/om4_demo.yaml
samudra viz   samudra_om4/viz.yaml   --data @data/om4_demo.yaml

Residual prediction

By default a model predicts each next state directly. With model.residual, it instead predicts one-step increments: the first output step is added to the newest input, and each later one to the step before it. residual: true adds the network output unscaled. scale: increment_rms multiplies it by each channel's typical one-step change, q, so the network emits unit-scale increments:

model:
  residual:                # or true for an unscaled head; omit or false to predict full states
    scale: increment_rms   # default none: add the network output unscaled

The loss compares the network's outputs with the label in the same units: the increment from the step before, divided by q. So with scale: increment_rms, every channel's error counts in units of its own typical change, and slowly changing fields such as deep temperature are not drowned out by fast ones such as velocities. This is the Δ-norm recipe, and it works with any loss (mse, mae, dynamic, …). Validation loss uses the same units. For an unscaled head the loss equals the loss on states, since the error is the same.

A checkpoint records its residual head, or that it has none. Loading it into a model with a different head, or with a head when it was trained without one, fails with the model.residual setting it was trained with. So an eval config must set model.residual as training did and read the same increment RMS store.

model.residual replaced model.pred_residuals: write residual: true for pred_residuals: true. A config that still sets pred_residuals: true fails validation with that message. pred_residuals: false, the old default that saved run configs spell out, still loads and means no head. Checkpoints trained before this change load without model.residual if they were trained without pred_residuals. Those trained with pred_residuals: true and one output step per call load with residual: true. They record no head, so loading can't check that choice. With several output steps, pred_residuals: true added each output to the input in the same slot rather than to the step before, so those checkpoints don't load with model.residual.

API Reference

samudra.config

JulianDate(value)

Represents a Julian date as a cftime.datetime at noon on the relevant day.

This is the format the OM4 data uses, so we match that here. TODO(jder): probably worth asserting the date format when opening the data.

Source code in src/samudra/config.py
def __init__(self, value: str):
    parsed = cftime.datetime.strptime(value, "%Y-%m-%d", calendar="julian")
    self.datetime = parsed.replace(hour=12)

NoLeapDate(value)

A CM4 simulation date at midnight on the 365-day calendar.

Source code in src/samudra/config.py
def __init__(self, value: str) -> None:
    self.datetime = cftime.datetime.strptime(value, "%Y-%m-%d", calendar="noleap")

Om4TimeConfig

Bases: BaseConfig

overlaps(other)

Match the inclusive endpoints used by xarray time selection.

Source code in src/samudra/config.py
def overlaps(self, other: Self) -> bool:
    """Match the inclusive endpoints used by xarray time selection."""
    return (
        self.start.datetime <= other.end.datetime
        and self.end.datetime >= other.start.datetime
    )

Cm4TimeConfig

Bases: BaseConfig

Date bounds for CM4's native no-leap, interval-end timestamps.

overlaps(other)

Match the inclusive endpoints used by xarray time selection.

Source code in src/samudra/config.py
def overlaps(self, other: Self) -> bool:
    """Match the inclusive endpoints used by xarray time selection."""
    return (
        self.start.datetime <= other.end.datetime
        and self.end.datetime >= other.start.datetime
    )

BaseDataSourceConfig

Bases: BaseConfig, ABC

default_statistic_location(statistic) abstractmethod

Where this source type keeps statistic when not configured.

Source code in src/samudra/config.py
@abc.abstractmethod
def default_statistic_location(self, statistic: str) -> Location:
    """Where this source type keeps ``statistic`` when not configured."""
    raise NotImplementedError

fill_statistic_locations()

Apply the naming convention now, so a saved config records the stores.

Source code in src/samudra/config.py
@pydantic.model_validator(mode="after")
def fill_statistic_locations(self) -> Self:
    """Apply the naming convention now, so a saved config records the stores."""
    if self.data_means_location is None:
        self.data_means_location = self.default_statistic_location("means")
    if self.data_stds_location is None:
        self.data_stds_location = self.default_statistic_location("stds")
    return self

require_increment_rms()

Read the increment RMS, from the naming convention unless configured.

Source code in src/samudra/config.py
def require_increment_rms(self) -> None:
    """Read the increment RMS, from the naming convention unless configured."""
    if self.data_increment_rms_location is None:
        self.data_increment_rms_location = self.default_statistic_location(
            "increment_rms"
        )

statistic_locations()

The store of each statistic, by statistic name.

Source code in src/samudra/config.py
def statistic_locations(self) -> dict[str, Location]:
    """The store of each statistic, by statistic name."""
    locations = {"means": self.data_means_location, "stds": self.data_stds_location}
    unset = [name for name, location in locations.items() if location is None]
    if unset:
        raise ValueError(f"Statistics locations are unset: {unset}")
    if self.data_increment_rms_location is not None:
        locations["increment_rms"] = self.data_increment_rms_location
    return {name: location for name, location in locations.items() if location}

canonicalize_datasets(source) abstractmethod

Put the data and every statistic in canonical channel form.

Source code in src/samudra/config.py
@abc.abstractmethod
def canonicalize_datasets(
    self, source: SourceTree
) -> tuple[SourceTree, DataLayout]:
    """Put the data and every statistic in canonical channel form."""
    raise NotImplementedError

RustDataLoadingConfig

Bases: BaseConfig

Configuration for the local Rust Zarr data loader.

InferenceDataLoadingConfig

Bases: BaseConfig

PyTorch worker policy for inference, independent of training I/O.

Om4FamilyDataSourceConfig

Bases: BaseDataSourceConfig[Om4FamilyTimeConfigT]

Shared physical channels and layouts for the OM4 and CM4 oceans.

canonicalize_datasets(source)

Normalize OM4 coordinates and statistics while retaining compact arrays.

Source code in src/samudra/config.py
def canonicalize_datasets(
    self, source: SourceTree
) -> tuple[SourceTree, DataLayout]:
    """Normalize OM4 coordinates and statistics while retaining compact arrays."""
    data_layout = self.build_layout()
    data = with_lat_lon_coords(source.data.copy())
    data = with_level_index_vars(data, depth_levels=data_layout.depth_levels)
    data = flatten_masks(data)
    statistics = {
        name: with_level_index_vars(
            dataset.copy(), depth_levels=data_layout.depth_levels
        )
        for name, dataset in source.statistics().items()
    }

    anomalies_vars = get_anomalies_vars(data_layout.boundary_var_names)
    if anomalies_vars:
        data, statistics["means"], statistics["stds"] = compute_anomalies(
            data, statistics["means"], statistics["stds"], anomalies_vars
        )

    canonical = SourceTree.from_datasets(
        data,
        **{name: expand_compact_levels(ds) for name, ds in statistics.items()},
    )
    return canonical, data_layout

PerceiverConfig

Bases: BaseConfig

A standard config interface to various perceiver implementations.

Builds either a regular Perceiver (for the encoder, via build) or a PerceiverIO (for the decoder, via build_io). Both respect the shared implementation setting from SamudraMultiConfig.perceiver_implementation.

build(in_channels, out_channels, max_patch_size, implementation)

Build a regular Perceiver (used by the encoder).

Source code in src/samudra/config.py
def build(
    self,
    in_channels: int,
    out_channels: int,
    max_patch_size: tuple[int, int],
    implementation: PerceiverImpl,
) -> nn.Module:
    """Build a regular Perceiver (used by the encoder)."""
    # This is not really a "frequency" but a maximum of the width appears to be reasonable from looking at the code.
    max_freq = max(*max_patch_size)

    num_freq_bands = 4
    fourier_dim = fourier_features_2d_dim(num_freq_bands)
    # Use the same explicit 2D Fourier features in both implementations so
    # intra-patch positions are encoded equivalently.
    return nn.Sequential(
        FourierFeatures2D(num_freq_bands=num_freq_bands, max_freq=max_freq),
        Perceiver(
            # Retained for compatibility with the original constructor;
            # positional features are added explicitly above.
            num_freq_bands=num_freq_bands,
            max_freq=max_freq,
            depth=self.depth,
            input_axis=2,
            input_channels=in_channels + fourier_dim,
            num_classes=out_channels,
            latent_dim=self.latent_dim,
            num_latents=self.num_latents,
            weight_tie_layers=True,
            fourier_encode_data=False,
            self_per_cross_attn=2,
            attention_backend=_attention_backend(implementation),
        ),
    )

build_io(in_channels, queries_dim, out_channels, implementation)

Build a PerceiverIO (used by the decoder).

Source code in src/samudra/config.py
def build_io(
    self,
    in_channels: int,
    queries_dim: int,
    out_channels: int,
    implementation: PerceiverImpl,
) -> nn.Module:
    """Build a PerceiverIO (used by the decoder)."""
    return PerceiverIO(
        depth=self.depth,
        dim=in_channels,
        queries_dim=queries_dim,
        logits_dim=out_channels,
        num_latents=self.num_latents,
        latent_dim=self.latent_dim,
        weight_tie_layers=True,
        decoder_ff=True,
        attention_backend=_attention_backend(implementation),
    )

DecoderConfig

Bases: BaseConfig

A PerceiverIO-based decoder configuration.

Uses PerceiverIO (with an explicit query mechanism) rather than a regular Perceiver. Output pixel positions are encoded as queries, so the output size is determined by the query count — not by num_latents.

When window_patches is set, the decoder tiles the output grid into spatial blocks of that many patches per side. Each block's PerceiverIO call receives only the overlapping latent tokens plus context_patches extra rings of neighbors, keeping cost bounded even when the latent grid is large (i.e. fine patch_extent).

ResidualConfig

Bases: BaseConfig

Predict each next state as one-step increments on the input, not the state.

Each output step is the network's output, times a per-variable scale, added to the step before it, starting from the newest input. The loss compares the network's outputs with the label in the same units, so with scale: increment_rms every variable's increment counts in units of its own typical change.

configure_data(data, data_stride)

Check the data suits this head, and request the statistics it needs.

q is the RMS of one stored step, so with increment_rms every model step must be one stored step: no stride.

Source code in src/samudra/config.py
def configure_data(self, data: DataConfig, data_stride: Sequence[int]) -> None:
    """Check the data suits this head, and request the statistics it needs.

    q is the RMS of one stored step, so with ``increment_rms`` every model
    step must be one stored step: no stride.
    """
    if not self.needs_increment_rms:
        return
    if any(stride != 1 for stride in data_stride):
        # A stride of s makes each model step span s stored steps.
        raise ValueError(
            "residual.scale='increment_rms' needs data_stride == [1]; q is the "
            f"RMS of a single step, got data_stride={list(data_stride)}"
        )
    if len(data.sources) != 1:
        raise ValueError(
            "residual.scale='increment_rms' is defined for a single data "
            "source's normalization"
        )
    data.sources[0].require_increment_rms()

SearchRunConfig

Bases: BaseConfig

Identity of a training run managed by an architecture search.

RolloutValidationConfig

Bases: BaseConfig

Configuration for expensive autoregressive validation during training.

ObsMetricsConfig

Bases: BaseConfig

Where the observation products live, and over what period to score.

Supplying this block is what turns observation metrics on: an eval job then compares its rollout against DUACS, OISST and ARGO-IAP once the rollout is on disk. Omit it (or pass --observations=null) to skip that phase.

window property

The scoring window, with a date-only end bound taken to end-of-day.

OM4 samples are stamped at 12:00, so a bare 2022-12-31 end bound would exclude that day's sample. Currently masked because the observation products end earlier and the window gets trimmed to the shared span, but it becomes a silent one-sample loss the moment coverage extends past rmse_end -- and the 7.5-day tolerance in the complete-calendar-year check is far too loose to notice.

PostTrainEvalConfig

Bases: BaseConfig

build(nets_dir, output_dir, data_root)

Build the runtime sweep.

Source code in src/samudra/config.py
def build(
    self,
    nets_dir: Path,
    output_dir: Path,
    data_root: ResolvedLocation,
) -> "CheckpointSweep":
    """Build the runtime sweep."""
    return CheckpointSweep(
        eval_config_path=self.eval_config_path,
        checkpoint_paths=CheckpointPaths(nets_dir),
        data_root=data_root,
        sweep_output_dir=output_dir / "evals",
        viz_config_path=self.viz_config_path,
        last_n_checkpoints=self.last_n_checkpoints,
        checkpoints=self.epochs,
    )

PostTrainEvalCliConfig(*args, **kwargs)

Bases: TopLevelConfig

Evaluate the saved checkpoints of an already-finished training run.

Source code in src/samudra/config_base.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

samudra.config_base

BaseConfig

Bases: BaseModel

Base class for all configs.

TopLevelConfig(*args, **kwargs)

Bases: BaseSettings

Base class for top-level configs (ie tasks like train or eval).

Source code in src/samudra/config_base.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

from_yaml(config_path) classmethod

Load and validate a YAML config without CLI overrides.

Source code in src/samudra/config_base.py
@classmethod
def from_yaml(cls, config_path: Path | str) -> Self:
    """Load and validate a YAML config without CLI overrides."""
    return cls(**cls._load_yaml(config_path))

from_yaml_and_cli(args_to_parse=None) classmethod

Load config from YAML & CLI with validation.

Source code in src/samudra/config_base.py
@classmethod
def from_yaml_and_cli(
    cls,
    args_to_parse: list[str] | None = None,
) -> Self:
    """Load config from YAML & CLI with validation."""
    parser = argparse.ArgumentParser(
        description=cls.__doc__,
        epilog=textwrap.dedent(
            """
            CONFIG may be a path to a YAML file or, when samudra is installed,
            the name of a bundled preset such as `samudra_om4/train.yaml`.
            YAML files can include other YAML files using the !include tag,
            as in `data: !include ../data/om4.yaml` (resolved relative to the
            including file). You can also replace any JSON argument listed above
            with a YAML file by specifying it with an @ symbol,
            eg `--some_param=@../data/om4.yaml`.
            """
        ),
    )
    parser.add_argument(
        "config",
        type=str,
        help="Path to a config YAML file, or a bundled preset name",
    )

    cli_source = IncludeYamlCliSettingsSource(
        cls,
        root_parser=parser,
        # If args_to_parse is None, we parse argv, which is what `True` does
        cli_parse_args=args_to_parse if args_to_parse is not None else True,
    )

    # We do this after creating CliSettingsSource (which populates the parser)
    # so the help is complete on error.
    args = parser.parse_args(args_to_parse)

    return cls(
        _cli_settings_source=cli_source,
        **cls._load_yaml(args.config),
    )

save_yaml(save_path)

Save config to YAML file.

Source code in src/samudra/config_base.py
def save_yaml(self, save_path: Path) -> None:
    """Save config to YAML file."""
    with open(save_path, "w") as f:
        yaml.safe_dump(self.model_dump(mode="json"), f)

IncludeYamlCliSettingsSource(*args, **kwargs)

Bases: CliSettingsSource

CliSettingsSource which permits @filename.yaml for JSON arguments.

Source code in src/samudra/config_base.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

register_include_constructor()

Set up yaml.safe_load to include other yaml files via !include.

Source code in src/samudra/config_base.py
def register_include_constructor():
    """Set up yaml.safe_load to include other yaml files via !include."""

    def include_constructor(loader: yaml.Loader, node: yaml.Node) -> Any:
        if hasattr(loader.stream, "name"):
            name = loader.stream.name  # type: ignore
        else:
            raise ValueError(
                "To support includes, you must load a file object, not a string"
            )
        filename = os.path.normpath(os.path.join(os.path.dirname(name), node.value))
        with open(filename) as f:
            return yaml.safe_load(f)

    # This is arguably unsafe, but we don't parse untrusted YAML
    yaml.loader.SafeLoader.add_constructor("!include", include_constructor)

resolve_config_path(config)

Resolve a config argument to a file on disk.

A real filesystem path wins, so a checkout behaves exactly as before. If it doesn't exist, fall back to a preset bundled in the installed package (e.g. samudra_om4/train.yaml), so samudra train samudra_om4/train.yaml works with no checkout. The bundled configs install as real co-located files, so their relative !includes resolve unchanged.

Source code in src/samudra/config_base.py
def resolve_config_path(config: str) -> Path:
    """Resolve a config argument to a file on disk.

    A real filesystem path wins, so a checkout behaves exactly as before. If it
    doesn't exist, fall back to a preset bundled in the installed package (e.g.
    ``samudra_om4/train.yaml``), so ``samudra train samudra_om4/train.yaml``
    works with no checkout. The bundled configs install as real co-located
    files, so their relative ``!include``s resolve unchanged.
    """
    path = Path(config).expanduser()
    if not path.exists():
        bundled = importlib.resources.files("samudra") / "configs" / config
        if bundled.is_file():
            path = Path(str(bundled))
    return path.resolve()