Skip to content

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

Closed

Description

@neuromechanist

Found while implementing #207, which assumed numpy_impl was the Fortran-faithful reference for the convergence criteria. It is not, for this one quantity.

The bug

Fortran normalizes the per-iteration log-likelihood before storing it:

! amica15.f90:1752
LL(iter) = LLtmp2 / dble(numgoodsum*nw)

numpy_impl does not:

# numpy_impl/core.py:911
updates["ll"] = np.sum(ll_samples)
# numpy_impl/core.py:1273
self.ll.append(updates["ll"])

There is no division by num_good_samples * data_dim anywhere on that path. Observed on a live run of the bundled sample: LL = -3317862.78 where Fortran reports LL ~= -3.3 for the same configuration, a factor of ~1e6 (30504 samples x 32 channels).

Consequence

self.min_dll defaults to 1e-9 and is compared against self.ll[-1] - self.ll[-2] (core.py:1557-1558). Against an un-normalized likelihood those deltas are ~1e6 times larger than the threshold assumes, so the use_min_dll stop is effectively dead code in numpy_impl: it cannot fire from genuine convergence. The maxincs counter around it is correct but unreachable.

Any direct comparison of AMICA_NumPy's reported LL against Fortran's, or against AMICATorchNG's (which stores the normalized value and is correct), is also comparing different quantities.

Not affected

AMICATorchNG normalizes correctly and does not inherit this. The parity numbers in the JOSS paper are from the PyTorch backend and are on the normalized scale, so they are unaffected.

Fix

  • Normalize self.ll by num_good_samples * data_dim at the point of accumulation, matching amica15.f90:1752.
  • Confirm min_dll/maxincs then fires on real data at the Fortran default, rather than being unreachable.
  • Check whether anything downstream (CLI output, saved history, validate_implementations.py) depended on the un-normalized scale, and whether any recorded NumPy LL numbers in the docs need restating.
  • Add a test asserting the NumPy and PyTorch backends report log-likelihoods on the same scale for the same fit; nothing currently catches this.

Activity

  1. neuromechanist commented on Aug 10, 2026

    @neuromechanist
    MemberAuthor

    The log-likelihood fix works. On the bundled sample, AMICA_NumPy now reports ll[-1] = -3.443 where it previously reported -3317862.78, matching Fortran's scale.

    Worth noting how the bug survived: four separate call sites had been hand-compensating for it. tests/torch_tests/test_ng_backend.py divided by (n_samples * NW) before comparing backends, benchmarks/benchmark_dimsweep.py did the same before reporting, and tests/test_sample_data.py divided by num_samples. Each fixup was locally correct and collectively hid the wrong convention.

    A second instance of the same bug, not fixed here

    self.nd (the weight-gradient norm) is wrong in the same way, and worse. After the fix above it still reads 5399.9 on the bundled sample where Fortran reports about 1e-5.

    Cause, from amica15.f90:1735-1743:

    dAk(:,comp_list(i,h)) = dAk(:,comp_list(i,h)) + gm(h)*dA(:,i,h)
    zeta(comp_list(i,h))  = zeta(comp_list(i,h)) + gm(h)
    ...
    do k = 1,num_comps
       dAk(:,k) = dAk(:,k) / zeta(k)          ! <- this division
    end do
    nd(iter,:) = sum(dAk*dAk,1)
    ndtmpsum   = sqrt(sum(nd(iter,:),mask=comp_used) / (nw*count(comp_used)))

    numpy_impl/core.py:1293-1295 accumulates gm[h] * dWtmp correctly but never divides by zeta, and does not apply the comp_used mask. AMICATorchNG does both (torch_impl/core.py, the dAk = dAk / zeta.clamp_min(...) line), so this is a NumPy-only divergence.

    Consequence: min_nd / use_grad_norm is unreachable in numpy_impl for exactly the same reason min_dll was. Both Fortran convergence criteria are dead in that backend, not one.

    This is not fixed in the current PR, deliberately. A first attempt at the comp_used mask alone was reverted: it did not address the scale (which is the actual problem), and it introduced a regression, asserting comp_used is not None on a path where the M-step runs before that attribute is set, breaking test_newton_mstep_matches_numpy_reference. A correct fix needs the zeta division plus confirmation that dWtmp is the same base quantity as Fortran's dA, and its own tests. A comment at the site now records this rather than leaving it silently wrong.

    Remaining

    • Fix the nd scale: divide by zeta, apply the comp_used mask, verify dWtmp matches Fortran's dA.
    • Confirm min_nd/use_grad_norm becomes reachable afterwards, or explain why not.
    • Check whether AMICATorchNG's own ndtmpsum is on Fortran's scale. It reports ~0.0014 against Fortran's ~1e-5 on comparable runs (noted during min_dll convergence criterion missing from AMICATorchNG (present in numpy_impl and Fortran) #207 and attributed to differing seeds and iteration counts, which is plausible but unproven). Worth settling, since the same threshold is used.
  2. neuromechanist commented on Aug 10, 2026

    @neuromechanist
    MemberAuthor

    Diagnosis complete for the nd half, with matched-config runs against the reference binary. Two corrections to how I characterized this earlier.

    AMICATorchNG is not off-scale

    I previously suggested torch's ndtmpsum might be mis-scaled because it reports ~0.0014 against Fortran's ~1e-5. That was wrong. Torch matches Fortran closely early on, and the late divergence has a different cause.

    Matched config (bundled 32ch sample, input.param verbatim, Fortran run to 2000 iterations with per-iteration printing):

    iter Fortran nd torch nd ratio
    1 5.75e-2 5.79e-2 1.01
    20 1.08e-2 1.14e-2 1.06
    100 2.23e-3 2.32e-3 1.04
    200 6.59e-4 1.16e-3 1.76
    500 1.58e-4 3.80e-3 24.1
    2000 2.51e-5 1.83e-3 73.0

    Agreement to within a few percent through ~100 iterations rules out a scale bug algebraically. The divergence after that is a near-fixed-point noise floor: dAk tends to zero at convergence, so nd measures a near-total cancellation, and small floating-point, threading, and BLAS-order differences get amplified into large relative differences in that residual. Each implementation settles on its own floor. The log-likelihood trajectories agree to 4-5 significant figures throughout (iter 2000: torch -3.398189 vs Fortran -3.398261), so both find the same solution.

    The NumPy bug is real, and larger than "missing the zeta division"

    numpy_impl/core.py:1279-1282 uses the raw dWtmp block sum. It never divides by dgm[h], never adds I, never premultiplies by A, and never masks by comp_used. It does not use directions[h], which is already computed two lines above and drives the actual update. Empirically it sits flat around 5400 for 300 iterations, so it does not track convergence at all.

    Verified fix, mirroring amica15.f90:1731-1743, reusing directions[h] and self.A from before the A-update loop:

    dAk = np.zeros_like(self.A); zeta = np.zeros(self.num_comps)
    for h in range(self.num_models):
        idx = self.comp_list[:, h]
        dAk[:, idx] += self.gm[h] * np.dot(directions[h].T, self.A[:, idx])
        zeta[idx] += self.gm[h]
    nz = zeta > 0; dAk[:, nz] /= zeta[nz]
    mask = self.comp_used if self.comp_used is not None else np.ones(self.num_comps, bool)
    nd_value = np.sqrt(np.sum(dAk[:, mask] ** 2) / (self.data_dim * mask.sum()))

    Against Fortran on the bundled sample: 1.01x at iter 1, 1.06x at 20, 1.04x at 100, then the same noise-floor divergence as torch. The two Python backends settle within ~1.3x of each other despite entirely separate code paths, which is good evidence the floor is a real cross-implementation phenomenon rather than a per-backend artifact.

    Note the comp_used guard: a naive assert comp_used is not None breaks test_newton_mstep_matches_numpy_reference, where the M-step runs before that attribute is set. The fallback above avoids that.

    min_nd = 1e-7 is unreachable on this dataset, for all three

    Fortran's own trajectory oscillates rather than shrinking: 4.7e-5 at iter 1000, 2.8e-5 at 1300, 3.2e-5 at 1700, 2.5e-5 at 2000, and it plateaus at 1.0-1.65e-5 out to iteration 5073 without stopping. The threshold sits about two orders below Fortran's own floor. Both Python backends plateau roughly two orders higher again.

    This is primarily a property of the data: 30504 samples is small relative to the free parameters (1024 in A alone, plus mixture parameters), so the natural-gradient residual has a finite-sample floor. Fortran ships the same default and has the same problem, so this should be documented, not "fixed". Changing the default to make it fire would be tuning a threshold to produce a desired outcome.

    Remaining

    • Apply the NumPy fix above, with a test comparing against Fortran's printed nd in the early iterations where the comparison is meaningful.
    • Document that min_nd is not a useful stop on small datasets, in both backends, citing Fortran's own floor.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions