Repository navigation
[models] Add TCCNet for sEMG gesture recognition - #1562
Conversation
# Conflicts: # NOTICE.txt # docs/whats_new.rst
8469ac4 to
40e45b9
Compare
|
Hi @bruAristimunha, I am following up on this TCCNet contribution. The pull request is conflict-free, and the Codacy and CircleCI checks have passed. It includes both classification heads, variable-length masking, model and documentation registration, source attribution, and independent numerical output and gradient-parity tests. When convenient, could you please review it and let me know if any changes are needed for integration? I will be happy to address your feedback. Thank you! |
…rward guards Nested filters already give the number of blocks and the convolutions per block, so residual_blocks, tcn_layers, depth, the per-layer kernel_size and _expand_per_block (plus their validation) go; kernel_size is one int as in every published config. Unused stored attributes and the forward shape guards (Conv1d already raises) are removed. Review findings 7 and 15.
The private _CausalConv1d re-implemented braindecode.modules.CausalConv1d. A bias-free CausalConv1d plus a separate bias added only where the convolution is non-zero (the reference CausalConv1D) gives the same output. The average-over-time pooling is functional.masked_mean; a fully padded input now gives NaN, as the reference MeanOverTime does (0 / 0). Review findings 6 and 11.
No released weights pin their layout; braindecode.modules simply has no shared TCN residual block or context-vector attention pooling. Review finding 16.
exp(scores) had no max subtraction and gave inf / inf = NaN once the context vector's L1 norm passed ~88.7 (float32) or ~11.1 (float16); the reference has the same flaw. Subtracting the detached row maximum m >= 0 and scaling the epsilon by exp(-m) keeps the reference's values exp(s) / (sum exp(s) + 1e-7) exactly in real arithmetic, including the epsilon, and fully padded rows still give 0. Review finding 10.
Keras 2.2.4 glorot_normal is a 2-sigma truncated normal rescaled by 1/0.8796, not torch's untruncated xavier_normal_, and its glorot_uniform takes fan_in = fan_out = sqrt(F) for the 1-D context vector, so the bound is sqrt(3/sqrt(F)), not sqrt(3/F). Initial weights only; no checkpoint exists. Review finding 9.
The head is one nn.Linear: record the new n_outputs with _set_n_outputs and rebuild it on the same device/dtype with the Keras initialisation. Without it from_pretrained(..., n_outputs=k) raised NotImplementedError. The shared reset_head tests (test_return_features._RESET_HEAD_CASES and test_model_contract) now pick TCCNet up from the registry. Review finding 4.
…l notes The defaults built the reference function's signature (8 convolutions, 121,525 parameters, dropout 0.5, no masking), which no experiment trained. They are now the paper's best model, Att with a 2500 ms receptive field: filters ((32, 32), (32, 32), (64, 64), (128,)), attention head, dropout 0.05, masking at -10 (88,757 parameters for 10 channels and 53 classes; summary.csv updated). The docstring lists the four paper models by receptive field, states that every model takes whole variable-length gestures pre-padded with -10 and masked, that min-max normalisation is off in the released configs, that the 1 Hz Butterworth runs forward-backward, and adds batch size, size_factor and the class-balanced weights. It also notes that the masked average over time equals the reference only for pre-padding. The registry keeps n_times=300 as a test length only. Review findings 1, 3 and 8.
Braindecode keeps model tests in the shared suites, which already cover shape, gradients, TorchScript, export, config and init. Kept: the NumPy transcription of the reference Keras layers (now two blocks, so the dilation carried across blocks is checked numerically, with and without pre-padding and masking, plus the central-difference input gradient) and the pre-padding-equals-unpadded test. Dropped: the shape/gradient test (shared), the structural dilation test (now numeric), the head-name check and the fully-padded test, which pinned a guard the reference lacks. Review finding 5.
Adds the one-line licence link to the class docstring, the (MIT) suffix to the header, and credits cbaziotis/keras-utilities (MIT), where the reference's MeanOverTime and AttentionWithContext come from, in the header and NOTICE.txt; the NOTICE paragraph is shortened to the style of its neighbours. The AI tool is removed from the Authors header (the PR body keeps the disclosure); the contributor stays. Review findings 12 and 13.
Review finding 14.
Crop of the "Proposed model" panel of Poster_A0_web.pdf in DSIP-UPatras/ICASSP2019_TCN (MIT, cd28909), as docs/_static/model/ tccnet.png, listed under MIT in NOTICE.txt. Review finding 17.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #1562 +/- ##
==========================================
+ Coverage 91.67% 91.70% +0.03%
==========================================
Files 176 177 +1
Lines 23015 23117 +102
==========================================
+ Hits 21098 21199 +101
- Misses 1917 1918 +1 🚀 New features to boost your workflow:
|
|
Hi @arslan-shafique, thanks again for this port. The pinned reference, the NumPy oracle and the list of deviations made the review quick. Instead of asking you for another round, we pushed the review changes to your branch (
Checks at
Before a model port merges, we replicate one paper number ourselves. That stays on our side, and nothing is needed from you. Thanks! |
Model information
Implementation fidelity
DSIP-UPatras/ICASSP2019_TCN, pinned at commitcd28909ccf3696b835446cbec2f15eb60610a2af; MIT license (license). Attribution is included in the module andNOTICE.txt.(batch, n_chans, n_times)convention and are transposed internally to the source's time-major layout.forward.mask_valueexposes the reference pre-padding convention (-10.0) directly and handles fully masked examples without NaNs.classify_as="mot"typo is represented by the supported paper headclassification_head="aot".test_tccnet.pytherefore uses an independent NumPy oracle that directly transcribes the pinned Keras causal-convolution, residual, average-over-time, attention, and dense equations. Both heads match double-precision outputs (rtol=1e-11) and finite-difference input gradients (rtol=2e-5,atol=1e-7). Additional tests cover source-style pre-padding equivalence, zero gradients on padding, global dilation order, and fully masked inputs. This demonstrates implementation agreement, not benchmark reproduction.Checklist
Implementation (
braindecode/models/tccnet.py)EEGModuleMixinbeforenn.Module;license="mit", source attribution, andNOTICE.txtmatch the source licensen_outputs,n_chans,chs_info,n_times,input_window_seconds,sfreq) forwarded tosuper().__init__(...)(batch_size, n_chans, n_times)to(batch_size, n_outputs)self.final_layeris the final child module; the classifier returns logits without softmax/log-softmaxactivationuses annn.Moduleclass default and dropout uses thedrop_probnametest_private_blocks.py; their docstrings explain their source-specific behaviorRegistration and documentation
braindecode/models/__init__.pyregistrymodels_mandatory_parameterswith NinaPro DB1 geometry (10channels,300samples,100 Hz)summary.csv; verified parameter count is121,525docs/api.rstdocs/whats_new.rstValidation and compatibility
reset_head: N/A — no checkpoint is published and TCCNet has no model-specific head-reset implementation; train/eval behavior, dropout, gradients, and dtype compatibility are covered by shared/model testsValidation evidence
Environment: Ubuntu 24.04 under WSL, Python 3.12, PyTorch 2.15 CPU.
pytest test/unit_tests/models/test_tccnet.py -q— 14 passedpytest test/unit_tests/models/test_model_init.py -k TCCNet -q— 2 passed, 170 deselectedpytest test/unit_tests/models/test_model_contract.py -k TCCNet -q— 7 passed, 1 skipped, 717 deselectedpytest test/unit_tests/models/test_integration.py -k TCCNet -q— 11 passed, 2 skipped, 1113 deselectedpytest test/unit_tests/models/test_models.py -k TCCNet -q— 3 passed, 741 deselectedpytest test/unit_tests/models/test_model_categorization.py test/unit_tests/models/test_model_modality.py -k TCCNet -q— 2 passed, 172 deselectedpytest test/unit_tests/models/test_private_blocks.py -q— 1 passedruff format --check braindecode/models/tccnet.py test/unit_tests/models/test_tccnet.py— passedruff check braindecode/models/tccnet.py test/unit_tests/models/test_tccnet.py— passedThe local lean test environment did not include
pytest-timeout, so pytest reported two configuration warnings. They do not affect test execution. The complete repository-widepytest test/suite was not run; focused model and shared contract/integration coverage is reported above.Benchmark reproduction
The original benchmark uses the login-required NinaPro DB1 dataset and does not publish trained weights. A full 27-subject, four-configuration training reproduction was therefore not run for this implementation PR.
The model docstring records the source protocol: 10-channel sEMG at 100 Hz; rectification; first-order Butterworth low-pass filtering at 1 Hz; per-sample min-max normalization excluding padding; repetitions 1, 3, 4, 6, 8, 9, and 10 for training and 2, 5, and 7 for validation; 53 classes; Adam with learning rate 0.01 and epsilon 0.001; 30 epochs; L2 coefficient 0.0005; time/magnitude warping 0.2; and additive noise at 25 dB SNR. Both published 300-sample and variable-length model configurations are included in the documentation.
Because the dataset requires a separate authenticated download and no original checkpoint is available, this PR makes no claim that the paper's benchmark accuracy has been reproduced. The independent source-equation output/gradient tests establish implementation parity only.
AI assistance disclosure
OpenAI Codex assisted with source analysis, implementation, tests, and PR preparation under the contributor's supervision. The contributor reviewed the architecture, source attribution, experiment protocol, deviations, and validation results and can explain the submitted changes.