CLI¶
Use soma to run experiments, discover components, score
predictions, reproduce benchmarks, and compare completed runs.
You provide three files — a dataset, splits, and a config. soma then
schedules every step: tiling, feature extraction, training, and metrics.¶
Basic usage¶
soma run runs a YAML config:
soma run /path/to/config.yaml
or a preset on your cohort (see Use cases):
soma run --preset mil_classification --encoder uni2 --aggregator abmil \
--cohort dataset.csv --splits splits.csv --out runs
A config is edited, not overridden: there are no override flags. To start from a preset and change it, print it as YAML with every default filled in, edit the file, and run it:
soma init mil_classification --encoder uni2 --aggregator abmil > experiment.yaml
soma run experiment.yaml
Use soma --help or soma COMMAND --help for command options.
Train on features you already have with --feature-dir: the directory of a
pooled feature cache (slide, patient and tile runs) or of dense grids
(segmentation and detection). The run attaches it and extracts nothing:
soma run config.yaml --feature-dir runs/features/uni2
Train the folds of a cross-validation run side by side with --devices,
one process per GPU. The features are extracted first; each fold then trains
in its own process and writes its output to fold_<k>/worker.log:
soma run config.yaml --devices 0,1,2,3
soma prints soma’s INFO log messages to stderr, and warnings and errors
from other libraries. See Log output for the same behaviour in a Python
script.
Available commands¶
soma run CONFIG [--feature-dir DIR] [--devices LIST]Run an experiment from a YAML config file, optionally on pre-extracted features. The run directory keeps the config as given (
config.yaml) and its resolved plan (plan.yaml), written before training starts;soma run plan.yamlreplays a run with every value pinned.--devices 0,1,2,3trains the folds side by side, one process per GPU (cpuentries train on the CPU); a one-fold run ignores it with a warning. See Train the folds side by side.soma run --preset NAME --cohort CSV --splits CSV --out DIR [--seed N] [PRESET ARGUMENTS] [--feature-dir DIR] [--devices LIST]Run a preset on a cohort: the preset’s own arguments are flags (
--encoder,--aggregator,--decoder;soma run --preset NAME --helplists them), its required ones are required, and--seeddefaults to 0. The registered presets:tile_classification(encoder)— Classify tile images: a linear probe on a frozen tile encoder’s embeddings.tile_regression(encoder)— Regress a value from tile images: a linear probe on a frozen tile encoder’s embeddings.mil_classification(encoder, aggregator, spacing=None, tile_size=None)— Classify whole slides: a frozen tile encoder, a MIL aggregator and a classifier.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.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.slide_classification(encoder)— Classify whole slides: a linear probe on a frozen slide encoder’s embeddings.slide_regression(encoder)— Regress a value from whole slides: a linear probe on a frozen slide encoder’s embeddings.slide_survival(encoder, loss, num_bins=None)— Predict survival from whole slides: a discrete-time or Cox head on a slide encoder’s embeddings.segmentation(encoder, decoder, num_classes)— Segment tissue: a decoder over a frozen encoder’s dense token grid.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.
soma init NAME [PRESET ARGUMENTS]Print the preset as an editable YAML config with every component’s params at their defaults. Fields the cohort or the machine decide are
null; pointcohort.recordsandcohort.splitsat your files beforesoma run.soma list [KIND] [--level {tile,slide,patient}]Without
KIND, list the component kinds:aggregators,augmentations,benchmarks,callbacks,decoders,encoders,heads,learners,optimizers,presets,samplers,schedulers. With aKIND, list its registered components and the default of each of their params;soma list benchmarksprints the namessoma reproduceandsoma leaderboardaccept.--levelnarrows the encoders totile,slide, orpatient.soma.components()returns the same listing in Python.soma evaluate PREDICTIONS --cohort CSV [--splits CSV --split NAME --fold N] [--metrics M ...] [--subgroups COL ...] [--unpredicted {error,exclude}] [--out JSON] [--backend NAME] [--mask-backend NAME] [--num-workers N] [--threshold T]Score saved predictions against the targets in
dataset.csv, joined bysample_id; no run directory is needed.PREDICTIONSis a predictions parquet, a points parquet (detection), a label-map directory (segmentation), or asoma predictoutput (whole-slide segmentation or detection). A predictions parquet is scored against the cohort’s target columns, points against the files in itspoints_pathcolumn, and label maps against the class-index masks in itslabel_mask_pathcolumn. Asoma predictoutput with one bundle’s maps, or one of its bundle directories, is scored against the annotation rasters inlabel_mask_path, read with the class scheme each map records; a second table gives each slide’s annotated pixels and the share of them not predicted. Its slides and annotation rasters are read with the hs2p readers itsplan.yamlrecords;--backendnames another reader for the slides and--mask-backendanother one for the annotation rasters. A map is read only in the windows that hold an annotated pixel.--num-workers Nscores its slides inNworker processes, one slide at a time each (default0: in the main process); the scores and the order of the rows do not change. Asoma predictoutput with one bundle’s points is scored against the annotated points inpoints_pathand the ignore masks inignore_mask_path, with the class scheme and the tune threshold each points file records; a second table gives each slide’s annotated area and counts.--mask-backendnames another reader for its ignore masks.--thresholdkeeps the points scoring at least that value: it replaces the recorded threshold, and an ensemble’s points, which record none, need it.--backendand--mask-backendare refused for predictions that read no slide or mask,--num-workersfor predictions other than the label maps of asoma predictoutput, and--thresholdfor predictions without points.--splitsselects one split (defaulttest) of one fold (default0); without it every row of the cohort is a target. Every prediction needs a target. A target without a prediction (a predictions parquet only) follows--unpredicted:error(default) refuses to score and names the samples,excludescores the predicted samples only. The metrics holdnum_samples,num_predictedandcoverageeither way.--metricstakes metric names or dotted import paths (default: the task family’s defaults);--subgroupsnames metadata columns to break the metrics down by. The metrics table is printed;--outalso writes the evaluation as JSON. See Evaluation, and Whole-slide inference forsoma predictoutputs.soma predict CONFIGPredict over whole slides with trained segmentation or detection bundles, all of one family. The config has three sections:
predict(output_dir,bundles,ensemble,stitch,restrict_to_mask,batch_size,num_workers,devices,split),cohort(records, and optionallysplits,subsetandfold: a fold, orbundlefor each bundle’s own fold) andextraction(thefeatures.extractionschema). The tile size and the read spacing come from the bundles, and setting other values is refused. The slides are read with the reader the bundles were trained with, unlessextraction.tiling.backendnames one: bundles that record different readers are refused unless it does, a reader other than a bundle’s is used with a warning, and when no bundle records a reader the slides are read withauto. Each slide gets one file per bundle and a record<sample_id>.json. A segmentation bundle writes a label TIFF,<output_dir>/<bundle>/<sample_id>.tif, where classkis stored ask + 1and0means not predicted. A detection bundle writes a points parquet,<output_dir>/<bundle>/<sample_id>.parquet, withxandyin level-0 pixels,classandscore: every peak above the head’smin_score, with no threshold applied. Its metadata records the bundle’s class scheme, and a detection bundle that records none is refused. With an overlap, its margin (tile * overlap / 2) must be at least the head’s NMS distance.index.parquetlists the files. The resolved plan is written to<output_dir>/plan.yamlfirst;soma predict <output_dir>/plan.yamlreplays it and predicts only the slides not done yet. The same in Python:soma.predict_slides(). See Whole-slide inference.soma compact-index OUTPUT_ROOTCompact
indexes/runs.csvto the latest row per run. Readers already deduplicate the append-only index; compaction saves space. A path to the CSV itself is also accepted. See Run outputs.
Benchmarking commands¶
soma prepare-croma RAW_ROOT [--rebuild]Download and decode the pinned PathoROB tile sources for CRoMa.
--rebuildreplaces a partial or revision-mismatched destination.soma reproduce NAME [--encoder NAME | --encoders NAME [NAME ...]] [--raw-root DIR | --curated-dir DIR | --from-run-dir DIR] [--seeds N] [--devices LIST]Curate, run, and score a registered benchmark.
NAMEis a benchmark (ocelot,eva/bach) or a family prefix (eva).--raw-rootcurates from raw data,--curated-dirreuses prepared manifests, and--from-run-dirrescores one existing run, or everyseed_<k>run under an output root.--encodersruns an ordered panel and writes one leaderboard per benchmark.--seeds Nruns seeds 0 through N−1.--devices 0,1,2,3runs the seeds side by side, one process per GPU (cpuentries run on the CPU); when the benchmark has more than one fold, it runs each seed’s folds side by side and the seeds one after another.--output-root,--cache-root, and--out-dirplace run artifacts, shared features, and curated manifests;--recordappends the score of a run over the benchmark’s canonical seeds to its results ledger,soma/benchmark/<protocol>/results.csvnext to itsreference.csv. See Benchmarking for panel validation, partial failures, parallel seeds, and reference comparisons.soma leaderboard [NAME] --root OUTPUT_ROOT [--vary AXIS] [--fix AXIS=VALUE] [--like DIR]Render a faceted leaderboard over the completed run dirs under an output root. A benchmark
NAMEsupplies the canonical facet and reference band;--vary/--fix/--likeshape the facet on top of it.
Full config reference¶
A config has seven sections, one per public callable: run holds
Pipeline’s keywords, cohort the cohort’s,
features the feature source’s, loaders the data loaders’, learner
the learner’s, trainer the Trainer’s and
evaluation evaluate()’s. The YAML below is
examples/reference.yaml: a slide-level classifier with every other field
at its default. A config states only what differs; soma.resolve() fills
in the rest and writes it to the run’s plan.yaml. Component params
({name, params}) are listed by soma list KIND. See
Configuration.
run:
output_dir: runs
seed: 0
folds: null
run_id: null
resume: false
mirror_root: null
cohort:
records: data/dataset.csv
splits: data/splits.csv
collapse: null
tune_is_test: false
allow_missing_tune: false
train_subset: null
features:
kind: cached
encoder:
name: uni2
params: {}
extraction:
tiling: null
segmentation:
method: hsv
downsample: 64
sthresh: 8
sthresh_up: 255
mthresh: 7
close: 4
sam2_checkpoint_path: null
sam2_config_path: null
sam2_device: cpu
sam2_num_workers: null
filter: null
preview:
save_mask_preview: true
save_tiling_preview: true
downsample: 32
tissue_contour_color:
- 157
- 219
- 129
mask_overlay_alpha: 0.5
masks:
pixel_mapping:
background:
- 0
tissue:
- 1
colors:
background: null
tissue:
- 157
- 219
- 129
min_coverage:
tissue: 0.01
output_mode: per_annotation
strategy: joint
requested_region_size_px: null
region_tile_multiple: null
read_coordinates_from: null
read_tiles_from: null
on_the_fly: true
save_tiles: false
gpu_decode: false
adaptive_batching: false
use_supertiles: true
jpeg_backend: pil
num_cucim_workers: 4
resume: false
execution:
output_dir: null
output_format: pt
batch_size: 32
num_workers_per_gpu: null
num_preprocessing_workers: null
num_gpus: null
precision: null
output_dtype: null
prefetch_factor: 4
save_tile_embeddings: false
save_slide_embeddings: false
save_latents: false
on_image_mismatch: raise
dense: null
cache:
enabled: true
root_dir: null
reuse_policy: strict
validate_payloads: false
dtype: null
on_identity_mismatch: error
spacing_policy: strict
loaders:
batch_size: 1
num_workers: 0
pin_memory: false
persistent_workers: false
sampler: null
augment: null
learner:
name: mil
params:
aggregator:
name: abmil
params: {}
head:
name: binary_classification
params: {}
trainer:
max_epochs: 50
max_steps: null
accumulate_grad_batches: 1
val_every_n_epochs: 1
device: auto
precision: fp32
eval_train: false
callbacks:
- name: checkpoint
params: {}
- name: early_stopping
params: {}
evaluation:
metrics: []
subgroups: []
unpredicted: error
holdout_test: false
overwrite_test: false
save_overlays: true
save_probabilities: false
save_heatmaps: false
attention_heatmaps: null
representation: null