Skip to content

Phase 4: port non-GG pdf families to the MLX backend - #275

Merged
neuromechanist merged 6 commits into
feature/issue-260-epic-mlx-parityfrom
feature/issue-265-phase4-mlx-pdf
Aug 23, 2026
Merged

neuromechanist merged 6 commits into
feature/issue-260-epic-mlx-parityfrom
feature/issue-265-phase4-mlx-pdf

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Ports the four fixed amica15.f90 source-density families (2 Gaussian, 3 logistic, 4 sub-Gaussian cosh+, 1 super-Gaussian cosh-) and the pdftype=1 extended-Infomax adaptive switcher from AMICATorchNG (issue #26) into AMICAMLXNG (issue #265), the final phase of epic #260. _score/_log_pdf (renamed from _score_gg/_log_pdf_gg) take an optional per-source pdtype array with pdtype is None as the zero-graph-node pdftype=0 fast path; a stable _logcosh avoids the float32 log(cosh(x)) overflow by |x|==90; constructor validation, dorho gating of the dead rho work, _choose_pdfs/_pdtype_from_kurtosis, and get_pdftype() are ported per AMICATorchNG. The plan is /Users/yahya/.claude/plans/cryptic-weaving-minsky.md; all ten decided policies were followed as written (see Deviations below for the one place I diverged and why).

pdftype=0 bit-identity

Compared the epic-tip (a8401fa, pre-#265) AMICAMLXNG against this PR's, both at pdftype=0, on the bundled sample EEG: single-model (n_mix=3, seed=42, 30 iters) and 2-model+Newton (seed=7, 15 iters) fits both produced bit-identical A (max abs diff 0.0) and identical ll_history. The default path is unchanged.

y==0 frequency per non-GG family

Policy 4's safe_y guard mirrors AMICATorchNG exactly for every family. Measured how often the y==0 lane actually fires over 15 iterations of the full bundled recording (32 ch x 30504 samples, float32): zero occurrences for all four non-GG families (2, 3, 4, 1) across every (sample, channel, mixture) triple touched. See .context/issue-265/pdf_family_findings.md for the full table.

Fixed-family vs torch results

The literal amica15.f90 z0/fp forms match MLX's float32 evaluation to rtol=atol=1e-6 on the standard 65-point grid for all four families; code 4's fp = y - tanh(y) was separately probed near zero and confirmed the plan's warning (100% relative error at y=1e-4, float32 rounds to exactly 0) — the absolute-tolerance criterion absorbs this correctly since the true value is itself tiny there, and no Taylor branch was added. A matched 100-iteration fit lands on the float64 PyTorch likelihood to within ~1e-7 for every family (gate is 0.05, four orders of margin).

Switcher no-oracle scoping

pdftype=1 has no bit-exact oracle in the reference binary: do_choose_pdfs is set at amica15.f90:612-613 but m2sum/m4sum (allocated at :608-609) are never accumulated, so it is behavior-validated only, exactly as ADR 0002 scopes for the PyTorch backend. On the bundled sample (seed=0, 20 iters, kurt_start=3/num_kurt=5/kurt_int=1) n_kurt_done reaches 5 and every source stayed super-Gaussian (kurtosis stayed positive for all 32 sources); the sub-Gaussian branch is separately pinned by a controlled-input unit test on the pure decision function (test_pdtype_from_kurtosis_decision), since real EEG at this seed never data-drives it.

Deviations from the plan

One: policy 5's _pdtype_from_kurtosis is described only as "the pure decision helper takes numpy arrays and returns the new int codes"; I gave it the exact 2-arg (kurt, nsub) signature AMICATorchNG uses (reading self.pdtype internally as the prior) rather than adding a third explicit prior argument, so it is a closer structural port and the existing torch unit test ports over call-for-call. No other deviations — the az_rho return-contract, the dorho gating of drho_n/lgamma-refresh/digamma, the host-float64 switcher accumulation, the shared_components() caveat, and the doc-accuracy fixes (including the numpy "GG only" correction) all follow the plan as written.

Gates (original round)

Gate 1 (pamica/tests/mlx_tests/ + test_mlx_pdf_families_cross_backend.py + test_mlx_sharing_cross_backend.py + test_mlx_newton_cross_backend.py + torch_tests/test_ng_pdf_families.py): 133 passed, 5 skipped (opt-in AMICA_RUN_FORTRAN=1 binary tests, pre-existing).
Gate 2 (uv run pytest -m "not slow" -n auto): 515 passed, 15 skipped, 1 xfailed — full suite green.
Gate 3 (ruff check + ruff format --check + ty check): zero diagnostics.
The slow full-fit-vs-torch tests (4 parametrizations of test_full_fit_ll_matches_torch_float64) were run once locally: all 4 passed, gaps ~1e-7 against the 0.05 bound.

Review response (4 pr-review-toolkit specialists, CI 8/8 green)

Fixed all 14 numbered findings across three atomic commits: 2 confirmed mutation-tested test-coverage holes, 2 additional test-quality items, 2 code items (entry-point pdtype validation and a new PDFTYPE_NAMES export), and 8 comment/doc accuracy fixes, plus documented 4 explicitly-rejected suggestions below.

Item 1 (test_multimodel_fixed_family, CRITICAL): ported verbatim from torch_tests/test_ng_pdf_families.py:344-355 into mlx_tests/test_mlx_pdf.py (n_models=2, pdftype=2, n_mix=3 real-EEG fit; asserts pdtype.shape==(NW,2), finite params, net non-decreasing LL).
Item 2 (get_pdftype error contract, CRITICAL): ported from torch_tests/test_ng_metadata.py:119-132, scoped to get_pdftype since MLX has no get_rho; independently re-verified by deleting _check_model_idx's bounds check locally and confirming the new test fails before restoring it.
Item 3: replaced the structurally-unfailable assert m.n_newton_fallbacks >= 0 with assert 0 <= m.n_newton_fallbacks <= len(ll).
Item 4: ported test_pdtype_h_is_none_only_for_gg as a cheap no-fit failure-attribution pin.
Item 5: added entry-point validation in _choose_pdfs (raises RuntimeError if a newly-decided code is outside {1, 4}) and in get_pdftype (raises if a stored code is outside {0,1,2,3,4}); both paths independently smoke-tested by injecting an out-of-range code and confirming the raise, per-call validation inside _score/_log_pdf was deliberately not added (see rejection (a) below).
Item 6: added PDFTYPE_NAMES to mlx_impl/core.py (duplicated from torch, no torch import) and exported it from mlx_impl/__init__.py, matching the torch surface.
Item 7 (CRITICAL): corrected the false "AMICATorchNG still pays the digamma pull every iteration" claim in all three flagged locations (core.py module docstring, docs/changelog.md, pdf_family_findings.md) — torch already gates its digamma pull behind self.dorho; its genuine non-GG dead work is the unconditional drho_n accumulation in _get_block_updates and the inline torch.lgamma(1+1/rho) recompute in _log_pdf_only.
Item 8: reworded the _logcosh precision claim from "exact to 1e-6" to "within float32 precision (~1e-4 absolute; measured 2.9e-5 at x=1000)".
Item 9: reworded the overflow-threshold claim from "at |x| >= 90" to "by |x| == 90 (measured crossover: finite at 89.0, inf at 89.5)".
Item 10: fixed the two stale pre-rename filenames in ADR 0002 (amica_pdf.py -> numpy_impl/pdf.py; torch_impl/amica_torch_ng.py -> torch_impl/core.py).
Item 11: added the "rho does not describe the fitted density for codes 1-4" caveat to the class-level pdftype doc block, not only get_pdftype's own docstring.
Item 12: replaced "see the PR" with the durable pointer .context/issue-265/pdf_family_findings.md.
Item 13: softened the kurt-hook-ordering comment to state plainly that the order is documentation, not a regression-tested contract (no test pins it, and swapping the hooks would pass the suite).
Item 14: copy-edited the amica-differences.md paragraph so self.dorho reads as a flag that gates work, not as work itself, and no longer repeats the digamma overclaim.

Explicitly rejected, per the coordinator's direction, restated here for the record: (a) per-call pdtype validation inside _score/_log_pdf — hot-path cost; the entry-point validation added in item 5 covers the same silent-failure risk. (b) Hardening the strippable asserts in _pdtype_h/_newton_direction-style code — this codebase's established type-narrowing convention on provably unreachable paths. (c) An MLX opt-in AMICA_RUN_FORTRAN binary-parity test — no existing MLX test uses that mechanism, and native-binary MLX integration is tracked separately against the #246 CI residue. (d) Non-opt-in switcher x Newton coverage — a shared pre-existing torch/MLX limitation on the no-oracle switcher, not debt introduced by this PR.

Gates (review-fix round)

Gate 1: 137 passed, 5 skipped (same pre-existing opt-in skips, plus the 4 new test items).
Gate 2 (uv run pytest -m "not slow" -n auto): 519 passed, 15 skipped, 1 xfailed — full suite green.
Gate 3 (ruff check + ruff format --check + ty check): zero diagnostics.
Head SHA after this round: 03f96d5.

Closes #265.
Part of epic #260.

@neuromechanist
neuromechanist merged commit ef1a4f5 into feature/issue-260-epic-mlx-parity Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-265-phase4-mlx-pdf branch August 23, 2026 16:42
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