"""EEG encoder, raw-patch variant: raw EEG cut into 4-sample patches (30 frames/s) -> 16-layer transformer -> one 768-d vector per frame. input_values [B, 41, T] microvolts @ 120 Hz -> divide by scale_uv (23.2), clip at +-clip (8) sites a recording lacks must be zero -> non-overlapping 4-sample patches over all 41 sites [B, 41 * 4 = 164, ceil(T / 4)] (no codec, nothing learned) -> LayerNorm + Linear 164 -> 768, + learned positions (max 512 frames = 17 s; longer inputs are cut into ~10 s chunks) -> 16 pre-LN transformer layers (bidirectional) -> last_hidden_state [B, frames, 768] (after a final LayerNorm); hidden_states = embeddings + every layer's output The same architecture, objective and pretraining data as the codec-based encoder; only the input differs (raw patches instead of the codec's latent). The front-end constants (scale_uv, clip, sampling_rate, channels) are read from config.codec_config; no codec weights. Which layer to use: middle-to-late layers carry the most task information. The benchmark heads learn a softmax mix over all layers, as EEGEncoderForSequenceClassification does. """ import math from typing import Optional import numpy as np import torch import torch.nn as nn from transformers import PreTrainedModel from transformers.modeling_outputs import BaseModelOutput, SequenceClassifierOutput from .configuration_eeg import EEGEncoderConfig class Body(nn.Module): def __init__(self, zdim, d, layers, heads, ff, max_len, causal, masked): super().__init__() self.causal = causal self.inp = nn.Sequential(nn.LayerNorm(zdim), nn.Linear(zdim, d)) if masked: self.mask_emb = nn.Parameter(torch.zeros(d)) self.pos = nn.Parameter(torch.zeros(1, max_len, d)) self.layers = nn.ModuleList(nn.TransformerEncoderLayer(d, heads, ff, dropout=0.1, batch_first=True, norm_first=True) for _ in range(layers)) self.norm = nn.LayerNorm(d) def forward(self, z, frame_mask=None): h = self.inp(z.transpose(1, 2)) if frame_mask is not None: h = torch.where(frame_mask[..., None], self.mask_emb.to(h.dtype), h) n = h.shape[1] h = h + self.pos[:, :n] mask = torch.triu(torch.full((n, n), float("-inf"), device=h.device), 1) if self.causal else None outs = [h] for layer in self.layers: h = layer(h, src_mask=mask, is_causal=self.causal) outs.append(h) return outs, self.norm(h) class EEGEncoderPreTrainedModel(PreTrainedModel): config_class = EEGEncoderConfig base_model_prefix = "encoder" main_input_name = "input_values" def _init_weights(self, module): """Only the fine-tuning head is ever new; every encoder weight comes from the checkpoint.""" if isinstance(module, EEGEncoderForSequenceClassification): nn.init.zeros_(module.layer_weights) elif isinstance(module, nn.Linear) and getattr(module, "_is_head", False): nn.init.normal_(module.weight, std=0.02) nn.init.zeros_(module.bias) elif isinstance(module, nn.LayerNorm) and getattr(module, "_is_head", False): nn.init.ones_(module.weight) nn.init.zeros_(module.bias) class EEGEncoderModel(EEGEncoderPreTrainedModel): def __init__(self, config: EEGEncoderConfig): super().__init__(config) c = config self.patch_size = int(getattr(c, "patch_size", 4)) self.body = Body(c.codec.channels * self.patch_size, c.hidden_size, c.num_hidden_layers, c.num_attention_heads, c.intermediate_size, c.max_frames, c.causal, masked=not c.causal) self.post_init() @property def frame_rate(self): return self.config.codec.sampling_rate / self.patch_size def get_latent(self, input_values): """[B, 41, T] microvolts -> patches [B, 41 * 4, ceil(T / 4)] (what the encoder reads): divide by scale_uv, clip, then cut each site into non-overlapping 4-sample patches (zero-padded at the end).""" cc = self.config.codec x = (input_values / cc.scale_uv).clamp(-cc.clip, cc.clip) b, c, t = x.shape p = self.patch_size f = (t + p - 1) // p x = nn.functional.pad(x, (0, f * p - t)) return x.reshape(b, c, f, p).permute(0, 1, 3, 2).reshape(b, c * p, f) def _chunks(self, n): fr = self.frame_rate if n <= self.config.max_unchunked_seconds * fr: return [(0, n)] k = math.ceil(n / (self.config.chunk_seconds * fr)) b = np.linspace(0, n, k + 1).round().astype(int) return list(zip(b[:-1], b[1:])) def forward(self, input_values=None, latent=None, frame_mask=None, output_hidden_states: bool = False, return_dict: bool = True): """input_values [B, 41, T] microvolts (or latent [B, 164, frames] from get_latent). Inputs longer than max_unchunked_seconds are encoded in equal chunks of about chunk_seconds and concatenated.""" if latent is None: latent = self.get_latent(input_values) latent = latent.float() hs, last = [], [] for a, b in self._chunks(latent.shape[-1]): o, l = self.body(latent[..., a:b], None if frame_mask is None else frame_mask[:, a:b]) hs.append(o) last.append(l) last = torch.cat(last, 1) hidden = tuple(torch.cat([h[i] for h in hs], 1) for i in range(len(hs[0]))) if output_hidden_states else None if not return_dict: return (last, hidden) return BaseModelOutput(last_hidden_state=last, hidden_states=hidden) class EEGEncoderForSequenceClassification(EEGEncoderPreTrainedModel): """Encoder + softmax-weighted mix of every layer's output + mean over frames + linear head. num_labels == 1 -> regression (MSE); otherwise single-label classification (cross-entropy). Call freeze_encoder() for a frozen probe (only the layer weights and the head train).""" def __init__(self, config: EEGEncoderConfig): super().__init__(config) self.encoder = EEGEncoderModel(config) self.layer_weights = nn.Parameter(torch.zeros(config.num_hidden_layers)) self.dropout = nn.Dropout(config.classifier_dropout) self.norm = nn.LayerNorm(config.hidden_size) self.classifier = nn.Linear(config.hidden_size, config.num_labels) self.norm._is_head = self.classifier._is_head = True self.post_init() def freeze_encoder(self): for p in self.encoder.parameters(): p.requires_grad_(False) def forward(self, input_values=None, labels=None, latent=None, return_dict: bool = True): out = self.encoder(input_values, latent=latent, output_hidden_states=True) hs = torch.stack(out.hidden_states[1:], 0) # [L, B, F, D] w = torch.softmax(self.layer_weights, 0) h = (w[:, None, None, None] * hs).sum(0).mean(1) logits = self.classifier(self.dropout(self.norm(h))) loss = None if labels is not None: if self.config.num_labels == 1: loss = nn.functional.mse_loss(logits.squeeze(-1), labels.float()) else: loss = nn.functional.cross_entropy(logits, labels.long()) if not return_dict: return (loss, logits) if loss is not None else (logits,) return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=None)