Skip to content

FIX EEGRegressor: compare squeezed predictions with their own target - #1833

Merged
bruAristimunha merged 3 commits into
braindecode:masterfrom
AxelNoun:fix/bd-t05-7-regressor-squeezed-output
Nov 29, 2026
Merged

bruAristimunha merged 3 commits into
braindecode:masterfrom
AxelNoun:fix/bd-t05-7-regressor-squeezed-output

Conversation

@AxelNoun

Copy link
Copy Markdown
Contributor

Summary

EEGRegressor.fit reshapes a 1-D y to (n, 1). When the module returns (batch,), such as a custom head ending in squeeze(-1), MSELoss broadcasts the pair to (batch, batch) and compares every prediction with every target. This is the mirror of #1180: #1197 handles a (batch, 1) prediction with a (batch,) target, and #1198 handles CroppedLoss.

import torch

from braindecode import EEGRegressor

net = EEGRegressor(torch.nn.Linear(1, 1)).initialize()
y_pred = torch.tensor([0.0, 1.0])  # (batch,)
y_true = torch.tensor([[0.0], [1.0]])  # (batch, 1), as fit makes from a 1-D y
print(net.get_loss(y_pred, y_true).item())  # master: 0.5; this branch: 0.0

Changes

  • EEGRegressor.get_loss squeezes a (batch, 1) target when the prediction is 1-D.
  • test_eegregressor_loss_is_per_trial_mse_for_each_shape_pair: hard-coded loss for the four (batch,) / (batch, 1) pairs.
  • docs/whats_new.rst: entry under Bug fixes.

Testing

Windows, Python 3.12.10, torch 2.15.0+cpu. AGENTS.md sections 5, 6, 7, 10 and 11 apply.

  • pytest test/unit_tests/test_eegneuralnet.py -n 2 -q -rfEs: 108 passed, 0 skipped (master: 104 passed).

  • Mutation check: without the new branch, case [pred_shape0-target_shape1] fails (22.625 instead of 7.5). Without y_pred.ndim == 1 or y_true.ndim == 2, another case of the same test fails. The two isinstance checks repeat those of the existing branch and have no test; a probe raises AttributeError without each.

  • Parity with master (script below, OMP_NUM_THREADS=1; losses and gradients in float64): torch.equal in 99/99 cases for the other shapes and paths, one-trial batches and cropped mode included. For (batch,) with (batch, 1), 11/14 change; the 3 others are one-trial batches.

  • The 104 registered models, built with n_outputs=1 and run on 2 trials: none returns a 1-D output.

  • test/unit_tests/training, test_util.py, augmentation/test_base.py, models/test_emg_pose_baselines.py, test_docstring_parameters.py, test_dependencies.py, test_no_error_catching.py, test_lazy_imports.py and three acceptance files: 541 passed, 86 skipped, same on master. Skips: 70 models without ch_mask, 1 fNIRS montage, 1 CUDA, 10 --run-network, 4 classes that forward **kwargs.

  • The two ECoG examples (plot_bcic_iv_4_ecog_trial.py, plot_bcic_iv_4_ecog_cropped.py) give the same loss values as on master in all 48 and 144 get_loss calls (digest of the values, OMP_NUM_THREADS=1). They and plot_regression.py run without a broadcasting warning.

  • Not run locally: the full suite (ci_plan.py asks for it, since regressor.py is a global trigger) and the full documentation build (the changelog page and the get_loss docstring render with Sphinx 8.2.3).

  • 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

  • Behavior change: only modules that return (batch,) with a (batch, 1) target train differently than in 2.1 (regressor.py is unchanged since v2.1.0).
  • Custom criteria that fixed the shapes themselves now get a (batch,) target. t.squeeze(-1), t.flatten() and p.view_as(t) still give the per-trial loss. t.squeeze(1) and t[:, 0] raise IndexError. mse(p.unsqueeze(1), t) becomes the broadcast loss, with torch's warning. BCEWithLogitsLoss, which raised ValueError, now works.
  • Reshaping the prediction to (batch, 1) instead would give the broadcast loss for all of these except view_as and BCEWithLogitsLoss. Fix EEGRegressor loss broadcasting for one target per trial #1197 has the mirror effect on a criterion that calls t.unsqueeze(1).
Parity script (run with save on master, compare on this branch)
"""python parity.py save|compare <file.pt>: only the "TARGET" cases may differ."""

import sys
import warnings

import numpy as np
import torch
from torch import nn

from braindecode import EEGRegressor
from braindecode.models import ShallowFBCSPNet
from braindecode.training import CroppedLoss, TimeSeriesLoss

warnings.simplefilter("ignore")
torch.use_deterministic_algorithms(True)
SEED = 20261124
torch.manual_seed(SEED)


class Head(nn.Module):
    def __init__(self, n_chans=2, n_times=20, n_outputs=1, squeeze=False):
        super().__init__()
        self.lin = nn.Linear(n_chans * n_times, n_outputs)
        self.squeeze = squeeze

    def forward(self, x):
        out = self.lin(x.flatten(1))
        return out.squeeze(-1) if self.squeeze else out


def regressor(criterion, cropped=False, **kw):
    net = EEGRegressor(
        Head(), criterion=criterion, cropped=cropped, train_split=None, verbose=0, **kw
    )
    return net.initialize()


def loss_and_grad(net, pred_shape, true_shape):
    gen = torch.Generator().manual_seed(SEED)
    p = torch.randn(pred_shape, generator=gen, dtype=torch.float64, requires_grad=True)
    t = torch.randn(true_shape, generator=gen, dtype=torch.float64)
    loss = net.get_loss(p, t)
    return torch.cat([loss.detach().reshape(1), torch.autograd.grad(loss, p)[0].reshape(-1)])


out = {}
for crit in (nn.MSELoss, nn.L1Loss, nn.SmoothL1Loss):
    net = regressor(crit)
    for b in (1, 2, 7, 16):
        shapes = {
            "pred(b,1) true(b,)": ((b, 1), (b,)),
            "pred(b,1) true(b,1)": ((b, 1), (b, 1)),
            "pred(b,) true(b,)": ((b,), (b,)),
            "pred(b,3) true(b,3)": ((b, 3), (b, 3)),
            "pred(b,1,5) true(b,1,5)": ((b, 1, 5), (b, 1, 5)),
            "TARGET pred(b,) true(b,1)": ((b,), (b, 1)),
        }
        for name, (ps, ts) in shapes.items():
            out[f"{name} b={b} {crit.__name__}"] = loss_and_grad(net, ps, ts)
        if b == 1:  # module ending in a bare .squeeze(): 0-d output for one trial
            out[f"pred() true(b,1) b=1 {crit.__name__}"] = loss_and_grad(net, (), (1, 1))

for fn in (nn.functional.mse_loss, nn.functional.l1_loss):
    net = regressor(CroppedLoss, cropped=True, criterion__loss_function=fn)
    for b in (1, 2, 7):
        for k, ts in ((1, (b,)), (1, (b, 1)), (3, (b, 3))):
            out[f"cropped pred(b,{k},5) true{ts} {fn.__name__}"] = loss_and_grad(net, (b, k, 5), ts)
    net = regressor(TimeSeriesLoss, cropped=True, criterion__loss_function=fn)
    for b in (1, 4):
        out[f"timeseries b={b} {fn.__name__}"] = loss_and_grad(net, (b, 2, 5), (b, 2, 9))

# A tuple target (Mixup) goes through unchanged.
net = regressor(nn.MSELoss)
net.criterion_ = lambda p, t: (t[2] * (p - t[0]) ** 2 + (1 - t[2]) * (p - t[1]) ** 2).mean()
p = torch.arange(4.0, dtype=torch.float64)
out["mixup tuple, pred (b,)"] = net.get_loss(p, [p + 1, p + 2, torch.full((4,), 0.25)])

rng = np.random.RandomState(SEED)
X = rng.randn(33, 2, 20).astype("float32")  # 33 = 2 * 16 + 1: one validation batch of one trial
Y = {1: X[:, 0].mean(1).astype("float32"), 3: X[:, 0, :3].astype("float32")}


def train(make, data, y, **kw):
    torch.manual_seed(SEED)  # before building the module, so that its weights are seeded
    module = make()
    kw = dict(
        lr=0.05, max_epochs=3, batch_size=16, train_split=None, verbose=0,
        iterator_train__drop_last=False,
    ) | kw
    net = EEGRegressor(module, **kw).fit(data, y)
    params = [v.reshape(-1) for v in net.module_.state_dict().values()]
    return torch.cat([*(v.double() for v in params), torch.tensor(net.history[:, "train_loss"]).double()])


def ds(y):
    return torch.utils.data.TensorDataset(torch.tensor(X), torch.tensor(y))


out["fit Head (b,1), y 1-D"] = train(lambda: Head(), X, Y[1])
out["fit Head (b,1), y (n,1)"] = train(lambda: Head(), X, Y[1][:, None])
out["fit Head (b,1), dataset 1-D"] = train(lambda: Head(), ds(Y[1]), None)
out["fit Head (b,3), y (n,3)"] = train(lambda: Head(n_outputs=3), X, Y[3])
out["fit Head squeezed, dataset 1-D"] = train(lambda: Head(squeeze=True), ds(Y[1]), None)
out["TARGET fit Head squeezed, y 1-D"] = train(lambda: Head(squeeze=True), X, Y[1])
out["TARGET fit Head squeezed, y (n,1)"] = train(lambda: Head(squeeze=True), X, Y[1][:, None])

Xl = rng.randn(8, 4, 300).astype("float32")
yl = rng.randn(8).astype("float32")
for cropped in (False, True):
    def shallow(cropped=cropped):
        m = ShallowFBCSPNet(
            n_chans=4, n_outputs=1, n_times=300, final_conv_length=2 if cropped else "auto"
        )
        if cropped:
            m.to_dense_prediction_model()
        return m

    kw = {}
    if cropped:
        kw = dict(cropped=True, criterion=CroppedLoss, criterion__loss_function=nn.functional.mse_loss)
    for name, y in (("1-D", yl), ("(n,1)", yl[:, None])):
        for bs in (1, 4):
            out[f"fit ShallowFBCSPNet cropped={cropped} y {name} batch={bs}"] = train(
                shallow, Xl, y, batch_size=bs, lr=0.001, **kw
            )

mode, path = sys.argv[1:]
if mode == "save":
    torch.save(out, path)
    print("saved", len(out), "cases")
else:
    ref = torch.load(path)
    assert ref.keys() == out.keys()
    same = {k: torch.equal(ref[k], out[k]) for k in out}
    for target in (False, True):
        keys = [k for k in out if k.startswith("TARGET") == target]
        print("TARGET" if target else "other", f"{sum(same[k] for k in keys)}/{len(keys)} bitwise equal")
        print("  differ:", [k for k in keys if not same[k]])
    print("nan cases:", [k for k in out if torch.isnan(out[k]).any()])

EEGRegressor.fit reshapes a 1-D y to (n, 1). When the module returns
(batch,), MSELoss broadcast the pair to (batch, batch) and compared every
prediction with every target. get_loss now squeezes such a target, the
mirror of the (batch, 1) prediction and (batch,) target case of braindecode#1197.
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.97%. Comparing base (07ebac2) to head (e2b9baf).
⚠️ Report is 11 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1833      +/-   ##
==========================================
- Coverage   93.98%   93.97%   -0.02%     
==========================================
  Files         192      192              
  Lines       26379    26377       -2     
==========================================
- Hits        24793    24787       -6     
- Misses       1586     1590       +4     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bruAristimunha
bruAristimunha merged commit 762e71d into braindecode:master Nov 29, 2026
4 checks passed
@AxelNoun
AxelNoun deleted the fix/bd-t05-7-regressor-squeezed-output branch November 29, 2026 19:56
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