Skip to content

Phase 5: guard raw backend accessors - #329

Merged
neuromechanist merged 12 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-306-phase5-backend-guards
Sep 23, 2026
Merged

neuromechanist merged 12 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-306-phase5-backend-guards

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

AMICATorchNG, AMICAMLXNG and the legacy NumPy AMICA backend's fitted-output accessors used to return numeric-looking output from a fit the backend itself classified as degenerate, with no warning at all; only get_rho carried a finiteness guard, and only the scikit-learn-style AMICA wrapper's _check_usable protected callers going through it.
Each backend now gets its own _check_usable(action) helper, mirroring the two-layer pattern state_dict()/write_amica_output() already used (a stop_reason/converged gate, then a defense-in-depth isfinite sweep over the fitted parameters), applied to transform, get_mixing_matrix, get_unmixing_matrix, get_sensor_mixing_matrix, get_rho, variance_order, model_loglik, model_probability, mir and pmi on torch/MLX, and to transform, get_weights and get_sensor_mixing_matrix on NumPy (using its own converged/stop_reason bookkeeping, per .rules/backend_parity.md).
The data-taking accessors among those now also validate that X/data is a 2D array with the model's fitted input channel count (n_channels_in/data_dim_in), raising the same named ValueError fit() already raises for the identical mistake instead of a raw matmul/broadcast error; model_probability also now tells a NaN log-likelihood (numerical corruption) apart from every model underflowing to -inf (an extreme outlier), where it previously reported both the same way.
AMICATorchNG.from_state_dict and AMICAMLXNG.from_state_dict (and MLX's .npz load(), which delegates to it) now wrap the constructor's bare TypeError on a malformed config (missing or unexpected key) into a ValueError naming the payload as the culprit, chaining the original exception, matching every neighboring validation step in that method.
One shared cross-backend test module (pamica/tests/test_backend_guards.py) covers all three backends on real bundled sample EEG, parametrized with pytest.importorskip for MLX.

Part of epic #324; resolves #306 (closes when the epic merges to dev).

Behavior changes

  • Raw backend accessors (transform and friends) now raise RuntimeError on a degenerate fit or a non-finite parameter, instead of silently returning NaN-tainted output.
  • Those same accessors' data-taking members now raise ValueError on a 1D or wrong-channel-count input, instead of a raw backend-specific matmul/broadcast error.
  • model_probability distinguishes a NaN log-likelihood from an all--inf one in its error message.
  • from_state_dict (torch, MLX) raises ValueError naming the payload on a malformed config, chaining the original TypeError, instead of letting the TypeError propagate bare.
  • docs/guides/amica-differences.md row 5 and docs/changelog.md updated accordingly.

Test plan

  • uv run ruff check --fix . && uv run ruff format . -- clean.
  • uv run ty check -- clean.
  • uv run pytest pamica/tests/test_backend_guards.py -q --no-cov -- 19 passed.
  • Same 19 tests against the pre-change backends (stashed the source diffs, kept the test file): 16 of 19 fail, 3 pass (the three healthy-fit checks, which exercise unaffected behavior).
  • uv run pytest pamica/tests -q --no-cov -n 4 -m "not slow" -- 1240 passed, 14 skipped, 1 xfailed, 0 failed (the CI subset, including the 19 new tests).

transform/get_*matrix/get_rho/variance_order/model_loglik/
model_probability/mir/pmi now refuse a degenerate fit or a
non-finite parameter, and validate X shape like fit() does.
from_state_dict wraps a malformed config's TypeError as ValueError.
Same guard as AMICATorchNG (backend_parity.md): transform/
get_*matrix/get_rho/variance_order/model_loglik/model_probability/
mir/pmi refuse a degenerate fit or a non-finite parameter, and
validate X shape like fit() does. from_state_dict (and load(), which
delegates to it) wraps a malformed config's TypeError as ValueError.
Same guard, ported to the legacy backend's own converged/
stop_reason bookkeeping: transform/get_weights/
get_sensor_mixing_matrix refuse a degenerate fit or a non-finite
parameter, and transform validates data shape like fit() does.
Parametrized over torch, MLX (importorskip) and NumPy: every
guarded accessor raises on a degenerate stop_reason and on a
non-finite parameter, and still works on a healthy fit; every
data-taking accessor rejects a 1D or wrong-channel-count array,
including after a pcakeep reduction; from_state_dict raises
ValueError (chaining TypeError) on a malformed config.
amica-differences.md row 5: the raw torch/MLX/NumPy backends now
refuse degenerate models themselves, not just the AMICA wrapper.
changelog.md: note the behavior change under Unreleased.
Factors the NaN-vs--inf diagnosis and column-wise softmax
normalization out of AMICATorchNG/AMICAMLXNG.model_probability so
neither backend duplicates it; lives under pamica/metrics/,
matching the existing mir/pairwise_mi split (backend computes the
array, a shared pure function does the rest).
Reviewer follow-up on #306 (PR #329):
- get_pdftype/shared_components now go through _check_usable too.
- New _nonfinite_params() batches the isfinite sweep into one
  stacked reduction (one device sync instead of one per parameter,
  skipping None entries), used by _check_usable, state_dict and
  write_amica_output instead of each repeating the sweep.
- model_probability no longer runs the guard twice (its own
  _check_usable plus model_loglik's): the core Lht computation
  moved to _model_loglik_unchecked, called by both public methods
  after their own single guard + shape check.
- model_probability's NaN-vs--inf diagnosis now delegates to the
  shared pamica.metrics.model_probability_from_loglik.
- mir()'s Raises docstring now covers the degenerate-fit
  RuntimeError and the bad-shape ValueError.
Same follow-up as the torch commit, ported to MLX:
- get_pdftype/shared_components now go through _check_usable too.
- New _nonfinite_params() batches the isfinite sweep into one
  stacked reduction -- one MLX graph evaluation instead of one per
  parameter (measured ~2.2ms -> ~0.4ms for the sweep, transform()
  on 512 samples ~2.5ms -> ~0.6ms), skipping None entries, used by
  _check_usable, state_dict and write_amica_output.
- model_probability no longer runs the guard twice: the core Lht
  computation moved to _model_loglik_unchecked, called by both
  public methods after their own single guard + shape check.
- model_probability delegates its NaN-vs--inf diagnosis to the
  shared pamica.metrics.model_probability_from_loglik.
- mir()'s Raises docstring now covers the degenerate-fit
  RuntimeError and the bad-shape ValueError.
Reviewer follow-up: the action string said 'get the unmixing
matrix', not what the public method itself is called.
get_pdftype/shared_components added to the torch/MLX accessor
table, so the existing degenerate/non-finite/healthy parametrized
tests now cover them. The pcakeep channel-count test now loops
over every data-taking accessor (transform/model_loglik/
model_probability/pmi), not just transform; mir is deliberately
excluded there since it always rejects a pcakeep-reduced model on
other grounds (rank-deficient sphere).
Real Lht from a real 2-model fit's model_loglik() on the bundled
sample: a healthy Lht's columns sum to 1 and match the backend's
own model_probability() (behavior-preserving); a column poisoned
entirely to -inf and a single entry poisoned to NaN raise distinct
messages.
The Unreleased entry for the backend-guard behavior change now
names the two accessors added in the PR #329 review round.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round (pr-review-toolkit: silent-failure-hunter, code-reviewer, pr-test-analyzer)

All findings addressed, 7 additional commits:

Code

  1. get_pdftype()/shared_components() on torch and MLX now go through _check_usable (action strings "get the density family"/"get the shared components", matching the AMICA wrapper's own wording) and are covered by the parametrized degenerate/non-finite/healthy tests.
  2. model_probability() no longer runs the guard twice. The core Lht computation moved to a private _model_loglik_unchecked; model_loglik/model_probability each do their own single guard + shape check (keeping their own action wording), then call the unchecked helper.
  3. The isfinite sweep (_check_usable, state_dict, write_amica_output) is now a single batched reduction with one device sync, not one sync per parameter. Measured before/after:
    • MLX _nonfinite_params: 2.40 ms -> 0.38 ms (6.3x)
    • MLX transform(512 samples): 2.50 ms -> 0.62 ms (4.0x) -- the sweep really was ~96% of that call's cost
    • torch-CPU _nonfinite_params: 0.028 ms -> 0.028 ms (no measurable difference; torch-CPU bool(tensor) isn't a real device sync, unlike CUDA/MPS, which the new code also protects via the same batched .item()/bool() pattern)
  4. Both sweeps now skip None entries (matching NumPy's existing _nonfinite_params), so a partially initialized instance can't raise a raw TypeError from the guard. Verified directly against a fresh unfitted instance of each backend.
  5. The sweep is factored into one private _nonfinite_params() per backend (same name as NumPy's existing helper), used by _check_usable, state_dict and write_amica_output; each caller keeps its own existing message text.

Tests
6. model_probability's NaN-vs--inf diagnosis and column-wise softmax normalization were factored into one shared pure function, pamica.metrics.posterior.model_probability_from_loglik(Lht, *, caller). It lives under pamica/metrics/ next to mir/pairwise_mi, which already split the same way (backend computes the array in its own array library, a shared pure NumPy function does the rest); caller keeps the per-backend message prefix (e.g. "AMICATorchNG.model_probability()") so the two backends' messages don't collide into one generic string. New pamica/tests/test_metrics_posterior.py (4 tests) exercises it directly on a real Lht from a real 2-model fit's model_loglik(): a healthy Lht gives columns summing to 1 and matches the backend's own model_probability() bit-for-bit (behavior-preserving); a column poisoned entirely to -inf and a separate single entry poisoned to NaN raise the two distinct messages.
7. The pcakeep=20-on-32-channels channel-count test now loops over every data-taking accessor (transform, model_loglik, model_probability, pmi), not just transform. mir is deliberately excluded: it always raises ValueError for a pcakeep-reduced model regardless of channel count (its separate rank-deficient-sphere guard), so a "good" 32-channel input would never return a value to assert on there.

Docs
8. mir()'s Raises docstring on both backends now covers the degenerate-fit RuntimeError and the bad-shape ValueError, matching pmi()/model_loglik().
9. NumPy get_weights()'s guard action string is now "get the weights (unmixing matrix)" instead of "get the unmixing matrix".
10. docs/changelog.md's Unreleased entry now names get_pdftype/shared_components in the guarded-accessor list. docs/guides/amica-differences.md row 5 already described the guard generically (no per-accessor enumeration), so no change was needed there.

Gates

  • uv run ruff check --fix . && uv run ruff format . -- clean.
  • uv run ty check -- clean (one narrowing fix needed: _model_loglik_unchecked now asserts self.sphere/self.mean are not None, since the type checker can't see across the new method boundary that both public callers already checked this).
  • uv run pytest pamica/tests/test_backend_guards.py pamica/tests/torch_tests/test_ng_model_posterior.py pamica/tests/mlx_tests pamica/tests/test_metrics_posterior.py -q --no-cov -n 4 -- 297 passed.
  • uv run pytest pamica/tests -q --no-cov -n 4 -m "not slow" -- 1244 passed, 14 skipped, 1 xfailed, 0 failed.

@neuromechanist
neuromechanist merged commit 2871656 into feature/issue-324-epic-mlx-first-class Sep 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-306-phase5-backend-guards branch September 23, 2026 00:48
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