Feature Extraction
Transformers
Safetensors
spera
eeg
biosignal
time-series
foundation-model
self-supervised-learning
representation-learning
transformer
jepa
neuroscience
brain-computer-interface
neurips-2026
custom_code
Eval Results (legacy)
Instructions to use sees4321/SPERA_EEG with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use sees4321/SPERA_EEG with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="sees4321/SPERA_EEG", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("sees4321/SPERA_EEG", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download modeling_spera.py from sees4321/SPERA_EEG: direct link, hf CLI and curl.
- Browser
- Download file 4 kB
-
https://huggingface.co/sees4321/SPERA_EEG/resolve/main/modeling_spera.py
- Command line
-
hf download hf://sees4321/SPERA_EEG/modeling_spera.py
-
curl -L -o modeling_spera.py https://huggingface.co/sees4321/SPERA_EEG/resolve/main/modeling_spera.py
4 kB
| """Transformers wrapper around the unchanged SPERA encoder (Transformers 5.3+).""" | |
| from __future__ import annotations | |
| import json | |
| import math | |
| from pathlib import Path | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from transformers import PreTrainedModel, initialization as init | |
| from transformers.modeling_outputs import BaseModelOutputWithPooling | |
| from .config import EEGModelConfig | |
| from .configuration_spera import SperaConfig | |
| from .encoder import EEGEncoder | |
| from .layers import MultiheadSelfAttentionRoPE, build_rope_cache | |
| from .spatial import CoordMLPEmbedding, LegendreAnchor, PairwiseLegendreBias | |
| class SperaModel(PreTrainedModel): | |
| config_class = SperaConfig | |
| base_model_prefix = "encoder" | |
| main_input_name = "eeg" | |
| _no_split_modules = ["DividedSpatiotemporalBlock", "FullAttentionBlock"] | |
| def __init__(self, config: SperaConfig): | |
| super().__init__(config) | |
| self.encoder = EEGEncoder(config.to_eeg_config()) | |
| self.post_init() | |
| def _init_weights(self, module): | |
| # Match native initialization, including custom parameters and RoPE | |
| # buffers omitted from state_dict. HF helpers preserve loaded tensors | |
| # when from_pretrained initializes only missing weights/buffers. | |
| if isinstance(module, nn.Linear): | |
| bound = 1 / math.sqrt(module.in_features) | |
| init.uniform_(module.weight, -bound, bound) | |
| if module.bias is not None: | |
| init.uniform_(module.bias, -bound, bound) | |
| elif isinstance(module, nn.LayerNorm): | |
| init.ones_(module.weight) | |
| init.zeros_(module.bias) | |
| elif isinstance(module, CoordMLPEmbedding): | |
| init.constant_(module.emb_w, self.config.coord_w_init) | |
| elif isinstance(module, PairwiseLegendreBias) and module.coeff is not None: | |
| init.zeros_(module.coeff) | |
| elif isinstance(module, LegendreAnchor): | |
| anchors = F.normalize(torch.randn_like(module.anchors), dim=-1) | |
| init.copy_(module.anchors, anchors) | |
| init.zeros_(module.coeff) | |
| elif isinstance(module, MultiheadSelfAttentionRoPE) and module.rotary_dim > 0: | |
| cos, sin = build_rope_cache( | |
| self.config.max_tokens, module.rotary_dim, self.config.rope_theta, | |
| module._rope_cos.device, module._rope_cos.dtype, | |
| ) | |
| init.copy_(module._rope_cos, cos) | |
| init.copy_(module._rope_sin, sin) | |
| def from_encoder_pretrained(cls, checkpoint_dir): | |
| """Convert a native config.json + pytorch_model.bin without retraining.""" | |
| checkpoint_dir = Path(checkpoint_dir) | |
| config = EEGModelConfig.from_json(str(checkpoint_dir / "config.json")) | |
| preprocessing_file = checkpoint_dir / "evaluation_preprocessing.json" | |
| preprocessing = json.loads(preprocessing_file.read_text()) if preprocessing_file.exists() else None | |
| model = cls(SperaConfig(**config.to_dict(), evaluation_preprocessing=preprocessing)) | |
| state = torch.load(checkpoint_dir / "pytorch_model.bin", map_location="cpu", weights_only=True) | |
| model.encoder.load_state_dict(state, strict=True) | |
| return model.eval() | |
| def forward(self, eeg: torch.Tensor, coords: torch.Tensor, return_dict=None): | |
| """Encode preprocessed EEG [B,C,T] with matching coordinates [B,C,3]. | |
| Returns last_hidden_state [B,C*P,D] (channel-major token order) and | |
| pooler_output [B,D] (mean over tokens, without a classifier or head norm). | |
| Normalization, resampling and coordinate scaling are caller operations. | |
| """ | |
| hidden = self.encoder(eeg, coords) | |
| pooled = hidden.mean(dim=1) | |
| return_dict = self.config.return_dict if return_dict is None else return_dict | |
| if not return_dict: | |
| return hidden, pooled | |
| return BaseModelOutputWithPooling(last_hidden_state=hidden, pooler_output=pooled) | |
| SperaModel.register_for_auto_class("AutoModel") | |