Skip to content

Phase 12: normalize the drawn initial mixing matrix - #350

Merged
neuromechanist merged 20 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-341-phase12-init-normalize
Sep 23, 2026
Merged

neuromechanist merged 20 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-341-phase12-init-normalize

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Summary

The reference normalizes every component of a randomly drawn initial mixing matrix to unit norm (amica15.f90:805-823): per model it draws Wtmp, sets the block to 0.01*(0.5-Wtmp), sets the diagonal to exactly one, and divides each component by sqrt(sum(A(:,k)*A(:,k))); its restart-on-NaN redraw does the same (:1026-1044), a loaded A is used as is (:793-802), and fix_init starts from the identity. pamica drew I + 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 A through 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, one rng.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 with fix_init. Components are rows (ADR 0007). The generator is called exactly as before, so mu/beta and 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 A is untouched: only the draw branch normalizes. The NumPy backend, the one backend that takes a supplied initial A, now checks it at fit start (shape, finiteness, an invertible block per model) and raises ValueError naming the problem. normalize_components refuses 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 A starts 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-change 027cb07 against this branch):

first LL moves by final LL moves by
1 model, doscaling on (default) 2.7e-5 1.8e-6
1 model, doscaling off 2.7e-5 6.6e-7
2 models, doscaling on 1.7e-6 4.5e-4
2 models, doscaling off 1.7e-6 9.2e-4

With doscaling on, 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:

path before now
PyTorch AMICATorchNG._initialize_parameters (every fit, fresh RandomState(seed)) I + 0.01*(0.5-u) per model initial_mixing (normalized)
MLX AMICAMLXNG._initialize_parameters (every fit) same, cast to float32 initial_mixing in float64, then cast
NumPy AMICA._initialize_parameters while A is None (from self.rng) same initial_mixing
best-of-N n_restarts (PyTorch/MLX _fit_restarts set self.seed; NumPy _reset_for_restart reseeds and nulls A) redraw through the above normalized, through the above
NumPy restart-on-NaN _reinitialize_for_restart (nulls A, redraws from the advanced self.rng) unnormalized redraw normalized redraw (:1039-1040)
NumPy fix_init (attribute only: the constructor rejects the keyword (#346), and fix_init/load_A are unsupported params-file keys) identity identity through initial_mixing(fix_init=True), no draw consumed (tested on a real fit)
NumPy A supplied before fit, NumPy refit continuing from the previous fit's A used as is, unchecked used as is, after validate_supplied_mixing (wrong shape or singular block used to raise LinAlgError deep in the fit; a NaN entry ended the fit with no stop reason)
PyTorch from_state_dict / AMICA.load, MLX from_state_dict / load restored as saved restored as saved (untouched; all three tested bit for bit)
AMICANative (the binary) the binary's own normalized draw unchanged

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 normalized A. PyTorch and MLX take no user-supplied A anywhere except their validated saves (_initialize_parameters always draws; the wrapper and the MNE layer have no init argument), so the supplied-A check exists only in NumPy, as a shared function in pamica/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_mixing equals the reference's loop written out literally (1, 2, 3 models, three seeds), bit for bit, including the generator position afterward; fix_init gives the identity and consumes nothing.
  • test_every_fit_starts_from_unit_norm_components (3 backends x 1/2 models x n_restarts 1/2): a pass-through spy on _initialize_parameters and _update_parameters records A after 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 the 027cb07 classes (via pre_change.py) raise, with every start off unit norm by more than 1e-3.
  • Supplied/loaded A bit for bit: NumPy A set before fit, NumPy refit, PyTorch state_dict, the AMICA wrapper's save/load (PyTorch), MLX from_state_dict and save/load (all from a real doscaling=False fit whose rows are off unit norm by more than 1e-2).
  • test_numpy_fix_init_starts_from_the_identity: the constructor rejects fix_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), and model.rng.rand() afterward equals an untouched RandomState(SEED).rand(), so nothing was drawn (not mu or beta either).
  • test_numpy_refuses_a_supplied_A_no_fit_can_start_from (component-column shape, a NaN entry, an all-zero component row): ValueError with the named problem, raised before any E-step (a pass-through spy records none) with an empty ll.
  • test_normalizing_a_zero_or_nan_component_raises: a direct normalize_components call on a zero or NaN row raises ValueError naming 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 first A, mu and beta draws; control on 027cb07 is off unit norm.
  • Gated test_the_reference_draws_unit_norm_components (1/2 models, seeds 1 and 42): a new native_oracle.run_drawn_reference runs the binary with nothing loaded and max_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.
  • Gated 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 with update_A=0, so its rescale (:1845-1847, the same expression as the init's :818-819) is the only change to A: the result equals pamica's initial A within 4.4e-16.

Why no bit-level draw-then-normalize oracle: the binary draws from gfortran's random_number and pamica from NumPy's RandomState, and the binary normalizes only a draw of its own (load_A is used as is, fix_init draws 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 (pin fb13d76), 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_code and ::test_sources_grouped_by_a_merge_share_one_component_map (pin 0930c0e), mlx_tests/test_mlx_fit_noop.py (pin 2e04006), and the pre-change control of test_iteration_order_native_oracle.py (pin 5b6ae4f). Without adaptation 76 non-slow tests failed: the init changes every configuration from its first E-step (for example the MLX canary's ll_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 drawn A with the live initial_mixing result, in its own layout and dtype (PyTorch/MLX recompute from their fresh RandomState(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 initial A. A moved pin alone (to 027cb07) 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 and lrate 0.5 -> 0.4 (kurt_start=7 kept). Reason: from the normalized init, seed 3 at lrate 0.5 climbs monotonically to max_iter, so the restore never runs. At lrate 0.5, seeds 0-11 x kurt_start 3-11 gave only seed 1/kurt_start 11, after its LL fell by 8.6e3; most others end on nan_direction/nan_params. At lrate 0.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 on min_dll at 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, A maxima (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 moved ll_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 in mu and 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 keeps gm 1.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, whose A is held on iterations 12-13, the second model's gm falls 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 drop gm to 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_now differs 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.
  • ADR 0006: the former known difference is marked resolved by this phase (and ADR 0007's pointer updated).
  • docs/guides/amica-differences.md: the do_sphere=False section's "A = I + noise initialization" 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.
  • Changelog: also records the NumPy supplied-A check as a behavior change.

Notes for the lead

  • Phase 13 (Use the reference's single-precision density constants #344) changes the density constants; the seeded oracles run with 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).
  • Pre-existing, not caused by this phase: the share_comps counts in amica-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 on 027cb07 with 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, typos
  • uv run mkdocs build --strict (docs extra)
  • New tests: pamica/tests/test_initial_mixing.py, 41 passed with AMICA_RUN_FORTRAN=1
  • All gated oracles with AMICA_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 skipped
  • Full non-slow suite with CI=1: 1893 passed, 37 skipped, 1 xfailed
  • -m slow: 10 passed, 2 xfailed (the two strict xfails still fail as expected)
  • Validation harness --backend all before and after (numbers above)
  • git rev-parse --is-shallow-repository prints false

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.
The byte-identity pins (fb13d76, 0930c0e, 2e04006) and the #339 oracle
control now fit the historical class from the live normalized initial A
through pre_change.with_normalized_initial_mixing, so each still isolates
its own change. Tested: all those byte-identity tests pass.
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.
The pre-#344 control class predates #341, so it now starts from the normalized initial A the seeded reference uses. Tested: gated family oracles pass.
@neuromechanist
neuromechanist merged commit 09b8247 into feature/issue-324-epic-mlx-first-class Sep 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-341-phase12-init-normalize branch September 23, 2026 19:33
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