Whole-slide inference¶
A segmentation or detection run trains and scores on the ROIs or tiles it samples. Whole-slide inference applies the trained model to every tissue tile of a slide. Two commands do the work:
soma predict CONFIGpredicts. It writes one file per slide and bundle: a label TIFF for a segmentation bundle, a points parquet for a detection bundle.soma evaluate PREDICTIONS --cohort dataset.csvscores those files against the slides’ annotations.
Use it to:
score a model on a test set of whole slides, over every annotated pixel or point instead of the ROIs a run samples;
predict slides that have no annotations. Prediction needs only the slides; only scoring needs annotations.
The model comes from a bundle (see Model bundle). A bundle holds all that prediction needs: the decoder and head, the class scheme, the tile size, the read spacing and the recipe of the frozen encoder. Prediction reads the pixels and runs the encoder again. It reads no feature cache.
A bundle trained on cached features before soma 2.4.0 records no encoder
recipe. Keep it in the run directory that trained it (<run>/bundle or
<run>/fold_<k>/bundle): soma predict reads the recipe from that run’s
plan.yaml, and refuses a copy of the bundle on its own before it predicts
any slide.
Predict¶
Write a config with three sections:
predict:
output_dir: predictions/beetle-test
bundles: runs/beetle # a run directory: the bundle of each fold
ensemble: false
stitch: pick_one # or average (segmentation only)
restrict_to_mask: false # true: 0 outside the mask (segmentation only)
batch_size: 8
num_workers: 8
devices: null # or [0, 1]: one process per GPU
split: slides # or tiles: share each slide's tiles across the devices
cohort:
records: dataset.csv
splits: splits.csv
subset: test
fold: 0
extraction:
tiling:
overlap: 0.0
segmentation:
method: hsv
masks:
min_coverage:
tissue: 0.01
Then run it:
soma predict predict.yaml
The same in Python. soma.predict_slides() takes one keyword per config
key, and leaves the others at their defaults:
import soma
index = soma.predict_slides(
output_dir="predictions/beetle-test",
bundles="runs/beetle",
records="dataset.csv",
splits="splits.csv",
subset="test",
num_workers=8,
extraction={"tiling": {"overlap": 0.0}},
)
It returns the index of the files it wrote (see Whole-slide prediction outputs). Relative paths resolve against the working directory. The keys:
Key |
Meaning |
|---|---|
|
Where the plan, the predictions and their index go. Required. |
|
The trained bundles: one bundle directory, a list of them, or one run
directory. A run directory stands for its bundles: |
|
|
|
How a label map combines overlapping tiles: |
|
|
|
Tiles per forward pass (default 8). A relaunch may change it (see The plan). |
|
Worker processes that read tiles while the model runs (default 0: the process that runs the model reads them). With several devices, each device process has its own. |
|
|
|
What is shared across |
|
The slides: a CSV with |
|
A splits CSV. Without it, every row of |
|
The split to predict (default |
|
The fold of that split (default 0), or |
|
How the slides are tiled and read: the |
|
Taken from the bundles. Leave them out: another value is refused. |
|
How far a pyramid level’s spacing may be from the read spacing (default: the bundles’ own). |
|
The share of a tile’s side that neighbouring tiles overlap, in
|
|
Always |
|
The hs2p reader of the slides (default: the one the bundles were trained with). See How a slide is tiled. |
|
The hs2p reader of the tissue masks (default |
|
The tissue segmentation of slides without a |
|
The share of a tile that tissue must cover to keep the tile (default
|
|
The values of the |
The plan¶
soma predict first resolves the config into a plan, and writes it to
<output_dir>/plan.yaml before it predicts any slide. In the plan:
every path is absolute;
a run directory is replaced by the list of its bundles;
the extraction is spelled in full, with the tile size, the read spacing, the read tolerance and the slide reader taken from the bundles.
The plan is a config too: soma predict <output_dir>/plan.yaml replays it.
A slide is done when its record, <sample_id>.json, exists, parses and names
a file that exists. A launch predicts only the slides that are not done, so a
stopped prediction resumes when you launch it again.
A launch into an existing output directory is refused when:
the directory’s
plan.yamldiffers from the new plan. The error names the keys that differ.predict.devices,predict.num_workersandpredict.splitmay change, because they decide where the work runs, not what it computes.predict.batch_sizemay change too (see below).a bundle changed since the directory was written.
provenance.jsonrecords the SHA-256 of each bundle’s files and, withcohort.fold: bundle, the fold and thefold_assignmentsthat each bundle records.
A relaunch with another predict.batch_size predicts the slides that are not
done with the new value. For example, after an out-of-memory error, resume with
a smaller batch. The slides already done are not predicted again, so they keep
the batch size they were predicted with. The launch logs one line with the old
and the new value.
The batch size can change a map slightly. In fp16, a tile’s output depends a
little on the other tiles of its batch, so two batch sizes can give maps that
differ in a few pixels. Each slide is predicted from start to finish in one
launch, so with one batch size. Its record, <sample_id>.json, holds that
batch_size: to reproduce a map, use the value in its record.
plan.yaml holds the value of the latest launch.
How a slide is tiled¶
hs2p lays one fixed grid over the whole slide, from its top-left corner. A tile starts at every multiple of the grid’s step that falls inside the slide. The grid does not follow the tissue, so neighbouring tiles always line up.
A tile is kept when tissue covers at least extraction.masks.min_coverage of
it. The tissue is the slide’s mask_path raster when the records give one,
and hs2p’s tissue segmentation otherwise. A tile with no tissue is never kept.
The tissue selects tiles, not pixels or points: each kept tile is predicted in
full, also where it holds no tissue. To set a label map to 0 outside the mask,
see Restrict a label map to the mask.
With the default extraction.filter, hs2p first drops each tissue region
whose area is at most four tiles (a_t: 4, see Preprocessing), and
only then measures coverage. The tissue of such a region counts towards no
tile’s coverage. Its pixels are not predicted, unless a tile kept for nearby
tissue contributes them (see How tiles are combined). The annotated
pixels that stay unpredicted count as misses when the slide is scored (see
Score label maps). Set extraction.filter.a_t: 0 to drop only the
regions of zero area. hs2p measures area on the coarse grid it reads the tissue
on, where a single pixel or a line one pixel wide has zero area. With the
default extraction.filter, a pixel_mapping with other classes already
uses a_t: 0.
Each kept tile is read at the bundles’ read spacing: from a pyramid level within the tolerance, or resampled from a finer level. soma never upsamples a slide. A slide whose level 0 is coarser than the read spacing, beyond the tolerance, is refused before any slide is predicted.
The slides are read with the reader the bundles were trained with: the
backend that each bundle’s encoder recipe records. To use another reader,
set extraction.tiling.backend; soma then warns that the pixels may decode
differently than in training. Bundles that record different readers are refused
unless extraction.tiling.backend names one. When no bundle records a
reader, the slides are read with auto.
A slide with no kept tile gets a warning, and an all-zero label map or a points file with no rows.
How tiles are combined¶
With overlap: 0, the tiles touch and do not overlap. Each tile contributes
its whole output. Both ways of combining tiles below then write the same map.
With an overlap, predict.stitch chooses how a label map combines the tiles.
Pick one (stitch: pick_one, the default). Each tile gives up a margin of
tile * overlap / 2 pixels on each side and contributes the middle of its
output. The tiles of the slide’s first row and first column also keep their
outer margin, so the map starts at pixel 0. Each map pixel comes from exactly
one tile.
With overlap 0.5, a tile gives up a quarter of its side on each side and contributes the middle. A tile on the slide’s first row or column also keeps its outer margin.¶
Average (stitch: average). Each map pixel takes the class with the
highest weighted mean softmax over every kept tile that covers it. A tile’s
weight is highest at its middle and falls towards its border along a raised
cosine (a Hann window that is never zero), so a tile counts most where it sees
the most context around the pixel. With ensemble: true, each tile’s softmax
is first the mean over the bundles. Averaging runs the model on the same tiles
as pick one: it costs memory, not model time (see Cost).
On crops of the annotated regions of the 10 BEETLE test slides, at overlap 0.5, averaging gave a dataset-global mean Dice of 0.896, against 0.894 for pick one, and 0.891 with no overlap. Each crop was read with 128 px of context around it, and all three ways of combining tiles used the same tile predictions. Averaging was better on all four classes and on 8 of the 10 slides. These are crop scores, not slide scores (see Slide scores are not run metrics).
The margin must be a whole number of pixels. With 512 px tiles, an overlap of 0.25 gives 64 px and 0.5 gives 128 px. Another value is refused, and the error proposes one that works. An overlap of 0.5 gives about four times as many tiles, and takes about four times as long.
A pixel that no kept tile covers is 0, “not predicted”. With pick one, so is
the margin a tile gives up next to a tile that was not kept. Averaging labels
that margin from the kept tile alone. At the border of the kept tiles, the two
can therefore give a slide different not_predicted_fraction values.
stitch: average is for segmentation only. With detection bundles, the plan
is refused before any slide is read.
For detection, each tile keeps the peaks in the region it contributes, and places them on the slide in level-0 pixels. Then one NMS per class over the whole slide removes the duplicates that two tiles found on either side of a seam. It uses the head’s NMS distance, which is the matching distance unless the head sets one. With an overlap, the margin must be at least the NMS distance, so that a tile sees the whole neighbourhood of each peak it keeps. A smaller margin is refused, and the error says which overlap works.
Restrict a label map to the mask¶
The mask selects tiles, and each kept tile is predicted in full. So a map made
with a tumour mask, or with an annotation raster as the mask, also holds
predictions in a band around each masked region. With
predict.restrict_to_mask: true, the label map is 0, “not predicted”, at
every pixel outside the mask. In Python, pass restrict_to_mask=True to
soma.predict_slides().
A mask pixel is in scope when its value maps, through
extraction.masks.pixel_mapping, to a class that
extraction.masks.min_coverage names: the classes that select tiles. For
example, pixel_mapping: {background: [0], tissue: [1, 2, 3, 4]} with
min_coverage: {tissue: 0} puts the values 1 to 4 in scope. With the default
masks, the tissue (value 1) is in scope.
The flag does not change which tiles are kept. The map keeps its size, spacing and pyramid.
The mask is read with
extraction.tiling.mask_backend, on the map’s pixel grid, assoma evaluatereads an annotation raster: each map pixel takes the mask value under its top-left corner. A mask at another resolution works: hs2p aligns it to the slide. A map pixel that lies partly off the slide is out of scope.The flag applies after the tiles are combined and after an ensemble averages its bundles. So it works the same way with
pick_oneandaverage, for each bundle’s map, for an ensemble and withcohort.fold: bundle.The map’s metadata and the slide’s record hold
restrict_to_mask.
With the flag, not_predicted_fraction counts the pixels in scope only: the
pixels in scope that are 0, over all pixels in scope. A slide with no pixel in
scope gets 0.0. Without the flag, it is the share of all the map’s pixels that
are 0, as before. soma evaluate does not change: it computes its own
fraction over the annotated pixels.
These are refused before any slide is predicted:
restrict_to_mask: truewith detection bundles;a slide without a
mask_path. hs2p’s tissue segmentation is too coarse to cut a map with, so there is no fallback. The error names the slides.
Predict the annotated regions only. Give each slide’s annotation raster as
its mask_path, name the annotated values as the class that selects tiles,
and keep every tile they touch:
predict:
output_dir: predictions/beetle-annotated
bundles: runs/beetle
restrict_to_mask: true
cohort:
records: annotated.csv # mask_path: the annotation raster
extraction:
masks:
pixel_mapping:
background: [0] # not annotated
tissue: [1, 2, 3, 4] # the annotated classes
min_coverage:
tissue: 0
min_coverage: {tissue: 0} keeps every tile that the annotated values touch,
as hs2p measures coverage on the mask. On BEETLE slide TCGA-EW-A1PH, this keeps
121 tiles, against 40,283 for the whole tissue (40 s against 118 min), and gives
the same Dice. When every value that the class scheme scores is in scope, the
flag changes no score: soma evaluate scores the annotated pixels only, and
they keep their labels.
Predict on several devices¶
predict.devices lists the devices, such as [0, 1] for two GPUs.
predict.split says what is shared across them:
split: slides(the default) gives each device whole slides. Each device process tiles its slides, predicts them, and stitches and writes their files.split: tilespredicts the slides one after another. All the devices work on the tiles of the current slide.
soma does not choose the mode. Choose it by the size of the slides, as below.
When to use each mode. Use slides for many slides with little model
work each. An example is a prediction restricted to the annotated regions (see
Restrict a label map to the mask): it keeps few tiles per slide, so tiling,
stitching and writing take a large share of each slide’s time. With
slides, each device process does this work for its own slides, at the same
time as the others. With tiles, the main process does it for every slide,
one slide at a time, and the devices wait while it tiles a slide and finishes
writing its files. Use tiles for few large slides, such as full-tissue
maps, where the model takes almost all the time (see Cost).
It is also the only mode in which a second device helps when there is a single
slide to predict.
How tiles are shared. With split: tiles, soma starts one process per
device, once for the whole run. Each device process loads every bundle once.
Then, for each slide in turn:
The main process tiles the slide. It cuts the kept tiles, in row order, into chunks of
predict.batch_sizetiles. Each chunk is the batch that a run on one device would form.Chunk
igoes to devicei mod N, whereNis the number of devices. All the devices start at the same time.Each device process reads its tiles, runs the encoder and the decoders, and sends back the raw outputs of each batch.
The main process takes the results back in chunk order. It turns them into classes or peaks (the softmax, the argmax, the peak finding), stitches the tiles, and writes the slide’s files and records.
A device process that gets ahead waits until the main process has read its earlier results. So each device holds about one batch of results, and no process holds the results of a whole slide. The memory that stitching and writing need (see Cost) is in the main process.
The main process holds no GPU. It builds each bundle’s head from the bundle’s
model.json, and uses it on the CPU to turn the raw outputs into classes or
peaks. So split: tiles needs each bundle to record its head in
model.json (params.head). A bundle that
soma run saves records it. A segmentation bundle that does not is refused,
with an error that names it, before any slide is predicted. It still predicts
with split: slides.
One step can still use a GPU in the main process: tissue segmentation, which
runs when a slide without a mask_path is tiled. With
extraction.segmentation.method: sam2 and sam2_device: cuda, SAM2 runs
on a GPU from the main process. The default sam2_device is cpu.
Reader processes. Each device process reads its own tiles with
predict.num_workers reader processes, as with split: slides. So up to
devices × num_workers reader processes run at a time: 16 for
devices: [0, 1] and num_workers: 8. The main process reads no tiles.
Output. The models get the same batches, in the same order, as on one device, and the main process stitches the results in the same order. So the effect of the batch size in fp16 (see The plan) does not change with the number of devices.
On CPU devices, such as
devices: ["cpu", "cpu"], the files are byte for byte those of a run on one device.On GPUs, a map matches a run on one GPU up to the hardware’s own differences. The main process computes the softmax, the argmax and the peaks on the CPU, where a run on one GPU computes them on the GPU. The two can round differently, so a pixel where two classes are almost tied, or a peak near a tie, can differ. GPUs of different models can also round fp16 differently, so a run that mixes them can differ a little more.
Failure and resume. With split: tiles, when a device process raises an
error or dies, for example because it ran out of memory, the run stops:
the slide in progress leaves no partial map, points file or record;
the other device processes are stopped;
the error names the device and its log,
<output_dir>/logs/worker_<k>.log. A one-lineError:message fromsoma predictdoes not: the full error is then at the end of one of these logs.
With split: slides, the other device processes first finish their own
slides, then the run ends with the error.
The slides already written keep their files and records. Launch the run again
to resume: the finished slides are skipped, and the slide that was in progress
is predicted again from its start. The relaunch may change
predict.devices, predict.split, predict.num_workers and
predict.batch_size (see The plan). For example, after an
out-of-memory error, resume with a smaller batch.
What it writes¶
Each slide gets one file and one record per bundle, in the bundle’s directory of the output. Whole-slide prediction outputs gives the full layout and the index.
Label TIFF (segmentation)¶
<output_dir>/<bundle>/<sample_id>.tif is a pyramidal, tiled TIFF of uint8
values, stored lossless (LZW). Its spacing is that of the pixels read, up to
hs2p’s rounding of the grid step. When a pyramid level is within the tolerance,
the tiles are read at that level’s own spacing, which can differ a little from
the read spacing. The index gives the width, height and spacing_um
of each map: use spacing_um, not read_spacing_um, for distances and
areas. Each coarser level keeps every other pixel of the level below, so it
holds stored values only, never an average.
The values are shifted by one:
0means “not predicted”: no kept tile contributed the pixel, or, withpredict.restrict_to_mask: true, the pixel is outside the mask.Class
kis stored ask + 1. A map holds at most 255 classes.
The PNG label maps that a run writes for its ROIs (predictions_<split>/)
store class k as k. An ROI is always predicted in full, so it needs no
“not predicted” value.
The description of the first page holds a JSON record of what the map means:
values: the name of each stored value, such as{"0": "not predicted", "1": "stroma", "2": "tumor"};classes: the raw annotation values that form each class, in class order;ignore: the raw annotation values left out of the loss and the metrics;pixel_mapping: the vocabulary that hs2p reads the annotation rasters with;sample_id,ensemble,read_spacing_um,tile_size_px,overlap,stitch,restrict_to_mask, andbundles: the name, path and SHA-256 of each bundle.
soma evaluate scores the map with this class scheme. Any TIFF library reads
the map:
import json
import tifffile
with tifffile.TiffFile("predictions/beetle-test/fold_0/slide-01.tif") as tiff:
metadata = json.loads(tiff.pages[0].description)
overview = tiff.series[0].levels[-1].asarray() # the coarsest level
classes = overview.astype(int) - 1 # -1 where nothing was predicted
Points parquet (detection)¶
<output_dir>/<bundle>/<sample_id>.parquet has four columns: x and y
in the slide’s level-0 pixels, class (the class index) and score. It
holds every peak above the head’s min_score. No threshold is applied, so a
threshold can be chosen later. Its schema metadata (key soma) records:
the class scheme the bundle was trained with:
classesmaps each class name to the annotated ids that form it, in class order, anddroplists the dropped ids (see Classes);the matching and NMS distances, in µm, and
min_score;the slide’s level-0 spacing, the read spacing, the tile size and the overlap;
the bundles: the name, path and SHA-256 of each;
the bundle’s tune threshold (
threshold).
The scheme comes from the bundle’s preprocessing.json. A bundle trained
before soma recorded it has no class_scheme, and soma predict refuses
it before it writes anything. Train the bundle again, or add class_scheme
to its preprocessing.json from the run’s config, for example
{"classes": {"mnl": [0, 1]}, "drop": [2]}. The class names must be the
bundle’s own.
Several bundles¶
predict.bundles may name several bundles, such as the folds of one run. They
must all be of one task family, and agree on the tile size, the read spacing and
the read tolerance. The bundles that share an encoder recipe share one encoder
pass per tile, so each extra bundle costs mostly its decoder’s time.
With an explicit cohort.fold, all the bundles predict the same slides: the
cohort.subset split of that fold. So predict a split that every bundle held
out, such as a test split that all folds share. When each fold has its own test
split, use cohort.fold: bundle (see Each fold’s own slides).
By default, each bundle gets its own prediction, in its own directory. The
directory is named by the shortest end of the bundle’s path that tells the
bundles apart, without a last bundle: runs/beetle/fold_0/bundle writes
to fold_0/. Score each directory on its own:
soma evaluate predictions/beetle-test/fold_0 --cohort dataset.csv --splits splits.csv
With ensemble: true, the bundles give one prediction per slide, in
ensemble/:
segmentation: the class with the highest mean softmax over the bundles;
detection: the peaks of the bundles’ mean heatmap, found with the first bundle’s head.
The bundles of an ensemble must share their class scheme. For segmentation, that
is the classes, the raw annotation values that form them and the values ignored.
For detection, it is the classes, their annotated ids, the dropped ids, both
distances and min_score. An ensemble’s points record no threshold (see
Score points).
Each fold’s own slides¶
In a cross-validation where each fold has its own test slides, set
cohort.fold: bundle. Each bundle then predicts the cohort.subset split
(default test) of its own fold, the fold that its provenance.json
records:
predict:
output_dir: predictions/beetle-cv
bundles: runs/beetle # fold_0/bundle, fold_1/bundle, ...
cohort:
records: dataset.csv
splits: splits.csv # the splits the run was trained on
fold: bundle
In Python, pass fold="bundle" to soma.predict_slides().
A fold bundle that soma run saves records its fold and its
fold_assignments: the SHA-256 of the split of each sample in that fold (see
soma.data.FoldSplit.assignments_digest()). soma predict computes the
digest again from that fold of cohort.splits, and refuses the bundle when
the two differ. So a bundle predicts only the slides it held out.
These are refused with cohort.fold: bundle:
no
cohort.splits;predict.ensemble: true, because the bundles predict different slides;cohort.subset: train, because each bundle was trained on it. To predict training slides, use an explicitcohort.fold;a bundle that records no
fold_assignments: one saved by an older soma, or bysoma.save()without a fold. Predict such bundles with one config per fold instead:predict.bundles: runs/beetle/fold_<k>/bundlewithcohort.fold: <k>, each into its ownpredict.output_dir;a bundle whose fold
cohort.splitsassigns differently from the splits it was trained on, or does not have;a
cohort.subsetthat is not a split of a bundle’s fold, or has no slides in it (such astunein a fold with no tune rows).
Two bundles may record the same fold, such as runs/uni2/fold_0/bundle and
runs/virchow2/fold_0/bundle trained on the same splits. Both predict the
slides of that fold. Each slide goes only through the bundles that predict it,
and the bundles that share an encoder recipe still share one encoder pass per
tile. predict.stitch applies to each of those maps as it does with an
explicit fold. index.parquet lists each bundle with its own slides.
plan.yaml keeps cohort.fold: bundle, so a replay reads the fold of each
bundle again. The output’s provenance.json records each bundle’s fold
and fold_assignments.
Score each bundle’s directory with its own fold:
for k in 0 1 2 3 4; do
soma evaluate predictions/beetle-cv/fold_$k --cohort dataset.csv \
--splits splits.csv --fold $k --out fold_$k.json
done
A wrong --fold fails, because every prediction needs a target and every
target a prediction. soma gives no summary over the folds.
Score¶
soma evaluate scores one bundle’s predictions, or one ensemble’s. Pass the
output directory when it holds one bundle, or else the bundle’s directory. Pass
the split you predicted: --splits splits.csv selects the test split of
fold 0 unless --split and --fold say otherwise. Without --splits,
every row of the cohort is a target. Every target needs a prediction, and every
prediction a target.
Every row of the cohort CSV must name its annotation (label_mask_path or
points_path), also the rows outside the split. To score part of a mixed
cohort, predict and score with a CSV of the annotated slides only: every
prediction still needs a target.
Score label maps¶
SlideLabelMaps is a handle on one bundle’s directory
of label TIFFs, and soma.evaluate() scores it against a
LabelMapSource of the slides’ annotation rasters:
import soma
from soma.data import AnnotationManifest, ImageManifest, LabelMapSource
from soma.evaluation import SlideLabelMaps
maps = SlideLabelMaps("predictions/beetle-test/fold_0")
targets = LabelMapSource.from_manifests(
AnnotationManifest.from_csv("dataset.csv"),
ImageManifest.from_csv("dataset.csv"), # aligns each raster to its slide
size=(0, 0),
backend=maps.mask_backend,
image_backend=maps.backend,
)
evaluation = soma.evaluate(maps, targets.subset(maps.sample_ids))
evaluation.per_sample # one row of counts per slide
soma evaluate predictions/beetle-test/fold_0 --cohort dataset.csv --splits
splits.csv scores the test split the same way. The cohort CSV gives each slide’s annotation raster in its
label_mask_path column.
The slides and the annotation rasters are read with the hs2p readers that the
prediction’s plan.yaml records (maps.backend and maps.mask_backend).
To read with other readers, pass --backend for the slides and
--mask-backend for the annotation rasters:
soma evaluate predictions/beetle-test/fold_0 --cohort dataset.csv --splits splits.csv \
--backend openslide --mask-backend tifffile
In Python, pass the readers to LabelMapSource.from_manifests as
image_backend and backend. Both options apply to a soma predict
output only; soma evaluate refuses them for other predictions.
Each slide is read one window at a time on the map’s pixel grid, so neither the map nor the annotation raster is held in memory. hs2p aligns an annotation raster at another resolution to the slide, and reads it at the map’s spacing. The class scheme is the one each map records from its bundle’s head: the raw annotation values of each class, the raw values to ignore, and the vocabulary the raster is read with, as in training. The class scheme, spacing and size of the target source are not used.
A pixel whose annotation value is ignored is not scored.
An annotated pixel of class
cthat was not predicted (value 0 in the map) is a false negative forc, and a false positive for no class.A map pixel that lies partly off the slide is not scored.
An annotation value that the scheme neither gives a class nor ignores is refused, with the slide’s name.
A window with no annotated pixel adds nothing to the counts: every annotation value in it is ignored, or the window lies wholly off the slide. For such a window, only the annotation raster is read. The map is not read, and nothing is counted. This is often most of a slide: on one BEETLE slide, 4,083 of the 4,095 windows held no annotated pixel. The scores are the same as when every window is read. Because the map is not read there, a map value that the map’s value mapping does not name is refused only in a window with an annotated pixel.
The slides are scored one after the other. To score several at a time, pass
num_workers:
from soma.evaluation import SlideLabelMaps
maps = SlideLabelMaps("predictions/beetle-test/fold_0", num_workers=4)
On the command line, pass --num-workers 4. Each worker process scores one
slide at a time and opens its own readers: the same ones as the main process,
--backend and --mask-backend included. With num_workers=0, the
default, the main process scores the slides. The scores, and the order of the
rows, do not change. Each worker holds one window of the map and one of the
annotation raster, as the main process does. A slide that fails stops the other
workers, with the same message as in the main process; if several slides fail,
the first one to fail is reported. --num-workers applies to the label maps
of a soma predict output only; soma evaluate refuses it for other
predictions.
The workers start with the spawn method, so each one imports the main
script again. In a Python script, call soma.evaluate() under
if __name__ == "__main__":.
Each slide gives one row of counts to the same reducers as
LabelMapPredictions. Evaluation.per_sample holds
the rows: annotated_px, not_predicted_px, not_predicted_fraction
(the annotated pixels not predicted, over all annotated pixels) and
tp_class_<c>, fp_class_<c>, fn_class_<c> per class. soma
evaluate prints each slide’s annotated_px and not_predicted_fraction
in a second table, and --out writes the full rows.
Score points¶
SlidePoints is a handle on one bundle’s directory of
points parquets, and soma.evaluate() scores it against a
PointSource of the slides’ annotated points:
import soma
from soma.data import AnnotationManifest, PointSource
from soma.evaluation import SlidePoints
points = SlidePoints("predictions/midog-test/fold_0")
targets = PointSource.from_manifest(AnnotationManifest.from_csv("dataset.csv"))
evaluation = soma.evaluate(points, targets.subset(points.sample_ids))
evaluation.per_sample # one row of counts per slide
soma evaluate predictions/midog-test/fold_0 --cohort dataset.csv --splits
splits.csv scores the test split the same way. The cohort CSV gives each slide’s points_path, a x,y,class file in
level-0 pixels that holds the dataset’s own annotated ids, and optionally its
ignore_mask_path.
The class scheme is the one each parquet records from its bundle: the annotated ids of each class, and the ids dropped. A points file written before soma recorded the scheme is refused: predict the slides again. The class scheme of the target source is not used.
An annotated point whose id is dropped is removed. A prediction there is a false positive.
An annotated id that the scheme neither gives a class nor drops is refused.
A prediction scoring below the threshold is removed.
With an ignore mask, a point (annotated or predicted) on a mask pixel of 255 is not scored. The mask may have any resolution that covers the slide: hs2p aligns it to the slide’s level 0 and reads it with the reader the prediction’s
plan.yamlrecords (points.mask_backend), or--mask-backend. Its pixels must be 0 (annotated) or 255 (not annotated); another value is refused. Without a mask, the whole slide is annotated.Predictions are matched to the annotations of their class within the bundle’s matching distance, in µm, at each slide’s own spacing. Matching is Hungarian by default. A metric leaf with
matching: greedymatches by descending score, andmatch_distancesets another distance, in µm.
The threshold is the bundle’s tune threshold, which the parquet records
(points.threshold). An ensemble’s points record none, and are refused until
one is set. Pick one on a tune split with
sweep_threshold(), which takes
SlidePoints too, and set it with with_threshold.
soma evaluate --threshold T sets one value for every class:
from soma.evaluation import sweep_threshold
tune = SlidePoints("predictions/tune/ensemble") # an ensemble's points
threshold, _ = sweep_threshold(tune, targets.subset(tune.sample_ids), per_class=True)
test = SlidePoints("predictions/test/ensemble").with_threshold(threshold)
evaluation = soma.evaluate(test, targets.subset(test.sample_ids))
Each slide gives one row of counts to the same reducers as
PointPredictions. Evaluation.per_sample holds the
rows: annotated_area_mm2 (the annotated mask pixels times their area, or the
whole slide without a mask) and tp_class_<c>, fp_class_<c>,
fn_class_<c> per class. The counts use the matching that all the metrics
name. If the metrics name none, or name different ones, the counts use the
default matching.
Matching lists only the pairs of points within the matching distance, so a slide with many points takes little memory: 100,000 predictions against 20,000 annotations of one class match in about a second.
Slide scores are not run metrics¶
A slide score is not comparable to the test metrics of the run that trained the bundle. The two measure different things:
A run scores only what it samples. For segmentation, these are the ROIs where an annotation class meets
min_coverage; for detection, the ROIs or tiles of its test split. A slide score covers every annotated pixel or point of the slide, and for detection every prediction outside the ignored region.A slide score counts the annotated pixels that were not predicted as misses. A run predicts its ROIs in full.
A metric that averages over samples changes meaning: a sample is an ROI in a run and a slide here.
In the BEETLE check below, the pooled dataset_global_mean_dice was 0.883
over whole slides and 0.893 over the run’s ROIs, and the Dice of each class
agreed within 0.020. But mean_dice, which averages over samples, was 0.537
over slides and 0.761 over ROIs. 1.7% of the annotated pixels were not
predicted, mostly on two slides (8.1% and 2.1%).
Compare slide scores with slide scores, and run metrics with run metrics.
Cost¶
These numbers come from one check on BEETLE breast resections, on a shared
machine: read them as orders of magnitude. The setup: one RTX 3080 Ti (12 GB),
Virchow2 in fp16, 512 px tiles at 0.5 µm, a lightweight_conv decoder with 4
classes, overlap: 0, hsv tissue segmentation, batch size 8, and slides read
with openslide from a local disk.
One slide of 92,819 × 45,702 px, with 10,117 kept tiles:
One slide |
|
|
|---|---|---|
Wall time |
24.7 min |
22.6 min |
Tiles per second |
6.8 |
7.5 |
Model (encoder and decoder) |
90% of the time |
99% of the time |
Tile reads |
9% (13.6 ms per tile) |
hidden by the workers |
Stitching and TIFF writing |
1% |
1% |
Peak memory, main process |
3.1 GiB |
3.1 GiB |
Peak GPU memory |
2.95 GiB |
2.95 GiB |
Speed. The encoder sets the pace. Prediction runs at about the speed of feature extraction with the same encoder. With
num_workersabove 0, the tile reads overlap with the model.Memory. Peak memory grows with the slide’s size in pixels, not with its tissue: hs2p’s TIFF writer holds the coarser levels of the map in memory, about a third of the raw map. This memory is per map, and without
ensemble: trueevery bundle’s map is written at the same time, so it adds up over the bundles. The largest slide (136,064 × 147,072 px, 2,052 kept tiles) peaked at 7.2 GiB, 6.0 GiB above the level after the model loaded. Writing took 23% of its 6.0 min, because the writer processes the whole map, also where nothing was predicted.File size. The maps compress well. The slide above takes 53 MB, for a raw map of 3.95 GiB. The largest slide takes 181 MB.
A test set. 10 slides (38,617 kept tiles) took 47.6 min on 3 GPUs with
split: slides, and 622 MB of maps.Overlap. An overlap of 0.5 gave four times the tiles and the time on one small slide, and the same score within 0.010.
Scoring.
soma evaluatereads every window of the annotation raster, and reads the map only in the windows with an annotated pixel (12 of the 4,095 windows of the slide above). Most of the time goes to reading the annotation raster.--num-workersscores several slides at a time.
Detection, ensembles, several bundles and slides resampled from a finer level were not measured.
Averaging (stitch: average) also holds, for each map, float32 sums over
one tile’s height of rows and the map’s whole width, one plane per class:
classes × tile × map width × 4 bytes. Without ensemble: true, each bundle’s
map has its own; with cohort.fold: bundle, only the maps of the bundles
that predict the slide. The slide’s height does not change this cost. With 4 classes
and 512 px tiles, a map 50,176 px wide needs 392 MiB of sums. On a synthetic
slide of 50,176 × 2,048 px, at overlap 0.5 with batch size 8 on the CPU (a
weight-free encoder and a 4-class linear decoder), the peak memory while
predicting rose by about 200 MiB with pick one and by about 650 MiB with
averaging. The 450 MiB more are mostly the sums and one batch of softmax
(32 MiB).
Reference¶
- soma.predict_slides(*, output_dir, bundles, records, splits=None, subset=None, fold=None, ensemble=False, stitch='pick_one', restrict_to_mask=False, batch_size=8, num_workers=0, devices=None, split='slides', extraction=None)¶
Predict over every slide of a cohort: one file per slide and bundle, a label TIFF for a segmentation bundle and a points parquet for a detection bundle.
One keyword per config key (see the module docstring for the config):
output_dir,bundles,ensemble,stitch,restrict_to_mask,batch_size,num_workers,devicesandsplitare thepredictsection,records,splits,subsetandfoldthecohortsection, andextractiontheextractionsection (a mapping, or aslide2vec.PreprocessingConfig). Relative paths resolve against the working directory.bundlesare segmentation or detection bundles (soma.save()), all of one family, that agree on tile size and read spacing, or one run directory, which stands for its bundles. Each slide is cut into hs2p’s slide grid withextraction.tiling.overlap; a tile is kept when its row’smask_path, or else hs2p’s tissue segmentation, covers at leastextraction.masks.min_coverageof it. Kept tiles are read at the bundles’ read spacing and run through each bundle’s model, behind one encoder forward for the bundles that share an encoder recipe.Segmentation:
stitchnames how overlapping tiles are combined (soma.evaluation.whole_slide). Withpick_one(the default), each map pixel takes the class of one tile. Withaverage, it takes the argmax of the Hann-weighted mean softmax of every kept tile that covers it, so next to a tile that was not kept it labels the margin that pick one leaves at 0. Averaging also holds, per map, float32 sums over one tile’s height of rows and the map’s width, one plane per class. Classkis stored ask + 1; 0 is “not predicted”.averageis refused for detection bundles.restrict_to_mask=Truesets each map to 0 wherever the slide’s mask is out of scope, after stitching and after an ensemble’s averaging: a mask pixel is in scope when its value maps, throughextraction.masks.pixel_mapping, to a class thatextraction.masks.min_coveragenames. It does not change which tiles are kept. The mask is read on the map’s grid withextraction.tiling.mask_backend, and a map pixel it does not cover is out of scope.not_predicted_fractionis then the share of the in-scope pixels that are 0 (0.0 for a slide with none), not of all the map’s pixels. It is refused for detection bundles and, before any slide is predicted, for a cohort with a slide without amask_path. Detection: each tile keeps the peaks in the region it contributes, lifted to level-0 pixels, and one per-class NMS over the slide removes the duplicates across seams (soma.evaluation.whole_slide_points). The parquet holds every peak above the head’smin_score, with columnsx,y,classandscore; the bundle’s tune threshold is recorded, not applied, and so is its class scheme (class_schemein itspreprocessing.json; a bundle that records none is refused). With an overlap, the margin (tile * overlap / 2) must be at least the head’s NMS distance.The slides are read with the reader the bundles were trained with (the
backendtheir encoder recipe records), unlessextraction.tiling.backendnames one. Bundles that record different readers are refused unless it does, and a reader other than a bundle’s is used with a warning. A bundle that records no reader leaves the choice to the others, andautowhen none records one. Aslide2vec.PreprocessingConfigalways names its reader. The masks are read withextraction.tiling.mask_backend.Without
splitsevery row ofrecordsis predicted; with it, thesubsetsplit (defaulttest) of foldfold(default 0).fold="bundle"gives each bundle thesubsetsplit of its own fold, thefolditsprovenance.jsonrecords. The bundle must also record that fold’sfold_assignments(soma.data.FoldSplit.assignments_digest()), andsplitsmust assign the fold the same way;ensembleandsubset="train"are refused with it, and so is a bundle whose fold has no slides insubset.ensemblewrites one file per slide instead of one per bundle: the argmax of the bundles’ mean softmax (to average, each tile’s softmax is that mean), or the peaks of their mean heatmap, with no threshold recorded.devices([0, 1],["cpu"]) predicts in one new process per device, the slides split across them; by default the slides are predicted in this process.splitnames what is split across the devices:"slides"(the default) or"tiles". With"tiles"the slides are predicted one after another: this process tiles each slide, gives chunkiofbatch_sizeof its kept tiles, in order, to devicei mod N, takes the results back in order, and stitches and writes them on the CPU, holding no device. Each device process loads every bundle once and reads its tiles withnum_workersprocesses; each logs to<output_dir>/logs/worker_<k>.log. On CPU devices the files are byte for byte those of one device. A device process that raises or dies stops the call, the slide being written leaves no file, and the error names the device and its log. With one device, or withoutdevices,"tiles"is"slides".Returns the index of the files, also written as
index.parquet: one row per file with itsbundledirectory,sample_id,path(relative tooutput_dir),width,height,spacing_um,read_spacing_umandnum_tiles, thennot_predicted_fractionfor label maps ornum_pointsfor points.width,heightandspacing_umare the frame of the file: the map’s pixels, or the slide’s level 0 for points.- Return type:
DataFrame