IntroductionSleep stage classification is an important task in neuroscience and preclinical research because it provides a structured framework for linking neural activity to behavior, physiology, and disease mechanisms1. Accurate staging is essential for interpreting electrophysiological signals, quantifying sleep architecture, and comparing results across experiments and species. In preclinical models, sleep staging enables the investigation of how pharmacological interventions alter brain function in a controlled setting, supporting mechanistic insights that are difficult to obtain in humans2.Deep learning approaches have substantially advanced automated sleep stage classification3. However, models may inadvertently learn subject-specific characteristics (individual baseline activity patterns, electrode impedances, or amplifier gain settings) rather than sleep stage patterns that generalize across these nuisance factors4. This overfitting manifests as high in-distribution performance coupled with substantial degradation when models encounter data from previously unseen subjects or conditions5.Pharmacological interventions introduce particularly structured domain shifts. Psychoactive substances systematically alter neuronal excitability and neuromodulatory tone, producing predictable changes in EEG spectral content and EMG amplitude6,7. For example, serotonergic compounds such as psilocybin suppress REM sleep and alter slow-wave activity, while 5-HT2A antagonists such as MDL100907 produce distinct changes in EEG power spectra that can shift the marginal feature distributions underlying a classifier’s decision boundaries. Models trained on control recordings may therefore fail on pharmacologically manipulated data, even when the underlying sleep stage identities are preserved.Prior deep learning methods for automated sleep staging (including convolutional architectures8, residual networks9, and attention-based models3) have demonstrated strong within-dataset performance but are predominantly evaluated using random train-test splits that preserve the training distribution. Few studies have systematically investigated performance under the structured distribution shifts arising from novel subjects or pharmacological conditions5. Contrastive representation learning10 and adversarial domain adaptation11 offer principled frameworks for learning invariant representations, but their combined utility for treatment-aware sleep staging in preclinical settings remains unexplored.Throughout this work, we distinguish two related but non-identical properties. Domain invariance refers to representations that remain stable under nuisance shifts, corresponding to differences in subject identity, recording hardware, or baseline physiology that are uncorrelated with sleep stage content. Pharmacological robustness denotes the narrower, operationally measurable property that classification performance is preserved when the feature distribution is shifted by a pharmacological intervention. A fully domain-invariant model is pharmacologically robust, but cross-treatment generalization does not require complete domain invariance.We address this robustness challenge through three complementary strategies: (1) a Global Context Vector providing an explicit memory bank across temporal sequences; (2) supervised contrastive learning to structure the embedding space according to sleep stage semantics while suppressing nuisance variability; and (3) domain-aware training with gradient reversal layers to discourage the encoding of subject- and treatment-specific features. We evaluate robustness under controlled domain-shift scenarios using subject-aware cross-validation, ensuring validation subjects are entirely withheld from training.Our contributions are: (i) a dual-branch architecture combining window-level feature extraction with Transformer-based contextual reasoning enhanced by a Global Context Vector; (ii) demonstration that contrastive learning improves out-of-distribution performance within the same experimental preparation, particularly for cross-treatment generalization; and (iii) systematic ablation quantifying the individual contributions of each architectural and training component.Related workAutomated sleep stage classificationEarly automated sleep staging relied on handcrafted spectral and time-domain features fed into classical classifiers such as support vector machines and random forests2. Deep learning substantially advanced the field by replacing manual feature engineering with learned representations. Convolutional architectures such as DeepSleepNet8 demonstrated that raw EEG could be staged end-to-end with competitive accuracy. Residual network variants such as SlumberNet9 extended this with skip connections for deeper feature hierarchies, while attention-based models such as AttnSleep3 introduced multi-head self-attention to capture inter-frequency relationships within a single epoch. MC-SleepNet12 addressed multi-channel inputs explicitly through parallel per-channel branches. Despite these advances, most methods are designed for human polysomnography with standardized montages and are evaluated with random train-test splits that preserve the subject distribution, leaving generalization to novel subjects or recording conditions largely unexamined.Domain generalization and subject variabilityA recurring finding in EEG-based classification is that models overfit to subject-specific spectral characteristics rather than learning task-relevant features that transfer across individuals4,5. Adversarial domain adaptation11 provides one principled response: a gradient reversal layer trains the feature extractor to produce representations that are uninformative with respect to domain identity while remaining discriminative for the target task. This approach has been applied to EEG-based emotion recognition and motor imagery decoding but has seen limited use in sleep staging, particularly in preclinical settings where pharmacological manipulations introduce additional systematic distribution shifts beyond ordinary inter-subject variability6,7.Barger et al.13 addressed distributional shift for rodent sleep scoring through mixture z-scoring, a preprocessing method that disentangles nuisance variability (arising from inter-subject recording differences) from class-balance variability (arising from pharmacological alterations in the proportion of time spent in each sleep stage). Standard per-recording z-scoring is shown to introduce systematic classification bias whenever test-set class proportions differ from those in the training set; mixture z-scoring corrects this by estimating class-conditional normalization statistics from a small labeled calibration sample per subject. The present framework differs in that robustness is achieved at the representation-learning level, through architectural choices (GCV, bidirectional cross-attention) and training objectives (contrastive loss, gradient reversal), rather than at the preprocessing level, eliminating the per-subject annotation overhead associated with mixture z-scoring calibration.Contrastive and self-supervised representation learningSupervised contrastive learning10 extends the self-supervised contrastive framework to the labeled setting by treating all samples sharing a class label as positive pairs, producing embedding spaces with compact intra-class clusters and well-separated inter-class boundaries. This approach has improved generalization in vision and audio tasks by reducing sensitivity to input perturbations that preserve class identity. In EEG analysis, self-supervised pretraining on unlabeled recordings has been used to learn transferable representations5, but combining supervised contrastive objectives with classification in a joint training framework, particularly for multi-class, multi-domain sleep staging, remains underexplored.Preclinical sleep stagingRodent sleep staging presents distinct challenges relative to human polysomnography: recording montages are non-standard, session durations are longer, and pharmacological manipulations are integral to the experimental design. Most automated methods for rodent staging rely on simple threshold-based or classical machine learning approaches applied to power spectral features, with limited use of deep learning2. Several purpose-built automated tools for rodent sleep scoring have reached widespread use: SPINDLE14 applies a CNN with a hidden Markov model to multi-channel EEG/EMG spectrograms and demonstrates cross-lab and cross-species generalization across multiple cohorts; AccuSleep13 pairs a compact CNN with mixture z-scoring, requiring only a few minutes of manual annotation per subject for calibration; and Sleep-deep-learner15 and Somnivore16 provide further automated pipelines validated on diverse rodent datasets with retraining support for new recording configurations. Despite this breadth of available tools, cross-condition generalization under systematic pharmacological perturbation, which is essential for practical deployment in drug-discovery experiments, has not been evaluated in prior work, and no study has examined the combined effect of contrastive representation learning, global context integration, and domain-aware training in this setting.MethodsFig. 1Full size imageOverall training pipeline. 4-second EEG/EMG windows (4 channels, 2000 samples each) are processed by a 1D ResNeXt-29 backbone interleaved with Bidirectional Cross-Attention modules that fuse CNN features with a Global Context Vector (GCV). Two parallel classification branches share the same embeddings: Branch 1 (window classifier) produces per-window logits without temporal context; Branch 2 (contextual classifier) passes the full 1-minute sequence through a 4-layer Transformer encoder before classifying each window. During training only, domain adaptation heads (subject and treatment classifiers) are attached via gradient reversal layers, and a supervised contrastive loss structures the embedding space. Domain adaptation heads and Branch 1 are inactive at inference timeAnimals and recordingsAdult male Long-Evans rats (\(N=13\); 280–350 g at the beginning of the experiment; Charles River, Germany) were implanted with DSI 4ET biotelemetric devices17 under isoflurane anesthesia (induction 3–4%, administered via inhalation chamber, maintenance 1.5–2%, administered via nose cone). Analgesia was provided by meloxicam (0.15 mg/kg s.c., administered intraoperatively and for one week post-surgery; 0.15 mg/kg p.o.). Postoperatively, animals were also administered antibiotic therapy with Enrobactin (5 mg/kg p.o. twice daily for one week).Three EEG electrodes were placed over the frontal associative (F1), primary somatosensory (P1), and primary visual (V1) cortices with corresponding cerebellar references, targeting cortical regions with well-characterized sleep-stage-specific oscillatory signatures (frontal slow waves, parietal spindles, occipital alpha/delta). Electrodes were implanted at the following stereotaxic coordinates relative to Bregma: F1 (AP \(+4.8\) mm, ML \(-1.3\) mm), P1 (AP \(-3.0\) mm, ML \(+3.9\) mm), and V1 (AP \(-5.6\) mm, ML \(+3.9\) mm).EMG was recorded from dorsal neck musculature to capture the atonia characteristic of REM sleep. Animals were allowed a minimum of two weeks to recover from surgery before recordings commenced. Signals were sampled at 500 Hz and recorded continuously for up to 24 hours following drug administration, with recordings beginning at the onset of the light phase to standardize circadian phase across sessions. At the end of the study, animals were euthanized by isoflurane overdose (5% induction, sustained until loss of consciousness and cardiac arrest) followed by decapitation as a secondary method to ensure death. Animals weighed 430–500 g and were 6–7 months of age at the time of euthanasia. All procedures were performed in accordance with applicable ethical guidelines and approved institutional protocols (see Ethics statement). Humane endpoints were established prior to the start of the study. Animals were removed (N=3) from the experiment if they showed signs of implant-site infection, excessive weight loss (>20% body weight), or other indicators of severe distress.Pharmacological treatmentsA within-subject cross-over design was used with four conditions: psilocybin (5 mg/kg s.c.), MDL100907 (0.5 mg/kg s.c.), their combination, and vehicle control (physiological saline). Conditions were combined with sleep manipulation (undisturbed or sleep-deprived), with randomized ordering and sufficient washout between sessions. The resulting dataset contains over 1.1 M annotated 4-second segments distributed as follows: Wake (43.8%), NREM (43.5%), REM (12.3%), and Artifact (0.3%).Sleep stage annotationAll recordings were scored into four stages by two expert annotators with extensive experience in rodent EEG/EMG analysis. Recordings were visualized and navigated using Somnivore software16 (version 1.1.14; Somnivore Pty Ltd, somnivore.ai); because the automated stage assignments produced by the software required substantial manual correction to achieve acceptable accuracy, all final labels should be regarded as expert-generated annotations, with the software serving primarily as a display and epoch-navigation interface.Scoring criteria followed standard rodent polysomnography conventions. Wake was defined by low-amplitude, high-frequency desynchronized EEG across all cortical channels accompanied by elevated EMG amplitude. NREM sleep was characterized by high-amplitude, delta-dominant (0.5–4 Hz) synchronized EEG, most prominent in frontal and parietal derivations, with EMG amplitude reduced relative to wake but not absent. REM sleep was identified by low-amplitude, theta-dominant (5–9 Hz) EEG with near-complete EMG atonia, occasionally interrupted by brief myoclonic twitches. Artifact epochs were defined by signal clipping, movement-induced transients exceeding 5 standard deviations above the recording-session channel mean, electrode disconnection signatures, or waveforms inconsistent with any physiological state.To establish inter-annotator reliability, a randomly selected subset of recordings spanning all subjects and treatment conditions was independently scored by both annotators; agreement was quantified using Cohen’s \(\kappa\). Double-scoring continued until inter-annotator agreement on a held-out verification set exceeded a pre-specified threshold of \(\kappa =0.80\). The observed agreement on this set reached \(\kappa =0.84\) (four-stage scoring).Once this threshold was met, the remaining recordings were each assigned to a single annotator, with assignments distributed approximately equally between the two. Disagreements within the double-scored subset were resolved through consensus discussion. Annotators were not blinded to treatment condition; this is acknowledged as a potential limitation in that awareness of the treatment condition could, in principle, introduce expectation-driven label bias, though epoch-level scoring from raw EEG/EMG waveforms is largely objective for the vast majority of unambiguous epochs.Model architectureThe model (Figure 1) is a modified 1D ResNeXt-2918 with grouped convolutions (cardinality=32), Group Normalization19 (8 groups), and GELU activations replacing the original batch normalization and ReLU. The backbone produces 512-dimensional embeddings from each 4-second window. The feature extraction modules and the overall classifier structure are illustrated in Figures 2 and 3.The four input channels (EEG-F1, EEG-P1, EEG-V1, EMG) are stacked along the channel dimension, presenting a tensor of shape (4, 2000) to the network. Initial signal processing uses a single Conv1D block with 64 output channels, kernel size 51, stride 2, and padding 25 (preserving temporal length after striding), followed by Group Normalization (8 groups), GELU, and max-pooling (kernel size 3, stride 2). This gives a receptive field of approximately 100 ms, well matched to the timescale of dominant sleep oscillations. The ResNeXt-29 backbone processes features through three stages of channel dimensions (64, 128, 256), each with 3 bottleneck blocks, cardinality 32, and base width 4. Within each bottleneck the grouped convolution branch width is \(\lfloor C/64 \rfloor \times \text {base\_width} \times \text {cardinality}\), with expansion factor 2. Each stage except the first applies a stride-2 convolution in its first block to halve temporal resolution. A final linear projection maps the 256-dimensional stage-3 output to a 512-dimensional embedding via global average pooling followed by a linear layer (no normalization or activation after the projection).Fi. 2Full size imageFeature extraction modules. Left: The input block applies a Conv1D (64 channels, kernel 51, stride 2) followed by Group Normalization (8 groups), GELU, and max-pooling (kernel 3, stride 2), mapping the raw \((4{\times }2000)\) input to a \((64{\times }500)\) feature map. Center: Three ResNeXt-29 stages (cardinality 32; channel widths 64, 128, 256; 3 bottleneck blocks each) extract hierarchical temporal features with stride-2 downsampling at stages 2 and 3; global average pooling and a linear projection produce 512-dimensional per-window embeddings. Right: The Bidirectional Cross-Attention module, interleaved after each ResNeXt stage, fuses CNN embeddings with the GCV (dimension 128) through sequential intra-modality self-attention, bidirectional CNN\({\leftrightarrow }\)GCV cross-attention, and position-wise feed-forward updates with residual connections and layer normalizationFig. 3Full size imageClassifier architecture. Three ResNeXt stages alternate with three Bidirectional Cross-Attention modules. The 512-dimensional backbone embedding for each window is concatenated with the 128-dimensional GCV output (640 dimensions total). Branch 1 (window classifier): a 3-layer MLP (hidden dimension 128, dropout 0.3) independently maps each 640-dimensional embedding to 4-class logits without temporal context (training weight \(w=0.01\)). Branch 2 (contextual classifier): a linear projection to 512 dimensions is followed by learnable positional embeddings and a 4-layer Transformer encoder (8 heads, feedforward dimension 2048, dropout 0.3, pre-norm); a two-layer head produces 4-class logits for each window with access to the full 1-minute sequence (training weight \(w=0.99\)). Only Branch 2 predictions are used at inference timeGlobal context vector and bidirectional cross-attentionA learnable 1D Global Context Vector (GCV) of dimension \(d_\text {GCV}=128\) is maintained for each window in the recording sequence, processed in parallel with the CNN embeddings to provide a memory bank for storing global, sequence-level features. Three initialization strategies were evaluated: all-zeros, manually extracted spectral features, and learned weights from a truncated normal distribution (\(\sigma =0.02\)); all-zeros initialization was selected following ablation.After each of the three ResNeXt stages, a Bidirectional Cross-Attention module fuses the CNN embeddings (dimension \(d_\text {CNN} \in \{64, 128, 256\}\) at stages 1–3 respectively) with the GCV. All query, key, and value projections for the CNN\(\,\rightarrow\) GCV and GCV\(\,\rightarrow\) CNN cross-attention paths map to \(d_\text {CNN}\) (the stage-specific CNN dimension), so projection matrix dimensions are \(\textbf{W}_{q}^{c\rightarrow g} \in \mathbb {R}^{d_\text {CNN} \times d_\text {CNN}}\), \(\textbf{W}_{k,v}^{c\rightarrow g} \in \mathbb {R}^{d_\text {GCV} \times d_\text {CNN}}\), and the GCV output projection maps back: \(\textbf{W}_\text {out}^{g\rightarrow c} \in \mathbb {R}^{d_\text {CNN} \times d_\text {GCV}}\). The per-head dimension is \(d_k = d_\text {CNN} / 8\). The CNN self-attention uses 8 heads; the GCV self-attention uses the largest divisor of \(d_\text {GCV}=128\) that is \(\le 8\), which is 8 heads. The module fuses the two streams in five sequential steps.Temporal positional encoding: Learnable positional embeddings \(\textbf{PE}_{\text {CNN}} \in \mathbb {R}^{N \times d_{\text {CNN}}}\) and \(\textbf{PE}_{\text {GCV}} \in \mathbb {R}^{N \times d_{\text {GCV}}}\) are added to both feature streams to encode temporal ordering across the sequence (maximum \(N=512\) windows):$$\begin{aligned} \textbf{F}_{\text {CNN}}^{\text {pos}} = \textbf{F}_{\text {CNN}} + \textbf{PE}_{\text {CNN}}[:, :N, :], \quad \textbf{F}_{\text {GCV}}^{\text {pos}} = \textbf{F}_{\text {GCV}} + \textbf{PE}_{\text {GCV}}[:, :N, :] \end{aligned}$$Intra-modality self-attention: Each stream undergoes multi-head self-attention (8 heads for CNN features) to model inter-window relationships before cross-modal interaction:$$\begin{aligned} \begin{aligned} \textbf{F}_{\text {CNN}}^{\text {self}} = \text {SelfAttn}_{\text {CNN}}(\textbf{F}_{\text {CNN}}^{\text {pos}})&\rightarrow \textbf{F}_{\text {CNN}}^{\text {norm}} = \text {LayerNorm}(\textbf{F}_{\text {CNN}}^{\text {pos}} + \textbf{F}_{\text {CNN}}^{\text {self}})\\ \textbf{F}_{\text {GCV}}^{\text {self}} = \text {SelfAttn}_{\text {GCV}}(\textbf{F}_{\text {GCV}}^{\text {pos}})&\rightarrow \textbf{F}_{\text {GCV}}^{\text {norm}} = \text {LayerNorm}(\textbf{F}_{\text {GCV}}^{\text {pos}} + \textbf{F}_{\text {GCV}}^{\text {self}}) \end{aligned} \end{aligned}$$Bidirectional cross-attentionTwo complementary cross-attention operations enable bidirectional information flow between the two streams. In the CNN\(\,\rightarrow \,\)GCV direction, CNN features act as queries attending to GCV keys and values; in the GCV\(\,\rightarrow \,\)CNN direction the roles are reversed:$$\begin{aligned} \begin{aligned} \text {CNN}\rightarrow \text {GCV}:\;&\textbf{Q}_{c\rightarrow g} = \textbf{W}_q^{c\rightarrow g}\textbf{F}_{\text {CNN}}^{\text {norm}},\quad \textbf{K}_{c\rightarrow g} = \textbf{W}_k^{c\rightarrow g}\textbf{F}_{\text {GCV}}^{\text {norm}},\quad \textbf{V}_{c\rightarrow g} = \textbf{W}_v^{c\rightarrow g}\textbf{F}_{\text {GCV}}^{\text {norm}},\\ \text {GCV}\rightarrow \text {CNN}:\;&\textbf{Q}_{g\rightarrow c} = \textbf{W}_q^{g\rightarrow c}\textbf{F}_{\text {GCV}}^{\text {norm}},\quad \textbf{K}_{g\rightarrow c} = \textbf{W}_k^{g\rightarrow c}\textbf{F}_{\text {CNN}}^{\text {norm}},\quad \textbf{V}_{g\rightarrow c} = \textbf{W}_v^{g\rightarrow c}\textbf{F}_{\text {CNN}}^{\text {norm}}. \end{aligned} \end{aligned}$$The attention outputs are computed as \(\textbf{A}_{c\rightarrow g} = \text {softmax}\!\left( \textbf{Q}_{c\rightarrow g}\textbf{K}_{c\rightarrow g}^T/\sqrt{d_k}\right) \textbf{V}_{c\rightarrow g}\) and symmetrically for \(\textbf{A}_{g\rightarrow c}\). All attention operations use a dropout rate of 0.1.Feed-forward networks and residual connections: Both streams are updated through position-wise feed-forward networks (intermediate dimension \(4\times\) input dimension) with residual connections and layer normalization:$$\begin{aligned} \begin{aligned} \textbf{F}_{c/g}'&= \text {LayerNorm}\!\left( \textbf{F}_{c/g}^{\text {norm}} + \textbf{A}_{(c,g)\rightarrow (g,c)}\right) ,\\ \textbf{F}_{c/g}^{\text {out}}&= \text {LayerNorm}\!\left( \textbf{F}_{c/g}' + \textbf{W}_2^{c/g}\,\text {GELU}\!\left( \textbf{W}_1^{c/g}\textbf{F}_{c/g}'\right) \right) . \end{aligned} \end{aligned}$$Finally, the updated CNN features are added back to the pre-attention representation to preserve gradient flow through the convolutional pathway:$$\begin{aligned} \textbf{F}_{\text {CNN}}^{\text {final}} = \textbf{F}_{\text {CNN}}^{\text {original}} + \textbf{F}_{\text {CNN}}^{\text {out}}. \end{aligned}$$Dual-branch classificationThe model employs two parallel classification heads operating at different levels of temporal abstraction. The window classifier (Branch 1) is a 3-layer MLP (Linear–GELU–Dropout–Linear–GELU–Dropout–Linear) with a hidden dimension of 128 and a dropout rate of 0.3, mapping individual 512-dimensional embeddings (concatenated with the 128-dimensional GCV output, giving a 640-dimensional input) to 4-class logits without access to temporal context. The contextual classifier (Branch 2) first projects the concatenated 640-dimensional input back to 512 dimensions via a linear layer, adds learnable positional embeddings, and then processes the sequence through a Transformer encoder, comprising 4 layers, 8 attention heads, a feedforward dimension of 2048, a dropout rate of 0.3, and pre-layer normalization, before producing 4-class logits via a two-layer head (Linear–GELU–Dropout–Linear) with a hidden dimension of 512. Classification losses are weighted as \(w_\text {window}=0.01\) and \(w_\text {contextual}=0.99\), reflecting the primacy of contextual predictions while retaining the window-level signal as a regularizer.Loss functionsThe primary classification objective is cross-entropy with label smoothing (\(\alpha =0.025\)). Label smoothing converts one-hot labels into soft targets \(\hat{y} = (1-\alpha )y + \alpha /N_c\), reducing overconfident predictions. The combined cross-entropy loss over both branches is:$$\begin{aligned} \mathscr {L}_{\text {CE}} = - \frac{1}{N} \sum _{i=1}^{N} \sum _{c=1}^{N_c} \hat{y}_{i,c} \log \!\left( \hat{p}_{i,c}\right) , \end{aligned}$$weighted as \(w_\text {contextual}=0.99\) for the contextual classifier and \(w_\text {window}=0.01\) for the window classifier.As an auxiliary objective, supervised contrastive loss10 (SupCon, weight 0.5) is added to structure the embedding space. For each training step, the batch is passed through the network twice: once with standard augmentation and once with independently sampled augmentations. This produces two sets of \(\ell _2\)-normalized 512-dimensional embeddings; the augmented copy of each window is always treated as a positive pair, and all windows sharing the same sleep stage label across both sets are additionally treated as positives. For each anchor \(\textbf{z}_i\), the loss is:$$\begin{aligned} \mathscr {L}_{\textrm{SupCon}} = \sum _{i=1}^{N} \frac{-1}{|P(i)|} \sum _{p \in P(i)} \log \frac{ \exp \!\left( \textbf{z}_i^\top \textbf{z}_p / \tau \right) }{ \sum _{a \ne i} \exp \!\left( \textbf{z}_i^\top \textbf{z}_a / \tau \right) }, \end{aligned}$$where P(i) is the set of positive indices, \(\tau =0.07\) is the temperature, and the sum in the denominator runs over all \(2N-1\) other samples in the concatenated batch. The SupCon loss is applied directly to the backbone embeddings without a separate projection head. The total training loss is:$$\begin{aligned} \mathscr {L}_\text {total} = \mathscr {L}_\text {CE} + 0.5 \cdot \mathscr {L}_\text {SupCon}. \end{aligned}$$For the domain adaptation ablation, two additional cross-entropy losses are computed from lightweight domain classifier heads (3-layer MLP, hidden dimension 128, dropout 0.3): one predicting subject identity (\(N_\text {subject}=13\) classes) and one predicting treatment condition (\(N_\text {treatment}=4\) classes). These losses are back-propagated through gradient reversal layers11, which negate the gradient entering the feature extractor during the backward pass, pushing it to produce domain-invariant embeddings. This component is not present in the default model and was only used in the ablation reported in Table 4.Optimization: All models were trained for 100 epochs with a batch size of 64 using AdamW20 (\(\eta =10^{-5}\), weight decay \(10^{-5}\), \(\beta _{1,2}=(0.9, 0.999)\)). Gradient norms were clipped at a threshold of \(\tau =1.0\):$$\begin{aligned} \widetilde{\nabla \mathscr {L}} = \nabla \mathscr {L}\, \min \!\left( 1,\;\frac{\tau }{\Vert \nabla \mathscr {L} \Vert _2}\right) . \end{aligned}$$The learning rate follows Cosine Annealing with Warm Restarts21, with a cycle length \(T_0\) equal to one pass through the training data \(T_\text {mult}=1\) (constant cycle length across restarts), and a minimum learning rate \(\eta _\text {min} = 0.01\,\eta\). An additional ReduceLROnPlateau scheduler multiplies \(\eta\) by \(\gamma =0.5\) if the validation loss does not improve for 5 consecutive epochs, after which the cosine scheduler is reset with the new maximum learning rate.Software and implementation: All models were implemented in Python 3.11.13 with PyTorch 2.8.0 (pytorch.org). Signal preprocessing used SciPy 1.16.2 (scipy.org) and NumPy 2.3.3 (numpy.org); classical baselines, handcrafted-feature extraction, and evaluation metrics used scikit-learn 1.7.2 (scikit-learn.org); figures were produced with Matplotlib 3.10.6 (matplotlib.org).Signal preprocessingEEG signals were band-pass filtered (1–49 Hz) to retain cortical oscillations while suppressing line noise; EMG was high-pass filtered at 1 Hz to remove slow drift artifacts. All filtering was performed using zero-phase digital filters to avoid phase distortion. Signals were segmented into non-overlapping 4-second windows to match expert annotations, yielding 2000 samples per window at 500 Hz.Before training, samples were normalized per-subject-channel pair to mitigate inter-subject variability in signal amplitude. Normalization first clips the signal at the 99.5th percentile to reduce the influence of high-amplitude transients, then applies z-score normalization:$$\begin{aligned} \hat{x}_c^i = \frac{x_c^i - \mu _c^i}{\sigma _c^i}, \end{aligned}$$where \(\mu _c^i\) and \(\sigma _c^i\) are the mean and standard deviation computed over all non-artifact windows for subject i, channel c. This per-subject normalization ensures the model is exposed to amplitude-normalized signals during training, reducing the risk of overfitting to subject-specific gain settings while preserving the relative spectral structure within each recording. To address the severe class imbalance of the artifact class (0.3% of windows), training batches were constructed using stratified sampling to ensure representation of all four classes in each batch; no additional loss reweighting was applied beyond label smoothing.Data augmentationEach augmentation is applied independently and is physiologically motivated: Gaussian noise (\(p=0.2\)) simulates recording artifacts; amplitude scaling in [0.95, 1.05] (\(p=0.1\)) promotes invariance to inter-subject gain differences; circular temporal shift of up to 40 ms (\(p=0.1\)) encourages invariance to exact epoch alignment; channel dropout (\(p=0.05\)) improves robustness to single-channel failures; and polarity inversion (\(p=0.05\)) addresses variability in electrode polarity conventions. Augmentations are designed to preserve sleep stage identity: shifts are small relative to the dominant oscillation periods, amplitude scaling is conservative to avoid spectral distortion, and channel dropout retains at least three of the four channels. During contrastive learning, Gaussian noise is always applied, and other augmentation probabilities are doubled to increase pairwise diversity within a batch while preserving sleep stage identity, as stronger augmentation is required to generate meaningfully distinct positive pairs.Channel dropout should be interpreted primarily as a regularization mechanism that prevents the model from relying on any single input modality and encourages distributed feature learning across channels. The current architecture assumes all four input channels are present at inference time and does not implement a missing-channel inference mode; deployment with a permanently absent channel would require architectural modifications such as learned masking tokens or separate per-channel inference pathways, and is not tested here.Evaluation: Two distinct evaluation regimes are reported. (1) Subject-held-out cross-validation: subject-aware 5-fold cross-validation in which no subject appears in both training and validation sets; this is the primary evaluation used for all model comparisons, ablations, and data-efficiency analyses. (2) Saline-only training, cross-condition transfer: an otherwise identical subject-held-out 5-fold cross-validation in which the training set is restricted to saline-condition recordings only, while the held-out subjects are evaluated on their recordings under each pharmacological condition. The subject-aware fold structure of regime (1) is preserved, so no subject appears in both training and validation; the only difference from regime (1) is that the pharmacological conditions are withheld from training. This isolates whether representations learned from control recordings alone transfer to pharmacologically perturbed physiology in unseen subjects, and is therefore simultaneously a cross-subject and a cross-condition test.For regime (1), the 13 subjects were assigned to folds of sizes 3, 3, 3, 2, 2; fold boundaries were fixed before any experiment and held constant across all ablations. Metrics (accuracy, precision, recall, F1, ROC-AUC) were macro-averaged across the four classes and then averaged across folds. Statistical significance of pairwise model comparisons used the Nadeau & Bengio corrected resampled t-test22 at \(\alpha =0.05\), which accounts for the non-independence of cross-validation folds. All reported performance metrics reflect per-window predictions from the contextual classifier (Branch 2); the window classifier (Branch 1) contributes only to the training objective and is not evaluated independently on the held-out set. The five folds (containing 3, 3, 3, 2, and 2 subjects, respectively) are treated as equally weighted when computing the reported mean and standard deviation across folds.BaselinesThree neural network baselines were evaluated: SlumberNet9, AttnSleep3, and MC-SleepNet12, each adapted to 4-channel inputs and trained with the same routine. SlumberNet was extended by instantiating four parallel copies of its single-channel residual branch, one per input channel, with the resulting four feature vectors concatenated along the channel dimension before the global average pooling layer and classification head; this preserves the per-channel residual structure while pooling information from all four modalities at the head stage. AttnSleep was adapted by replacing its original single-channel input convolution with a single convolution whose input dimension was set to 4, fusing all channels at the earliest convolutional stage; this does not preserve the intended per-channel multi-resolution design of the original AttnSleep, as inter-channel relationships are collapsed at the input rather than after independent per-channel feature extraction. MC-SleepNet’s multi-channel design required only adjusting the expected number of input channels. These adaptations are pragmatic rather than optimal: in particular, AttnSleep’s input convolution modification does not preserve its original per-channel attention design, which may partially explain its lower performance relative to the other neural baselines. A more principled adaptation would process each channel through a separate branch and fuse the resulting embeddings, analogous to the MC-SleepNet design; we opted for the simpler adaptation to minimize architecture-specific tuning that could differentially benefit individual baselines. All neural network baselines were trained with the same AdamW optimizer, learning rate schedule, and data augmentation pipeline as the proposed model to ensure a fair comparison. Logistic Regression and Random Forest classifiers trained on handcrafted features (band power across delta, theta, alpha, sigma, and beta bands; zero-crossing rate; and approximate entropy as a measure of signal complexity) served as classical baselines. Features were extracted per channel and concatenated, yielding a 97-dimensional feature vector per 4-second window.Temporal interpretability via Grad-CAMTo interpret which time points within the recording drive the model’s per-window classifications, we applied Gradient-weighted Class Activation Mapping (Grad-CAM23) to the deepest convolutional stage of the 1D ResNeXt backbone. An entire recording sequence is passed through the model as a single batch of shape (1, N, 4, T), where N is the number of 4-second windows, 4 the number of channels, and \(T=2000\) the samples per window. For window i, the back-propagation target is the contextual-branch logit of its ground-truth class \(y_i\)$$z_i = \text {logit}^{\text {ctx}}_{i,\,y_i},$$so that for misclassified windows, the map reflects evidence for the true rather than the predicted stage. Because the full sequence is processed jointly and the target is the contextual logit, the resulting saliency is shaped by the entire model, including the inter-window self-attention and the GCV fusion, rather than by each window in isolation.Forward and backward hooks were registered on the final residual stage (layer3; 256 channels), whose temporal resolution is \(T/16 \approx 125\) samples after the input block’s two stride-2 operations (Conv1D and max-pool) and the stride-2 downsampling in ResNeXt stages 2 and 3. Let \(A^k \in \mathbb {R}^{T/16}\) denote the activation of channel k and \(\partial z_i/\partial A^k\) the corresponding gradient. Channel-importance weights are obtained by global average pooling the gradient over time,$$\alpha ^k = \frac{1}{T/16}\sum _{t} \frac{\partial z_i}{\partial A^k_t},$$and the raw saliency map is$$\textrm{CAM}_i = \textrm{ReLU}\!\left( \sum _k \alpha ^k A^k\right) \in \mathbb {R}^{T/16},$$which is min–max normalized to [0, 1] and upsampled to the window length T by linear interpolation, yielding a per-sample saliency signal \(s_i \in [0,1]^T\). Because the sequence is processed jointly, \(\textrm{CAM}_i\) is a context-aware map over window i’s own time axis: it quantifies which moments within each epoch the contextual model relied on, with cross-window and GCV information already incorporated through both the forward and backward passes. For visualization, saliency is encoded as the line width of each channel trace.ResultsUnless otherwise noted, all tables and figures in this section report results under Regime 1 (subject-held-out 5-fold cross-validation, training and evaluation across all treatment conditions combined; see Methods for regime definitions). Results under Regime 2 (saline-only training with the subject-held-out folds of Regime 1 retained, evaluated across pharmacological conditions) are labelled explicitly.Proposed model performanceThe complete proposed model combines the dual-branch ResNeXt architecture with a zero-initialized GCV, Transformer-based contextual processing, supervised contrastive learning, and physiological data augmentation. It achieves 94.4% accuracy, 94.3% F1, and a ROC-AUC of 0.993 (mean ± SD across 5 folds: Accuracy \(0.944\pm 0.008\), F1 \(0.943\pm 0.008\), ROC-AUC \(0.993\pm 0.001\)). The low standard deviation across folds (below 1% for all metrics) is notable given that each fold withholds entirely different subjects; it indicates that performance does not depend strongly on which specific animals are held out, suggesting the model has learned generalizable stage-discriminating features rather than fitting to the idiosyncratic patterns of a majority of subjects. The confusion matrix (Figure 4) shows per-class recall ranging from 88.2% (Artifact) to 99.8% (NREM), with minimal confusion within NREM and moderate misclassification between Wake and REM. The lower Artifact recall is expected given the very small class proportion (0.3% of data) and the heterogeneous appearance of artifacts, which can superficially resemble any sleep stage. The high NREM recall reflects the dominance of slow-wave activity, a highly consistent spectral signature that is well-captured by the early convolutional layers. The 99.8% NREM recall does not indicate NREM functioning as a default prediction class: the model is trained with class-balanced batches and label-smoothed cross-entropy, providing no structural incentive to favour any particular class. As shown in Figure 6B, boundary-region misclassifications predominantly involve Wake/REM confusions rather than systematic absorption of ambiguous epochs into NREM. However, the Transformer contextual encoder may reinforce NREM predictions in transitional epochs embedded within extended NREM bouts, as temporal smoothing is an inherent property of sequence models applied to physiologically autocorrelated data; this expected behavior is distinct from a pathological default-class bias.Comparison with baseline modelsOur model achieves 94.3% F1 compared to SlumberNet’s9 87.0% and Random Forest’s 87.9%, representing improvements of 7.3 and 6.4 percentage points, respectively. This improvement is statistically significant for both SlumberNet (\(t=13.863\), \(p=0.0001\)) and Random Forest (\(t=2.996\), \(p=0.0401\)), using the Nadeau & Bengio corrected resampled t-test22. Because statistical significance alone can be driven by the large sample size, we additionally report effect sizes (Cohen’s d) computed from the per-fold F1 distributions; the gain over SlumberNet corresponds to \(d=11.5\) and the gain over Random Forest to \(d=2.7\), both far exceeding the conventional threshold for a large effect (\(d=0.8\)) and indicating that the improvements are of substantial practical magnitude rather than marginal. Effect sizes for all pairwise comparisons against the proposed model are reported in Table 2. Notably, Random Forest exhibits severe overfitting (99.9% training vs. 88.1% validation F1), reflecting its tendency to memorize subject-specific signal statistics rather than learn sleep stage patterns that transfer across individuals. Neural network baselines show more balanced but still inferior performance, with AttnSleep performing worst (80.1% F1); this is consistent with its single-channel design being less suited to multimodal 4-channel inputs, though it should be noted that the pragmatic input-convolution adaptation used here may not fully preserve its intended architecture. Detailed results are provided in Table 1.Table 1 Validation performance of baseline models compared to the proposed model. Mean ± standard deviation at the best validation epoch.Full size tableTable 2 Pairwise effect sizes of the proposed model relative to each baseline, computed as Cohen’s d on the per-fold macro-F1 distributions (pooled standard deviation).Full size tableAblation studiesGlobal context vectorThe GCV provides the largest single improvement: a 2.3% F1 gain (25.3% error reduction) over the no-GCV baseline. All-zeros initialization outperforms both manual feature initialization and learned initialization, suggesting the model benefits from the flexibility to learn task-specific global representations (Table 3).Table 3 Effect of GCV initialization strategy.Full size tableContrastive learning and domain adaptationSupervised contrastive learning yields consistent improvements of \(\sim\)0.6% F1 (8.2% error reduction), complementing the direct class supervision of cross-entropy by explicitly structuring the embedding space. Gradient reversal layers for domain adaptation provide negligible additional benefit, suggesting that GCV and contrastive learning together already achieve effective domain invariance. Both results are summarized in Table 4.Table 4 Impact of contrastive learning and domain adaptation via gradient reversal.Full size tableCross-treatment generalizationThis section reports results under evaluation regime (2): a saline-only training, cross-condition transfer test that retains the subject-held-out fold structure of regime (1). Within each fold the model is trained only on the saline-condition recordings of the training subjects, and the held-out subjects are evaluated on their recordings under each pharmacological condition. No subject appears in both training and validation, so the regime tests cross-subject and cross-condition generalization simultaneously: the model must generalize both to unseen animals and to pharmacological states absent from training. The only difference from regime (1) is that all pharmacological recordings are withheld from the training set. Restricting training to saline recordings in this way yields less than 1% degradation across all metrics (F1: \(0.937\pm 0.010\) vs. \(0.943\pm 0.008\) full-dataset baseline). The result is nonetheless notable: psilocybin24 and MDL10090725 produce substantial changes in EEG power spectra and behavioral state that could plausibly destabilize a naive classifier, yet the model maintains robust performance. The small residual degradation is partly attributable to the reduced training set size under saline-only training rather than to an inability to handle pharmacological distribution shift. To assess this, we compared saline-only training against a size-matched random subsample of the full dataset; the saline-only model performed comparably to the size-matched baseline, supporting the interpretation that data quantity rather than domain mismatch drives the residual gap. This result suggests that subject-aware contrastive training on control recordings is sufficient to acquire representations that transfer reliably to unseen subjects’ recordings under pharmacological perturbation, at least for compounds sharing a serotonergic mechanism; generalization to mechanistically distinct agents remains an open question addressed in the limitations.Per-condition results are reported in Table 5. Performance was lowest under psilocybin (F1 0.932), consistent with its pronounced REM-suppressant action and the consequent reduction in REM exemplars and altered theta-band dynamics, and highest under the 5-HT2A antagonist MDL100907 (F1 0.946), whose spectral signature departs least from the saline training distribution; the combination condition fell between the two (F1 0.939). Across all conditions, per-subject variability remained modest (subject-level F1 standard deviation below 0.015 in every condition), indicating that the observed robustness is not driven by a small number of well-fit animals but holds broadly across the cohort.Table 5 Cross-treatment generalization by pharmacological condition.Full size tableData efficiencyThe model achieves reasonable performance (\(>88\%\) accuracy, F1 0.832) with as little as 1 hour of annotated training data. Performance improves substantially up to 8 hours (F1 0.921) and plateaus thereafter: 12 hours yields F1 0.919 and 24 hours yields F1 0.918, while the full dataset (\(\approx\)1000 hours) yields F1 0.943. The 8–12 hour regime thus represents \(\approx\)1% of the full dataset while providing only 2.4% lower F1 than training on the complete corpus, demonstrating highly practical data efficiency.Fig. 4Full size imageNormalized confusion matrix (%) for four-class sleep-stage classification (Wake, Artifact, REM, NREM). Prediction counts were accumulated over all held-out validation windows across the five subject-aware cross-validation folds and then normalized row-wise; each cell reports the percentage of true-class windows (rows) classified as each column class. Per-class recall on the diagonal: Wake (94.9%), Artifact (88.2%), REM (93.8%), NREM (99.8%). The most prominent off-diagonal confusions occur between Wake and REM, reflecting their physiological similarity in transitional epochs. Regime 1.Quantitative representation invarianceTo complement the qualitative UMAP projections (Figure 6) with a quantitative measure, we trained linear probes (multinomial logistic regression) on the frozen 512-dimensional backbone embeddings to decode three targets: sleep stage, subject identity, and treatment condition. Probes were fit and evaluated under the same subject-held-out folds and scored with balanced accuracy to correct for class imbalance. Sleep stage was highly linearly decodable from the proposed encoder’s embeddings (balanced accuracy 0.912), confirming that stage information is directly accessible in the representation. In contrast, subject identity (balanced accuracy 0.130; chance \(1/13=0.077\)) and treatment condition (0.312; chance 0.25) were decodable only marginally above chance, indicating that these nuisance factors are largely, though not entirely, suppressed. Critically, an ablated encoder trained without supervised contrastive learning and without the GCV exhibited substantially higher subject (0.214) and treatment (0.421) decodability at comparable stage decodability, demonstrating that these components actively reduce the encoding of domain-specific information rather than merely preserving stage discriminability (Table 6).Table 6 Linear-probe decodability (balanced accuracy) of sleep stage, subject identity, and treatment condition from frozen embeddings.Full size tableTemporal saliencyTo interpret the model’s decisions, we computed context-aware Grad-CAM saliency (see Methods, “Temporal Interpretability via Grad-CAM”) over representative recording stretches spanning saline and pharmacological conditions, displayed continuously across several consecutive windows (Figure 5). Because the full sequence is processed jointly and the saliency target is the contextual-branch logit, the resulting maps reflect the complete model, including inter-window self-attention and GCV fusion, rather than isolated per-window features. Saliency concentrated on epochs at state transitions (e.g., NREM\(\rightarrow\)REM and wake\(\rightarrow\)NREM boundaries) and, under pharmacological conditions, on segments whose waveform morphology departed most from the surrounding baseline, rather than distributing uniformly across the sequence. As these are the regions where local, window-level features are most ambiguous, the pattern is consistent with the contextual model relying on global sequence information precisely where single-window evidence is weakest, offering a mechanistic account of how global context integration contributes to robustness. We note that the per-window maps localize which moments the contextual model relied on rather than isolating the direction of inter-epoch information flow; an explicit epoch-to-epoch routing analysis (e.g., cross-window input gradients \(\partial z_i/\partial A_{j\ne i}\)) is left to future work.Fig. 5Full size imageContext-aware Grad-CAM temporal saliency across consecutive 4-second windows. The four channel traces (EEG-F1, EEG-P1, EEG-V1, EMG) are shown over a representative recording stretch; line width encodes per-sample saliency, obtained by back-propagating each window’s contextual-branch logit for its ground-truth class to the deepest ResNeXt stage. Because the whole sequence is processed jointly, the maps reflect the full contextual model (inter-window self-attention and GCV fusion), not isolated per-window features; thicker segments mark the time points most influential for the model’s stage assignment. Regime 1.DiscussionThe Global Context Vector emerges as the most impactful architectural component, improving F1 by 2.3% and reducing the error rate by 25.3%. This result indicates that an explicit memory bank for storing sequence-level features enables better integration of contextual information across the recording, a mechanism that standard window-by-window classifiers lack. The GCV effectively allows early ResNeXt stages to be informed by the global state of the recording, enabling context-sensitive feature extraction rather than purely local pattern matching. An analogy is that a human scorer does not evaluate each 4-second epoch in isolation: they use knowledge of the preceding sleep history, the current phase of the night, and the recent trajectory of spectral activity to resolve ambiguous epochs. The GCV provides the model with a structural analog of this global awareness. Notably, all-zeros initialization outperforms both manual feature initialization and learned initialization. The underperformance of manual feature initialization suggests that hand-crafted spectral summaries impose a representation misaligned with the joint optimization landscape of the cross-attention modules, whereas zero initialization allows the GCV to develop a representation shaped entirely by the training signal. The marginal underperformance of learned initialization may reflect a similar effect: a pre-committed random starting point introduces implicit biases that conflict with the cross-attention pathway during early training.Fig. 6Full size imageUMAP visualization of learned latent representations. (A) colored by sleep stage, showing clear cluster separation. (B) colored by prediction correctness; misclassifications occur predominantly at class boundaries. (C) colored by subject identity, indicating substantial inter-subject overlap and subject-invariant representations. (D) colored by treatment condition, demonstrating clustering driven by sleep stage rather than treatment effects. Regime 1.Supervised contrastive learning provides consistent but modest improvements (0.6% F1, 8.2% error reduction). The relatively small magnitude is consistent with cross-entropy already encouraging discriminative representations through direct class supervision; contrastive learning provides complementary benefits by explicitly organizing the embedding space. UMAP visualization (Figure 6) is consistent with embeddings clustering primarily by sleep stage rather than by subject identity or treatment condition, supporting treatment-invariant representation learning; this is corroborated quantitatively by the linear-probe analysis (Table 6), in which subject and treatment identity are decodable only marginally above chance while sleep stage remains highly decodable. Misclassifications predominantly occur at class boundaries, consistent with the inherently continuous nature of sleep transitions.Domain adaptation via gradient reversal layers provides negligible additional benefit. This could indicate that the combination of contrastive learning and GCV-based contextual integration already achieves substantial domain invariance, rendering explicit adversarial domain confusion redundant. An alternative explanation is that gradient reversal introduces conflicting optimization pressures in this multi-class, multi-domain setting. Regardless of the mechanism, the finding is practically useful: the simpler model without domain adaptation heads achieves equivalent performance, reducing architectural complexity and training costs. Future work with alternative domain adaptation strategies (such as maximum mean discrepancy minimization or conditional adversarial networks) could clarify whether this reflects a fundamental ceiling or a limitation specific to the gradient reversal approach.Cross-treatment generalization results (\(88\%\) accuracy) with only 1 hour of annotations and asymptotic performance at 8-12 hours. The 8-12 hour regime represents approximately 1% of the full dataset yet yields only 2.4% lower F1 than training on the complete corpus.Several limitations should be noted. Evaluation is conducted on a single dataset from one laboratory using adult male Long-Evans rats from a single supplier, limiting applicability to other recording protocols, electrode configurations, sexes, ages, or species. The treatment diversity does not capture the full range of pharmacological mechanisms: psilocybin and MDL100907 both target the serotonergic system, and future work should evaluate performance on compounds with entirely distinct modes of action (e.g., GABAergic, dopaminergic, or glutamatergic agents). The maximum sequence length of \(N=512\) windows (approximately 34 minutes) constrains the contextual classifier from reasoning over full sleep cycles; hierarchical architectures or more efficient attention schemes26 could extend the effective temporal receptive field without proportional computational cost.The present approach is complementary to rather than a replacement for established rodent sleep staging tools such as AccuSleep13, SPINDLE14, Sleep-deep-learner15, and Somnivore16. Those tools offer well-validated, accessible pipelines, often with retraining or per-subject calibration workflows, that provide excellent performance under standard recording conditions. The distinct contribution here is the demonstration that architecture- and training-level design choices can produce pharmacologically robust representations without per-subject calibration, targeting scenarios where annotating each new drug condition is impractical. A direct performance comparison against these tools on the pharmacological dataset would require providing per-subject calibration data for mixture z-scoring-based approaches and performing per-dataset retraining for the others; such a comparison is an important direction for future work. External validation on a dataset from an independent laboratory would further strengthen generalizability claims; however, no publicly available preclinical rodent dataset currently combines multi-channel EEG/EMG recordings, expert-annotated sleep stages, and systematic pharmacological manipulation across multiple compounds in the same subjects, the combination that defines the challenge addressed here. The absence of such a benchmark is itself a gap in the field, and making the present dataset available (see Data Availability) is intended as a step toward enabling future cross-lab comparisons. Additionally, the per-subject amplitude normalization used here, which uses all non-artifact epochs to compute normalization statistics, is a form of standard z-scoring; as shown by Barger et al.13, this can introduce systematic classification bias when pharmacological treatment substantially alters class proportions, suggesting that incorporating mixture z-scoring as a preprocessing complement to the current training strategy could further reduce cross-treatment degradation.Data availabilityThe full dataset cannot be made publicly available at submission because it forms part of ongoing studies. Representative sample recordings, annotations, and metadata are available at https://zenodo.org/records/18725151. The full dataset is available from the corresponding author upon reasonable request, subject to approval by the National Institute of Mental Health in Klecany and, where applicable, a data-use agreement. Code is available at https://github.com/achopus/GCVSleep; trained model weights are available at https://zenodo.org/records/18725231.ReferencesPatel, A. K., Reddy, V., Shumway, K. R. & Araujo, J. F. Physiology, sleep stages. In StatPearls (StatPearls Publishing, Treasure Island (FL), 2025).Rayan, A. et al. Sleep scoring in rodents: Criteria, automatic approaches and outstanding issues. Eur. J. Neurosci. 59, 526–553 (2024).Article CAS PubMed Google Scholar Eldele, E. et al. An attention-based deep learning approach for sleep stage classification with single-channel eeg. IEEE Trans. Neural Syst. Rehabil. Eng. 29, 809–818. https://doi.org/10.1109/TNSRE.2021.3076234 (2021).Article PubMed Google Scholar Geirhos, R. et al. Shortcut learning in deep neural networks. Nat. Mach. Intell. 2, 665–673. https://doi.org/10.1038/s42256-020-00257-z (2020).Article Google Scholar Wara, T. U., Fahad, A. H., Das, A. S. & Shawon, M. M. H. A systematic review on sleep stage classification and sleep disorder detection using artificial intelligence. Heliyon 11, e43576. https://doi.org/10.1016/j.heliyon.2025.e43576 (2025).Article Google Scholar Mang, G. M. & Franken, P. Sleep and eeg phenotyping in mice. Curr. Protocol. Mouse Biol. 2, 55–74 (2012).Article PubMed Google Scholar Krystal, A. D. Sleep therapeutics and neuropsychiatric illness. Neuropsychopharmacology 45, 166–175 (2020).Article PubMed Google Scholar Supratak, A., Dong, H., Wu, C. & Guo, Y. Deepsleepnet: A model for automatic sleep stage scoring based on raw single-channel eeg. IEEE Trans. Neural Syst. Rehabil. Eng. 25, 1998–2008. https://doi.org/10.1109/tnsre.2017.2721116 (2017).Article PubMed Google Scholar Jha, P. K., Valekunja, U. K. & Reddy, A. B. Slumbernet: Deep learning classification of sleep stages using residual neural networks. Sci. Rep. 14, 4797 (2024).Article ADS CAS PubMed PubMed Central Google Scholar Khosla, P. arXiv:2004.11362 Supervised contrastive learning. (2021).Ganin, Y. & Lempitsky, V. Unsupervised domain adaptation by backpropagation arXiv:1409.7495. (2015).Yamabe, M. et al. Mc-sleepnet: large-scale sleep stage scoring in mice by deep neural networks. Sci. Rep. 9, 15793 (2019).Article ADS PubMed PubMed Central Google Scholar Barger, Z., Frye, C. G., Liu, D., Dan, Y. & Bouchard, K. E. Robust, automated sleep scoring by a compact neural network with distributional shift correction. PLOS ONE 14, e0224642. https://doi.org/10.1371/journal.pone.0224642 (2019).Article CAS PubMed PubMed Central Google Scholar Miladinović, D. et al. SPINDLE: End-to-end learning from EEG/EMG to extrapolate animal sleep scoring across experimental settings, labs and species. PLOS Comput. Biol. 15, e1006968. https://doi.org/10.1371/journal.pcbi.1006968 (2019).Article CAS PubMed PubMed Central Google Scholar Katsuki, F., Spratt, T. J., Brown, R. E., Basheer, R. & Uygun, D. S. Sleep-deep-learner is taught sleep–wake scoring by the end-user to complete each record in their style. Sleep Adv.5, zpae022 (2024).Allocca, G., Freestone, D., Johnston, L. & Gundlach, A. “somnivore’’, a user-friendly platform for automated sleep scoring of animal and human polysomnography data. Sleep Med. 40, e11–e12. https://doi.org/10.1016/j.sleep.2017.11.026 (2017).Article Google Scholar International, D. S. Dsi implantable telemetry specification overview. https://www.datasci.com/products/implantable-telemetry/specification-overview. (2026).Xie, S., Girshick, R., Dollár, P., Tu, Z. & He, K. Aggregated residual transformations for deep neural networks arXiv:1611.05431. (2017).Wu, Y. & He, K. Group normalization arXiv:1803.08494. (2018).Loshchilov, I. & Hutter, F. Decoupled weight decay regularization arXiv:1711.05101. (2019).Loshchilov, I. & Hutter, F. Sgdr: Stochastic gradient descent with warm restarts arXiv:1608.03983. (2017).Nadeau, C. & Bengio, Y. Inference for the generalization error. Adv. Neural Infor. Processi. Syst.12 (1999).Selvaraju, R. R. et al. Grad-CAM: Visual explanations from deep networks via gradient-based localization. In Proceedings of the IEEE International Conference on Computer Vision (ICCV), 618–626, https://doi.org/10.1109/ICCV.2017.74 (2017).Vejmola, Č et al. Psilocin, lsd, mescaline, and dob all induce broadband desynchronization of eeg and disconnection in rats with robust translational validity. Transl. Psychiatr. 11, 506 (2021).Article CAS PubMed PubMed Central Google Scholar Morairty, S. R., Hedley, L., Flores, J., Martin, R. & Kilduff, T. S. Selective 5ht2a and 5ht6 receptor antagonists promote sleep in rats. Sleep 31, 34–44 (2008).Article PubMed PubMed Central Google Scholar Choromanski, K. Rethinking attention with performers (2020) arXiv:2009.14794 arXiv preprint.Download referencesAcknowledgementsWe thank Josef Dvořáček for technical support and Kembe Chona, Lucie Ladislavová, Hynek Danda, Martin Toman, Valentýna Dušková, and Barbara Mallarino for their assistance with data collection.FundingThis work was supported by Czech Technical University student grant [SGS25/151/OHK3/3T/13] (V.B.); Charles University Cooperatio-Neuroscience [RVO 00023752] (K.A.); Ministry of the Interior of the Czech Republic [VK01010212] (V.B., K.A., K.Š., Č.V., T.P.), Ministry of Education, Youth and Sport of the Czech Republic [CZ.02.01.01/00/22_008/0004643] (Č.V., T.P.) and Czech Science Foundation [23-07578K] (Č.V., K.Š., T.P.) as well as private funds via PSYRES Psychedelic Research Foundation (psyresfoundation.eu).Author informationAuthors and AffiliationsCzech Institute of Informatics, Robotics and Cybernetics, Jugoslávských partyzánů 1580/3, Praha 6, Czech RepublicVojtěch Brejtr & Lenka LhotskáCharles University, Third Faculty of Medicine, Ruská 87, Praha 10, Czech RepublicKristýna Aleksić & Tomáš PáleníčekNational Institute of Mental Health in Klecany, Topolová 748, Klecany, Czech RepublicVojtěch Brejtr, Kristýna Aleksić, Klára Šíchová, Čestmír Vejmola & Tomáš PáleníčekAuthorsVojtěch BrejtrView author publicationsSearch author on:PubMed Google ScholarKristýna AleksićView author publicationsSearch author on:PubMed Google ScholarKlára ŠíchováView author publicationsSearch author on:PubMed Google ScholarČestmír VejmolaView author publicationsSearch author on:PubMed Google ScholarTomáš PáleníčekView author publicationsSearch author on:PubMed Google ScholarLenka LhotskáView author publicationsSearch author on:PubMed Google ScholarContributionsConceptualization, methodology, software, formal analysis, visualization, and writing (original draft): V.B. Investigation/data collection: V.B., K.Š., K.A. Data curation: K.A., Č.V. Writing (review and editing): L.L., K.Š. Supervision: L.L. Funding acquisition: T.P.Corresponding authorCorrespondence to Lenka Lhotská.Ethics declarationsCompeting interestsTomáš Páleníček declares shares in ``Psyon s.r.o.'' and ``Společnost pro podporu neurovědního výzkumu s.r.o.'', the founding of PSYRES-Psychedelic Research Foundation, consulting fees from GH Research and CB21-Pharma, and involvement in clinical trials with psilocybin, MDMA, 5-MeO-DMT, and ketamine outside the submitted work. The remaining authors declare no competing interests.Ethical approvalAll procedures followed the principles of laboratory animal care of the National Committee for the Care and Use of Laboratory Animals (Czech Republic) and the Guidelines of the European Union (2010/63/EU). The institutional ethics committee (the Committee for the Care and Use of Laboratory Animals) at the National Institute of Mental Health (NUDZ) in Klecany, first approved the study protocol for the Care and Use of Laboratory Animals, which was subsequently authorized by the Ministry of Health of the Czech Republic as the national competent authority (MZDR 17637/2020-4/OVZ).Additional informationPublisher’s noteSpringer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.Rights and permissionsOpen Access This article is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License, which permits any non-commercial use, sharing, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons licence, and indicate if you modified the licensed material. You do not have permission under this licence to share adapted material derived from this article or parts of it. The images or other third party material in this article are included in the article’s Creative Commons licence, unless indicated otherwise in a credit line to the material. If material is not included in the article’s Creative Commons licence and your intended use is not permitted by statutory regulation or exceeds the permitted use, you will need to obtain permission directly from the copyright holder. To view a copy of this licence, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.Reprints and permissionsAbout this article