eeg-encoder-41ch-120hz / modeling_eeg_encoder.py
shangeth's picture
Initial release
d4279d2 verified
Raw History Blame Contribute Delete
6.64 kB
"""EEG encoder: the frozen codec's continuous latent (30 frames/s) -> 16-layer transformer -> one 768-d vector per frame.
input_values [B, 41, T] microvolts @ 120 Hz
-> codec.get_latent (frozen, causal) [B, 256, T / 4]
-> LayerNorm + Linear 256 -> 768, + learned positions (max 512 frames = 17 s; longer inputs are cut into ~10 s chunks)
-> 16 pre-LN transformer layers (bidirectional unless config.causal)
-> last_hidden_state [B, frames, 768] (after a final LayerNorm); hidden_states = embeddings + every layer's output
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
from .modeling_eeg_codec import EEGCodecModel
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 and codec 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.codec = EEGCodecModel(c.codec)
self.body = Body(c.codec.dim, 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.frame_rate
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, 256, frames] from codec.get_latent). The codec is frozen: no gradient
flows into it. Inputs longer than max_unchunked_seconds are encoded in equal chunks of about chunk_seconds and concatenated."""
if latent is None:
with torch.no_grad():
latent = self.codec.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)