Skip to content

Phase 7: normalize component rows in doscaling - #340

Merged
neuromechanist merged 29 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-333-phase7-doscaling-rows
Sep 23, 2026
Merged

neuromechanist merged 29 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-333-phase7-doscaling-rows

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Summary

doscaling (on by default) now normalizes components, as the reference does, in the PyTorch, NumPy and MLX backends.
pamica stores each model's mixing block transposed relative to the reference (the issue #24 convention), so source i of model h is row i of A[:, comp_list[:, h]], with its density at mu[:, comp_list[i, h]] and beta[:, comp_list[i, h]].
Every backend normalized stored columns instead, which is not a change of scale of any component; each now has a _rescale_components method that divides every component row by its norm and multiplies/divides the matching mu/beta by it (zero-norm rows untouched, as in amica15.f90:1843-1851).
Models are processed in order with one vectorized pass each (batched torch ops, mx.put_along_axis on MLX, no per-source loop); a column merged by share_comps is handled by the same per-block rule, which Phase 8 (#334) replaces with the component-row layout.

scalestep, which the reference parses but never reads (it rescales every iteration), stays a pamica extension but now counts from 1 (iterations s, 2s, ...), so the default 1 is the reference; the 1-based rule is inline with a comment to move to schedule.every when Phase 9 (#338) lands.
With doscaling on, every constructor now rejects a scalestep that is not an integer of at least 1 with the same ValueError (scalestep=0 used to raise a bare ZeroDivisionError mid-fit).

pamica/tests/native_oracle.py is a reusable helper that seeds the native binary (pinned v0.3.3 through the resolver, PAMICA_NATIVE_BINARY overrides) from a pamica state through the reference's load_* files and reads back its raw output, including the load_comp_list path Phase 8 needs (the reference reads that from the file named c, amica15.f90:831).

ADR 0006 states the storage convention and amends ADR 0001; the issue #24 notes point to it; the differences page gains a scalestep row; the changelog has the behavior-change entry.

Part of epic #324; resolves #333 (closes when the epic merges to dev).

The branch merges the epic head (Phase 6, e38aa11; Phase 10, 353a748). The only conflicts were documentation: both sides added row 13 to the differences table, so Phase 6's do_sphere=False row stays 13 and scalestep becomes row 14 (changelog, ADR 0006 and the row credits follow), and both changelog entries are kept. Phase 6 had already moved test_family_converged_ll_matches_fortran and the two end-to-end tests to tmp_path, and its session conftest.py runs the suite from a temporary directory; a grep finds no other test writing into the working tree.

Behavior change

Default fits on every backend change trajectory, toward the reference. Scale-blind results (log-likelihood, component directions, correlation, Amari distance) barely move; element-wise A, mu, sbeta now match the reference, and fitted components have unit norm. doscaling=False is byte-identical to the pre-fix code on all three backends (pinned in-process against the fb13d76 classes). Saved models load unchanged.

Oracle numbers (seeded native binary v0.3.3, sample EEG, natural gradient, doscaling on)

before (column rule) after
1 iteration, max abs error A / mu / sbeta 7.2e-5 / 6.6e-5 / 8.6e-5 5.0e-16 / 7.8e-11 / 1.1e-14
3 iterations 1.4e-3 / 6.7e-3 / 2.2e-3 2.7e-13 / 8.6e-10 / 2.7e-11

(torch, one model; two models: 5.2e-16 / 4.5e-12 / 1.1e-14 after 1 iteration. The doscaling=False noise floor is the same: 1.2e-15 / 8.0e-11 / 9.1e-15.)

Parity before/after

  • 100 seeded iterations with Newton (newt_start=50), one model: final LL gap 2.3e-4 -> 2.1e-4 (Newton start, Newton appears to start one iteration late (0- vs 1-based newt_start) #335), matched correlation 0.999988 -> 0.999998, Amari 5.6e-4 -> 2.3e-4, component norms [0.940, 1.070] -> 1, max abs A 4.9e-2 -> 3.5e-3, mu 5.7e-2 -> 1.7e-2, sbeta 8.5e-2 -> 7.5e-3.
  • Same, two models: LL gap 6.0e-3 -> 2.8e-4, correlation 0.8497 -> 0.99998, Amari 7.0e-2 -> 5.8e-4, norms [0.046, 1.969] -> 1.
  • Bundled amicaout fixture (unseeded), 200 iterations: LL -3.401777 -> -3.401673 (fixture -3.401873), correlation 0.99752 -> 0.99740, Amari 5.95e-3 -> 6.14e-3, norms [0.804, 1.324] -> 1.

Float32 canaries: tolerances from a perturbation study

CI run 35821222887 failed two float32 pins on the macOS runner's GPU (1422 passed there); neither was a fit-path change.
Each tolerance below now comes from a float32-rounding perturbation study recorded in the test:
the input multiplied elementwise by (1 + eps * z), with eps the float32 machine epsilon (1.19e-7), z standard normal and numpy.random.default_rng(20260922), on an Apple M4 Pro.

  • mlx_tests/test_mlx_transform.py::test_fit_path_is_unchanged_by_phase1, 48 draws.
    Largest deviations: A[0,0] 1.87e-5, A[5,5] 1.49e-6, A[10,20] 1.90e-6, A[31,31] 1.49e-6, A[0,31] 1.87e-5; relative log-likelihood 7.2e-8 to 5.0e-6 per iteration (final 4.1e-6).
    Each entry's tolerance is 3x its maximum.
    The old flat 5e-6 relative log-likelihood tolerance had no margin (study maximum 5.0e-6), so the log-likelihood entries get per-iteration tolerances too.
    CI's deviations (A[0,0] 9.2e-6, ll_history[0] about 7e-8 relative) sat inside the study maxima, and 16 fresh draws from another random stream used at most 0.44 of any tolerance.
    Against the column-rule change the tolerances still discriminate: A[0,0] moved 1800x its tolerance, A[5,5] 8800x, A[31,31] 530x, A[0,31] 11x, ll_history[2] and [3] 15x and 12x.
    A[10,20] (1.3x) and ll_history[0] and [1] (under 1x) do not separate the two rules; the test comment says so.
  • test_mlx_transform_cross_backend.py::test_variance_order_matches_float64_twin: the fixed 1e-3 near-tie guard is gone, and the fit is back at its pre-doscaling normalizes stored columns, not components (all backends) #333 30 iterations.
    The two orders must agree exactly except for swaps between sources whose twin-variance gap lies inside the float32 band measured in the test (the sum of the two sources' |svar_mlx - svar_twin|).
    Study, 48 draws plus the unperturbed fit, 98 per-model orders: per-source relative difference at most 1.65e-6 (capped at 3x, 4.95e-6); no pair ever fell inside its band (the closest adjacent pair sat 34x outside it), so no order differed; 35 of 3038 adjacent gaps were under 1e-3, none under 3e-5.
    The old guard assumed a band about 300x wider than the measured one.
    At most one swap per model: from the gap density near zero, about 1e-3 in-band pairs are expected per model, and two in one model about 5e-7.
    Negative controls, each rejected: MLX order reversed (496 swapped pairs outside the band, over the swap cap); shuffled (221); the closest adjacent pair outside the band swapped (one swap, under the cap, gap 0.20 against a band of 7.1e-5, so the band alone catches it); one source's variance moved by twice the cap (9.5e-6 relative against 4.95e-6).
    8 fresh perturbations at 5, 30 and 50 iterations (48 per-model checks): no violation.
  • test_mlx_reject_cross_backend.py::test_reject_x_pdftype1_kurtosis_switch_matches_across_backends: the equal-rejected-count assertion is replaced by the band check (_rejection_violations).
    Over seeds 0-5, 7 and 8, and 12 MLX-only perturbations at seed 2: band at most 1.2e-4 of the per-sample log-likelihood spread, at most 1 borderline sample, no disagreement.
    The pdtype check stays exact because the switch has margin: the smallest |kurtosis| any switch saw at seed 2 is 1.24e-2, 560x the largest float32-vs-float64 kurtosis difference over the perturbations (2.2e-5).

Review fixes

From the PR review (no critical code bug; the row rescale was verified identical across backends and to the reference):

  • Changelog: the norm ranges now read as the previous state ("previously, after 100 seeded iterations, norms ranged over ...").
  • docs/guides/validation.md: the per-backend parity figures and their at-a-glance row note that they predate issue doscaling normalizes stored columns, not components (all backends) #333 and will be re-measured before epic Epic: make MLX a first-class, end-to-end backend #324 merges.
  • ADR 0006: semantic line breaks; the drawn-initial-A difference now says Phase 8 (share_comps compares and merges the wrong vectors (all backends) #334) aligns it while it rewrites the storage layout and initialization (no characterization test here).
  • _ORACLE_TOL comment: the maxima are over both backends and both model counts, which is why they exceed the single-configuration figures above.
  • Constructor docstrings (PyTorch, NumPy, MLX): scalestep is validated only when doscaling is on and is inert otherwise.
  • test_doscaling_rows.py:
    • new test_a_zero_or_nan_norm_row_is_left_untouched (3 backends x zero/NaN): the planted row and its mu/beta columns stay bit for bit, and every other row, mu and beta equal the same backend's rescale of the unplanted state bit for bit, at unit norm;
    • the cross-backend rescale runs a fully permuted comp_list within each model besides the disjoint and merged ones;
    • the one-pass invariance tests also run on a Newton-reached state (do_newton=True, newt_start=1, asserted by lrate ramping to 0.3 on every backend; the column rule moves those states' log-likelihood by 2.1e-4 to 2.2e-4).
  • test_newton_posdef_mstep_composition: the independent expected value applies the production zero-norm guard.
  • Recipe preconditions fail instead of skipping: the six "run was monotone" / "did not overshoot" sites (test_llt_stash.py, mlx_tests/test_mlx_llt_stash.py, test_mlx_mir.py, test_mlx_export.py, torch_tests/test_amica_ng_wrapper.py, test_ng_backend.py::test_keep_best_returns_within_tol_of_peak) now assert max(ll_history) - ll_history[-1] > _KEEP_BEST_TOL, and their "ended degenerate" skips assert a usable fit. On the first CI run with these assertions, three torch tests failed on both runners (test_llt_stash.py::test_keep_best_restore_rolls_the_llt_stash_back, test_amica_ng_wrapper.py::test_write_amica_output_ll_matches_kept_iterate, test_ng_backend.py::test_keep_best_returns_within_tol_of_peak): their fixed 60-iteration aggressive-Newton recipe overshot on the development machine (peak 57 of 60) but ran monotone on the Linux and macOS runners, so on CI these tests had been skipping silently. All three now use the recipe of test_ng_convergence.py (the same kwargs plus the loosened min_dll stop, 150-iteration budget, same data and block size), whose trajectory they reproduce bit for bit (peak at iteration 70, stop at 71, 1.9e-4 below) and whose restore already passed on both runners. The MLX recipes already used that stop and passed on the macOS runner. A suite-wide grep found five more recipe skips in test_amica_ng_wrapper.py (four "short fit ended degenerate", one "no merge fired"); they assert too. None of them skipped locally before the change.
  • native_oracle.run_seeded_reference: removes out/ and init/ before running, so a reused workdir never supplies old output; requires every file it reads (A, mu, sbeta, rho, alpha, gm, c, comp_list, LL, S); fails on a nonzero exit, on an Error / Got NaN / NaN-restart ("Reinitializaing", which discards the seed) line in stdout even with exit status 0, and on a gfortran runtime error in stderr, with both output tails. Checked: a reused workdir with a planted zero A reads fresh output (1e-18 from a clean run, the binary's own two-thread run-to-run spread), and a run the binary aborts with exit status 0 ("Error: minimum segment size too small") raises.
  • CI: the Linux and macOS pytest jobs and the weekly macOS job check out full history (fetch-depth: 0); the doscaling=False byte-identity pin fails, not skips, when CI is set and the pinned commit is unreachable, and skips with its message only in a local shallow clone. The same rule now covers the older MLX byte-identity pin in mlx_tests/test_mlx_fit_noop.py, which had the same silent-skip path.

Not changing, with reasons:

  • An LL bound on a merged comp_list (test review 3): Phase 8 (share_comps compares and merges the wrong vectors (all backends) #334) redefines shared-component semantics and adds the exact test there.
  • A characterization test of the drawn initial A (test review 5): covered by the ADR 0006 note above; Phase 8 changes it.
  • No amica15.f90:201 citation exists in this PR's files, as the comment review found; none was expected.

Test plan

  • pamica/tests/test_doscaling_rows.py: exact change of scale per backend and model count (float64 LL change <= 4.4e-16, the old column rule 1.0e-4); NumPy and MLX rescale a shared state (disjoint and merged comp_list) like PyTorch; doscaling=False byte-identical to fb13d76 on all three backends; scalestep cadence and validation on all three backends
  • Gated oracle AMICA_RUN_FORTRAN=1: torch and NumPy match the seeded binary after 1 and 3 iterations, one and two models
  • Updated tests that encoded the column rule or a trajectory it produced (listed below); no tolerance was loosened to absorb the change. The three float32 canaries above were re-derived from the measured study after the CI failure, which made some entries wider (A[0,0], A[0,31], A[10,20], ll_history[4] onward and final_ll_) and others tighter (ll_history[0] to [3], A[5,5], A[31,31], and the variance agreement, 1e-3 to 4.95e-6 relative)
  • uv run pytest pamica/tests -q --no-cov -n 4 -m "not slow" after the review fixes: 1443 passed, 20 skipped (opt-in Fortran or native-binary gates and one NumPy-specific skip; no "run was monotone" skips remain), 1 xfailed (strict, as before)
  • Review fixes, with AMICA_RUN_FORTRAN=1: test_doscaling_rows.py 50 passed (both seeded-oracle tests through the hardened helper); the 11 test files these fixes and the float32 canaries touched, 232 passed, none skipped
  • CI run 35827679443 (89af771), all jobs green: Linux 882 passed, 153 skipped (MLX-only and opt-in); macOS 1448 passed, 15 skipped. The doscaling=False byte-identity pins ran instead of skipping: 6 of 6 passed on macOS, and on Linux the 4 PyTorch/NumPy cases passed while the 2 MLX cases skip (no MLX there); the 3 MLX test_mlx_fit_noop.py pins passed on macOS
  • Every test file either side of the merge touched (32 files), with AMICA_RUN_FORTRAN=1, the v0.3.3 binary and slow tests included: 568 passed, 3 xfailed (strict, as before), none skipped; the working tree stays clean afterwards
  • Slow parity tests before the merge (-m slow): 10 passed, 2 xfailed; test_rholrate_ratchets_at_maxdecs_not_per_decrease needed the recipe change listed below
  • uv run ruff check . && uv run ruff format --check ., uv run ty check, typos: clean

Existing tests changed

Tests that encoded the column rule:

  • torch_tests/test_ng_backend.py::test_newton_posdef_mstep_composition: the independent expected A applied the column rescale (new code differed from it by 3.6e-3); it now applies the row rescale and matches within the unchanged 1e-10.
  • torch_tests/test_ng_convergence.py::test_a_frozen_window_still_computes_fresh_grad_norm: compared column directions, which a row rescale changes; it now asserts a frozen iteration's A equals exactly what _rescale_components alone gives, and that every unfrozen iteration differs from that (so the check can fail).
  • mlx_tests/test_mlx_fit_noop.py (renamed test_unscaled_fit_*): compares against the pre-Phase-3 MLX class from git, which has the column rule; both fits now run with doscaling=False, so everything else stays compared bit for bit.
  • mlx_tests/test_mlx_transform.py::test_fit_path_is_unchanged_by_phase1: re-recorded pin (same M4 Pro; the old values reproduced exactly before the change): final LL -3.25075626 -> -3.25063539, A[0,0] 0.8832 -> 0.9854; ll_history[0] unchanged; tolerances now from the float32 study above.

Recipes whose scenario came from the column rule's per-iteration perturbation (the new trajectories are monotone where the old ones dipped):

  • torch_tests/test_ng_convergence.py::test_keep_best_restores_genuine_overshoot_under_min_dll_stop, ::test_mir_history_survives_keep_best_restore, mlx_tests/test_mlx_keepbest.py (six tests), mlx_tests/test_mlx_llt_stash.py, mlx_tests/test_mlx_export.py, mlx_tests/test_mlx_mir.py, test_mlx_keepbest_cross_backend.py, test_llt_stash.py, torch_tests/test_amica_ng_wrapper.py::test_write_amica_output_ll_matches_kept_iterate: the aggressive-Newton recipe (newt_start=1, lrate=0.5) now runs monotone to max_iter on every seed tried (0-11, both backends), so the restore never fired (failures, or silent "run was monotone" skips in five tests). Added newtrate=3.0 and, where the run stops via min_dll, a 150-iteration budget: torch now peaks at 70 and stops at 71 (gap 1.9e-4), MLX at 63/64 (gap 4.2e-4). test_mlx_mir.py uses seed 1: seed 0's restored and last iterates differ in MIR by only 4.9e-5 relative, under its 1e-4 float32 margin (seed 1: 7.5e-4).
  • mlx_tests/test_mlx_keepbest.py pdftype=1 recipe: kurt_start 8 -> 6 (the run now stops at iteration 8 after two switch passes; with 6 all five run before the stop at 12, and the peak at 5 still precedes the first pass).
  • torch_tests/test_ng_backend.py::test_keep_best_returns_within_tol_of_peak: the Multi-model NG log-likelihood is ~0.02 lower and more variable than Fortran #51 config (seed 8) dipped below its peak only under the column rule (base: late gains down to -2.0e-3; now monotone, as are seeds 0-5); switched to the aggressive recipe with the loosened min_dll stop (see "Review fixes"). Also fixed a latent ordering bug: the "returned parameters sit at final_ll_" recompute ran before the overshoot guard, but it only holds for a restored iterate (on a monotone run it is off by one iteration's gain, 2.85e-4).
  • torch_tests/test_ng_backend.py::test_rholrate_ratchets_at_maxdecs_not_per_decrease (slow): the newtrate=1.0 run is now monotone through 300 iterations, so no ratchet fired; newtrate=3.0 decreases 6 times and both ceilings ratchet twice.
  • torch_tests/test_ng_convergence.py::test_min_dll_stop_reachable_at_shipped_default_threshold: the old config stopped at 326 because LL dips counted as small gains; it now keeps gaining 1e-8 to 1e-7 per iteration through 2000 iterations, and so does the seeded native binary on the same config. n_mix=1 stops at 368 with final gains of 8e-11 to 9e-10, still far above the 7.6e-15 a raw-scale comparison would need.

Cross-backend preconditions:

  • test_mlx_transform_cross_backend.py::test_variance_order_matches_float64_twin: its fixed near-tie guard rejected the 30-iteration fit after this change (minimum variance gap 5.0e-4 < 1e-3); the guard is now replaced by a measured float32 band (see "Float32 canaries" above), at the original 30 iterations.
  • test_mlx_reject_cross_backend.py::test_reject_same_sample_set_across_backends is replaced by test_reject_decisions_agree_up_to_float32_rounding (rejsig back at 2.0, seeds 7 and 8, one and two models) plus two negative controls. Exact agreement of the rejected set was config luck: the float32 and float64 per-sample LLs differ by up to ~0.1 by the second pass, and base also disagreed at seed 8, rejsig 2.0. The new check is per pass: a pass-through recorder keeps each backend's good set and per-sample LL; the recomputed threshold must reproduce each backend's own decisions; every disagreement must lie within the band measured on that pass (largest per-sample float32-vs-float64 difference plus the threshold difference), so all decisions outside it are identical; the band is capped at 0.1 of the per-sample LL spread and 1% of the samples, and at most 3 samples may end up rejected by only one backend. A threshold divergence (MLX at rejsig 2.2) and a trajectory divergence (MLX from another seed) both fail it (band 0.2 and 0.41-1.4 of the spread, 82-83 samples differing).
  • test_mlx_reject.py::test_keep_best_restore_never_fires_under_do_reject and its torch twin test_ng_backend.py::test_keep_best_inactive_under_reject were vacuous (monotone fits). Both now use the overshoot recipe, assert that the same fit restores without do_reject and that the do_reject trajectory itself ends below an earlier peak (MLX: peak 36, stop 37, 2.0e-3 below; torch: peak 57, stop 59, 2.2e-4 below), then assert no restore. NumPy has no keep_best, so no NumPy twin exists.

Rejection agreement by seed (rejsig 2.0; second pass, the widest)

seed models band / LL spread borderline samples disagreements
7 1 9.8e-4 1 0
7 2 3.1e-3 2 1
0 1 / 2 3.9e-3 / 8.0e-3 1 / 0 0 / 0
1 1 / 2 2.7e-3 / 2.0e-3 1 / 1 0 / 0
2 1 / 2 3.8e-3 / 5.2e-3 3 / 3 0 / 0
3 1 / 2 6.7e-3 / 5.1e-3 5 / 5 0 / 0
4 1 / 2 2.3e-3 / 3.8e-3 2 / 2 0 / 0
5 1 / 2 6.0e-3 / 7.5e-3 1 / 1 0 / 0
8 1 4.3e-3 3 0
8 2 3.3e-2 14 1

Every disagreement lay inside its band. At rejsig 2.5 and 3.0 (seeds 0, 7, 8) the widest band was 3.6e-2 of the spread with at most 10 borderline samples and 1 disagreement.

neuromechanist and others added 29 commits September 22, 2026 21:21
Writes a pamica state in the reference's load_* formats, runs the
pinned v0.3.3 binary and reads its raw output arrays back, for
element-wise oracle tests (issue #333). Used by the tests that follow.
Each model's stored A block is the transpose of the reference's
mixing matrix, so a component is a block row. doscaling normalized
stored columns, which is not a change of scale; torch, NumPy and MLX
now rescale each component row with the matching mu/beta, exactly as
amica15.f90:1843-1851 does (issue #333).

Tested: invariance, cross-backend and doscaling=False byte-identity
tests; seeded native oracle matches A/mu/sbeta to round-off. Tests
that encoded the column rule are updated.
With components rescaled, the aggressive-Newton recipes run monotone,
so keep_best restores never fired (failures or silent skips). Add
newtrate=3.0 and longer budgets where needed, move the pdftype=1
switch to kurt_start=6, pick n_mix=1 for the default min_dll stop,
and check the keep_best recompute only after a restore.

Tested: every retuned test passes and no longer skips.
The variance-order guard rejected the 30-iteration fit (gap 5e-4), so
run 50 (gap 2.4e-3). One two-model sample sat on the rejsig=2.0
threshold between float32 and float64; use rejsig=2.5.

Tested: both tests pass for one and two models.
The reference parses scalestep but rescales every iteration. Keep it
as a pamica extension counted from 1 (iterations s, 2s, ...), so the
default 1 is the reference, and reject a non-integer or < 1 value at
construction on every backend instead of dividing by zero mid-fit.
Record it as row 13 of the differences page.

Tested: cadence and validation tests on torch, NumPy and MLX.
ADR 0006 states the storage convention (components are rows of each
stored block), the doscaling fix and the Phase 8 layout change, and
amends ADR 0001; the issue #24 notes point to it. The changelog
records the behavior change with the oracle numbers.
Brings in Phase 6 (validation harness, NumPy outdir=None, sensor
mixing transpose, viz fixes) and Phase 10 (sphere written
column-major). The scalestep row becomes row 14 of the differences
page after Phase 6's do_sphere row 13; both changelog entries kept.
Both the MLX and torch tests ran monotone fits, so final_ll_ equal to
the last LL proved nothing. Use the overshoot recipe, require that
it restores without do_reject and that the do_reject trajectory also
ends below an earlier peak, then assert no restore.

Tested: both tests pass; the old configs were monotone.
Exact agreement of the rejected set is config luck: float32 and
float64 per-sample LLs differ by up to ~0.1 by the second pass.
Record each pass, require every disagreement to lie within the band
measured on that pass, cap the band and the disagreement count, and
add controls where a threshold or trajectory divergence fails.

Tested: seeds 7 and 8, one and two models, at rejsig 2.0.
@neuromechanist
neuromechanist merged commit 3627a6e into feature/issue-324-epic-mlx-first-class Sep 23, 2026
8 checks passed
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.

1 participant