Repository navigation
Phase 13: use the reference's single-precision constants - #349
Merged
neuromechanist merged 13 commits intoSep 23, 2026
Merged
neuromechanist merged 13 commits into
neuromechanist merged 13 commits into
Conversation
The reference writes its density normalizers as default-kind literals widened with dble, so the binary uses their float32 roundings. All three backends now read those values, and epsdble's, from one shared module, pamica/reference_constants.py; MLX holds the rho == 2 normalizer in its lgamma table. The literal-formula tests and the benchmark's copy now use the reference's values. Tested: pdf-family and backend test files pass.
The byte-identity tests against code from before issue #344 (component rows, doscaling off, the MLX pre-Phase-3 tip) now give the live backend its old density constants through pre_change.use_pre_344_constants, so they still isolate the change each was written for: their two-model and non-GG fits reach the changed normalizers. Tested: the three files pass.
test_reference_constants.py checks each shared constant against the float32 rounding of its literal on the cited reference line (exact rational arithmetic), pins the sweep of amica15.f90 and its header, checks that no backend keeps a copy, checks every backend's rho == 2 log-density, and (opt-in) seeds the native binary for pdftype 2, 4 and 1. Tested: 23 passed with AMICA_RUN_FORTRAN=1.
The merged-state oracle no longer holds maxrho at 1.99: its warm seed now has mixtures clamped at 2, it asserts that, and the code before issue #344 is replayed from the same state as a control (off by 2.8e-9 in log-likelihood after 1 iteration, against 2.2e-15 now). Tolerances unchanged. Tested with AMICA_RUN_FORTRAN=1.
Changelog entry with the oracle numbers; the differences guide gains a section on the constants, and row 16 now records the one kind of single-precision literal pamica keeps at its decimal value (defaults of input.param keys); the validation guide notes the new family oracle. Tested: mkdocs build --strict, typos.
Without an lrate key the reference never sets its ceiling lrate0, so its lrate drops to 0 after the first iteration (checked against the pinned binary). Row 16 now says so and uses comp_thresh as the example. Tested: mkdocs build --strict, typos.
On a host without MLX the byte-identity tests imported the MLX module to patch it before the check that skips them. Resolve the classes first. Tested: the two files pass with MLX and skip its cases without.
numpy_impl.pdf.compute_log_pdf had no callers in the package, tests or docs. Tested: the pdf and viz tests pass.
compute_pdf, which viz.plot_pdf_fits draws, now takes its normalizers from pamica.reference_constants, including the reference's single-precision sqrt(pi) at rho == 2, so it draws the density the fit uses. Its docstring says it is a plotting helper with the legacy pdftype numbering. Tested: the pdf, viz and constants tests pass.
The no-copy test now scans every .py file of torch_impl, numpy_impl and mlx_impl with comments and strings blanked, and flags the linear forms (sqrt(pi), sqrt(2*pi), ...) as well as the log forms and the literals. A new test checks that it flags every definition this change removed. Tested: passes; fails on the old pdf.py sqrt(pi) line (checked by hand).
The family oracle now asserts that every source kept its family and no kurtosis switch ran (n_kurt_done == 0), for pdftype=1 with num_kurt=0 too, in the live and the pre-change runs. Tested with AMICA_RUN_FORTRAN=1.
A control test: every constant use_pre_344_constants patches differs from the live value, the patch takes effect, it covers every changed constant each backend module reads, and on MLX it restores the pre-change rho == 2 table entry. Tested: passes on all three backends.
compute_pdf now draws the fit's density and compute_log_pdf is gone. Tested: mkdocs build --strict, typos.
neuromechanist
merged commit Sep 23, 2026
0138a71
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 writes several density normalizers as default-kind (single-precision) Fortran literals widened with
dble, for examplelog(dble(2.506628274)), so the binary uses the float32 rounding of each decimal, not the decimal. pamica used the decimals' double values. All three backends (PyTorch, NumPy, MLX) now read the reference's values from one new shared module,pamica/reference_constants.py: the generalized Gaussian'srho == 2normalizer (log(dble(1.772453851)), amica15.f90:1313), the Gaussian and the two cosh families (pdftype2, 4 and 1, :1333, :1359, :1371), and the rho-update guardepsdble(1.0e-16, amica15_header.f90:73, hard-coded, used at :1558). The dyadiclog(dble(2.0))andlog(dble(4.0))move into the same module at their exact values. MLX casts the values to float32; atrho == 2its host-side lgamma table now holdsLOG_SQRT_PI - LOG2, soLOG2 + tableis the reference's normalizer.The default
maxrho = 2clamp makes therho == 2branch common (a two-model fit on 4096 samples of the bundled recording reaches it on its fifth iteration), so default GG trajectories move by a tiny amount toward the reference. The merged-state oracle of Phase 8 no longer needs itsmaxrho = 1.99workaround: seeded atrho == 2, PyTorch and NumPy match the binary to float64 round-off, where the code before this change is off by 2.8e-9 in log-likelihood after one iteration and 1.2e-8 after three (and 8.4e-3 in themuof a low-mass mixture). New seeded oracles forpdftype2, 4 and 1 show the pre-change log-likelihood off by exactly each literal's rounding (3.66e-10, 2.02e-8, -2.06e-8), now 2.7e-15 or less; this also confirms against the binary the three offsets Phase 8 had only computed.Parameters the reference reads from
input.paramare unchanged (lead's decision): the binary's compiled-in defaults are single-precision too (lrateprints as 0.1000000015 when the key is missing, 0.10000000000000001 when given), but pamica's native engine and the seeded oracles write every such key. Checking that also showed a reference quirk: without anlratekey its ceilinglrate0is never set (amica15.f90:3617 is its only assignment), so the binary'slratedrops to 0 from the second iteration (min(lrate0, ...), :1812); row 16 says so. Row 16 of the differences guide is rewritten to record exactly that remaining difference; the fix itself gets its own section. The initialization scales (0.05, 0.1, 0.01) are single-precision literals too but are init code (Phase 12's) drawn from a different generator, so they are recorded and not adopted.The three tests that compare a live backend bit for bit with code from before this change (Phase 8's layout comparison, Phase 7's
doscaling=Falsecomparison, and the MLX pre-Phase-3 no-op check) failed because their two-model and non-GG fits reach the changed normalizers. They now give the live backend its pre-#344 constants first through a new helper,pamica.tests.pre_change.use_pre_344_constants(monkeypatches the five module constants; every code path still runs), so each still isolates the change it was written for, at full byte-identity strength.Review follow-up: the NumPy plotting helper
numpy_impl.pdf.compute_pdf(drawn byviz.plot_pdf_fits) now takes its normalizers frompamica.reference_constants, including the single-precisionsqrt(pi)atrho == 2, so it draws the density the fit uses; its module docstring now says it is a plotting helper with the legacypdftypenumbering, and its unusedcompute_log_pdfis removed. The no-copy test scans every.pyfile oftorch_impl,numpy_implandmlx_impl(comments and strings blanked) and flags linear forms (sqrt(pi),sqrt(2 * np.pi), ...) as well as log forms and literals; a companion test checks it flags every definition this change removed, and restoring the oldpdf.pyline makes it fail (checked by hand). A control test checks thatuse_pre_344_constantschanges every constant it patches, covers every changed constant each backend reads, and restores the pre-change MLXrho == 2table entry. The family oracle asserts that every source kept its family and no kurtosis switch ran (n_kurt_done == 0).Part of epic #324; resolves #344 (closes when the epic merges to dev).
The literal sweep
Every real literal in
amica15.f90's code isdble(<default-kind literal>); there are no bare ord0literals (pinned bytest_every_inexact_single_precision_literal_in_the_reference_is_accounted_for).funmod2.f90(gamln,psifun) usesD-exponent double literals throughout, plus exact1.0.log(dble(1.772453851)), GG atrho == 20.5*log(pi)(MLX:log 2 + lgamma(1.5))maxrhoclamp; adopted (LOG_SQRT_PI)log(dble(2.506628274)),pdftype2log(2.506628274)LOG_SQRT_2PI)log(dble(4.132731354)),pdftype4log(4.132731354)LOG_NORM_COSH_SUB)log(dble(1.858073988)),pdftype1log(1.858073988)LOG_NORM_COSH_SUP)epsdble = 1.0e-16(never read from input.param)1e-16log(dble(2.0))log(2.0)LOG2, same valuelog(dble(4.0)), logisticlog(4.0)LOG4, same valuedble(0.05),muinit jitterdble(0.1),sbetainitdble(0.01),Ainit and NaN-restart redrawdble(-999999999.0),dble(999999999.0)dble(1.5)dble(0.0),1.0,2.0,0.5,-1.0,0.25,4.0mineig = 1.0e-15lrate = 0.1,minlrate = 1.0e-12,rholrate = rholrate0 = 0.05rholratefact = 0.1invsigmin = 0.0001comp_thresh = 0.99,min_dll = 1.0e-9,min_nd = 1.0e-7(keymin_grad_norm)mincond = 1.0e-15,maxdble = 1.0e32,mineigv = 1.0e-15,minhess = 1.0e-5minrho = 1.0,maxrho = 2.0,minlog = -1500.0,rejsig = 3.0,lratefact = 0.5,rho0 = 1.5,invsigmax = 1000.0,newtrate = 0.5Oracle numbers (native binary v0.3.3, float64)
rho == 2, merged two-model warm state (test_component_rows.py::test_updates_from_a_merged_state_match_the_seeded_reference,maxrho = 2.0, maxima over PyTorch/NumPy anddoscalingon/off; bounds unchanged):Same state with no merge (noise floor): 1 iteration A 1.1e-15, mu 1.7e-12, sbeta 1.2e-14, LL 0; 3 iterations A 5.1e-14, mu 3.3e-9, sbeta 1.9e-12, LL 1.3e-14. The pre-#344 replay is now an in-test control (every quantity over its bound, LL over 10x).
Fixed families, seeded from pamica's initialization (
test_reference_constants.py::test_family_matches_the_seeded_reference, PyTorch):pdftypeBefore the change the A/mu/sbeta errors were the same (the normalizer shifts every mixture of a family alike); only the log-likelihood was off, by exactly
log(float32(lit)) - log(lit). The test asserts that for the replayed pre-#344 code, to 1e-12.The other gated oracles (
test_doscaling_rows,test_iteration_order_native_oracle,test_schedule_native_oracle,test_llt_stash,test_fortran_param_forwarding,test_ng_pdf_familiesconverged LL) pass with their bounds unchanged.Existing tests changed
torch_tests/test_ng_pdf_families.py,test_mlx_pdf_families_cross_backend.py: the "literal Fortran" normalizers are now the float32 roundings of the literals (the binary's values); tolerances unchanged (1e-12 and 1e-6).torch_tests/test_ng_backend.py: its independentrho == 2log-density uses the reference's normalizer.test_component_rows.py: merged oracle atmaxrho = 2.0; the seed guard flipped fromrho.max() < 2to "some mixture sits atrho == 2" (so the branch is exercised); pre-Use the reference's single-precision density constants #344 control added; measured-numbers comment updated; bounds unchanged. The byte-identity test against0930c0ecallsuse_pre_344_constants.test_doscaling_rows.py::test_doscaling_off_is_byte_identical_to_the_pre_fix_codeandmlx_tests/test_mlx_fit_noop.py(both tests): calluse_pre_344_constants.benchmarks/reproduce_table1.py: its literal-formula copy uses the reference's values.test_pamica.py::test_pdf_computationandtest_amica.py::test_pdf_computation: therho == 2expectation ofcompute_pdfis the reference's normalizer (tolerance unchanged).No MLX float32 pin moved, so no new perturbation-derived tolerance was needed.
Test plan
uv run ruff check,ruff format --check,ty check,typosmkdocs build --strict(isolated env with the docs extra)pamica/tests/test_reference_constants.py: 55 passed withAMICA_RUN_FORTRAN=1on Apple Silicon (60 passed, 5 skipped with the pdf tests in an env without MLX)AMICA_RUN_FORTRAN=1, plus the byte-identity, pdf and viz tests: 350 passedCI=1: 1910 passed, 34 skipped, 1 xfailed (after the review follow-up)-m slowwithCI=1: 10 passed, 2 xfailed (the two existingtest_sample_data.pyxfails)uv run --isolated, as on the Linux runner): 114 passed, 58 skippedgit rev-parse --is-shallow-repository: false