API¶
Use the Python API to extract features once, train downstream models, and inspect results. Start with Getting started for the complete pipeline; the recipes here cover custom orchestration.
Main building blocks¶
Page |
Focus |
|---|---|
CSV manifest schema and fold assignment rules |
|
Tissue segmentation and slide tiling at a given spacing |
|
Feature extraction backends |
|
MIL pooling and bag-level aggregation |
|
Prediction heads and metric contracts |
|
Metric contracts, subgroup analysis, predictions and evaluations |
|
Optimization behavior and training defaults |
Extract once, cache, and reuse features across experiments¶
Extract a shared feature source, then train each downstream model in its own
run directory. This example uses uni2; see Encoders for model access
requirements.
from dataclasses import replace
import soma
from soma import Cohort, ExperimentConfig, ImageManifest, Pipeline
from soma.config import CacheOptions, CohortConfig, LearnerConfig, RunConfig, TrainerConfig
# The cohort holds identity, targets and folds; the image manifest holds the paths.
cohort = Cohort.from_csv("dataset.csv", "splits.csv", targets=["label"])
images = ImageManifest.from_csv("dataset.csv")
cache = CacheOptions(enabled=True, root_dir="shared/cache")
# Features enter through soma.extract: it reads the image manifest and returns the source.
features = soma.extract(images, encoder="uni2", cache=cache, output_dir="output")
def experiment(aggregator: dict) -> ExperimentConfig:
return ExperimentConfig(
run=RunConfig(output_dir="output"),
cohort=CohortConfig(records="dataset.csv", splits="splits.csv"),
learner=LearnerConfig(
"mil", {"aggregator": aggregator, "head": "binary_classification"}
),
trainer=TrainerConfig(max_epochs=50),
)
abmil = experiment({"name": "abmil", "params": {"hidden_dim": 256}})
clam = experiment({"name": "clam_sb", "params": {"hidden_dim": 256, "attn_dim": 128}})
abmil_result = Pipeline(abmil, source=features).run()
clam_result = Pipeline(clam, source=features).run()
Each config trains in its own run directory under run.output_dir; the source
is attached, never re-extracted.
soma.extract is the single way features enter soma; a Pipeline
without a source extracts through it too. It is also the namespace of
soma.extract.live_encoder().
- soma.extract.extract(images, *, encoder, cache, annotations=None, unit='slide', rois=None, execution=None, extraction=None, dense=None, spacing_policy='strict', output_dir, on_progress=None)¶
Extract (or reuse from the feature cache)
encoder’s features ofimages.- Parameters:
images (
ImageManifest) – The samples’ pixels: one row per whole slide (unit="slide") or per pre-cropped image (unit="tile"). The cache keys each sample on its row.encoder (
EncoderLeaf|str) – A slide2vec encoder name or{name, params}leaf.cache (
CacheOptions) – The feature and tiling cache policy (CacheOptions(enabled=False)writes underoutput_dironly).annotations (
AnnotationManifest|None) – The annotation rasters ROI sampling reads (label_mask_path); needed only to sample ROIs from whole slides.unit (
Literal['slide','tile']) – What one row is: a whole slide or a pre-cropped image.rois (
RoiSet|None) – The ROIs of an earlier annotation-sampled extraction (its source’srois): their grids are encoded again, without sampling. Their label crops were stored at the read spacing and window they were sampled at, so pass the sameextraction,denseandspacing_policy; another geometry is refused.execution (
ExecutionOptions|None) – slide2vec’sExecutionOptions(batch size, precision, GPUs).extraction (
PreprocessingConfig|None) – slide2vec’sPreprocessingConfig(tiling, segmentation, masks); unset fields come from the encoder’s recommendation.dense (
DenseOptions|None) – slide2vec’sDenseOptions: given, the features are token grids read and encoded at it; else one tensor per sample.spacing_policy (
str) – How a grid run reads a sample coarser thandense.spacing_um(native_if_coarserreads it at its own spacing).output_dir (
str|Path) – Where the run’s tiling, extraction record and uncached features go.on_progress (
Callable[[ExtractionProgress],Any] |None) – Called with anExtractionProgresseach time the extraction’s state changes (at most twice a second within a phase), in this process and one call at a time. The last call of a successful extraction hasphase="finished". An exception from it is logged once and ignored. A slow hook slows the extraction down.
- Returns:
A
SetSource(CachedSetSource) or, withdenseorrois, aGridSource(CachedGridSource). An annotation-sampled grid source is keyed by ROI id and carries theRoiSetasrois.
- class soma.extract.RoiSet(entries, *, sampling=None)¶
Bases:
objectThe ROIs annotation sampling drew from a cohort’s whole slides.
An annotation-sampled
soma.extract()returns a grid source keyed by ROI id whoseroisis this set. It names each ROI’s parent sample (children, forsoma.data.Cohort.derived()) and serves what is read per ROI: the label maps of the mask crops sampling stored (label_maps()) and each ROI’s window of its slide (pixels()). Pass it back assoma.extract(..., rois=...)to encode the same ROIs again (another encoder or recipe) without sampling.samplingrecords the extraction the ROIs were sampled (and their mask crops stored) at, assoma.extract.cache.roi_sampling_signaturegives it; a replay at another one is refused. A set built without it is not checked.
The source can be reused across experiments as long as the upstream dataset, preprocessing, and encoder settings do not change; Caching gives the rules.
Follow an extraction¶
soma.extract(..., on_progress=fn) calls fn with the state of the
extraction each time it changes. Use it to show progress where there is no
terminal: a batch job, or a user interface that runs soma. The terminal display
does not change: on_progress comes in addition to it.
from soma.extract import ExtractionProgress
def show(progress: ExtractionProgress) -> None:
if progress.samples_cached is None:
print(f"{progress.encoder}: {progress.phase}")
return
pending = progress.samples_total - progress.samples_cached
line = f"{progress.encoder}: {progress.phase} {progress.samples_done}/{pending}"
if progress.tiles_total is not None:
line += f" ({progress.tiles_done}/{progress.tiles_total} tiles)"
print(line)
features = soma.extract(images, encoder="uni2", cache=cache, output_dir="output", on_progress=show)
Each call gets the whole state, so fn needs to keep nothing. A sample is one
row of the image manifest: a whole slide, or a pre-cropped image with
unit="tile". This is also true for dense grids and for ROIs sampled from
slides.
The phases come in this order. An extraction skips the phases it does not have, and a phase never comes back:
Phase |
When |
|---|---|
|
Always first. |
|
Whole slides only: tiling the slides, or sampling ROIs from them. |
|
Loading the encoder. With several GPUs, until the first GPU starts to encode. |
|
Encoding tiles, images or ROIs. |
|
Slide encoders only: the second pass, from tile features to one feature per slide. |
|
Always the last call of an extraction that succeeds. An extraction that
fails raises and sends no |
When every sample is in the cache and no slide has to be tiled or sampled
again, fn sees checking_cache, then finished. If a slide has to be
tiled or sampled again, tiling comes between them.
samples_cached is None until the cache has been checked, then it does
not change. Over whole slides that need tiling, the slides are tiled before the
cache is checked, so samples_cached stays None during most of
tiling. With rois=, a slide of the manifest that has no ROI in rois
has nothing to encode, so it is counted in samples_cached, even with the
cache off. For a slide encoder, a sample is cached when its slide feature is.
samples_done counts the samples not cached that have completed the current
phase, and starts again from 0 in each phase. A slide whose tile features are
already cached counts as done in embedding from the start. tiles_done and
tiles_total count tiles over every pending sample and every GPU, and an ROI
counts as one tile. They are set only during embedding, and they are
None for pre-cropped images.
- class soma.extract.ExtractionProgress(encoder, phase, samples_total, samples_cached, samples_done, tiles_done, tiles_total)¶
Bases:
objectThe state of one extraction, as
soma.extract’son_progresshook receives it.- encoder¶
The encoder this extraction runs. A composite run extracts once per member, so each member gets its own cycle of snapshots.
- phase¶
What the extraction is doing. Phases only move forward, and
finishedis always the last snapshot of a successful extraction.
- samples_total¶
The rows of the image manifest.
- samples_cached¶
The rows whose features were in the cache at the start.
Noneuntil the cache has been checked.
- samples_done¶
Of the rows not cached, how many have completed the current phase. It starts again from 0 in each phase.
- tiles_done¶
Tiles encoded so far, over every pending row and every GPU. Only set during
embedding, and only where the extraction counts tiles.
- tiles_total¶
Tiles to encode, over every pending row. Set with
tiles_done.
Delivery:
Within a phase,
fnis called at most twice a second. The first call of each phase andfinishedare never held back. Nothing is sent when nothing changed.fnis called in your process, never in a GPU worker, and one call at a time. It may be called from another thread.The extraction waits for
fnto return, so a slowfnslows the extraction down.If
fnraises anException, the extraction goes on. soma logs the first error as a warning with its traceback and keeps callingfn.
Pipeline(config, on_extraction_progress=fn) passes fn to every
soma.extract call the run makes. A composite encoder extracts once per
member, so fn sees one cycle for each member, and encoder tells them
apart. Like callback_factory, fn is not part of the config, the plan or
the experiment identity. The run extracts in your process, also with
devices, so fn does not have to pickle.
Evaluation settings and attention heatmaps¶
Both live in the evaluation section. See Evaluation for metric
contracts and Run outputs for the saved attention scores and overlays:
from soma.config import EvaluationConfig
evaluation = EvaluationConfig(
metrics=["auroc", "balanced_accuracy", "f1"],
subgroups=["center", "grade"],
attention_heatmaps={"cmap": "coolwarm", "alpha": 0.5},
)
result = Pipeline(replace(abmil, evaluation=evaluation), source=features).run()
Watch a run while it trains¶
Pipeline(config, source=..., callback_factory=...) attaches runtime observers
to each fold it trains. run() calls callback_factory(context) once per
fold, before it seeds the fold, and appends the Trainer callbacks it returns after
the config’s callbacks. context is a FoldContext.
Like source, the factory is not part of the config, the plan or the
experiment identity:
class TuneLoss:
def __init__(self, context):
self.fold = context.fold
def on_epoch_end(self, trainer, learner):
if trainer.summary is not None: # None on an epoch without a tune evaluation
print(self.fold, trainer.epoch, trainer.summary["tune/loss"])
result = Pipeline(abmil, source=features, callback_factory=lambda context: [TuneLoss(context)]).run()
An observer only reads: it must not stop the run, change the learner or the
optimizer, or draw from the global random state. An exception from the factory or
from an observer fails the run, and run.yaml records it. Watching a managed run
gives the fields an observer may read, the seed convention, the resume behaviour
and the failure policy.
- class soma.pipeline.FoldContext(run_id, run_dir, fold_dir, fold, num_folds, seed)¶
Bases:
objectThe fold a
Pipelineis about to train, as itscallback_factorygets it.seedis the run’s base seed (run.seed): the fold trains undersoma.seed_everything(seed, fold=fold), so its effective seed isseed + fold. A single-fold run’sfold_diris itsrun_dir.
Train the folds side by side¶
Pipeline(config, devices=[...]) trains the folds of a run with several folds
side by side, one new process per fold, on the devices you list. The run extracts
the features first, in your process, and writes the summary when every fold is
done. Each fold writes its output to fold_<k>/worker.log. Without devices,
the folds train one after another, in your process:
class TuneLoss: # at module level: a fold's process imports it by name
...
def tune_loss(context):
return [TuneLoss(context)]
if __name__ == "__main__":
result = Pipeline(config, callback_factory=tune_loss, devices=["cuda:0", "cuda:1"]).run()
Each process receives the config, source and callback_factory pickled, so
they must pickle: a lambda or a nested function does not. Each process also imports
your script again, so put the call under if __name__ == "__main__":. The folds
train in other processes, so result.fold_results is empty; read the folds from
the run directory. See Train the folds side by side for resume, failures and the run
layout.
Dense features over given images¶
Dense extraction is an extraction setting, not a manifest kind: dense asks
for token grids and unit="tile" says each row is a pre-cropped image. The
grid recipe is slide2vec’s DenseOptions (read spacing, supervision size,
padding, window, feature kind); batch size and precision are slide2vec’s
ExecutionOptions:
from slide2vec import DenseOptions, ExecutionOptions
import soma
from soma import ImageManifest
from soma.config import CacheOptions
grids = soma.extract(
ImageManifest.from_csv("segmentation.csv"),
encoder="phikon",
unit="tile",
dense=DenseOptions(spacing_um=0.5, target_size=224),
execution=ExecutionOptions(batch_size=64),
cache=CacheOptions(enabled=True, root_dir="shared/cache"),
output_dir="output/dense",
)
grid = grids.load("roi_001") # float32: (feature_dim, grid_h, grid_w)
geometry = grids.geometry("roi_001")
Annotation-sampled whole slides¶
A table of whole-slide image and annotation paths becomes an annotation-sampled
grid extraction when the extraction carries an annotation vocabulary (hs2p’s
MaskSamplingConfig) and a grid runs over whole slides. The grids are keyed
by ROI id; their rois name each ROI’s slide, from which the slide cohort
derives the ROI cohort (each ROI inherits its slide’s splits):
from hs2p import MaskSamplingConfig, SegmentationConfig, TilingConfig
from slide2vec import DenseOptions, PreprocessingConfig
import soma
from soma import AnnotationManifest, Cohort, ImageManifest
from soma.config import CacheOptions
grids = soma.extract(
ImageManifest.from_csv("slides.csv"),
annotations=AnnotationManifest.from_csv("slides.csv"),
encoder="phikon",
dense=DenseOptions(spacing_um=0.5, target_size=512),
extraction=PreprocessingConfig(
tiling=TilingConfig(
requested_spacing_um=0.5, requested_tile_size_px=512, tolerance=0.05, overlap=0.0
),
segmentation=SegmentationConfig(method="hsv"),
masks=MaskSamplingConfig(
pixel_mapping={"background": 0, "tumor": 1},
min_coverage={"tumor": 0.1},
strategy="joint",
output_mode="merged",
),
),
cache=CacheOptions(enabled=True, root_dir="shared/cache"),
output_dir="output/annotation-rois",
)
rois = Cohort.from_csv("slides.csv", "splits.csv").derived(grids.rois.children)
label_maps = grids.rois.label_maps(size=(512, 512)) # the stored mask crops
Slides with no sampled ROI have no child, so they leave the ROI cohort;
output/annotation-rois/extraction_provenance.json lists them.
Score and compare saved predictions¶
Each test split’s predictions_<split>.parquet can be scored again, with
other metrics or subgroups, and compared across runs. Given two single-fold
runs over the same cohort:
from soma import evaluate
from soma.evaluation import Predictions, compare
targets = cohort.targets("test")
abmil = Predictions.from_parquet(abmil_result.run_dir / "predictions_test.parquet")
clam = Predictions.from_parquet(clam_result.run_dir / "predictions_test.parquet")
evaluation = evaluate(abmil, targets, metrics=["auroc", "f1"], subgroups=["center"])
p_values = compare([abmil, clam], targets, "auroc")
compare gives the best set 1.0 and every other set the p-value of a
paired permutation test against it. See Evaluation for the scoring
rules and Benchmarking for leaderboards across many runs.
soma.components() names the component kinds (aggregators, heads,
decoders, encoders, optimizers, …); soma.components("aggregators") lists
one kind’s registered components, each with its params and their defaults.
See A custom component through the registry for adding your own.
Segmentation and detection building blocks¶
The verbs soma.learn.loaders, soma.fit, soma.predict and
soma.evaluate also cover feature grids. The grid shape walks through a
complete run; these are the parts:
Object |
Role |
|---|---|
|
Cached feature grids, one |
Pixels of pre-cropped tiles for the live path;
|
|
|
Segmentation targets: label masks, or the ROI mask crops stored by annotation sampling |
|
Detection targets; |
|
A parameter-free frozen encoder stage that re-encodes pixels at every step |
|
|
|
The grid learner and its batch (cached |
Joint image and label-mask or point augmentation for the live path |
|
|
What |
Picks a detection score threshold on tune predictions |
|
|
|
|
A weight-free encoder stage for tests |
Every target source has subset(sample_ids) to restrict it to one split.
Two tools apply a run’s bundles to images larger than one tile:
soma.predict_slides()(soma predict) predicts over whole slides, for segmentation or detection. It streams each slide tile by tile and writes one file per slide and bundle (for its memory use, see Cost). Use it for slides, and to score them withsoma evaluate. See Whole-slide inference.SlidingWindowSegmentationPredictor.from_bundles(bundles)(soma.evaluation.sliding_window) predicts segmentation over one image held in memory, and returns its label map. It slides the fold ensemble over the image and blends the softmaxes of overlapping tiles. Use it for a bounded image, such as an ROI or a region read from a slide, in a notebook. Load each fold’s bundle withsoma.load()and pass the list. Likesoma.predict_slides(), it reads the image with the read spacing, read tolerance and slide reader the bundles record, so it reads the image as training did. Passspacing_um=,tolerance=orbackend=to read it another way.
Both build each bundle’s frozen encoder stage with
soma.pipeline.build.bundle_encoder_stage(). A bundle trained live carries
its stage. A bundle trained on cached grids records the encoder that extracted
them, and the helper builds that stage. from_bundles takes encoder= to
use another stage with the same frame.
- soma.pipeline.build.bundle_encoder_stage(bundle, *, run_dir=None)¶
The frozen encoder stage that turns pixels into the grids
bundlewas trained on.bundleis a loaded grid bundle (soma.load()). A bundle trained live carries its stage, built when it loaded. A bundle trained on cached grids records the recipe of the encoder that extracted them (thesoma.extract.live_encoder()arguments), and the stage is built from it here, not at load time. Bundles with the same recipe share one stage while it is in use.A cached grid bundle written before soma recorded the recipe takes it from the
plan.yamlof the run that trained it:run_dir, or else the run directory the bundle was loaded from (<run>/bundleor<run>/fold_<k>/bundle).Refused: a set-shape bundle; a bundle trained on a composite of several encoders, which has no single stage; a bundle whose run was given its grids and named no encoder; and a recipe whose frame differs from the one the bundle was trained on.
Task-free representation evaluation¶
Evaluate frozen tile embeddings with the fixed CRoMa v1 protocol by leaving out
the learner and setting evaluation.representation. Save this as a YAML
config and run it with soma run config.yaml:
cohort:
records: dataset.csv
splits: splits.csv
features:
encoder:
name: phikon
evaluation:
representation:
confounder_column: medical_center
split: test
evaluation_design: all
m: 5
alpha: 0.10
Selected dataset rows require non-empty label, group_id (a metadata column
naming the non-independence group), and medical_center columns. The selected split must occur in exactly one fold;
cross-validation is unsupported. The cohort must provide enough same- and
other-confounder neighbours for m=5; CRoMa raises if any selected sample
lacks them.
Representation runs return metrics in result.summary with an empty
fold_results list. They fit no task head, so they write no predictions and no
bundle. Provenance
records the installed CRoMa version and encoder configuration, including output
variant. It does not include checkpoint hashes or an upstream fingerprint, so
these records alone cannot establish byte-identical weights or preprocessing.
See CRoMa for the registered cohorts and metrics.
Reproduce a packaged benchmark programmatically¶
Every registered benchmark is a Python object, so the
soma reproduce flow is available from code, with results directly
comparable to the CLI’s. The benchmarks live in the soma.benchmark
package, which import soma does not import: importing it (here through
from soma.benchmark import get_benchmark) registers them, after which
soma.components("benchmarks") lists them:
import statistics
import soma
from soma.benchmark import get_benchmark
from soma.pipeline import Pipeline
[entry["name"] for entry in soma.components("benchmarks")] # [..., "eva/bach", "hest/IDC", "ocelot"]
benchmark = get_benchmark("eva/bach")
manifest = benchmark.curate("/path/to/eva/bach", "runs/eva-bach/curated")
measured = []
for seed in benchmark.canonical_seeds:
seed_root = f"runs/eva-bach/seed_{seed}"
config = benchmark.build_config(
encoder="uni2", # the axis a benchmark varies
dataset_csv=manifest.dataset_csv,
splits_csv=manifest.splits_csv,
output_root=seed_root,
seed=seed,
# share one feature cache across seeds (extraction is seed-independent)
overrides={"cache": {"enabled": True, "root_dir": "runs/eva-bach/cache"}},
)
result = Pipeline(config).run()
metrics = benchmark.score(result.run_dir)
measured.append(metrics[benchmark.primary_metric])
print(statistics.fmean(measured))
benchmark.expected(encoder="uni2") returns the packaged reference rows to
compare against, and benchmark.score(run_dir) alone re-scores an existing run
without retraining (the --from-run-dir fast path).
The one-call equivalent is soma.benchmark.run_benchmark, the importable
orchestration behind soma reproduce itself: the canonical-seed loop, the
reference-row tolerance status, provenance stamping (git commit, slide2vec/croma
versions), and the results-ledger append used by the CLI. Its keywords
mirror the CLI flags, plus results_root so an external repository can append
MeasuredRow rows to its own committed ledger instead of the packaged one
(soma/benchmark/<protocol>/results.csv):
from soma.benchmark import run_benchmark
run_benchmark(
"eva/bach",
encoder="uni2",
raw_root="/path/to/eva/bach",
output_root="runs/eva-bach",
record=True,
# host the results ledger outside the soma checkout:
# appends to <results_root>/eva.csv with full provenance
results_root="/path/to/leaderboard-repo/results",
)
Run an external benchmark specification¶
A project outside soma can own its benchmark protocol as a typed
soma.benchmark.BenchmarkSpec — a config builder, the canonical seed set,
and a scorer — and hand it to soma.benchmark.run_benchmark_spec for
execution. soma runs every canonical seed with one shared feature cache and
returns the aggregated BenchmarkRunResult together with the per-seed
evidence roots, without touching the registry, reference tables, or ledger.
The result also carries the dataset, splits and test checksums that every seed
ran against.
By default each seed runs as Pipeline(config).run(). Some protocols cannot
run through a Pipeline: HEST fits a closed-form probe that only
HestBenchmark.run executes. For those, set the spec’s optional run
field. soma then calls run(config) for each seed in place of the
Pipeline. The runner must return an object with dataset_checksum,
splits_checksum and test_checksum, as a PipelineResult does. To
wrap a registered recipe, pass its runner along; getattr gives None
for a recipe that a Pipeline runs:
from soma.benchmark import BenchmarkSpec, get_benchmark, run_benchmark_spec
recipe = get_benchmark("hest/IDC")
spec = BenchmarkSpec(
name="my-leaderboard/hest-IDC",
canonical_seeds=recipe.canonical_seeds,
primary_metric=recipe.primary_metric,
build_config=recipe.build_config,
score=recipe.score,
run=getattr(recipe, "run", None),
)
result = run_benchmark_spec(
spec,
dataset_csv="hest/IDC/curated/dataset.csv",
splits_csv="hest/IDC/curated/splits.csv",
encoder="uni2",
output_root="runs/hest-IDC",
)
Both run_benchmark and run_benchmark_spec take devices, for example
devices=["cuda:0", "cuda:1"], to run the seeds side by side, one process per
device. When a seed trains through a Pipeline on splits with more than one fold,
they spread each seed’s folds instead, and the seeds run one after another. See
Run the seeds in parallel for what this costs and what it asks of your script.
Runnable demonstrations live in examples/
(examples/README.md):
examples/external_benchmark_spec.py— build and execute aBenchmarkSpec;examples/fixed_step_training.py— fixed optimizer-step training budgets (TrainerConfig(max_steps=N));examples/portable_identity.py— manifest identity is portable across storage roots.