Skip to content

Add OOM-safe block-size auto-tuner - #296

Merged
neuromechanist merged 11 commits into
devfrom
feature/issue-232-opt-block
Aug 24, 2026
Merged

neuromechanist merged 11 commits into
devfrom
feature/issue-232-opt-block

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Ports Fortran's do_opt_block block-size search to all three backends, behind Fortran's own four parameter names, with the OOM-safe fallback the reference lacks.

The reference implementation is the thing to fix, not copy. Fortran's determine_block_size (amica15.f90:2078) walks upward into larger blocks and calls allocate_blocks with no stat=, so a candidate it cannot fit aborts the whole run: it exits exactly where it should degrade. Here a failing candidate is skipped, the upward walk stops (every larger candidate would fail too), and the fit continues at the largest size that actually ran.

Decided policies

Semantics. With do_opt_block=True, fit times one accumulate pass (the E-step plus sufficient statistics every EM iteration does) per candidate at the start of the fit -- after preprocessing and parameter initialization, before the first EM iteration -- and keeps the fastest. The choice and every timing are logged at INFO.

Stepping and bounds. blk_step keeps Fortran's arithmetic meaning (range(blk_min, blk_max + 1, blk_step), amica15.f90:2084), matching both Fortran and the old numpy determine_block_size, so a literal input.param means the same thing on both sides. The pamica defaults are re-derived rather than copied: Fortran's 128-1024 is entirely below where any pamica backend peaks, so the defaults are 4096-32768 by 4096, which bracket the measured CPU optimum (16384-32768, #216) and include the shipped 8192 in the same 8 candidates Fortran uses. Every candidate is clamped to [1, n_samples] (#292: Fortran silently NaNs when block_size exceeds the frames available per thread) and to a conservative memory estimate.

OOM safety. A candidate that cannot allocate is skipped and the search falls back to the last working size; if nothing can be timed the configured block_size is kept. Nothing aborts and nothing propagates. Per-candidate failures log at DEBUG, per issue #232's "expected, not exceptional, must not look like a defect"; the truncation gets one summary WARNING naming the size that failed and the size the fit continues at, per the lead's "skipped with a WARNING". That reconciles both instructions: one visible line per search, not one per candidate.

The predicate is MemoryError by type plus a message match on RuntimeError. Matching the message is load-bearing: on torch and MLX an allocation failure arrives as a plain RuntimeError, the same class a genuine bug raises, so anything not recognizably an allocation failure is re-raised. A bug in an E-step must not be absorbed as memory pressure and reported as a tuned block size; that path is tested on all three backends.

No numerics change beyond block size. The probes only read model state and consume no RNG, and block_size is restored around every candidate (in a finally), so the model never holds a size that failed. test_post_tune_fit_is_bit_identical_to_a_direct_fit asserts on each backend that a fit which tuned its way to size N is bit-for-bit the fit handed N directly -- same A, same W, same ll_history. The numpy backend has an extra such test under do_reject, the one path where a probe writes model state (_last_ll_samples, restored explicitly).

Reproducibility caveat. The winner is decided by measured time, so two machines can pick different sizes and their trajectories then differ at the ~1e-6 level any block-size change produces. Off by default in every backend, and documented in docs/guides/amica-differences.md (new row 9 plus a full section) and in every class docstring: a parity run pins block_size and leaves the search off.

Param reader (#286). do_opt_block/blk_min/blk_max/blk_step move from FORTRAN_UNSUPPORTED_KEYS to identity mappings in FORTRAN_TO_PAMICA_KEY, since they now have pamica equivalents: 57 translated (56 distinct), 32 unsupported, 89 recognized. Module docstring, docs mapping table and tests updated; the zero-recognized ValueError logic is untouched.

MLX OOM probe result

Probed live before relying on try/except, given the LU-abort precedent (#274). On an M4 Pro under mlx 0.32, an over-maximum Metal buffer raises a catchable Python RuntimeError, it does not abort the process:

RuntimeError: [metal::malloc] Attempting to allocate 160000000000 bytes which is
greater than the maximum allowed buffer size of 41747087360 bytes.

So try/except is sound on MLX and is what the backend relies on. test_metal_allocation_failure_is_a_catchable_exception pins this against a future MLX regression by requesting a buffer above the device's own advertised max_buffer_length, which is refused outright without the host ever backing it with memory.

Two related findings. MLX's set_memory_limit is documented as a soft guideline (allocation fails only when limit and RAM and swap are exhausted), and a 256 MB allocation under a 64 MB limit succeeded, so there is no CI-safe way to provoke a genuine OOM. And MLX will allocate past the recommended working set and page rather than fail, which surfaces as a mysteriously slow candidate; the MLX memory cap is therefore taken against max_recommended_working_set_size.

The memory cap applies on every backend, estimating one block's peak as block_size * n_channels * n_mix * itemsize * (3 * n_models + 8) -- the three (block, n_channels, n_mix) tensors each model holds for the whole block plus eight live intermediates counted off _forward/_get_block_updates -- capped at 25% of what the device reports available. It is an order-of-magnitude guard, not exact accounting; catching the failure remains the real safety net.

Timings

The tuner's own INFO output on the bundled 32-channel sample (30504 frames, M4 Pro), one line per backend:

torch-CPU  chose 16384 (22.9 ms/pass) from 4096:43.1 8192:26.7 12288:25.3 16384:22.9 20480:23.6 24576:28.6 28672:33.2 30504:31.2
MLX        chose 12288 ( 9.7 ms/pass) from 4096:12.0 8192:10.0 12288: 9.7 16384:10.0 20480:10.1 24576:10.2 28672:10.5 30504:11.2
NumPy      chose 16384 (155.9 ms/pass) from 4096:169.5 8192:160.9 12288:158.1 16384:155.9 20480:157.1 24576:157.2 28672:158.5 30504:156.5

Steady-state throughput at the tuned size versus the 8192 default, measured separately from the one-time search cost: torch-CPU 25.0 vs 28.2 ms/iteration (1.13x), NumPy 191.6 vs 196.9 ms/iteration (1.03x). The win is modest here because the block-size curve on this 32-channel sample is flat; the 16-60% gaps motivating #232 are on configurations whose optimum sits far from 8192.

Each candidate is timed twice and scored on its fastest pass. One pass was not enough: on Metal a new block shape triggers shader compilation, which inflated single measurements about fourfold (a candidate measured at 71.4 ms against a warm 16.7 ms) and left a cold search picking a block size a warm search beat by 1.4x. The cost is stated plainly in the docs rather than hidden: about 16 accumulate passes, 0.54 s on torch-CPU and 2.8 s on NumPy for this sample, which pays for itself over a normal multi-hundred-iteration fit and not over a very short one. That is the other half of why this is opt-in.

I did not benchmark PyTorch-MPS end-to-end: repeat measurements of the same configuration varied by ~50% on this host, so any speedup number would have been noise. The MPS path is exercised by the tests, not claimed as a benchmark.

Two numpy behavior changes worth flagging

do_opt_block defaulted to on in the numpy backend (following Fortran's header) with a 128-1024 sweep, so every numpy fit quietly re-tuned itself to a small block and ignored the block_size it was given, and made its result depend on the host. It is now off, like the other backends.

That exposed a second issue: numpy_impl/params.json pinned block_size to 128, which only went unnoticed because the tuner always overrode it. Turning the tuner off without fixing that would have shipped a ~9x slowdown, so the numpy default is now the shipped 8192.

The naive determine_block_size helper is removed outright rather than shimmed: it timed a bare X.T @ X, which is the shape of no work AMICA actually does, over a range below where any backend peaks, and could not fall back at all.

Error-path testing

A real OOM cannot be provoked safely in CI on any of the three backends (no portable per-process cap; MLX's limit is soft). The fallback is therefore tested by monkeypatching the per-candidate probe to raise each backend's verbatim allocation exception -- NumPy's MemoryError, PyTorch's alloc_cpu.cpp "Ran out of memory" RuntimeError, MLX's [metal::malloc] RuntimeError (captured from the live probe above). This is approved error-path injection of the kind already used for non-finite-sphere paths, not a forbidden mock: the exceptions are genuine, and all of the logic under test -- candidate construction, the ascending walk, the fallback, the state the model is left in, and the fit that then completes -- is real. Each such test says so in its docstring.

Design

Shared logic lives in pamica/blocktune.py; each backend supplies a probe callable and two numbers (element width, device-reported available memory) and makes one blocktune.search(...) call. Sharing was clean here because the three backends differ only in how a pass is forced to complete: torch reads the accumulated LL (which syncs CUDA/MPS), MLX calls mx.eval over every accumulator (without it the clock would measure lazy-graph construction and pick whichever size builds fastest -- there is a test for that), and numpy is eager.

Review round

The code reviewer traced the numpy default flip to its primary source and found something worse than a mistuned default. The old determine_block_size timed X.T @ X, whose cost grows with block size, so it was structurally guaranteed to return blk_min: every numpy fit ran at 128 regardless of what the sweep bounds said. The place that matters is test_sample_data_numpy_vs_fortran, the issue #24 numpy-vs-Fortran gating test, which asks for block_size=512 to match the reference input.param -- its parity was therefore never demonstrated at the size it specifies. Re-verified here at the literal 512 it now actually gets, under the new default: Hungarian-matched component correlation 0.981 (gate > 0.9), final log-likelihood -3.4039 after 150 iterations. Recorded in the changelog and the differences guide.

Fixed in this round:

  1. Diagnostics bug. When the first (or only) candidate failed allocation, two warnings fired and the first claimed "Continuing at block_size=N, the fastest size that ran" -- N was the untouched fallback and nothing had run. Now one warning saying what actually happened: nothing was measured, the configured block_size is kept untested. Every pre-existing failure test failed at a later candidate, so this case had no coverage; test_first_candidate_failure_does_not_claim_a_size_ran adds it and asserts the false wording is absent.
  2. Predicate tightened. The bare cannot/unable to/failed to allocate arms now require a size or memory token beside the verb -- allocating a device id, a file handle or a port is not something a smaller block fixes. No verified backend message depends on that arm (all five match out of memory, bad_alloc, metal::malloc or maximum allowed buffer size), so it is a narrow safety net for unseen wordings. The residual misclassification risk is written down next to the pattern, with why the alternative (treating every RuntimeError as fatal) would make the fallback useless on the two backends that need it.
  3. Capacity vs free. One comment each at the torch-MPS and MLX memory sites: those figures, and host RAM, are capacity and do not subtract what is already allocated, unlike CUDA's mem_get_info. The cap is an upper bound on what the device could ever give -- a first filter, with the real allocation catch behind it.
  4. Rank-reduced coverage, per backend. A real fit on rank-reduced EEG (the SVD-projection route established in test_ng_rank_deficient.py) asserting the search was handed the kept rank, not the input channel count -- the observable consequence of running after preprocessing, and wrong by 60% here if it were wired in ahead of the reduction.
  5. Also added: a multi-model (n_models=2) tuner fit, since multi-model changes both per-block memory and the work each probe times; a small-data fit (n_samples < blk_min) pinning the clamp end to end; a bare-default numpy fit pinning block_size == 8192 on the object a user actually gets; MLX device_info monkeypatched to report both keys with different values so preferring the wrong one is visible rather than indistinguishable (the previous assertion was near-vacuous), plus its fallback and no-report branches; the torch host-memory branch; and the two MLX injections aligned to monkeypatch.setattr like their torch and numpy siblings.

Rejected, with reasons. A test for host_memory_bytes' unavailable branch: it is a thin sysconf wrapper whose entire body is a try/except returning None, so a test would assert the language, not the project's logic. Tests for the CUDA and MPS memory branches: neither device exists in CI, and both degrade to None (no cap) when the query fails, so an untested regression there costs a missing first filter rather than a wrong one -- the allocation catch still backs it. The torch test names this exclusion in its docstring so the gap is deliberate and visible rather than silent.

Gates

  • pytest pamica/tests/test_fortran_params.py pamica/tests/test_blocktune.py pamica/tests/test_numpy_block_tuning.py pamica/tests/torch_tests/test_ng_block_tuning.py pamica/tests/mlx_tests/: 208 passed
  • pytest -m "not slow" -n auto: 660 passed, 16 skipped, 1 xfailed
  • pytest test_sample_data_numpy_vs_fortran (slow, run locally on the final head): 1 passed -- correlation 0.981, LL -3.4039 at 150 iterations, effective block_size 512
  • ruff check / ruff format --check / ty check: clean, zero new diagnostics (verified against a stashed baseline)

Closes #232.

New pamica/blocktune.py: candidate construction (Fortran's arithmetic
stepping, re-derived bounds, clamped to n_samples and to a conservative
memory estimate), the ascending timed search, and the degrade-never-exit
fallback Fortran's own do_opt_block lacks -- it aborts the run when a
candidate cannot allocate. Unit-tested against each backend's verbatim
allocation-failure exception.

Part of issue #232.
do_opt_block/blk_min/blk_max/blk_step on AMICATorchNG, off by default.
The probe is one _accumulate_blocks pass, forced to complete before the
clock stops so CUDA/MPS async queues are timed honestly; block_size is
restored around every candidate, so the model never holds a size that
failed and a post-tune fit is bit-identical to a direct fit at the
chosen size. The tuned size is persisted in state_dict.

Part of issue #232.
Same four parameters and semantics as AMICATorchNG. The probe evaluates
the whole accumulate graph: MLX is lazy, so timing without mx.eval would
measure graph construction and pick whichever size builds fastest. The
memory cap uses the GPU's recommended working set, since MLX allocates
past it and pages rather than failing. A Metal allocation failure was
probed and confirmed to raise a catchable RuntimeError, not to abort the
process the way MLX's LU does (issue #274); a test pins that.

Part of issue #232.
determine_block_size timed a bare X.T @ X -- the shape of no work AMICA
does -- over Fortran's 128-1024 range, and could not fall back at all.
Removed outright (no shim) in favour of the shared search.

Two default changes this forces: do_opt_block was on (Fortran's header
default), so every numpy fit quietly re-tuned itself to a small block
and ignored the block_size it was given; it is now off like the other
backends. And params.json pinned block_size to 128, which only went
unnoticed because the tuner always overrode it -- it is now the shipped
8192.

Part of issue #232.
do_opt_block/blk_min/blk_max/blk_step move from FORTRAN_UNSUPPORTED_KEYS
to identity mappings now that every backend implements the search under
those names: 57 translated (56 distinct), 32 unsupported, 89 recognized.

Part of issue #232.
New amica-differences row 9 and a section on the machine-dependent
choice (parity runs pin block_size and leave the search off), the
re-derived bounds, and the OOM fallback. Cross-referenced from the
validation guide's block-size sensitivity table; param-reader counts
updated; changelog entry.

Closes #232.
One timed pass per candidate is not enough. The first pass at a given
block size pays one-off costs that belong to no candidate: on Metal a new
block shape triggers shader compilation, which inflated single
measurements ~4x on an M4 Pro and left a cold search picking a size a
warm search beat by 1.4x. Two passes, scored on the minimum, flattens
that.

Doubles the search cost to ~16 accumulate passes, which is now stated in
the docs alongside measured throughput: on the bundled 32-channel sample
torch-CPU picks 16384 for ~1.13x over the 8192 default and NumPy ~1.03x,
so the search pays for itself over a long fit and not a short one.

Part of issue #232.
When the first (or only) candidate could not allocate, two warnings fired
and the first said 'Continuing at block_size=N, the fastest size that
ran' -- N was the untouched fallback and nothing had run. Now one
warning that says what actually happened: nothing was measured and the
configured block_size is kept untested. Every existing failure test
fails at a LATER candidate, so this case had no coverage; added.

Also tightens is_allocation_failure: the bare 'could not allocate' arms
now require a size/memory token beside the verb, since allocating a
device id or a port is not something a smaller block fixes. No verified
message depends on that arm. The residual misclassification risk is
recorded next to the pattern.

Part of issue #232.
torch-MPS's recommended_max_memory, MLX's device_info sizes and host RAM
all report capacity; only CUDA's mem_get_info reports currently-free
memory. Neither subtracts what is already allocated, so the cap is an
upper bound on what the device could ever give -- a first filter, with
the real allocation catch behind it.

Part of issue #232.
Per backend, a rank-reduced fit asserting the search saw the KEPT rank
rather than the input channel count -- the observable consequence of
running it after preprocessing, and wrong by 60% here if it were wired
in ahead of the reduction.

Also: a multi-model (n_models=2) tuner fit, since multi-model changes
both the per-block memory and the work each probe times; a small-data
fit (n_samples < blk_min) pinning the clamp end to end; a bare-default
numpy fit pinning block_size==8192 on the object a user gets; MLX
device_info now monkeypatched to report both keys with different values
so preferring the wrong one is visible; the torch host-memory branch;
and the two MLX injections aligned to monkeypatch.setattr like their
torch and numpy siblings.

Part of issue #232.
The old numpy search timed X.T @ X, whose cost grows with block size, so
it was structurally guaranteed to pick blk_min: every numpy fit ran at
128 whatever the bounds said. test_sample_data_numpy_vs_fortran (the
issue #24 gating test) asks for block_size=512 to match the reference
input.param, so its parity was never demonstrated at the size it
specifies. Re-verified at the literal 512 under the new default:
component correlation 0.981 (gate > 0.9), LL -3.4039 at 150 iterations.

Part of issue #232.
@neuromechanist
neuromechanist merged commit a41b02d into dev Aug 24, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-232-opt-block branch August 24, 2026 00:28
@neuromechanist neuromechanist mentioned this pull request Aug 25, 2026
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.

Port do_opt_block: choose block_size per host and data instead of a constant

1 participant