Skip to content

[models] Add TCCNet for sEMG gesture recognition - #1562

Merged
bruAristimunha merged 15 commits into
braindecode:masterfrom
arslan-shafique:add-tccnet
Nov 15, 2026
Merged

bruAristimunha merged 15 commits into
braindecode:masterfrom
arslan-shafique:add-tccnet

Conversation

@arslan-shafique

Copy link
Copy Markdown
Contributor

Model information

Implementation fidelity

  • Reference implementation: DSIP-UPatras/ICASSP2019_TCN, pinned at commit cd28909ccf3696b835446cbec2f15eb60610a2af; MIT license (license). Attribution is included in the module and NOTICE.txt.
  • Deviations:
    • Inputs use Braindecode's (batch, n_chans, n_times) convention and are transposed internally to the source's time-major layout.
    • The source's final softmax is omitted because Braindecode models return logits.
    • Source L2 kernel regularization is documented for configuration as optimizer weight decay rather than embedded in forward.
    • mask_value exposes the reference pre-padding convention (-10.0) directly and handles fully masked examples without NaNs.
    • The source constructor's invalid classify_as="mot" typo is represented by the supported paper head classification_head="aot".
    • Validation messages are TorchScript-compatible; names follow Braindecode/PyTorch conventions.
  • Checkpoint/parity evidence: The source repository does not publish a checkpoint. test_tccnet.py therefore 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)

  • Class inherits from EEGModuleMixin before nn.Module; license="mit", source attribution, and NOTICE.txt match the source license
  • Signal parameters (n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq) forwarded to super().__init__(...)
  • Input/output shapes tested: (batch_size, n_chans, n_times) to (batch_size, n_outputs)
  • self.final_layer is the final child module; the classifier returns logits without softmax/log-softmax
  • activation uses an nn.Module class default and dropout uses the drop_prob name
  • Model docstring describes the architecture, parameters, paper, preprocessing, experiment configurations, and deviations
  • Runtime dependency changes: none
  • The small private residual/attention blocks are source-specific and listed in test_private_blocks.py; their docstrings explain their source-specific behavior

Registration and documentation

  • Exported through the lazy braindecode/models/__init__.py registry
  • Added to models_mandatory_parameters with NinaPro DB1 geometry (10 channels, 300 samples, 100 Hz)
  • Added to summary.csv; verified parameter count is 121,525
  • Added to docs/api.rst
  • Architecture figure: N/A — the source provides no standalone architecture asset suitable for reuse; the block layout and both heads are documented in the model docstring
  • Added to docs/whats_new.rst

Validation and compatibility

  • Model-specific parity/regression tests and relevant shared model suites were run; results are below
  • Ruff formatting and lint checks pass for the new model and test files
  • Shared components changed: none
  • Serialization/config contract and TorchScript compile/save/load pass in the shared suites
  • 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 tests

Validation evidence

Environment: Ubuntu 24.04 under WSL, Python 3.12, PyTorch 2.15 CPU.

  • pytest test/unit_tests/models/test_tccnet.py -q — 14 passed
  • pytest test/unit_tests/models/test_model_init.py -k TCCNet -q — 2 passed, 170 deselected
  • pytest test/unit_tests/models/test_model_contract.py -k TCCNet -q — 7 passed, 1 skipped, 717 deselected
  • pytest test/unit_tests/models/test_integration.py -k TCCNet -q — 11 passed, 2 skipped, 1113 deselected
  • pytest test/unit_tests/models/test_models.py -k TCCNet -q — 3 passed, 741 deselected
  • pytest test/unit_tests/models/test_model_categorization.py test/unit_tests/models/test_model_modality.py -k TCCNet -q — 2 passed, 172 deselected
  • pytest test/unit_tests/models/test_private_blocks.py -q — 1 passed
  • ruff format --check braindecode/models/tccnet.py test/unit_tests/models/test_tccnet.py — passed
  • ruff check braindecode/models/tccnet.py test/unit_tests/models/test_tccnet.py — passed

The local lean test environment did not include pytest-timeout, so pytest reported two configuration warnings. They do not affect test execution. The complete repository-wide pytest test/ suite was not run; focused model and shared contract/integration coverage is reported above.

Benchmark reproduction

  • Benchmark limitation is explained below
  • A paper-value comparison is unavailable for this PR and the reason is explained
  • Dataset, splits, preprocessing, evaluation protocol, optimizer, training budget, and deviations are documented
  • The absence of a reproduced paper score is explicitly separated from implementation parity

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.

Copilot AI balanced review requested due to automatic review settings November 10, 2026 06:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

# Conflicts:
#	NOTICE.txt
#	docs/whats_new.rst
Copilot AI balanced review requested due to automatic review settings November 10, 2026 06:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@arslan-shafique

Copy link
Copy Markdown
Contributor Author

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.
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.
Copilot AI balanced review requested due to automatic review settings November 15, 2026 00:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.01961% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.70%. Comparing base (1e3f425) to head (71207b3).
⚠️ Report is 1 commits behind head on master.

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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bruAristimunha

Copy link
Copy Markdown
Collaborator

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 (40e45b9..71d68a3, after merging current master), one commit per change:

  • Fewer knobs: nested filters now fixes the blocks and the convolutions per block, so residual_blocks, tcn_layers, depth, the per-layer kernel_size, _expand_per_block and the forward shape guards (which Conv1d already covers) are gone.
  • Shared code: the convolution is a bias-free braindecode.modules.CausalConv1d plus the reference's bias-only-where-non-zero step (custom_layers.py#L202-L223), and the average over time is functional.masked_mean.
  • Attention: the attention subtracts the row maximum before exp and rescales the epsilon, so the values stay the reference's exp(s) / (sum exp(s) + 1e-7) (custom_layers.py#L127-L136) but no longer overflow to NaN.
  • Initialisation: now matches Keras 2.2.4: a truncated Glorot normal, and sqrt(3/sqrt(F)) for the 1-D context vector.
  • reset_head: added, so from_pretrained(..., n_outputs=k) works. The shared reset_head tests pick it up.
  • Defaults: now the paper's best model, Att with a 2500 ms receptive field (TCCNet_att_2500.json), with 88,757 parameters for 10 channels and 53 classes. summary.csv is updated, and the other three paper models are listed as kwargs in the docstring.
  • Protocol notes: 300/2500 are receptive fields in ms (run.sh#L4). Every model takes whole gestures, pre-padded with -10 and masked (generator.py#L103-L106). Min-max normalisation is off (utils.py#L151). The filter runs forward-backward. The notes add the batch size, size_factor, the class weights, and the pre-padding-only equivalence of the masked average.
  • Tests: the oracle test (now two blocks, with and without masking) and the pre-padding test moved into test_models.py; test_tccnet.py is gone.
  • Licence and credit: a licence link in the docstring, and a credit to cbaziotis/keras-utilities (MIT) for MeanOverTime/AttentionWithContext in the header and NOTICE.txt (custom_layers.py#L1-L3). Only human authors stay in the file headers; your PR description keeps the AI disclosure.
  • Docs: :gh: 1562 in the changelog, api.rst order, the honest reason the two private blocks stay private, and the poster's "Proposed model" panel as the model-card figure.

Checks at 71d68a3:

  • The forward matches a NumPy transcription of your Keras layers to ≤ 4.4e-16 (float64) for the four paper models with pre-padding.
  • The TCCNet tests and the shared model tests pass.
  • CI is green.

Before a model port merges, we replicate one paper number ourselves. That stays on our side, and nothing is needed from you. Thanks!

Copilot AI balanced review requested due to automatic review settings November 15, 2026 23:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@bruAristimunha
bruAristimunha merged commit c95a08c into braindecode:master Nov 15, 2026
9 checks passed
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.

3 participants