Skip to content

Fix numpy_impl weight-gradient norm to Fortran's formula - #217

Merged
neuromechanist merged 3 commits into
mainfrom
212-numpy-nd-formula
Aug 10, 2026
Merged

neuromechanist merged 3 commits into
mainfrom
212-numpy-nd-formula

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Completes #212. The log-likelihood half landed in #215; this is the gradient-norm half.

The bug

self.nd was built from the raw dWtmp block sum. It was never divided by dgm[h], never had I added, was never premultiplied by A, and was never masked by comp_used. It did not use directions[h] at all, despite that being the quantity computed two lines above which drives the actual A update.

Result: it reported about 5.4e3 on the bundled sample where Fortran reports about 5.7e-2, and it sat flat across iterations rather than tracking convergence. min_nd/use_grad_norm was therefore unreachable in this backend, exactly as min_dll was before #215. Both Fortran convergence criteria were dead here, not one.

The fix

Mirrors amica15.f90:1731-1743: dAk is the gm-weighted average of the per-model directions mapped through A, scattered by comp_list, divided by zeta, then masked by comp_used.

It also moves the computation. Fortran builds dAk inside accum_updates_and_likelihood (:1731-1743) strictly before update_params applies the step (:1789), so the norm describes the step about to be taken. Ours was computed after the A update and after the doscaling rescale, which measures a different quantity.

comp_used is None until fit() sets it up, and the M-step is exercised directly in tests before that happens, so the mask falls back to all-used rather than asserting. An earlier attempt that asserted non-None broke test_newton_mstep_matches_numpy_reference.

Verification

Against the reference binary on the bundled sample, iteration 1: 5.717e-2 vs Fortran's 5.75e-2, ratio 0.994.

Later iterations diverge, and that is expected rather than a defect. dAk tends to zero at the fixed point, so the norm measures a near-total cancellation and small floating-point and BLAS-order differences are amplified in the residual. Both backends settle on their own noise floor while agreeing on the log-likelihood to 4-5 significant figures. The same pattern holds between AMICATorchNG and Fortran.

Tests

pamica/tests/test_numpy_grad_norm.py, real bundled EEG, no hardcoded Fortran constants. Both assert properties the bug actually violated, and both were confirmed to fail against the pre-fix implementation (984.0 and 1449.1 against bounds of 1.0 and half the initial mean):

  • the norm is on a normalized scale, order 1e-2 rather than 1e3;
  • the norm shrinks as the fit approaches a stationary point, where the old one was flat.

A third test comparing doscaling on and off was written and then removed: it passed against the pre-fix implementation too, because rescaling changes A, which changes the next iteration's sufficient statistics, so the trajectories differ either way. It would have asserted nothing. A comment records that so nobody re-adds it.

Exact-value assertions against Fortran are avoided deliberately. Iteration counts for convergence quantities vary by more than 3x across BLAS implementations (measured 326 / 412 / 1076 for the same min_dll stop across macOS-arm64, Linux-x86_64 and the CI runner in #213), so a golden value would be a snapshot of one machine.

Not addressed

min_nd = 1e-7 remains unreachable on this dataset for all three implementations, Fortran included: Fortran's own trajectory oscillates around 1e-5 out to iteration 5073 without stopping. That is a property of 30504 samples against 1024+ free parameters, and Fortran ships the same default. It should be documented, not tuned, and is tracked separately.

self.nd was built from the raw dWtmp block sum: never divided by
dgm[h], never +I, never premultiplied by A, never masked by comp_used.
It did not use directions[h], the quantity computed two lines above
that drives the actual A update. It reported ~5.4e3 on the bundled
sample where Fortran reports ~5.7e-2, and sat flat rather than tracking
convergence, so min_nd/use_grad_norm was unreachable in this backend.

Now mirrors amica15.f90:1731-1743: dAk is the gm-weighted average of the
per-model directions mapped through A, divided by zeta, masked by
comp_used. Moved to before the A step and the doscaling rescale, since
Fortran builds dAk in accum_updates_and_likelihood (:1731-1743) strictly
before update_params applies it (:1789).

Verified against the reference binary: nd at iteration 1 is 5.717e-2
against Fortran's 5.75e-2, a ratio of 0.994.

Refs #212
- Correct a comment that described ndtmpsum as dividing by lrate. It does
  not, and neither does Fortran; the comment risked someone 'fixing' a
  nonexistent bug.
- Record that self.gm is already updated when dAk is built, where Fortran
  still holds the previous iteration's value. Invisible for one model and
  for disjoint comp_list, differs under share_comps. Filed as #219.
- Add a test that pins the computation to the pre-step mixing matrix, the
  one gap the previous two tests could not cover. It derives the expected
  norm from the step actually taken, (A_before - A_after)/lrate for a
  single model with rescaling off, so it needs no implementation
  internals. Verified to fail when A is perturbed by 0.1 percent inside
  the dAk computation alone.

Refs #212, #219
@neuromechanist
neuromechanist merged commit 2f23eb9 into main Aug 10, 2026
7 checks passed
@neuromechanist
neuromechanist deleted the 212-numpy-nd-formula branch August 10, 2026 05:04
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.

numpy_impl log-likelihood is un-normalized, so min_dll can never fire

1 participant