diff --git a/AGENTS.md b/AGENTS.md index 39b56123..bb6546b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -291,8 +291,14 @@ src/morphobricks_preprocessing/ channel_by_number (a channel number only when every image has the same channel IDs at the same C positions, translated once to the ID; #440); segmentation_cellpose_model.py choose_model (a built-in name or an existing file, - before loading), load_model (the weights file and device verified after loading, no - download without allow_download, SHA-256 recorded, DINOv3 at a pinned commit); + before loading), load_model (the weights file and device verified after loading, + SHA-256 recorded, DINOv3 installed at a pinned commit on a cpdino model's first + load: ensure_dinov3); segmentation_cellpose_weights.py fetch_weights: the chosen + built-in model's file only, from a pinned Hugging Face revision, checked against + its pinned SHA-256 (a cached copy too), a failed download a refusal (owner, + #574: choosing the model and loading it is the consent; no tick); + segmentation_cellpose_eval.py eval_arguments, inference_parameters (what + model.eval is given and what the batch records); notebook_cellpose.py CellposeWorkflow, ChannelPicker, CellStop: the widgets behind notebooks/MorphoBricks_Cellpose.ipynb notebook_stop.py CellStop (one line, no traceback), defined once: cells 2-8 diff --git a/CHANGELOG.md b/CHANGELOG.md index 841cf7f1..2073ff78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **Cellpose: no download ticks; the chosen model's weights download on first use, pinned and checked (v0.9.1, #574 item 3; owner decision of 26 November 2026).** Choosing the model and pressing **Preview** or **Segment** (or **Load the model** in the Cellpose notebook) is now the consent to download its weights: the "Allow the weights download from Hugging Face" and "Install DINOv3 now" ticks are removed from the model form (both notebooks share it). Cellpose no longer downloads anything itself: the new `segmentation_cellpose_weights.fetch_weights` downloads only the chosen model's file from `mouseland/cellpose-sam` at the pinned commit `WEIGHTS_REVISION` (`7c61431b5fbb`, not Cellpose's moving `main`, and with TLS verification, which Cellpose's own download turns off), through a temporary file kept only with the pinned size and SHA-256 (`PINNED_WEIGHTS`, as Hugging Face lists them at that commit), then hands Cellpose the absolute path. A copy already in Cellpose's model folder is hashed and must match the pin; one that differs is refused, not used and not replaced. The file's identity (device, inode, size, modification time) taken when it is hashed must be unchanged right before Cellpose opens it and after Cellpose loaded it (also for a model file of one's own), else the load is refused: a file gone in between would make Cellpose fetch a model from its moving branch with TLS off while the record carried the pinned hash (review of #577). The download is fsynced before the rename; a local write error (a full disk) is refused as a write error naming the folder, not as a network problem, and a failed rename names the target. A failed or blocked download, or bytes that do not match, is a refusal naming the model and the URL; nothing partial is kept and no other model is used. The notebook shows a "Downloading weights…" line with the megabytes received, a bar and the elapsed time (`notebook_cellpose_download.DownloadLine`), then how long it took; Cellpose's `tqdm` bar is no longer patched (`BAR_LABEL` and `notebook_bar` are removed). DINOv3, the code of the `cpdino` networks (their weights are all in the Cellpose file), is installed at its pinned commit on a `cpdino` model's first load when no DINOv3 is installed (`ensure_dinov3`, before Cellpose is imported); a DINOv3 of another commit is refused, not replaced. The check that Cellpose imported DINOv3 now looks at `cellpose.vit` (Cellpose 4.2.1.1 defines `CPDINO` whether or not DINOv3 imports, so the former `hasattr(models, "CPDINO")` check could not fail). The record's `parameters` add `weights_repository`, `weights_revision`, `dinov3_source` and `dinov3_installed`; `weights_source` is the pinned URL. **API change:** `load_model(model, device, *, progress=None)` (no `allow_download`), `CellposeWorkflow.load` and `load_nuclei` take `(model, custom_model_file, device)`, `LoadedModel` gains `repository`, `revision` and `dinov3_installed`. `normalization`, `eval_arguments` and `inference_parameters` moved, unchanged apart from the new fields, to `segmentation_cellpose_eval` (re-exported by `segmentation_cellpose`) to keep the file under the 600-line rule. `tests/test_segmentation_cellpose_weights.py`; nothing is downloaded in the tests. +- **Cellpose: torch's "Sparse invariant checks are implicitly disabled" warning is hidden while Cellpose runs (v0.9.1, #574 item 5).** Cellpose's `dynamics.py` builds a sparse tensor and torch warns each session. `segmentation_cellpose.evaluate` now runs `model.eval` inside `segmentation_cellpose_model.sparse_warning_hidden()`, which filters only that `UserWarning`, by its message's start (`SPARSE_WARNING`), from the `torch` or `cellpose` modules, inside `warnings.catch_warnings()` (no global filter; every other warning is shown). The checks it is about only validate sparse tensors and do not change results, so nothing is recorded. `tests/test_segmentation_cellpose_weights.py`. - **The run's masks counter ends at N of N (follow-up of #567).** The mask header check reported "done of N" before each mask and nothing after the last, so the run's wait stopped at "N-1 of N" (preflight's closing `("masks", 1, 1, "")` is a placeholder the wait ignores unless the total is 1). The check now also reports `(total, total, "")` after the last mask; what is read and recorded is unchanged. A stray docstring in `notebook_progress` (the one of `PREPARING` sat after `COUNTED_PHASES`) is back under `PREPARING`. Tests: `tests/test_run_checking_progress.py`, `tests/test_notebook_progress.py`. - **`piece_counts` counts the pieces of masks of objects by runs (#69).** It sorted every pixel (`np.unique(..., return_inverse=True)`, most of its time) and labelled each label again in its bounding box, so labels spread over the plane read it once each. Each row is now cut into runs of one label and runs of one label in neighbouring rows that touch (8-connected, from `masks.binary.STRUCTURE`) are joined with `scipy.sparse.csgraph.connected_components` (new pure module `mask_pieces`; `mask_scan.piece_counts` is the same function, imported). On pixel-scale masks (noise, checkerboards) runs are almost pixels and that graph needs several times the memory of the sort, so above `RUNS_PER_PIXEL_LIMIT` = 0.25 runs per pixel the former route is taken, unchanged. The results are byte-identical either way (labels in the mask's pixel type, counts `int64`): a property test compares both routes, forced and as chosen, with the former function, kept in the test as the reference, on random masks of every label pixel type (touching labels, holes, single pixels, edges, corners, no background, empty) and on the benchmark masks; every digest of `tools/benchmark_kernels.py --group masks` is unchanged, including its new pixel-scale cases (`benchmark_inputs.pixel_mask`). On the benchmark machine `piece_counts` of the 4096 px cells mask went from 2.1 to 2.3 s to 0.07 to 0.10 s and one position's scan from 4.9 to 5.1 s to 0.9 to 1.0 s; the pixel-scale masks take the time and memory they took before (`docs/benchmarks.md`). Outside the former results: a mask with a side of length 0 now has no labels, where the former function failed inside SciPy; a mask that is not 2D is refused with a `ValueError` saying so (it was a SciPy `RuntimeError`, or no labels when it was all background). **The mask scan refuses a mask plane of no pixels** (`mask_without_pixels`, naming the mask): before, SciPy's failure in `piece_counts` was its only guard, and with no labels such a plane would have counted as an image and as a plane of at most one label in its mask type's kind. `pair_counts` and the repeated pair work of #69 are not changed. `tests/test_mask_pieces.py`, `tests/test_mask_scan.py`. - **The run shows its own folder and header check, and that check is no longer quadratic (owner Colab test of v0.9.0, 25 November 2026).** On a large mixed-layout experiment, *Run* showed "Preparing: checking the folders and the image headers again · 0:00 elapsed" for 10-15 minutes before the first image: the run checks every header again (bound to its fingerprint) with no progress reported, and the elapsed time was redrawn only on a progress report. The run now reports that check through `RunMode(checking=...)` (preflight's `(phase, done, total, path)`, operational only like `workers`; `run_experiment`'s parameters are unchanged), and the notebook shows each phase and each header of how many ("Preparing: reading the image headers again · 120 of 24,000"), with the elapsed time redrawn every second by `Wait.ticking()` while the run works. While it goes, the notebook says that a cell run meanwhile waits for it, and how to interrupt it. Two steps of the check were O(n²): each image's staging key took `MetadataReport.dtype` (a pass over every header) and the mask-name screen compared each image's name with every other one (`mask_names._mask_owner` now looks up the prefixes of the name). The outputs are byte for byte the same (`plane_histograms.csv`, `experiment_design.csv`, `image_qc.csv` of a 4,800-image three- and two-channel tree); the check before the first image took 30.0 s → 10.3 s for 12,000 images and 72-75 s → 24-27 s for 24,000 on local disk (`tests/test_run_checking_progress.py`). In a `verify_content` run (the notebook's default, and any run on a fresh output folder) the run then reads every image whole for its content SHA-256 before the first pixel is read: on Google Drive that pass, not the header check, is what took minutes (owner: about 200 images, 10-15 minutes). It is now reported too, as the phase `contents` (`run.phases.CONTENTS`, "Preparing: reading each image whole for its content SHA-256 · 12 of 200"); what is read and verified is unchanged. diff --git a/docs/contract.md b/docs/contract.md index db613c21..e423eed4 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1399,7 +1399,18 @@ Cellpose's own `model.device` is not evidence (it only repeats the device it was nothing beyond the network's tensors is verified. The device is the placement of the network's tensors; Cellpose's own post-processing is not covered by it: Cellpose may move the flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`; that is Cellpose's -behaviour, **not refused**, and the batch records it as a note. Uncached weights are downloaded only on an explicit request; more than +behaviour, **not refused**, and the batch records it as a note. Built-in weights are never +downloaded by Cellpose: choosing a built-in model and loading it is the consent to download that +model's file (owner, #574), which `segmentation_cellpose_weights` fetches from +`mouseland/cellpose-sam` at a pinned commit (`WEIGHTS_REVISION`) and accepts only with its +pinned size and SHA-256 (`PINNED_WEIGHTS`); a copy already in Cellpose's model folder must match +too, else it is refused and left as it is; the file's identity (device, inode, size, modification +time) taken when it is hashed must be unchanged right before and after Cellpose loads it, else +the load is refused. A failed or blocked download is a refusal naming the +model and the URL (a local write error names the folder instead); nothing partial is kept and no other model is used. Cellpose is then given +the file's absolute path. While `model.eval` runs, torch's `UserWarning` starting "Sparse +invariant checks are implicitly disabled" from the `torch` or `cellpose` modules is filtered +(`warnings.catch_warnings`, never a global filter); it does not affect results. More than three channels are refused (Cellpose reads the first three by position); a blank diameter is the model's native scale, never an estimate and never 0, and a diameter that gives fewer than one flow iteration (`int(200 / rescale)` is 0) is refused, never raised to 1. The batch's `model` holds the model @@ -1407,12 +1418,15 @@ name, the weights file name (or the custom file's path) and its SHA-256, and its every effective setting (diameter in pixels or null with its meaning, thresholds, the **full** normalisation dictionary given to Cellpose (its defaults read from its module at call time, with the user's values applied) and the flow iterations `niter` (`int(200 / rescale)`, passed -explicitly), batch and tile size, `channel_axis` 0, device type, versions, `weights_downloaded` -and `weights_source` (the Hugging Face URL Cellpose uses; null for a model file), the device -`notes` and, for a DINOv3 model, the DINOv3 commit). The batch ID is the record's -`new_batch_id()`. The DINOv3 package is installed with `--no-deps` at a pinned commit, the head -of its default branch on 22 November 2026, which is **not verified against `cpdino`**; Cellpose -imports it only when first imported, so the runtime is restarted after installing it. +explicitly), batch and tile size, `channel_axis` 0, device type, versions, `weights_downloaded`, +`weights_source` (the pinned URL, `.../resolve//`), `weights_repository` and +`weights_revision` (all three null for a model file), the device `notes` and, for a DINOv3 +model, `dinov3_commit`, `dinov3_source` and `dinov3_installed`). The batch ID is the record's +`new_batch_id()`. The DINOv3 package (the code of the `cpdino` networks) is installed on the +first load of a `cpdino` model when none is installed, with `--no-deps` at a pinned commit, the +head of its default branch on 22 November 2026, which is **not verified against `cpdino`**; a +DINOv3 of another commit is refused, not replaced. Cellpose imports it only when first imported +(`cellpose.vit`), so a DINOv3 installed after that needs a restart, and the load says so. Two-dimensional images only. **A mask the batch publishes is never left without its record entry**: each mask's SHA-256 and the record write (the batch so far, the same batch ID growing) happen in `write_mask`'s `on_published`, **under the type's write lock**, before the next image diff --git a/docs/plan.md b/docs/plan.md index fdf624eb..567efaa3 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1715,3 +1715,19 @@ Raised during review; to be decided before the milestones that need them: work records; mask headers and projection markers are read as always; *Start fresh* writes and deletes nothing; a finished run is one `RunInputs.open` opens (review of #547) (`notebook_restore`, contract §9.2). +86. Does the Cellpose step need the user's tick to download a model's weights, and to install + DINOv3? *Decided (owner, 26 November 2026, v0.9.1, #574):* no. Choosing the model, then + pressing **Preview** or **Segment** (or **Load the model** in the Cellpose notebook), is the + consent to download that model's weights; the "Allow the weights download from Hugging + Face" and "Install DINOv3 now" ticks are removed. Only the chosen model's file is + downloaded, on first use, with a visible "Downloading weights…" line; the record + names the weights exactly; another model is never used instead and a failed download is a + refusal. *Encoding choices of this brick:* the file is downloaded from + `mouseland/cellpose-sam` at a pinned commit (`WEIGHTS_REVISION`, not Cellpose's moving + `main`) and kept only with its pinned size and SHA-256 (`PINNED_WEIGHTS`, the hashes Hugging + Face lists at that commit); a copy already on disk must match too, else it is refused and + left in place; the record adds `weights_repository` and `weights_revision` beside + `weights_source`, `weights_downloaded` and the model's `sha256`. DINOv3 (the code of the + `cpdino` networks, no weights of its own) is installed at its pinned commit only when none + is installed; a DINOv3 of another commit is refused, not replaced + (`segmentation_cellpose_weights`, `segmentation_cellpose_model.ensure_dinov3`). diff --git a/docs/testing/cellpose-stepper-human-test.md b/docs/testing/cellpose-stepper-human-test.md index b79a552e..661c9db2 100644 --- a/docs/testing/cellpose-stepper-human-test.md +++ b/docs/testing/cellpose-stepper-human-test.md @@ -50,11 +50,14 @@ note anything that looks wrong next to it. - [ ] There is no **Load the model** button. Each setting (diameter, flow threshold, cell probability threshold, batch size) has a one-line help beside it saying which way to move it. -- [ ] Leave the device on `cuda`. If the model's weights are not on this runtime yet, press - **Preview** without the download tick: it refuses and says to allow the download. -- [ ] Tick **Allow the weights download** and press **Preview**: the download shows as **one** - progress bar (no stream of log lines), then a green *Model ... loaded on cuda* card and the - preview figures for the image in the dropdown. +- [ ] There is no **Allow the weights download** tick and no **Install DINOv3 now** tick. +- [ ] Leave the device on `cuda`. With the model's weights not on this runtime yet, press + **Preview**: a line **Downloading cpsam_v2 weights…** shows the megabytes received of the + total (no stream of log lines), then *done in m:ss*, then a green *Model ... loaded on + cuda* card (it names the repository and revision) and the preview figures for the image + in the dropdown. +- [ ] Press **Preview** again after a runtime restart: nothing downloads; the card says the + weights on this computer match the pinned file. - [ ] Choose another image and press **Preview**: no loading card appears this time (the model is reused); the preview is of the new image. - [ ] Change the diameter and press **Preview**: still no reload; the new diameter is used. diff --git a/docs/user_guide.md b/docs/user_guide.md index 9aa3b28c..723a7457 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -296,9 +296,24 @@ banner then says "commit unknown" and that the override is on). Then: channels, so more are refused. - **Model.** `cpsam_v2` (default), `cpsam`, `cpdino`, `cpdino-vitb` or a model file of your own. A name or file that does not exist is refused: Cellpose itself would silently use - `cpsam_v2`. The weights of a built-in model are downloaded from Hugging Face on first use, - only if you tick the download box. `cpdino` models also need DINOv3, installed at a pinned - commit (the head of its default branch on 22 November 2026, not verified against `cpdino`; installed without its dependencies) only if you tick its box. Restart the runtime after installing it, then run the cells again. + `cpsam_v2`. +- **Weights download (owner, #574).** Choosing a built-in model and pressing **Preview** or + **Segment** (or **Load the model** in the Cellpose notebook) is your consent to download that + model's weights; there is no box to tick. The first time, only that model's file is + downloaded, from Hugging Face (`mouseland/cellpose-sam` at the pinned revision + `7c61431b5fbb`, never the moving `main` branch), with a line such as **Downloading cpsam_v2 + weights…** (megabytes, a bar, the time). The file must have its pinned size and SHA-256 + before it is used; a copy already on this computer (in Cellpose's model folder) is checked + too, and one that differs is refused, not used and not replaced: delete it and press the + button again. A failed or blocked download stops with a message naming the model and the + URL; nothing partial is kept, and no other model is ever used instead. +- **DINOv3 (`cpdino` models).** DINOv3 is the code of the `cpdino` networks (their weights are + all in the Cellpose file). When no DINOv3 is installed, the first load of a `cpdino` model + installs it, without its dependencies, at a pinned commit (the head of its default branch on + 22 November 2026, not verified against `cpdino`). A DINOv3 of another commit is not + replaced: the load is refused with the command to run. If Cellpose was already loaded in + this runtime (another model loaded first), the load asks you to restart the runtime and run + the cells again; nothing is downloaded again. - **Device.** The model form says, before anything loads, whether a GPU was found and which. You choose `cuda`, `mps` or `cpu`. A GPU that is not available is refused, never replaced by the CPU, and after loading every parameter and buffer of the network must be on @@ -310,9 +325,13 @@ banner then says "commit unknown" and that the override is on). Then: decrease if merged), the flow threshold (0.4; increase to keep more objects, decrease if they are badly shaped), the cell probability threshold (0; decrease to find more and larger objects, increase for fewer) and the batch size (8; lower it if the GPU runs out of memory). -- **Download display.** While a model loads, a weights download shows as one progress bar and - Cellpose's log lines are not printed; its warnings are shown in one card. What is loaded is - unchanged: the same file, no download without the tick, no substitution, no device fallback. +- **Download display.** While a model loads, a weights download shows as one line with its + progress, then how long it took; Cellpose's log lines are not printed and its warnings are + shown in one card. Cellpose never downloads anything itself: it is given the checked file. +- **One torch warning is hidden.** While Cellpose runs, torch's *UserWarning: Sparse invariant + checks are implicitly disabled…* (from Cellpose's `dynamics.py`) is not shown. Only that + warning, from torch or Cellpose, only during the call; it is about validating sparse tensors + and does not change any result. Every other warning is shown. - **Diameter** is in pixels. Blank means the model's own native scale (Cellpose 4.2.1.1 does not estimate a diameter); 0 is refused. - **Normalisation** is always Cellpose's own, per image (each channel to its 1st to 99th @@ -323,7 +342,7 @@ banner then says "commit unknown" and that the override is on). Then: - **Result.** One mask per image at `///.tif` (2D, `int32`, 0 is background, the image's width and height), never over an existing mask unless you tick overwrite, and `//segmentation_record.json` with the model's - file name and SHA-256, every setting (the full normalisation and the flow iterations included), whether the weights were downloaded now and from where, the channels, the device and each image as written, + file name and SHA-256, every setting (the full normalisation and the flow iterations included), where the weights come from (`weights_repository`, `weights_revision`, `weights_source`) and whether they were downloaded now (`weights_downloaded`), for a `cpdino` model the DINOv3 commit and source and whether it was installed now, the channels, the device and each image as written, skipped or failed. The final table lists every image, with the error of a failed one. - **The masks folder is checked when the run is opened.** **Open the run** refuses a masks folder that is the run's output folder or the experiment folder, or inside or around either, diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index 50f1a715..34763abb 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -25,11 +25,11 @@ "- **2D images only for now.** An image with more than one Z plane or time point fails with a message that says so; it is never reduced to one plane.\n", "- **Channels by ID.** You choose channels by their ID (for example `DNA`, `ACTIN`): a cell channel, a nuclear channel or both, and the output, a cell mask (cell channel, then the nuclear one if chosen) or a nuclei mask (nuclear channel only). In a run where some images have a channel that others lack, only the channels every image has can be used; the notebook shows the refusal as it is. Cellpose reads at most three channels and drops the rest by position, so more than three are refused.\n", "- **Models:** `cpsam_v2` (default), `cpsam`, `cpdino`, `cpdino-vitb`, or a model file of your own. A name or file Cellpose cannot find is **refused**; Cellpose itself would silently use `cpsam_v2` instead.\n", - "- **Downloads:** built-in weights are downloaded from Hugging Face (mouseland/cellpose-sam) on first use. Nothing downloads unless you tick the download box in the form of cell 5. The `cpdino` models also need DINOv3 (installed only if you tick its box, at a pinned commit; see cell 5, which also says that the runtime must be restarted after that).\n", + "- **Downloads:** choosing a built-in model and pressing **Load the model** is your consent to download that model's weights, the first time only: just that one file, from Hugging Face (mouseland/cellpose-sam, at the pinned revision `7c61431b5fbb`), with a progress line, checked against its pinned SHA-256. Weights already on this computer are checked against it too. A failed or blocked download stops with a message naming the model and where it comes from; no other model is ever used instead. The `cpdino` models also need DINOv3, installed the first time at a pinned commit (see cell 5, which says when the runtime must be restarted).\n", "- **Device:** you choose `cuda`, `mps` or `cpu`. A GPU that is not available is **refused**; it never falls back to the CPU, and the notebook checks that every weight of the network sits on the device you chose (that is the network's placement only). Cellpose's own post-processing is not covered by that check: it may move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's own behaviour, it is **not refused**, and it is written to the record as a note.\n", "- **Diameter:** in pixels. **Blank means the model's own native scale** (Cellpose 4.2.1.1 does not estimate a diameter). Zero is refused.\n", "- **Normalisation** is always Cellpose's own, per image (each channel to its 1st-99th percentile); it is not a choice: images are never sent to Cellpose unnormalised.\n", - "- Every setting that ran (the full normalisation and the flow iterations included), the model's file name and its SHA-256, and whether the weights were downloaded in this session and from where, are written to the record.\n", + "- Every setting that ran (the full normalisation and the flow iterations included), the model's file name and its SHA-256, where the weights come from (the repository, its revision and the URL) and whether they were downloaded in this session, are written to the record.\n", "\n", "### How to run\n", "\n", @@ -440,11 +440,11 @@ "\n", "## **5. Choose the model and the settings, then load the model**\n", "\n", - "Choose the model (or give a model file of your own), the device and the settings in the form, then press **Load the model**. Built-in weights are downloaded from **Hugging Face** on first use, and only if you tick the download box; the download shows one progress bar, and Cellpose's log lines are not printed (its warnings are shown in one card). When the form appears it says whether a GPU was found here, and which, before anything loads. The device is never chosen for you: a GPU that is not available is refused, not replaced by the CPU. The notebook loads the model, then checks that the weights file is the one you asked for and that the network's weights are on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter, the flow and cell probability thresholds and the batch size are in **Cellpose settings**, each with a one-line help saying which way to move it (the defaults are Cellpose's). The diameter is in pixels; blank is the model's native scale. Normalisation is not a setting: it is always Cellpose's own, per image (each channel to its 1st-99th percentile).\n", + "Choose the model (or give a model file of your own), the device and the settings in the form, then press **Load the model**. The first time a built-in model is loaded, its weights are downloaded from **Hugging Face** (mouseland/cellpose-sam at revision `7c61431b5fbb`): choosing the model and pressing **Load the model** is the consent, there is no box to tick. Only that model's file is downloaded, with a line such as **Downloading cpsam_v2 weights…** (megabytes, a bar and the time), and it is checked against its pinned SHA-256 before it is used; a copy already here is checked too, and one that differs is refused, not replaced. A failed or blocked download is refused with the model and the source named; no other model is used. Cellpose's log lines are not printed (its warnings are shown in one card). When the form appears it says whether a GPU was found here, and which, before anything loads. The device is never chosen for you: a GPU that is not available is refused, not replaced by the CPU. The notebook loads the model, then checks that the weights file is the one you asked for and that the network's weights are on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter, the flow and cell probability thresholds and the batch size are in **Cellpose settings**, each with a one-line help saying which way to move it (the defaults are Cellpose's). The diameter is in pixels; blank is the model's native scale. Normalisation is not a setting: it is always Cellpose's own, per image (each channel to its 1st-99th percentile).\n", "\n", - "**The check covers every parameter and buffer of the network** (not Cellpose's own `device` attribute, which only repeats what it was given). Cellpose's post-processing is outside this check: it may move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's behaviour, not refused; the record carries it as a note, together with the full normalisation, the flow iterations, and whether the weights were downloaded now and from where.\n", + "**The check covers every parameter and buffer of the network** (not Cellpose's own `device` attribute, which only repeats what it was given). Cellpose's post-processing is outside this check: it may move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's behaviour, not refused; the record carries it as a note, together with the full normalisation, the flow iterations, and where the weights come from (repository, revision, URL) and whether they were downloaded now.\n", "\n", - "**The `cpdino` models need DINOv3, and a restart.** Ticking the install box and pressing **Load the model** installs DINOv3 with `--no-deps` (so it cannot change your PyTorch) at commit `6876159a11b4`, **the head of its default branch on 22 November 2026, not verified against `cpdino`**. Cellpose imports DINOv3 only when it is first imported, so after installing DINOv3 **restart the runtime** (Colab: Runtime > Restart session), run cells 1 to 4 again and load a `cpdino` model; loading before the restart is refused with that instruction." + "**The `cpdino` models need DINOv3, and sometimes a restart.** DINOv3 is the code of their network (their weights are all in the Cellpose file). When none is installed, loading a `cpdino` model installs it first, with `--no-deps` (so it cannot change your PyTorch) at commit `6876159a11b4`, **the head of its default branch on 22 November 2026, not verified against `cpdino`**. A DINOv3 of another commit is yours and is not replaced: the load is refused with the command to run. Cellpose imports DINOv3 only when it is first imported, so if Cellpose was already loaded in this runtime (another model loaded before), **restart the runtime** (Colab: Runtime > Restart session), run cells 1 to 4 again and load the `cpdino` model; loading before the restart is refused with that instruction, and nothing is downloaded again." ] }, { @@ -568,7 +568,7 @@ "\n", "## **Versions and citation**\n", "\n", - "**Versions.** This notebook runs **Cellpose 4.2.1.1** (pinned in cell 1, which also pins the MorphoBricks preprocessing commit and prints both versions when it says **Ready**). Each batch in `//segmentation_record.json` stores the tool and its exact version (`tool`, `tool_version`; again as `cellpose_version` in the batch's `parameters`), the model's name, weights file and SHA-256, the DINOv3 commit for a `cpdino` model (`dinov3_commit`), whether the weights were downloaded and from where, the device and every setting that ran. The preprocessing version is not in that record: cell 1 prints it, and the run's own `run_manifest.json` records the preprocessing that made the run.\n", + "**Versions.** This notebook runs **Cellpose 4.2.1.1** (pinned in cell 1, which also pins the MorphoBricks preprocessing commit and prints both versions when it says **Ready**). Each batch in `//segmentation_record.json` stores the tool and its exact version (`tool`, `tool_version`; again as `cellpose_version` in the batch's `parameters`), the model's name, weights file and SHA-256, the DINOv3 commit for a `cpdino` model (`dinov3_commit`), where the weights come from (`weights_repository`, `weights_revision`, `weights_source`) and whether they were downloaded (`weights_downloaded`), the device and every setting that ran. The preprocessing version is not in that record: cell 1 prints it, and the run's own `run_manifest.json` records the preprocessing that made the run.\n", "\n", "**Citation.** As Cellpose's own README (release 4.2.1.1) asks:\n", "\n", diff --git a/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb b/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb index 225e65a9..3a892a4c 100644 --- a/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb @@ -34,7 +34,7 @@ "4. **Segment with Cellpose** installs Cellpose (with PyTorch) the first time, only when you tick it, then segments the run of cell 3.\n", "5. **Register the masks** declares the new masks, runs again and describes them.\n", "\n", - "Cells 1 to 3 are exactly those of the MorphoBricks preprocessing notebook. Cellpose, PyTorch and the model weights are downloaded only in cell 4, and only when you tick their boxes." + "Cells 1 to 3 are exactly those of the MorphoBricks preprocessing notebook. Cellpose, PyTorch and the model weights are downloaded only in cell 4: Cellpose and PyTorch when you tick their box, a model's weights the first time you press **Preview** or **Segment** with it." ] }, { @@ -623,7 +623,7 @@ "\n", "1. **Folders**: the run and the masks folder. The masks folder is checked here: it may not be the run's output folder or the experiment folder, nor inside or around either. Once the run is open, its images are shown with the preprocessing image viewer (channels named by their IDs).\n", "2. **Output and channels**: the **output**, explained next to the choice (Cell mask, Nuclei mask or **Both**: two mask types, both channels required, each its own batch), then the channels **by channel ID** or **By number** (counted from 1, only when every image has the same channels in the same order).\n", - "3. **Model and preview**: the model, the device and the settings (each with a one-line help). **Preview** loads the model the first time (built-in weights are downloaded from **Hugging Face** only if you tick the download box, with one progress bar; a GPU that is not available is refused, never replaced by the CPU), then segments the image chosen; nothing is written. Choose another image and press **Preview** again: the model is reused, and loaded again only if you change the model, its file or the device. With **Both**, a box below lets the nuclei use a model and settings of their own.\n", + "3. **Model and preview**: the model, the device and the settings (each with a one-line help). **Preview** loads the model the first time (choosing the model and pressing **Preview** or **Segment** is the consent to download its weights: only that model's file, from **Hugging Face** at a pinned revision, with a line such as **Downloading cpsam_v2 weights…**, checked against its pinned SHA-256; a failed download is refused, never replaced by another model; a `cpdino` model also installs DINOv3 at a pinned commit; a GPU that is not available is refused, never replaced by the CPU), then segments the image chosen; nothing is written. Choose another image and press **Preview** again: the model is reused, and loaded again only if you change the model, its file or the device. With **Both**, a box below lets the nuclei use a model and settings of their own.\n", "4. **Segment**: the whole experiment (existing masks are never overwritten unless you tick it). One line at the end says what comes next: cell 5.\n", "\n", "Cells and nuclei are never paired by label number: MorphoRelate relates them later, by geometry. Cellpose's own normalization is always on. **Open the run** fixes the run and the masks folder as they are then: if the run is published again (cell 3 or cell 5 runs it again) or a relative masks folder would now point elsewhere (the working directory changed), Preview and Segment refuse until you press **Open the run** again." diff --git a/pyproject.toml b/pyproject.toml index 00e113d2..139cd43a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -392,9 +392,11 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.cellpose_install" = "io" "morphobricks_preprocessing.segmentation_cellpose" = "io" "morphobricks_preprocessing.segmentation_cellpose_commit" = "io" +"morphobricks_preprocessing.segmentation_cellpose_eval" = "io" "morphobricks_preprocessing.segmentation_cellpose_model" = "io" "morphobricks_preprocessing.segmentation_cellpose_run" = "io" "morphobricks_preprocessing.segmentation_cellpose_settings" = "pure" +"morphobricks_preprocessing.segmentation_cellpose_weights" = "io" "morphobricks_preprocessing.segmentation_handoff" = "io" "morphobricks_preprocessing.segmentation_record" = "io" "morphobricks_preprocessing.lock_file" = "io" diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index d9a8c452..fc688b83 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -29,7 +29,7 @@ MaskTarget, _card, ) -from .notebook_cellpose_download import quiet_cellpose +from .notebook_cellpose_download import DownloadLine, quiet_cellpose from .notebook_cellpose_preview import MaskResult, preview_figures from .notebook_progress import progress_html from .notebook_stop import CellStop @@ -273,33 +273,21 @@ def set_nuclei_settings( self.nuclei_settings = _settings(diameter, flow_threshold, cellprob_threshold, batch_size) @stops - def load( - self, - model: str, - custom_model_file: str, - device: str, - download_weights: bool, - install_dino: bool, - ) -> None: - """Say what loading does, then load the verified model (cell 5).""" + def load(self, model: str, custom_model_file: str, device: str) -> None: + """Say what loading does, then load the verified model (cell 5). + + Loading a built-in model is the consent to download its weights when they are not on + this computer (and DINOv3 for a ``cpdino`` model; owner, #574): there is no tick. + """ self._need("channels") self.picker.current_targets() if self.settings is None: raise SegmentationError("Set the settings first: press Load the model.") self.loaded = None - self.loaded = self._load_model( - model, custom_model_file, device, download_weights, install_dino, self.settings - ) + self.loaded = self._load_model(model, custom_model_file, device, self.settings) @stops - def load_nuclei( - self, - model: str, - custom_model_file: str, - device: str, - download_weights: bool, - install_dino: bool, - ) -> None: + def load_nuclei(self, model: str, custom_model_file: str, device: str) -> None: """Load a separate model for the nuclei of the output Both (cell 5's Advanced).""" self._need_both() if self.nuclei_settings is None: @@ -309,7 +297,7 @@ def load_nuclei( ) self.nuclei_loaded = None self.nuclei_loaded = self._load_model( - model, custom_model_file, device, download_weights, install_dino, self.nuclei_settings + model, custom_model_file, device, self.nuclei_settings ) def _need_both(self) -> None: @@ -327,36 +315,35 @@ def same_model_for_nuclei(self) -> None: self.nuclei_loaded = self.nuclei_settings = None def _load_model( - self, - model: str, - custom_model_file: str, - device: str, - download_weights: bool, - install_dino: bool, - settings: cp.Settings, + self, model: str, custom_model_file: str, device: str, settings: cp.Settings ) -> cp.LoadedModel: - """Load the model chosen, verified, and show what was loaded.""" + """Load the model chosen, verified, and show what was loaded (and any download).""" chosen = custom_model_file.strip() or model - if install_dino and chosen in cp.DINO_MODELS: - self._show(_card("info", "Installing DINOv3", (" ".join(cp.dinov3_install_command()),))) - cp.install_dinov3() self._show( _card( "info", f"Loading {chosen} on {device}", ( - "Built-in weights are downloaded from Hugging Face on first use; they are " - "downloaded only if the download box is ticked, with one progress bar.", + "Built-in weights not yet on this computer are downloaded now, from " + f"Hugging Face ({cp.WEIGHTS_REPOSITORY} at revision " + f"{cp.WEIGHTS_REVISION[:12]}), and checked against their pinned SHA-256; " + "weights already here are checked too. Only this model's weights are " + "downloaded, and no other model is ever used instead.", "On a GPU Cellpose may move its flow-threshold quality step to the CPU " "when GPU memory is short, and always computes the masks on the CPU on " "mps. That is Cellpose's own behaviour; it is recorded as a note.", ), ) ) - with quiet_cellpose() as said: # one tqdm.auto bar; what is loaded is unchanged + line = DownloadLine(self._show) # shown only if something downloads + with quiet_cellpose() as said: + ok = False try: - loaded = cp.load_model(chosen, device, allow_download=download_weights) + with line.wait.ticking(): + loaded = cp.load_model(chosen, device, progress=line) + ok = True finally: + line.finish(ok) if said: self._show(_card("warn", "Cellpose said, while loading", tuple(said))) self._show( @@ -367,11 +354,7 @@ def _load_model( f"Weights file: {loaded.file}", f"SHA-256: {loaded.sha256}", f"Network {loaded.backbone}, tile size {loaded.tile_size}", - ( - f"Weights downloaded now from {loaded.source}" - if loaded.downloaded - else "Weights were already on this computer (nothing downloaded)" - ), + *_weights_lines(loaded), "Diameter: " + _diameter(settings), ), ) @@ -544,3 +527,19 @@ def _diameter(settings: cp.Settings) -> str: def _named(exc: BaseException) -> str: """Return an error as ``Type: message``.""" return f"{type(exc).__name__}: {exc}" + + +def _weights_lines(loaded: cp.LoadedModel) -> tuple[str, ...]: + """Return where the loaded weights came from, for the card that says what was loaded.""" + if loaded.source is None: + return ("A model file of your own (nothing downloaded)",) + where = f"{loaded.repository} at revision {loaded.revision}" + lines = [ + f"Weights downloaded now from {loaded.source} ({where}); SHA-256 matches the pinned one" + if loaded.downloaded + else f"Weights were already on this computer and match the pinned file of {where} " + "(nothing downloaded)" + ] + if loaded.dinov3_installed: + lines.append(f"DINOv3 installed now at commit {loaded.dinov3_commit}") + return tuple(lines) diff --git a/src/morphobricks_preprocessing/notebook_cellpose_download.py b/src/morphobricks_preprocessing/notebook_cellpose_download.py index a8532fe2..6fcbe785 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_download.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_download.py @@ -1,46 +1,46 @@ -"""What the notebook shows while Cellpose loads a model: one progress bar, no log noise. - -Cellpose 4.2.1.1 downloads built-in weights with ``cellpose.utils.download_url_to_file``, which -draws a plain-text ``tqdm`` bar (in a notebook, a new line of text at each update), and logs -each step at INFO through the ``cellpose`` loggers. While a model loads, -:func:`quiet_cellpose` only changes how that is **shown**: - -- the bar is ``tqdm.auto``'s (one widget bar in a notebook), same total, unit and updates; -- the ``cellpose`` loggers' INFO lines are dropped and their warnings are collected, to be - shown in one card afterwards (never lost). - -Nothing about **what** is loaded changes: the same URL, file and bytes, and the checks of -:func:`.segmentation_cellpose_model.load_model` (no download without the user's tick, no model -substitution, no device fallback) run unchanged. Everything is put back when the load ends, -also when it fails. Cellpose is imported here only when the pinned release is installed (the -load imports it right after anyway); otherwise nothing is patched and the load refuses as -before. +"""What the notebook shows while a model loads: the download's progress, no Cellpose log noise. + +Owner decision (issue #574): choosing a model and pressing **Preview** or **Segment** (or +**Load the model**) is the consent to download that model's weights, so there is no tick to +allow it; the download is shown instead. :class:`DownloadLine` is the ``progress`` given to +:func:`.segmentation_cellpose_model.load_model`: the first time it is told something it +appears, as one line "Downloading weights…" with the megabytes received of the total, +a bar and the elapsed time (:class:`.notebook_progress.Wait`), or "Installing DINOv3…" for a +``cpdino`` model; it says at the end how long it took, or that it stopped. A model already on +this computer shows nothing. + +Cellpose itself never downloads here: the model is handed to it as the absolute path of the +checked file (:mod:`.segmentation_cellpose_weights`). While it loads, :func:`quiet_cellpose` +drops the ``cellpose`` loggers' INFO lines and collects their warnings, to be shown in one card +afterwards (never lost). Everything is put back when the load ends, also when it fails. """ from __future__ import annotations -import importlib import logging -import sys -from collections.abc import Iterator +import time +from collections.abc import Callable, Iterator from contextlib import contextmanager -from types import ModuleType -from . import segmentation_cellpose_model as model_module +import ipywidgets as widgets + +from .notebook_progress import Wait +from .notebook_style import status LOGGER = "cellpose" """The parent of every Cellpose logger (``cellpose.models``, ``cellpose.core``, ...).""" -BAR_LABEL = "Downloading the weights" CPDINO_IMPORT = "Could not import CPDINO" """How Cellpose 4.2.1.1's ``cellpose.models`` starts the warning it logs at import when DINOv3 is not importable; the warning goes on to recommend ``pip install git+.../dinov3`` unpinned.""" CPDINO_NOTE = ( - "Cellpose could not import DINOv3. Only the cpdino models need it: for those, tick " - "Install DINOv3 now (it installs the pinned commit), then restart the runtime. The other " - "models do not use it." + "Cellpose could not import DINOv3. Only the cpdino models need it: choosing one and pressing " + "the button installs the pinned commit, and the runtime then needs a restart if Cellpose was " + "already imported. The other models do not use it." ) -"""What is shown instead: the notebook's pinned installation (``install_dinov3``), never an +"""What is shown instead: the notebook's pinned installation (``ensure_dinov3``), never an unpinned one.""" +MEGABYTE = 1 << 20 +"""The unit the download's line counts in (MB, as 2**20 bytes).""" class _Collect(logging.Handler): @@ -53,40 +53,13 @@ def __init__(self) -> None: def emit(self, record: logging.LogRecord) -> None: text = record.getMessage() if text.startswith(CPDINO_IMPORT): - text = CPDINO_NOTE # never an unpinned install: the notebook's own tick instead + text = CPDINO_NOTE # never an unpinned install: the notebook's own instead self.lines.append(f"{record.levelname.title()}: {text}") -def _cellpose_utils() -> ModuleType | None: - """Return ``cellpose.utils`` of the pinned release, or None (nothing is then patched).""" - loaded = sys.modules.get("cellpose.utils") - if loaded is not None: - return loaded - if model_module.installed_version("cellpose") != model_module.CELLPOSE_VERSION: - return None - try: - return importlib.import_module("cellpose.utils") - except ImportError: - return None - - -def _auto_bar() -> type | None: - """Return ``tqdm.auto.tqdm`` (Cellpose depends on tqdm), or None where it does not import.""" - try: - return importlib.import_module("tqdm.auto").tqdm - except (ImportError, AttributeError): - return None - - -def notebook_bar(*args: object, **kwargs: object) -> object: - """Return ``tqdm.auto``'s bar with Cellpose's own arguments and a plain label.""" - kwargs.setdefault("desc", BAR_LABEL) - return _auto_bar()(*args, **kwargs) - - @contextmanager def quiet_cellpose() -> Iterator[list[str]]: - """Show Cellpose's download as one ``tqdm.auto`` bar and collect its warnings. + """Drop Cellpose's INFO lines and collect its warnings while a model loads. Yields ------ @@ -95,21 +68,67 @@ def quiet_cellpose() -> Iterator[list[str]]: """ logger = logging.getLogger(LOGGER) handler, propagate = _Collect(), logger.propagate - logger.addHandler(handler) # first: importing Cellpose below may already log + logger.addHandler(handler) # before the load imports Cellpose: importing it may log logger.propagate = False - utils, original = None, None try: - utils = _cellpose_utils() - if utils is not None and _auto_bar() is not None: # else Cellpose's own bar stays - original = getattr(utils, "tqdm", None) - if original is not None: - utils.tqdm = notebook_bar yield handler.lines finally: - if original is not None: - utils.tqdm = original logger.removeHandler(handler) logger.propagate = propagate -__all__ = ["BAR_LABEL", "CPDINO_IMPORT", "CPDINO_NOTE", "LOGGER", "notebook_bar", "quiet_cellpose"] +class DownloadLine: + """The ``progress(label, done, total)`` of a load, drawn as one wait line once called. + + Parameters + ---------- + show + Called once with :attr:`widget`, the first time there is something to show. + clock + Returns the time in seconds (monotonic), for the wait; replaced in tests. + + Attributes + ---------- + widget + The line (HTML). + labels + Every label shown, in order (``"Downloading cpsam_v2 weights…"``, ...). + """ + + def __init__( + self, show: Callable[[widgets.Widget], object], clock: Callable[[], float] = time.monotonic + ) -> None: + self.widget = widgets.HTML() + self.wait = Wait(self.widget, clock=clock) + self.labels: list[str] = [] + self._show = show + + def __call__(self, label: str, done: int, total: int) -> None: + """Show ``done`` of ``total`` bytes under ``label`` (a new label starts a new line).""" + first = not self.labels + if first or self.labels[-1] != label: + self.labels.append(label) + self.wait.start(label, total // MEGABYTE) + self.wait.step(done // MEGABYTE, total // MEGABYTE, "MB") + if first: # drawn first, so that what is shown says what is happening + self._show(self.widget) + + def finish(self, ok: bool) -> None: + """Replace the line by how long it took, or by where it stopped (if it was shown).""" + if not self.labels: + return + label = self.labels[-1].rstrip("…") + if ok: + self.widget.value = status("ok", f"{label}: done in {self.wait.took()}") + else: + self.widget.value = status("error", f"{label}: stopped after {self.wait.took()}") + + +__all__ = [ + "CPDINO_IMPORT", + "CPDINO_NOTE", + "LOGGER", + "MEGABYTE", + "DownloadLine", + "quiet_cellpose", +] diff --git a/src/morphobricks_preprocessing/notebook_cellpose_fields.py b/src/morphobricks_preprocessing/notebook_cellpose_fields.py index 6ffe2b76..27d3a519 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_fields.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_fields.py @@ -1,14 +1,14 @@ """The fields of the Cellpose notebook's forms: paths with **Browse…**, the model and settings. Split from :mod:`.notebook_cellpose_form` to keep each file small; built from the Preprocessing -app's helpers in :mod:`.notebook_style`. The defaults are those of the former Colab form: -the weights download and the DINOv3 installation off, the device ``cuda`` (an unavailable GPU -is refused, never replaced by the CPU), the model ``cpsam_v2`` and a blank diameter. +app's helpers in :mod:`.notebook_style`. The defaults are those of the former Colab form: the +device ``cuda`` (an unavailable GPU is refused, never replaced by the CPU), the model +``cpsam_v2`` and a blank diameter. There is no tick for the weights download or for DINOv3: +choosing the model and pressing the button that loads it is the consent (owner, #574). The output Both (#440) segments the cells and the nuclei with **one model and one set of settings** by default. In the box **Output Both: the nuclei**, a tick gives the nuclei a model -and settings of their own (:data:`NUCLEI_FIELDS`); the device and the download and install -ticks stay shared. +and settings of their own (:data:`NUCLEI_FIELDS`); the device stays shared. """ from __future__ import annotations @@ -249,10 +249,6 @@ def model_fields() -> dict[str, widgets.Widget]: description="Device", style=STYLE, ), - "download_weights": widgets.Checkbox( - value=False, description="Allow the weights download from Hugging Face" - ), - "install_dinov3": widgets.Checkbox(value=False, description="Install DINOv3 now"), **{name: main[name] for name in NUCLEI_FIELDS[2:]}, SEPARATE_NUCLEI: widgets.Checkbox( value=False, description="Output Both: a different model or settings for the nuclei" @@ -290,8 +286,7 @@ def shown(change: dict) -> None: full_help( "Both writes the cells and the nuclei. By default the nuclei use the " "model and the settings above. Tick to give the nuclei their own model and " - "settings (for example a smaller diameter); the device and the download and " - "install ticks are shared." + "settings (for example a smaller diameter); the device is shared." ), fields[SEPARATE_NUCLEI], own, @@ -307,7 +302,7 @@ def show_nuclei_box(box: widgets.Widget, fields: dict[str, widgets.Widget], both def model_cards(fields: dict[str, widgets.Widget], status: widgets.HTML) -> list[widgets.Widget]: - """Return cell 5's cards: the model, device and downloads; the settings; the nuclei's box. + """Return cell 5's cards: the model and device; the settings; the nuclei's box. ``status`` shows, under a model file, how to paste its path where no dialog opens. The nuclei's box is the last card, hidden until the output is Both (:func:`show_nuclei_box`). @@ -330,12 +325,13 @@ def model_cards(fields: dict[str, widgets.Widget], status: widgets.HTML) -> list "The device is never chosen for you: a GPU that is not available is " "refused, not replaced by the CPU." ), - fields["download_weights"], - fields["install_dinov3"], ui.help_text( - "Built-in weights are downloaded from Hugging Face on first use, only with " - "the download ticked. The cpdino models need DINOv3: tick to install it, then " - "restart the runtime and run the notebook again from its first cell." + "The first time a built-in model is used, only its weights are downloaded " + "from Hugging Face (a pinned revision), with a progress line, and checked " + "against their pinned SHA-256: choosing the model and pressing the button " + "is the consent. A failed download stops; no other model is used. The " + "cpdino models also install DINOv3 (a pinned commit) the first time; if " + "Cellpose was already loaded, you are asked to restart the runtime." ), ], ), diff --git a/src/morphobricks_preprocessing/notebook_cellpose_form.py b/src/morphobricks_preprocessing/notebook_cellpose_form.py index 771abc56..782dff50 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_form.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_form.py @@ -10,9 +10,11 @@ ``clean_path``); a refusal that stopped the cell (:class:`.CellStop`) is shown with the same message, verbatim, in a red card. -The defaults are those of the former form: overwrite, the weights download and the DINOv3 -installation are off, the device is ``cuda`` (an unavailable GPU is refused, never replaced by -the CPU), the model ``cpsam_v2`` and a blank diameter (the model's native scale). +The defaults are those of the former form: overwrite is off, the device is ``cuda`` (an +unavailable GPU is refused, never replaced by the CPU), the model ``cpsam_v2`` and a blank +diameter (the model's native scale). There is no tick for the weights download or the DINOv3 +installation: choosing the model and pressing the button that loads it is the consent (owner, +#574). """ from __future__ import annotations @@ -332,21 +334,11 @@ def _load_from(self, fields: dict[str, widgets.Widget]) -> None: self._nuclei_failed = False value = {name: field.value for name, field in fields.items()} self._set_form_settings(fields) - self.load( - value["model"], - value["custom_model_file"], - value["device"], - value["download_weights"], - value["install_dinov3"], - ) + self.load(value["model"], value["custom_model_file"], value["device"]) if value[SEPARATE_NUCLEI]: try: self.load_nuclei( - value["nuclei_model"], - value["nuclei_custom_model_file"], - value["device"], - value["download_weights"], - value["install_dinov3"], + value["nuclei_model"], value["nuclei_custom_model_file"], value["device"] ) except BaseException: # a refusal, any error or an interrupt: neither stays loaded self.loaded = self.nuclei_loaded = None diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index ba442bc3..353d3a6a 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -8,8 +8,10 @@ Loading a model (:func:`load_model`, in :mod:`.segmentation_cellpose_model`, re-exported here) refuses what Cellpose 4.2.1.1 would do silently: substitute ``cpsam_v2`` for a model it cannot -find, fall back from the GPU to the CPU, and download uncached weights. This module adds the -rest of what an audit of the Cellpose hand-off asked for: +find and fall back from the GPU to the CPU; built-in weights are downloaded on first use from a +pinned revision and checked against their pinned SHA-256 +(:mod:`.segmentation_cellpose_weights`), never by Cellpose. This module adds the rest of what +an audit of the Cellpose hand-off asked for: - **Channels by ID.** The channels are resolved by canonical ID (:func:`.segmentation_handoff.resolve_segmentation`) and passed as a ``(C, Y, X)`` stack with @@ -24,8 +26,10 @@ (:func:`inference_parameters`), every image into the batch with its outcome, written, skipped or failed with the error (:func:`run_batch`); nothing is dropped. Each mask's hash and record entry are written under the type's write lock; a failure there rolls the mask back. The full - normalisation, the flow iterations, and whether built-in weights were downloaded (and from - where) are in it. + normalisation, the flow iterations, and the built-in weights' source (repository, revision + and URL) and whether they were downloaded are in it. +- **One torch warning hidden** while Cellpose runs (:func:`evaluate`, + :func:`.segmentation_cellpose_model.sparse_warning_hidden`); it does not change any result. Mask paths, pairing, the mask-type rules, writing, the folder rules and the record are the hand-off's own (:mod:`.segmentation_handoff`, :mod:`.segmentation_record`); nothing is repeated. @@ -48,6 +52,16 @@ is_recorded, replaced_earlier_mask, ) +from .segmentation_cellpose_eval import ( + MAX_SIZE_FRACTION, + MIN_SIZE, + NATIVE_SCALE, + NORMALIZE_PERCENTILE, + TILE_OVERLAP, + eval_arguments, + inference_parameters, + normalization, +) from .segmentation_cellpose_model import ( BUILTIN_MODELS, CELLPOSE_VERSION, @@ -55,7 +69,9 @@ DEVICE_NOTE, DINO_MODELS, DINOV3_COMMIT, + DINOV3_LABEL, DINOV3_URL, + SPARSE_WARNING, LoadedModel, ModelChoice, check_device, @@ -68,6 +84,7 @@ installed_dinov3_commit, installed_version, load_model, + sparse_warning_hidden, weights_file, ) from .segmentation_cellpose_run import ( @@ -99,6 +116,7 @@ output_inputs, rescale_factor, ) +from .segmentation_cellpose_weights import WEIGHTS_REPOSITORY, WEIGHTS_REVISION, weights_url from .segmentation_handoff import ( SegmentationPlan, images_to_segment, @@ -119,6 +137,17 @@ ) __all__ = [ + "DEVICE_NOTE", + "MAX_SIZE_FRACTION", + "MIN_SIZE", + "NATIVE_SCALE", + "NORMALIZE_PERCENTILE", + "TILE_OVERLAP", + "eval_arguments", + "flow_iterations", + "inference_parameters", + "normalization", + "rescale_factor", "MAX_CHANNELS", "channel_coverage", "check_channel_count", @@ -129,6 +158,7 @@ "CELLPOSE_VERSION", "DEFAULT_MODEL", "DINOV3_COMMIT", + "DINOV3_LABEL", "DINOV3_URL", "DINO_MODELS", "BOTH_NEEDS", @@ -141,6 +171,9 @@ "NUCLEAR_ROLE", "NUCLEI_OUTPUT", "OUTPUT_MASK_TYPES", + "SPARSE_WARNING", + "WEIGHTS_REPOSITORY", + "WEIGHTS_REVISION", "LoadedModel", "ModelChoice", "Settings", @@ -159,16 +192,10 @@ "installed_version", "load_model", "weights_file", + "weights_url", ] TOOL = "cellpose" -TILE_OVERLAP, MIN_SIZE, MAX_SIZE_FRACTION = 0.1, 15, 0.4 -"""Cellpose's own defaults, passed explicitly so that the record holds the effective values.""" -NORMALIZE_PERCENTILE = [1.0, 99.0] -NATIVE_SCALE = ( - "native scale of the model: Cellpose 4.2.1.1 does not estimate the diameter, so a blank " - "diameter means the model's own scale" -) IMAGE_SKIPPED = "a mask of this type is already there; not replaced (overwrite is off)" IMAGE_UNRECORDED = ( "exists without provenance (not made by a recorded batch); not replaced (overwrite is off)" @@ -183,49 +210,6 @@ # --- one image -------------------------------------------------------------------------------- -def normalization(settings: Settings) -> dict[str, Any]: - """Return the full normalisation given to Cellpose: its defaults now, with the user's values. - - The defaults (``tile_norm_blocksize``, ``sharpen_radius``, ``invert``, ``lowhigh``, ...) come - from Cellpose's module global at call time, copied; ``normalize`` (always on: a setting - that is not True is refused) and the percentiles are then set. Nothing is left to Cellpose's - defaults, so the record holds all. - """ - if settings.normalize is not True: # Settings refuses it; never reach Cellpose without it - raise SegmentationError(NORMALIZE_REFUSAL) - return { - **default_normalization(), - "normalize": True, - "percentile": list(NORMALIZE_PERCENTILE), - } - - -def eval_arguments(loaded: LoadedModel, settings: Settings) -> dict[str, Any]: - """Return every argument given to ``model.eval``, the effective inference settings. - - ``channel_axis`` is 0: the stack from :meth:`.segmentation_handoff.SegmentationPlan.read` - is ``(C, Y, X)`` in the order of the requested channel IDs. The tile size, the full - normalisation, the flow iterations and the other values Cellpose would default are given - explicitly, so what is recorded is what ran. - """ - return { - "batch_size": settings.batch_size, - "resample": True, - "channel_axis": 0, - "normalize": normalization(settings), - "diameter": settings.diameter, - "flow_threshold": settings.flow_threshold, - "cellprob_threshold": settings.cellprob_threshold, - "do_3D": False, - "min_size": MIN_SIZE, - "max_size_fraction": MAX_SIZE_FRACTION, - "niter": flow_iterations(settings), - "augment": False, - "tile_overlap": TILE_OVERLAP, - "bsize": loaded.tile_size, - } - - def segment_image(loaded: LoadedModel, settings: Settings, stack: np.ndarray) -> np.ndarray: """Segment one ``(C, Y, X)`` stack (the chosen channels, in the order chosen). @@ -247,49 +231,21 @@ def evaluate(loaded: LoadedModel, settings: Settings, stack: np.ndarray) -> tupl """Return the labels of :func:`segment_image` and Cellpose's flows (``flows[0]`` is RGB). The flows are for the preview (``cellpose.plot.show_segmentation``); the batch keeps only - the labels. None when Cellpose returned no flows. + the labels. None when Cellpose returned no flows. While Cellpose runs, torch's warning that + begins :data:`SPARSE_WARNING` is hidden, and only it (:func:`sparse_warning_hidden`). """ array = np.asarray(stack) if array.ndim != 3: raise SegmentationError(f"The stack is {array.ndim}D; Cellpose gets (C, Y, X).") check_channel_count([f"channel {i}" for i in range(array.shape[0])]) - out = loaded.model.eval(array, **eval_arguments(loaded, settings)) + with sparse_warning_hidden(): + out = loaded.model.eval(array, **eval_arguments(loaded, settings)) labels = np.asarray(out[0] if isinstance(out, tuple) else out) if labels.ndim != 2: raise SegmentationError(f"Cellpose returned {labels.ndim}D labels; a mask is 2D (Y, X).") return labels, (out[1] if isinstance(out, tuple) and len(out) > 1 else None) -def inference_parameters( - loaded: LoadedModel, settings: Settings, channel_ids: Sequence[str] -) -> dict[str, Any]: - """Return the parameters of a batch for the record: every effective setting, plain JSON. - - The diameter is in pixels, or null with the statement that it is the model's native - scale; ``rescale`` is the factor Cellpose derives from it (30 / diameter, or 1). The - normalisation is the full dictionary given to Cellpose and ``niter`` the flow iterations - it derives from the rescale. ``weights_downloaded`` and ``weights_source`` say whether this - session downloaded the built-in weights and from where; ``notes`` holds Cellpose's device - behaviour (:data:`.segmentation_cellpose_model.DEVICE_NOTE`) for a GPU run. - """ - arguments = eval_arguments(loaded, settings) - notes = [DEVICE_NOTE] if loaded.device != "cpu" else [] - return { - **arguments, - "diameter_unit": "pixels" if settings.diameter is not None else NATIVE_SCALE, - "rescale": rescale_factor(settings), - "channel_ids_order": list(channel_ids), - "device_type": loaded.device, - "backbone": loaded.backbone, - "use_bfloat16": True, - "cellpose_version": CELLPOSE_VERSION, - "dinov3_commit": loaded.dinov3_commit, - "weights_downloaded": loaded.downloaded, - "weights_source": loaded.source, - "notes": notes, - } - - # --- the batch -------------------------------------------------------------------------------- diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_eval.py b/src/morphobricks_preprocessing/segmentation_cellpose_eval.py new file mode 100644 index 00000000..624982d1 --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_cellpose_eval.py @@ -0,0 +1,130 @@ +"""The arguments Cellpose's ``eval`` is given, and the parameters a batch records. + +Split from :mod:`.segmentation_cellpose` (which re-exports these names) to keep each file +small. Every value Cellpose would default is given explicitly, so what is recorded is what ran: +the full normalisation (Cellpose's defaults read at call time, with the user's values), the +flow iterations, the tile size; and, for the record, where the weights came from (the pinned +repository, revision and URL, :mod:`.segmentation_cellpose_weights`) and whether they, or +DINOv3, were fetched in this session. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from .segmentation_cellpose_model import ( + CELLPOSE_VERSION, + DEVICE_NOTE, + DINOV3_URL, + LoadedModel, + default_normalization, +) +from .segmentation_cellpose_settings import ( + NORMALIZE_REFUSAL, + Settings, + flow_iterations, + rescale_factor, +) +from .segmentation_record import SegmentationError + +TILE_OVERLAP, MIN_SIZE, MAX_SIZE_FRACTION = 0.1, 15, 0.4 +"""Cellpose's own defaults, passed explicitly so that the record holds the effective values.""" +NORMALIZE_PERCENTILE = [1.0, 99.0] +NATIVE_SCALE = ( + "native scale of the model: Cellpose 4.2.1.1 does not estimate the diameter, so a blank " + "diameter means the model's own scale" +) + + +def normalization(settings: Settings) -> dict[str, Any]: + """Return the full normalisation given to Cellpose: its defaults now, with the user's values. + + The defaults (``tile_norm_blocksize``, ``sharpen_radius``, ``invert``, ``lowhigh``, ...) come + from Cellpose's module global at call time, copied; ``normalize`` (always on: a setting + that is not True is refused) and the percentiles are then set. Nothing is left to Cellpose's + defaults, so the record holds all. + """ + if settings.normalize is not True: # Settings refuses it; never reach Cellpose without it + raise SegmentationError(NORMALIZE_REFUSAL) + return { + **default_normalization(), + "normalize": True, + "percentile": list(NORMALIZE_PERCENTILE), + } + + +def eval_arguments(loaded: LoadedModel, settings: Settings) -> dict[str, Any]: + """Return every argument given to ``model.eval``, the effective inference settings. + + ``channel_axis`` is 0: the stack from :meth:`.segmentation_handoff.SegmentationPlan.read` + is ``(C, Y, X)`` in the order of the requested channel IDs. The tile size, the full + normalisation, the flow iterations and the other values Cellpose would default are given + explicitly, so what is recorded is what ran. + """ + return { + "batch_size": settings.batch_size, + "resample": True, + "channel_axis": 0, + "normalize": normalization(settings), + "diameter": settings.diameter, + "flow_threshold": settings.flow_threshold, + "cellprob_threshold": settings.cellprob_threshold, + "do_3D": False, + "min_size": MIN_SIZE, + "max_size_fraction": MAX_SIZE_FRACTION, + "niter": flow_iterations(settings), + "augment": False, + "tile_overlap": TILE_OVERLAP, + "bsize": loaded.tile_size, + } + + +def inference_parameters( + loaded: LoadedModel, settings: Settings, channel_ids: Sequence[str] +) -> dict[str, Any]: + """Return the parameters of a batch for the record: every effective setting, plain JSON. + + The diameter is in pixels, or null with the statement that it is the model's native + scale; ``rescale`` is the factor Cellpose derives from it (30 / diameter, or 1). The + normalisation is the full dictionary given to Cellpose and ``niter`` the flow iterations + it derives from the rescale. ``weights_downloaded`` says whether this session downloaded + the built-in weights; ``weights_source``, ``weights_repository`` and ``weights_revision`` + where from (the URL, the Hugging Face repository and its commit; null for a model file of + one's own); the file's SHA-256 is the batch's model ``sha256``. ``dinov3_source`` names + the DINOv3 repository of ``dinov3_commit`` and ``dinov3_installed`` whether this session + installed it. ``notes`` holds Cellpose's device behaviour + (:data:`.segmentation_cellpose_model.DEVICE_NOTE`) for a GPU run. + """ + arguments = eval_arguments(loaded, settings) + notes = [DEVICE_NOTE] if loaded.device != "cpu" else [] + return { + **arguments, + "diameter_unit": "pixels" if settings.diameter is not None else NATIVE_SCALE, + "rescale": rescale_factor(settings), + "channel_ids_order": list(channel_ids), + "device_type": loaded.device, + "backbone": loaded.backbone, + "use_bfloat16": True, + "cellpose_version": CELLPOSE_VERSION, + "dinov3_commit": loaded.dinov3_commit, + "dinov3_source": DINOV3_URL if loaded.dinov3_commit else None, + "dinov3_installed": loaded.dinov3_installed, + "weights_downloaded": loaded.downloaded, + "weights_source": loaded.source, + "weights_repository": loaded.repository, + "weights_revision": loaded.revision, + "notes": notes, + } + + +__all__ = [ + "MAX_SIZE_FRACTION", + "MIN_SIZE", + "NATIVE_SCALE", + "NORMALIZE_PERCENTILE", + "TILE_OVERLAP", + "eval_arguments", + "inference_parameters", + "normalization", +] diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_model.py b/src/morphobricks_preprocessing/segmentation_cellpose_model.py index 6b1440f9..d431ebee 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_model.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_model.py @@ -1,4 +1,4 @@ -"""Loading a Cellpose model without substitution, device fallback or silent download. +"""Loading a Cellpose model without substitution, device fallback or unchecked download. Part of :mod:`.segmentation_cellpose` (which re-exports these names). Cellpose, ``torch`` and ``dinov3`` are imported only inside the functions here, so importing this module stays inert; @@ -11,9 +11,16 @@ device is unavailable-refused up front, and after loading **every parameter and every buffer** of the network (``model.net``) must sit on a device of the requested type (``cuda:1`` counts as ``cuda``; the index is not checked). ``model.device`` is not evidence: Cellpose 4.2.1.1 only -stores the device it was given. Uncached weights are downloaded only with ``allow_download``; -whether they were, and from where, goes into the record. The weights file is hashed for the -record. +stores the device it was given. + +Built-in weights are never downloaded by Cellpose: choosing the model and loading it is the +consent to download that model's file (owner, issue #574), which +:mod:`.segmentation_cellpose_weights` fetches from a pinned revision and checks against its +pinned SHA-256 (a copy on disk too); Cellpose is then handed the file's absolute path. A +``cpdino`` model also needs the DINOv3 package (the code of its network; its weights are all in +the Cellpose file), installed at :data:`DINOV3_COMMIT` on first use (:func:`ensure_dinov3`). +Whether the weights were downloaded, from which repository, revision and URL, and the file's +SHA-256 go into the record. """ from __future__ import annotations @@ -23,13 +30,25 @@ import importlib.util import json import os +import re import subprocess import sys +import warnings +from collections.abc import Iterator +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from types import ModuleType from ._io import file_sha256 +from .segmentation_cellpose_weights import ( + WEIGHTS_REPOSITORY, + WEIGHTS_REVISION, + Progress, + changed_refusal, + fetch_weights, + file_identity, +) from .segmentation_record import DEVICES, SegmentationError CELLPOSE_VERSION = "4.2.1.1" @@ -44,6 +63,8 @@ """The DINOv3 commit installed for ``cpdino`` models: the head of its default branch on 22 November 2026, **not verified against cpdino** (it is a pin, not a tested pairing). A model that needs DINOv3 runs only with exactly this commit installed.""" +DINOV3_LABEL = "Installing DINOv3 (the network code of the cpdino models)…" +"""What the notebook shows while DINOv3 is installed (:func:`ensure_dinov3`).""" DEVICE_NOTE = ( "The device recorded is where the network's tensors were verified to sit; Cellpose's " "post-processing is not covered by that check. Cellpose may move the flow-threshold quality " @@ -52,6 +73,12 @@ "own behaviour; it is not refused." ) """Recorded with a batch that ran on a GPU (not refused: the network still runs on the device).""" +SPARSE_WARNING = "Sparse invariant checks are implicitly disabled" +"""The start of the one torch ``UserWarning`` hidden while Cellpose runs +(:func:`sparse_warning_hidden`).""" +SPARSE_WARNING_MODULES = r"(cellpose|torch)(\.|$)" +"""The modules it is hidden from: torch's own, or Cellpose's (``cellpose.dynamics`` builds the +sparse tensor; a warning from torch's C++ code is attributed to that caller).""" SAM_TILE, DINO_TILE = 256, 384 """The tile size (``bsize``) of a SAM model and of a DINOv3 model.""" @@ -117,6 +144,12 @@ def installed_version(distribution: str) -> str | None: def _cellpose_models() -> ModuleType: """Import ``cellpose.models`` of the pinned release, or refuse.""" + _check_cellpose_version() + return importlib.import_module("cellpose.models") + + +def _check_cellpose_version() -> None: + """Refuse unless the pinned Cellpose release is installed (nothing is imported).""" found = installed_version("cellpose") if found != CELLPOSE_VERSION: have = f"version {found} is installed" if found else "it is not installed" @@ -124,7 +157,6 @@ def _cellpose_models() -> ModuleType: f"This notebook runs Cellpose {CELLPOSE_VERSION}; {have}. Run the install cell, " "then restart the runtime if it asks." ) - return importlib.import_module("cellpose.models") def _torch() -> ModuleType: @@ -237,8 +269,14 @@ def dinov3_install_command() -> list[str]: ] +def dinov3_present() -> bool: + """Return whether a ``dinov3`` package is installed, whatever its commit (nothing imported).""" + importlib.invalidate_caches() + return bool(importlib.metadata.packages_distributions().get("dinov3")) + + def install_dinov3() -> None: - """Install DINOv3 at the pinned commit (only ever called when the user chooses to). + """Install DINOv3 at the pinned commit (:func:`ensure_dinov3`, for a ``cpdino`` model). Raises ------ @@ -253,11 +291,33 @@ def install_dinov3() -> None: ) from exc +def ensure_dinov3(progress: Progress | None = None) -> bool: + """Install DINOv3 at :data:`DINOV3_COMMIT` when no DINOv3 is installed; return True if it was. + + Called for a ``cpdino`` model only, before Cellpose is imported, so that Cellpose finds it + (choosing that model and loading it is the consent, as for its weights). A DINOv3 already + installed at another or an unknown commit is the user's own and is not replaced: + :func:`check_dinov3` refuses it, naming the command. + + Raises + ------ + SegmentationError + When the installation fails. + """ + if dinov3_present(): + return False + if progress is not None: + progress(DINOV3_LABEL, 0, 0) + install_dinov3() + return True + + def check_dinov3(models: ModuleType) -> str: """Return the commit of the installed DINOv3 if it is the pinned one, else refuse. - Cellpose imports DINOv3 when it is first imported, so DINOv3 installed after that needs a - restart of the runtime (the check says so): install it, restart, then load the model. + Cellpose 4.2.1.1 imports DINOv3 once, when ``cellpose.vit`` is first imported (it then + defines ``CPDINO`` whether or not that worked), so a DINOv3 installed after that needs a + restart of the runtime; the check looks at ``cellpose.vit`` itself and says so. """ command = " ".join(dinov3_install_command()[2:]) commit = installed_dinov3_commit() @@ -268,17 +328,41 @@ def check_dinov3(models: ModuleType) -> str: else "none is installed, or its commit is unknown" ) raise SegmentationError( - f"The DINOv3 models need DINOv3 at commit {DINOV3_COMMIT}; {found}. Tick the " - f"installation in the notebook (it runs: {command}), then restart the runtime." + f"The DINOv3 models need DINOv3 at commit {DINOV3_COMMIT}; {found}. A DINOv3 of " + f"your own is not replaced: uninstall it (pip uninstall dinov3), or install the " + f"pinned one ({command}), then restart the runtime and press the button again." ) - if not hasattr(models, "CPDINO"): + vit = sys.modules.get("cellpose.vit") # imported with ``models`` + if not hasattr(vit, "dinov3_vitl16"): raise SegmentationError( - "DINOv3 is installed but Cellpose was imported before it. Restart the runtime, then " - "run the cells again." + f"DINOv3 is installed (commit {commit[:12]}), but Cellpose was imported in this " + "runtime before it was there. Restart the runtime (Colab: Runtime > Restart " + "session), run the cells again and press the button again; nothing is downloaded " + "again." ) return commit +@contextmanager +def sparse_warning_hidden() -> Iterator[None]: + """Hide torch's "Sparse invariant checks are implicitly disabled" warning in the block only. + + Cellpose 4.2.1.1's ``dynamics.py`` builds a sparse tensor and torch warns that its invariant + checks are off. Those checks only validate sparse tensors; they change no result, so nothing + is recorded. Only a ``UserWarning`` starting :data:`SPARSE_WARNING` from the modules + :data:`SPARSE_WARNING_MODULES` is filtered, inside ``warnings.catch_warnings()`` (never a + global filter: the filters are put back when the block ends); every other warning shows. + """ + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=re.escape(SPARSE_WARNING), + category=UserWarning, + module=SPARSE_WARNING_MODULES, + ) + yield + + # --- loading and verifying a model ------------------------------------------------------------ @@ -304,14 +388,18 @@ class LoadedModel: downloaded True when this call downloaded the built-in weights (they were not on disk). source - Where Cellpose downloads the built-in weights from (its URL on Hugging Face), or None - for a custom model file. + The URL the built-in weights are downloaded from (the pinned revision on Hugging + Face, :func:`.segmentation_cellpose_weights.weights_url`), or None for a model file. + repository, revision + The Hugging Face repository and the commit of that URL, or None for a model file. backbone Cellpose's name of the network (``sam_vitl``, ``dino_vitl``, ...). tile_size The tile size (``bsize``) used: 256 for a SAM network, 384 otherwise. dinov3_commit The DINOv3 commit for a DINOv3 network, else None. + dinov3_installed + True when this call installed DINOv3 (it was not installed). """ model: object @@ -325,39 +413,9 @@ class LoadedModel: dinov3_commit: str | None = None downloaded: bool = False source: str | None = None - - -def _source(models: ModuleType, choice: ModelChoice) -> str | None: - """Return the URL Cellpose downloads built-in weights ``choice`` from, None for a file.""" - return None if choice.path is not None else f"{models._MODEL_URL}{choice.name}" - - -def _expected( - models: ModuleType, choice: ModelChoice, allow_download: bool -) -> tuple[Path, str, bool]: - """Return the weights file, what to hand to Cellpose to load it, and whether it downloads. - - A built-in model already on disk is handed over by its absolute path, so Cellpose looks - nowhere else (not in the working folder, not in its list of user models) and cannot - download. One that is not on disk is handed over by name only when ``allow_download``. - """ - if choice.path is not None: - return choice.path, os.fspath(choice.path), False - expected = Path(os.fspath(models.MODEL_DIR)) / choice.name - if expected.is_file(): - return expected, os.fspath(expected), False - if not allow_download: - raise SegmentationError( - f"The weights of {choice.name} are not on this computer ({expected}). The built-in " - f"weights are downloaded from Hugging Face ({_source(models, choice)}) on first use. " - "Allow the download on purpose (tick it in the notebook) and run the cell again." - ) - if os.path.lexists(choice.name): - raise SegmentationError( - f"A file or folder named {choice.name} is in the working folder, and Cellpose would " - "load it instead of downloading the model. Change to another working folder." - ) - return expected, choice.name, True + repository: str | None = None + revision: str | None = None + dinov3_installed: bool = False def _construct(models: ModuleType, request: str, device: str) -> object: @@ -416,32 +474,65 @@ def _verify(loaded: object, expected: Path, device: str, choice: ModelChoice) -> ) +def _identity(path: Path) -> tuple[int, int, int, int] | None: + """Return the weights file's :func:`.segmentation_cellpose_weights.file_identity`, or None.""" + try: + return file_identity(path) + except OSError: + return None + + def load_model( - model: str | os.PathLike, device: str, *, allow_download: bool = False + model: str | os.PathLike, device: str, *, progress: Progress | None = None ) -> LoadedModel: """Load a Cellpose model, verified to be the weights file and device asked for. - The order is: the model and device are validated, Cellpose's version is checked, the - weights must be on disk (or the download allowed), a DINOv3 model needs the pinned - DINOv3; then the model is loaded and **verified** (the weights file it reports is the one - asked for; every parameter and buffer of the network sits on the stated device type), and - the weights file is hashed. + The order is: the model and device are validated; a DINOv3 model gets DINOv3 installed at + the pinned commit if none is (before Cellpose is imported); Cellpose's version is checked; + a built-in model's weights are downloaded if missing and checked against their pinned + SHA-256 (:func:`.segmentation_cellpose_weights.fetch_weights`); a DINOv3 model needs the + pinned DINOv3; then the model is loaded from that file's absolute path and **verified** + (the weights file it reports is the one asked for; every parameter and buffer of the + network sits on the stated device type). The file's identity (device, inode, size, + modification time) taken when it was hashed must be the same right before Cellpose opens it + and after Cellpose loaded it (and, for a model file of one's own, after it was hashed): + Cellpose would download ``cpsam_v2`` from its moving branch for a path that is gone, and a + file replaced in between is not the one recorded. Choosing the model and calling this is + the consent to those downloads; nothing else is fetched and no other model is used. + + Parameters + ---------- + progress + Told ``(label, done, total)`` while weights download (bytes) or DINOv3 installs. Raises ------ SegmentationError For an unknown model or one that does not exist, a device that is not available or - not the one the model sits on, a substituted model, weights that are not downloaded - (and no ``allow_download``), another Cellpose version or another DINOv3 commit. + not the one the model sits on, a substituted model, weights that cannot be downloaded + or are not the pinned file, a weights file that changed after it was checked, another + Cellpose version or another DINOv3 commit. """ choice = choose_model(model) check_device(device) - models = _cellpose_models() dino = choice.name in DINO_MODELS + _check_cellpose_version() + installed = ensure_dinov3(progress) if dino else False + models = _cellpose_models() commit = check_dinov3(models) if dino else None - expected, request, downloads = _expected(models, choice, allow_download) - loaded = _construct(models, request, device) + if choice.path is not None: + expected, weights = choice.path, None + identity = _identity(expected) + else: + weights = fetch_weights(choice.name, os.fspath(models.MODEL_DIR), progress) + expected, identity = weights.path, weights.identity + if _identity(expected) != identity: # gone now: Cellpose would download cpsam_v2 instead + raise changed_refusal(expected) + loaded = _construct(models, os.fspath(expected), device) _verify(loaded, expected, device, choice) + sha256 = file_sha256(expected) if weights is None else weights.sha256 + if _identity(expected) != identity: # the file Cellpose read may not be the one hashed + raise changed_refusal(expected) backbone = getattr(loaded, "backbone", None) if not isinstance(backbone, str): raise SegmentationError("The loaded model does not say which network it is; refused.") @@ -452,11 +543,14 @@ def load_model( name=choice.name, file=os.fspath(expected) if choice.path else expected.name, path=expected, - sha256=file_sha256(expected), + sha256=sha256, device=device, backbone=backbone, tile_size=SAM_TILE if backbone == "sam_vitl" else DINO_TILE, dinov3_commit=commit, - downloaded=downloads, - source=_source(models, choice), + downloaded=weights is not None and weights.downloaded, + source=None if weights is None else weights.url, + repository=None if weights is None else WEIGHTS_REPOSITORY, + revision=None if weights is None else WEIGHTS_REVISION, + dinov3_installed=installed, ) diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_weights.py b/src/morphobricks_preprocessing/segmentation_cellpose_weights.py new file mode 100644 index 00000000..ebc44c9e --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_cellpose_weights.py @@ -0,0 +1,322 @@ +"""The built-in Cellpose weights: pinned, downloaded on first use, checked by their SHA-256. + +Part of :mod:`.segmentation_cellpose_model`. Owner decision (issue #574, 26 November 2026): +choosing a built-in model and pressing **Preview** or **Segment** (or **Load the model**) is the +consent to download that model's weights; there is no separate tick. What is downloaded, and +how, is fixed here rather than left to Cellpose 4.2.1.1, which fetches +``.../resolve/main/`` (a moving branch) with TLS verification turned off and checks +nothing: + +- **Only the chosen model's file.** One file of :data:`PINNED_WEIGHTS`, by its name, from the + Hugging Face repository :data:`WEIGHTS_REPOSITORY` at the commit :data:`WEIGHTS_REVISION` + (:func:`weights_url`), with the default TLS verification. Nothing else is fetched; another + model is never used instead. +- **Checked.** The bytes downloaded must have the pinned size and SHA-256 (the hashes are those + Hugging Face lists for the files at that commit, its LFS object IDs); they go to a temporary + file next to the target and replace it only once checked. A copy already in Cellpose's model + folder is hashed and must match too: a copy that differs is refused, never used or replaced. +- **A refusal, never a fallback.** A failed or blocked download, or bytes that do not match, + stop the load with a message naming the model and the source; no partial file is left. +- **Seen.** ``progress(label, done, total)`` is told the bytes received (``total`` is 0 when the + server gives no size) so the notebook can show "Downloading weights…" with a bar. +""" + +from __future__ import annotations + +import hashlib +import http.client +import os +import tempfile +import urllib.error +import urllib.request +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType + +from ._io import file_sha256 +from .segmentation_record import SegmentationError + +WEIGHTS_HOST = "https://huggingface.co" +WEIGHTS_REPOSITORY = "mouseland/cellpose-sam" +"""The Hugging Face repository Cellpose 4.2.1.1 downloads its built-in weights from.""" +WEIGHTS_REVISION = "7c61431b5fbb078f3296754bd15d9f51b320f837" +"""The commit of :data:`WEIGHTS_REPOSITORY` downloaded from: the head of ``main`` on +26 November 2026 (its last change, 17 May 2026, renamed ``cpdino_vitb`` to ``cpdino-vitb``).""" +CHUNK = 1 << 20 +"""Bytes read from the server at a time.""" +TIMEOUT = 60 +"""Seconds without an answer from the server before the download is refused.""" + + +@dataclass(frozen=True) +class PinnedFile: + """The SHA-256 and the size in bytes of one weights file at :data:`WEIGHTS_REVISION`.""" + + sha256: str + size: int + + +PINNED_WEIGHTS = MappingProxyType( + { + "cpsam_v2": PinnedFile( + "0f1cc3f7ecdd8a037a57c6c48d9d8921391be4cbce3fa9f13c3e3a2e1253c667", 1233586851 + ), + "cpsam": PinnedFile( + "e1440429eb384f95afe32bcba6510f90d518eaedc917ede549bed6804004abe2", 1233587898 + ), + "cpdino": PinnedFile( + "fad0dda262554922da1c5ab0e0004b00c1b14b8a48bea6781b89222567577573", 1213987717 + ), + "cpdino-vitb": PinnedFile( + "3ed4c06a3963ab13ff377d4e2957174aaaf637434eb031ae9931fcbfaf9a217f", 343599997 + ), + } +) +"""Every built-in model's file at :data:`WEIGHTS_REVISION`, as Hugging Face lists it.""" + +Progress = Callable[[str, int, int], None] +"""``progress(label, done, total)``: what is being fetched, bytes received, bytes in all (0 for +unknown).""" + + +@dataclass(frozen=True) +class WeightsFile: + """A built-in model's weights file on disk, checked against its pin. + + Attributes + ---------- + name + The built-in model's name (also the file's name). + path + The file in Cellpose's model folder. + sha256 + Its SHA-256, equal to the pinned one. + url + Where it is downloaded from (:func:`weights_url`). + repository, revision + :data:`WEIGHTS_REPOSITORY` and :data:`WEIGHTS_REVISION`. + downloaded + True when this call downloaded it; False when the copy on disk was used. + identity + The file's :func:`file_identity` when it was hashed (checked again after loading). + """ + + name: str + path: Path + sha256: str + url: str + repository: str = WEIGHTS_REPOSITORY + revision: str = WEIGHTS_REVISION + downloaded: bool = False + identity: tuple[int, int, int, int] | None = None + + +def weights_url(name: str) -> str: + """Return the URL of built-in model ``name``'s file at :data:`WEIGHTS_REVISION`.""" + return f"{WEIGHTS_HOST}/{WEIGHTS_REPOSITORY}/resolve/{WEIGHTS_REVISION}/{name}" + + +def download_label(name: str) -> str: + """Return what the notebook shows while ``name``'s weights download.""" + return f"Downloading {name} weights…" + + +def _pinned(name: str) -> PinnedFile: + """Return the pin of built-in model ``name``, or refuse a name without one.""" + pin = PINNED_WEIGHTS.get(name) + if pin is None: + raise SegmentationError( + f"There are no pinned weights for {name!r}; only {', '.join(PINNED_WEIGHTS)} are " + "downloaded. Give the path of a model file instead." + ) + return pin + + +def _open_url(url: str, timeout: float) -> object: + """Open ``url`` for reading (a seam for the tests: they never download).""" + return urllib.request.urlopen(url, timeout=timeout) + + +def _refusal(name: str, url: str, why: str) -> SegmentationError: + """Return the refusal of a download that did not give the pinned file.""" + return SegmentationError( + f"The weights of {name} could not be downloaded from {url} ({why}). Nothing was loaded, " + "no other model is used and no partial file is kept. Check the internet access (a " + "proxy or firewall may block huggingface.co), then press the button again." + ) + + +def file_identity(path: str | os.PathLike) -> tuple[int, int, int, int]: + """Return a file's identity now: its device, inode, size and modification time (ns). + + Taken when the file is hashed and compared after Cellpose loads it + (:func:`.segmentation_cellpose_model.load_model`): a file replaced, removed or written to + in between is another file than the one hashed. + + Raises + ------ + OSError + When the file cannot be read (it is gone, say). + """ + found = os.stat(path) + return (found.st_dev, found.st_ino, found.st_size, found.st_mtime_ns) + + +def fetch_weights( + name: str, model_dir: str | os.PathLike, progress: Progress | None = None +) -> WeightsFile: + """Return built-in model ``name``'s pinned weights file, downloading it when missing. + + Parameters + ---------- + name + One of :data:`PINNED_WEIGHTS`. + model_dir + Cellpose's model folder (``cellpose.models.MODEL_DIR``), where the file is kept. + progress + Told ``(label, bytes received, bytes in all)`` while downloading; not called for a + copy already on disk. + + Raises + ------ + SegmentationError + For a copy on disk that is not the pinned file (or changed while it was hashed), a + download that fails or is blocked, bytes that are not the pinned size and SHA-256 (each + names the model and the source), or a file that cannot be written (it names the folder). + """ + pin, url = _pinned(name), weights_url(name) + target = Path(model_dir) / name + if target.is_file(): + before = file_identity(target) + found = file_sha256(target) + if found != pin.sha256: + raise SegmentationError( + f"The weights of {name} on this computer ({target}) are not the pinned file of " + f"{url}: SHA-256 {found}, expected {pin.sha256}. They are not used, and not " + "replaced. Delete that file (or move it away), then press the button again to " + "download the pinned weights." + ) + if file_identity(target) != before: + raise changed_refusal(target) + return WeightsFile(name, target, found, url, identity=before) + sha256 = _download(name, url, target, pin, progress) + return WeightsFile(name, target, sha256, url, downloaded=True, identity=file_identity(target)) + + +def changed_refusal(path: Path) -> SegmentationError: + """Return the refusal of a weights file that changed after it was hashed.""" + return SegmentationError( + f"The weights file {path} changed after it was checked (it was replaced, removed or " + "written to), so the model loaded may not be the file whose SHA-256 is recorded. " + "Nothing was segmented and that model is not used. Make sure nothing else writes to " + "Cellpose's model folder, then press the button again." + ) + + +def _write_refusal(name: str, folder: Path, exc: OSError) -> SegmentationError: + """Return the refusal of weights that could not be written on this computer.""" + return SegmentationError( + f"The weights of {name} could not be written to {folder} ({type(exc).__name__}: {exc}). " + "The disk may be full or the folder not writable; this is not a network problem. " + "Nothing was loaded and no partial file is kept. Free some space (the file is up to " + "1.2 GB) or make the folder writable, then press the button again." + ) + + +def _download(name: str, url: str, target: Path, pin: PinnedFile, progress: Progress | None) -> str: + """Download ``url`` to ``target`` through a checked temporary file; return its SHA-256.""" + try: + target.parent.mkdir(parents=True, exist_ok=True) + handle, temporary = tempfile.mkstemp(prefix=f".{name}.", suffix=".part", dir=target.parent) + except OSError as exc: + raise _write_refusal(name, target.parent, exc) from exc + try: + done, found = _stream(name, url, handle, target.parent, progress) + if (done, found) != (pin.size, pin.sha256): + raise _refusal( + name, + url, + f"received {done:,} bytes with SHA-256 {found}; the pinned file has " + f"{pin.size:,} bytes and SHA-256 {pin.sha256}", + ) + try: + os.replace(temporary, target) + except OSError as exc: + raise SegmentationError( + f"The weights of {name} were downloaded and checked but could not be moved to " + f"{target} ({type(exc).__name__}: {exc}). Nothing was loaded and no partial " + "file is kept. Check that the folder is writable, then press the button again." + ) from exc + finally: + if os.path.exists(temporary): + os.remove(temporary) + return found + + +def _stream( + name: str, url: str, handle: int, folder: Path, progress: Progress | None +) -> tuple[int, str]: + """Write ``url``'s bytes to the open file ``handle``, synced; return their count and hash. + + A network error is a download refusal; a write error (a full disk) is a write refusal. + """ + label, digest, done = download_label(name), hashlib.sha256(), 0 + network = (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) + out = os.fdopen(handle, "wb") + try: + try: + response = _open_url(url, TIMEOUT) + except urllib.error.HTTPError as exc: + raise _refusal(name, url, f"the server answered {exc.code} {exc.reason}") from exc + except network as exc: + why = getattr(exc, "reason", None) or exc + raise _refusal(name, url, f"{type(exc).__name__}: {why}") from exc + with response: + size = response.headers.get("Content-Length") + total = int(size) if size and size.isdigit() else 0 + if progress is not None: + progress(label, 0, total) + while True: + try: + block = response.read(CHUNK) + except network as exc: + why = getattr(exc, "reason", None) or exc + raise _refusal(name, url, f"{type(exc).__name__}: {why}") from exc + if not block: + break + try: + out.write(block) + except OSError as exc: + raise _write_refusal(name, folder, exc) from exc + digest.update(block) + done += len(block) + if progress is not None: + progress(label, done, total) + try: + out.flush() + os.fsync(out.fileno()) # on disk before the rename makes it the weights file + out.close() + except OSError as exc: + raise _write_refusal(name, folder, exc) from exc + finally: + out.close() + return done, digest.hexdigest() + + +__all__ = [ + "CHUNK", + "PINNED_WEIGHTS", + "TIMEOUT", + "WEIGHTS_HOST", + "WEIGHTS_REPOSITORY", + "WEIGHTS_REVISION", + "PinnedFile", + "Progress", + "WeightsFile", + "changed_refusal", + "download_label", + "fetch_weights", + "file_identity", + "weights_url", +] diff --git a/tests/cellpose_stub.py b/tests/cellpose_stub.py index f79fbf8f..f2190256 100644 --- a/tests/cellpose_stub.py +++ b/tests/cellpose_stub.py @@ -3,13 +3,19 @@ Cellpose is not a dependency of the brick and is not installed in CI. The stand-in keeps what the real ``CellposeModel`` does that matters here, read from the 4.2.1.1 source: a name or path it cannot find is replaced by ``cpsam_v2`` (downloaded if absent), a built-in name is looked for -in ``MODEL_DIR`` and fetched when missing, and ``pretrained_model`` / ``device`` / ``backbone`` -are set on the loaded model. As in 4.2.1.1 ``device`` is only the device it was given; where +in ``MODEL_DIR`` and fetched when missing (``cellpose_downloaded``: the brick hands Cellpose a +path, so this must stay empty), and ``pretrained_model`` / ``device`` / ``backbone`` are set on +the loaded model. Nothing is ever downloaded: the brick's own download +(:mod:`.segmentation_cellpose_weights`) gets the stand-in bytes of :func:`weights_bytes` +(``downloaded``), whose SHA-256 and size are made the pins; ``download_fail`` makes it fail. +As in 4.2.1.1 ``device`` is only the device it was given; where the weights sit is told by ``net`` (parameters and buffers with a ``device``). Its ``eval`` records every call (the stack and the keywords) and returns a fixed label image, so a test sees exactly what Cellpose was given. """ +import hashlib +import io import logging import sys import types @@ -19,6 +25,7 @@ import numpy as np from morphobricks_preprocessing import segmentation_cellpose_model as model_module +from morphobricks_preprocessing import segmentation_cellpose_weights as weights_module from morphobricks_preprocessing.run_inputs import RunInputs from test_segmentation_handoff import EXTRA_FIRST from test_stage3_channels import described_run, extra_stain @@ -87,6 +94,8 @@ def __init__(self, gpu=False, pretrained_model="cpsam_v2", device=None, **kwargs state.constructed.append( SimpleNamespace(gpu=gpu, pretrained_model=pretrained_model, device=device, **kwargs) ) + if state.on_construct is not None: # something else touches the file meanwhile + state.on_construct(pretrained_model) if state.cpdino_log: # 4.2.1.1 logs this when cellpose.models cannot import DINOv3 logging.getLogger("cellpose.models").warning(CPDINO_WARNING) self.pretrained_model = state.substitute or self._resolve(pretrained_model) @@ -106,7 +115,7 @@ def _resolve(requested): ) return str(state.models_dir / "cpsam_v2") # the silent substitution if not path.exists(): - state.downloaded.append(requested) + state.cellpose_downloaded.append(requested) data = weights_bytes(requested) # As cellpose.utils.download_url_to_file: a bar of cellpose.utils.tqdm. bar_class = sys.modules["cellpose.utils"].tqdm @@ -135,8 +144,10 @@ def modules(state): models._MODEL_URL = "https://huggingface.co/mouseland/cellpose-sam/resolve/main/" models.normalize_default = dict(state.normalize_default) models.CellposeModel = model_class(state) - if state.has_cpdino: - models.CPDINO = object + models.CPDINO = object # 4.2.1.1 defines it whether or not DINOv3 imports + vit = types.ModuleType("cellpose.vit") + if state.has_cpdino: # what cellpose.vit imports from DINOv3 when it can + vit.dinov3_vitl16 = vit.dinov3_vitb16 = object plot = types.ModuleType("cellpose.plot") def show_segmentation(fig, img, maski, flowi, channels=(0, 0), file_name=None): @@ -149,7 +160,7 @@ def show_segmentation(fig, img, maski, flowi, channels=(0, 0), file_name=None): utils = types.ModuleType("cellpose.utils") utils.tqdm = TextBar # Cellpose's own: tqdm's plain text bar package = types.ModuleType("cellpose") - package.models, package.plot, package.utils = models, plot, utils + package.models, package.plot, package.utils, package.vit = models, plot, utils, vit torch = types.ModuleType("torch") torch.device = Device torch.cuda = SimpleNamespace(is_available=lambda: state.cuda) @@ -159,6 +170,7 @@ def show_segmentation(fig, img, maski, flowi, channels=(0, 0), file_name=None): "cellpose.models": models, "cellpose.plot": plot, "cellpose.utils": utils, + "cellpose.vit": vit, "torch": torch, } @@ -169,8 +181,10 @@ def install(monkeypatch, tmp_path, **options): Switches (set on the returned state before loading): ``cuda`` / ``mps`` availability, ``substitute`` (the path every loaded model reports, whatever was asked), ``params`` / ``buffers`` (the device types of the network's tensors, when not the requested one), - ``no_net``, ``fail`` (a function of the stack that raises), ``version`` and - ``dinov3_commit``. + ``no_net``, ``fail`` (a function of the stack that raises), ``version``, + ``dinov3_commit`` (None: no DINOv3 installed; ``install_dinov3`` then installs the pinned + one and records it in ``dinov3_installs``), ``dinov3_present`` (a DINOv3 of unknown commit) + and ``download_fail`` (an exception the download raises). """ models_dir = tmp_path / "cellpose_models" models_dir.mkdir(exist_ok=True) @@ -180,6 +194,11 @@ def install(monkeypatch, tmp_path, **options): constructed=[], bars=[], downloaded=[], + urls=[], + cellpose_downloaded=[], + dinov3_installs=[], + dinov3_present=False, + download_fail=None, models_dir=models_dir, cuda=False, mps=False, @@ -192,6 +211,7 @@ def install(monkeypatch, tmp_path, **options): dinov3_commit=model_module.DINOV3_COMMIT, has_cpdino=True, cpdino_log=False, + on_construct=None, normalize_default={ "lowhigh": None, "percentile": None, @@ -217,9 +237,56 @@ def install(monkeypatch, tmp_path, **options): lambda name: state.version if name == "cellpose" else real_version(name), ) monkeypatch.setattr(model_module, "installed_dinov3_commit", lambda: state.dinov3_commit) + fetching(monkeypatch, state) return state +def fetching(monkeypatch, state): + """Stand in for DINOv3's installation and the weights download (nothing is fetched).""" + monkeypatch.setattr( + model_module, + "dinov3_present", + lambda: state.dinov3_commit is not None or state.dinov3_present, + ) + + def install_dinov3(): + state.dinov3_installs.append(model_module.DINOV3_COMMIT) + state.dinov3_commit = model_module.DINOV3_COMMIT + + monkeypatch.setattr(model_module, "install_dinov3", install_dinov3) + monkeypatch.setattr(weights_module, "PINNED_WEIGHTS", fake_pins()) + monkeypatch.setattr(weights_module, "_open_url", lambda url, timeout: served(state, url)) + + +def fake_pins(): + """Return pins for the stand-in bytes of every built-in model (as the real pins are).""" + return { + name: weights_module.PinnedFile( + hashlib.sha256(weights_bytes(name)).hexdigest(), len(weights_bytes(name)) + ) + for name in BUILTINS + } + + +class Response(io.BytesIO): + """What ``urlopen`` returns: a readable body with headers.""" + + def __init__(self, data, headers): + super().__init__(data) + self.headers = headers + + +def served(state, url): + """Answer the brick's download of ``url`` with the stand-in bytes (never the network).""" + name = url.rsplit("/", 1)[-1] + state.downloaded.append(name) + state.urls.append(url) + if state.download_fail is not None: + raise state.download_fail + data = weights_bytes(name) + return Response(data, {"Content-Length": str(len(data))}) + + def custom_model(tmp_path, name="my_model"): """Write a custom model file and return its path.""" path = tmp_path / "custom" / name diff --git a/tests/test_notebook_cellpose.py b/tests/test_notebook_cellpose.py index 63cc9d14..c395d5c0 100644 --- a/tests/test_notebook_cellpose.py +++ b/tests/test_notebook_cellpose.py @@ -11,6 +11,7 @@ import html import json import re +import urllib.error from pathlib import Path import numpy as np @@ -318,15 +319,28 @@ def test_an_unknown_or_missing_model_stops_the_cell_with_no_substitution(cells): assert cells.ns["workflow"].loaded.name == "my_model" -def test_the_weights_download_needs_its_box_and_the_cell_says_where_from(cells): +def test_loading_a_model_downloads_its_weights_and_the_cell_shows_it(cells): + # Owner (#574): choosing the model and pressing the button is the consent; no tick. cells.stub.models_dir.joinpath("cpsam_v2").unlink() open_and_choose(cells) - with pytest.raises(notebook_cellpose.CellStop, match="Hugging Face"): - run_cell(cells.ns, MODEL, device="cpu") - assert cells.stub.downloaded == [] - assert "downloaded from Hugging Face on first use" in " ".join(cells.ns["workflow"].shown) - run_cell(cells.ns, MODEL, device="cpu", download_weights=True) + run_cell(cells.ns, MODEL, device="cpu") + fields = cells.ns["workflow"].forms["model"].fields + assert "download_weights" not in fields and "install_dinov3" not in fields assert cells.stub.downloaded == ["cpsam_v2"] + shown = " ".join(cells.ns["workflow"].shown) + assert ( + "Downloading cpsam_v2 weights…" in shown and "checked against their pinned SHA-256" in shown + ) + + +def test_a_failed_download_stops_the_cell_naming_the_model_and_the_source(cells): + cells.stub.models_dir.joinpath("cpsam").unlink() + cells.stub.download_fail = urllib.error.URLError("blocked") + open_and_choose(cells) + with pytest.raises(notebook_cellpose.CellStop, match="weights of cpsam could not be") as caught: + run_cell(cells.ns, MODEL, model="cpsam", device="cpu") + assert "https://huggingface.co/mouseland/cellpose-sam/resolve/" in str(caught.value) + assert cells.ns["workflow"].loaded is None and cells.stub.constructed == [] def test_the_load_card_says_whether_the_weights_were_downloaded_and_from_where(cells): @@ -334,11 +348,13 @@ def test_the_load_card_says_whether_the_weights_were_downloaded_and_from_where(c run_cell(cells.ns, MODEL, device="cpu") assert "nothing downloaded" in cells.ns["workflow"].shown[-1] cells.stub.models_dir.joinpath("cpsam").unlink() - run_cell(cells.ns, MODEL, model="cpsam", device="cpu", download_weights=True) - assert "downloaded now from https://huggingface.co/" in cells.ns["workflow"].shown[-1] + run_cell(cells.ns, MODEL, model="cpsam", device="cpu") + url = "https://huggingface.co/mouseland/cellpose-sam/resolve/" + cp.WEIGHTS_REVISION + assert f"downloaded now from {url}/cpsam" in cells.ns["workflow"].shown[-1] run_cell(cells.ns, BATCH) params = read_record(cells.run.masks, "Cells").batches[0].parameters - assert params["weights_downloaded"] is True and params["weights_source"].endswith("/cpsam") + assert params["weights_downloaded"] is True and params["weights_source"] == url + "/cpsam" + assert params["weights_revision"] == cp.WEIGHTS_REVISION @pytest.mark.parametrize("cell", [PREVIEW, BATCH]) diff --git a/tests/test_notebook_cellpose_both.py b/tests/test_notebook_cellpose_both.py index 826ff4a4..d810b6d4 100644 --- a/tests/test_notebook_cellpose_both.py +++ b/tests/test_notebook_cellpose_both.py @@ -275,7 +275,7 @@ def test_the_record_of_both_is_plain_json_without_a_partner(cells): def settings_and_cell_model(workflow): """Set the cells' settings and load their model, as cell 5 does first.""" workflow.set_settings("", 0.4, 0.0, 8) - workflow.load("cpsam_v2", "", "cpu", False, False) + workflow.load("cpsam_v2", "", "cpu") def nothing_written(cells, *names): @@ -296,7 +296,7 @@ def refuse(*args, **kwargs): monkeypatch.setattr(cp, "load_model", refuse) with pytest.raises(notebook_cellpose.CellStop, match="no weights"): - workflow.load_nuclei("cpsam", "", "cpu", False, False) + workflow.load_nuclei("cpsam", "", "cpu") assert workflow.nuclei_loaded is None with pytest.raises( notebook_cellpose.CellStop, match="The nuclei have their own model: load it first" diff --git a/tests/test_notebook_cellpose_form.py b/tests/test_notebook_cellpose_form.py index 1d0e84a9..4f433ac4 100644 --- a/tests/test_notebook_cellpose_form.py +++ b/tests/test_notebook_cellpose_form.py @@ -84,8 +84,6 @@ def test_the_forms_start_with_the_former_defaults(): "model": "cpsam_v2", "custom_model_file": "", "device": "cuda", # never chosen for the user: an unavailable GPU is refused - "download_weights": False, - "install_dinov3": False, "diameter": "", "flow_threshold": 0.4, "cellprob_threshold": 0.0, @@ -121,8 +119,6 @@ def test_every_field_reaches_the_workflow_as_given(monkeypatch): "model": "cpdino", "custom_model_file": "/models/mine", "device": "mps", - "download_weights": True, - "install_dinov3": True, "diameter": "17.5", "flow_threshold": 0.7, "cellprob_threshold": -1.5, @@ -148,7 +144,7 @@ def test_every_field_reaches_the_workflow_as_given(monkeypatch): ("open", ("/data/run", "/data/masks")), ("choose_channels", ("Nuclear", "nuclei", "Nuclear2")), ("set_settings", ("17.5", 0.7, -1.5, 3)), - ("load", ("cpdino", "/models/mine", "mps", True, True)), + ("load", ("cpdino", "/models/mine", "mps")), ("preview", ("a/b.tif",)), ("run", (True,)), ] @@ -196,12 +192,19 @@ def test_a_refusal_is_shown_verbatim_in_a_red_card_and_the_form_can_be_pressed_a assert form.stopped is None and "Run opened" in workflow.shown[-1] -def test_nothing_downloads_without_the_tick(cells): - cells.stub.models_dir.joinpath("cpsam_v2").unlink() +def test_only_the_chosen_models_weights_download_and_only_when_it_loads(cells): + # Owner (#574): no tick; choosing the model and pressing the button is the consent. + for name in ("cpsam_v2", "cpsam"): + cells.stub.models_dir.joinpath(name).unlink() open_and_choose(cells) - with pytest.raises(notebook_cellpose.CellStop, match="Hugging Face"): - run_cell(cells.ns, MODEL, device="cpu") # the download box as the form starts: off - assert cells.stub.downloaded == [] and cells.stub.constructed == [] + assert cells.stub.downloaded == [] + run_cell(cells.ns, MODEL, device="cpu", model="cpsam") + assert cells.stub.downloaded == ["cpsam"] and cells.stub.cellpose_downloaded == [] + labels = [ + str(getattr(w, "description", "")) + for w in cells.ns["workflow"].forms["model"].fields.values() + ] + assert not any("download" in label.lower() or "DINOv3" in label for label in labels) def test_an_unavailable_gpu_is_refused_from_the_form_never_replaced_by_the_cpu(cells): @@ -212,25 +215,30 @@ def test_an_unavailable_gpu_is_refused_from_the_form_never_replaced_by_the_cpu(c assert cells.stub.constructed == [] and cells.ns["workflow"].loaded is None -def test_dinov3_is_installed_only_on_its_tick_and_says_to_restart(cells, monkeypatch): - installed = [] - monkeypatch.setattr(cp, "install_dinov3", lambda: installed.append(True)) +def test_dinov3_is_installed_on_first_use_of_a_cpdino_model_with_no_tick(cells): cells.stub.dinov3_commit = None open_and_choose(cells) - with pytest.raises(notebook_cellpose.CellStop, match="restart the runtime"): - run_cell(cells.ns, MODEL, device="cpu", model="cpdino", download_weights=True) - assert installed == [] - with pytest.raises(notebook_cellpose.CellStop, match="restart the runtime"): - run_cell( - cells.ns, - MODEL, - device="cpu", - model="cpdino", - download_weights=True, - install_dinov3=True, - ) - assert installed == [True] - assert "Installing DINOv3" in " ".join(cells.ns["workflow"].shown) + run_cell(cells.ns, MODEL, device="cpu", model="cpsam_v2") + assert cells.stub.dinov3_installs == [] # a SAM model does not need it + run_cell(cells.ns, MODEL, device="cpu", model="cpdino") + assert cells.stub.dinov3_installs == [cp.DINOV3_COMMIT] + shown = " ".join(cells.ns["workflow"].shown) + assert ( + "Installing DINOv3" in shown + and f"DINOv3 installed now at commit {cp.DINOV3_COMMIT}" in shown + ) + assert cells.ns["workflow"].loaded.dinov3_installed + + +def test_dinov3_installed_after_cellpose_was_imported_asks_for_a_restart(cells, monkeypatch): + import sys + + cells.stub.dinov3_commit = None + monkeypatch.delattr(sys.modules["cellpose.vit"], "dinov3_vitl16") # Cellpose imported first + open_and_choose(cells) + with pytest.raises(notebook_cellpose.CellStop, match="Restart the runtime"): + run_cell(cells.ns, MODEL, device="cpu", model="cpdino") + assert cells.stub.dinov3_installs == [cp.DINOV3_COMMIT] and cells.stub.constructed == [] def test_overwrite_stays_off_unless_ticked(cells): diff --git a/tests/test_notebook_cellpose_stepper.py b/tests/test_notebook_cellpose_stepper.py index 41dde69b..47a48b48 100644 --- a/tests/test_notebook_cellpose_stepper.py +++ b/tests/test_notebook_cellpose_stepper.py @@ -4,14 +4,14 @@ (chips, Back, Next): Folders, Output and channels, Model and preview, Segment. These tests press the widgets as a user would, with the stand-in Cellpose of ``tests/cellpose_stub.py``: the whole flow, the folder refusal at step 1, the run's images in the preprocessing viewer, -Preview loading the model once and reusing it, the download shown as one ``tqdm.auto`` bar, +Preview loading the model once and reusing it, the first-use download shown as one line (#574), and that no *What to do next* step is left. """ import html import logging import sys -import types +import urllib.error import pytest @@ -256,61 +256,67 @@ def test_the_nuclei_box_shows_for_both_only(mixed_run, stub): assert is_visible(box) and "Output Both: the nuclei" in texts(box) -# the download: one tqdm.auto bar, nothing else changes ----------------------------------------- +# the download on first use (#574): one "Downloading weights…" line, no tick ---------- -@pytest.fixture -def auto_bar(monkeypatch): - """A stand-in ``tqdm.auto`` that records the bars made (tqdm comes with Cellpose).""" - made = [] - - class Bar(TextBar): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - made.append(self) - - auto = types.ModuleType("tqdm.auto") - auto.tqdm = Bar - package = types.ModuleType("tqdm") - package.auto = auto - monkeypatch.setitem(sys.modules, "tqdm", package) - monkeypatch.setitem(sys.modules, "tqdm.auto", auto) - return made - - -def test_a_download_shows_one_notebook_bar_and_the_same_weights(mixed_run, stub, auto_bar): +def test_preview_downloads_the_chosen_models_weights_with_a_visible_line(mixed_run, stub): (stub.models_dir / "cpsam").unlink() app = ready(mixed_run) fields = app.workflow.forms["model"].fields - fields["model"].value, fields["download_weights"].value = "cpsam", True + assert "download_weights" not in fields and "install_dinov3" not in fields + fields["model"].value = "cpsam" preview(app) - assert stub.downloaded == ["cpsam"] - assert stub.bars == [download.notebook_bar] # Cellpose's bar, drawn by tqdm.auto - (bar,) = auto_bar - assert bar.kwargs["desc"] == download.BAR_LABEL and bar.kwargs["unit"] == "B" - assert bar.done == len(b"weights of cpsam") - assert sys.modules["cellpose.utils"].tqdm is TextBar # put back + assert stub.downloaded == ["cpsam"] and stub.cellpose_downloaded == [] + shown = " ".join(app.workflow.shown) + assert "Downloading cpsam weights…" in shown # the line as first shown assert app.workflow.loaded.downloaded and app.workflow.loaded.name == "cpsam" assert app.workflow.loaded.path == stub.models_dir / "cpsam" + preview(app) # loaded once, then reused: nothing downloads again + assert stub.downloaded == ["cpsam"] -def test_no_download_without_the_tick_even_with_the_quiet_display(mixed_run, stub, auto_bar): +def test_the_download_line_counts_megabytes_and_says_how_it_ended(): + shown = [] + line = download.DownloadLine(shown.append) + line.finish(True) + assert shown == [] and line.widget.value == "" # nothing to say: nothing shown + mb = download.MEGABYTE + line("Downloading cpsam weights…", 0, 300 * mb) + assert shown == [line.widget] + line("Downloading cpsam weights…", 300 * mb, 300 * mb) + value = html.unescape(line.widget.value) + assert "Downloading cpsam weights…" in value and "300 of 300" in value and "MB" in value + line.finish(True) + assert ( + "Downloading cpsam weights: done in" in line.widget.value and "mb-ok" in line.widget.value + ) + now = [0.0] + stopped = download.DownloadLine(shown.append, clock=lambda: now[0]) + stopped("Downloading cpdino weights…", 0, 0) + now[0] = 1.0 + stopped("Downloading cpdino weights…", 5 * mb, 0) # no size from the server: MB so far + assert "5 so far" in stopped.widget.value + stopped.finish(False) + assert "stopped after" in stopped.widget.value and "mb-error" in stopped.widget.value + + +def test_a_failed_download_on_preview_is_a_refusal_and_nothing_loads(mixed_run, stub): (stub.models_dir / "cpsam").unlink() + stub.download_fail = urllib.error.URLError("blocked") app = ready(mixed_run) app.workflow.forms["model"].fields["model"].value = "cpsam" form = app.workflow.forms["preview"] form.button.click() - assert "Allow the download on purpose" in form.refusal - assert stub.downloaded == [] and auto_bar == [] and stub.constructed == [] + assert "weights of cpsam could not be downloaded from https://huggingface.co/" in form.refusal + assert stub.constructed == [] and app.workflow.loaded is None and stub.calls == [] -def test_cellpose_logs_are_quiet_and_its_warnings_are_kept(stub, auto_bar): +def test_cellpose_logs_are_quiet_and_its_warnings_are_kept(stub): logger = logging.getLogger("cellpose") before = logger.propagate with download.quiet_cellpose() as said: logging.getLogger("cellpose.models").info("Downloading: noise") logging.getLogger("cellpose.models").warning("pretrained model x not found") - assert sys.modules["cellpose.utils"].tqdm is download.notebook_bar assert said == ["Warning: pretrained model x not found"] assert logger.propagate is before and sys.modules["cellpose.utils"].tqdm is TextBar @@ -327,12 +333,6 @@ def test_there_is_no_what_to_do_next_step(mixed_run, stub): assert not any("What to do next" in (getattr(w, "description", "") or "") for w in walk(app)) -def test_without_tqdm_auto_cellposes_own_bar_is_left_as_it_is(stub, monkeypatch): - monkeypatch.setitem(sys.modules, "tqdm.auto", None) # import tqdm.auto fails - with download.quiet_cellpose(): - assert sys.modules["cellpose.utils"].tqdm is TextBar - - # review of #548 --------------------------------------------------------------------------------- @@ -402,7 +402,7 @@ def test_the_model_chip_is_not_done_once_the_model_changes(mixed_run, stub): assert app.stepper.states()[2].done and "cpsam" in app.stepper.states()[2].text -def test_cellposes_unpinned_dinov3_advice_becomes_the_notebooks_pinned_tick(mixed_run, stub): +def test_cellposes_unpinned_dinov3_advice_becomes_the_notebooks_pinned_install(mixed_run, stub): # L2: Cellpose logs "run pip install git+.../dinov3" (unpinned) when it cannot import # DINOv3; the card points to the notebook's own pinned installation instead. from cellpose_stub import CPDINO_WARNING @@ -412,7 +412,7 @@ def test_cellposes_unpinned_dinov3_advice_becomes_the_notebooks_pinned_tick(mixe preview(app) (card,) = [s for s in app.workflow.shown if "Cellpose said" in s] assert "pip install" not in card and "git+" not in card - assert "Install DINOv3 now" in html.unescape(card) and "pinned commit" in card + assert "installs the pinned commit" in html.unescape(card) and "restart" in card with download.quiet_cellpose() as said: logging.getLogger("cellpose.models").warning(CPDINO_WARNING) assert said == ["Warning: " + download.CPDINO_NOTE] diff --git a/tests/test_segmentation_cellpose.py b/tests/test_segmentation_cellpose.py index 9ab6a4c4..7be97de1 100644 --- a/tests/test_segmentation_cellpose.py +++ b/tests/test_segmentation_cellpose.py @@ -185,28 +185,29 @@ def test_the_gpu_is_used_when_asked_and_present(stub): cp.load_model("cpsam_v2", "gpu") -# no silent download, the weights are hashed (audit B9) -------------------------------------- +# downloads on first use, checked; the weights are hashed (audit B9, #574) ------------------- -def test_weights_that_are_not_on_disk_are_not_downloaded_unless_allowed(stub): +def test_weights_not_on_disk_are_downloaded_on_first_use_and_given_to_cellpose_by_path(stub): + # Owner (#574): choosing the model and loading it is the consent; Cellpose never downloads. (stub.models_dir / "cpsam").unlink() - with pytest.raises(SegmentationError, match="Hugging Face"): - cp.load_model("cpsam", "cpu") - assert stub.constructed == [] and stub.downloaded == [] - loaded = cp.load_model("cpsam", "cpu", allow_download=True) - assert stub.downloaded == ["cpsam"] and stub.constructed[0].pretrained_model == "cpsam" + loaded = cp.load_model("cpsam", "cpu") + assert stub.downloaded == ["cpsam"] and stub.cellpose_downloaded == [] + assert stub.constructed[0].pretrained_model == str(stub.models_dir / "cpsam") assert loaded.sha256 == hashlib.sha256(weights_bytes("cpsam")).hexdigest() + assert loaded.downloaded and (stub.models_dir / "cpsam").read_bytes() == weights_bytes("cpsam") + cp.load_model("cpsam", "cpu") + assert stub.downloaded == ["cpsam"] # the second time: the checked copy on disk -def test_a_file_in_the_working_folder_that_shadows_a_download_is_refused( - stub, tmp_path, monkeypatch -): +def test_a_file_in_the_working_folder_cannot_shadow_the_weights(stub, tmp_path, monkeypatch): (stub.models_dir / "cpsam").unlink() (tmp_path / "cpsam").write_bytes(b"not the model") monkeypatch.chdir(tmp_path) - with pytest.raises(SegmentationError, match="working folder"): - cp.load_model("cpsam", "cpu", allow_download=True) - assert stub.constructed == [] + loaded = cp.load_model("cpsam", "cpu") + assert loaded.path == stub.models_dir / "cpsam" + assert stub.constructed[0].pretrained_model == str(stub.models_dir / "cpsam") + assert (tmp_path / "cpsam").read_bytes() == b"not the model" @pytest.mark.parametrize("found", [None, "4.2.0", "4.3.0"]) @@ -230,7 +231,7 @@ def test_the_model_name_file_and_weights_hash_are_in_the_record(run, stub): assert batch.run_manifest_sha256 == hashlib.sha256(manifest).hexdigest() -# DINOv3 models: installed only when chosen, at a pinned commit ------------------------------ +# DINOv3 models: installed on first use of one, at a pinned commit (#574) -------------------- def test_the_dinov3_install_command_pins_the_commit(): @@ -241,28 +242,43 @@ def test_the_dinov3_install_command_pins_the_commit(): assert len(cp.DINOV3_COMMIT) == 40 -@pytest.mark.parametrize("commit", [None, "0" * 40]) -def test_a_dino_model_needs_the_pinned_dinov3_commit(stub, commit): - stub.dinov3_commit = commit +@pytest.mark.parametrize("commit", ["0" * 40, None]) +def test_a_dino_model_refuses_a_dinov3_of_another_commit_and_does_not_replace_it(stub, commit): + stub.dinov3_commit, stub.dinov3_present = commit, True # None: installed, commit unknown with pytest.raises(SegmentationError, match=f"commit {cp.DINOV3_COMMIT}.*pip install"): - cp.load_model("cpdino", "cpu", allow_download=True) - assert stub.constructed == [] + cp.load_model("cpdino", "cpu") + assert stub.constructed == [] and stub.dinov3_installs == [] and stub.downloaded == [] cp.load_model("cpsam_v2", "cpu") # a SAM model needs no DINOv3 at all +def test_a_dino_model_installs_the_pinned_dinov3_when_none_is_there(stub): + stub.dinov3_commit = None + told = [] + loaded = cp.load_model("cpdino", "cpu", progress=lambda *a: told.append(a)) + assert stub.dinov3_installs == [cp.DINOV3_COMMIT] and loaded.dinov3_installed + assert told[0] == (cp.DINOV3_LABEL, 0, 0) + assert loaded.dinov3_commit == cp.DINOV3_COMMIT + again = cp.load_model("cpdino", "cpu") + assert stub.dinov3_installs == [cp.DINOV3_COMMIT] and not again.dinov3_installed + stub.dinov3_commit = None + cp.load_model("cpsam_v2", "cpu") # a SAM model never installs it + assert stub.dinov3_installs == [cp.DINOV3_COMMIT] + + def test_a_dino_model_needs_cellpose_to_have_imported_dinov3(monkeypatch, tmp_path): state = install(monkeypatch, tmp_path, has_cpdino=False) with pytest.raises(SegmentationError, match="Restart the runtime"): - cp.load_model("cpdino-vitb", "cpu", allow_download=True) + cp.load_model("cpdino-vitb", "cpu") assert state.constructed == [] def test_a_dino_model_records_the_dinov3_commit(run, stub): - loaded = cp.load_model("cpdino", "cpu", allow_download=True) + loaded = cp.load_model("cpdino", "cpu") assert loaded.dinov3_commit == cp.DINOV3_COMMIT and loaded.tile_size == 384 assert stub.downloaded == ["cpdino"] params = cp.inference_parameters(loaded, cp.Settings(), ("DNA",)) assert params["dinov3_commit"] == cp.DINOV3_COMMIT and params["bsize"] == 384 + assert params["dinov3_source"] == cp.DINOV3_URL and params["dinov3_installed"] is False def test_dinov3_is_installed_only_when_asked_and_a_failure_is_refused(monkeypatch): diff --git a/tests/test_segmentation_cellpose_record.py b/tests/test_segmentation_cellpose_record.py index 63855396..b6b13691 100644 --- a/tests/test_segmentation_cellpose_record.py +++ b/tests/test_segmentation_cellpose_record.py @@ -27,16 +27,24 @@ def stub(monkeypatch, tmp_path): def test_the_record_says_whether_the_weights_were_downloaded_and_from_where(stub, tmp_path): - url = "https://huggingface.co/mouseland/cellpose-sam/resolve/main/" + revision = "7c61431b5fbb078f3296754bd15d9f51b320f837" + url = f"https://huggingface.co/mouseland/cellpose-sam/resolve/{revision}/" + assert (cp.WEIGHTS_REPOSITORY, cp.WEIGHTS_REVISION) == ("mouseland/cellpose-sam", revision) on_disk = cp.load_model("cpsam", "cpu") assert (on_disk.downloaded, on_disk.source) == (False, url + "cpsam") (stub.models_dir / "cpsam").unlink() - fetched = cp.load_model("cpsam", "cpu", allow_download=True) + fetched = cp.load_model("cpsam", "cpu") assert (fetched.downloaded, fetched.source) == (True, url + "cpsam") + assert stub.urls == [url + "cpsam"] params = cp.inference_parameters(fetched, cp.Settings(), ("DNA",)) assert params["weights_downloaded"] is True and params["weights_source"] == url + "cpsam" + assert params["weights_repository"] == "mouseland/cellpose-sam" + assert params["weights_revision"] == revision + assert params["dinov3_commit"] is None and params["dinov3_source"] is None own = cp.load_model(str(custom_model(tmp_path)), "cpu") - assert (own.downloaded, own.source) == (False, None) + assert (own.downloaded, own.source, own.repository, own.revision) == (False, None, None, None) + params = cp.inference_parameters(own, cp.Settings(), ("DNA",)) + assert (params["weights_source"], params["weights_revision"]) == (None, None) def test_the_full_normalisation_is_read_from_cellpose_now_copied_and_recorded(run, stub): diff --git a/tests/test_segmentation_cellpose_weights.py b/tests/test_segmentation_cellpose_weights.py new file mode 100644 index 00000000..179a5a01 --- /dev/null +++ b/tests/test_segmentation_cellpose_weights.py @@ -0,0 +1,333 @@ +"""The built-in weights (#574): pinned, downloaded on first use, checked; one torch warning hidden. + +Nothing is downloaded here: the stand-in (``cellpose_stub.install``) answers the brick's +download with its own bytes, whose SHA-256 and size it makes the pins. +""" + +import email.message +import errno +import hashlib +import io +import os +import re +import urllib.error +import warnings + +import numpy as np +import pytest + +from cellpose_stub import BUILTINS, install, weights_bytes +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing import segmentation_cellpose_model as model_module +from morphobricks_preprocessing import segmentation_cellpose_weights as weights_module +from morphobricks_preprocessing.segmentation_record import SegmentationError, read_record +from test_segmentation_cellpose import make_job + +SPARSE_MESSAGE = ( + "Sparse invariant checks are implicitly disabled. Memory errors (e.g. SEGFAULT) will occur " + "when operating on a sparse tensor which violates the invariants, but checks are disabled. " + "See torch.sparse.check_sparse_tensor_invariants.enable for more information." +) +"""torch's warning, as Cellpose 4.2.1.1's ``dynamics.py`` triggers it.""" + + +@pytest.fixture +def run(mixed_run): + return mixed_run + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +# the pins --------------------------------------------------------------------------------------- + + +def test_every_builtin_model_has_a_pinned_file_at_a_pinned_revision(): + assert tuple(weights_module.PINNED_WEIGHTS) == cp.BUILTIN_MODELS == BUILTINS + assert re.fullmatch("[0-9a-f]{40}", cp.WEIGHTS_REVISION) + for pin in weights_module.PINNED_WEIGHTS.values(): + assert re.fullmatch("[0-9a-f]{64}", pin.sha256) and pin.size > 100_000_000 + url = cp.weights_url("cpsam_v2") + assert url == ( + f"https://huggingface.co/mouseland/cellpose-sam/resolve/{cp.WEIGHTS_REVISION}/cpsam_v2" + ) + assert "/main/" not in url # never the moving branch Cellpose itself downloads from + + +# the download: only the chosen model's file, with its progress ------------------------------- + + +def test_only_the_chosen_models_weights_are_downloaded_with_their_progress(stub): + for name in BUILTINS: + (stub.models_dir / name).unlink(missing_ok=True) + told = [] + loaded = cp.load_model("cpsam", "cpu", progress=lambda *a: told.append(a)) + assert stub.downloaded == ["cpsam"] and stub.urls == [cp.weights_url("cpsam")] + assert sorted(p.name for p in stub.models_dir.iterdir()) == ["cpsam"] # no partial file + size = len(weights_bytes("cpsam")) + assert told == [ + ("Downloading cpsam weights…", 0, size), + ("Downloading cpsam weights…", size, size), + ] + assert (loaded.repository, loaded.revision) == (cp.WEIGHTS_REPOSITORY, cp.WEIGHTS_REVISION) + assert stub.cellpose_downloaded == [] # Cellpose was given the file, never a name + + +def test_a_copy_on_disk_shows_no_progress_and_is_not_downloaded(stub): + told = [] + loaded = cp.load_model("cpsam_v2", "cpu", progress=lambda *a: told.append(a)) + assert told == [] and stub.downloaded == [] and not loaded.downloaded + + +# refusals: the model and the source named, nothing substituted, nothing left ----------------- + + +def _http_error(url, code, reason): + return urllib.error.HTTPError(url, code, reason, email.message.Message(), None) + + +@pytest.mark.parametrize( + ("failure", "said"), + [ + (urllib.error.URLError("blocked by the proxy"), "blocked by the proxy"), + (TimeoutError("timed out"), "timed out"), + ("http", "the server answered 403 Forbidden"), + ], +) +def test_a_failed_or_blocked_download_is_a_refusal_naming_the_model_and_the_source( + stub, failure, said +): + (stub.models_dir / "cpsam").unlink() + url = cp.weights_url("cpsam") + stub.download_fail = _http_error(url, 403, "Forbidden") if failure == "http" else failure + with pytest.raises(SegmentationError) as caught: + cp.load_model("cpsam", "cpu") + message = str(caught.value) + assert "weights of cpsam could not be downloaded from " + url in message + assert said in message and "no other model is used" in message + assert stub.constructed == [] # nothing loaded, cpsam_v2 (on disk) not used instead + assert not (stub.models_dir / "cpsam").exists() + assert not [p for p in stub.models_dir.iterdir() if p.name.endswith(".part")] + + +def test_downloaded_bytes_that_are_not_the_pinned_file_are_refused_and_not_kept(stub, monkeypatch): + (stub.models_dir / "cpsam").unlink() + monkeypatch.setitem( + weights_module.PINNED_WEIGHTS, "cpsam", weights_module.PinnedFile("0" * 64, 16) + ) + with pytest.raises(SegmentationError, match="cpsam could not be downloaded") as caught: + cp.load_model("cpsam", "cpu") + assert "the pinned file has 16 bytes and SHA-256 " + "0" * 64 in str(caught.value) + assert stub.constructed == [] and sorted(p.name for p in stub.models_dir.iterdir()) == [ + "cpsam_v2" + ] + + +def test_a_copy_on_disk_that_is_not_the_pinned_file_is_refused_not_replaced(stub): + (stub.models_dir / "cpsam").write_bytes(b"older weights of cpsam") + with pytest.raises(SegmentationError, match="not the pinned file") as caught: + cp.load_model("cpsam", "cpu") + assert str(stub.models_dir / "cpsam") in str(caught.value) + assert hashlib.sha256(b"older weights of cpsam").hexdigest() in str(caught.value) + assert stub.constructed == [] and stub.downloaded == [] + assert (stub.models_dir / "cpsam").read_bytes() == b"older weights of cpsam" + + +def test_a_model_file_of_ones_own_is_never_checked_against_a_pin_or_downloaded(stub, tmp_path): + from cellpose_stub import custom_model + + loaded = cp.load_model(str(custom_model(tmp_path)), "cpu") + assert stub.downloaded == [] and loaded.source is None and loaded.revision is None + + +def test_the_written_record_names_the_weights_source_revision_and_hash(run, stub): + (stub.models_dir / "cpsam_v2").unlink() + result = cp.run_batch(make_job(run), batch_id="b1") + (batch,) = read_record(run.masks, "Cells").batches + assert batch == result.batch + assert batch.model_sha256 == hashlib.sha256(weights_bytes("cpsam_v2")).hexdigest() + params = batch.parameters + assert params["weights_source"] == cp.weights_url("cpsam_v2") + assert params["weights_repository"] == "mouseland/cellpose-sam" + assert params["weights_revision"] == cp.WEIGHTS_REVISION + assert params["weights_downloaded"] is True + + +# the torch warning (#574, item 5) ------------------------------------------------------------- + + +def _warn(message, module, category=UserWarning): + def warn(_stack): + warnings.warn_explicit(message, category, "dynamics.py", 541, module=module) + + return warn + + +def _evaluate(stub): + loaded = cp.load_model("cpsam_v2", "cpu") + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + before = list(warnings.filters) + cp.evaluate(loaded, cp.Settings(), np.zeros((2, 8, 8), np.uint16)) + assert warnings.filters == before # the filter was only there during the call + return [str(w.message) for w in seen] + + +@pytest.mark.parametrize("module", ["cellpose.dynamics", "torch", "torch.sparse"]) +def test_the_sparse_invariant_warning_is_hidden_while_cellpose_runs(stub, module): + stub.fail = _warn(SPARSE_MESSAGE, module) + assert _evaluate(stub) == [] + + +@pytest.mark.parametrize( + ("message", "module", "category"), + [ + (SPARSE_MESSAGE, "my_analysis", UserWarning), # another module + (SPARSE_MESSAGE, "cellposeextra", UserWarning), # not the cellpose package + (SPARSE_MESSAGE, "cellpose.dynamics", RuntimeWarning), # another category + ("Something else from torch", "torch", UserWarning), # another message + ("Note: " + SPARSE_MESSAGE, "cellpose.dynamics", UserWarning), # not its start + ], +) +def test_every_other_warning_is_still_shown(stub, message, module, category): + stub.fail = _warn(message, module, category) + assert _evaluate(stub) == [message] + + +def test_the_warning_is_shown_again_outside_the_cellpose_call(stub): + _evaluate(stub) + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + _warn(SPARSE_MESSAGE, "cellpose.dynamics")(None) + assert [str(w.message) for w in seen] == [SPARSE_MESSAGE] + + +# review of #577 --------------------------------------------------------------------------------- + + +def test_the_sparse_filter_is_put_back_when_cellpose_raises(stub): + loaded = cp.load_model("cpsam_v2", "cpu") + + def broken(_stack): + raise RuntimeError("CUDA out of memory") + + stub.fail = broken + before = list(warnings.filters) + with pytest.raises(RuntimeError, match="out of memory"): + cp.evaluate(loaded, cp.Settings(), np.zeros((2, 8, 8), np.uint16)) + assert warnings.filters == before + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + _warn(SPARSE_MESSAGE, "cellpose.dynamics")(None) + assert [str(w.message) for w in seen] == [SPARSE_MESSAGE] + + +def _replace_with_same_bytes(path): + data = path.read_bytes() + path.unlink() + path.write_bytes(data) # another file (inode, time) with the very same bytes + + +@pytest.mark.parametrize("what", ["removed", "replaced"]) +def test_a_weights_file_that_changes_while_cellpose_loads_it_is_refused(stub, what): + # Removed: Cellpose 4.2.1.1 would fetch cpsam_v2 from its moving branch with TLS off, to + # the same path, while the record would carry the pinned hash. + path = stub.models_dir / "cpsam_v2" + stub.on_construct = ( + (lambda _r: path.unlink()) + if what == "removed" + else (lambda _r: _replace_with_same_bytes(path)) + ) + with pytest.raises(SegmentationError, match="changed after it was checked") as caught: + cp.load_model("cpsam_v2", "cpu") + assert str(path) in str(caught.value) and len(stub.constructed) == 1 + + +def test_a_weights_file_gone_before_cellpose_opens_it_is_refused_without_cellpose( + stub, monkeypatch +): + real = model_module.fetch_weights + + def fetch_then_lose(*args, **kwargs): + found = real(*args, **kwargs) + found.path.unlink() # between the check and the load + return found + + monkeypatch.setattr(model_module, "fetch_weights", fetch_then_lose) + with pytest.raises(SegmentationError, match="changed after it was checked"): + cp.load_model("cpsam_v2", "cpu") + assert stub.constructed == [] and stub.cellpose_downloaded == [] + + +def test_a_model_file_of_ones_own_that_changes_while_loading_is_refused(stub, tmp_path): + from cellpose_stub import custom_model + + path = custom_model(tmp_path) + stub.on_construct = lambda _r: path.write_bytes(b"retrained meanwhile") + with pytest.raises(SegmentationError, match="changed after it was checked"): + cp.load_model(str(path), "cpu") + + +class _OS: + """The ``os`` module as the weights module sees it, with some calls replaced.""" + + def __init__(self, **replaced): + self.__dict__.update(replaced) + + def __getattr__(self, name): + return getattr(os, name) + + +class _FullDisk(io.BufferedWriter): + def write(self, data): + raise OSError(errno.ENOSPC, "No space left on device") + + +def test_a_full_disk_is_a_write_refusal_not_a_network_one(stub, monkeypatch): + (stub.models_dir / "cpsam").unlink() + + def fdopen(handle, mode): + return _FullDisk(io.FileIO(handle, "w")) + + monkeypatch.setattr(weights_module, "os", _OS(fdopen=fdopen)) + with pytest.raises(SegmentationError, match="could not be written to") as caught: + cp.load_model("cpsam", "cpu") + message = str(caught.value) + assert "No space left on device" in message and str(stub.models_dir) in message + assert "not a network problem" in message and "internet" not in message + assert sorted(p.name for p in stub.models_dir.iterdir()) == ["cpsam_v2"] + assert stub.constructed == [] + + +def test_a_failed_rename_names_the_target_and_keeps_nothing(stub, monkeypatch): + (stub.models_dir / "cpsam").unlink() + + def replace(source, target): + raise PermissionError(errno.EACCES, "Permission denied") + + monkeypatch.setattr(weights_module, "os", _OS(replace=replace)) + with pytest.raises(SegmentationError, match="could not be moved to") as caught: + cp.load_model("cpsam", "cpu") + assert str(stub.models_dir / "cpsam") in str(caught.value) + assert "Permission denied" in str(caught.value) + assert sorted(p.name for p in stub.models_dir.iterdir()) == ["cpsam_v2"] + assert stub.constructed == [] + + +def test_the_download_is_synced_to_disk_before_the_rename(stub, monkeypatch): + (stub.models_dir / "cpsam").unlink() + calls = [] + + def fsync(handle): + calls.append("fsync") + os.fsync(handle) + + def replace(source, target): + calls.append("replace") + os.replace(source, target) + + monkeypatch.setattr(weights_module, "os", _OS(fsync=fsync, replace=replace)) + cp.load_model("cpsam", "cpu") + assert calls == ["fsync", "replace"]