Skip to content

FIX CodeBrain: keep the kernel norm in a copy fed through its buffers - #1866

Merged
bruAristimunha merged 3 commits into
braindecode:masterfrom
AxelNoun:fix/bd-t08-4-kernel-norm-buffer
Dec 1, 2026
Merged

bruAristimunha merged 3 commits into
braindecode:masterfrom
AxelNoun:fix/bd-t08-4-kernel-norm-buffer

Conversation

@AxelNoun

@AxelNoun AxelNoun commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Since #1578 (2.1.0), _GConv computes its kernel norm when a Python flag is unset, and only _load_from_state_dict syncs that flag with the kernel_norm_initialized buffer. A copy made before the first forward and then given the model's values in place, as an EMA copy is, has the buffer set but not the flag: its first forward overwrites kernel_norm, so it returns other outputs than the model with the same state_dict. A DataParallel replica sets the flag on itself, so every step recomputes the norm.

Toy run (script below):

master this branch v2.0.0
AveragedModel(use_buffers=True) or in-place copy, made before the first forward logits differ (relative gap 5.4e-4) equal equal
same, made after the first forward equal equal equal
emulated DataParallel: kernel_norm changed at steps 1, 2 True, True False, False False, False

Changes

  • _GConv.forward writes the computed norm only where kernel_norm_initialized is unset (torch.where, no host read; the model still compiles into one graph).
  • One test in test_codebrain_compile.py; whats_new.rst.

Testing

Windows 11, Python 3.12.10, torch 2.15.0+cpu, on master at 92cb203 and on this branch, with -p no:cacheprovider and -n 2 where shown. Counts are master / branch.

  • pytest -rfEs -n 2 test/unit_tests/models/ --select-models=CodeBrain -k "CodeBrain or completeness or summary_csv or categorization": 83 / 84 passed (the new test), 8 / 8 skipped, 0 failed; 71 test ids contain [CodeBrain.

  • pytest -rfEs -n 2 test/unit_tests/models/test_model_contract.py --select-models=CodeBrain -k CodeBrain: 12 / 12 passed, 3 / 3 skipped; 15 ids contain [CodeBrain.

  • pytest -rfEs test/unit_tests/models/test_pretrained_compat.py --select-models=CodeBrain -k "CodeBrain or covers_every or no_strategy": 15 / 15 passed.

  • pytest -rfEs test/unit_tests/models/test_codebrain_compile.py: 5 / 6 passed.

  • Skip reasons: pydantic not installed, fixed length (2), torch.compile on Windows, no embedding parameter, forward reads tensor values on meta (2), no ch_mask.

  • test_config.py --select-models=CodeBrain, run again with numpydantic 2.0.1 installed: 19 passed on master and here.

  • torch 2.6.0 (the floor), test_integration.py --select-models=CodeBrain -k "CodeBrain and (exported or torch_script)": 2 passed on master and here; the new test passes.

  • The 23 other files listed by scripts/ci_plan.py (select_models: CodeBrain), -n 2 --select-models=CodeBrain: 1681 / 1681 passed, 43 / 43 skipped (network 18, MPS 6, no ch_mask 4, Windows torch.compile 2, meta 2, fixed length 2, no embedding parameter 2, EEGNet **kwargs 2, then one each: pydantic, sphinx, Windows bfloat16 fold, CUDA, HF token), 13 / 13 failed, the same on both: 5 Windows symlink tests (WinError 1314) and 8 UnicodeDecodeError (cp1252). With PYTHONUTF8=1, test_model_rules.py, test_private_blocks.py and test_dependencies.py: 19 / 19 passed.

  • Mutation: restoring self.kernel_norm.copy_(norm) fails test_codebrain_copy_fed_through_its_buffers_keeps_the_kernel_norm.

  • Script below: master, branch and v2.0.0 outputs as in the table.

  • pre-commit run --files on the three files: passed.

  • Not run: several GPUs.

  • 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

  • Ordinary use is unchanged: in float64, two training steps then eval, n_times 400 and 1000, outputs, return_features, all gradients, state_dict, a reload and from_config(get_config()) are bitwise equal to master (1570 tensors).
  • v2.0.0 state dicts (saved here with torch 2.15), before or after the first forward, load strictly and give v2.0.0's outputs bitwise, on master and here. CodeBrain is not added to _V2_MODELS, which would need fixtures regenerated under torch 2.6.
  • DataParallel was emulated on CPU, not run on GPUs. The effect was not measured on a real training.
Script
"""BD-T08-4: a CodeBrain copy updated through its buffers recomputes its kernel norm.

Consumes: the braindecode found first on sys.path (set PYTHONPATH to the tree to test).
Produces: text on stdout only (synthetic data, fixed seeds, CPU).
Hypothesis: a copy made before the first forward, then fed the source's state_dict
values (AveragedModel(use_buffers=True), or an in-place copy of the values),
must give the source's outputs; a DataParallel replica must not change kernel_norm.
Run: python reproduction.py
"""
import copy
import warnings

import torch
from torch.optim.swa_utils import AveragedModel, get_ema_multi_avg_fn

import braindecode
from braindecode.models import CodeBrain

warnings.simplefilter("ignore")
torch.set_num_threads(2)

N_CHANS, N_TIMES, N_EXAMPLES, STEPS, LR = 8, 400, 64, 50, 1e-3


def data(g):
    X = torch.randn(N_EXAMPLES, N_CHANS, N_TIMES, generator=g)
    y = torch.randint(0, 2, (N_EXAMPLES,), generator=g)
    X[y == 1] += 2 * torch.sin(torch.arange(N_TIMES) * 0.3)
    return X, y


def run(kind, forward_first):
    torch.manual_seed(0)
    model = CodeBrain(
        n_chans=N_CHANS, n_outputs=2, n_times=N_TIMES, num_res_layers=2
    ).train()
    g = torch.Generator().manual_seed(1)
    X, y = data(g)
    if forward_first:
        with torch.no_grad():
            model(X[:2])
    if kind == "AveragedModel":  # decay 0: the average is the last state
        ema = AveragedModel(
            model, multi_avg_fn=get_ema_multi_avg_fn(0.0), use_buffers=True
        )
        copy_ = ema.module
    else:  # state_dict values copied in place, as an EMA loop with decay 0 does
        ema = copy_ = copy.deepcopy(model)
    opt = torch.optim.AdamW(model.parameters(), lr=LR)
    for _ in range(STEPS):
        i = torch.randint(0, N_EXAMPLES, (16,), generator=g)
        torch.nn.functional.cross_entropy(model(X[i]), y[i]).backward()
        opt.step()
        opt.zero_grad()
        if kind == "AveragedModel":
            ema.update_parameters(model)
        else:
            with torch.no_grad():
                for a, b in zip(ema.state_dict().values(), model.state_dict().values()):
                    a.copy_(b)
    model.eval()
    copy_.eval()
    same = all(
        torch.equal(a, b)
        for a, b in zip(copy_.state_dict().values(), model.state_dict().values())
    )
    with torch.no_grad():
        logits, logits_copy = model(X), copy_(X)
    gap = ((logits_copy - logits).norm() / logits.norm()).item()
    print(
        f"{kind}, copied {'after' if forward_first else 'before'} the first forward: "
        f"same state_dict {same}, outputs equal {torch.equal(logits, logits_copy)}, "
        f"relative logit gap {gap:.2g}"
    )


def replica(module):
    """nn.DataParallel replica emulated on CPU: shallow copy sharing the tensors."""
    r = module._replicate_for_data_parallel()
    r._parameters, r._buffers = dict(module._parameters), dict(module._buffers)
    for k, c in module._modules.items():
        r._modules[k] = None if c is None else replica(c)
    return r


print("braindecode", braindecode.__version__, braindecode.__file__)
for kind in ("AveragedModel", "in-place copy"):
    for forward_first in (False, True):
        run(kind, forward_first)

torch.manual_seed(0)
model = CodeBrain(n_chans=N_CHANS, n_outputs=4, n_times=1000, num_res_layers=2).train()
layer = model.residual_layer.residual_blocks[0].sgconv
opt = torch.optim.SGD(model.parameters(), lr=0.01)
x, last = torch.randn(2, N_CHANS, 1000), None
for step in range(3):
    replica(model)(x).pow(2).mean().backward()
    opt.step()
    opt.zero_grad()
    if last is not None:
        print(
            f"emulated DataParallel, step {step}: kernel_norm changed "
            f"{not torch.equal(last, layer.kernel_norm)}"
        )
    last = layer.kernel_norm.clone()

A copy made before the first forward and then given the model's values (an EMA copy), or a DataParallel replica, has kernel_norm_initialized set but the Python flag unset, so its first forward overwrote the kernel norm with the norm of the current kernels. The norm is now written only where the buffer is unset.
@bruAristimunha
bruAristimunha merged commit b6d4f65 into braindecode:master Dec 1, 2026
10 checks passed
@AxelNoun
AxelNoun deleted the fix/bd-t08-4-kernel-norm-buffer branch December 1, 2026 12:08
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