Download submission.py from fairfriend/proteus-stream-decoder: direct link, hf CLI and curl.
- Browser
- Download file 27.3 kB
-
https://huggingface.co/fairfriend/proteus-stream-decoder/resolve/main/submission.py
- Command line
-
hf download hf://fairfriend/proteus-stream-decoder/submission.py
-
curl -L -o submission.py https://huggingface.co/fairfriend/proteus-stream-decoder/resolve/main/submission.py
27.3 kB
| """Codabench submission for Track 02 (BCI decoding): patch transformers blended with two tangent-space members. | |
| Each window is classified by the transformers and by two linear members. The | |
| transformers take 0.4 of the blend, the tangent-space member 0.45 and the | |
| region member 0.15. A running correction then divides the blend by the | |
| stream's mean prediction so far. | |
| Pipeline for one window | |
| ----------------------- | |
| 1. Transformers. ``CausalAlign`` z-scores the window with the running statistics | |
| of the stream (one session of one participant) and whitens it with the running | |
| mean covariance of the windows seen so far. Every transformer then cuts the | |
| aligned window into overlapping patches, embeds them at three time scales, | |
| encodes the token sequence, and fuses the result with a summary of the | |
| inter-channel phase synchrony of the whole window. The softmax probabilities | |
| of all transformers are averaged. | |
| 2. Tangent-space member. ``TangentMember`` band-passes the raw window and stacks | |
| each channel with a delayed copy of itself, estimates one shrunk covariance per | |
| band, recenters it with the running mean covariance of the stream, projects it | |
| to the tangent space of the training references, appends the mean and slope | |
| of every raw channel z-scored with the stream's running statistics, and | |
| applies a logistic regression. | |
| 3. Region member. ``RegionMember`` band-passes the raw window, averages the | |
| channels of five scalp regions, and classifies the recentered tangent vectors | |
| of the region covariances the same way. | |
| Each member's class score is shifted by the gap between the stream's mean | |
| score for that class, weighted by the corrected blend's past predictions, | |
| and the training mean of that class, started by a prior of 5 windows. | |
| 4. Class-prior correction. The blended probabilities are divided by the mean | |
| probabilities of the stream's windows so far, started by a prior of uniform | |
| predictions, and renormalized. Every command appears in equal shares in a | |
| stream, so this removes a drift of the predictions towards one class. | |
| The stream starts empty, so no statistic carries over from another participant | |
| or session. | |
| Weights | |
| ------- | |
| Every ``weights_*.pt`` file holds ``state_dicts`` (the transformers' | |
| parameters) and ``model_cfg`` (the architecture as a dict). ``tangent.npz`` | |
| holds the tangent-space member's references, training mean covariances, | |
| logistic regression, frequency bands, delays and slow-feature statistics, and | |
| ``regcov.npz`` the region member's references, training means, logistic | |
| regression, bands and region channel indices. The architecture is built from | |
| ``model_cfg`` and the input description in ``meta``, so nothing here depends on | |
| the number of channels or the window length. | |
| """ | |
| import math | |
| import numpy as np | |
| import torch | |
| from scipy.signal import butter, sosfiltfilt | |
| from sklearn.covariance import oas | |
| from torch import nn | |
| from benchmark_utils.base_solver import CompetSolver | |
| NETWORK_WEIGHT = 0.4 | |
| TANGENT_SHARE = 0.75 # share of the tangent-space member in the linear half, the rest goes to the region member | |
| DEBIAS_PRIOR_WINDOWS = 5.0 # windows of uniform prediction that start the running mean | |
| PROTO_PRIOR_WINDOWS = 5.0 # windows of the training class projection that start each member's running class shift | |
| def inverse_sqrt(cov, floor): | |
| """Inverse square root of a symmetric positive definite matrix. | |
| Parameters | |
| ---------- | |
| cov : ndarray, shape (n, n) | |
| floor : float | |
| Floor on the eigenvalues. | |
| Returns | |
| ------- | |
| ndarray, shape (n, n) | |
| """ | |
| values, vectors = np.linalg.eigh(cov) | |
| return (vectors / np.sqrt(np.maximum(values, floor))) @ vectors.T | |
| def upper_log_map(centered, reference_inv_sqrt): | |
| """Tangent vector of a recentered covariance at a training reference. | |
| Parameters | |
| ---------- | |
| centered : ndarray, shape (n, n) | |
| Covariance whitened by the stream's running mean. | |
| reference_inv_sqrt : ndarray, shape (n, n) | |
| Inverse square root of the tangent space reference. | |
| Returns | |
| ------- | |
| ndarray, shape (n * (n + 1) / 2,) | |
| Upper triangle of the matrix logarithm, off-diagonal entries scaled by sqrt(2). | |
| """ | |
| values, vectors = np.linalg.eigh(reference_inv_sqrt @ centered @ reference_inv_sqrt) | |
| log_map = (vectors * np.log(values)) @ vectors.T | |
| rows, cols = np.triu_indices(len(log_map)) | |
| # Off-diagonal entries count twice in the tangent space norm. | |
| return np.where(rows == cols, 1.0, math.sqrt(2.0)) * log_map[rows, cols] | |
| def softmax(logits): | |
| """Class probabilities from class scores. | |
| Parameters | |
| ---------- | |
| logits : ndarray, shape (n_classes,) | |
| Returns | |
| ------- | |
| ndarray, shape (n_classes,) | |
| """ | |
| logits = np.exp(logits - logits.max()) | |
| return logits / logits.sum() | |
| class CausalAlign: | |
| """Running per-channel z-score followed by running Euclidean alignment. | |
| The z-score uses the pooled mean and variance of every sample seen so far in | |
| the stream, the current window included. The alignment then whitens the | |
| z-scored window with the inverse square root of the mean covariance of the | |
| z-scored windows seen so far. Both are defined from the first window. | |
| Parameters | |
| ---------- | |
| cov_prior_windows : float | |
| Weight, in windows, of an identity covariance prior. Z-scored windows | |
| have unit variance per channel, so identity is the natural prior. It | |
| keeps the first whitener full rank. | |
| """ | |
| def __init__(self, cov_prior_windows): | |
| self.cov_prior_windows = cov_prior_windows | |
| self.reset() | |
| def reset(self): | |
| """Forgets every window seen, ready for a new stream.""" | |
| self.n_windows = 0 | |
| self.sum_mean = None | |
| self.sum_sq = None | |
| self.sum_cov = None | |
| def __call__(self, window): | |
| """Adds one window to the running statistics and returns it aligned. | |
| Parameters | |
| ---------- | |
| window : ndarray, shape (n_channels, n_times) | |
| The next window of the stream. | |
| Returns | |
| ------- | |
| ndarray, shape (n_channels, n_times) | |
| The z-scored, whitened window, as float32. | |
| """ | |
| x = np.asarray(window, dtype=np.float64) | |
| n_channels, n_times = x.shape | |
| if self.n_windows == 0: | |
| self.sum_mean = np.zeros(n_channels) | |
| self.sum_sq = np.zeros(n_channels) | |
| self.sum_cov = np.zeros((n_channels, n_channels)) | |
| self.n_windows += 1 | |
| # Z-score with the mean and variance of all samples of the stream so far. | |
| self.sum_mean += x.mean(axis=1) | |
| self.sum_sq += (x ** 2).mean(axis=1) | |
| mean = self.sum_mean / self.n_windows | |
| var = self.sum_sq / self.n_windows - mean ** 2 | |
| z = (x - mean[:, None]) / (np.sqrt(np.maximum(var, 0.0)) + 1e-8)[:, None] | |
| # Whiten with the inverse square root of the running covariance, shrunk toward identity. | |
| self.sum_cov += z @ z.T / n_times | |
| cov = (self.cov_prior_windows * np.eye(n_channels) + self.sum_cov) / (self.cov_prior_windows + self.n_windows) | |
| return (inverse_sqrt(cov, 1e-12) @ z).astype(np.float32) | |
| class TangentMember: | |
| """Filter-bank tangent-space classifier on causally recentered covariances. | |
| Parameters | |
| ---------- | |
| params : dict | |
| Arrays of ``tangent.npz``: "bands" (n_bands, 2), "lags" (n_bands,) delay in | |
| samples of the copy stacked with the channels of each band, "reference" and | |
| "prior" (n_bands, dim, dim) with dim twice the channel count, "coef" | |
| (n_classes, n_features), "intercept" (n_classes,), "prior_windows", and | |
| "slow_mean", "slow_variance" (2 * n_channels,) and "slow_prior_windows", the | |
| training streams' average statistics of the slow features and their weight, | |
| and "class_projection" (n_classes,), the training mean of each class projected | |
| on that class's weights. | |
| sfreq : float | |
| Sampling rate of the windows in Hz. | |
| """ | |
| def __init__(self, params, sfreq): | |
| self.sfreq = sfreq | |
| self.filters = [butter(4, [low, high], "bandpass", fs=sfreq, output="sos") for low, high in params["bands"]] | |
| self.lags = [int(lag) for lag in params["lags"]] | |
| self.prior = params["prior"] | |
| self.prior_windows = float(params["prior_windows"]) | |
| self.reference_inv_sqrt = [inverse_sqrt(reference, 1e-9) for reference in params["reference"]] | |
| self.coef = params["coef"] | |
| self.intercept = params["intercept"] | |
| self.class_projection = params["class_projection"] | |
| self.slow_mean = params["slow_mean"] | |
| self.slow_second = params["slow_variance"] + params["slow_mean"] ** 2 | |
| self.slow_prior_windows = float(params["slow_prior_windows"]) | |
| self.reset() | |
| def reset(self): | |
| """Forgets every window seen, ready for a new stream.""" | |
| self.n_windows = 0 | |
| self.running = self.prior_windows * self.prior | |
| self.slow_sum = self.slow_prior_windows * self.slow_mean | |
| self.slow_sum_sq = self.slow_prior_windows * self.slow_second | |
| def slow_features(self, x): | |
| """Mean and slope of every channel, z-scored with the stream's windows so far, this one included. | |
| Parameters | |
| ---------- | |
| x : ndarray, shape (n_channels, n_times) | |
| Raw window. | |
| Returns | |
| ------- | |
| ndarray, shape (2 * n_channels,) | |
| """ | |
| t = np.arange(x.shape[-1]) / self.sfreq | |
| centered = t - t.mean() | |
| features = np.concatenate([x.mean(axis=-1), (x * centered).sum(axis=-1) / (centered ** 2).sum()]) | |
| self.slow_sum = self.slow_sum + features | |
| self.slow_sum_sq = self.slow_sum_sq + features ** 2 | |
| weight = self.n_windows + self.slow_prior_windows | |
| mean = self.slow_sum / weight | |
| variance = self.slow_sum_sq / weight - mean ** 2 | |
| return (features - mean) / (np.sqrt(np.maximum(variance, 0.0)) + 1e-8) | |
| def __call__(self, window): | |
| """Adds one window to the running covariances and returns its class scores. | |
| Parameters | |
| ---------- | |
| window : ndarray, shape (n_channels, n_times) | |
| The next raw window of the stream. | |
| Returns | |
| ------- | |
| ndarray, shape (n_classes,) | |
| Weights times features, without the intercept. | |
| """ | |
| x = np.asarray(window, dtype=np.float64) | |
| self.n_windows += 1 | |
| features = [] | |
| for band, (sos, lag, reference_inv_sqrt) in enumerate(zip(self.filters, self.lags, self.reference_inv_sqrt)): | |
| filtered = sosfiltfilt(sos, x, axis=-1) | |
| # Each channel x(t) is stacked with x(t - lag), dropping the first lag samples, as in the training covariances. | |
| filtered = np.concatenate([filtered[:, lag:], filtered[:, :-lag]], axis=0) | |
| cov = oas(filtered.T)[0] | |
| cov = cov / np.trace(cov) * cov.shape[0] | |
| self.running[band] += cov | |
| whitener = inverse_sqrt(self.running[band] / (self.n_windows + self.prior_windows), 1e-9) | |
| features.append(upper_log_map(whitener @ cov @ whitener, reference_inv_sqrt)) | |
| features.append(self.slow_features(x)) | |
| return self.coef @ np.concatenate(features) | |
| class RegionMember: | |
| """Tangent-space classifier on causally recentered covariances of region-averaged signals. | |
| Parameters | |
| ---------- | |
| params : dict | |
| Arrays of ``regcov.npz``: "bands" (n_bands, 2), "regions" (n_regions, max_size) | |
| channel indices padded with -1, "reference" and "prior" (n_bands, n_regions, | |
| n_regions), "coef" (n_classes, n_features), "intercept" (n_classes,), | |
| "prior_windows" and "class_projection" (n_classes,). | |
| sfreq : float | |
| Sampling rate of the windows in Hz. | |
| """ | |
| def __init__(self, params, sfreq): | |
| self.filters = [butter(4, [low, high], "bandpass", fs=sfreq, output="sos") for low, high in params["bands"]] | |
| self.regions = [row[row >= 0] for row in params["regions"]] | |
| self.prior = params["prior"] | |
| self.prior_windows = float(params["prior_windows"]) | |
| self.reference_inv_sqrt = [inverse_sqrt(reference, 1e-9) for reference in params["reference"]] | |
| self.coef = params["coef"] | |
| self.intercept = params["intercept"] | |
| self.class_projection = params["class_projection"] | |
| self.reset() | |
| def reset(self): | |
| """Forgets every window seen, ready for a new stream.""" | |
| self.n_windows = 0 | |
| self.running = self.prior_windows * self.prior | |
| def __call__(self, window): | |
| """Adds one window to the running covariances and returns its class scores. | |
| Parameters | |
| ---------- | |
| window : ndarray, shape (n_channels, n_times) | |
| The next raw window of the stream. | |
| Returns | |
| ------- | |
| ndarray, shape (n_classes,) | |
| Weights times features, without the intercept. | |
| """ | |
| x = np.asarray(window, dtype=np.float64) | |
| self.n_windows += 1 | |
| features = [] | |
| for band, (sos, reference_inv_sqrt) in enumerate(zip(self.filters, self.reference_inv_sqrt)): | |
| filtered = sosfiltfilt(sos, x, axis=-1) | |
| regions = np.stack([filtered[idx].mean(axis=0) for idx in self.regions]) | |
| regions = regions - regions.mean(axis=-1, keepdims=True) | |
| cov = regions @ regions.T / regions.shape[-1] | |
| # Ridge of 1e-6 of the mean variance, as in training. | |
| cov = cov + 1e-6 * np.trace(cov) / len(cov) * np.eye(len(cov)) | |
| self.running[band] += cov | |
| whitener = inverse_sqrt(self.running[band] / (self.n_windows + self.prior_windows), 1e-9) | |
| features.append(upper_log_map(whitener @ cov @ whitener, reference_inv_sqrt)) | |
| return self.coef @ np.concatenate(features) | |
| class MultiBandPatchEmbedding(nn.Module): | |
| """Turns a window into one token per patch. | |
| Parallel temporal convolutions of different lengths share the same stride, | |
| so every patch is described at several time scales. Their outputs split the | |
| embedding channels between them. A spatial convolution then mixes all EEG | |
| channels into one value per embedding channel, so each patch becomes one token. | |
| Parameters | |
| ---------- | |
| n_channels : int | |
| Number of EEG channels. | |
| embed_dim : int | |
| Token dimension. | |
| patch_size : int | |
| Length of a patch in samples, which is also the shortest kernel. | |
| patch_stride : int | |
| Step between two patches in samples. | |
| kernels : list of int | |
| Lengths in samples of the parallel temporal convolutions. Each exceeds | |
| patch_size by an even number, and is zero-padded symmetrically so that | |
| all of them yield the same patches. | |
| """ | |
| def __init__(self, n_channels, embed_dim, patch_size, patch_stride, kernels): | |
| super().__init__() | |
| widths = [embed_dim // len(kernels)] * len(kernels) | |
| widths[-1] += embed_dim - sum(widths) | |
| self.temporal_conv = nn.ModuleList([ | |
| nn.Conv2d(1, width, (1, k), stride=(1, patch_stride), padding=(0, (k - patch_size) // 2), bias=False) | |
| for width, k in zip(widths, kernels) | |
| ]) | |
| self.spatial_conv = nn.Conv2d(embed_dim, embed_dim, (n_channels, 1), bias=False) | |
| self.norm = nn.BatchNorm2d(embed_dim) | |
| self.activation = nn.ELU() | |
| def forward(self, x): | |
| """ | |
| Parameters | |
| ---------- | |
| x : Tensor, shape (batch, n_channels, n_times) | |
| Returns | |
| ------- | |
| Tensor, shape (batch, n_patches, embed_dim) | |
| """ | |
| x = x.unsqueeze(1) # (batch, 1, channels, times) | |
| x = torch.cat([conv(x) for conv in self.temporal_conv], dim=1) # (batch, embed_dim, channels, n_patches) | |
| x = self.activation(self.norm(self.spatial_conv(x))) # (batch, embed_dim, 1, n_patches) | |
| return x.squeeze(2).transpose(1, 2) | |
| class PhaseSynchrony(nn.Module): | |
| """Summarizes the phase synchrony between channel pairs over a whole window. | |
| The window is band-passed and Hilbert transformed in the frequency domain, | |
| which gives a phase per channel and band. For every channel pair, the | |
| phase-locking value of each short sliding window is the average of | |
| exp(i * phase difference). Its real and imaginary parts are averaged over the | |
| sliding windows and projected linearly to a single vector. The imaginary part | |
| vanishes for zero-lag coupling, which is how volume conduction appears, so it | |
| carries the lagged coupling alone. Only the final projection has learned | |
| weights. | |
| Parameters | |
| ---------- | |
| n_channels : int | |
| Number of EEG channels. | |
| n_times : int | |
| Number of samples of a window. | |
| out_dim : int | |
| Length of the output vector. | |
| window : int | |
| Length of the sliding windows in samples. | |
| stride : int | |
| Step between two sliding windows in samples. | |
| bands : list of list of float | |
| [low, high] edges in Hz of each frequency band. | |
| sfreq : float | |
| Sampling rate of the windows in Hz. | |
| """ | |
| def __init__(self, n_channels, n_times, out_dim, window, stride, bands, sfreq): | |
| super().__init__() | |
| self.window, self.stride = window, stride | |
| rows, cols = torch.triu_indices(n_channels, n_channels, offset=1) | |
| self.register_buffer("rows", rows, persistent=False) | |
| self.register_buffer("cols", cols, persistent=False) | |
| # Doubling the positive frequencies of a band and zeroing the rest gives the analytic signal. | |
| freqs = torch.fft.fftfreq(n_times, 1.0 / sfreq) | |
| masks = torch.stack([2.0 * ((freqs >= low) & (freqs < high)).float() for low, high in bands]) | |
| self.register_buffer("masks", masks, persistent=False) | |
| self.projection = nn.Linear(2 * len(bands) * len(rows), out_dim, bias=False) | |
| self.norm = nn.BatchNorm1d(out_dim) | |
| self.activation = nn.ELU() | |
| def forward(self, x): | |
| """ | |
| Parameters | |
| ---------- | |
| x : Tensor, shape (batch, n_channels, n_times) | |
| Returns | |
| ------- | |
| Tensor, shape (batch, out_dim) | |
| """ | |
| spectrum = torch.fft.fft(x.float(), dim=-1) # (batch, channels, times) | |
| analytic = torch.fft.ifft(spectrum[:, None] * self.masks[None, :, None], dim=-1) # (batch, bands, channels, times) | |
| phasor = analytic / analytic.abs().clamp(min=1e-8) # unit phasor, amplitude discarded | |
| windows = phasor.unfold(-1, self.window, self.stride).permute(0, 1, 3, 2, 4) # (batch, bands, n_windows, channels, window) | |
| plv = windows @ windows.conj().transpose(-1, -2) / self.window # (batch, bands, n_windows, channels, channels) | |
| plv = plv[..., self.rows, self.cols] # (batch, bands, n_windows, n_pairs) | |
| features = torch.cat([plv.real, plv.imag], dim=-1).permute(0, 2, 1, 3).flatten(2) | |
| features = features.mean(dim=1) # average over the sliding windows | |
| return self.activation(self.norm(self.projection(features))) | |
| def sinusoidal_positional_encoding(seq_len, embed_dim, device): | |
| """Computes fixed sinusoidal position encodings. | |
| Parameters | |
| ---------- | |
| seq_len : int | |
| Number of token positions. | |
| embed_dim : int | |
| Token dimension. | |
| device : torch.device | |
| Device on which to allocate the encoding. | |
| Returns | |
| ------- | |
| Tensor, shape (seq_len, embed_dim) | |
| """ | |
| position = torch.arange(seq_len, device=device).unsqueeze(1) | |
| div_term = torch.exp(torch.arange(0, embed_dim, 2, device=device) * (-math.log(10000.0) / embed_dim)) | |
| pe = torch.zeros(seq_len, embed_dim, device=device) | |
| pe[:, 0::2] = torch.sin(position * div_term) | |
| pe[:, 1::2] = torch.cos(position * div_term) | |
| return pe | |
| class PatchTransformer(nn.Module): | |
| """Transformer encoder over patch tokens, fused with a phase synchrony vector. | |
| Parameters | |
| ---------- | |
| n_channels : int | |
| Number of EEG channels. | |
| n_times : int | |
| Number of samples of a window. | |
| n_classes : int | |
| Number of output classes. | |
| sfreq : float | |
| Sampling rate of the windows in Hz. | |
| cfg : dict | |
| Architecture as saved in the weights file (``model_cfg``). | |
| """ | |
| def __init__(self, n_channels, n_times, n_classes, sfreq, cfg): | |
| super().__init__() | |
| self.patch_embed = MultiBandPatchEmbedding( | |
| n_channels, cfg["embed_dim"], cfg["patch_size"], cfg["patch_stride"], cfg["multiband_kernels"]) | |
| # The sliding windows of the phase branch advance with the patch stride. | |
| self.phase_late = PhaseSynchrony( | |
| n_channels, n_times, cfg["embed_dim"], cfg["phase_window"], cfg["patch_stride"], cfg["phase_bands"], sfreq) | |
| encoder_layer = nn.TransformerEncoderLayer( | |
| d_model=cfg["embed_dim"], nhead=cfg["n_heads"], dim_feedforward=cfg["ff_dim"], | |
| dropout=cfg["dropout"], batch_first=True) | |
| self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=cfg["n_layers"]) | |
| self.classifier = nn.Linear(2 * cfg["embed_dim"], n_classes) | |
| def forward(self, x): | |
| """ | |
| Parameters | |
| ---------- | |
| x : Tensor, shape (batch, n_channels, n_times) | |
| Returns | |
| ------- | |
| Tensor, shape (batch, n_classes) | |
| Class logits. | |
| """ | |
| tokens = self.patch_embed(x) | |
| tokens = tokens + sinusoidal_positional_encoding(tokens.shape[1], tokens.shape[2], tokens.device).unsqueeze(0) | |
| pooled = self.encoder(tokens).mean(dim=1) # average over the patch tokens | |
| return self.classifier(torch.cat([pooled, self.phase_late(x)], dim=-1)) | |
| class Blend(nn.Module): | |
| """Averages the transformers' probabilities, blends in the linear members and corrects the class prior. | |
| Parameters | |
| ---------- | |
| networks : list of PatchTransformer | |
| Trained networks, in eval mode. | |
| aligner : CausalAlign | |
| Alignment shared by all networks, applied once per window. | |
| member : TangentMember | |
| Tangent-space classifier on the raw windows. | |
| region_member : RegionMember | |
| Region covariance classifier on the raw windows. | |
| """ | |
| def __init__(self, networks, aligner, member, region_member): | |
| super().__init__() | |
| self.networks = nn.ModuleList(networks) | |
| self.aligner = aligner | |
| self.member = member | |
| self.region_member = region_member | |
| self.reset_state() | |
| def reset_state(self): | |
| """Forgets the stream's running statistics. Codabench calls it before each stream.""" | |
| self.aligner.reset() | |
| self.member.reset() | |
| self.region_member.reset() | |
| self.n_windows = 0 | |
| self.prob_sum = None | |
| self.soft_sums = [0.0, 0.0] | |
| self.soft_count = 0.0 | |
| def predict(self, X): | |
| """Predicts the class of each window of the stream. | |
| Parameters | |
| ---------- | |
| X : Tensor, shape (batch, n_channels, n_times) | |
| The next windows of the stream, in recording order. | |
| Returns | |
| ------- | |
| Tensor, shape (batch,) | |
| Predicted class index of each window. | |
| """ | |
| self.eval() | |
| # Both running states are stateful, so windows go through them one by one, in order. | |
| windows = X.cpu().numpy() | |
| aligned = torch.from_numpy(np.stack([self.aligner(window) for window in windows])).to(X.device, X.dtype) | |
| probs = torch.stack([network(aligned).softmax(dim=1) for network in self.networks]).mean(dim=0).double().cpu().numpy() | |
| predicted = [] | |
| for window, network_probs in zip(windows, probs): | |
| members = [(TANGENT_SHARE, self.member), (1.0 - TANGENT_SHARE, self.region_member)] | |
| scores = [member(window) for _, member in members] | |
| linear = 0.0 | |
| for (share, member), score, soft_sum in zip(members, scores, self.soft_sums): | |
| # Each class score moves by how far the stream's soft-labelled mean has drifted from the training mean. | |
| shift = (PROTO_PRIOR_WINDOWS * member.class_projection + soft_sum) / (PROTO_PRIOR_WINDOWS + self.soft_count) - member.class_projection | |
| linear = linear + share * softmax(score + member.intercept - shift) | |
| corrected = self.debias((NETWORK_WEIGHT * network_probs + (1.0 - NETWORK_WEIGHT) * linear)[None])[0] | |
| self.soft_sums = [soft_sum + corrected * score for soft_sum, score in zip(self.soft_sums, scores)] | |
| self.soft_count = self.soft_count + corrected | |
| predicted.append(corrected.argmax()) | |
| return torch.tensor(predicted, device=X.device) | |
| def debias(self, probs): | |
| """Divides each window's probabilities by the running mean of the stream's, this window included. | |
| Parameters | |
| ---------- | |
| probs : ndarray, shape (n_windows, n_classes) | |
| Blended probabilities of the next windows of the stream, in order. | |
| Returns | |
| ------- | |
| ndarray, shape (n_windows, n_classes) | |
| """ | |
| n_classes = probs.shape[1] | |
| if self.prob_sum is None: | |
| self.prob_sum = np.zeros(n_classes) | |
| counts = self.n_windows + np.arange(1, len(probs) + 1) | |
| sums = self.prob_sum + np.cumsum(probs, axis=0) | |
| self.n_windows += len(probs) | |
| self.prob_sum = sums[-1] | |
| running = (DEBIAS_PRIOR_WINDOWS / n_classes + sums) / (DEBIAS_PRIOR_WINDOWS + counts)[:, None] | |
| corrected = probs / running | |
| return corrected / corrected.sum(axis=1, keepdims=True) | |
| class Solver(CompetSolver): | |
| name = "mi-stream-decoder" | |
| def load_model(self, meta): | |
| """Builds the blend from the weights files of the submission. | |
| Parameters | |
| ---------- | |
| meta : dict | |
| Input description and paths provided by Codabench. | |
| Returns | |
| ------- | |
| Blend | |
| In eval mode, on ``meta["device"]``. | |
| """ | |
| networks = [] | |
| for path in sorted(meta["submission_dir"].glob("weights_*.pt")): | |
| saved = torch.load(path, map_location=meta["device"], weights_only=True) | |
| for state_dict in saved["state_dicts"]: | |
| network = PatchTransformer(meta["n_chans"], meta["n_times"], meta["n_classes"], meta["sfreq"], saved["model_cfg"]) | |
| network.load_state_dict(state_dict) | |
| networks.append(network.eval()) | |
| with np.load(meta["submission_dir"] / "tangent.npz") as params: | |
| member = TangentMember({name: params[name] for name in params.files}, meta["sfreq"]) | |
| with np.load(meta["submission_dir"] / "regcov.npz") as params: | |
| region_member = RegionMember({name: params[name] for name in params.files}, meta["sfreq"]) | |
| COV_PRIOR_WINDOWS = 1.0 # as in the alignment the networks were trained with | |
| return Blend(networks, CausalAlign(COV_PRIOR_WINDOWS), member, region_member).to(meta["device"]).eval() | |