Skip to content

Inference

photosvi.inference.points.train_points_svi

train_points_svi(model, y, inj_t, *, lr=0.001, steps=1000, device='cpu', verbose=True, log_every=100, seed=None, keep_best=True)

Fit a SingleTraceModel by relaxed-discrete SVI. Returns the per-element ELBO loss history.

y is [B, T] observed traces sharing the injection bin inj_t. Optimizes Trace_ELBO(max_plate_nesting=2) (sequences x time plates) with ClippedAdam.

The relaxed ELBO loss is noisy and backslides off its minimum, so by default (keep_best=True) the param store is snapshotted at every new best and restored at the end -- the returned model carries the best-checkpoint params, not the last step's. Set keep_best=False to leave the store at the last step (the raw trajectory, for debugging). This is the best-checkpoint analogue of standard early stopping: no run is halted early (there is no held-out split to stop on), but the fit is read off the minimum, not the tail.

Returns {"elbo": [...], "best_loss": float, "best_step": int} -- the per-element negative ELBO history (lower is better), the minimum loss, and its 1-indexed step.

Source code in src/photosvi/inference/points/train.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def train_points_svi(
    model,
    y: torch.Tensor,
    inj_t: int,
    *,
    lr: float = 1e-3,
    steps: int = 1000,
    device: str = "cpu",
    verbose: bool = True,
    log_every: int = 100,
    seed: int | None = None,
    keep_best: bool = True,
) -> dict:
    """Fit a `SingleTraceModel` by relaxed-discrete SVI. Returns the per-element ELBO loss history.

    `y` is [B, T] observed traces sharing the injection bin `inj_t`. Optimizes
    `Trace_ELBO(max_plate_nesting=2)` (sequences x time plates) with ClippedAdam.

    The relaxed ELBO loss is noisy and backslides off its minimum, so by default
    (`keep_best=True`) the param store is snapshotted at every new best and
    restored at the end -- the returned model carries the *best-checkpoint*
    params, not the last step's. Set `keep_best=False` to leave the store at the
    last step (the raw trajectory, for debugging). This is the best-checkpoint
    analogue of standard early stopping: no run is halted early (there is no
    held-out split to stop on), but the fit is read off the minimum, not the tail.

    Returns `{"elbo": [...], "best_loss": float, "best_step": int}` -- the
    per-element negative ELBO history (lower is better), the minimum loss, and
    its 1-indexed step.
    """
    model.to(device)
    y = y.to(device)
    if seed is not None:
        pyro.set_rng_seed(seed)
    pyro.clear_param_store()

    optim = ClippedAdam({"lr": float(lr)})
    elbo = Trace_ELBO(max_plate_nesting=2)
    svi = SVI(model.model, model.guide, optim, elbo)

    n_elem = y.numel()
    hist: list[float] = []
    best_loss, best_step, best_state = float("inf"), 0, None
    start = time.time()
    if verbose:
        print(f"Device: {device}  |  {y.shape[0]} seqs x {y.shape[1]} bins, tau={model.tau}")

    for step in range(1, steps + 1):
        loss = svi.step(y, inj_t) / n_elem
        hist.append(loss)
        if loss < best_loss:
            best_loss, best_step = loss, step
            if keep_best:
                best_state = copy.deepcopy(pyro.get_param_store().get_state())
        if verbose and (step == 1 or step % log_every == 0):
            print(f"[step {step}/{steps}] elbo loss: {loss:.4f}")

    # restore the best checkpoint so the returned model is read off the minimum,
    # not the noisy last step.
    if keep_best and best_state is not None:
        pyro.get_param_store().set_state(best_state)

    if verbose:
        elapsed = time.time() - start
        print(f"Training completed in {elapsed:.2f}s ({elapsed / 60:.2f} min) "
              f"| best elbo {best_loss:.4f} @ step {best_step}")
    return {"elbo": hist, "best_loss": best_loss, "best_step": best_step}

Convergence

photosvi.inference.points.EstimandPlateau

EstimandPlateau(tol=0.02, window=6, min_steps=5000)

Stop when the reported estimand has stopped moving.

Records a value at each probe and reports convergence once the estimand has stopped drifting, which is not the same as it having stopped moving. At a usable learning rate the iterate oscillates around the optimum rather than creeping toward it -- measured at lr=0.01, beta_inj runs 0.714, 0.748, 0.698, 0.741, 0.739 while sitting on its answer. A test on the spread of those values reads that as unconverged and never fires, while a slow creep at lr=0.001 passes it easily and stops the fit 0.09 short. So the criterion compares the mean of the first half of the window against the second: no systematic movement between them, whatever the oscillation amplitude.

Report plateau_mean rather than the last probe. Once the iterate is orbiting, the final value is one draw from the orbit and the average over it is a better estimate.

Parameters:

Name Type Description Default
tol movement of the window's centre, on the log-rate axis, that still counts

as settled. The default of 0.02 is well inside the estimator's own sampling spread across seeds (0.13-0.16), so it is a statement about the optimiser having stopped, not a claim about precision.

0.02
window probes held. Must be even enough to halve; 6 gives three per half.
6
min_steps a floor below which convergence is never declared. Early in a fit

beta_inj passes slowly through the region it starts in, which looks flat at any tolerance -- measured, it sits within 0.02 of its initial value for the first several hundred steps while going nowhere.

5000
Source code in src/photosvi/inference/points/convergence.py
52
53
54
55
56
57
58
59
60
61
62
def __init__(self, tol: float = 0.02, window: int = 6, min_steps: int = 5_000):
    if tol <= 0:
        raise ValueError(f"tol must be > 0 (got {tol})")
    if window < 4:
        raise ValueError(f"window must be >= 4 probes to halve (got {window})")
    self.tol = float(tol)
    self.window = int(window)
    self.min_steps = int(min_steps)
    self._vals: deque[list[float]] = deque(maxlen=self.window)
    self._dim: int | None = None
    self.converged_at: int | None = None

drift property

drift

Largest coordinate drift of the window's centre; NaN until full.

drift_per_coordinate property

drift_per_coordinate

Per-coordinate movement of the window's centre between its halves.

plateau_mean property

plateau_mean

Mean over the window -- the value to report once converged.

Scalar for a scalar estimand; for a vector use plateau_means.

plateau_means property

plateau_means

Per-coordinate mean over the window -- the values to report.

update

update(step, value)

Record a probe; return True once the plateau condition holds.

value may be a scalar or a vector. The cohort estimand is mu_drug, one coordinate per drug, and the criterion is then the worst coordinate's drift: a fit is not finished because the drug that settled first has settled. A scalar is the one-coordinate case of the same rule.

Source code in src/photosvi/inference/points/convergence.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def update(self, step: int, value: float | Sequence[float]) -> bool:
    """Record a probe; return True once the plateau condition holds.

    `value` may be a scalar or a vector. The cohort estimand is `mu_drug`, one
    coordinate per drug, and the criterion is then the **worst** coordinate's
    drift: a fit is not finished because the drug that settled first has
    settled. A scalar is the one-coordinate case of the same rule.
    """
    v = ([float(value)] if isinstance(value, (int, float))
         else [float(x) for x in value])
    if self._dim is None:
        self._dim = len(v)
    elif len(v) != self._dim:
        raise ValueError(
            f"estimand changed width mid-fit: {self._dim} -> {len(v)}"
        )
    self._vals.append(v)
    if step < self.min_steps or len(self._vals) < self.window:
        return False
    if self.drift <= self.tol:
        if self.converged_at is None:
            self.converged_at = step
        return True
    return False

Device selection

photosvi.inference.points.resolve_device

resolve_device(spec='auto', *, batch=1)

Pick a torch device.

Parameters:

Name Type Description Default
spec "auto" (default), "cpu", "cuda", "cuda:1", or a `torch.device`. None is

treated as "auto". An explicit request for CUDA when none is available is an error, not a silent fallback: a run that was launched for the GPU and quietly took 60x longer on CPU is worse than one that refused to start.

'auto'
batch the number of sequences the fit will carry. Only consulted under "auto",

where it selects by the rule in the module docstring.

1
Source code in src/photosvi/inference/points/device.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def resolve_device(spec: str | torch.device | None = "auto", *, batch: int = 1) -> torch.device:
    """Pick a torch device.

    Parameters
    ----------
    spec : "auto" (default), "cpu", "cuda", "cuda:1", or a `torch.device`. None is
        treated as "auto". An explicit request for CUDA when none is available is an
        **error**, not a silent fallback: a run that was launched for the GPU and
        quietly took 60x longer on CPU is worse than one that refused to start.
    batch : the number of sequences the fit will carry. Only consulted under "auto",
        where it selects by the rule in the module docstring.
    """
    if isinstance(spec, torch.device):
        return spec
    s = "auto" if spec is None else str(spec).strip().lower()
    if s == "auto":
        return torch.device("cuda" if (batch >= _BATCH_THRESHOLD
                                       and torch.cuda.is_available()) else "cpu")
    if s == "cpu":
        return torch.device("cpu")
    if s.startswith("cuda"):
        if not torch.cuda.is_available():
            raise RuntimeError(
                f"device {spec!r} was requested but CUDA is not available. Pass "
                "'cpu' or 'auto' to run on CPU -- falling back silently would turn a "
                "GPU-sized run into one that takes far longer without saying so."
            )
        dev = torch.device(s)
        n = torch.cuda.device_count()
        if dev.index is not None and dev.index >= n:
            raise RuntimeError(f"{spec!r} requested but only {n} CUDA device(s) present")
        return dev
    raise ValueError(f"unrecognized device {spec!r}; use 'auto', 'cpu' or 'cuda[:i]'")

photosvi.inference.points.prepare

prepare(model, y, device)

Move a model and its traces onto device together, and set CPU threading.

On CPU the fits are run one-per-process under an external fan-out, so a single torch thread per process is right: the math backends otherwise build an OpenMP pool per worker and oversubscribe the machine several times over. On GPU the thread count is irrelevant and left alone.

Source code in src/photosvi/inference/points/device.py
81
82
83
84
85
86
87
88
89
90
91
92
def prepare(model, y: torch.Tensor, device) -> tuple[object, torch.Tensor]:
    """Move a model and its traces onto `device` together, and set CPU threading.

    On CPU the fits are run one-per-process under an external fan-out, so a single
    torch thread per process is right: the math backends otherwise build an OpenMP
    pool per worker and oversubscribe the machine several times over. On GPU the
    thread count is irrelevant and left alone.
    """
    dev = torch.device(device)
    if dev.type == "cpu":
        torch.set_num_threads(1)
    return model.to(dev), y.to(dev)