Skip to content

Weight nd by pre-update model weights - #241

Merged
neuromechanist merged 3 commits into
devfrom
219-nd-gm-ordering
Aug 16, 2026
Merged

neuromechanist merged 3 commits into
devfrom
219-nd-gm-ordering

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #219.

The ordering

Fortran builds dAk inside accum_updates_and_likelihood and only reassigns gm in update_params:

dAk(:,comp_list(i,h)) = dAk(:,comp_list(i,h)) + gm(h)*dA(:,i,h)          ! ~1753
ndtmpsum = sqrt(sum(nd(iter,:),mask=comp_used) / (nw*count(comp_used)))  ! ~1761
gm = dgm_numer / dble(all_blks)                                          ! ~1788

So the reference weights by the previous iteration's model weights. Both backends reassigned gm first; both now snapshot it.

Correction to the issue

#219 describes this as diagnostic-only. That holds for numpy_impl, where dAk feeds nd alone. It does not hold for AMICATorchNG, where the same dAk is the A-update (self.A = self.A - self.lrate * dAk), so the ordering reaches fitted parameters there. Worth stating plainly, since the issue's framing implied this PR could not change results.

Measured effect

Single-model and Newton fits are bit-identical (gm == 1). Multi-model shifts by 1.0e-06 relative in log-likelihood.

That shift is not a semantic change: for a disjoint comp_list each column belongs to exactly one model, so gm[h] cancels against zeta[idx] = gm[h] and the result is algebraically identical either way. What changes is the floating-point association, amplified by the chaotic EM trajectory to ~1e-6 — the same order as the documented block_size trajectory shift, and well inside the ~5e-4 parity tolerance.

The weighting differs semantically only under share_comps, where a column belongs to more than one model and the cancellation no longer applies.

Tests

Two added to test_numpy_grad_norm.py: one pinning the pre-update weighting with a forced shared column, one asserting a shared column keeps the gradient norm finite (zeta accumulates a positive weight per contributing model, so the division cannot go 0/0).

Found on the way

Writing the sharing test surfaced #240: numpy_impl + share_comps leaves half of mu and beta NaN while reporting a successful fit. Pre-existing and independent of this change — the mixture update never reads dAk — so it is filed rather than fixed here.

@neuromechanist

Copy link
Copy Markdown
Member Author

Review findings addressed

The test reviewer did the decisive thing I had not: it reverted the change and re-ran. All tests still passed, on both backends. The PR had no regression guard.

Three findings, all fixed:

1. The ordering test was vacuous. It mutated comp_list after fit() had returned, then asserted on model.nd[-1], which was computed during that fit. The mutation was dead code with respect to every assertion, and the docstring described "two M-steps" that did not exist.

2. Nothing would fail if the change were reverted. The remaining assertions (isfinite, > 0, gm sums to 1) hold under either weighting.

3. The PyTorch backend had no test at all, despite being the backend where dAk is the A-update rather than a diagnostic — a direct gap against .rules/backend_parity.md.

The discriminator

Hold one accumulator dict fixed across two M-steps, so the post-update gm (dgm / n_samples) is identical by construction, and vary only the gm present when dAk is built. Weighting by the post-update value makes the two runs identical; weighting by the pre-update value does not.

nd_a = step_with_pre_update_gm(model, acc, n, [0.9, 0.1])
nd_b = step_with_pre_update_gm(model, acc, n, [0.1, 0.9])
assert nd_a != nd_b

Each has a complement asserting the same pre-update gm is deterministic, so they cannot pass on unrelated sensitivity, plus a single-model case pinning why issue #24 parity is untouched (gm == 1).

Verified by reverting

  • NumPy reverted -> test_nd_uses_pre_update_model_weights fails
  • PyTorch reverted -> test_ndtmpsum_uses_pre_update_model_weights and test_a_update_uses_pre_update_model_weights fail

10 tests pass with the fix in place. New file pamica/tests/torch_tests/test_ng_gm_ordering.py covers the torch half, including that the fitted A itself moves with the ordering — the consequence unique to that backend.

@neuromechanist

Copy link
Copy Markdown
Member Author

Second reviewer's findings addressed

The general code reviewer independently reproduced the revert-and-rerun result, and added three more.

Comment accuracy — my regression. The pre-PR numpy comment said "Diagnostic only, it does not affect the fitted parameters"; I dropped that clause, leaving a comment that reads identically to the torch one for a change with materially different consequences. Restored, and now states explicitly that numpy's A-update is a separate loop that never reads dAk, while torch applies the same dAk to A.

Torch comment undersold its own scope. It said "the ndtmpsum block below", but that block is also the A-update. Reworded to say dAk both drives the A-update and reports ndtmpsum. The reviewer noted this was inconsistent with the file's own min_nd docstring, which already describes dAk correctly as the update direction.

Latent fragility. gm_prev = self.gm aliased rather than copied, unlike numpy's .copy(). Safe today — gm is only ever rebound, never written in place — but an in-place write elsewhere would silently corrupt the snapshot. Now .clone(), with the reason recorded.

The reviewer also asked that the numpy/torch asymmetry be called out explicitly; it already is, under "Correction to the issue" in the PR description.

Filed rather than fixed here

#242 — the reviewer found that numpy_impl's A-update is a per-model loop with no gm weighting, no zeta division and no post-merge A-freeze, so a genuinely shared column is updated twice in sequence, the second time against an already-updated A. Fortran applies one weighted average; the PyTorch backend matches Fortran. That is a different operation, not a rounding difference, and it means the two backends do not implement the same algorithm under share_comps.

Pre-existing and untouched by this PR (the loop is not in the diff), and out of scope here. With #240 it makes numpy_impl + share_comps a coherent piece of work rather than two loose ends.

@neuromechanist
neuromechanist merged commit c80fb33 into dev Aug 16, 2026
7 checks passed
@neuromechanist
neuromechanist deleted the 219-nd-gm-ordering branch August 16, 2026 02:32
neuromechanist added a commit that referenced this pull request Aug 16, 2026
Every job was ubuntu-latest, so pamica/tests/mlx_tests/ had never run in CI
and the Accelerate BLAS path was untested. The second gap is not theoretical:
a test_ng_convergence.py assertion stayed green on Linux through #241 and
failed immediately on macOS, because the ~1e-6 trajectory shift moved the
stopping iteration off the multiple of mir_step the assertion assumed.

macos-26 is the current arm64 image and standard runners are free for public
repositories. The job installs the mlx extra and asserts the import rather
than letting mlx_tests self-skip into a green no-op.

Refs #246.

Co-Authored-By: Claude Opus 5 <[email protected]>
neuromechanist added a commit that referenced this pull request Aug 16, 2026
* Add a macOS Apple Silicon CI job

Every job was ubuntu-latest, so pamica/tests/mlx_tests/ had never run in CI
and the Accelerate BLAS path was untested. The second gap is not theoretical:
a test_ng_convergence.py assertion stayed green on Linux through #241 and
failed immediately on macOS, because the ~1e-6 trajectory shift moved the
stopping iteration off the multiple of mir_step the assertion assumed.

macos-26 is the current arm64 image and standard runners are free for public
repositories. The job installs the mlx extra and asserts the import rather
than letting mlx_tests self-skip into a green no-op.

Refs #246.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Assert the Apple GPU; correct the macOS job comments

Review findings.

Assert mx.default_device().type == gpu, not just that mlx imports. The
mlx_tests module is gated on both (test_mlx_backend.py:28-33), so a runner
that imported mlx and fell back to CPU would skip all 11 tests and still
report success. The hosted macos-26 image does expose the GPU -- all 11
passed on the first run -- but nothing in the job would have caught it if a
future image stopped.

Add PYTORCH_ENABLE_MPS_FALLBACK=1. The two Linux jobs already set it
defensively; this is the only job whose hardware can actually auto-select
MPS.

Add EXTRA_LDFLAGS=-static-libquadmath so the build really is the
release-binaries.yml macos-arm64 recipe the comment claims.

Correct the -m 'not slow' rationale: it was attributed to Rosetta and the
x86_64 amica15mac, but most slow tests never invoke a binary, and the two
that do resolve through PAMICA_NATIVE_BINARY (native/resolver.py:112), which
this job sets to the arm64 binary it just built. They are excluded for
wall-clock, and enabling them is a real follow-up rather than blocked work.

Refs #246.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
neuromechanist added a commit that referenced this pull request Aug 25, 2026
* Complete 0.3.3 changelog for release

Rename Unreleased to 0.3.3 with a release summary and add the missing
user-facing entries: best-of-N restarts (#198/#299), MNE bad_* annotation
rejection (#251/#252), the numpy comp_used staleness fix (#240/#243), and
the nd pre-update gm weighting (#219/#241). Docs only, not tested beyond
proofread.

* Correct stale counts and citations in changelog

The 0.3.3 param-reader entry still said 36 unsupported keywords and
listed the do_opt_block search among them; #232 moved those four keys
to identity mappings, leaving 32 (fortran_params.py's own arithmetic:
57 + 32 = 89). Also aligned two Fortran citations with the literal
source: the loglik/modloglik allocation spans 2617-2620 and the
reject_data zeroing block 2231-2234, matching the ranges now used
across the codebase. Docs only.
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