Skip to content

Phase 4: Newton + adaptive PDF + outlier rejection - #22

Merged
neuromechanist merged 4 commits into
feature/issue-9-epic-torch-parityfrom
feature/issue-13-phase4-newton-pdf-reject
Jul 3, 2026
Merged

neuromechanist merged 4 commits into
feature/issue-9-epic-torch-parityfrom
feature/issue-13-phase4-newton-pdf-reject

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Ports the Fortran Newton preconditioner, adaptive-PDF (rho) confirmation, and outlier rejection
into the natural-gradient backend AMICATorchNG, and adds Fortran-style learning-rate control.
All three features are implemented and unit-parity-verified against the (Fortran-corrected) NumPy
reference to float64 precision.

Important: this does NOT yet close the epic's >0.95 correlation gate. The NG backend converges
to a different fixed point than Fortran (~0.68 correlation, LL -3.47 vs -3.41), and Newton only
accelerates convergence to that same NG fixed point. The root cause is upstream of Newton and is
tracked separately in #21. The end-to-end gate test is therefore kept as xfail with an accurate
reason.

Closes #13. Part of epic #9.

What changed

  • torch_impl/amica_torch_ng.py
    • Newton preconditioner: score-based curvature stats (sigma2/lambda/kappa), vectorized
      per-source-pair 2x2 direction solve, positive-definiteness fallback to natural gradient,
      newtrate-capped ramp. Matches amica17.f90.
    • Outlier rejection: per-sample log-likelihood threshold (mean - rejsig*std), one-directional
      good-sample mask, good-count normalization of gm and reported LL.
    • Learning-rate control: replaces the ad-hoc backtracking with Fortran's convergence logic
      (anneal on LL decrease; ratchet the lrate ceiling and newtrate after maxdecs decreases). This
      fixes a pre-existing divergence where the natural gradient drifted the LL down at lrate=0.05.
    • Extracted a shared _forward E-step helper (used by block updates and the rejection LL).
  • pyAMICA.py: corrected the NumPy reference Newton math to Fortran spec (score fp not the
    density derivative; dsigma2 accumulated once per source; sbeta^2 on kappa; baralpha-weighted
    mu^2 term in lambda; positive-definiteness fallback), so it is a valid Newton parity target.
  • amica.py: do_newton now plumbs through backend="ng" instead of raising.

Test plan

  • test_newton_stats_match_numpy_reference - finalized sigma2/lambda/kappa vs NumPy, <1e-8.
  • test_newton_mstep_matches_numpy_reference - one full Newton M-step A-update vs NumPy, <1e-8.
  • test_newton_direction_matches_formula - direction formula + posdef guard on controlled input.
  • test_rejection_shrinks_good_sample_set - real-data rejection drops samples, stays finite.
  • test_end_to_end_correlation_vs_fortran - xfail (fixed-point gap, NG backend converges to a different fixed point than Fortran (~0.68 corr, blocks >0.95 gate) #21).
  • Full fast suite green: 46 passed, 4 xfailed, 0 failures. Real sample EEG + Fortran binary only.

Newton curvature stats used the density derivative dpdf where Fortran
uses the score fp; dsigma2 was inflated num_mix-fold inside the mixture
loop; kappa lacked the sbeta^2 factor and lambda the baralpha-weighted
mu^2 term. Correct all four to amica17.f90 semantics and add the
positive-definiteness fallback (whole-model natural gradient when a pair
fails sk1*sk2>1), so the reference is a valid Newton parity target.
Port the Fortran Newton preconditioner (per-source-pair 2x2 solve with
positive-definiteness fallback), the score-based curvature statistics
(sigma2/lambda/kappa), and outlier rejection (per-sample LL threshold,
one-directional good-sample mask, good-count normalization) into
AMICATorchNG. Replace the ad-hoc backtracking with Fortran's convergence
control (anneal lrate/rholrate on LL decrease; ratchet the lrate ceiling
and newtrate down after maxdecs consecutive decreases). Wire do_newton
through the public AMICA(backend='ng') interface.

Newton is unit-verified against the reference to ~1e-16 but does not yet
close the >0.95 correlation gate; the NG backend converges to a different
fixed point than Fortran (issue #21).
Newton stat parity (sigma2/lambda/kappa vs NumPy reference), full
Newton M-step A-update parity, the Newton direction formula and its
positive-definiteness guard, and outlier-rejection sample shrinkage on
real data. Update the >0.95 end-to-end gate to xfail with an accurate
reason (fixed-point gap, issue #21) and enable Newton in it so it
exercises the full path.
- Reject using the pre-update per-sample LL (Fortran order), not post-update.
- Guard empty/degenerate good sets: validate reject params at construction,
  raise a clear ValueError instead of a downstream None/TypeError crash.
- Port the dalpha epsilon floor from the NumPy reference (do_reject makes the
  zero-responsibility divide more likely).
- Expose Newton fallback observability: n_newton_fallbacks counter + warning
  (mirrors Fortran's print), stop_reason attribute, lrate-floor break promoted
  to warning; log the NumPy reference fallback too.
- Fix stale/overclaiming docstrings (lrate control, do_newton wiring, tests).
- Add tests: positive-definite Newton M-step composition, rho=1/2 boundary
  stat parity, multi-model finiteness, degenerate-LL rejection error, reject
  param validation, and LL good-count normalization.
@neuromechanist

Copy link
Copy Markdown
Member Author

/review-pr summary (3 agents, Sonnet)

Ran code-review, test-coverage, and silent-failure reviewers on the diff. No findings on the (intentional, tracked) >0.95 gate. Findings addressed in ec84388:

Correctness / parity

  • Rejection now uses the pre-update per-sample log-likelihood (Fortran computes loglik in the E-step before update_params); previously it recomputed from post-update parameters, a spec deviation.
  • Ported the NumPy reference's dalpha epsilon floor to the NG backend (do_reject makes a zero-responsibility divide more likely).

Robustness (no silent failures)

  • Validate rejint/rejsig/maxrej at construction; raise a clear ValueError when a degenerate/NaN LL would empty the good set, instead of the opaque downstream None/TypeError crash the reviewers reproduced.
  • Newton fallback is no longer silent: n_newton_fallbacks counter + logger.warning (mirrors Fortran's print), stop_reason attribute, and the lrate-floor stop promoted to warning.

Docs

  • Fixed stale/overclaiming docstrings: the lrate-control params (this PR implements the convergence decay the old text said was absent), do_newton wiring (only functional for backend="ng"), and two test docstrings that claimed to exercise the positive-definite Newton path (on this data the curvature is not positive definite, so it always falls back — confirmed by the reviewers).

Coverage added

  • Positive-definite Newton M-step composition (forced posdef, independent recomputation of A + lrate*(A@H) + rescale).
  • rho=1.0/2.0 boundary stat parity (the _score special cases).
  • Multi-model finiteness/shape (NumPy parity is intentionally invalid for n_models>1 due to the Jacobian-in-v deviation).
  • Degenerate-LL rejection error, reject param validation, and LL good-count normalization.

Full fast suite: 52 passed, 4 xfailed, 0 failures. Reviewers explicitly noted the diagonal Newton lambda division is unguarded but matches Fortran (Wtmp(i,i)=dA(i,i)/lambda(i), no check), so kept Fortran-faithful; the NaN-LL break + enriched logging make it diagnosable.

The unmet >0.95 gate is a real, deeper NG-vs-Fortran fixed-point discrepancy (issue #21), not a Newton bug; the gate test stays xfail.

@neuromechanist
neuromechanist merged commit 0b9f0a1 into feature/issue-9-epic-torch-parity Jul 3, 2026
@neuromechanist
neuromechanist deleted the feature/issue-13-phase4-newton-pdf-reject branch July 3, 2026 18:26
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