Skip to content

perf: drop dead dpdf + dedup |y|^rho in E-step (#63) - #69

Merged
neuromechanist merged 4 commits into
mainfrom
63-optimize-amicatorchng-per-iteration-cost-pow-hot-spot-+-cpu-threading
Jul 8, 2026
Merged

neuromechanist merged 4 commits into
mainfrom
63-optimize-amicatorchng-per-iteration-cost-pow-hot-spot-+-cpu-threading

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Part of #63. The clear, bit-identical win from the benchmark's pow hot spot.

What

The forward pass computed the density derivative dpdf every block, but every caller discards it (the exact-EM M-step uses the score fp, not dpdf) -- so a |y|^(rho-1) power and three exp()s per block-model were dead work. Separately, |y|^rho was computed twice (density + the rho-update accumulator).

Added a lean _log_pdf_only that computes only log_pdf and returns |y|^rho; _forward threads it through to _get_block_updates, which reuses it instead of recomputing. _log_pdf_and_deriv/_score are untouched (still cover the pdf-family tests).

Safety

Bit-identical -- single-model final LL matches the pre-change value to all 15 digits (verified by stashing the change and re-running), and the full torch suite is green (108 passed, 5 skipped). The parity tests (NumPy 1e-10, families 1e-12) all pass unchanged.

Measured (real sample EEG, single thread)

Metric Before After
pow time (20 it) 2.55s 1.30s (-49%)
30-iter wall 255 ms/it 166 ms/it (-35%)

Not in this PR (need your call -- data in the PR thread)

  • Larger block_size default (128->512): another ~-18%, but shifts results ~6e-6 (accumulation order).
  • CPU threading: ~-16% at 4 threads, degrades beyond (workload-limited).
  • GPU float32 fast path: the real GPU lever; needs a CUDA host to validate.

The forward pass computed the density derivative dpdf every block, but every
caller discards it (the exact-EM M-step uses the score fp, not dpdf) -- so a
|y|^(rho-1) power and three exp()s per block-model were dead work. And |y|^rho
was computed twice (density + the rho-update accumulator).

Add a lean _log_pdf_only that computes only log_pdf and returns |y|^rho for
reuse; _forward calls it and threads |y|^rho through to _get_block_updates,
which reuses it for the rho update instead of recomputing. _log_pdf_and_deriv
and _score are unchanged (still cover the pdf-family tests).

Bit-identical (single-model final LL matches to all 15 digits; full torch suite
green, 108 passed). ~35% faster single-thread on real sample EEG: pow time
2.55->1.30s, 30-iter wall 255->166 ms/it. Refs #63.
@codecov

codecov Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.43%. Comparing base (4cc9ef6) to head (6dc1191).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main      #69      +/-   ##
==========================================
+ Coverage   79.26%   79.43%   +0.16%     
==========================================
  Files          14       14              
  Lines        1958     1974      +16     
  Branches      336      337       +1     
==========================================
+ Hits         1552     1568      +16     
  Misses        301      301              
  Partials      105      105              
Files with missing lines Coverage Δ
pyAMICA/torch_impl/core.py 93.46% <100.00%> (+0.16%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

block_size default 128 -> 512 (matches Fortran): ~-18% CPU (168 -> 137 ms/it),
compounding with the pow-dedup to ~-47%. All tests specify block_size, and
single-iteration stats are block-size-independent to 1e-8, so the default change
is safe (full suite green, 108 passed).

Add benchmarks/benchmark_gpu.py (device/precision sweep). Real RTX 4090 numbers:
CUDA float64 is 2.14x over CPU float64 and numerically identical (-3.42408).
float32 is 5-8x faster but NaNs on full-size data (mixture underflow ~iter 23,
caught by the degenerate-fit contract); usable on small slices only, stabilization
tracked in #70.

Findings in .context/issue-63/perf_findings.md; AGENTS.md perf note added.
The first CUDA call pays context init + kernel compilation, inflating the first
timed fit ~2-3x; add an untimed warmup. Corrected RTX 4090 numbers (warmed, min
of repeats, pinned threads): CUDA float64 is 38.5 ms/it vs 172.8 ms/it CPU-f64
(16 thr) = ~4.5x (~7x vs single-thread), numerically identical (-3.42408). The
earlier 2.14x was a cold-start artifact. float32 is seed-flaky (NaN on many seeds
at full data), tracked in #70.
@neuromechanist

Copy link
Copy Markdown
Member Author

#63 complete: measured on CPU + a real RTX 4090 (hallu)

Went beyond the pow-dedup to cover all three levers you asked for, with real GPU numbers.

Landed here (float64, safe)

Lever Effect
E-step pow-dedup (drop dead dpdf) -35%, bit-identical
block_size default 128->512 -18% (compounds to ~-47%)
CUDA float64 (auto-selected) ~4.5x over 16-thread CPU (38.5 vs 172.8 ms/it), numerically identical (-3.42408)

Full torch suite green (108 passed). Added benchmarks/benchmark_gpu.py (device/precision sweep, with warmup); findings in .context/issue-63/perf_findings.md.

Honest caveats (the surprises)

  • float32 is NOT a free fast path. It's 5-19x faster but seed-flaky NaN on full-size data (a mixture component underflows in float32's ~7-digit range ~iter 23; the degenerate-fit contract stops it loudly). Converges on small slices. Stabilization tracked in Stabilize float32 AMICATorchNG for the GPU fast path #70.
  • MPS is currently slower than CPU on 32-channel data (0.51x) -- dispatch overhead unamortized on small montages; revisit with newer drivers / larger channel counts.
  • CPU threading is workload-limited (~4 threads sweet spot on a laptop) -- documented as guidance, not forced (a library shouldn't mutate global torch.set_num_threads).
  • Measurement note: a cold first CUDA call reads ~131 ms/it (2.5x inflation); always warm up before timing GPU.

Net: float64 CPU ~-47%, plus a clean 4.5x on GPU, all parity-preserving. The bigger multipliers (float32) need the stability work in #70.

Review (3 Sonnet reviewers) found no code bugs (bit-identity independently
verified) but real doc-accuracy issues:

- block_size 512 does NOT 'match the Fortran reference': Fortran's header default
  is 128 and it auto-tunes via do_opt_block (128-1024). Reworded in core.py +
  perf_findings.md.
- Corrected test citation test_block_size_independence -> test_blocking_invariance.
- Fixed the false 'all tests specify block_size explicitly' claim (7 pdf-family
  tests fit on the default; they pass on tolerant assertions).
- benchmark_gpu.py docstring called float32 'the production fast path (10-50x)',
  contradicting perf_findings.md (experimental, seed-flaky NaN); aligned + fixed
  the range to 5x CPU / 10-19x CUDA.
- Softened 'numerically identical' -> 'agrees to 5 sig digits' (print precision);
  dropped the unsupported cross-machine '~7x' figure and the untested workstation
  thread claim; reworded '_score site' -> _get_block_updates.

Added test_log_pdf_only_matches_log_pdf_and_deriv (parametrized None/0/1/2/3/4:
torch.equal on log_pdf + az_rho==|y|^rho) to lock in the bit-identity for
families 1-4 (their only non-gated regression check), and
test_block_size_default_is_512. 34 passed.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review complete (3 Sonnet reviewers) + all findings addressed

Code: clean. All three reviewers independently verified the bit-identity -- one ran torch.equal on _log_pdf_only vs _log_pdf_and_deriv's log_pdf (exactly equal, both branches) and confirmed the |y|^rho reuse is a true reuse (diffed vs main). No correctness bugs, no parity risk.

Doc accuracy: several real fixes (my perf docs overstated).

  • block_size=512 does not 'match the Fortran reference' -- Fortran's header default is 128 and it auto-tunes via do_opt_block (128-1024). Reworded.
  • benchmark_gpu.py docstring called float32 'the production fast path (10-50x)', contradicting perf_findings.md (experimental, seed-flaky NaN). Aligned + fixed range to 5x CPU / 10-19x CUDA.
  • Fixed the false 'all tests specify block_size explicitly' claim, the test_block_size_independence->test_blocking_invariance name, the overstated 'numerically identical' (->'agrees to 5 sig digits'), the unsupported cross-machine '~7x', and the untested workstation-threads claim.

Tests added (test-analyzer, Priority 7): test_log_pdf_only_matches_log_pdf_and_deriv (parametrized None/0/1/2/3/4) locks in the bit-identity for families 1-4 -- their only non-gated regression check -- plus test_block_size_default_is_512. 34 passed.

No findings skipped.

@neuromechanist
neuromechanist merged commit c3c2e67 into main Jul 8, 2026
7 checks passed
@neuromechanist
neuromechanist deleted the 63-optimize-amicatorchng-per-iteration-cost-pow-hot-spot-+-cpu-threading branch July 8, 2026 01:31
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.

Optimize AMICATorchNG per-iteration cost (pow hot spot + CPU threading)

1 participant