Repository navigation
Phase 5: guard raw backend accessors - #329
neuromechanist merged 12 commits into
Conversation
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.
Review round (pr-review-toolkit: silent-failure-hunter, code-reviewer, pr-test-analyzer)All findings addressed, 7 additional commits: Code
Tests Docs Gates
|
2871656
into
feature/issue-324-epic-mlx-first-class
Summary
AMICATorchNG,AMICAMLXNGand the legacy NumPyAMICAbackend's fitted-output accessors used to return numeric-looking output from a fit the backend itself classified as degenerate, with no warning at all; onlyget_rhocarried a finiteness guard, and only the scikit-learn-styleAMICAwrapper's_check_usableprotected callers going through it.Each backend now gets its own
_check_usable(action)helper, mirroring the two-layer patternstate_dict()/write_amica_output()already used (astop_reason/convergedgate, then a defense-in-depth isfinite sweep over the fitted parameters), applied totransform,get_mixing_matrix,get_unmixing_matrix,get_sensor_mixing_matrix,get_rho,variance_order,model_loglik,model_probability,mirandpmion torch/MLX, and totransform,get_weightsandget_sensor_mixing_matrixon NumPy (using its ownconverged/stop_reasonbookkeeping, per.rules/backend_parity.md).The data-taking accessors among those now also validate that
X/datais a 2D array with the model's fitted input channel count (n_channels_in/data_dim_in), raising the same namedValueErrorfit()already raises for the identical mistake instead of a raw matmul/broadcast error;model_probabilityalso 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_dictandAMICAMLXNG.from_state_dict(and MLX's.npzload(), which delegates to it) now wrap the constructor's bareTypeErroron a malformed config (missing or unexpected key) into aValueErrornaming 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 withpytest.importorskipfor MLX.Part of epic #324; resolves #306 (closes when the epic merges to dev).
Behavior changes
transformand friends) now raiseRuntimeErroron a degenerate fit or a non-finite parameter, instead of silently returning NaN-tainted output.ValueErroron a 1D or wrong-channel-count input, instead of a raw backend-specific matmul/broadcast error.model_probabilitydistinguishes a NaN log-likelihood from an all--infone in its error message.from_state_dict(torch, MLX) raisesValueErrornaming the payload on a malformed config, chaining the originalTypeError, instead of letting theTypeErrorpropagate bare.docs/guides/amica-differences.mdrow 5 anddocs/changelog.mdupdated 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.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).