CLI

Use soma to run experiments, discover components, score predictions, reproduce benchmarks, and compare completed runs.

Three input files flow into one soma command that schedules tiling, feature extraction, training, and metrics.

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.yaml replays a run with every value pinned. --devices 0,1,2,3 trains the folds side by side, one process per GPU (cpu entries 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 --help lists them), its required ones are required, and --seed defaults 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; point cohort.records and cohort.splits at your files before soma 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 a KIND, list its registered components and the default of each of their params; soma list benchmarks prints the names soma reproduce and soma leaderboard accept. --level narrows the encoders to tile, slide, or patient. 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 by sample_id; no run directory is needed. PREDICTIONS is a predictions parquet, a points parquet (detection), a label-map directory (segmentation), or a soma predict output (whole-slide segmentation or detection). A predictions parquet is scored against the cohort’s target columns, points against the files in its points_path column, and label maps against the class-index masks in its label_mask_path column. A soma predict output with one bundle’s maps, or one of its bundle directories, is scored against the annotation rasters in label_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 its plan.yaml records; --backend names another reader for the slides and --mask-backend another one for the annotation rasters. A map is read only in the windows that hold an annotated pixel. --num-workers N scores its slides in N worker processes, one slide at a time each (default 0: in the main process); the scores and the order of the rows do not change. A soma predict output with one bundle’s points is scored against the annotated points in points_path and the ignore masks in ignore_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-backend names another reader for its ignore masks. --threshold keeps the points scoring at least that value: it replaces the recorded threshold, and an ensemble’s points, which record none, need it. --backend and --mask-backend are refused for predictions that read no slide or mask, --num-workers for predictions other than the label maps of a soma predict output, and --threshold for predictions without points. --splits selects one split (default test) of one fold (default 0); 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, exclude scores the predicted samples only. The metrics hold num_samples, num_predicted and coverage either way. --metrics takes metric names or dotted import paths (default: the task family’s defaults); --subgroups names metadata columns to break the metrics down by. The metrics table is printed; --out also writes the evaluation as JSON. See Evaluation, and Whole-slide inference for soma predict outputs.

soma predict CONFIG

Predict 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 optionally splits, subset and fold: a fold, or bundle for each bundle’s own fold) and extraction (the features.extraction schema). 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, unless extraction.tiling.backend names 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 with auto. 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 class k is stored as k + 1 and 0 means not predicted. A detection bundle writes a points parquet, <output_dir>/<bundle>/<sample_id>.parquet, with x and y in level-0 pixels, class and score: every peak above the head’s min_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.parquet lists the files. The resolved plan is written to <output_dir>/plan.yaml first; soma predict <output_dir>/plan.yaml replays it and predicts only the slides not done yet. The same in Python: soma.predict_slides(). See Whole-slide inference.

soma compact-index OUTPUT_ROOT

Compact indexes/runs.csv to 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. --rebuild replaces 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. NAME is a benchmark (ocelot, eva/bach) or a family prefix (eva). --raw-root curates from raw data, --curated-dir reuses prepared manifests, and --from-run-dir rescores one existing run, or every seed_<k> run under an output root. --encoders runs an ordered panel and writes one leaderboard per benchmark. --seeds N runs seeds 0 through N−1. --devices 0,1,2,3 runs the seeds side by side, one process per GPU (cpu entries 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-dir place run artifacts, shared features, and curated manifests; --record appends the score of a run over the benchmark’s canonical seeds to its results ledger, soma/benchmark/<protocol>/results.csv next to its reference.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 NAME supplies the canonical facet and reference band; --vary / --fix / --like shape 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

See also

  • API — Python interfaces and recipes.

  • Modeling — supported component combinations.