Repository navigation
Phase 7: normalize component rows in doscaling - #340
Merged
neuromechanist merged 29 commits intoSep 23, 2026
Merged
neuromechanist merged 29 commits into
neuromechanist merged 29 commits into
Conversation
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
merged commit Sep 23, 2026
3627a6e
into
feature/issue-324-epic-mlx-first-class
8 checks passed
This was referenced Sep 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
iof modelhis rowiofA[:, comp_list[:, h]], with its density atmu[:, comp_list[i, h]]andbeta[:, 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_componentsmethod that divides every component row by its norm and multiplies/divides the matchingmu/betaby 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_axison MLX, no per-source loop); a column merged byshare_compsis 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 (iterationss,2s, ...), so the default 1 is the reference; the 1-based rule is inline with a comment to move toschedule.everywhen Phase 9 (#338) lands.With
doscalingon, every constructor now rejects ascalestepthat is not an integer of at least 1 with the sameValueError(scalestep=0used to raise a bareZeroDivisionErrormid-fit).pamica/tests/native_oracle.pyis a reusable helper that seeds the native binary (pinned v0.3.3 through the resolver,PAMICA_NATIVE_BINARYoverrides) from a pamica state through the reference'sload_*files and reads back its raw output, including theload_comp_listpath Phase 8 needs (the reference reads that from the file namedc, 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
scalesteprow; 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=Falserow stays 13 andscalestepbecomes row 14 (changelog, ADR 0006 and the row credits follow), and both changelog entries are kept. Phase 6 had already movedtest_family_converged_ll_matches_fortranand the two end-to-end tests totmp_path, and its sessionconftest.pyruns 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,sbetanow match the reference, and fitted components have unit norm.doscaling=Falseis byte-identical to the pre-fix code on all three backends (pinned in-process against thefb13d76classes). Saved models load unchanged.Oracle numbers (seeded native binary v0.3.3, sample EEG, natural gradient,
doscalingon)A/mu/sbeta(torch, one model; two models: 5.2e-16 / 4.5e-12 / 1.1e-14 after 1 iteration. The
doscaling=Falsenoise floor is the same: 1.2e-15 / 8.0e-11 / 9.1e-15.)Parity before/after
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 absA4.9e-2 -> 3.5e-3,mu5.7e-2 -> 1.7e-2,sbeta8.5e-2 -> 7.5e-3.amicaoutfixture (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), withepsthe float32 machine epsilon (1.19e-7),zstandard normal andnumpy.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) andll_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
pdtypecheck 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):
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.Adifference 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_TOLcomment: the maxima are over both backends and both model counts, which is why they exceed the single-configuration figures above.scalestepis validated only whendoscalingis on and is inert otherwise.test_doscaling_rows.py:test_a_zero_or_nan_norm_row_is_left_untouched(3 backends x zero/NaN): the planted row and itsmu/betacolumns stay bit for bit, and every other row,muandbetaequal the same backend's rescale of the unplanted state bit for bit, at unit norm;comp_listwithin each model besides the disjoint and merged ones;do_newton=True, newt_start=1, asserted bylrateramping 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.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 assertmax(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 oftest_ng_convergence.py(the same kwargs plus the loosenedmin_dllstop, 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 intest_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: removesout/andinit/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 anError/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 zeroAreads 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.fetch-depth: 0); thedoscaling=Falsebyte-identity pin fails, not skips, whenCIis 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 inmlx_tests/test_mlx_fit_noop.py, which had the same silent-skip path.Not changing, with reasons:
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(test review 5): covered by the ADR 0006 note above; Phase 8 changes it.amica15.f90:201citation 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 mergedcomp_list) like PyTorch;doscaling=Falsebyte-identical tofb13d76on all three backends;scalestepcadence and validation on all three backendsAMICA_RUN_FORTRAN=1: torch and NumPy match the seeded binary after 1 and 3 iterations, one and two modelsA[0,0],A[0,31],A[10,20],ll_history[4]onward andfinal_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)AMICA_RUN_FORTRAN=1:test_doscaling_rows.py50 passed (both seeded-oracle tests through the hardened helper); the 11 test files these fixes and the float32 canaries touched, 232 passed, none skippeddoscaling=Falsebyte-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 MLXtest_mlx_fit_noop.pypins passed on macOSAMICA_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-m slow): 10 passed, 2 xfailed;test_rholrate_ratchets_at_maxdecs_not_per_decreaseneeded the recipe change listed belowuv run ruff check . && uv run ruff format --check .,uv run ty check,typos: cleanExisting tests changed
Tests that encoded the column rule:
torch_tests/test_ng_backend.py::test_newton_posdef_mstep_composition: the independent expectedAapplied 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'sAequals exactly what_rescale_componentsalone gives, and that every unfrozen iteration differs from that (so the check can fail).mlx_tests/test_mlx_fit_noop.py(renamedtest_unscaled_fit_*): compares against the pre-Phase-3 MLX class from git, which has the column rule; both fits now run withdoscaling=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 tomax_iteron every seed tried (0-11, both backends), so the restore never fired (failures, or silent "run was monotone" skips in five tests). Addednewtrate=3.0and, where the run stops viamin_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.pyuses 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.pypdftype=1 recipe:kurt_start8 -> 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 loosenedmin_dllstop (see "Review fixes"). Also fixed a latent ordering bug: the "returned parameters sit atfinal_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): thenewtrate=1.0run is now monotone through 300 iterations, so no ratchet fired;newtrate=3.0decreases 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=1stops 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_backendsis replaced bytest_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_rejectand its torch twintest_ng_backend.py::test_keep_best_inactive_under_rejectwere vacuous (monotone fits). Both now use the overshoot recipe, assert that the same fit restores withoutdo_rejectand that thedo_rejecttrajectory 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 nokeep_best, so no NumPy twin exists.Rejection agreement by seed (rejsig 2.0; second pass, the widest)
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.