Run outputs¶
Each pipeline run writes a run directory beneath run.output_dir.
It holds the configuration as given and as resolved, per-fold
artifacts, and the metrics needed to compare experiments reproducibly.
The shared cache, which stores reusable upstream artifacts such as tiling and feature extraction, is documented separately in Caching.
Experiment identity¶
Managed outputs group runs by experiment identity, with a timestamp/W&B suffix
for each run. A run started in the same second as an earlier run of the same
experiment gets -2, -3, … appended instead of reusing its directory.
Identity version 9 hashes the train and tune manifest
slices and the run’s plan (see The plan): the features section as
extraction resolves it, the cohort options, the loaders’ batch size, sampler and
augmentation, the learner with every leaf’s params, the trainer and the
evaluation. With cohort.train_subset, it also hashes the sorted ids the
file lists, so each subset is its own experiment (see Training on a subset).
Representation-only runs instead hash their configured evaluation split and
representation settings.
The run section (output directory, seed, run id, resume, mirror root, fold
selection), the cohort file paths (the train subset’s too), the loader worker settings,
trainer.device, the train pass (trainer.eval_train), the grid-output save
toggles and evaluation.overwrite_test do not change experiment identity.
Enabled attention-heatmap settings do, because they change generated artifacts.
Adding or changing test* rows leaves the training experiment identity
unchanged. A separate test digest identifies the test assignments and their
sample rows; test_results.json records test identities and guards against
accidental re-scoring. See Evaluation for test holdout and overwrite
controls.
Dataset checksums follow semantic manifest identity: storage paths are excluded while semantic values in the selected rows are hashed. Run metadata still records the resolved manifest paths and whole-file SHA-256 values, so relocation or added test rows remain visible in provenance. Cache identity separately includes physical inputs as described in Caching.
Run directory layout¶
The run directory holds config.yaml (the config as given), plan.yaml
(the config as resolved, see The plan) and summary.json.
When splits.csv has no fold column (or a single fold value), the
per-fold artifacts are written directly inside it; with several folds, each
fold_N/ subdirectory holds its own set:
bundle/, the trained model (see Model bundle),metrics.jsonandtraining_history.json(see Logged values)feature_adapter.jsonwhennormalizationorprojectionis active: the methods,epsfloor and floored-channel count, dimensions, projection seed, PCA explained variance, and the number of samples and feature rows used to fit each stagepredictions_<split>.parquetandnot_predicted_<split>.parquetfor each test split of a slide, patient or tile runsubgroup_metrics_<split>.jsonfor tune and for each test split whenevaluation.subgroupsis set (see Subgroup metrics)attention/<split>/<sample_id>.npzandheatmaps/<sample_id>.pngwhenevaluation.attention_heatmapsis setfor segmentation and detection, the predictions of tune and every test split and the optional overlays, probabilities and heatmaps; see Segmentation and detection outputs
worker.logwhen the fold trained in a process of its own (see Train the folds side by side)
The plan¶
soma.resolve() turns a config into a soma.Plan before anything
runs: the config with every default of every component’s params spelled out,
plus what the cohort decides (for example a classification head’s label map or
a survival head’s bin count). A value the config states wins over what the
cohort suggests; a contradiction (an explicit class count the cohort does not
match) is refused. Feature dimensions are not in the plan: they come from the
features at build time and are recorded in the bundle’s model.json.
plan.yaml is the plan as YAML. It loads as a config, so soma run
plan.yaml replays the run with every value pinned. A component named by a
dotted import path keeps that path in the plan. Versions and code are not part
of the plan: the run records the code each component resolved to (see
Component code).
A resume into an existing run directory (run.resume or run.run_id)
compares the current plan with the saved plan.yaml and refuses on any
difference, except where and how the launch runs: run.output_dir,
run.run_id, run.resume, run.mirror_root and run.folds. A changed
run.seed is drift. GPU and preprocessing worker counts the config leaves unset
stay unset in the plan, so a run resumes on another machine. The cohort files’
content is then checked against the run’s experiment identity, and the code of
the external components against the run’s component record.
Component code¶
The experiment identity holds each component’s name and params, not its code.
The run records the code instead: the components field of run.yaml and
the components list of each bundle’s provenance.json hold one entry for
each component of the plan. These are the encoder, the sampler, the
augmentation, each trainer callback, the learner and its aggregator or decoder,
head, optimizer and schedulers, and each metric in evaluation.metrics. An
entry holds:
kind, andnameas the plan spells itobject: themodule.qualnameof the class or function the name resolved todistributionandversionwhen the object’s file belongs to an installed distribution (itsRECORDlists the file), andeditable: truewhen that install is editable (the file is in its project directory)source_sha256: the SHA-256 of the file that defines the object, ornullwhen there is no file (for example a notebook cell)git: theshaanddirtystate of the git work tree that holds the file, when there is onefingerprint: theversionof a non-editable install, otherwisesource_sha256
A component is external when its object does not come from soma, slide2vec, hs2p or torch. The run already records the versions of these four. Two checks compare the fingerprints of the external components:
Resume. A resume into a run whose
run.yamlhas a component record is refused when the fingerprint of an external component changed. The error names each component with its old and new fingerprint. No setting overrides this: start a fresh run.Leaderboard.
soma leaderboardkeeps the latest run of each seed of an experiment. If these runs disagree on the fingerprint of an external component, it stops with an error that names the experiment and the components. Rerun the stale seeds on the current code: the newer run of a seed replaces the older one.
Both checks also compare the object: a name that now resolves to another
class or function is a change, even when the fingerprint is the same (two
classes of one unchanged file have the same source_sha256). The error then
lists the old object as absent in the new run, and the new one as
absent in the old run.
Runs without a component record are not compared. When an external component has no fingerprint (no source file and no installed version), the run warns at start that neither check can detect edits to it.
The checks cover runs. The feature cache has a check of its own. A custom encoder is an external component, so the record and both checks see an edit to it. Its feature cache records the same fingerprint, and refuses to reuse features that other code extracted (see Feature identity). The cache does not see the encoder’s weights, or code that the encoder class inherits or imports from other files. After you change these, delete the encoder’s feature cache directory (see Caching).
Model bundle¶
Each fold saves its selected model as a bundle with soma.save(). A bundle
is a directory of four files:
weights.safetensors: the model’s fullstate_dict. The fitted feature adaptor (normalization/projection) is stored here as buffers.model.json: how to rebuild the model before the weights load: its shape, the builder and the builder’s arguments (aggregator or decoder, task head, adaptor sections, and the encoder of a live run).preprocessing.json: what scoring needs beyond the model: the task family, class names, target schema, metrics, and for grid runs the grid geometry, read spacing, tile size andencoder, the recipe of the encoder the grids came from (thesoma.extract.live_encoder()arguments). A detection bundle also records the score threshold chosen on tune, the matching distance and the class scheme (class_scheme, see Classes).provenance.json: the soma, slide2vec and hs2p versions, the component record (see Component code), the selected epoch and its monitor (selection_monitor: thetune/name and its value), the fold (fold,num_folds), the run id and the identity of the feature source (the cache key and feature identity, not a path).fold_assignmentsis the SHA-256 of the split of each sample in the fold, as the splits table assigns them (soma.data.FoldSplit.assignments_digest()).soma predictwithcohort.fold: bundlechecks it (see Each fold’s own slides).
soma.load() rebuilds the model in eval mode and returns a
soma.ModelBundle with model, preprocessing, provenance and
the path it was loaded from. A live run’s frozen encoder is built when the
bundle loads, so missing encoder weights fail at load time. A bundle written by
another soma major version is refused; another minor or patch version loads with
a warning:
import soma
bundle = soma.load("runs/.../fold_0/bundle")
predictions = soma.predict(bundle.model, loader)
A grid bundle names its encoder, so the bundle alone can predict from pixels.
soma.pipeline.build.bundle_encoder_stage(bundle) returns the frozen encoder
stage: the one a live bundle carries, or, for a bundle trained on cached grids,
one built from the recorded recipe. Loading a cached bundle builds no encoder;
the helper does, once for all bundles with the same recipe. The helper refuses a
bundle trained on a composite of several encoders, which has no single encoder
stage. A cached bundle written by an older soma records no recipe: load it from
its run directory, or pass that directory as run_dir=, and the run’s
plan.yaml supplies the recipe.
soma.save writes the bundle atomically: a reader sees the previous bundle
or the new one, never a partial one. A model built by hand in a notebook can be
saved too; soma.load rebuilds it only when soma.learn.record_builder
recorded the function that builds it, and otherwise refuses: load its
weights.safetensors into the same model instead.
Resume is per fold. A fold is complete when its metrics.json and its
bundle/ exist. A relaunch into the same run directory (run.resume or
run.run_id) skips complete folds and trains the others from epoch 0.
Split-specific artifacts¶
When a dataset defines multiple test splits, each split gets its own set of
artifacts, e.g. predictions_test.parquet and
predictions_test_external.parquet.
Prediction files¶
predictions_<split>.parquet holds one row per sample of the split that the
model predicted: a sample_id column, the columns the task head declares (prob_0 …
prob_<k-1> and predicted_label for classification, predicted_label
and raw_score for ordinal classification, predicted_value for
regression (value_0 … value_<G-1> with num_outputs: G),
risk_score for survival), and any column a custom learner adds. A sample
the model could not predict (no features) has no row: it is listed in
not_predicted_<split>.parquet instead, with sample_id and reason.
That file is written even when it has no row (see Samples without features).
Targets are not stored here; they come from dataset.csv. The parquet schema
metadata records the task family, the soma version, the role of each column and
the class label of each probability column. Read the file with
soma.evaluation.Predictions.from_parquet() and score it again with
soma evaluate (see CLI).
Metric keys in summary.json are prefixed by split name:
Single fold:
test/auroc,test_external/aurocCross-validation:
test/auroc_mean,test/auroc_std
Each split also has num_samples, num_predicted and coverage
(test/coverage, or test/coverage_mean over folds). A coverage below 1
means the metrics leave out samples the model could not predict (see
Samples without features).
The run-summary panel prints the coverage of each split with its counts, for
example 50.0% (2/4). Over folds, the counts are means per fold:
97.0% (10/10.33 per fold). soma leaderboard adds a coverage column
when a row’s runs left samples out. The column shows the mean coverage of the
row’s runs, on the rows below 1 only. Its JSON output has a coverage value
on every row (null when the runs record none).
*_std is the sample standard deviation (ddof=1) across folds. Threshold-free
metrics (AUROC, AUPRC, C-index, …) are nan on a fold whose split holds a single
class or no comparable pairs; such folds are excluded from *_mean / *_std and
counted in test/<metric>_nan_folds, which is only written when the count is non-zero.
With evaluation.subgroups, the summary also holds the subgroup metrics of
each split from its subgroup_metrics_<split>.json (see
Subgroup metrics): test/center=A/auroc for one group and
test/mean_over_center/auroc for the mean over the column’s groups, with the
same _mean, _std and _nan_folds over several folds. A fold whose
split has fewer than two samples of a group has no value for it; that fold counts
in the group’s _nan_folds, as a NaN value does.
The summary covers the test splits. With evaluation.holdout_test: true,
which scores no test split, it covers tune instead: tune/auroc,
tune/center=A/auroc. The run-summary panel shows the summary’s first pooled
metric, and soma leaderboard ranks on it unless a benchmark names its own
metric; neither picks a subgroup key.
Segmentation and detection outputs¶
Segmentation and detection runs write predictions for tune and for every test split:
Segmentation:
predictions_<split>/, one PNG label map of class indices per sample and anindex.parquet. Read it withsoma.evaluation.LabelMapPredictions.load().Detection:
predictions_<split>.parquet, the level-0 point listsample_id, x, y, class, scorewith every peak above the head’smin_score, before any threshold. Read it withsoma.evaluation.PointPredictions.from_parquet().
soma evaluate scores either again (see Segmentation and detection predictions). Optional
artifacts follow evaluation settings:
Setting |
Writes |
Default |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Per-sample confusion matrices are not written; recompute them from the saved
label maps with soma.evaluation.confusion_records().
Whole-slide prediction outputs¶
soma predict (see Whole-slide inference) writes a prediction
directory, not a run directory:
<output_dir>/
├── plan.yaml the resolved config; soma predict replays it
├── provenance.json the soma, hs2p, slide2vec and torch versions, and
│ each bundle's name, path and SHA-256 (with
│ cohort.fold: bundle, also its fold and
│ fold_assignments)
├── index.parquet one row per slide and bundle
├── fold_0/ one directory per bundle, or ensemble/
│ ├── <sample_id>.tif segmentation: the label TIFF
│ ├── <sample_id>.parquet detection: the points
│ └── <sample_id>.json the slide's record
├── fold_1/
└── logs/ with predict.devices: worker_<k>.log per process
Each bundle’s directory is named by the end of its path
(runs/beetle/fold_0/bundle writes to fold_0/). With
predict.ensemble: true there is one directory, ensemble/. With
cohort.fold: bundle, each bundle’s directory holds the slides of its own
fold only.
index.parquet has one row per slide and bundle that predicts it, with the
columns:
bundle: the directory of the file;sample_id;path: the file, relative to the output directory;width,heightandspacing_um: the file’s frame. That is the map’s pixels for a label TIFF, and the slide’s level 0 for points;read_spacing_um: the requested read spacing the bundles set (the map’s own spacing isspacing_um);num_tiles: the kept tiles;not_predicted_fraction(segmentation): the share of the map’s pixels that no kept tile contributed. Withpredict.restrict_to_mask: true, the share of the pixels inside the mask, and 0.0 for a slide with none (see Restrict a label map to the mask);num_points(detection): the points in the file.
Each <sample_id>.json record holds the same values, the file’s name and
the batch_size the slide was predicted with (a relaunch may change it, see
The plan). A label map’s record also holds restrict_to_mask.
A slide is done when its record parses and its file exists: a relaunch predicts
only the other slides. The index is rebuilt from the records at the end of each
launch.
Run index¶
<run.output_dir>/indexes/runs.csv is append-only: every status change of a
run appends one line, and readers keep the last line per run_id. Run
soma compact-index <output_dir> to rewrite it with one row per run.
Heatmap artifacts¶
When evaluation.attention_heatmaps is set, the pipeline scores each fold’s bundle
once every fold is done and stores raw attention scores in
attention/<split>/<sample_id>.npz and rendered overlays in heatmaps/
(directly in the run directory for single-fold runs, inside each fold_N/
subdir for cross-validation). The rendered overlays can be regenerated with
different visual settings without rerunning inference.
Aggregators that support attention extraction: abmil, clam_sb,
clam_mb, dsmil. Heatmaps are skipped for mean_pool, max_pool,
transmil, dtfdmil, and hipt.
Heatmap appearance is set by the keys of evaluation.attention_heatmaps
({} keeps the defaults): cmap (colormap name, default coolwarm),
alpha (overlay opacity, default 0.5), blur_sigma (Gaussian blur radius
in pixels, default 0).
Train the folds side by side¶
On one machine with several GPUs, pass --devices to train the folds of a run
side by side, one fold per GPU:
soma run config.yaml --devices 0,1,2,3
In Python, pass devices to the pipeline:
soma.Pipeline(config, devices=["cuda:0", "cuda:1"]).run()
The run first extracts the features in its own process and fills the feature
cache. Then each fold trains in a new process on a free device, and reads the
features from the cache. The output of a fold goes to fold_<k>/worker.log,
not to your terminal. When every fold is done, the run writes summary.json.
Folds seed independently, so the result is the one you get when the folds train
one after another.
An entry is
cuda:<n>orn(the n-th GPU this process sees) orcpu. An entry may repeat, so0,0trains two folds at a time on GPU 0. A device takes the next fold when its fold is done, and devices without a fold stay idle.devicespicks the GPU of each fold, and a fold’s process sees only that GPU, ascuda:0. Settrainer.devicetoautoorcuda. A run that setstrainer.deviceto another GPU, such ascuda:1, is refused before any extraction starts.devicesis not part of the config or the plan:config.yamlandplan.yamldo not record it.The feature cache must be on (
features.cache.enabled), unless you pass the features assource. The config,sourceandcallback_factorymust pickle: define your callbacks and components as module-level functions or classes. ATypeErrorsays so before any extraction starts.With
run.folds, only the listed folds train side by side. A resume trains only the folds that are not complete.If a fold fails, no new fold starts. The folds that are running finish, and the first error is raised, with the path of the failed fold’s
worker.log. The run writes no summary, and the folds that completed stay on disk, so a rerun trains only the folds that are left.A run with one fold, or a representation run, ignores
deviceswith a warning and runs in your process. UseCUDA_VISIBLE_DEVICESto choose its GPU.
To spread the folds over several machines, start one launch per machine. Pin
every launch to the same run.run_id and give each its share with
run.folds (for example run.folds: [2]). A launch trains only its listed
folds and leaves the other pending folds alone. While folds remain pending, the
run is recorded as partial and no summary.json is written. The launch
that finds every fold complete writes the summary, so finish with one launch
without run.folds if no fold launch ended last. Two launches given the same
fold would both train it: the selection is not a lock.
Log output¶
soma reports progress through Python’s logging module, under the soma
logger. The soma command prints soma’s INFO messages to stderr; other
libraries print warnings and errors only.
In a Python script, soma checks the logging setup when you create a
Pipeline or call soma.extract:
If you have not configured logging (no handler on the root logger or on the
somalogger), soma adds one stderr handler to thesomalogger and sets that logger to INFO. You see messages such as the fold summary without any setup. soma adds this handler only once. A level you set yourself is kept: on thesomalogger, or on the root logger when it is not Python’s default WARNING (logging.getLogger().setLevel(logging.ERROR)keeps soma quiet).If you have configured logging, for example with
logging.basicConfig, soma changes nothing and your configuration decides what is shown.If you configure logging after you create a
Pipeline, soma’s handler stops writing as soon as the root logger or thesomalogger has a handler of yours, so each message prints once, through your handlers. Thesomalogger stays at INFO. If you setpropagate = Falseon thesomalogger, its messages never reach your root handlers, so soma’s handler keeps printing them unless you add a handler to thesomalogger.
To change the output:
import logging
soma_logger = logging.getLogger("soma")
soma_logger.setLevel(logging.WARNING) # hide soma's INFO messages
soma_logger.setLevel(logging.DEBUG) # or show soma's DEBUG messages too
soma_logger.handlers.clear() # remove soma's default handler
soma_logger.propagate = False # keep soma out of your root handlers