Skip to content

Phase 14: reject unknown NumPy options - #347

Merged
neuromechanist merged 6 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-346-phase14-numpy-kwargs
Sep 23, 2026
Merged

neuromechanist merged 6 commits into
feature/issue-324-epic-mlx-first-classfrom
feature/issue-346-phase14-numpy-kwargs

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Summary

pamica/numpy_impl/core.py: AMICA_NumPy(**kwargs) forwarded every keyword into a params dict read with params.get(...), so a typo (max_iters=50) or an option the legacy backend does not implement (keep_best=True) constructed silently and had no effect, unlike the PyTorch/MLX constructors (explicit keyword parameters, TypeError on an unknown name) and the params-file reader (issue #304), which already warned by name about a setting it could not apply.
__init__ now validates **kwargs before any other processing (_reject_unknown_kwargs).
An unrecognized name raises TypeError, with a difflib-based "did you mean" suggestion when a close match exists among the names the constructor accepts.
A name implemented on the PyTorch backend (AMICATorchNG) but not this one (keep_best, device, dtype, the kurtosis-switch schedule kurt_start/num_kurt/kurt_int) raises TypeError naming it and pointing to AMICA(backend='torch').
The accepted-keyword set (_ACCEPTED_KWARGS) is derived from _CONSUMED_KEYS/_CANONICAL_TO_NUMPY_KEY, the same source the params-file routing uses, plus the constructor's own explicit parameter names, so the two surfaces cannot drift apart; the unsupported-option set (_torch_only_options()) is derived from AMICATorchNG's own signature the same way.
The three settings this backend spells differently from AMICATorchNG (min_nd/maxdecs/share_iter, the canonical spelling a params file already resolves either way) are now also accepted as keyword arguments directly and translated to this backend's own attribute name; passing both spellings of the same setting at once raises TypeError naming both, mirroring fortran_params._apply_json_aliases's identical guard for a params file.

pamica/tests/test_numpy_kwargs.py (new): real AMICA_NumPy(...) constructions only, no mocks and no .fit() needed to exercise __init__'s validation (except the data-location tests below, which fit the real bundled sample EEG).
Covers a typo with its suggestion, a typo of a named constructor parameter, every torch-only option raising the specific message (parametrized), the three canonical aliases taking effect and their conflict being rejected, every documented option constructing with a representative value of the right type (alone and all together), and a source scan proving _CONSUMED_KEYS matches every params.get(...)/raw_params.get(...) read site in __init__ exactly, so the accepted set cannot silently drift from what the constructor actually reads.

docs/changelog.md: an "Unreleased" entry recording the behavior change for the legacy NumPy backend.

docs/api/numpy-backend.md: a short paragraph on the new kwargs-rejection behavior, mirroring the page's existing pdftype callout.

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

Behavior change

Legacy NumPy backend only: AMICA_NumPy(**kwargs) (and AMICA_NumPy.from_params_file(..., **kwargs)) now raises TypeError for an unrecognized or unsupported keyword argument instead of silently ignoring it. Every existing call site in the repository (constructors, tests, the CLI, validate_implementations.py's NumPy runner) was audited (AST scan plus manual review of every dynamic **kwargs call site) and already passes only accepted names, so this lands with no other code changes required.

Two secondary effects of the same fix, both additive:

  • min_nd, maxdecs and share_iter (AMICATorchNG's own spelling of min_grad_norm/max_decs/share_int) are now accepted as keyword arguments directly, not just from a params file.
  • Passing both spellings of the same setting at once (e.g. min_nd=... and min_grad_norm=...) now raises TypeError rather than silently letting dict-update ordering decide the winner.

Review follow-up

All addressed in three more commits, each keeping the whole repo ty-clean (the pre-commit hook checks the whole project, so numpy_impl/core.py and its test file had to land together):

  1. files/data_dim/field_dim now actually work as keyword arguments. They already passed the accepted-kwargs check (they are in _CONSUMED_KEYS), but were read only off a parsed params_file, never off kwargs -- so fit() with no data still said "no 'files' configured in params_file" even after a caller had just set one via a kwarg. They are now read off kwargs too, with the same meaning; a conflicting value between params_file and a kwarg raises TypeError (the same value from both is not a conflict, only a different value is). New TestDataLocationKwargs class fits the real bundled sample EEG (32 channels x 30504 frames) through the kwarg path and asserts it is bit-for-bit identical to the same fit configured through params_file. The no-data error messages were reworded to say "via params_file or as a keyword argument" instead of "in params_file".
  2. n_models/n_mix/n_channels no longer get the misleading generic torch-only message. n_models/n_mix are AMICATorchNG's own spelling of this backend's num_models/num_mix -- this backend does support the setting, so "use AMICA(backend='torch')" was actively wrong; they now get a message naming the correct spelling instead (_ALTERNATE_SPELLING). n_channels is not a settable hyperparameter on any backend's public fit path (inferred from the data at fit() time everywhere, including the AMICA wrapper's own fit(**kwargs), which explicitly excludes it) so it gets its own explanation rather than a torch-only pointer that would also be wrong.
  3. Every offending keyword in one call is now named in a single error. A first version of _reject_unknown_kwargs raised on the first category it found, so AMICA_NumPy(n_models=2, totally_bogus=1) named only n_models and silently dropped totally_bogus -- the same silent-drop failure mode issue AMICA_NumPy silently ignores unknown options #346 itself is about, one layer in. All categories (alternate spelling, n_channels, torch-only, unrecognized) are now computed up front and every one present is named in one TypeError. Found the identical bug in pamica/amica.py's own AMICA.fit keyword check for backend='mlx' (fit(dtype=..., blocksize=...) named only dtype) and fixed it the same way, in its own commit; the two pre-existing single-category messages are unchanged.
  4. (Suggestion, applied) The torch-only option set now excludes n_models/n_mix/n_channels (covered by 2 above) and imports AMICATorchNG lazily, inside its own function body (_torch_only_options(), functools.cache), called only on the error path -- numpy_impl/core.py's own source now carries no module-level torch_impl import.
  5. (Suggestion, applied) The source-scan test now fails loudly, naming the offending snippet, if __init__ ever reads a hyperparameter via params[...] bracket access or a non-literal params.get(...) key -- either shape would silently be invisible to the scan.
  6. (Suggestion, applied) difflib/inspect moved to sit with the other stdlib imports (now a clean stdlib-then-third-party-then-local block).
  7. (Suggestion, applied) Added typo-suggestion tests for params_file and use_tqdm, alongside the existing verbose one.

Deviation from the brief worth flagging

Item 3 of the original brief asked for TypeError or ValueError, "whichever the existing pdftype != 0 NotImplementedError precedent suggests." That precedent is itself neither: it raises NotImplementedError (a value of an accepted keyword the backend cannot honor). I used TypeError for every error shape here, matching the closer in-repo precedent instead: pamica/amica.py's own AMICA.fit keyword check, which raises TypeError for a name no backend recognizes at all and ValueError only for its own always-present device/dtype parameters used with the wrong backend selector -- a different situation from ours, where every unrecognized name here is simply a keyword this constructor does not accept, which is what TypeError means in Python's own calling convention.

No new row was added to docs/guides/amica-differences.md: this PR does not introduce a new capability gap between backends (keep_best, the pdftype families, etc. were already absent from the NumPy backend and already recorded there), it only makes the pre-existing gaps raise instead of silently doing nothing.

Test plan

  • New/updated tests: uv run pytest pamica/tests/test_numpy_kwargs.py (155 passed)
  • AMICA wrapper item 4 fix: uv run pytest pamica/tests/test_wrapper_backends.py (45 passed, including the new combined-category test)
  • Params-file/CLI/MNE/harness routes unaffected: uv run pytest pamica/tests/test_numpy_params_file.py pamica/tests/test_numpy_cli.py pamica/tests/mne_tests/ pamica/tests/test_fortran_param_forwarding.py (334 passed, 3 skipped -- MLX not installed in that one check)
  • Wrapper/backend-selection routes (AMICA, AMICAICA) never construct AMICA_NumPy at all (grepped; confirmed by reading pamica/amica.py and pamica/mne_compat/core.py), so they cannot pass a now-rejected key
  • Broad regression sweep: uv run pytest pamica/tests -k "numpy or wrapper or fortran_params or backend_guards or schedule_gates or doscaling_rows or component_rows or restarts or share_comps" (731 passed, 9 skipped)
  • Full non-slow suite, CI-equivalent: CI=1 uv run pytest -m "not slow" -n auto --cov-fail-under=80 (1738 passed, 27 skipped, 1 xfailed, coverage 91.26%)
  • ruff check . / ruff format --check . clean
  • ty check . clean (whole repo, matching the pre-commit hook's own scope)
  • typos clean
  • mkdocs build --strict clean
  • git rev-parse --is-shallow-repository prints false
  • Original CI run (before the review round) finished all 8 jobs green, including both Test matrix jobs

AMICA_NumPy(**kwargs) forwarded every keyword into a params dict read
with params.get(...), so a typo (max_iters=50) or an option the legacy
backend does not implement (keep_best=True) constructed silently and
had no effect.

__init__ now validates **kwargs before any other processing: an
unrecognized name raises TypeError with a difflib-based suggestion,
and a name implemented on the PyTorch backend (AMICATorchNG) but not
this one raises TypeError naming it and pointing to
AMICA(backend='torch'). The accepted-keyword set is derived from
_CONSUMED_KEYS/_CANONICAL_TO_NUMPY_KEY (the same source the
params-file routing uses) plus this constructor's own named
parameters, so the two surfaces cannot drift apart. The canonical
spelling of the three renamed settings (min_nd/maxdecs/share_iter) is
now also accepted as a keyword argument directly, translated the same
way a params file's setting already is; passing both spellings at
once raises TypeError.
Real construction only, no mocks (no .fit() needed to exercise
__init__'s validation): a typo raises TypeError with a suggestion; an
unsupported cross-backend option raises the specific message; the
three canonical-spelling aliases are accepted and their conflict is
rejected; every documented NumPy option constructs, alone and all
together; and a source scan proves _CONSUMED_KEYS matches every
params.get(...)/raw_params.get(...) read site exactly, so the
accepted-kwargs set cannot silently drift from what __init__ actually
reads.
docs/changelog.md: Unreleased entry noting the legacy NumPy backend
behavior change (unknown or unsupported options now raise instead of
being ignored). docs/api/numpy-backend.md: a short paragraph mirroring
the existing pdftype callout.
PR #347 review follow-up, several items together since they touch the
same functions:

- files/data_dim/field_dim now work as constructor keywords, with the
  same meaning as in params_file, instead of passing the accepted-
  kwargs check but staying silently inert (fit() with no data still
  said "no 'files' configured" even after a caller set one via a
  kwarg). Conflicting values between params_file and a kwarg raise;
  the same value from both does not.
- n_models/n_mix (AMICATorchNG's spelling of this backend's own
  num_models/num_mix) get a message naming the correct spelling
  instead of the generic (and here wrong) torch-only message.
- n_channels gets its own message: it is inferred from the data
  passed to fit() on every backend, not a constructor keyword on any
  of them (the AMICA wrapper's own fit(**kwargs) excludes it too).
- Every offending keyword in one call is named in a single error,
  however many different categories are mixed together. A first
  version raised on the first category found, so
  AMICA_NumPy(n_models=2, totally_bogus=1) named only n_models and
  dropped totally_bogus.
- _torch_only_options() imports AMICATorchNG lazily, inside its own
  body, called only on the error path, so numpy_impl carries no
  module-level dependency on torch_impl.
- Groups difflib/inspect with the other stdlib imports.
- Hardens the source-scan test: fails loudly on a params[...] bracket
  read or a non-literal params.get(...) key, either of which would be
  invisible to the scan.
- Adds typo-suggestion tests for params_file/use_tqdm alongside verbose.
PR #347 review item 4: the same single-category drop
AMICA_NumPy._reject_unknown_kwargs had (issue #346) existed here too --
backend='mlx' with fit(dtype=..., blocksize=...) named only 'dtype'
(ValueError) and silently dropped 'blocksize' from the message, since
the torch-only check raised before the unknown-keyword check ever ran.

Both categories are computed before either is raised; a combination
now names both in one TypeError. The two single-category messages are
unchanged (still ValueError for torch-only alone, TypeError for
unknown alone), so existing callers/tests keep working.
docs/changelog.md: a Review follow-up sub-bullet under the Phase 14
entry. docs/api/numpy-backend.md: mentions files/data_dim/field_dim as
keyword arguments and the n_models/n_mix/n_channels-specific
messages.
@neuromechanist
neuromechanist merged commit 724c391 into feature/issue-324-epic-mlx-first-class Sep 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-346-phase14-numpy-kwargs branch September 23, 2026 12:39
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