Repository navigation
Phase 12: normalize the drawn initial mixing matrix - #350
Merged
neuromechanist merged 20 commits intoSep 23, 2026
Merged
neuromechanist merged 20 commits into
neuromechanist merged 20 commits into
Conversation
run_drawn_reference runs the binary with nothing loaded and a fixed seed; with max_iter=0 it writes its drawn initialization. The run and read-back are shared with run_seeded_reference.
Every backend now draws its initial A through the shared pamica.initialization.initial_mixing: per model, 0.01*(0.5-u) with the diagonal set to one and each component divided by its norm, as the reference does (amica15.f90:805-823), including the NumPy restart redraw. A supplied or loaded A is used as is. Tested in later commits.
Always-on cross-backend start checks with a pre-change control, the supplied/loaded A paths, the NumPy restart redraw, and two gated native oracles. Tested: 34 passed with AMICA_RUN_FORTRAN=1.
The normalized initial A made seed 3 at lrate 0.5 climb monotonically to max_iter, so the restore was never exercised. Seed 6 at lrate 0.4 (kurt_start 7) overshoots by 0.17 after all five switch passes, on all 12 perturbed inputs. Tested: test_mlx_keepbest.py passes.
The normalized initial A moved the recorded trajectory (ll_history[0] by 1.55e-5). Pins re-recorded on the M4 Pro and tolerances re-derived from the same 48-draw float32 perturbation study, floored at one float32 unit: no draw moved ll_history[0]. Tested: the canary passes.
From seed 42's normalized init, one sample sits 2.3e-7 from a mixture center; the mu update amplifies the 1e-14 sphere round-off to 1.3e-9 (PyTorch and NumPy differ by 7.9e-10), over the 1e-9 bound. Seed 45 stays 7x under every bound; a new precondition asserts the backends' own disagreement sits 3x below each bound. Tested with the binary.
From its normalized initial A, seed 20's second model keeps gm 1.2e-3 after the second scan instead of collapsing to zero in one iteration. Seed 23 (of 23, 32, 40, 41 in seeds 0-49) collapses as the test needs. Tested with the binary (AMICA_RUN_FORTRAN=1).
Changelog entry with the measured behavior change, ADR 0006's remaining difference marked resolved (and ADR 0007's pointer), the differences guide's init wording and the re-searched collapse recipe. mkdocs build --strict passes.
From its normalized initial A, seed 0's discarded step moved the MIR by 2.1e-4 relative (3.4e-5 to 2.1e-3 over 8 perturbed inputs), inside the 1e-4 margin on the CI GPU. Seed 7 moves it by 2.3e-3 to 2.9e-3 on every input. Tested: test_mlx_mir.py passes.
normalize_components now raises ValueError on a zero or non-finite row norm instead of returning NaN. The reference path cannot reach it (the unit diagonal keeps every norm >= 1). Tested: zero and NaN rows.
A supplied A (or one left by a previous fit) now raises ValueError on a wrong shape, a non-finite entry or a singular model block, through the shared validate_supplied_mixing. Before, it raised LinAlgError deep in the fit, or (NaN) ended with no stop reason. Tested: all three.
fix_init (an attribute) starts from the stacked identity and leaves the generator untouched; AMICA save/load restores the PyTorch A bit for bit. Tested: test_initial_mixing.py passes.
The 9.0e-4 gm drop is pamica's own fit, whose A is held on those iterations; the 4.2e-3 both sides reach comes from the freeze-free continuation. Docs and test comment now say so. Docs only.
ADR 0006 marks the init difference as former; the _FLOOR_MARGIN comment names the worse of doscaling on and off; pre_change notes a component is a block row in both layouts. Comments only.
Brings in 0138a71 (issue #344, the reference's single-precision constants). Byte-identity pins against pre-#341 commits now combine with_normalized_initial_mixing on the old class with use_pre_344_constants on the live one. Changelog keeps both entries. Tested: the pins, test_initial_mixing and test_reference_constants pass (223 passed, 15 gated skips).
The merged-state oracle now sphers pamica's data with the binary's own sphere, so both sides start from the same bits after the Phase 12 and 13 merge. Tested: gated component-row oracles pass.
neuromechanist
merged commit Sep 23, 2026
09b8247
into
feature/issue-324-epic-mlx-first-class
8 checks passed
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
The reference normalizes every component of a randomly drawn initial mixing matrix to unit norm (
amica15.f90:805-823): per model it drawsWtmp, sets the block to0.01*(0.5-Wtmp), sets the diagonal to exactly one, and divides each component bysqrt(sum(A(:,k)*A(:,k))); its restart-on-NaN redraw does the same (:1026-1044), a loadedAis used as is (:793-802), andfix_initstarts from the identity. pamica drewI + 0.01*(0.5-u)(diagonal one plus noise) and never normalized, so its initial components were up to about 5e-3 off unit norm.Every backend (PyTorch, NumPy, MLX) now draws its initial
Athrough one shared function,pamica.initialization.initial_mixing(.rules/backend_parity.md: the draw is a shared decision), which follows the reference's exact recipe and order: per model, onerng.rand(n, n)call,0.01*(0.5-u), diagonal set to one, each component row divided by its Euclidean norm (no zero-norm guard, as in the reference: the unit diagonal makes every norm at least 1), identity withfix_init. Components are rows (ADR 0007). The generator is called exactly as before, somu/betaand every later draw are unchanged; MLX normalizes in float64 and then casts to float32. The NumPy restart after a non-finite likelihood redraws through the same function (:1039-1040).A supplied or loaded
Ais untouched: only the draw branch normalizes. The NumPy backend, the one backend that takes a supplied initialA, now checks it at fit start (shape, finiteness, an invertible block per model) and raisesValueErrornaming the problem.normalize_componentsrefuses a zero or non-finite component instead of returning NaN (unreachable on the reference path, whose unit diagonal keeps every norm at least 1).Part of epic #324; resolves #341 (closes when the epic merges to dev).
Behavior change
Normalizing at init is not a compensated rescale, so every fit from a drawn
Astarts from a different point: the first E-step changes, and the trajectory after it. Measured on the bundled sample (PyTorch float64, seed 42, 100 iterations, pre-change027cb07against this branch):doscalingon (default)doscalingoffdoscalingondoscalingoffWith
doscalingon, the first rescale used to normalize the components after iteration 1 anyway, so the effect is small; with it off the init scale was never corrected and the change reaches the whole fit. The validation harness (--backend all, 100 iterations, against the native binary from its own draw) is unchanged at its precision: mean matched correlation 0.9991 and Amari distance 0.0038 before and after on all three backends; LL gap 2.61e-4 to 2.67e-4 before, 2.67e-4 to 2.75e-4 after.Init-path inventory
Every path that sets an initial
A, and whether this PR touches it:AMICATorchNG._initialize_parameters(everyfit, freshRandomState(seed))I + 0.01*(0.5-u)per modelinitial_mixing(normalized)AMICAMLXNG._initialize_parameters(everyfit)initial_mixingin float64, then castAMICA._initialize_parameterswhileA is None(fromself.rng)initial_mixingn_restarts(PyTorch/MLX_fit_restartssetself.seed; NumPy_reset_for_restartreseeds and nullsA)_reinitialize_for_restart(nullsA, redraws from the advancedself.rng):1039-1040)fix_init(attribute only: the constructor rejects the keyword (#346), andfix_init/load_Aare unsupported params-file keys)initial_mixing(fix_init=True), no draw consumed (tested on a real fit)Asupplied beforefit, NumPy refit continuing from the previous fit'sAvalidate_supplied_mixing(wrong shape or singular block used to raiseLinAlgErrordeep in the fit; a NaN entry ended the fit with no stop reason)from_state_dict/AMICA.load, MLXfrom_state_dict/loadAMICANative(the binary)Tests seed the binary with pamica's init through
load_A(pamica/tests/native_oracle.py), so every existing seeded oracle now runs from the normalizedA. PyTorch and MLX take no user-suppliedAanywhere except their validated saves (_initialize_parametersalways draws; the wrapper and the MNE layer have no init argument), so the supplied-Acheck exists only in NumPy, as a shared function inpamica/initialization.py.Tests
New module
pamica/tests/test_initial_mixing.py(35 always-on, 6 gated):test_the_shared_draw_is_the_reference_recipe:initial_mixingequals the reference's loop written out literally (1, 2, 3 models, three seeds), bit for bit, including the generator position afterward;fix_initgives the identity and consumes nothing.test_every_fit_starts_from_unit_norm_components(3 backends x 1/2 models xn_restarts1/2): a pass-through spy on_initialize_parametersand_update_parametersrecordsAafter each init and at the first update; each restart starts from the recipe for its own seed (float64 bits on PyTorch and NumPy, their float32 cast on MLX, so the backends agree), unit norm within 1e-15 (float64) / 1.2e-7 (float32), unchanged up to the first update.test_the_pre_change_code_fails_the_start_checks: the same checks run on the027cb07classes (viapre_change.py) raise, with every start off unit norm by more than 1e-3.Abit for bit: NumPyAset beforefit, NumPy refit, PyTorchstate_dict, theAMICAwrapper'ssave/load(PyTorch), MLXfrom_state_dictandsave/load(all from a realdoscaling=Falsefit whose rows are off unit norm by more than 1e-2).test_numpy_fix_init_starts_from_the_identity: the constructor rejectsfix_init=True(AMICA_NumPy silently ignores unknown options #346); set as the attribute, a real two-model fit starts from exactly the stacked identity (spy at init and at the first update), andmodel.rng.rand()afterward equals an untouchedRandomState(SEED).rand(), so nothing was drawn (notmuorbetaeither).test_numpy_refuses_a_supplied_A_no_fit_can_start_from(component-column shape, a NaN entry, an all-zero component row):ValueErrorwith the named problem, raised before any E-step (a pass-through spy records none) with an emptyll.test_normalizing_a_zero_or_nan_component_raises: a directnormalize_componentscall on a zero or NaN row raisesValueErrornaming the row.test_the_numpy_restart_redraws_unit_norm_components(1/2 models): the sanctioned NaN injection forces a restart; the redraw is unit norm, differs from the first draw and equals the recipe on the generator continuing past the firstA,muandbetadraws; control on027cb07is off unit norm.test_the_reference_draws_unit_norm_components(1/2 models, seeds 1 and 42): a newnative_oracle.run_drawn_referenceruns the binary with nothing loaded andmax_iter=0, which writes its own drawn init; its components are unit norm within 4.4e-16, the diagonal entry is each component's largest, and the others relative to it lie within the draw's half-width 0.005 (measured max 0.004998); pamica's draw has the same shape.test_the_reference_normalizes_pamicas_draw_as_pamica_does(1/2 models): the binary is loaded (load_A) with pamica's draw BEFORE normalization (off unit norm by 1.8e-4) and run one iteration withupdate_A=0, so its rescale (:1845-1847, the same expression as the init's:818-819) is the only change toA: the result equals pamica's initialAwithin 4.4e-16.Why no bit-level draw-then-normalize oracle: the binary draws from gfortran's
random_numberand pamica from NumPy'sRandomState, and the binary normalizes only a draw of its own (load_Ais used as is,fix_initdraws nothing), so it cannot be fed pamica's unnormalized draw on its init path. The two gated tests above check the two halves instead (the draw path normalizes; the normalization arithmetic matches on pamica's own draw). This is also written in the test module docstring.Existing tests changed, with reasons
Byte-identity pins (values unchanged; old side adapted):
test_doscaling_rows.py::test_doscaling_off_is_byte_identical_to_the_pre_fix_code(pinfb13d76),test_component_rows.py::test_unshared_fits_are_byte_identical_to_the_column_layout(66 configurations),::test_single_model_export_is_byte_identical_to_the_pre_change_codeand::test_sources_grouped_by_a_merge_share_one_component_map(pin0930c0e),mlx_tests/test_mlx_fit_noop.py(pin2e04006), and the pre-change control oftest_iteration_order_native_oracle.py(pin5b6ae4f). Without adaptation 76 non-slow tests failed: the init changes every configuration from its first E-step (for example the MLX canary'sll_history[0]by 1.55e-5). Decision: an init-normalization-aware comparison, keeping the original pins.pre_change.with_normalized_initial_mixing(cls)subclasses the historical class so it draws exactly as it always did and then replaces only the drawnAwith the liveinitial_mixingresult, in its own layout and dtype (PyTorch/MLX recompute from their freshRandomState(seed); NumPy renormalizes its own draw, whose off-diagonals are bit-identical to the live draw's, which also covers its restart redraw). With it, every pinned configuration is bit-identical, which is the evidence that this phase changes nothing but the initialA. A moved pin alone (to027cb07) could not pass, for the same reason, and would drop each test's original claim.Data-driven tests re-searched or re-recorded (no tolerance loosened):
mlx_tests/test_mlx_keepbest.py::test_pdftype1_forced_restore_rolls_back_n_kurt_done_with_pdtype: recipe seed 3 -> 6 andlrate0.5 -> 0.4 (kurt_start=7kept). Reason: from the normalized init, seed 3 atlrate0.5 climbs monotonically tomax_iter, so the restore never runs. Atlrate0.5, seeds 0-11 xkurt_start3-11 gave only seed 1/kurt_start11, after its LL fell by 8.6e3; most others end onnan_direction/nan_params. Atlrate0.3/0.4/0.6/0.7, eight runs overshoot sanely (0.06 to 0.19), each on 12/12 relative data perturbations of 1e-6. The chosen one stops onmin_dllat ll index 18, 0.17 below the peak at index 6, after all five switch passes.mlx_tests/test_mlx_transform.py::test_fit_path_is_unchanged_by_phase1(float32 canary): re-recorded on the M4 Pro (the pre-change recording reproduced exactly first).ll_history-3.3320186 ... -3.2506354 -> -3.3320341 ... -3.2506275;A[0,0]0.9853508 -> 0.98533404,A[5,5]0.99289405 -> 0.992889,A[10,20]-0.0037210553 -> -0.0037056825,A[31,31]0.99681115 -> 0.9968118,A[0,31]0.0327551 -> 0.03281356. Tolerances re-derived from the same 48-draw float32 perturbation study (seed 20260922): relative LL maxima [7.16e-8, 1.38e-6, 2.91e-7, 4.38e-7, 2.63e-6, 4.09e-6, 4.98e-6, 3.66e-6, 3.23e-6, 4.11e-6] -> [0, 1.09e-6, 5.83e-7, 2.92e-7, 2.19e-7, 1.83e-6, 4.68e-6, 6.67e-6, 4.91e-6, 4.03e-6], final 4.11e-6 -> 4.03e-6,Amaxima (1.87e-5, 1.49e-6, 1.90e-6, 1.49e-6, 1.87e-5) -> (1.76e-5, 1.79e-6, 1.34e-5, 1.25e-6, 3.36e-6). No draw movedll_history[0](nor any of 192 draws), which would make its tolerance zero although CI's GPU once moved it by one float32 unit, so every tolerance is now floored at one float32 unit in the last place of the recorded value (the study's resolution):ll_history[0]keeps 7.2e-7, exactly its previous tolerance. A 192-draw study stays within every tolerance (largest ratio 1.8 against the 48-draw maxima). The canary catches this change:ll_history[0]moved 22 times its tolerance,ll_history[1..4]4.1 to 8.5 times,A[0,31]5.8 times.test_doscaling_rows.py::test_doscaling_matches_the_seeded_reference(gated): oracle seed 42 ->ORACLE_SEED = 45, plus a new precondition. Reason: seed 42's normalized two-model state puts one sample 2.3e-7 from a mixture center, and the exact-EM mu update weighs it|y|^(rho-2), amplifying the 1e-14 differences between the three spheres: after one iteration PyTorch and NumPy disagree with EACH OTHER by 7.9e-10 inmuand with the reference by 5.1e-10 and 1.3e-9 (bound 1e-9); the binary against itself (1/2/4 threads) differs by 1e-16. So this is the state's round-off floor, not a parity defect. Of seeds 42 and 45-56 only 45 (0.14 of the bounds) and 47 (0.33) stay within every bound; the others exceed one by up to 34 times, with PyTorch and NumPy as far apart as each is from the reference (with the pre-change init, seeds 42-49 kept the one-iteration PyTorch mu deviation below 2.7e-10). New measured maxima (doscaling on/off): 1 it A 2.1e-15/2.3e-15, mu 1.3e-10/1.3e-10, sbeta 2.4e-14; 3 its A 3.6e-12/1.1e-11, mu 1.4e-7/4.3e-8, sbeta 1.1e-10. Bounds unchanged. The new guard asserts the PyTorch-vs-NumPy disagreement sits at least 3 times below every bound (the smallest margin the bounds were set with), so an ill-conditioned state fails as a setup error instead of a parity failure.test_component_rows.py::test_an_early_mass_merge_collapses_the_reference_too(gated): recipe seed 20 -> 23. Reason: from its normalized init, seed 20's second model keepsgm1.2e-3 after the second scan and 1.7e-3 one iteration later, instead of reaching zero. Of seeds 0-49 (share_start=share_iter=11), 23, 32, 40 and 41 satisfy every condition (share 10: none of 0-29; 12: seeds 11 and 27). Seed 23: 28 merges at iteration 11. In the fit itself, whoseAis held on iterations 12-13, the second model'sgmfalls from 0.57 to 9.0e-4 within two iterations. The test's continuation from the post-scan state runs without the freeze on both sides: the binary's update and pamica's update rule both dropgmto 4.2e-3 within two iterations (the 4.2e-3 and the 9.0e-4 are different runs, not a disagreement). After the second scan both reach zero in one iteration, and the binary reports a NaN restart after two.mlx_tests/test_mlx_mir.py::test_mir_history_survives_keep_best_restore: seed 0 -> 7 (the forced-overshoot recipe otherwise unchanged). Found by the first CI run of this PR: on the CI macOS GPU the final assertion (mir_nowdiffers from the last waypoint by more than 1e-4 relative) failed. Reason: from seed 0's normalized init, the one discarded step moves the MIR by 2.1e-4 relative locally (it was 9.4e-4), and by 3.4e-5 to 2.1e-3 over 8 relative data perturbations of 1e-6, so it sits inside the float32 margin on some inputs. Of seeds 0-11 (each with the 8 perturbations), seed 7 has the largest smallest shift: 2.5e-3 (2.3e-3 to 2.9e-3 perturbed), stopping at iteration 15, 2.5e-2 below the peak at 14. The margin is unchanged.Docs
docs/changelog.md"Unreleased": the behavior change and its measured size.docs/guides/amica-differences.md: thedo_sphere=Falsesection's "A = I + noiseinitialization" wording, and the collapse recipe (seed 23 numbers, with the fit's 9.0e-4, freeze included, kept apart from the freeze-free 4.2e-3 both sides reach). No table row mentioned the init scale.Acheck as a behavior change.Notes for the lead
maxrho=2, so whichever PR lands second should re-run the gated oracles (the doscaling oracle now has about 7 times margin on every bound).share_compscounts inamica-differences.md(a scan at iteration 8 merges 32/24, at 20 merges 24/5; the binary-state similarity 32/32/30; three pairs at 300 iterations) do not reproduce on027cb07with the obvious protocol (full sample, seed 42, PyTorch defaults): 31/19 at 8, 24/4 at 20, 32/31/19, and 10 merges at 300 iterations. On this branch the same protocol gives 30/17, 22/5, 31/30/17 (the binary-state similarity again merges exactly the PyTorch and NumPy pairs) and 10 merges. I left those sentences unchanged.Test plan
uv run ruff check .,uv run ruff format --check .,uv run ty check,typosuv run mkdocs build --strict(docs extra)pamica/tests/test_initial_mixing.py, 41 passed withAMICA_RUN_FORTRAN=1AMICA_RUN_FORTRAN=1(test_component_rows,test_doscaling_rows,test_fortran_param_forwarding,test_initial_mixing,test_iteration_order_native_oracle,test_llt_stash,test_schedule_native_oracle,torch_tests/test_ng_pdf_families): 277 passed, none skippedCI=1: 1893 passed, 37 skipped, 1 xfailed-m slow: 10 passed, 2 xfailed (the two strict xfails still fail as expected)--backend allbefore and after (numbers above)git rev-parse --is-shallow-repositoryprintsfalse