Skip to content

BENDR pretrained: contextualizer input projection and final LayerNorm seem to differ from the original release #1495

Open

Description

@neuromechanist

While wrapping the pretrained BENDR for a comparison against the authors' code, we found two places where braindecode.models.BENDR loaded from the Hub does not seem to reproduce the original pretrained model. We may well be missing something (a deliberate choice, or a different reference release), so please treat this as a question with evidence rather than a confirmed bug.

Setup. braindecode 1.4.0; Hub weights braindecode/braindecode-bendr at revision 191f221cd56de8203899ea9a8d0f43238724f8b6 (model.safetensors); reference: the authors' release assets encoder.pt (SHA-256 32c913b1...0fcf84cb) and contextualizer.pt (SHA-256 b8ee0c8c...6f91526) from SPOClab-ca/BENDR release v0.1-alpha, loaded with strict=True into ConvEncoderBENDR and BENDRContextualizer from dn3_ext.py at commit ac918ab. Comparisons are in eval mode on CPU.

1. The contextualizer's input projection looks like an initialization, not the pretrained layer. The encoder tensors in the Hub file equal the release's encoder.pt exactly, and the weight-normalized position convolution matches too. But contextualizer.input_conditioning.3 (the 512 to 1536 projection) does not match the release's input_conditioning.4 (the same projection as a 1x1 Conv1d, compared after squeezing the kernel dimension): the correlation between the two weight tensors is about 0.001, their standard deviations are 0.0124 against 0.0013, and the Hub bias is exactly zero. That pattern looks to us like a freshly initialized layer saved with the converted checkpoint, but we could not find the conversion script to check.

2. The contextualizer applies a final LayerNorm that the original forward does not seem to use. In bendr.py, _BENDRContextualizer.forward calls x = self.norm(x) (line 543 in 1.4.0) before self.output_layer. In the original BENDRContextualizer.forward (dn3_ext.py, lines 556 to 581 at ac918ab), self.norm is defined but, as far as we can read, never called; the output is output_layer(transformer_layers(...)). The release's norm.* tensors are not an identity (weight constant at about 0.9235, bias 0), so the extra call changes the output.

Effect. With the release tensors mapped into braindecode's BENDR (issue 1 worked around), the last-position contextualizer output differs from the original classes by a factor of about 22 in relative norm (cosine similarity about 0.74). After setting model.contextualizer.norm = nn.Identity(), the maximum absolute difference to the original classes is 0.0, for the last position and for every other position. So the rest of the port (layer order, weight-norm parameters, the 1x1 convolution as a linear layer) looks right to us; only these two points differ.

Questions. Is the Hub checkpoint meant to carry the pretrained input_conditioning weights, and was the final norm call intentional (for example matching a later version of the authors' code that we have not found)? If useful, we can share the short comparison script.

Possibly related: #1227 (input-geometry audit of the pretrained classes), which covers BENDR's channel handling but not weight equivalence.

Activity

  1. bruAristimunha commented on Oct 29, 2026

    @bruAristimunha
    Collaborator

    You are right here about the layernorm extra, but we had a very, very long journey with bendr, and this model is really bad. Including or not doesn't make a difference in the downstream benchmark.

    I think the conversion should be in Hugging Face; this is where we are doing the deposit.

    But i come back soon with more results...

    and please keep digging the models :)

  2. antonsoo commented on Oct 30, 2026

    @antonsoo
    Contributor

    I will check the final LayerNorm against the pinned release classes and weights on recorded EEG, then prepare a focused fix that keeps existing state dictionaries loadable. I will check the projection tensors separately so the two differences stay distinguishable.

  3. antonsoo commented on Oct 30, 2026

    @antonsoo
    Contributor

    I reproduced both differences using the pinned release tensors and 12 recorded PhysioNet EEG windows. #1498 addresses the extra final LayerNorm while retaining checkpoint keys.

    Only the projection weight and bias differ among the mapped contextualizer tensors; all encoder tensors match. A local copy can restore those two tensors with:

    import torch
    from safetensors.torch import load_file, save_file
    
    release = torch.load("contextualizer.pt", map_location="cpu", weights_only=True)
    weights = load_file("model.safetensors")
    weights["contextualizer.input_conditioning.3.weight"] = release["input_conditioning.4.weight"].squeeze(-1).contiguous()
    weights["contextualizer.input_conditioning.3.bias"] = release["input_conditioning.4.bias"]
    save_file(weights, "model.corrected.safetensors", metadata={"format": "pt"})

    With the code fix and these two replacements, full contextualizer outputs agree with the original classes within 1.8e-8 on CPU/CUDA; the start-token features agree exactly. With the code fix alone, the original Hub projection still gives a maximum difference of 0.0867 on the three-window CPU check. This is numerical equivalence, not a downstream accuracy result.

  4. BabaSanfour commented on Nov 14, 2026

    @BabaSanfour
    Contributor

    A follow-up on the contextualizer now that #1498 is merged. With the projection taken from the release (the workaround above), braindecode's contextualizer matches a plain-torch rebuild of the authors' forward from the release tensors (max |diff| 2.4e-7). All other contextualizer tensors on the Hub equal the release's to 1e-6, so the projection is the only weight that differs.

    With these weights, the start-token output that BENDR.forward passes to final_layer (context[:, :, 0]) is almost the same for every input. The authors' fine-tuning code reads the last position instead: BENDRClassification.features_forward in dn3_ext.py returns context[:, :, -1], with the context[:, :, 0] line commented out.

    Spread across 32 random-walk windows (std across windows / mean |value|), master 3118540a:

    Hub weights + release projection
    start token context[:, :, 0] 3.0e-5 7.7e-6
    last position context[:, :, -1] 1.11 0.70
    • On 1.8.1 the start token had a spread of 0.006, on synthetic and on real EEG (2,142 windows, 29 subjects); that came from the final LayerNorm that FIX BENDR contextualizer output to match the pretrained reference #1498 removed.
    • A linear classifier separating windows with and without a 10 Hz rhythm is at chance on the start token (AUC 0.52), against 0.62 on the last position and 0.56 on the mean of the time tokens.
    • Probably why: the start token is a constant (-5) and the layers have no LayerNorm (T-Fixup), so the time tokens hardly move it, although it does attend to them (attention weight on itself about 0.03 per layer).

    So with the release weights, a head on context[:, :, 0] gets a near-constant input. Should forward read the last position, as the authors' code does?

    Reproduction

    contextualizer.pt is the release asset of SPOClab-ca/BENDR v0.1-alpha (sha256 b8ee0c8c…6f91526). Without the workaround block, it gives the "Hub weights" column.

    import numpy as np
    import torch
    
    from braindecode.models import BENDR
    
    model = BENDR.from_pretrained(
        "braindecode/braindecode-bendr", n_chans=20, n_times=2560, sfreq=256, n_outputs=2
    ).eval()
    # The #1495 workaround: the projection from the release's contextualizer.pt
    release = torch.load("contextualizer.pt", map_location="cpu", weights_only=True)
    proj = model.contextualizer.input_conditioning[3]
    with torch.no_grad():
        proj.weight.copy_(release["input_conditioning.4.weight"].squeeze(-1))
        proj.bias.copy_(release["input_conditioning.4.bias"])
    
    # 32 random-walk windows, min-max scaled to -1..1, plus the SCALE channel at 0
    rng = np.random.default_rng(0)
    x = np.cumsum(rng.standard_normal((32, 19, 2560)), axis=-1)
    lo, hi = x.min(axis=(1, 2), keepdims=True), x.max(axis=(1, 2), keepdims=True)
    x = np.concatenate([2 * (x - lo) / (hi - lo) - 1, np.zeros((32, 1, 2560))], axis=1)
    
    with torch.no_grad():
        context = model.contextualizer(model.encoder(torch.from_numpy(x).float()))
    
    
    def spread(f):  # std across windows / mean |value|
        return (f.std(dim=0).mean() / f.abs().mean()).item()
    
    
    print(f"start token   context[:, :, 0]:  {spread(context[:, :, 0]):.1e}")
    print(f"last position context[:, :, -1]: {spread(context[:, :, -1]):.2f}")

    Claude Code was used to run these measurements and check them against the release; I reviewed and ran them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions