diff --git a/biahub/segment.py b/biahub/segment.py index 3d5e2eb51..c09f33b38 100644 --- a/biahub/segment.py +++ b/biahub/segment.py @@ -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, @@ -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: @@ -149,46 +138,24 @@ 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( @@ -196,22 +163,19 @@ def _segment_czyx( 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: @@ -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) @@ -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, diff --git a/biahub/segmentation/__init__.py b/biahub/segmentation/__init__.py new file mode 100644 index 000000000..b77cb1db2 --- /dev/null +++ b/biahub/segmentation/__init__.py @@ -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``. +""" diff --git a/biahub/segmentation/backends.py b/biahub/segmentation/backends.py new file mode 100644 index 000000000..96f18ceb8 --- /dev/null +++ b/biahub/segmentation/backends.py @@ -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, + ), +} diff --git a/biahub/segmentation/devices.py b/biahub/segmentation/devices.py new file mode 100644 index 000000000..79daee2c7 --- /dev/null +++ b/biahub/segmentation/devices.py @@ -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 diff --git a/biahub/segmentation/methods/__init__.py b/biahub/segmentation/methods/__init__.py new file mode 100644 index 000000000..ca8e17e8a --- /dev/null +++ b/biahub/segmentation/methods/__init__.py @@ -0,0 +1 @@ +"""One module per segmentation backend.""" diff --git a/biahub/utils/cellpose.py b/biahub/segmentation/methods/cellpose.py similarity index 73% rename from biahub/utils/cellpose.py rename to biahub/segmentation/methods/cellpose.py index ad874c757..b1bbb5eb2 100644 --- a/biahub/utils/cellpose.py +++ b/biahub/segmentation/methods/cellpose.py @@ -1,6 +1,6 @@ -"""Helpers for running cellpose on the cluster. +"""The cellpose 4 backend of ``biahub segment``, and the problems it works around. -Two problems this module exists to solve, both observed in one overnight run: +Two problems, both observed in one overnight run: * cellpose resolves its own device in ``cellpose.core.assign_device``, which probes CUDA inside a bare ``except: pass`` and quietly returns the CPU whenever the probe @@ -9,8 +9,9 @@ is an NFS export on Bruno. A per-position fan-out reads that one file from dozens of nodes at once. -``cellpose_device`` addresses the first, ``warm_cellpose_weights`` (once, on the -head node) and ``stage_cellpose_weights`` (per worker) the second. +The first is solved for every backend by :func:`biahub.segmentation.devices.segmentation_device`, +the second by ``warm_cellpose_weights`` (once, on the head node) and +``stage_cellpose_weights`` (per worker; the copy itself is :mod:`biahub.segmentation.staging`). A third: cellpose 4 ignores ``model_type`` and falls back to ``cpsam_v2`` with only a log warning when ``pretrained_model`` names a model it does not know. @@ -20,72 +21,25 @@ ``cpdino`` extra installs (it is not on PyPI and has its own licence). Without it cellpose only logs "Could not import CPDINO" and fails when the model is built. ``check_cellpose_model_name`` stops at ``--init`` with the install command instead. + +:func:`segment` runs a loaded model on one CZYX image (the backend's ``segment`` hook). """ import getpass import importlib.util import logging import os -import shutil import sys -import time from pathlib import Path import click +import numpy as np import torch -logger = logging.getLogger(__name__) - -# Attempts for each node-local cellpose weight copy. ESTALE on the NFS home export -# is transient and is the very thing staging exists to avoid, so retry the copy -# before giving up and reading the weights over NFS. See stage_cellpose_weights. -_STAGE_ATTEMPTS = 3 - - -def cellpose_device(gpu: bool) -> torch.device: - """Resolve the torch device for cellpose, refusing a silent CPU fallback. - - Left to itself, cellpose 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. +from biahub.segmentation.staging import _copy_weight - 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 ~130x slower for cellpose. " - "Ask for the CPU explicitly to segment on it deliberately " - "(tracking: cellpose_config.gpu: false)." - ) from exc - return device +logger = logging.getLogger(__name__) def _cellpose_models_dir() -> Path: @@ -94,32 +48,6 @@ def _cellpose_models_dir() -> Path: return Path(env_dir) if env_dir else Path.home() / ".cellpose" / "models" -def _copy_weight(source: Path, dest: Path) -> None: - """Copy ``source`` to ``dest``, skipping a copy that is already there. - - The bytes land on a private temporary name and are renamed into place, so tasks - staging concurrently on the same node never read a half-written file and the - loser of the race just overwrites with identical content. Weights are matched - on size alone: they are ~1.2 GB and immutable once downloaded, so hashing them - on every task would cost more than the read this function avoids. - """ - if dest.is_file() and dest.stat().st_size == source.stat().st_size: - return - - partial = dest.with_name(f".{dest.name}.{os.getpid()}.partial") - for attempt in range(1, _STAGE_ATTEMPTS + 1): - try: - shutil.copyfile(source, partial) - break - except OSError as exc: - partial.unlink(missing_ok=True) - if attempt == _STAGE_ATTEMPTS: - raise - logger.warning("Retrying copy of %s to node-local scratch: %r", source, exc) - time.sleep(attempt) - os.replace(partial, dest) - - def stage_cellpose_weights() -> Path | None: """Cache the cellpose weights on node-local scratch and point cellpose at them. @@ -295,3 +223,21 @@ def warm_cellpose_weights(pretrained_model: str = "cpsam_v2") -> Path | None: click.echo(f"Cellpose weights ready: {weights}") return weights + + +def segment(czyx_data: np.ndarray, model, cellpose_model) -> np.ndarray: + """Segment a CZYX image with a loaded cellpose model; returns (Z, Y, X) labels.""" + # 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. + 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). + return np.reshape(segmentation, image.shape[1:] if model.is_3d else (1, *image.shape[-2:])) diff --git a/biahub/utils/microsam.py b/biahub/segmentation/methods/microsam.py similarity index 88% rename from biahub/utils/microsam.py rename to biahub/segmentation/methods/microsam.py index 38a1976a3..16c6173db 100644 --- a/biahub/utils/microsam.py +++ b/biahub/segmentation/methods/microsam.py @@ -8,6 +8,10 @@ worker copies them to node-local scratch and points micro-sam's cache there (:func:`stage_microsam_weights`), so the jobs do not all read the weights over NFS and the temporary embeddings micro-sam writes for tiled images stay on the node. + +:func:`segment` runs a loaded model on the Z=1 plane of one CZYX image and :func:`check_plane` +refuses a ``downsample`` too large for the plane (the backend's ``segment`` and +``check_plane`` hooks). """ import getpass @@ -21,7 +25,7 @@ import click import numpy as np -from biahub.utils.cellpose import _copy_weight +from biahub.segmentation.staging import _copy_weight logger = logging.getLogger(__name__) @@ -233,3 +237,26 @@ def segment_plane( # Nearest upsampling: each label pixel covers a downsample x downsample block. labels = np.repeat(np.repeat(labels, downsample, axis=0), downsample, axis=1) return labels[: plane.shape[0], : plane.shape[1]].astype(np.uint32) + + +def segment(czyx_data: np.ndarray, model, loaded) -> np.ndarray: + """Segment the model's channel of a Z=1 CZYX image; returns (1, Y, X) labels.""" + # One channel, one Z=1 plane: micro-sam segments the (Y, X) plane. + predictor, segmenter = loaded + plane = czyx_data[model.channel_indices[0], 0] + labels = segment_plane(plane, predictor, segmenter, model.downsample, **model.eval_args) + return labels[np.newaxis] + + +def check_plane(model, y_size: int, x_size: int) -> None: + """Refuse a ``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. + """ + 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." + ) diff --git a/biahub/segmentation/staging.py b/biahub/segmentation/staging.py new file mode 100644 index 000000000..26e5bbcc6 --- /dev/null +++ b/biahub/segmentation/staging.py @@ -0,0 +1,41 @@ +"""Copying model weights to node-local scratch, shared by the segmentation backends.""" + +import logging +import os +import shutil +import time + +from pathlib import Path + +logger = logging.getLogger(__name__) + +# Attempts for each node-local weight copy. ESTALE on the NFS home export is transient +# and is the very thing staging exists to avoid, so retry the copy before giving up and +# reading the weights over NFS. Used by every backend's stage hook. +_STAGE_ATTEMPTS = 3 + + +def _copy_weight(source: Path, dest: Path) -> None: + """Copy ``source`` to ``dest``, skipping a copy that is already there. + + The bytes land on a private temporary name and are renamed into place, so tasks + staging concurrently on the same node never read a half-written file and the + loser of the race just overwrites with identical content. Weights are matched + on size alone: they are ~1.2 GB and immutable once downloaded, so hashing them + on every task would cost more than the read this function avoids. + """ + if dest.is_file() and dest.stat().st_size == source.stat().st_size: + return + + partial = dest.with_name(f".{dest.name}.{os.getpid()}.partial") + for attempt in range(1, _STAGE_ATTEMPTS + 1): + try: + shutil.copyfile(source, partial) + break + except OSError as exc: + partial.unlink(missing_ok=True) + if attempt == _STAGE_ATTEMPTS: + raise + logger.warning("Retrying copy of %s to node-local scratch: %r", source, exc) + time.sleep(attempt) + os.replace(partial, dest) diff --git a/biahub/utils/__init__.py b/biahub/utils/__init__.py index e7cdfc990..72f4b1067 100644 --- a/biahub/utils/__init__.py +++ b/biahub/utils/__init__.py @@ -1,7 +1,6 @@ """Helpers shared across the step CLIs, grouped by concern. * :mod:`biahub.utils.array_ops` -- NumPy cropping and empty-frame detection. -* :mod:`biahub.utils.cellpose` -- cellpose device policy and weight caching. * :mod:`biahub.utils.cluster` -- per-position resource sizing, executor choice. * :mod:`biahub.utils.config` -- YAML configs <-> pydantic settings models. * :mod:`biahub.utils.ngff` -- OME-Zarr store paths, versions, and provenance. diff --git a/biahub/utils/cluster.py b/biahub/utils/cluster.py index 6ecf46a56..792c57f19 100644 --- a/biahub/utils/cluster.py +++ b/biahub/utils/cluster.py @@ -49,7 +49,7 @@ def local_executor_parameters(timeout_min: float, gpu: bool = True) -> dict: SLURM jobs get their GPU from ``slurm_gpus_per_node``/gres and their limit from ``slurm_time``, and ``debug`` runs in-process with the caller's GPU. submitit's local executor ignores both: it sets ``CUDA_VISIBLE_DEVICES`` only from the generic - ``gpus_per_node`` (otherwise every GPU is hidden and ``cellpose_device`` refuses), and + ``gpus_per_node`` (otherwise every GPU is hidden and ``segmentation_device`` refuses), and kills jobs after the generic ``timeout_min`` (default 2 minutes). Note that local jobs all run at once on the same GPU, so keep local runs to a few positions. diff --git a/tests/test_cli/test_segment_cli.py b/tests/test_cli/test_segment_cli.py index fd194750b..4ed212cf0 100644 --- a/tests/test_cli/test_segment_cli.py +++ b/tests/test_cli/test_segment_cli.py @@ -45,7 +45,7 @@ def plate_2d(create_custom_plate, tmp_path): @pytest.fixture def cpu_cellpose(monkeypatch): """Workers ask for the GPU; run the (fake) model on the CPU instead.""" - monkeypatch.setattr("biahub.segment.cellpose_device", lambda gpu: torch.device("cpu")) + monkeypatch.setattr("biahub.segment.segmentation_device", lambda gpu: torch.device("cpu")) @pytest.fixture(autouse=True) @@ -327,7 +327,7 @@ def test_segment_gives_local_jobs_a_gpu( fake_cellpose, plate_2d, segment_config, tmp_path, monkeypatch, cluster, expected ): """submitit's local executor only exposes GPUs through gpus_per_node; without it the - local subprocess runs with CUDA_VISIBLE_DEVICES='' and cellpose_device refuses.""" + local subprocess runs with CUDA_VISIBLE_DEVICES='' and segmentation_device refuses.""" monkeypatch.setattr("biahub.segment.submitit.AutoExecutor", _RecordingExecutor) monkeypatch.delenv("CI", raising=False) # CI forces cluster=debug plate_path, _ = plate_2d diff --git a/tests/test_cli/test_segment_microsam_cli.py b/tests/test_cli/test_segment_microsam_cli.py index b34ebb899..9c1882ab8 100644 --- a/tests/test_cli/test_segment_microsam_cli.py +++ b/tests/test_cli/test_segment_microsam_cli.py @@ -25,7 +25,7 @@ def plate_2d(create_custom_plate, tmp_path): @pytest.fixture def cpu_device(monkeypatch): """Workers ask for the GPU; run the (fake) model on the CPU instead.""" - monkeypatch.setattr("biahub.segment.cellpose_device", lambda gpu: torch.device("cpu")) + monkeypatch.setattr("biahub.segment.segmentation_device", lambda gpu: torch.device("cpu")) @pytest.fixture diff --git a/tests/test_segment_microsam.py b/tests/test_segment_microsam.py index 61c4742a8..a9aab6e99 100644 --- a/tests/test_segment_microsam.py +++ b/tests/test_segment_microsam.py @@ -232,13 +232,13 @@ def test_a_mixed_config_runs_each_backend(fake_cellpose, fake_microsam): def test_check_accepts_a_finetuned_model(fake_microsam): - from biahub.utils.microsam import check_microsam_model + from biahub.segmentation.methods.microsam import check_microsam_model check_microsam_model("hvit_b_cells", "apg") def test_check_refuses_an_unknown_name(fake_microsam): - from biahub.utils.microsam import check_microsam_model + from biahub.segmentation.methods.microsam import check_microsam_model with pytest.raises(ValueError, match="Unknown micro-sam model 'vit_b_lm'"): check_microsam_model("vit_b_lm", "ais") @@ -246,7 +246,7 @@ def test_check_refuses_an_unknown_name(fake_microsam): def test_check_refuses_a_backbone_without_decoder_for_ais(fake_microsam): # The plain SAM2 backbones have no decoder: only AMG can use them. - from biahub.utils.microsam import check_microsam_model + from biahub.segmentation.methods.microsam import check_microsam_model with pytest.raises(ValueError, match="amg"): check_microsam_model("hvit_b", "ais") @@ -254,21 +254,21 @@ def test_check_refuses_a_backbone_without_decoder_for_ais(fake_microsam): def test_check_says_how_to_install_micro_sam(no_microsam): - from biahub.utils.microsam import check_microsam_model + from biahub.segmentation.methods.microsam import check_microsam_model with pytest.raises(ImportError, match=r"biahub\[microsam\]"): check_microsam_model("hvit_b_cells", "ais") def test_warm_fetches_the_model_and_its_decoder(fake_microsam): - from biahub.utils.microsam import warm_microsam_weights + from biahub.segmentation.methods.microsam import warm_microsam_weights warm_microsam_weights("hvit_b_cells") assert fake_microsam.fetched == ["hvit_b_cells", "hvit_b_cells_decoder"] def test_warm_skips_a_checkpoint_file(fake_microsam, tmp_path): - from biahub.utils.microsam import warm_microsam_weights + from biahub.segmentation.methods.microsam import warm_microsam_weights ckpt = tmp_path / "best.pt" ckpt.write_bytes(b"") @@ -289,7 +289,7 @@ def test_warm_skips_a_checkpoint_file(fake_microsam, tmp_path): ], ) def test_check_accepts_the_engines_own_eval_args(fake_microsam, engine, eval_args): - from biahub.utils.microsam import check_microsam_model + from biahub.segmentation.methods.microsam import check_microsam_model check_microsam_model("hvit_b_cells", engine, eval_args) @@ -307,14 +307,14 @@ def test_check_accepts_the_engines_own_eval_args(fake_microsam, engine, eval_arg def test_check_refuses_eval_args_the_engine_does_not_take( fake_microsam, engine, eval_args, bad ): - from biahub.utils.microsam import check_microsam_model + from biahub.segmentation.methods.microsam import check_microsam_model with pytest.raises(ValueError, match=rf"{bad}.*{engine}"): check_microsam_model("hvit_b_cells", engine, eval_args) def test_check_refuses_an_unknown_ais_mode(fake_microsam): - from biahub.utils.microsam import check_microsam_model + from biahub.segmentation.methods.microsam import check_microsam_model with pytest.raises(ValueError, match="mode"): check_microsam_model("hvit_b_cells", "ais", {"mode": "watershed"}) @@ -341,7 +341,7 @@ def test_stage_copies_the_model_and_decoder_to_scratch(fake_microsam): from pathlib import Path - from biahub.utils.microsam import stage_microsam_weights + from biahub.segmentation.methods.microsam import stage_microsam_weights shared = _shared_weights(["hvit_b_cells", "hvit_b_cells_decoder", "hvit_t_cells"]) dest = stage_microsam_weights(["hvit_b_cells"]) @@ -357,7 +357,7 @@ def test_stage_copies_the_model_and_decoder_to_scratch(fake_microsam): def test_stage_twice_is_a_no_op(fake_microsam): - from biahub.utils.microsam import stage_microsam_weights + from biahub.segmentation.methods.microsam import stage_microsam_weights _shared_weights(["hvit_b_cells", "hvit_b_cells_decoder"]) first = stage_microsam_weights(["hvit_b_cells"]) @@ -369,7 +369,7 @@ def test_stage_without_shared_weights_still_moves_the_cache_to_scratch(fake_micr # temporary embeddings must still not be written to the shared cache. import os - from biahub.utils.microsam import stage_microsam_weights + from biahub.segmentation.methods.microsam import stage_microsam_weights dest = stage_microsam_weights(["hvit_b_cells"]) assert os.environ["MICROSAM_CACHEDIR"] == os.fspath(dest) @@ -392,7 +392,7 @@ def test_segment_stages_before_building_the_model(fake_microsam): def test_warm_fetches_a_plain_backbone(fake_microsam): - from biahub.utils.microsam import warm_microsam_weights + from biahub.segmentation.methods.microsam import warm_microsam_weights warm_microsam_weights("hvit_b") assert fake_microsam.fetched == ["hvit_b"] diff --git a/tests/test_segmentation/test_backends.py b/tests/test_segmentation/test_backends.py new file mode 100644 index 000000000..40dce29e7 --- /dev/null +++ b/tests/test_segmentation/test_backends.py @@ -0,0 +1,56 @@ +"""biahub/segmentation: the backend registry and the hooks segment calls.""" + +import typing + +import numpy as np + + +def test_every_backend_a_config_can_name_is_registered(): + from biahub.segmentation.backends import BACKENDS + from biahub.settings import SegmentationModelConfig + + # SegmentationModelConfig = Annotated[Annotated[A, Tag] | Annotated[B, Tag] | ..., Discriminator] + union = typing.get_args(SegmentationModelConfig)[0] + classes = [typing.get_args(member)[0] for member in typing.get_args(union)] + names = {typing.get_args(cls.model_fields["backend"].annotation)[0] for cls in classes} + assert len(classes) >= 2 + assert names == set(BACKENDS) + + +def test_segment_stages_cellpose_weights_before_loading_the_model(fake_cellpose, monkeypatch): + """Workers must copy the weights to scratch before cellpose is imported and loaded.""" + import biahub.segmentation.methods.cellpose as cellpose_method + + from biahub.segment import _segment_czyx, resolve_models + from biahub.settings import SegmentationSettings + + calls = [] + real_load = cellpose_method.load_cellpose_model + monkeypatch.setattr( + cellpose_method, "stage_cellpose_weights", lambda: calls.append("stage") + ) + monkeypatch.setattr( + cellpose_method, + "load_cellpose_model", + lambda name, device: calls.append("load") or real_load(name, device), + ) + settings = SegmentationSettings( + models={"nuclei": {"pretrained_model": "cpsam_v2", "channels": ["c0"]}} + ) + models = resolve_models(settings, ["c0"], scale=(1,) * 5, z_size=1) + + _segment_czyx(np.zeros((1, 1, 8, 8), np.float32), models, gpu=False) + + assert calls == ["stage", "load"] + + +def test_backend_hooks_take_models(): + """warm and stage take resolved models, like load / segment / check_plane.""" + import inspect + + from biahub.segmentation.backends import BACKENDS + + for name, backend in BACKENDS.items(): + for hook in ("warm", "stage", "load", "segment", "check_plane"): + first = next(iter(inspect.signature(getattr(backend, hook)).parameters)) + assert first in ("model", "models", "czyx_data"), (name, hook, first) diff --git a/tests/test_utils/test_cellpose.py b/tests/test_segmentation/test_cellpose.py similarity index 86% rename from tests/test_utils/test_cellpose.py rename to tests/test_segmentation/test_cellpose.py index 27f3cb4f4..ac427adc4 100644 --- a/tests/test_utils/test_cellpose.py +++ b/tests/test_segmentation/test_cellpose.py @@ -6,10 +6,9 @@ import pytest import torch -import biahub.utils.cellpose as cellpose_utils +import biahub.segmentation.methods.cellpose as cellpose_method -from biahub.utils.cellpose import ( - cellpose_device, +from biahub.segmentation.methods.cellpose import ( check_cellpose_model_name, load_cellpose_model, stage_cellpose_weights, @@ -17,27 +16,6 @@ ) -def test_cellpose_device_cpu_when_not_requested(): - assert cellpose_device(gpu=False) == torch.device("cpu") - - -def test_cellpose_device_raises_instead_of_falling_back(monkeypatch): - """An unusable GPU must fail loudly, not silently segment on the CPU.""" - - def unavailable(*args, **kwargs): - raise RuntimeError("CUDA error: all CUDA-capable devices are busy or unavailable") - - monkeypatch.setattr(torch, "zeros", unavailable) - monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "3") - - with pytest.raises(RuntimeError, match="Refusing to fall back to the CPU") as excinfo: - cellpose_device(gpu=True) - - # The message has to carry enough to debug the node it happened on. - assert "CUDA_VISIBLE_DEVICES='3'" in str(excinfo.value) - assert "busy or unavailable" in str(excinfo.value) - - @pytest.fixture() def cellpose_cache(tmp_path, monkeypatch): """A shared weights directory and an empty node-local scratch to stage into.""" @@ -180,7 +158,7 @@ def __init__(self, pretrained_model, gpu, device): _fake_cellpose(monkeypatch, FakeModel) sys.modules["cellpose.models"].MODEL_NAMES = ["cpsam_v2", "cpdino"] sys.modules["cellpose.models"].get_user_models = lambda: [] - monkeypatch.setattr(cellpose_utils, "_dinov3_installed", lambda: True) + monkeypatch.setattr(cellpose_method, "_dinov3_installed", lambda: True) load_cellpose_model("cpdino", torch.device("cpu")) assert built == {"pretrained_model": "cpdino", "gpu": False} @@ -196,7 +174,7 @@ def _known_models(monkeypatch): def test_cpdino_without_dinov3_says_how_to_install(monkeypatch, name): """cellpose only warns 'Could not import CPDINO' and fails later; stop at init instead.""" _known_models(monkeypatch) - monkeypatch.setattr(cellpose_utils, "_dinov3_installed", lambda: False) + monkeypatch.setattr(cellpose_method, "_dinov3_installed", lambda: False) with pytest.raises(ValueError, match="dinov3") as excinfo: check_cellpose_model_name(name) @@ -228,13 +206,13 @@ def test_cpdino_extra_is_opt_in_and_pinned(): def test_cpdino_with_dinov3_passes(monkeypatch): _known_models(monkeypatch) - monkeypatch.setattr(cellpose_utils, "_dinov3_installed", lambda: True) + monkeypatch.setattr(cellpose_method, "_dinov3_installed", lambda: True) check_cellpose_model_name("cpdino") def test_cpsam_does_not_need_dinov3(monkeypatch): _known_models(monkeypatch) - monkeypatch.setattr(cellpose_utils, "_dinov3_installed", lambda: False) + monkeypatch.setattr(cellpose_method, "_dinov3_installed", lambda: False) check_cellpose_model_name("cpsam_v2") diff --git a/tests/test_segmentation/test_devices.py b/tests/test_segmentation/test_devices.py new file mode 100644 index 000000000..88c01685a --- /dev/null +++ b/tests/test_segmentation/test_devices.py @@ -0,0 +1,27 @@ +"""The device every segmentation job runs on: a GPU, or a loud failure, never a silent CPU.""" + +import pytest +import torch + +from biahub.segmentation.devices import segmentation_device + + +def test_segmentation_device_cpu_when_not_requested(): + assert segmentation_device(gpu=False) == torch.device("cpu") + + +def test_segmentation_device_raises_instead_of_falling_back(monkeypatch): + """An unusable GPU must fail loudly, not silently segment on the CPU.""" + + def unavailable(*args, **kwargs): + raise RuntimeError("CUDA error: all CUDA-capable devices are busy or unavailable") + + monkeypatch.setattr(torch, "zeros", unavailable) + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "3") + + with pytest.raises(RuntimeError, match="Refusing to fall back to the CPU") as excinfo: + segmentation_device(gpu=True) + + # The message has to carry enough to debug the node it happened on. + assert "CUDA_VISIBLE_DEVICES='3'" in str(excinfo.value) + assert "busy or unavailable" in str(excinfo.value)