"""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) @classmethod 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")