Repository navigation
Phase 14: reject unknown NumPy options - #347
Merged
neuromechanist merged 6 commits intoSep 23, 2026
Merged
neuromechanist merged 6 commits into
neuromechanist merged 6 commits into
Conversation
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
merged commit Sep 23, 2026
724c391
into
feature/issue-324-epic-mlx-first-class
8 checks passed
This was referenced Sep 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
pamica/numpy_impl/core.py:AMICA_NumPy(**kwargs)forwarded every keyword into a params dict read withparams.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,TypeErroron 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**kwargsbefore any other processing (_reject_unknown_kwargs).An unrecognized name raises
TypeError, with adifflib-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 schedulekurt_start/num_kurt/kurt_int) raisesTypeErrornaming it and pointing toAMICA(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 fromAMICATorchNG'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 raisesTypeErrornaming both, mirroringfortran_params._apply_json_aliases's identical guard for a params file.pamica/tests/test_numpy_kwargs.py(new): realAMICA_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_KEYSmatches everyparams.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 existingpdftypecallout.Part of epic #324; resolves #346 (closes when the epic merges to dev).
Behavior change
Legacy NumPy backend only:
AMICA_NumPy(**kwargs)(andAMICA_NumPy.from_params_file(..., **kwargs)) now raisesTypeErrorfor 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**kwargscall 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,maxdecsandshare_iter(AMICATorchNG's own spelling ofmin_grad_norm/max_decs/share_int) are now accepted as keyword arguments directly, not just from a params file.min_nd=...andmin_grad_norm=...) now raisesTypeErrorrather 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, sonumpy_impl/core.pyand its test file had to land together):files/data_dim/field_dimnow actually work as keyword arguments. They already passed the accepted-kwargs check (they are in_CONSUMED_KEYS), but were read only off a parsedparams_file, never offkwargs-- sofit()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 offkwargstoo, with the same meaning; a conflicting value betweenparams_fileand a kwarg raisesTypeError(the same value from both is not a conflict, only a different value is). NewTestDataLocationKwargsclass 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 throughparams_file. The no-data error messages were reworded to say "viaparams_fileor as a keyword argument" instead of "inparams_file".n_models/n_mix/n_channelsno longer get the misleading generic torch-only message.n_models/n_mixareAMICATorchNG's own spelling of this backend'snum_models/num_mix-- this backend does support the setting, so "useAMICA(backend='torch')" was actively wrong; they now get a message naming the correct spelling instead (_ALTERNATE_SPELLING).n_channelsis not a settable hyperparameter on any backend's public fit path (inferred from the data atfit()time everywhere, including theAMICAwrapper's ownfit(**kwargs), which explicitly excludes it) so it gets its own explanation rather than a torch-only pointer that would also be wrong._reject_unknown_kwargsraised on the first category it found, soAMICA_NumPy(n_models=2, totally_bogus=1)named onlyn_modelsand silently droppedtotally_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 oneTypeError. Found the identical bug inpamica/amica.py's ownAMICA.fitkeyword check forbackend='mlx'(fit(dtype=..., blocksize=...)named onlydtype) and fixed it the same way, in its own commit; the two pre-existing single-category messages are unchanged.n_models/n_mix/n_channels(covered by 2 above) and importsAMICATorchNGlazily, 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-leveltorch_implimport.__init__ever reads a hyperparameter viaparams[...]bracket access or a non-literalparams.get(...)key -- either shape would silently be invisible to the scan.difflib/inspectmoved to sit with the other stdlib imports (now a clean stdlib-then-third-party-then-local block).params_fileanduse_tqdm, alongside the existingverboseone.Deviation from the brief worth flagging
Item 3 of the original brief asked for
TypeErrororValueError, "whichever the existingpdftype != 0NotImplementedErrorprecedent suggests." That precedent is itself neither: it raisesNotImplementedError(a value of an accepted keyword the backend cannot honor). I usedTypeErrorfor every error shape here, matching the closer in-repo precedent instead:pamica/amica.py's ownAMICA.fitkeyword check, which raisesTypeErrorfor a name no backend recognizes at all andValueErroronly for its own always-presentdevice/dtypeparameters 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 whatTypeErrormeans 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, thepdftypefamilies, 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
uv run pytest pamica/tests/test_numpy_kwargs.py(155 passed)AMICAwrapper item 4 fix:uv run pytest pamica/tests/test_wrapper_backends.py(45 passed, including the new combined-category test)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)AMICA,AMICAICA) never constructAMICA_NumPyat all (grepped; confirmed by readingpamica/amica.pyandpamica/mne_compat/core.py), so they cannot pass a now-rejected keyuv 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)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 .cleanty check .clean (whole repo, matching the pre-commit hook's own scope)typoscleanmkdocs build --strictcleangit rev-parse --is-shallow-repositoryprintsfalseTestmatrix jobs