Survival

Two heads model time-to-event with right censoring; the head selects the loss:

  • discrete_survival — discrete-time survival modeling. The continuous time axis is split into num_bins bins; the head emits one hazard logit per bin and trains with the sigmoid-hazard negative log-likelihood (the Gensheimer / HIPT NLLSurvLoss formulation).

  • cox_survival — continuous-time CoxPH. The head emits a single risk scalar and trains with the Breslow partial-likelihood loss. The risk set must contain several samples, and the loader uses an event-balanced sampler so every batch/window contains at least one event (trainer.accumulate_grad_batches must be 1). Two modes, switched by the head’s cox_window param:

    • Padded mode (cox_window unset / 1): the risk set is the batch (batch_size >= 2). Works on single-embedding slide/patient features (no aggregator) or on MIL bags (any of abmil/transmil/mean_pool), where variable-length bags are padded and masking keeps the result exact.

    • Accumulation mode (cox_window >= 2): for large variable-size MIL bags. batch_size is pinned to 1 and an aggregator is required. The trainer forwards cox_window bags un-padded and computes one Cox loss and one optimizer step per window. By default, the window keeps every bag’s activations in GPU memory until the backward pass. With learner.params.checkpoint_cox_window: true, it keeps one bag’s at a time: the backward pass computes each bag again, so a window takes about twice as long, with the same loss and gradients. A run that ran out of GPU memory can resume with it on.

Both losses rank with Harrell’s C-index via scikit-survival. The mil_survival preset takes the loss as its loss argument: "nll" builds the discrete_survival head with binning: train_quantiles and the preset’s num_bins (required), and "cox" the cox_survival head in accumulation mode, with cox_window: 32 (it takes no num_bins).

During training, a Cox head’s tune/loss is the partial-likelihood loss over the whole tune split. With the train pass, train/loss is the one over the whole train split, not over the event-balanced training batches (see The train pass). A split without an event has no partial-likelihood loss and no C-index: both are NaN. When best-epoch selection or early stopping monitors either one, the run stops with an error. With evaluation.subgroups, each group’s loss is computed over the group’s own risk sets, so the groups’ losses do not average to tune/loss (see Subgroup metrics).

Survival datasets carry these target columns; the head’s targets param maps a target to a differently named column, for example targets: {time: label}:

Column

Meaning

time

Continuous time-to-event (uncensored) or time-to-last-follow-up (censored).

event

1 if the event was observed, 0 if right-censored.

bin

Index of the discrete time bin containing time, for every sample including censored ones. Read by the discrete_survival head with binning: column only.

Time bins

The discrete_survival head’s binning param says where each sample’s bin comes from: train_quantiles, fixed or column. You always set it yourself: no other param changes it.

binning: train_quantiles (recommended) derives the bins in the run, from each fold’s training split, so the cohort needs only time and event. num_bins is required: it is the number of bins and the head width. Binning on the whole cohort would let the tune and test times shape the cut points; here only the training times do.

head:
  name: discrete_survival
  params: {binning: train_quantiles, num_bins: 4}

For each fold, with K = num_bins:

  • The cut points are the K - 1 inner quantiles (1/K, ..., (K-1)/K) of the uncensored training times, with linear interpolation (np.quantile’s method="linear").

  • The training times are those of the samples the fold trains on: its training slides with features (a slide without tissue never trains), or for a patient run (cohort.collapse: patient_id) one time per training patient, however many slides it has. cohort.tune_is_test and cohort.allow_missing_tune change tune only and do not move the cut points.

  • Bins are left-closed, [c_j, c_{j+1}): a time equal to a cut point goes to the upper bin. The first and last bins are open, so a tune or test time outside the training range falls in bin 0 or bin K - 1.

  • A censored sample gets the bin its time falls in, like an uncensored one.

A fold whose training split has fewer than K uncensored times, or whose cut points tie (several training times equal to one cut point), cannot form K bins: the run stops with an error naming the fold, num_bins, the number of uncensored training times and the repeated cut point. Lower num_bins; empty bins are never created. The check runs when the run starts, on each fold’s splits (before any tiling or extraction), and again when each fold is trained.

The fitted cut points are the head’s bin_edges. The fold’s log prints them, and each fold bundle records them in model.json, so soma.load() rebuilds a head that carries them. plan.yaml records binning, num_bins and bin_edges: null, never the fitted cut points, because the plan is the same for every fold. With binning: train_quantiles a config cannot set bin_edges (choose them with binning: fixed), and the cohort may not have a bin column: drop it, or set binning: column.

binning: fixed bins each time with cut points you choose, for example 12, 24 and 36 months:

head:
  name: discrete_survival
  params: {binning: fixed, bin_edges: [12, 24, 36]}

The cohort needs only time and event, and may not have a bin column. The bins follow the same rules as above: each bin holds its lower cut point, and the first and last bins are open. So [12, 24, 36] makes four bins: [0, 12), [12, 24), [24, 36) and [36, inf). The cut points do not depend on the data, so nothing is fitted per fold and the tune and test times cannot shape them.

  • bin_edges are in the units of the time column. Nothing checks this: cut points in months on a time in years put almost every case in the first bin.

  • bin_edges is a list of at least one finite number above 0, in strictly increasing order. A list out of order or with a repeat is refused, never sorted or deduplicated for you. The cut points are kept as floats, so [12, 24, 36] and [12.0, 24.0, 36.0] give the same plan.

  • num_bins is len(bin_edges) + 1. You may leave it out; if you set it, it must be that number. plan.yaml records binning, bin_edges and num_bins, and each fold bundle’s model.json records the same cut points.

For each fold, the log counts the training cases and events in each bin, once when the run starts and again when the fold is trained:

Fold 0: discrete_survival fixed bins on 162 training cases:
  [0, 12): 41 cases, 30 events | [12, 24): 38 cases, 19 events | [24, 36): 22 cases, 8 events | [36, inf): 61 cases, 5 events

A case is one sample the fold trains on: a slide, or a patient in a patient run. Empty bins are allowed: clinical cut points on a small cohort often leave the last bin empty in some fold, and an empty first or middle bin still learns from the samples in later bins, which survived it. A fold whose training cases all fall in one bin is refused, because the cut points then decide nothing: check the units of bin_edges first. Tune and test are not checked: the outer bins are open, and evaluation does not read the bins.

Outside soma, the same bins are a bin column you compute yourself and read with binning: column, for example pd.cut(time, [0, 12, 24, 36, np.inf], right=False, labels=False).

binning: column (the default) reads the bins you computed before the run from the cohort’s bin column. Set the head’s num_bins param to fix the head width: any subset of indices in [0, num_bins) is then valid, including empty intervals, and indices are never renumbered. Without an explicit width, observed bins must be contiguous from zero and num_bins is inferred as max(bin) + 1. Cut points computed on the whole cohort carry information about the tune and test times into training; train_quantiles avoids this, and so does fixed with cut points chosen before looking at the data.

Risk scores, time and event are all that prediction and evaluation read; no mode changes them.

Samples and aggregators

Survival samples are slides or patients (cohort.collapse: patient_id); a tile-level run is rejected. For patient runs, all slides of a patient must agree on the survival target. Survival MIL supports abmil, transmil, mean_pool and hipt; other aggregators are rejected. A hierarchical store works with all four: hipt reads it grouped, and the others read it as a flat bag of its tiles (see Aggregators).

Task heads

class soma.models.heads.survival.DiscreteSurvivalHead(input_dim, num_bins, alpha=0.15, metrics=None, dropout=0.0, binning='column', bin_edges=None)

Bases: TaskHead

Discrete-time survival head (sigmoid-hazard NLL).

Parameters:
  • input_dim (int) – Dimension of the input representation.

  • num_bins (int) – Number of discrete time bins (model output width).

  • alpha (float) – Up-weighting of the uncensored NLL term (HIPT default 0.15).

  • metrics (list[str] | None) – Metrics to compute. Empty list uses the survival default (c_index).

  • dropout (float) – Probability of zeroing an element of the head’s input, applied before the linear layer. 0.0 (default) builds no dropout module.

  • binning (str) – "column" (default) reads each sample’s bin from its bin target; "train_quantiles" and "fixed" derive it from time and bin_edges.

  • bin_edges (Sequence[float] | None) – The num_bins - 1 increasing cut points: under "fixed", the config’s (required); under "train_quantiles", those fit_bin_edges() fits on a fold’s training split. Bin j holds the times in [bin_edges[j-1], bin_edges[j]); the first and last bins are open.

class soma.models.heads.survival.CoxSurvivalHead(input_dim, ties='breslow', min_events_per_window=1, cox_window=1, metrics=None, dropout=0.0)

Bases: TaskHead

Continuous-time CoxPH survival head (Breslow partial likelihood).

Emits a single risk scalar per sample; the Cox partial likelihood is computed over a risk set of multiple samples. Unlike DiscreteSurvivalHead, there is no binning and risk is the raw model output — higher means higher hazard / shorter survival, which is what concordance_index_censored expects. (Reusing the NLL head’s -sum(surv) derivation here would double-invert the C-index sign.)

The cox_survival head. Two training modes, switched by its cox_window param (carried here as accumulation_window):

  • Padded mode (cox_window unset / 1): the risk set is the batch. Single-embedding slide/patient features (no aggregator, batch_size >= 2) or padded MIL bags (batch_size >= 2, masking handles padding).

  • Accumulation mode (cox_window >= 2): for large variable-size MIL bags. batch_size is pinned to 1; the trainer forwards cox_window bags un-padded, keeps their risk scalars graph-connected, and computes one Cox loss over the window. accumulates_predictions signals this to the trainer.

In both modes the pipeline builds the training loader with an event-balanced sampler (needs_event_balanced_batches) and the tune loss is computed over the whole cohort (full_cohort_eval_loss). Config validation enforces the mode constraints.

Parameters:
  • input_dim (int) – Dimension of the input representation.

  • ties (str) – Tie-handling method. Only "breslow" is implemented.

  • min_events_per_window (int) – Minimum events the event-balanced sampler guarantees per batch / window (>= 1).

  • cox_window (int) – Prediction-accumulation window size. 1 (default) selects padded mode; >= 2 selects accumulation mode with this risk-set size.

  • metrics (list[str] | None) – Metrics to compute. Empty list uses the survival default (c_index).

  • dropout (float) – Probability of zeroing an element of the head’s input, applied before the linear layer. 0.0 (default) builds no dropout module.