Skip to content

FIX get_config: keep NumPy scalar arguments as Python numbers - #1871

Merged
bruAristimunha merged 4 commits into
braindecode:masterfrom
AxelNoun:fix/bd-t12-1-config-numpy-scalars
Dec 1, 2026
Merged

bruAristimunha merged 4 commits into
braindecode:masterfrom
AxelNoun:fix/bd-t12-1-config-numpy-scalars

Conversation

@AxelNoun

@AxelNoun AxelNoun commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Summary

get_config() leaves out a constructor argument passed as a NumPy scalar, such as n_outputs=y.max() + 1 (an np.int64) or sfreq=np.float32(200.0). np.int64 and np.float32 are not int or float, so the Hub mixin config and build_model_config both drop them: the config holds the default (Hub) or nothing, and from_config builds the default. On master:

TCCNet(n_chans=10, n_outputs=4, kernel_size=np.int64(5)).get_config()["kernel_size"]   # 3
TCCNet.from_pretrained(saved_dir)   # RuntimeError: size mismatch for feature_extractor.0.convolutions.0.conv.weight
SPARCNet(n_chans=3, n_times=1000, n_outputs=np.int64(4)).get_config()["n_outputs"]   # None
TSception(n_chans=3, n_times=1000, n_outputs=4, sfreq=np.float32(200.0)).get_config()["sfreq"]   # None

reset_head(np.int64(3)) stores the NumPy value, and json.dumps(model.get_config()) raises TypeError. Copilot flagged the same loss on #1260, which fixed it inside Guetschel2026 only.

Changes

  • models/util.py: _numpy_scalars_to_python turns NumPy scalars into Python numbers with .item(), also inside plain lists, tuples and dicts. build_model_config applies it before its JSON check (the path without huggingface_hub).
  • models/base.py: the mixin's _is_jsonable and _encode_arg apply it, so the Hub config keeps these values; _update_init_kwargs applies it for reset_head.
  • Two tests in test_base.py and a changelog entry.

Testing

Windows 11, Python 3.12, torch 2.15.0 CPU, pytest -n 2 -q -rfEs. Same commands on master and on this branch, first at 92cb203, then again after merging master at f2b9783. Counts are passed / failed / skipped, master then branch.

  • test_config.py, test_huggingface.py, test_base.py (f2b9783): 846 / 5 / 22 and 849 / 5 / 22. The 3 extra are the new tests; the 5 failures, on both, are the symlink tests of test_huggingface.py (WinError 1314, no symlink privilege).

  • test_integration.py (92cb203): 1153 / 1 / 209 and 1154 / 0 / 209. The master failure is a crashed xdist worker; that test passes alone on both.

  • test_model_contract.py (92cb203): 1359 / 0 / 110 on both.

  • This branch after the merge with f2b9783, -n 3: test_integration.py 1154 / 0 / 209 and test_model_contract.py 1359 / 0 / 110, as before the merge.

  • The other 43 files of test/unit_tests/models/ (92cb203): 5025 / 6 / 159 (47 xfailed) on both. The 6 failures are a Windows UnicodeDecodeError in test_model_rules.py and test_private_blocks.py; with PYTHONUTF8=1, 17 / 0 / 0 on both.

  • The model test files the merge changed, test_models.py, test_foundation_models.py, test_codebrain_compile.py (f2b9783): 1457 / 0 / 28 on both.

  • Hub and serialization files outside models/ (test_hub_integration.py, test_hub_formats.py, test_serialization.py, test_util.py, 92cb203): 111 / 0 / 119 on both.

  • Skip reasons, identical on both: no network, no CUDA, MPS or other accelerator, no CPU bfloat16 LSTM kernel, torch.compile on Windows, export not possible on this platform or too slow for CI, missing optional packages (zarr, peft, pywt, ptwt), models that are not classifiers or have no embedding or activation parameter, fixed-length or tokenizer models, and the contract exemptions the tests print (meta tensors, no ch_mask, graph fitted later, fixed or grouped montages, 5-D inputs).

  • Mutations, each one undoing one changed line or helper branch: the 7 mutants all fail a new test (the hub or init-kwargs case, or the reset_head test).

  • repr(get_config()) of the 104 models of models_mandatory_parameters, built with plain Python arguments, on both config paths: identical to master.

  • pre-commit on the changed files (command in the checklist below): passed.

  • New or changed behavior is covered by relevant regression tests (or N/A with reason)

  • Style checks recorded, e.g. pre-commit run --files <changed files>

  • docs/whats_new.rst updated (at most 3 lines), or the no changelog label, which a maintainer adds, for changes to code that is not released yet (the changelog CI check requires one of the two)

Notes for reviewers

  • Only configs that held NumPy scalars change (last Testing bullets); from_config and the loading code are not modified.
  • A np.float32 is saved at its float32 value (np.float32(0.1) gives 0.10000000149011612), the value the model received.
  • Arrays and tensors are still left out (Copilot on Add DIVER-1 any-variate iEEG foundation model #1170). Converting them with .tolist() round-trips BaRISTA and CSBrain in a local probe, but rebuilds the model with a list where the user passed an array. I would rather do that in a separate PR.
  • FIX: Save numpy scalar and array kwargs as JSON in BaseConcatDataset.save #1863 (merged) does the same conversion for the dataset kwargs saved by BaseConcatDataset.save.

build_model_config and the Hugging Face Hub config left out arguments passed as NumPy scalars (np.int64, np.float32), so from_config and from_pretrained rebuilt the default. Convert NumPy scalars, also inside lists, tuples and dicts, to Python numbers before the JSON checks, and in _update_init_kwargs so reset_head(np.int64(n)) keeps the config serializable.
…ig-numpy-scalars

# Conflicts:
#	docs/whats_new.rst
@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.73684% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 94.40%. Comparing base (f2b9783) to head (6d02f28).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1871   +/-   ##
=======================================
  Coverage   94.39%   94.40%           
=======================================
  Files         192      192           
  Lines       26549    26567   +18     
=======================================
+ Hits        25061    25080   +19     
+ Misses       1488     1487    -1     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…rrays

Review follow-up (P2/P3): exact-type checks left subclasses of
list/tuple/dict (OrderedDict, custom lists) holding raw NumPy
scalars (JSON then fails or silently drops them), never converted
NumPy dict keys, and dropped 0-d arrays. Widen to isinstance,
normalize keys, and unwrap 0-d arrays with .item() like the dataset
save path (braindecode#1863).
@bruAristimunha

Copy link
Copy Markdown
Collaborator

Maintainer note: widened _numpy_scalars_to_python per an ultra-review P2 - container subclasses (OrderedDict, list subclasses), NumPy dict keys, and 0-d arrays now convert too instead of falling through to a JSON failure or silent drop. Probed locally incl. json.dumps round-trip.

@bruAristimunha
bruAristimunha merged commit 00cba6c into braindecode:master Dec 1, 2026
13 checks passed
@AxelNoun
AxelNoun deleted the fix/bd-t12-1-config-numpy-scalars branch December 1, 2026 14:31
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.

2 participants