Skip to content

FIX MaxNormLinear constraining input columns instead of output units - #1476

Merged
bruAristimunha merged 6 commits into
masterfrom
fix/maxnorm-linear-axis
Nov 1, 2026
Merged

bruAristimunha merged 6 commits into
masterfrom
fix/maxnorm-linear-axis

Conversation

@adammounir

Copy link
Copy Markdown
Collaborator

MaxNormLinear says it is the equivalent of Keras Dense(..., kernel_constraint=max_norm()). ATCNet and EEGTCNet use it for their classification layer, as max_norm(0.25) on the final Dense of the official code.

A Keras Dense kernel has shape (in_features, out_features), and max_norm() defaults to axis=0. That bounds the incoming weights of each output unit (Keras docs: "In a Dense layer the weight matrix has shape (input_dim, output_dim), set axis to 0 to constrain each weight vector of length (input_dim,)"). A torch nn.Linear weight is (out_features, in_features), so the matching norm is over dim=1, one per row. LinearWithConstraint / MaxNormParametrize already do this. The MaxNorm parametrization behind MaxNormLinear took the norm over dim=0, one per input column. So it bounded the wrong vectors: rows over the bound were kept, and rows within the bound were rescaled.

Repro (master)

import torch
from braindecode.modules import MaxNormLinear
from braindecode.models import ATCNet

lin = MaxNormLinear(3, 2, max_norm_val=2.0)
lin.weight = torch.tensor([[1.5, 1.5, 1.5], [0.1, 0.0, 0.0]])
print(lin.weight.norm(dim=1))        # tensor([2.5981, 0.1000])  -> row over the bound kept

m = ATCNet(n_chans=4, n_outputs=4, n_times=1000)
fl = m.final_layer[0]
with torch.no_grad():
    fl.parametrizations.weight.original.fill_(0.2)
print(fl.weight.norm(dim=1))         # 0.7071 per output unit, with max_norm_const=0.25

With the fix these give [2.0000, 0.1000] and 0.2500. With ATCNet's defaults (32 input features), a row could reach sqrt(32) * 0.25 = 1.41.

Fix

MaxNorm.forward and right_inverse take the norm over dim=1. The clamping formula is unchanged. old_maxnorm in test_modules.py (the reference for test_new_vs_old_maxnorm_are_identical) copied the old axis, so it is updated too.

The stored weights (parametrizations.weight.original) keep their shape, so ATCNet / EEGTCNet checkpoints saved before still load. Their effective classification weights can differ, though, and the whats_new entry says so.

Tests

New test_max_norm_linear_constrains_each_output_unit fails on master and passes with the fix. test_new_vs_old_maxnorm_are_identical (3 cases) passes with the updated reference. Also run individually and passing: test_atcnet_conv_max_norm, test_atcnet_source_optimizer_param_groups (2), test_eegtcnet_tcn_batchnorm, test_atcnet_n_params, test_atcnet_concat_uses_every_window.

Full test files

Run on a Linux CPU node, on this branch rebased on current master and on master itself, with -m "not network and not huggingface": test_modules.py test_models.py test_integration.py test_model_contract.py test_pretrained_compat.py (test/unit_tests/models/).
Branch: 2986 passed, 181 skipped, 7 failed. master: 2985 passed, 181 skipped, 7 failed. The 7 failures are test_model_compiled cases that also fail on master in that environment (torch inductor could not find openssl). No test fails only on this branch.

MaxNorm took the norm of the (out_features, in_features) weight over
dim=0, so it bounded the weights of each input feature rather than the
incoming weights of each output unit, which is what the Keras
Dense(kernel_constraint=max_norm()) it reproduces does (and what
LinearWithConstraint does). This affects the classification layer of
ATCNet and EEGTCNet.
@codecov

codecov Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.32%. Comparing base (aaa31f0) to head (6033abe).
⚠️ Report is 5 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1476   +/-   ##
=======================================
  Coverage   91.32%   91.32%           
=======================================
  Files         170      170           
  Lines       22075    22076    +1     
=======================================
+ Hits        20159    20160    +1     
  Misses       1916     1916           
🚀 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

Benchmark is necessary, could be in the bnci with moabb

@bruAristimunha

Copy link
Copy Markdown
Collaborator

BNCI benchmark as requested (MOABB BNCI2014_001, session 1 train / session 2 test, subjects 1–3, seeds 0–2, 100 epochs, CPU, Voyager). Each pair starts from identical initial weights, data order and dropout streams; only the max-norm axis differs (master dim=0 vs this PR dim=1). Final-epoch test accuracy, no model selection on test:

model pairs mean Δacc (fixed − old) range pairs improved
ATCNet 9 +3.5 pp −0.7 … +11.1 pp 7/9
EEGTCNet 9 −0.7 pp −3.8 … +2.1 pp 3/9

With this PR every output unit stays within the max-norm limit (checked after training in all 18 runs). ATCNet benefits clearly; EEGTCNet is within seed noise (small, mixed). Integrated head 275b63d0; harness and per-epoch logs available on request.

Resolve changelog overlap while retaining master and this PR entry. Tree verified by Voyager follow-up tests.

@antonsoo antonsoo 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.

Tested dfa9ed0 against base 05b764d with PyTorch 2.7 on CPU and an RTX 5070. The new regression fails on base; 73 relevant module/model tests pass on head (pytest test/unit_tests/models/{test_modules,test_models}.py -k 'maxnorm or max_norm or atcnet or eegtcnet').

I also checked ATCNet's mean and concat heads and EEGTCNet on recorded PhysioNet S001R04 EEG: two seeds on each device, four Adam steps. All 12 base runs exceeded the per-output bound; all 12 head runs obey it. An independent row-by-row constraint agrees with forward/backward evaluation from the same weights and optimizer state (largest gradient difference 7.4e-7). Base checkpoints load strictly on head; saving model and optimizer after two steps and resuming preserves the following predictions and model state exactly.

This is a focused numerical/checkpoint review. I did not repeat the BNCI accuracy benchmark or full suite.

Copilot AI balanced review requested due to automatic review settings November 1, 2026 04:34

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.

🟢 Approval recommended

No active review issues remain for the per-output max-norm correction.

No open issues 🎉

What changed in this PR

Corrects MaxNormLinear to constrain each output unit’s incoming weights, matching Keras Dense max-norm behavior for ATCNet and EEGTCNet classification layers.

Changes:

  • Uses row-wise norms in MaxNorm.forward and right_inverse.
  • Updates the reference calculation and adds a regression test for per-output constraints.
  • Documents that existing checkpoints still load, but effective classification weights may change.
File Description
test/​unit_tests/​models/​test_modules.py Updates the reference norm axis and tests per-output constraints.
docs/​whats_new.rst Explains the correction and checkpoint behavior.
braindecode/​modules/​parametrization.py Applies row-wise norms and documents the intended constraint.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 1, 2026 04:39
@bruAristimunha
bruAristimunha merged commit 3eb3dae into master Nov 1, 2026
3 of 5 checks passed

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.

🟢 Approval recommended

There are no active review issues for the per-output-unit max-norm correction.

No open issues 🎉

Review effort: Balanced

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.

4 participants