Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 20 additions & 83 deletions biahub/segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,10 @@
sbatch_filepath,
sbatch_to_submitit,
)
from biahub.segmentation.backends import BACKENDS
from biahub.segmentation.devices import segmentation_device
from biahub.segmentation.methods.cellpose import stage_cellpose_weights
from biahub.settings import SegmentationSettings
from biahub.utils.cellpose import (
cellpose_device,
check_cellpose_model_name,
load_cellpose_model,
stage_cellpose_weights,
warm_cellpose_weights,
)
from biahub.utils.cluster import (
apply_sbatch_overrides,
echo_resources,
Expand All @@ -37,13 +33,6 @@
local_executor_parameters,
)
from biahub.utils.config import settings_fingerprint, yaml_to_model
from biahub.utils.microsam import (
check_microsam_model,
load_microsam_model,
segment_plane,
stage_microsam_weights,
warm_microsam_weights,
)
from biahub.utils.ngff import label_layout

if TYPE_CHECKING:
Expand Down Expand Up @@ -149,69 +138,44 @@ def index(name: str, what: str) -> int:
def _cached_model(model: ResolvedModel, device: "torch.device") -> Any:
key = (model.backend, model.pretrained_model, model.engine, str(device))
if key not in _MODEL_CACHE:
if model.backend == "microsam":
_MODEL_CACHE[key] = load_microsam_model(
model.pretrained_model, model.engine, device
)
else:
_MODEL_CACHE[key] = load_cellpose_model(model.pretrained_model, device)
_MODEL_CACHE[key] = BACKENDS[model.backend].load(model, device)
return _MODEL_CACHE[key]


def _check_model(model) -> None:
"""Raise if a configured model cannot run (unknown name, missing extra, bad eval_args)."""
if model.backend == "microsam":
check_microsam_model(model.pretrained_model, model.engine, model.eval_args)
else:
check_cellpose_model_name(model.pretrained_model)
BACKENDS[model.backend].check(model)


def check_plane_size(models: list[ResolvedModel], y_size: int, x_size: int) -> None:
"""Refuse a micro-sam ``downsample`` that leaves fewer than 2 pixels along Y or X.

micro-sam squeezes a singleton axis and then cannot read the plane as 2D.
"""
"""Refuse a plane a model cannot segment (a micro-sam ``downsample`` too large for it)."""
for model in models:
if model.backend != "microsam":
continue
small = (-(-y_size // model.downsample), -(-x_size // model.downsample))
if min(small) < 2:
raise ValueError(
f"Model {model.name}: downsample {model.downsample} turns the "
f"{y_size} x {x_size} plane into {small[0]} x {small[1]} pixels; micro-sam "
"needs at least 2 along each axis. Lower downsample."
)
BACKENDS[model.backend].check_plane(model, y_size, x_size)


def _warm_model(model) -> None:
"""Fetch a configured model's weights into its shared cache (head node, --init)."""
if model.backend == "microsam":
warm_microsam_weights(model.pretrained_model)
else:
warm_cellpose_weights(model.pretrained_model)
BACKENDS[model.backend].warm(model)


def _segment_czyx(
czyx_data: np.ndarray,
models: list[ResolvedModel],
gpu: bool = True,
) -> np.ndarray:
"""Segment a CZYX image with each resolved model (cellpose 4 or micro-sam 2).
"""Segment a CZYX image with each resolved model.

Returns an array of shape (n_models, Z, Y, X); Z is 1 for 2D models.
"""
# Every job this step submits asks SLURM for a GPU, so an unusable one is a
# broken allocation, not a reason to fall back to a ~130x slower CPU run.
device = cellpose_device(gpu)
if any(m.backend == "cellpose" for m in models):
# Stage weights on node-local scratch before cellpose is first imported (no-op
# after).
stage_cellpose_weights()
microsam_models = [m.pretrained_model for m in models if m.backend == "microsam"]
if microsam_models:
# Same for micro-sam: its weights and temporary embeddings go to node-local
# scratch (no-op after the first timepoint).
stage_microsam_weights(microsam_models)
# broken allocation, not a reason to fall back to a far slower CPU run.
device = segmentation_device(gpu)
# Stage each backend's weights on node-local scratch before it is first imported
# (no-op after the first timepoint).
for name, backend in BACKENDS.items():
backend_models = [m for m in models if m.backend == name]
if backend_models:
backend.stage(backend_models)

czyx_segmentation = []
for model in models:
Expand All @@ -221,35 +185,8 @@ def _segment_czyx(
f"Processing with {func.__name__} with kwargs {kwargs} to channel {c_idx}"
)
czyx_data[c_idx] = func(czyx_data[c_idx], **kwargs)

if model.backend == "microsam":
# One channel, one Z=1 plane: micro-sam segments the (Y, X) plane.
predictor, segmenter = _cached_model(model, device)
plane = czyx_data[model.channel_indices[0], 0]
labels = segment_plane(
plane, predictor, segmenter, model.downsample, **model.eval_args
)
czyx_segmentation.append(labels[np.newaxis])
continue

# Cellpose 4 refuses a z axis for 2D processing, so a 2D model gets the (C, Y, X)
# plane of the Z=1 input and a 3D model the (C, Z, Y, X) stack. It also ignores
# `channels` and keeps the first 3 channels it is given, so pass only the
# configured ones.
cellpose_model = _cached_model(model, device)
if model.is_3d:
image, z_axis = czyx_data[model.channel_indices], 1
else:
image, z_axis = czyx_data[model.channel_indices, 0], None
segmentation, _, _ = cellpose_model.eval(
image, channel_axis=0, z_axis=z_axis, **model.eval_args
)
# Cellpose squeezes singleton axes; restore the (Z, Y, X) shape the output
# plate expects (Z is 1 for a 2D model).
segmentation = np.reshape(
segmentation, image.shape[1:] if model.is_3d else (1, *image.shape[-2:])
)
czyx_segmentation.append(segmentation)
loaded = _cached_model(model, device)
czyx_segmentation.append(BACKENDS[model.backend].segment(czyx_data, model, loaded))
return np.stack(czyx_segmentation, axis=0)


Expand Down Expand Up @@ -460,7 +397,7 @@ def segment(
"slurm_cpus_per_task": num_cpus,
"slurm_array_parallelism": 100, # process up to 100 positions at a time
"slurm_time": time_minutes,
# cellpose runs on the GPU; the non-preemptible `gpu` partition keeps long
# the models run on the GPU; the non-preemptible `gpu` partition keeps long
# per-position jobs from being evicted. Override via --sbatch-filepath.
"slurm_partition": "gpu",
"slurm_gpus_per_node": 1,
Expand Down
6 changes: 6 additions & 0 deletions biahub/segmentation/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""Segmentation library code: one module per backend (``methods/``) and what they share.

``biahub segment`` (the CLI, the label images in the plate, resume, resources, SLURM fan-out)
stays in ``biahub/segment.py``, which looks backends up in :mod:`biahub.segmentation.backends`.
The modules here do no plate (OME-Zarr) I/O, like ``biahub/tracking``.
"""
110 changes: 110 additions & 0 deletions biahub/segmentation/backends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""The segmentation backends ``biahub segment`` can run, keyed by a model's ``backend``.

Each backend provides the same hooks, so ``biahub/segment.py`` looks them up instead of
branching on the backend:

================= =========================== =============================================
hook runs on does
================= =========================== =============================================
``check`` head node refuse a model that cannot run (name, extra,
arguments) before anything is scaffolded
``warm`` head node, ``--init`` fetch the weights into the shared cache once
``stage`` worker, before the import copy the weights to node-local scratch
``load`` worker, cached per process build the model on a device
``segment`` worker, per timepoint CZYX image -> (Z, Y, X) labels
``check_plane`` head node refuse a plane the model cannot segment
================= =========================== =============================================

``check`` takes the model as configured (a ``biahub.settings`` model: it runs before the
config is resolved against a plate); the other hooks take models resolved against the
input plate (``biahub.segment.ResolvedModel``), ``stage`` all of the backend's models in
the job. ``check_plane`` defaults to accepting every plane.

To add a backend: a module in ``methods/`` with these functions, its settings class in
``biahub/settings.py`` (with a ``backend`` literal and a ``Tag`` in
``SegmentationModelConfig``), and an entry in :data:`BACKENDS`.
"""

from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

from biahub.segmentation.methods import cellpose, microsam

if TYPE_CHECKING:
import numpy as np
import torch

from biahub.segment import ResolvedModel


def _accept_every_plane(model: "ResolvedModel", y_size: int, x_size: int) -> None:
return None


@dataclass(frozen=True)
class Backend:
check: Callable[[Any], None]
warm: Callable[["ResolvedModel"], Any]
stage: Callable[[list["ResolvedModel"]], Any]
load: Callable[["ResolvedModel", "torch.device"], Any]
segment: Callable[["np.ndarray", "ResolvedModel", Any], "np.ndarray"]
check_plane: Callable[["ResolvedModel", int, int], None] = _accept_every_plane


# --- cellpose 4


def _cellpose_check(model) -> None:
cellpose.check_cellpose_model_name(model.pretrained_model)


def _cellpose_warm(model: "ResolvedModel"):
return cellpose.warm_cellpose_weights(model.pretrained_model)


def _cellpose_stage(models: list["ResolvedModel"]):
# cellpose stages its whole weights directory, whatever the models.
return cellpose.stage_cellpose_weights()


def _cellpose_load(model: "ResolvedModel", device: "torch.device"):
return cellpose.load_cellpose_model(model.pretrained_model, device)


# --- micro-sam 2


def _microsam_check(model) -> None:
microsam.check_microsam_model(model.pretrained_model, model.engine, model.eval_args)


def _microsam_warm(model: "ResolvedModel"):
return microsam.warm_microsam_weights(model.pretrained_model)


def _microsam_stage(models: list["ResolvedModel"]):
return microsam.stage_microsam_weights([m.pretrained_model for m in models])


def _microsam_load(model: "ResolvedModel", device: "torch.device"):
return microsam.load_microsam_model(model.pretrained_model, model.engine, device)


BACKENDS: dict[str, Backend] = {
"cellpose": Backend(
check=_cellpose_check,
warm=_cellpose_warm,
stage=_cellpose_stage,
load=_cellpose_load,
segment=cellpose.segment,
),
"microsam": Backend(
check=_microsam_check,
warm=_microsam_warm,
stage=_microsam_stage,
load=_microsam_load,
segment=microsam.segment,
check_plane=microsam.check_plane,
),
}
50 changes: 50 additions & 0 deletions biahub/segmentation/devices.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""The torch device a segmentation job runs on, for every backend."""

import os

import torch


def segmentation_device(gpu: bool) -> torch.device:
"""Resolve the torch device for segmentation, refusing a silent CPU fallback.

The backends then run on this device instead of choosing their own. Left to itself,
cellpose (for example) picks its device in ``cellpose.core.assign_device``,
which probes CUDA inside a bare ``except: pass`` and quietly returns the CPU
whenever the probe fails — a transient CUDA init error on a busy node included.
Nothing in the logs distinguishes the two devices, and on an A6000 against a
1664x1193 frame the CPU is 130x slower (2.0 s vs 264 s per frame), so a
three-minute task silently runs for hours. Probing here surfaces the real CUDA
error and fails the task in seconds instead, which lets the caller (or the
workflow) retry on a fresh allocation.

Parameters
----------
gpu : bool
Whether GPU segmentation was requested.

Returns
-------
torch.device
``cuda:0`` — the GPU SLURM allocated, via CUDA_VISIBLE_DEVICES — when
``gpu`` is set, ``cpu`` otherwise.

Raises
------
RuntimeError
If ``gpu`` is set but CUDA cannot be used on this host.
"""
if not gpu:
return torch.device("cpu")

device = torch.device("cuda:0")
try:
torch.zeros(1).to(device)
except Exception as exc:
raise RuntimeError(
"GPU segmentation was requested but CUDA is unusable on this host "
f"(CUDA_VISIBLE_DEVICES={os.environ.get('CUDA_VISIBLE_DEVICES')!r}): {exc}. "
"Refusing to fall back to the CPU, which is far slower (~130x for cellpose). "
"Rerun on a node with a working GPU."
) from exc
return device
1 change: 1 addition & 0 deletions biahub/segmentation/methods/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""One module per segmentation backend."""
Loading