Feature Extraction
Transformers
Safetensors
eeg_encoder
eeg
self-supervised
foundation-model
hubert
brain-computer-interface
biosignals
custom_code
Instructions to use Neuralace-AI/eeg-encoder-41ch-120hz with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Neuralace-AI/eeg-encoder-41ch-120hz with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Neuralace-AI/eeg-encoder-41ch-120hz", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Neuralace-AI/eeg-encoder-41ch-120hz", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download modeling_eeg_codec.py from Neuralace-AI/eeg-encoder-41ch-120hz: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/Neuralace-AI/eeg-encoder-41ch-120hz/resolve/main/modeling_eeg_codec.py
- Command line
-
hf download hf://Neuralace-AI/eeg-encoder-41ch-120hz/modeling_eeg_codec.py
-
curl -L -o modeling_eeg_codec.py https://huggingface.co/Neuralace-AI/eeg-encoder-41ch-120hz/resolve/main/modeling_eeg_codec.py
10.5 kB
| """EEG codec: causal SEANet encoder -> causal transformer -> stride-2 conv -> 16-level RVQ -> mirror-image decoder. | |
| input_values [B, 41, T] microvolts @ 120 Hz | |
| -> / scale_uv, clip +-8 (the model's own front end) | |
| -> latent [B, 256, T / 4] (30 frames/s, causal) | |
| -> eeg_codes [B, num_quantizers, T / 4] (10 bits each) | |
| -> eeg_values [B, 41, T] microvolts | |
| Every convolution and attention is causal, so the codec streams: a frame depends only on the signal up to its end. | |
| Inference-only re-implementation of the training code; weight norm is folded into plain weights and each codebook is stored as its | |
| centroid matrix. Outputs match the training code to float precision (see the model card's parity test). | |
| """ | |
| import math | |
| from dataclasses import dataclass | |
| from typing import Optional | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from transformers import PreTrainedModel | |
| from transformers.utils import ModelOutput | |
| from .configuration_eeg import EEGCodecConfig | |
| class CausalConv1d(nn.Module): | |
| def __init__(self, cin, cout, k, stride=1, dilation=1): | |
| super().__init__() | |
| self.conv = nn.Conv1d(cin, cout, k, stride=stride, dilation=dilation) | |
| self.stride = stride | |
| self.pad = (k - 1) * dilation + 1 - stride | |
| def forward(self, x): | |
| T = x.shape[-1] | |
| n_frames = math.ceil(T / self.stride) | |
| extra = (n_frames - 1) * self.stride + (self.pad + self.stride) - (T + self.pad) | |
| return self.conv(F.pad(x, (self.pad, max(extra, 0)))) | |
| class CausalConvT1d(nn.Module): | |
| def __init__(self, cin, cout, k, stride): | |
| super().__init__() | |
| self.conv = nn.ConvTranspose1d(cin, cout, k, stride=stride) | |
| self.trim = k - stride | |
| def forward(self, x): | |
| y = self.conv(x) | |
| return y[..., : y.shape[-1] - self.trim] if self.trim else y | |
| class ResBlock(nn.Module): | |
| def __init__(self, dim, dilation): | |
| super().__init__() | |
| h = dim // 2 | |
| self.block = nn.Sequential(nn.ELU(), CausalConv1d(dim, h, 3, dilation=dilation), nn.ELU(), CausalConv1d(h, dim, 1)) | |
| def forward(self, x): | |
| return x + self.block(x) | |
| class SEANetEncoder(nn.Module): | |
| def __init__(self, channels, dim, n_filters, ratios): | |
| super().__init__() | |
| layers = [CausalConv1d(channels, n_filters, 7)] | |
| c = n_filters | |
| for r in ratios: | |
| layers += [ResBlock(c, 1), nn.ELU(), CausalConv1d(c, 2 * c, 2 * r, stride=r)] | |
| c *= 2 | |
| layers += [nn.ELU(), CausalConv1d(c, dim, 3)] | |
| self.net = nn.Sequential(*layers) | |
| def forward(self, x): | |
| return self.net(x) | |
| class SEANetDecoder(nn.Module): | |
| def __init__(self, channels, dim, n_filters, ratios): | |
| super().__init__() | |
| c = n_filters * 2 ** len(ratios) | |
| layers = [CausalConv1d(dim, c, 7)] | |
| for r in ratios: | |
| layers += [nn.ELU(), CausalConvT1d(c, c // 2, 2 * r, stride=r)] | |
| c //= 2 | |
| layers += [ResBlock(c, 1)] | |
| layers += [nn.ELU(), CausalConv1d(c, channels, 7)] | |
| self.net = nn.Sequential(*layers) | |
| def forward(self, z): | |
| return self.net(z) | |
| def _rope(q, k): | |
| T, hd = q.shape[-2], q.shape[-1] | |
| inv = 1.0 / (10000 ** (torch.arange(0, hd, 2, device=q.device).float() / hd)) | |
| f = torch.outer(torch.arange(T, device=q.device).float(), inv) | |
| cos, sin = f.cos().to(q.dtype), f.sin().to(q.dtype) | |
| def rot(x): | |
| x1, x2 = x[..., ::2], x[..., 1::2] | |
| return torch.stack((x1 * cos - x2 * sin, x1 * sin + x2 * cos), -1).flatten(-2) | |
| return rot(q), rot(k) | |
| class TLayer(nn.Module): | |
| def __init__(self, d, heads, ff): | |
| super().__init__() | |
| self.h = heads | |
| self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d) | |
| self.qkv, self.out = nn.Linear(d, 3 * d, bias=False), nn.Linear(d, d, bias=False) | |
| self.ff = nn.Sequential(nn.Linear(d, ff, bias=False), nn.GELU(), nn.Linear(ff, d, bias=False)) | |
| self.s1 = nn.Parameter(torch.full((d,), 0.01)) | |
| self.s2 = nn.Parameter(torch.full((d,), 0.01)) | |
| def forward(self, x, mask): | |
| B, T, D = x.shape | |
| q, k, v = self.qkv(self.n1(x)).view(B, T, 3, self.h, D // self.h).permute(2, 0, 3, 1, 4) | |
| q, k = _rope(q, k) | |
| a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) | |
| x = x + self.s1 * self.out(a.transpose(1, 2).reshape(B, T, D)) | |
| return x + self.s2 * self.ff(self.n2(x)) | |
| class CausalTransformer(nn.Module): | |
| """Causal RoPE transformer over [B, D, T] with an attention context of `context` frames.""" | |
| def __init__(self, d, layers, heads, ff, context): | |
| super().__init__() | |
| self.context = context | |
| self.layers = nn.ModuleList(TLayer(d, heads, ff) for _ in range(layers)) | |
| def forward(self, x): | |
| x = x.transpose(1, 2) | |
| i = torch.arange(x.shape[1], device=x.device) | |
| mask = (i[None, :] <= i[:, None]) & (i[:, None] - i[None, :] < self.context) | |
| for layer in self.layers: | |
| x = layer(x, mask) | |
| return x.transpose(1, 2) | |
| class Codebook(nn.Module): | |
| def __init__(self, dim, size): | |
| super().__init__() | |
| self.register_buffer("embed", torch.zeros(size, dim)) | |
| def encode(self, x): | |
| return torch.cdist(x, self.embed).argmin(-1) | |
| def decode(self, codes): | |
| return F.embedding(codes, self.embed) | |
| class RVQ(nn.Module): | |
| def __init__(self, in_dim, dim, n_q, size): | |
| super().__init__() | |
| self.n_q = n_q | |
| self.proj_in = nn.Conv1d(in_dim, dim, 1) | |
| self.proj_out = nn.Conv1d(dim, in_dim, 1) | |
| self.books = nn.ModuleList(Codebook(dim, size) for _ in range(n_q)) | |
| def encode(self, z, n_q): | |
| x = self.proj_in(z.float()) | |
| B, D, T = x.shape | |
| r = x.transpose(1, 2).reshape(-1, D) | |
| out = [] | |
| for cb in self.books[:n_q]: | |
| c = cb.encode(r) | |
| r = r - cb.decode(c) | |
| out.append(c) | |
| return torch.stack(out, 1).view(B, T, -1).transpose(1, 2) | |
| def decode(self, codes, levels=None): | |
| """codes [B, L, T]; `levels` (indices into the L rows) sums only those levels, e.g. [0] = the first level alone.""" | |
| B, L, T = codes.shape | |
| levels = range(L) if levels is None else levels | |
| q = sum(self.books[i].decode(codes[:, i].reshape(-1)) for i in levels) | |
| return self.proj_out(q.view(B, T, -1).transpose(1, 2)) | |
| class EEGCodecEncoderOutput(ModelOutput): | |
| """eeg_codes [B, num_quantizers, frames] (int64, 0-1023); latent [B, 256, frames], the continuous pre-quantizer latent.""" | |
| eeg_codes: Optional[torch.LongTensor] = None | |
| latent: Optional[torch.FloatTensor] = None | |
| class EEGCodecDecoderOutput(ModelOutput): | |
| """eeg_values [B, 41, T] microvolts.""" | |
| eeg_values: Optional[torch.FloatTensor] = None | |
| class EEGCodecOutput(ModelOutput): | |
| eeg_values: Optional[torch.FloatTensor] = None | |
| eeg_codes: Optional[torch.LongTensor] = None | |
| latent: Optional[torch.FloatTensor] = None | |
| class EEGCodecPreTrainedModel(PreTrainedModel): | |
| config_class = EEGCodecConfig | |
| base_model_prefix = "codec" | |
| main_input_name = "input_values" | |
| def _init_weights(self, module): | |
| pass # every weight comes from the checkpoint | |
| class EEGCodecModel(EEGCodecPreTrainedModel): | |
| def __init__(self, config: EEGCodecConfig): | |
| super().__init__(config) | |
| c = config | |
| self.encoder = SEANetEncoder(c.channels, c.dim, c.n_filters, c.ratios) | |
| self.enc_tf = CausalTransformer(c.dim, c.t_layers, c.t_heads, c.t_ff, c.context) | |
| self.down = CausalConv1d(c.dim, c.dim, 4, stride=2) | |
| self.quantizer = RVQ(c.dim, c.codebook_dim, c.n_q, c.codebook_size) | |
| self.up = CausalConvT1d(c.dim, c.dim, 4, stride=2) | |
| self.dec_tf = CausalTransformer(c.dim, c.t_layers, c.t_heads, c.t_ff, c.context) | |
| self.decoder = SEANetDecoder(c.channels, c.dim, c.n_filters, c.ratios) | |
| self.post_init() | |
| def frame_rate(self): | |
| return self.config.frame_rate | |
| def front(self, x): | |
| """Microvolts -> model units (divide by scale_uv, clip at +-clip). Sites a recording lacks must be zero.""" | |
| return (x / self.config.scale_uv).clamp(-self.config.clip, self.config.clip) | |
| def get_latent(self, input_values): | |
| """[B, 41, T] microvolts -> continuous latent [B, 256, ceil(T / 4)] (what the encoder reads).""" | |
| return self.down(self.enc_tf(self.encoder(self.front(input_values)))) | |
| def _decode_latent(self, zq, length=None): | |
| x = self.decoder(self.dec_tf(self.up(zq))) * self.config.scale_uv | |
| return x if length is None else x[..., :length] | |
| def encode(self, input_values, num_quantizers: Optional[int] = None, return_dict: bool = True): | |
| """[B, 41, T] microvolts -> eeg_codes [B, num_quantizers, frames] (+ the continuous latent). num_quantizers 1-16 sets the | |
| bitrate: 0.3 kbps per level.""" | |
| n = num_quantizers or self.config.n_q | |
| z = self.get_latent(input_values) | |
| codes = self.quantizer.encode(z, n) | |
| return EEGCodecEncoderOutput(codes, z) if return_dict else (codes, z) | |
| def decode(self, eeg_codes, length: Optional[int] = None, return_dict: bool = True): | |
| """eeg_codes [B, L, frames] (any number of leading levels L) -> eeg_values [B, 41, frames * 4] microvolts, cut to `length`.""" | |
| x = self._decode_latent(self.quantizer.decode(eeg_codes), length) | |
| return EEGCodecDecoderOutput(x) if return_dict else (x,) | |
| def dequantize(self, eeg_codes, levels=None): | |
| """eeg_codes -> the latent a decoder rebuilds from them [B, 256, frames]; `levels` picks a subset of the levels.""" | |
| return self.quantizer.decode(eeg_codes, levels) | |
| def forward(self, input_values, num_quantizers: Optional[int] = None, return_dict: bool = True): | |
| """Encode then decode. num_quantizers=0 skips quantization (the decoder on the continuous latent: the codec's best fidelity).""" | |
| T = input_values.shape[-1] | |
| z = self.get_latent(input_values) | |
| if num_quantizers == 0: | |
| q = self.quantizer | |
| x, codes = self._decode_latent(q.proj_out(q.proj_in(z.float())), T), None | |
| else: | |
| codes = self.quantizer.encode(z, num_quantizers or self.config.n_q) | |
| x = self._decode_latent(self.quantizer.decode(codes), T) | |
| return EEGCodecOutput(x, codes, z) if return_dict else (x, codes, z) | |