Configuration

An experiment is one soma.ExperimentConfig. Its seven sections each hold the keyword arguments of one public callable, so a YAML file and a Python config spell every field the same way: a knob that cannot be passed in Python cannot appear in YAML.

Section

Callable

Holds

run

Pipeline

output_dir, seed, run_id, resume, folds, mirror_root

cohort

Cohort

records and splits (the two CSV files), collapse, tune_is_test, allow_missing_tune, train_subset

features

the feature source

the encoder leaf, slide2vec’s extraction, execution and dense options, the cache, kind and spacing_policy (see Preprocessing)

loaders

soma.learn.loaders()

batch_size, worker settings, the sampler and augment leaves

learner

Learner

the learner’s name and params: the model’s aggregator or decoder and head leaves, optimizer, scheduler, normalization, projection and the learner’s own keywords

trainer

Trainer

max_epochs or max_steps, accumulate_grad_batches, val_every_n_epochs, device, precision, eval_train, callbacks

evaluation

soma.evaluate()

metrics, subgroups, unpredicted, holdout_test, overwrite_test, the saved artifacts, attention_heatmaps and representation

Only cohort is required. A field left out keeps its default; examples/reference.yaml spells every section at its defaults (see the CLI reference).

Components

Every swappable component is a {name, params} leaf: the encoder, the aggregator, decoder and head, the optimizer and each scheduler, the sampler, the augmentation, each trainer callback and the learner itself. name is a registry key or a dotted import path to a class; params are its constructor keywords, validated against the params the component declares (ADR 0018). A bare name stands for {name, params: {}}. soma list KIND prints every registered component of a kind with its params and their defaults.

learner:
  name: mil
  params:
    aggregator: abmil
    head:
      name: multiclass_classification
      params: {dropout: 0.1}
    optimizer: {name: adamw, params: {lr: 3.0e-4}}

The learner decides the training path. mil trains the set shape (a bag or a vector per sample) and dense the grid shape (a feature grid per sample, segmentation and detection). The head decides the task family. A set run’s sample is a patient with cohort.collapse: patient_id, a tile when a tile encoder runs without an aggregator, and otherwise a slide.

Training on a subset

cohort.train_subset names a text file with one sample id per line. Each line is read literally, like the ids in the CSV files: a space is part of the id. Empty lines are skipped. Each fold then trains on the listed ids of its train split only, in the split’s order. Tune and test do not change. Use it to train the same experiment on less data, for example to measure how a model scales with the number of annotated samples.

cohort:
  records: slides.csv
  splits: splits.csv
  train_subset: subsets/rung_0128.txt
  • One file serves every fold of the run. Every listed id must be in the train split of every fold. The run refuses an empty file, an id listed twice, an id the cohort does not have, and an id that a fold puts in tune or test. The error names the fold and the id.

  • The ids are the run’s samples. When the run samples ROIs from whole slides, they are ROI ids, not slide ids (see Training on a subset of the ROIs). A patient run (cohort.collapse: patient_id) refuses cohort.train_subset.

  • What the run fits on the train split sees the subset only: the feature normalization, the ROI batch sampler and the survival bins.

  • The listed ids are part of the experiment identity: two subsets are two experiments. The feature caches do not depend on the subset, so runs over several subsets share them.

Editing a config

A config has no override mechanism: you edit it. In Python, assign its fields:

from soma import presets

config = presets.mil_classification("uni2", "abmil")
config.run.seed = 1
config.trainer.max_steps = 2000
config.learner.params["head"].params["dropout"] = 0.2

A field write runs no check of its own; soma.plan.check() builds every section again, so a value its constructor would refuse is refused before anything runs. A step budget written over an epoch budget replaces it, as at construction. On the command line, edit the YAML file: soma init PRESET prints a preset (see Use cases) with every default filled in, and soma run config.yaml runs a file. ExperimentConfig.from_yaml(path) reads a YAML file and to_yaml(path) writes one.

Checking and resolving

soma.plan.check() validates a config across its sections (for example that a decoder belongs to the dense learner, or that a survival head is not given tile samples) without reading any file. soma.resolve() then expands the config against its cohort into a soma.Plan: every component’s params with their defaults, plus what the cohort decides, such as a classification head’s label map. A value the config states wins; a contradiction raises. A null value counts as unset, so the cohort decides it. Pipeline runs both at its start. A plan is frozen: its sections refuse field writes.

The run directory keeps config.yaml (the config as given) and plan.yaml (the plan). plan.yaml loads as a config, so soma run plan.yaml replays a run with every value pinned, while soma run config.yaml resolves again against the current code and cohort. See The plan for how a resume compares plans and what the experiment identity digests.

class soma.ExperimentConfig(*, run=<factory>, cohort, features=<factory>, loaders=<factory>, learner=None, trainer=<factory>, evaluation=<factory>)

Bases: Editable

A whole experiment: the seven sections. Only cohort is required; a run that trains needs a learner with a head.

soma.resolve(config, cohort)

Expand config into its Plan against cohort.

Every {name, params} leaf takes its registered params dataclass’s defaults; the head’s infer hook adds what the cohort decides, under the explicit params (a differing explicit value raises); the head’s targets are spelled out. The plan is normalized through its YAML form, so a Python config and the YAML it saves resolve to one plan.

Return type:

Plan

class soma.Plan(config)

Bases: Mapping

A resolved config, frozen: section name -> section.

plan.learner (or plan["learner"]) is the resolved section; its sections refuse field writes. to_yaml() / from_yaml() round-trip it, and two plans are equal when their YAML forms are.

class soma.config.Component(name, params=<factory>)

Bases: object

A {name, params} leaf: a registry key or a dotted import path, and its params.

Presets

A preset returns a complete config for a common task. The use-case table shows which preset fits your encoder and task, and soma.components("presets") lists them with their arguments.

segmentation and detection decode each tile’s token grid, so they take a tile-level encoder. Each preset checks the level of its encoder when it is built, and refuses an encoder of another level by naming the preset to use: presets.tile_classification("titan") asks for slide_classification, and presets.slide_classification("uni2") for mil_classification or tile_classification. No preset covers patient-level encoders (moozy) yet.

A choice that changes the model has no default: you name the aggregator of a mil_* preset, the loss of mil_survival and slide_survival ("nll" or "cox", and num_bins for "nll") and the num_classes of segmentation and detection.

The mil_* presets take the tiling as arguments: spacing (µm per pixel) and tile_size (pixels). An argument you leave out takes the encoder’s recommended value, and the preset keeps its tiles with at least 10% tissue:

config = presets.mil_classification("uni2", "abmil", spacing=0.5, tile_size=224)

On the command line, they are the --spacing and --tile-size flags of soma init and soma run --preset. The slide_* presets keep the same tissue, at the slide encoder’s own tiling: a slide encoder is tied to the tile size and spacing of its tile encoder, so they take no tiling arguments.

soma.presets.tile_classification(encoder)

Classify tile images: a linear probe on a frozen tile encoder’s embeddings.

Each row of the cohort is one image, embedded whole by encoder (no tiling, no aggregator), and a multiclass_classification head learns the cohort’s label column. Batches of 256 embeddings, AdamW (lr 3e-4) without a schedule, 50 epochs, the best tune-loss checkpoint and early stopping after 10 epochs without improvement.

Return type:

ExperimentConfig

soma.presets.tile_regression(encoder)

Regress a value from tile images: a linear probe on a frozen tile encoder’s embeddings.

Each row of the cohort is one image, embedded whole by encoder (no tiling, no aggregator), and a regression head learns the cohort’s value column with a mean squared error loss. To regress several values, set the head’s num_outputs param to their count G: the head then reads the columns value_0 to value_{G-1}. Batches of 256 embeddings, AdamW (lr 3e-4) without a schedule, 50 epochs, the best tune-loss checkpoint and early stopping after 10 epochs without improvement.

Return type:

ExperimentConfig

soma.presets.mil_classification(encoder, aggregator, spacing=None, tile_size=None)

Classify whole slides: a frozen tile encoder, a MIL aggregator and a classifier.

Each slide is tiled at spacing (µm per pixel) and tile_size (pixels), keeping the tiles with at least 10% tissue. An argument left out takes the encoder’s recommended value; virchow2, which supports several spacings, recommends none, so give it spacing. soma.plan.check() refuses a spacing or tile size the encoder does not support. The tiles are embedded once and cached, and aggregator (abmil, transmil, mean_pool, …; soma list aggregators) pools the bag for a multiclass_classification head (two classes or more; the classes come from the cohort’s label column). AdamW (lr 1e-4) with a cosine schedule, 50 epochs, the best tune-loss checkpoint and early stopping after 10 epochs without improvement.

Return type:

ExperimentConfig

soma.presets.mil_regression(encoder, aggregator, spacing=None, tile_size=None)

Regress a value from whole slides: a frozen tile encoder, a MIL aggregator and a regressor.

Slides are tiled at spacing and tile_size and embedded as in mil_classification(); aggregator pools the bag for a regression head, which learns the cohort’s value column with a mean squared error loss. To regress several values, set the head’s num_outputs param to their count G: the head then reads the columns value_0 to value_{G-1}. AdamW (lr 1e-4) with a cosine schedule, 50 epochs, the best tune-loss checkpoint and early stopping after 10 epochs without improvement.

Return type:

ExperimentConfig

soma.presets.mil_survival(encoder, aggregator, loss, num_bins=None, spacing=None, tile_size=None)

Predict survival from whole slides: a MIL bag and a discrete-time or Cox head.

Slides are tiled at spacing and tile_size and embedded as in mil_classification(); aggregator pools the bag for the head loss picks. Both heads read the cohort’s time and event columns:

  • nll: the discrete_survival head, a discrete-time model trained with the hazard negative log-likelihood over num_bins time bins (required for nll). The run derives the bins from each fold’s training split (binning: train_quantiles): the cut points are quantiles of its uncensored times, so the tune and test times never shape them. The cohort carries no bin column.

  • cox: the cox_survival head, a Cox proportional-hazards model trained with the Breslow partial likelihood; it has no bins, so it takes no num_bins. Bags are forwarded one at a time and each loss is computed over a window of 32 of them, its risk set (the head’s cox_window): one optimizer step per 32 bags, where nll takes one per bag.

Both losses train the same way: AdamW (lr 1e-4) with a cosine schedule, 50 epochs, selection and early stopping on the tune loss.

Return type:

ExperimentConfig

soma.presets.slide_classification(encoder)

Classify whole slides: a linear probe on a frozen slide encoder’s embeddings.

Each slide is tiled at the encoder’s own tile size and spacing, keeping the tiles with at least 10% tissue (the tissue of the mil_* presets). encoder (titan, prism, …; soma list encoders --level slide) embeds each slide’s tiles with its tile encoder and pools them into one embedding, cached once. A multiclass_classification head (two classes or more; the classes come from the cohort’s label column) learns from that embedding: there is no aggregator to train. Batches of 32 slides, AdamW (lr 3e-4) without a schedule, 50 epochs, the best tune-loss checkpoint and early stopping after 10 epochs without improvement.

Return type:

ExperimentConfig

soma.presets.slide_regression(encoder)

Regress a value from whole slides: a linear probe on a frozen slide encoder’s embeddings.

Slides are tiled and embedded as in slide_classification(), and a regression head learns the cohort’s value column from each slide’s embedding with a mean squared error loss. To regress several values, set the head’s num_outputs param to their count G: the head then reads the columns value_0 to value_{G-1}. Batches of 32 slides, AdamW (lr 3e-4) without a schedule, 50 epochs, the best tune-loss checkpoint and early stopping after 10 epochs without improvement.

Return type:

ExperimentConfig

soma.presets.slide_survival(encoder, loss, num_bins=None)

Predict survival from whole slides: a discrete-time or Cox head on a slide encoder’s embeddings.

Slides are tiled and embedded as in slide_classification(), and the head loss picks learns from each slide’s embedding. Both heads read the cohort’s time and event columns:

  • nll: the discrete_survival head, a discrete-time model trained with the hazard negative log-likelihood over num_bins time bins (required for nll). The run derives the bins from each fold’s training split (binning: train_quantiles), as in mil_survival(). The cohort carries no bin column.

  • cox: the cox_survival head, a Cox proportional-hazards model trained with the Breslow partial likelihood; it has no bins, so it takes no num_bins. Each slide is one embedding, so the head computes its loss over each batch of 32 slides, its risk set (padded mode, with no cox_window).

Both losses train the same way: batches of 32 slides, AdamW (lr 3e-4) without a schedule, 50 epochs, selection and early stopping on the tune loss.

Return type:

ExperimentConfig

soma.presets.segmentation(encoder, decoder, num_classes)

Segment tissue: a decoder over a frozen encoder’s dense token grid.

Each tile (at the encoder’s recommended size and spacing) is encoded once into a token grid and cached; decoder upsamples it to per-pixel segmentation logits for num_classes classes, whose indices the label masks hold (2 for background 0 and one foreground class 1). For masks holding raw values, replace the head’s params with a classes mapping (class name -> raw mask values) and ignore. Batches of 8, AdamW (lr 1e-4) with a cosine schedule, 50 epochs, selection and early stopping on the tune loss.

Return type:

ExperimentConfig

soma.presets.detection(encoder, decoder, num_classes, match_distance=3.0)

Detect cells: a decoder over a frozen encoder’s dense token grid, one heatmap per class.

Each image is encoded once into a token grid and cached; decoder predicts a peak heatmap for each of num_classes classes, whose indices the point annotations hold (1 for a single cell class), scored by F1 at match_distance µm (3 µm, about a nucleus radius, by default). For points holding raw classes, replace the head’s params with a classes mapping (class name -> raw point classes) and drop. One image per batch, AdamW (lr 1e-4) with a cosine schedule, 50 epochs, selection and early stopping on the tune loss.

Return type:

ExperimentConfig