Skip to content

refactor(segment): move the segmentation library code into biahub/segmentation - #511

Merged
tayllatheodoro merged 9 commits into
mainfrom
refactor/segmentation-package
Dec 1, 2026
Merged

tayllatheodoro merged 9 commits into
mainfrom
refactor/segmentation-package

Conversation

@tayllatheodoro

@tayllatheodoro tayllatheodoro commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Implements step 1 of #504: move the segmentation library code into a biahub/segmentation/ package, the same way #454 did for tracking. There is no behaviour change.

Stacked on #494 (micro-sam backend): the base is feat/segment-microsam, so the diff shows only the refactor. I'll retarget it to main once #494 merges.

Layout

biahub/
├── segment.py                 CLI and orchestration: resolve_models, label images and provenance, resume,
│                              resources, SLURM/local/debug, model cache, check_plane_size.
│                              Looks backends up in BACKENDS instead of branching on model.backend.
├── segmentation/
│   ├── __init__.py            library code only, no plate I/O (like biahub/tracking)
│   ├── backends.py            Backend hooks (check, warm, stage, load, segment, check_plane) + BACKENDS
│   ├── devices.py             segmentation_device (was cellpose_device): the GPU / no-CPU-fallback policy
│   ├── staging.py             _copy_weight: node-local weight copy with retries, used by both backends
│   └── methods/
│       ├── cellpose.py        was biahub/utils/cellpose.py, + segment()
│       └── microsam.py        was biahub/utils/microsam.py (#494), + segment() and check_plane()
└── utils/                     only the shared step helpers now (array_ops, cluster, config, ngff, notify)

Every hook takes models: check the configured model, the others models resolved against the plate (stage all of the backend's models in the job). check_plane defaults to accepting every plane.

hook runs on cellpose micro-sam
check head node (--init; every path for micro-sam) check_cellpose_model_name check_microsam_model
warm head node, --init warm_cellpose_weights warm_microsam_weights
stage worker, before the import stage_cellpose_weights stage_microsam_weights
load worker, cached per process load_cellpose_model load_microsam_model
segment worker, per timepoint the cellpose branch of _segment_czyx the micro-sam branch
check_plane head node no-op the body of check_plane_size

To add a backend: one module in methods/, one entry in BACKENDS, and its settings class in settings.py. segment.py doesn't change.

What stays the same

  • Moved code is identical: all 22 definitions moved from utils/cellpose.py and utils/microsam.py are AST-identical to their old versions (checked with an ast.dump comparison). The only new code is the registry and the per-backend segment / check_plane, lifted from segment.py.
  • segment.py's names: segmentation_device, stage_cellpose_weights (head-node path), _MODEL_CACHE and check_plane_size stay in segment.py's namespace. A patch of biahub.segment.stage_cellpose_weights reaches only the head-node call: the worker staging goes through the backend hook, so it is tested on its own (see Tests).
  • No re-export of biahub/utils/cellpose.py: a GitHub code search across Biohub and czbiohub-sf finds no import of it outside biahub. utils/microsam.py was never released.

Tests

  • Changed tests: import paths and the patch target biahub.segment.segmentation_device. The four tests that patch _dinov3_installed now patch biahub.segmentation.methods.cellpose. tests/test_utils/test_cellpose.py moved to tests/test_segmentation/test_cellpose.py, with the device tests in test_devices.py.
  • New tests (tests/test_segmentation/test_backends.py):
    • every backend class in SegmentationModelConfig is registered
    • _segment_czyx stages cellpose weights before loading the model. Nothing tested this before, on main either: disabling the stage hook left every test green. With the hook disabled, this test now fails.
    • every hook takes models
  • Full suite: pytest 1233 passed, 18 skipped, with main merged into feat(segment): micro-sam 2 as a segmentation backend (backend: microsam) #494. ruff check and ruff format --check are clean.
  • Real data: one config with a cellpose model (cpsam_v2) and a micro-sam model (hvit_b_cells, APG, downsample: 4) on a Z=1 copy of 2026_04_28 A/2/001002 (67 frames), run through feat(segment): micro-sam 2 as a segmentation backend (backend: microsam) #494 and through this branch. Both label images and their recorded provenance are identical on every frame. I ran it again after the review fixes: still identical.
  • Reviews: three independent reviews (Opus, Sonnet, Fable) found no behaviour change. Their findings (the staging-test gap, the registry test, hook signatures, the cellpose-named device, stale docstrings) are fixed in aacea1e. Logger names now follow the modules (biahub.segmentation.*); nothing filters on the old ones.

Not in this PR

The preprocess.py / postprocess.py modules and the follow-up ideas in #504 (classical backends, physical-unit size filters, consensus) each get their own PR.

A segment model can now set `backend: microsam` to run micro-sam 2 (SAM2)
automatic instance segmentation instead of cellpose 4. Configs without
`backend` stay cellpose, and a cellpose model's recorded settings and resume
token are unchanged (the field is excluded from dumps).

- MicroSamModel: pretrained_model (micro-sam 2 name or checkpoint path),
  one channel, engine ais|apg|amg, downsample (stride, labels scaled back to
  the input grid), eval_args forwarded to micro-sam's post-processing.
  2D (Z=1) plates only. Models of both backends can share one config.
- --init stops when micro_sam is missing (names the extra), on an unknown
  model, or on a SAM2 backbone with ais/apg (no decoder); it fetches the
  weights once on the head node.
- Opt-in extra `microsam` (not in `all`): micro_sam==2.0.1 plus Meta's SAM2
  from git. micro_sam pins the PyPI `sam2`, a third-party fork upload; a uv
  override drops it. The lock now resolves pydantic 2.13.5 (micro_sam caps
  <2.14).
Diffed the sam2 1.1.0 sdist against facebookresearch/sam2 at 2b90b9f: the
sam2 package is identical; only setup.py's name, version, URL and author
differ (micro_sam's setup.cfg says the same). Keep installing SAM2 from
Meta's repo with the uv override, but describe it as installing from the
original source, and say that pip (which installs both) gets the same code.
…scratch

Review fixes for the micro-sam backend:

- eval_args are checked against the engine micro-sam will run, read from the
  signatures of the callables that receive them (AIS flow / multicut by mode,
  APG and AMG generate). A typo, a cellpose argument or min_size with amg
  (which calls it min_object_size) used to pass --init and then fail with a
  TypeError in every GPU job. micro-sam models are now checked on every
  head-node path (--init, SLURM, local, debug), before labels are created.
- stage_microsam_weights copies the model and decoder to node-local scratch
  ($TMPDIR/micro_sam-<user>) and points MICROSAM_CACHEDIR there, like
  stage_cellpose_weights: jobs no longer all read the weights over NFS, and
  the temporary embeddings micro-sam writes for tiled AIS go to scratch.
- --init refuses a downsample that leaves fewer than 2 pixels along Y or X
  (micro-sam squeezed the axis and failed in the job).
- warm_microsam_weights also prefetches plain SAM2 backbones.
- Docs: eval_args keys depend on the engine and sizes are in downsampled
  pixels; the pydantic<2.14 cap applies to every install from uv.lock.
- Tests: the micro-sam stand-in returns one id per pixel, so the upsampling
  test checks where each label lands, and carries micro-sam's real
  post-processing signatures.
biahub's nuclei label image is labels/nuclei (a549 segment.yml model name,
track.yml labels: nuclei, tracks_nuclei in QC, the VS channel
nuclei_prediction). The micro-sam example and its tests used nucleus.
The example segmentation config called it nucleus, while the example track
config (and the a549 configs) read labels: nuclei.
…mentation

Implements #504, step 1 (no behaviour change). Stacked on #494.

- biahub/segmentation/methods/cellpose.py and methods/microsam.py: the
  former biahub/utils/cellpose.py and utils/microsam.py, plus each backend's
  `segment` (the per-backend branches of _segment_czyx) and micro-sam's
  `check_plane` (the body of check_plane_size).
- biahub/segmentation/staging.py (_copy_weight, shared by both backends) and
  devices.py (cellpose_device, used by both).
- biahub/segmentation/backends.py: BACKENDS registry with the hooks check,
  warm, stage, load, segment and check_plane; segment.py looks backends up
  instead of branching on model.backend. segment.py keeps the CLI, the label
  images, resume, resources and the model cache.
- All 22 moved definitions are AST-identical to their old versions.
- biahub/utils/cellpose.py is removed without a re-export: nothing outside
  biahub imports it (GitHub code search over Biohub / czbiohub-sf).
- Tests: import paths only (patches of _dinov3_installed now target the new
  module), plus tests/test_segmentation_package.py (every backend a config
  can name is registered).
ieivanov
ieivanov previously approved these changes Nov 30, 2026
From three independent reviews of #511 (no behaviour change):

- Test that _segment_czyx stages cellpose weights before loading the model.
  Disabling the cellpose stage hook left every test green; the old test only
  reached the head-node staging call. The micro-sam equivalent existed.
- The registry test reads the backend classes from SegmentationModelConfig
  instead of listing them, so a third backend cannot be missed.
- Hooks take models: warm(model), stage(models) like load, segment and
  check_plane; named functions instead of lambdas, typed; check_plane
  defaults to accepting every plane.
- cellpose_device -> segmentation_device (it serves every backend); its
  docstring and error text no longer assume cellpose, and drop the stale
  tracking: cellpose_config.gpu hint.
- Docstrings and comments that still described the old layout: the cellpose
  and micro-sam module docstrings, the staging comment, segment.py's GPU
  comments.
- tests/test_utils/test_cellpose.py -> tests/test_segmentation/test_cellpose.py
  (device tests split into test_devices.py), test_segmentation_package.py ->
  tests/test_segmentation/test_backends.py.

Logger names follow the modules (biahub.segmentation.*); nothing filters on
the old ones.
…-package

# Conflicts:
#	biahub/segment.py
#	tests/test_cli/test_segment_microsam_cli.py
#	tests/test_segment_microsam.py
@tayllatheodoro
tayllatheodoro changed the base branch from feat/segment-microsam to main November 30, 2026 23:44
@tayllatheodoro
tayllatheodoro dismissed ieivanov’s stale review November 30, 2026 23:44

The base branch was changed.

@tayllatheodoro

Copy link
Copy Markdown
Collaborator Author

Hi Ivan, merging #494 and retargeting this PR to main dismissed your approval (GitHub does that on a base change). The code is what you approved, plus aacea1e: fixes from three extra reviews, no behaviour change. CI passes on main. Could you re-approve? Thanks!

@tayllatheodoro
tayllatheodoro merged commit 62f51ec into main Dec 1, 2026
7 checks passed
@tayllatheodoro
tayllatheodoro deleted the refactor/segmentation-package branch December 1, 2026 01:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants