Skip to content

piece_counts: vectorised (#69) - #568

Merged
guijacquemet merged 6 commits into
mainfrom
claude/piece-counts-speed
Nov 26, 2026
Merged

guijacquemet merged 6 commits into
mainfrom
claude/piece-counts-speed

Conversation

@guijacquemet

@guijacquemet guijacquemet commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Post-v0.9.0: not for the release. Part of #69 (the piece_counts item only; pair_counts and the K(K−1) repeated pair work of #69 are untouched, so this does not close it).

Summary

  • mask_pieces.py (new, pure): piece_counts takes one of two routes, with the same counts either way.
    • Runs (masks of objects): each row is cut into runs of one nonzero label. A run's place is row * (columns + 2) + column, and places increase in row-major order, so the runs of the row above whose widened columns overlap a run are one slice, found by two searchsorted calls. No sort is needed. Of those, the runs with the same label are joined with scipy.sparse.csgraph.connected_components, and a label's pieces are its groups of runs. The corner reach (8-connected) comes from masks.binary.STRUCTURE and is not restated.
    • Boxes (pixel-scale masks): above RUNS_PER_PIXEL_LIMIT = 0.25 runs per pixel, the former function is used unchanged (a sort of every pixel, then ndimage.label per label in its bounding box).
    • Places and edge indices are int32 when every value and every search fits (bounds checked explicitly, _place_kind) and int64 otherwise. Temporaries are deleted before the graph is built. NumPy/SciPy only, no new dependency.
  • mask_scan.py: piece_counts is imported from mask_pieces (it was already at the 600-line limit). New: scan_masks refuses a mask plane of no pixels (mask_without_pixels, naming the mask).
  • Benchmark tool: tools/benchmark_kernels.py --group masks gains three pixel-scale masks (benchmark_inputs.pixel_mask: a two-label uint16 checkerboard, a one-label int32 checkerboard, and half the pixels carrying labels 1–4).
  • Docs: docs/benchmarks.md (before / first version / after, and the trade-off), CHANGELOG.md, AGENTS.md map, docs/development.md, user guide message table and contract §15 (mask_without_pixels), pyproject.toml layer (mask_pieces = pure). Reports: docs/benchmark_results/2026-11-26-kernels-masks-{before,first,after}-69.json.

Review of 85715dc (CHANGES NEEDED): fixes

  1. Fine-grained masks were much worse. The runs route no longer sorts and keeps its temporaries in int32, and above 0.25 runs per pixel the former route is taken. The pixel-scale cases now cost what they cost on main (table below). The first version needed 3.4 GiB on the two-label checkerboard; it now needs 464 MiB, the same as main.
  2. A zero-pixel plane passed the mask scan silently. scan_masks now raises ValueError "the mask … has no pixels (shape (0, 8)); save the mask with the image's height and width (mask_without_pixels)". Regression test test_a_mask_plane_without_pixels_is_refused (0×8 image and masks through preflight and scan_masks). It failed (did not raise) before the fix. Documented in the CHANGELOG, user guide and contract.
  3. int(label.max()) + 1 computed three times. Gone: the new search has no label bound.

Review of 5986acb (MERGE on the code; one low finding): fix

  • A mask of shape (1, 2³¹−3) chose int32 places (rows * width was exactly the int32 maximum), but the search subtracts width + reach = 2³¹ and raised OverflowError. The place type is now chosen by _place_kind(rows, columns, reach): int32 only when rows * (columns + 2) + reach fits (b2c8e46).
  • test_places_are_int32_only_when_every_search_fits tests the selection function only, with no large allocation: the boundary shapes with reach 1 and 0, a two-row case, and 4096². It fails with the former condition.
  • main at 316be56 (Run: show every check before the first image read, and make the header check linear (v0.9.0 release blocker) #567) is merged in (41c1bcf). The only conflict was CHANGELOG.md, where both entries are kept.

Identity evidence (byte-identical)

  • tests/test_mask_pieces.py keeps the former function word for word as the reference, and compares dtype, shape and tobytes() of both outputs. Every test runs three times (an autouse fixture): runs route forced, boxes route forced, and the route piece_counts chooses. The tests cover:
    • 300 random masks for each of 9 pixel types (bool, uint8, int8, uint16, int16, uint32, int32, int64, uint64): touching labels with holes, scattered single pixels, blocks with repeated labels and holes, no background, a one-label checkerboard touching at corners and edges, and empty masks;
    • edge cases (1×1, label 2,147,483,647, two labels crossing at a corner, a ring around a hole, …);
    • the benchmark cells, nuclei and cells cut into rings around nuclei;
    • a test that a checkerboard takes the boxes route and 16 px blocks the runs route.
  • Result at b2c8e46: 75 passed, 12 skipped. The skips are the route-choice and place-type tests under the two forced routes; neither depends on the route.
  • Mutation check: corner reach 0, or one search bound off by one, makes 21 tests fail. Moving the limit is not detected, by design: both routes give the same bytes.
  • Benchmark digests: all 14 mask cases have the same SHA-256 in all five runs (two before, two after, one first version), and the inputs have the same digests in all five.

Benchmark (#544's tool with the new cases, same machine, five runs in turn: before, after, first, before, after; 7 timed calls after a warm-up)

Intel Xeon @ 2.10 GHz, 4 CPUs, Python 3.13.18, numpy 2.5.5, scipy 1.18.1. Another job's tests were running (1-minute load 1.9–2.1 at the starts), shared by every run. Before = main at 88a1c42, first = this PR at 85715dc, after = 5986acb source. The source was chosen with PYTHONPATH. (b2c8e46 only changes which integer type is chosen at 2³¹ places, which no benchmark mask reaches.)

Case Before (runs 1, 2) After (runs 1, 2) First Traced: before / after / first Digest (first 16)
piece_counts cells 2048 322, 321 ms 15.9, 16.9 ms 35.9 ms 132 / 8.5 / 12.1 MiB 4abd144b846d176c
piece_counts cells 4096 2,327, 2,061 ms 103, 65.4 ms 168 ms 528 / 33.6 / 48.0 MiB c575615afca962cf
scan of one position 2048 766, 821 ms 206, 173 ms 214 ms 132 / 78.5 / 78.5 MiB 69de16bd28281cc3
scan of one position 4096 5,095, 4,889 ms 965, 923 ms 1,100 ms 528 / 314 / 314 MiB ec5910c05e04c1c7
two-label checkerboard 2048 195, 210 ms 191, 178 ms 1,481 ms 116 / 116 / 852 MiB e90ded1a1d3176d9
one-label checkerboard 2048 135, 112 ms 147, 121 ms 678 ms 132 / 132 / 430 MiB 6543cf267d7ad990
noise, four labels 2048 250, 231 ms 234, 237 ms 549 ms 132 / 132 / 253 MiB 484c7df9ddc9e95d
two-label checkerboard 4096 931, 932 ms 1,009, 961 ms 7,374 ms 464 / 464 / 3,407 MiB e90ded1a1d3176d9
one-label checkerboard 4096 574, 570 ms 556, 568 ms 3,366 ms 528 / 528 / 1,720 MiB 6543cf267d7ad990
noise, four labels 4096 1,248, 1,215 ms 1,049, 1,235 ms 2,917 ms 528 / 528 / 1,011 MiB 99f3f03132d213f6

pair_counts is unchanged: 241–259 ms at 4096 in every run. Peak RSS of the benchmark process: before 905 / 891 MiB, after 889 / 889 MiB, first 3,720 MiB.

Trade-off, stated plainly. The runs route costs per run; the former route costs per pixel (about 32 bytes each for the sort). The threshold sweep below was run at 4096 px outside the tool (median of 3, tracemalloc peak, equal outputs). Each cell shows the runs route first, then the former route.

Runs per pixel Time (runs / former) Memory (runs / former)
0.08 0.29 / 0.85 s 100 / 528 MiB
0.16 0.54 / 0.92 s 183 / 528 MiB
0.21 0.74 / 0.91 s 238 / 528 MiB
0.25 (one-label noise at 50 %) 0.89 / 0.81 s 220 / 528 MiB
0.32 1.15 / 1.05 s 346 / 528 MiB
0.5 2.02 / 0.49 s —
1.0 5.0 / 0.92 s 1,136 / 464 MiB

So the limit is 0.25. Below it, the runs route never used more memory than the former one and was at most about 10 % slower (at the limit itself). Above it, the route is the former one. The extra cost of choosing is one boolean plane (16 MiB at 4096²), freed before the former route starts. A mask just below the limit that the runs route handles badly in time is possible but was not found.

Adversarial check outside the tool (former function vs new, median of 3, equal outputs):

  • 2048 px, 1,000 labels scattered over 20 % of the pixels (0.20 runs/px): 15.2 s → 0.11 s;
  • 4,000 touching Voronoi cells: 0.38 s → 0.041 s.

Behaviour outside the former results

  • piece_counts of a mask with a side of length 0 returns no labels (the former function failed inside SciPy). The mask scan now refuses such a plane explicitly (fix 2).
  • A mask that is not 2D is refused with ValueError. Before, SciPy raised RuntimeError, or returned no labels for an all-background mask.

Notes for review

  • The reports' machine.commit is the tool's checkout (85715dc), not the source measured, which was set with PYTHONPATH (stated in docs/benchmarks.md).
  • The 25 November reports of the first version were replaced by the 26 November ones (they were only ever on this branch).
  • No force-push: every fix is a new commit (26c9404, 5986acb, b2c8e46), and main is merged in rather than rebased.

Tests

  • Focused at b2c8e46 (test_mask_pieces, test_mask_scan, test_masks, test_benchmark_kernels): 156 passed, 12 skipped; ruff and --rules pass. The full check was not rerun after b2c8e46: the release has the lock, and CI runs on the push.
  • Focused at 5986acb (the same files plus the docs/API/contract/guide tests): 525 passed, 3 skipped.
  • Full check under the shared lock at 5986acb: the same commands tools/check.py runs, with pytest given --basetemp in the session scratchpad (no PYTEST_ADDOPTS). ruff check . passed, ruff format --check . passed (762 files), pytest 8794 passed, 22 skipped, code rules (--rules) passed, exit 0. The 22 skips:
    • 11 missing skimage (tissue-mask);
    • 3 release-only (notebook pins);
    • 3 case-sensitive file system;
    • 2 root permissions;
    • 1 editable install (code identity);
    • 2 the route-choice test under the forced routes (by design).

🤖 Generated with Claude Code

https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a

piece_counts sorted every pixel (np.unique with return_inverse) and
labelled each label again in its bounding box. 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.

Results are byte-identical: a property test compares it with the former
function on random masks of every label pixel type and on the benchmark
masks, and every digest of benchmark_kernels --group masks is unchanged.
4096 px cells: 2.37 s -> 0.18 s; one position's scan 5.2 s -> 1.25 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a
)

The runs route of the first version needed up to 3.4 GiB and 7.4 s on a
4096 px two-label checkerboard (464 MiB and 0.93 s before), as runs are
almost pixels there and its int64 temporaries were all alive at the
graph. Now:

- runs are found without a sort: places are row * (columns + 2) + column,
  increasing, so the runs above a run that touch it are one slice found
  by two binary searches; places and edges are int32 when they fit
  (bounds checked), int64 otherwise; temporaries are freed before the
  graph is built, and the label bound is no longer recomputed;
- above RUNS_PER_PIXEL_LIMIT = 0.25 runs per pixel the former route
  (sort, then ndimage.label per label in its box) is taken, unchanged.

Every identity test now runs three times: runs forced, boxes forced and
the route chosen. The kernel benchmark gains three pixel-scale masks
(two checkerboards and noise); docs/benchmarks.md has before, first
version and after, with equal digests, and the trade-off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a
SciPy's failure inside piece_counts was the only guard against a plane
of height or width 0; with the runs route it has no labels, so it
counted as an image and as a plane of at most one label in its mask
type's kind. scan_masks now refuses it, naming the mask
(mask_without_pixels). Regression test, user guide, contract §15 and
changelog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a
A mask of shape (1, 2**31 - 3) chose int32 places (rows * width is the
int32 maximum) but the search subtracts width + reach, 2**31, and raised
OverflowError. The place type is now chosen by _place_kind, which also
counts the reach. Test of the selection only, no large allocation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a
@guijacquemet
guijacquemet marked this pull request as ready for review November 26, 2026 06:31
@guijacquemet
guijacquemet merged commit f8b08b9 into main Nov 26, 2026
3 checks passed
@guijacquemet
guijacquemet deleted the claude/piece-counts-speed branch November 26, 2026 06:31
guijacquemet pushed a commit that referenced this pull request Nov 26, 2026
…0.9.0 release branch

One conflict, in CHANGELOG.md: both sides added entries at the top of the v0.9.0 list. Both
kept; the #576 entry is in the v0.9.0 section. main is not merged: #568, #572 and the later
work stay out of v0.9.0. The notebooks' pins, the RELEASE_CALLS entry and the pin assertion are put back to their
pre-pin values (the branch carried commit B's) so that commit B' moves them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a
@guijacquemet guijacquemet mentioned this pull request Nov 26, 2026
3 of 9 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants