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 |
|---|---|---|
|
|
|
|
|
|
|
the feature source |
the |
|
|
|
|
|
the learner’s name and params: the model’s |
|
|
|
|
|
|
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) refusescohort.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:
EditableA whole experiment: the seven sections. Only
cohortis required; a run that trains needs alearnerwith ahead.
- soma.resolve(config, cohort)¶
Expand
configinto itsPlanagainstcohort.Every
{name, params}leaf takes its registered params dataclass’s defaults; the head’sinferhook adds what the cohort decides, under the explicit params (a differing explicit value raises); the head’stargetsare 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:
- class soma.Plan(config)¶
Bases:
MappingA resolved config, frozen: section name -> section.
plan.learner(orplan["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:
objectA
{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 amulticlass_classificationhead learns the cohort’slabelcolumn. 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:
- 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 aregressionhead learns the cohort’svaluecolumn with a mean squared error loss. To regress several values, set the head’snum_outputsparam to their countG: the head then reads the columnsvalue_0tovalue_{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:
- 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) andtile_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 itspacing.soma.plan.check()refuses a spacing or tile size the encoder does not support. The tiles are embedded once and cached, andaggregator(abmil,transmil,mean_pool, …;soma list aggregators) pools the bag for amulticlass_classificationhead (two classes or more; the classes come from the cohort’slabelcolumn). 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:
- 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
spacingandtile_sizeand embedded as inmil_classification();aggregatorpools the bag for aregressionhead, which learns the cohort’svaluecolumn with a mean squared error loss. To regress several values, set the head’snum_outputsparam to their countG: the head then reads the columnsvalue_0tovalue_{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:
- 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
spacingandtile_sizeand embedded as inmil_classification();aggregatorpools the bag for the headlosspicks. Both heads read the cohort’stimeandeventcolumns:nll: thediscrete_survivalhead, a discrete-time model trained with the hazard negative log-likelihood overnum_binstime bins (required fornll). 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 nobincolumn.cox: thecox_survivalhead, a Cox proportional-hazards model trained with the Breslow partial likelihood; it has no bins, so it takes nonum_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’scox_window): one optimizer step per 32 bags, wherenlltakes 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:
- 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. Amulticlass_classificationhead (two classes or more; the classes come from the cohort’slabelcolumn) 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:
- 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 aregressionhead learns the cohort’svaluecolumn from each slide’s embedding with a mean squared error loss. To regress several values, set the head’snum_outputsparam to their countG: the head then reads the columnsvalue_0tovalue_{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:
- 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 headlosspicks learns from each slide’s embedding. Both heads read the cohort’stimeandeventcolumns:nll: thediscrete_survivalhead, a discrete-time model trained with the hazard negative log-likelihood overnum_binstime bins (required fornll). The run derives the bins from each fold’s training split (binning: train_quantiles), as inmil_survival(). The cohort carries nobincolumn.cox: thecox_survivalhead, a Cox proportional-hazards model trained with the Breslow partial likelihood; it has no bins, so it takes nonum_bins. Each slide is one embedding, so the head computes its loss over each batch of 32 slides, its risk set (padded mode, with nocox_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:
- 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;
decoderupsamples it to per-pixelsegmentationlogits fornum_classesclasses, whose indices the label masks hold (2for background 0 and one foreground class 1). For masks holding raw values, replace the head’s params with aclassesmapping (class name -> raw mask values) andignore. Batches of 8, AdamW (lr 1e-4) with a cosine schedule, 50 epochs, selection and early stopping on the tune loss.- Return type:
- 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;
decoderpredicts a peak heatmap for each ofnum_classesclasses, whose indices the point annotations hold (1for a single cell class), scored by F1 atmatch_distanceµm (3 µm, about a nucleus radius, by default). For points holding raw classes, replace the head’s params with aclassesmapping (class name -> raw point classes) anddrop. One image per batch, AdamW (lr 1e-4) with a cosine schedule, 50 epochs, selection and early stopping on the tune loss.- Return type: