Google Research Style Architecture Overview

SimDINOv2 for 12-Lead Electrocardiography

Visualizing 3D tensor batch representation, temporal patch projection, multi-crop view extractions, and joint self-supervised distillation for ECG representation learning.

xECG (Lunelli et al., 2025) arXiv:2509.10151 bench-xecg Official Architecture
1

Input Tensor Representation in 3D Space

Mini-batch: \(B=128\) ECGs • Visualized for \(B=3\)
Standard 12-lead electrocardiography records simultaneous electrical potential differences across the myocardium from 12 distinct anatomical viewpoints. In a typical training mini-batch on GPU, the input data forms a 3-dimensional tensor \(\mathbf{X} \in \mathbb{R}^{B \times 12 \times T}\) (e.g. \([128, 12, 5000]\) samples for 10-second continuous recordings at \(500\,\mathrm{Hz}\); illustrated below for \(B=3\) patient sheets):
  • Time \(T\) (\(X\)-axis): Continuous temporal progression (\(0.0\,\mathrm{s} \to 10.0\,\mathrm{s}\)) containing recurring P-QRS-T cardiac cycles.
  • 12 Leads (\(Y\)-axis): 6 Limb leads (I, II, III, aVR, aVL, aVF) measuring frontal vector projections + 6 Precordial leads (V1–V6) measuring horizontal transverse plane vectors.
  • Batch \(B\) (\(Z\)-axis): \(B=128\) independent patient recordings stacked in GPU memory for parallel matrix operations.
↑ 12 Leads (Y)
⤨ Batch items: B=3 (Z)
Time T (X) →
Sheet 3 (ECG Recording 3) \([12, T=5000]\)
Lead I
Lead II
Sheet 2 (ECG Recording 2) \([12, T=5000]\)
Lead I
Lead II
Sheet 1 (ECG Recording 1) • Active ECG in Mini-batch Patient 1 • \([12, T=5000]\)
Lead I
Lead II
Lead V1
Lead V5
+ Leads III, aVR, aVL, aVF, V2, V3, V4, V6 (12 Leads total) Tensor: [B=3, C=12, T=5000] · 500 Hz (10.0s recording)
Pipeline Flow 1 → 2 Transition to Signal Domain Augmentations: The network does not train on the unedited 10-second recording directly. In the DataLoader (PretrainDataset), each continuous 12-lead signal \([12, T]\) is augmented with physical sensor variations and sampled into multi-scale temporal crops (Global & Local views).
2

Multi-Crop View Extraction & Waveform Augmentations

Continuous Raw 12-Lead Signal Domain
In the xECG self-supervised distillation framework, multi-crop view sampling and physical waveform augmentations operate directly on the continuous 12-lead raw signal \([12, T]\) in the data loader before any temporal patch tokenization takes place:
Continuous 12-Lead Recording Canvas (from Step 1: Duration T = 10.0s / 5000 samples)
Lead I Lead II Lead V1
t = 0.0s (start) Full 12-Lead Continuous Recording [12, T = 5000] • Simultaneous Multi-Channel Signal t = 10.0s (end)
Global Views (~80% duration of 10s recording = 4000 samples • Fed to Student & Teacher): Batch Slot Fill: 100% (0 Pad)
Global View 1 (~80% duration • t = 0.4s → 8.4s • 4000 samples) Fed to Student & Teacher
Global View 2 (~80% duration • t = 1.6s → 9.6s • 4000 samples) Fed to Student & Teacher
Local Views (~40% duration = 2000 samples • Fed to Student Only): 🎲 Stochastic: \(t_{\mathrm{start}} \sim \mathcal{U}(0, T - L_{\mathrm{crop}})\) • Batch Slot: 50% (+ 2000 Zero-Pad)
Each crop offset is drawn independently at random per iteration — non-sequential, partially overlapping, and capturing arbitrary heartbeats:
Local Crop 1 (Random \(t = 1.2\mathrm{s} \to 5.2\mathrm{s}\) • 2000 smp) Student Only
Local Crop 2 (Random \(t = 5.5\mathrm{s} \to 9.5\mathrm{s}\) • 2000 smp) Student Only
Local Crop 3 (Random \(t = 0.3\mathrm{s} \to 4.3\mathrm{s}\) • 2000 smp) Student Only
Local Crop 4 (Random \(t = 3.4\mathrm{s} \to 7.4\mathrm{s}\) • 2000 smp) Student Only
Physical Signal Augmentations (Applied per crop in DataLoader):
⚡ Stochastic Lead Dropout

Randomly zeroes out 1–3 leads (e.g. Lead III \(\to 0\)), simulating detached ECG electrodes and forcing cross-lead reconstruction.

〰 Baseline Wander

Injects low-frequency sinusoidal drift (\(0.15\text{–}0.5\,\mathrm{Hz}\)), simulating patient respiration and thoracic impedance shifts.

📊 Gaussian Noise & EMG

Adds zero-mean high-frequency jitter simulating skeletal muscle tremor and electrical noise during telemetry.

↕ Amplitude Scaling

Multiplies leads by scale factor \(\alpha \in [0.8, 1.2]\) simulating chest geometry and skin conductance differences.

Recurrent Alignment & Flatline Zero-Padding in Continuous Domain Continuous Raw Signals · NO Patches Yet
Original xECG Paper & Codebase Specification: Each extracted view immediately starts at index 0 (\(t=0\)) as an autonomous continuous waveform. Shape alignment padding is applied strictly on the right / end only as flatline zero voltage (\(0.0\,\mathrm{mV}\)). There is no front/left padding to preserve the source recording's offset.
✓ Adopted in xECG: Start at \(t=0\) + Right-Pad End with Zero Voltage (\(0\,\mathrm{mV}\)) Paper & Official Code
t = 0.0s (Real ECG signal begins immediately) t = 4.0s (Crop End) t = 8.0s (0.0 mV Zero-Padding)
The continuous crop is treated as a fresh autonomous sub-sequence starting at \(t=0\). The xLSTM recurrent memory states \((h_0, c_0)\) initialize directly on real cardiac waveform, learning translation-invariant representations. Implemented via RandomCrop + _pad_time_end in bench-xecg.
✗ NOT Used: Pad Beginning & End (Absolute Position Alignment) Breaks Recurrence
Dummy 0.0 mV Front Pad \(t_k = t_{\mathrm{start}}\) (Offset) Dummy 0.0 mV End Pad
Padding the beginning to preserve the crop's absolute position offset forces forward recurrent xLSTM cells to step through 1000+ dummy zero samples before encountering cardiac signal, corrupting memory states. In contrast, adopted crops start immediately on signal.
Batched Multi-Channel Continuous Views (Per Mini-Batch Item)
Tensor shape: \([B \times 6 \text{ views}, 12 \text{ leads}, T_{\max} = 4000 \text{ samples}]\) • Rectangular batch tensor aligned on time axis
Batch: \(B=128\) ECGs × 6 Views
Why do Global Views fill 100% and Local Crops fill 50% here? (Batch Slot Normalization)
In PyTorch, all 6 views must share the same tensor length \(T_{\max} = 4000\) samples (\(8.0\,\mathrm{s}\)) to assemble a dense mini-batch \([B, 6, 12, 4000]\):
Global Views: Cropped to \(\mathbf{80\%}\) of 10s recording \(= 4000\) samples.
→ Fills \(\mathbf{100\%}\) of 4000 batch slot (\(\mathbf{0}\) padding).
Local Crops: Cropped to \(\mathbf{40\%}\) of 10s recording \(= 2000\) samples.
→ Fills \(\mathbf{50\%}\) of 4000 batch slot (\(2000\) real \(+ \mathbf{2000}\) zero-pad).
Global View 1 [12 leads × 4000 samples] 80% crop (4000 real) • 0 pad
4000 Real • 0 Pad
Global View 2 [12 leads × 4000 samples] 80% crop (4000 real) • 0 pad
4000 Real • 0 Pad
Local Crop 1 [12 leads × 4000 samples] 40% crop + 2000 pad
0.0 mV Flatline Pad (+2000 smp)
2000 Real • 2000 Pad
Local Crop 2 [12 leads × 4000 samples] 40% crop + 2000 pad
0.0 mV Flatline Pad (+2000 smp)
2000 Real • 2000 Pad
Local Crop 3 [12 leads × 4000 samples] 40% crop + 2000 pad
0.0 mV Flatline Pad (+2000 smp)
2000 Real • 2000 Pad
Local Crop 4 [12 leads × 4000 samples] 40% crop + 2000 pad
0.0 mV Flatline Pad (+2000 smp)
2000 Real • 2000 Pad
Important Architectural Boundary: All signals shown above are raw continuous multi-channel waveforms \([12, T]\). Slicing into discrete temporal patch tokens \((P_1, P_2, \dots, P_N)\) occurs next in Step 3.
Pipeline Flow 2 → 3 Transition to Temporal Tokenization: We now have autonomous 12-lead view tensors \([12, T_{\mathrm{crop}}]\). In Step 3, these multi-channel waveforms are sliced along the time dimension across all 12 leads into discrete temporal patch tokens \((P_1, P_2, \dots, P_N)\).
3

3D Temporal Patching Across All 12 Leads

Multichannel Waveform Tokenization
Unlike 2D images in Vision Transformers (which patch across height and width), a 12-lead ECG is an electrophysiological recording where the 12 leads represent simultaneous spatial projections of a single heart dipole vector \(\vec{D}(t)\). Slicing across leads would destroy spatial anatomical coherence. Therefore, xECG uses 1D temporal patching spanning all 12 leads:
Temporal Slicing of Extracted 12-Lead View (Window Length \(P_s = 25\) samples \(= 50\,\mathrm{ms}\)): Slicing Planes: \(\Delta t = 25\) samples at 500 Hz
Lead I
Lead II
... (12 L)
Leads III, aVR, aVL, aVF, V1, V2, V3, V4, V5 (Simultaneously Sliced at every Δt)
Lead V6
P₁
P₂
P₃ (QRS)
P₄
P₅
PN-1
PN
pad
pad
Anatomy of Patch \(P_3\) Matrix \([12 \times 25]\)
↓ 12 Lead Rows 25 Time Samples (50 ms) →
Lead I
Lead II
Lead III
⋮ Leads aVR, aVL, aVF, V1 – V5 (stacked vertically) ⋮
Lead V6
Shape: \([12 \text{ rows} \times 25 \text{ cols}] = 300\text{ raw voltages}\)
2D Stack: Leads are stacked vertically as rows in the patch matrix. Unrolling them horizontally into a 1D vector happens next in Step 4.
Why Multi-Lead Temporal Slicing? During any \(50\,\mathrm{ms}\) interval, myocardial electrical activation generates an instantaneous 3D vector dipole in space. Slicing across all 12 leads captures simultaneous frontal and horizontal plane projections, preserving the complete cardiac dipole geometry for that window.
\(\mathbf{P}_i \in \mathbb{R}^{12 \times P_s} = \mathbb{R}^{12 \times 25} \implies D_{\mathrm{in}} = 300 \text{ scalar voltage readings}\)
Physical Patch Representation vs. Neural Input (Step 3 → Step 4)
In this step, patch \(\mathbf{P}_i\) is still a 2D physical matrix of shape \([12 \text{ leads} \times 25 \text{ samples}]\). Each lead provides a horizontal row of 25 consecutive voltages.
→ In Step 4, this matrix is unrolled row-by-row into a single \(1 \times 300\) row vector to be mapped into the latent space via the linear projection matrix.
Pipeline Flow 3 → 4 Transition to Linear Patch Projection: Each patch \(\mathbf{P}_i \in \mathbb{R}^{12 \times 25}\) is currently a 2D matrix of 12 lead rows. In Step 4, it is unrolled row-by-row into a 300-dimensional row vector \(\mathbf{x}_i \in \mathbb{R}^{1 \times 300}\) and projected through learned linear matrix \(\mathbf{W}_{\mathrm{proj}} \in \mathbb{R}^{300 \times 1024}\) to produce the token sequence \((\mathbf{z}_1, \dots, \mathbf{z}_N)\).
4

Patch Flattening & Linear Projection (Patch Embedding + Selective Masking)

Tensor Mapping: \([B \cdot 6, N=160, 12, P_s=25] \to [B \cdot 6, N=160, 1024]\)
Each multi-lead patch \(\mathbf{P}_i \in \mathbb{R}^{12 \times 25}\) produced in Step 3 represents a \(50\,\mathrm{ms}\) instantaneous temporal slice across all 12 anatomical leads (\(12 \times 25 = 300\) scalar voltage readings). To prepare these physical voltage matrices for the neural encoder, xECG performs three sequential mathematical operations on every patch, followed by selective masking for student global views:
  1. Spatial-Temporal Unrolling (Flattening): Concatenates the 12 lead rows into a contiguous 300-dimensional voltage vector \(\mathbf{x}_i \in \mathbb{R}^{300}\).
  2. Learnable Linear Projection: Multiplies by weight matrix \(\mathbf{W}_{\mathrm{proj}} \in \mathbb{R}^{300 \times 1024} + \mathbf{b}_{\mathrm{proj}}\) to project raw microvolts into the latent representation space \(D=1024\).
  3. 1D Positional Embedding Summation: Injects temporal sequence order by adding a learned positional vector \(\mathbf{E}_i \in \mathbb{R}^{1024}\), yielding embedded token \(\mathbf{z}_i = \mathbf{h}_i + \mathbf{E}_i\).
1. Multi-Lead Patch Slice \(\mathbf{P}_i\) \([12, 25] = 300\) vals
\(50\,\mathrm{ms}\) cardiac snapshot across all 12 simultaneous electrical channels:
Lead I
Lead II
Lead III
frontal limb leads (aVR, aVL, aVF)
Lead V1
precordial leads (V2 – V5)
Lead V6
Captures 3D cardiac dipole orientation during \(\Delta t = 50\,\mathrm{ms}\).
Flatten
2. Linear Projection \(\mathbf{W}_{\mathrm{proj}}\) Row Vector: \([1 \times 300]\)
Row-major concatenation of 12 lead rows into horizontal row vector \(\mathbf{x}_i \in \mathbb{R}^{1 \times 300}\):
I II III aVR aVL aVF V1 V2 V3 V4 V5 V6
Idx 0 ← 300 raw voltages → Idx 299
12 leads × 25 samples = 300-dim row vector \(\mathbf{x}_i\)
Linear Kernel Transformation:
\(\mathbf{h}_i = \mathbf{x}_i \mathbf{W}_{\mathrm{proj}} + \mathbf{b}_{\mathrm{proj}} \in \mathbb{R}^{1 \times 1024}\)
Row vector \(\mathbf{x}_i\) maps to row vector \(\mathbf{h}_i\) via 1024 learned dipole filters.
+ Pos Enc
3. Embedded Patch Token \(\mathbf{z}_i\) Row Token: \(\mathbf{z}_i \in \mathbb{R}^{1 \times 1024}\)
Injects absolute temporal coordinates along the ECG recording:
Projected Row Vector: \(\mathbf{h}_i \in \mathbb{R}^{1 \times 1024}\)
+ 1D Pos Row Vector: \(+ \mathbf{E}_i \in \mathbb{R}^{1 \times 1024}\)
= Token Row Vector: \(\mathbf{z}_i \in \mathbb{R}^{1 \times 1024}\)
Dim 0 ← 1024 latent features → Dim 1023
Stacks as row \(i\) in sequence matrix \(\mathbf{Z} \in \mathbb{R}^{160 \times 1024}\)
4.2 THE OUTPUT

Full Batch of Patch Token Embeddings

Every temporal patch across all 12 leads, all 6 views, and all 128 batch recordings is now a dense continuous 1024-dimensional latent embedding vector \(\mathbf{z} \in \mathbb{R}^{1024}\).
122,880 Total Patch Embeddings in Batch
Single View Sequence Matrix \(\mathbf{Z} \in \mathbb{R}^{160 \times 1024}\) 160 Rows × 1024 Columns
Each row is the 1024-dim continuous embedding vector of one temporal patch \(\mathbf{P}_i\):
Patch Token Row ← 1024 Continuous Latent Features (Dimension \(0 \dots 1023\)) →
\(\mathbf{z}_1\) \(P_1\,(0\text{--}50\,\mathrm{ms})\)
… 1024 continuous scalar features …
\(\mathbf{z}_2\) \(P_2\,(50\text{--}100\,\mathrm{ms})\)
… 1024 continuous scalar features …
\(\mathbf{z}_3\) \(P_3\,(100\text{--}150\,\mathrm{ms})\)
… QRS dipole activation features …
Sequential patch embeddings continue up to \(P_{80}\) (Local crops) or \(P_{160}\) (Global views) ⋮
\(\mathbf{z}_{160}\) \(P_{160}\) (Pad / End)
… Flatline zero-pad embedding (\(\mathbf{0} \mathbf{W}_{\mathrm{proj}} + \mathbf{b} + \mathbf{E}_{160}\)) …
All Items of the Batch \([B=128, V=6, N=160, D=1024]\) Flattened: \([768, 160, 1024]\)
Every patient in the mini-batch supplies 6 view sequences of 160 patch embeddings:
Patient ECG #1 (Item \(b=0\)) 6 Views × 160 = 960 Patch Embeddings
G₁
z₁z₂z₃z₁₆₀
160×1024
G₂
z₁z₂z₃z₁₆₀
160×1024
L₁
z₁z₈₀pad
160×1024
L₂
z₁z₈₀pad
160×1024
L₃
z₁z₈₀pad
160×1024
L₄
z₁z₈₀pad
160×1024
Patient ECG #2 (Item \(b=1\)) 6 Views × 160 = 960 Patch Embeddings
G₁160×1024
G₂160×1024
L₁160×1024
L₂160×1024
L₃160×1024
L₄160×1024
⋮ Stacking across batch dimension \(b = 2 \dots 127\) (\(128\) total patients) ⋮
Patient ECG #128 (Item \(b=127\)) 6 Views × 160 = 960 Patch Embeddings
G₁160×1024
G₂160×1024
L₁160×1024
L₂160×1024
L₃160×1024
L₄160×1024
\(1 \times 1024\) 1 Patch Embedding Token
× 160 →
\([160, 1024]\) 1 View Sequence Matrix
× 6 →
\([6, 160, 1024]\) 1 Patient (960 Tokens)
× 128 →
\([128, 6, 160, 1024]\) Full Batch (122,880 Tokens • 491.5 MB Float32)
GPU Batch Vectorization: Zero Sequential Python Loops
\(128 \times 6 \times 160 = \mathbf{122{,}880 \text{ tokens parallel}}\)
On the GPU accelerator, projection is executed as a single batched tensor operation across all \(B=128\) patient recordings and all \(V=6\) views simultaneously. In PyTorch, this corresponds to: tokens = self.proj(patches.flatten(-2, -1)) + self.pos_embed[:, :seq_len, :]
1. Multi-Crop Views [128, 6, 160, 12, 25] All views right-padded to equal maximum length \(N=160\).
2. Flatten Leads & Samples [768, 160, 300] Collapses \(12 \times 25 \to 300\) contiguous raw voltage scalars per patch.
3. Linear GEMM Kernel [768, 160, 1024] Matrix multiply with \(\mathbf{W}_{\mathrm{proj}} \in \mathbb{R}^{300 \times 1024}\) in a single hardware kernel.
4. Broadcast Positional \(\mathbf{E}\) [768, 160, 1024] Learnable 1D temporal matrix broadcasted across all 768 sequences.
Selective Masking Strategy: Asymmetric Information Flow
Student Global Masked • Teacher & Local Unmasked
SimDINOv2 unifies masked autoencoding (MIM) with multi-crop self-distillation. Crucially, masking is applied asymmetrically: only Student Global views have patches replaced with the shared learnable [MASK] token vector \(\mathbf{e}_{\mathrm{mask}} \in \mathbb{R}^{1024}\). Local crops and all Teacher views remain 100% unmasked. All 8 individual views are stacked vertically below to compare token sequences, stochastic mask distributions, and trailing padding directly:
All 8 Views Stacked Comparison (\(B \times 6\) Student + \(B \times 2\) Teacher)
zᵢ Student Global Token
[M] Learnable Mask \(\mathbf{e}_{\mathrm{mask}}\)
zᵢ Student Local Token
pad Trailing Pad Zero
zᵢ Teacher Target Token
Student Global Views (\(u_1, u_2\)) — 8.0 s Context • 160 Tokens
Independent 30–40% Stochastic Masking • Drives \(\mathcal{L}_{\mathrm{patch}}\)
u₁
Student Global 1 t ∈ [0.0, 8.0] s • Mask A
z₁ z₂ [M] z₄ [M] [M] z₇ z₈ z₉ [M] z₁₁ z₁₂ [M] z₁₆₀
35% Masked • 56 [M] tokens
u₂
Student Global 2 t ∈ [2.0, 10.0] s • Mask B
z₁ [M] z₃ [M] z₅ z₆ [M] z₈ [M] z₁₀ z₁₁ z₁₂ z₁₅₉ [M]
38% Masked • 61 [M] tokens
Student Local Crops (\(v_1, v_2, v_3, v_4\)) — 4.0 s Context • 80 Real + 80 Right-Pad
0% Signal Masking • Flatline Padding Masked in Attention
v₁
Student Local 1 t ∈ [0.8, 4.8] s • QRS Complex
z₁ z₂ z₃ z₄ z₅ z₆ z₇₉ z₈₀ pad pad pad pad
80 Real + 80 Pad • 0% Masked
v₂
Student Local 2 t ∈ [2.2, 6.2] s • ST Segment
z₁ z₂ z₃ z₄ z₅ z₆ z₇₉ z₈₀ pad pad pad pad
80 Real + 80 Pad • 0% Masked
v₃
Student Local 3 t ∈ [3.6, 7.6] s • T Wave Peak
z₁ z₂ z₃ z₄ z₅ z₆ z₇₉ z₈₀ pad pad pad pad
80 Real + 80 Pad • 0% Masked
v₄
Student Local 4 t ∈ [5.1, 9.1] s • Late Cycle
z₁ z₂ z₃ z₄ z₅ z₆ z₇₉ z₈₀ pad pad pad pad
80 Real + 80 Pad • 0% Masked
Teacher Global Views (\(u_1, u_2\)) — 8.0 s Context • 160 Tokens
100% Pristine Ground-Truth Targets • Zero Gradient (EMA)
u₁
Teacher Global 1 t ∈ [0.0, 8.0] s • Pristine Target
z₁ z₂ z₃ z₄ z₅ z₆ z₇ z₈ z₉ z₁₀ z₁₁ z₁₂ z₁₅₉ z₁₆₀
100% Pristine • Target for u₁
u₂
Teacher Global 2 t ∈ [2.0, 10.0] s • Pristine Target
z₁ z₂ z₃ z₄ z₅ z₆ z₇ z₈ z₉ z₁₀ z₁₁ z₁₂ z₁₅₉ z₁₆₀
100% Pristine • Target for u₂
Student Global Strategy (\(u_1, u_2\))
  • Masking Ratio: ~30–40% of patch tokens randomly substituted with learnable vector \(\mathbf{e}_{\mathrm{mask}} + \mathbf{E}_i\).
  • Supervisory Role: Drives the patch reconstruction objective \(\mathcal{L}_{\mathrm{patch}}\).
  • Physiological Rationale: Forces the student to reconstruct occluded QRS complexes or ST elevations from surrounding rhythm context.
Student Local Crops Strategy (\(v_1 \dots v_4\))
  • Masking Ratio: 0% masked. All 80 real signal tokens remain pristine.
  • Trailing Padding: Tokens 81–160 are right-padded flatline zeros, completely masked from attention pooling.
  • Why No Masking? Local crops span only \(4.0\,\mathrm{s}\). Additional masking would destroy critical cardiac morphology needed for part-to-whole alignment.
Teacher Global Strategy (\(u_1, u_2\))
  • Masking Ratio: 0% masked. Complete 160 active tokens fed to EMA teacher.
  • Supervisory Target: Unmasked teacher representations provide the ground-truth targets for \(\mathcal{L}_{\mathrm{patch}}\) and \(\mathcal{L}_{\mathrm{comp}}\).
  • Anti-Corruption Guarantee: Masking the teacher would provide corrupted, noisy regression targets and destabilize distillation.
View Stream & Target Crop Duration Sequence Tokens Masking Strategy Active Loss Objectives Core Learning Mechanism
Student Global (\(u_1, u_2\)) \(8.0\,\mathrm{s}\) (\(80\%\)) \(160\) active tokens 30–40% [MASK] tokens \(\mathcal{L}_{\mathrm{comp}} + \mathcal{L}_{\mathrm{expa}} + \mathcal{L}_{\mathrm{patch}}\) Reconstruct occluded wave complexes while aligning global semantics.
Student Local (\(v_1 \dots v_4\)) \(4.0\,\mathrm{s}\) (\(40\%\)) \(80\) real + \(80\) pad 0% masked (unmasked) \(\mathcal{L}_{\mathrm{comp}}\) (student local → teacher global) Enforce part-to-whole view invariance across temporal shifts.
Teacher Global (\(u_1, u_2\)) \(8.0\,\mathrm{s}\) (\(80\%\)) \(160\) active tokens 0% masked (100% pristine) EMA Regression Target (no grad) Provides stable, noise-free semantic targets for the student network.
Pipeline Flow 4 → 5 Sequence Ready for xLSTM Backbone: With raw voltages converted to normalized \(D=1024\) latent embeddings and positional coordinates injected, the sequence \((\mathbf{z}_1, \dots, \mathbf{z}_N) \in \mathbb{R}^{N \times 1024}\) is passed directly into the 9-block Bidirectional xLSTM encoder. Unlike ViTs, no artificial [CLS] token is prepended.
5

Bidirectional xLSTM Encoder Backbone

Batch: Parallel Across All \(B \times 6 = 768\) View Sequences
In contrast to Vision Transformers (ViT), which prepend an artificial [CLS] token at index 0, xECG inputs pure temporal patch tokens \((z_1, \dots, z_N) \in \mathbb{R}^{N \times 1024}\). Prepending dummy tokens into recurrent architectures like xLSTM alters initial cell states \((h_0, c_0)\) and introduces artificial initialization bias. Illustrated below for a single sequence; on the GPU, all \(B \times 6 = 768\) view sequences in the mini-batch are processed concurrently through 9 bidirectional xLSTM blocks alternating between sLSTM (scalar memory with exponential gating) and mLSTM (matrix memory with associative storage and retrieval):
sLSTM 1 ⇄ BiDir
sLSTM 2 ⇄ BiDir
mLSTM 3 ⇄ BiDir
mLSTM 4 ⇄ BiDir
sLSTM 5 ⇄ BiDir
sLSTM 6 ⇄ BiDir
mLSTM 7 ⇄ BiDir
mLSTM 8 ⇄ BiDir
sLSTM 9 ⇄ BiDir
sLSTM (Scalar Memory Blocks: 1, 2, 5, 6, 9)

Exponential gating with memory mixing stabilizes long-range tracking of rhythmic baseline features, heart rate variability, and recurrent cardiac wave cycles.

mLSTM (Matrix Memory Blocks: 3, 4, 7, 8)

Key-value associative memory \(C_t = C_{t-1} + v_t k_t^\top\) stores high-capacity representations of complex morphologic abnormalities (e.g. bundle branch blocks, ST elevation).

Backbone Output: The 9th block outputs contextualized sequence representations \(\mathbf{s} = (s_1, s_2, \dots, s_N) \in \mathbb{R}^{N \times 1024}\). Each token \(s_i\) encapsulates both forward past context and backward future context of the 12-lead ECG.
6

Step-by-Step Representation Head: Attention Pooling & \(\ell_2\) Normalization

Sequence Aggregation to Unit Hypersphere \(\mathbb{S}^{D-1}\)
Instead of using an ad-hoc token (like [CLS]) or simple mean-pooling (which dilutes localized cardiac events like ventricular ectopy across quiet intervals), xECG condenses the contextualized patch sequence \((s_1, \dots, s_N) \in \mathbb{R}^{N \times 1024}\) through a 2-stage representation head (defined in bench_xecg/models/pooling.py):
6.1 Attention Pooling Block (AttentionPooling)
Query Cross-Attention + Residual MLP
Learned query parameter probe \(\mathbf{q} \in \mathbb{R}^{1 \times 1024}\) performs multi-head cross-attention across all patch tokens \((s_1 \dots s_N)\) with zero-weight padding masking.
Learned Query Probe: \(\mathbf{q} \in \mathbb{R}^{1 \times 1024}\) • Broadcast across mini-batch \([B \cdot 6, 1, 1024]\)
Dynamic Attention Weights \(\alpha_i\) Across Cardiac Cycle Peaks on QRS Complex (\(\alpha_3 = 0.54\))
0.11
0.05
0.54 ★
0.07
0.21
0.02
0.00
s₁ P Wave
s₂ PR Segment
s₃ (Peak) QRS Depol.
s₄ ST Segment
s₅ T Repol.
s₆ TP Segment
spad Masked (\(\alpha=0\))
\[\alpha_i = \operatorname{softmax}\left(\frac{\mathbf{q} \cdot \mathbf{s}_i^\top}{\sqrt{d_k}}\right), \quad \mathbf{x}_{\mathrm{attn}} = \sum_{i=1}^N \alpha_i \mathbf{s}_i \in \mathbb{R}^{1024}\] \[\mathbf{z}_{\mathrm{pool}} = \mathbf{x}_{\mathrm{attn}} + \mathrm{Linear}_{4D \to D}\Big(\mathrm{GELU}\big(\mathrm{Linear}_{D \to 4D}(\mathrm{LayerNorm}(\mathbf{x}_{\mathrm{attn}}))\big)\Big) \in \mathbb{R}^{1024}\]
Physiological Grounding: The learned probe automatically focuses attention mass on the high-voltage QRS complex (\(\approx 54\%\)) and T-wave repolarization (\(\approx 21\%\)), while the attention padding mask strictly forces \(\alpha_{\mathrm{pad}} = 0.00\) on all trailing zero-pad tokens.
6.2 \(\ell_2\) Hypersphere Normalization
Unit Hypersphere \(\mathbb{S}^{D-1}\)
Projects the pooled vector \(\mathbf{z}_{\mathrm{pool}}\) onto the unit hypersphere \(\mathbb{S}^{D-1}\), bounding vector norm to \(\|\hat{\mathbf{z}}\|_2 = 1.0\).
||ẑ||₂ = 1.0 Unit Hypersphere \(\mathbb{S}^{1023}\)
\[\hat{\mathbf{z}} = \frac{\mathbf{z}_{\mathrm{pool}}}{\|\mathbf{z}_{\mathrm{pool}}\|_2} \implies \|\hat{\mathbf{z}}\|_2 = 1.0\] \[\frac{1}{2}\|\hat{\mathbf{x}} - \hat{\mathbf{y}}\|_2^2 = 1 - \cos(\hat{\mathbf{x}}, \hat{\mathbf{y}})\]
Why \(\ell_2\) Normalization is Mandatory: On the unit hypersphere, Euclidean distance exactly equals Cosine distance (\(1 - \cos\)). This eliminates representation magnitude drift, stabilizes the batch covariance matrix \(\operatorname{Cov}(\hat{\mathbf{z}})\), and allows SimDINOv2 to compute the coding rate \(R_\varepsilon\) directly.
Vectorized Mini-Batch Scope: Computed simultaneously across all \(B \times 6 = 768\) views on GPU \(\implies \hat{\mathbf{z}} \in \mathbb{R}^{768 \times 1024}\).
Pipeline Flow 6 → 7 Normalized Representations Ready for Dual Distillation: With each view encoded into a unit-normalized vector \(\hat{\mathbf{z}} \in \mathbb{S}^{1023}\) and constituent token sequence \(\mathbf{s} \in \mathbb{R}^{N \times 1024}\), the pipeline bifurcates into an asymmetric Student-Teacher architecture. The Student learns via backpropagation gradients, while the Teacher maintains a noise-free historical target via Exponential Moving Average (EMA).
7

Teacher-Student Dual Network Dynamics & Exponential Moving Average (EMA)

Dual Pathway: Student (\(\nabla_\theta\)) & Teacher (EMA \(\theta_t\))
Self-supervised representation learning without negative examples faces a catastrophic collapse hazard: both networks can trivially output a constant zero or static bias vector. SimDINOv2 eliminates this through structural network asymmetry and momentum parameter updates. The Student network \(\mathbf{f}_{\theta_s}\) processes all views (including masked and cropped variants) with active gradient tracking, while the Teacher network \(\mathbf{f}_{\theta_t}\) evaluates only pristine global signals under torch.no_grad() and updates its weights strictly through an Exponential Moving Average (EMA):
S Student Network \(\mathbf{f}_{\theta_s}\)
Backprop Gradients Enabled
Input Scope: All 6 views per patient • \(2\) Global Views (30–40% masked) + \(4\) Local Crops (0% masked). Total mini-batch throughput on GPU: \(B \times 6 = 768\) sequences.
STUDENT FORWARD PIPELINE:
6 Views [MASK] (Globals) 9-Block xLSTM AttnPool \(\ell_2\) Norm
Produced Student Tensors:
\(\hat{\mathbf{z}}_s \in \mathbb{R}^{768 \times 1024}\) Pooled unit vectors on \(\mathbb{S}^{1023}\) across all 6 views.
\(\mathbf{S}_s^{\mathrm{masked}} \in \mathbb{R}^{M \times 1024}\) Token latents at masked temporal positions.
Optimization Rule (AdamW):
\[\theta_s^{(t+1)} \leftarrow \theta_s^{(t)} - \eta \cdot \frac{\mathbf{m}_t}{\sqrt{\mathbf{v}_t} + \epsilon} - \eta \lambda_{\mathrm{wd}} \theta_s^{(t)}, \quad \mathbf{g}_t = \nabla_{\theta_s} \mathcal{L}_{\mathrm{total}}\]
T Teacher Network \(\mathbf{f}_{\theta_t}\)
Stop-Gradient (torch.no_grad())
Input Scope: ONLY the 2 Global Views (\(u_1, u_2\)) • 0% Masking (100% pristine waveforms). Total mini-batch throughput on GPU: \(B \times 2 = 256\) sequences (3× lighter compute).
TEACHER FORWARD PIPELINE:
2 Globals 0% Mask (Clean) 9-Block xLSTM AttnPool \(\ell_2\) Norm
Produced Teacher Targets:
\(\hat{\mathbf{z}}_t \in \mathbb{R}^{256 \times 1024}\) Target unit vectors for global cross-view alignment.
\(\mathbf{S}_t^{\mathrm{clean}} \in \mathbb{R}^{256 \times 160 \times 1024}\) Noise-free target tokens for masked patch regression.
Momentum Update Rule (EMA):
\[\theta_t^{(t+1)} \leftarrow \lambda_t \theta_t^{(t)} + (1 - \lambda_t) \theta_s^{(t+1)}, \quad \lambda_t \in [0.99, 1.0]\]
The EMA Momentum Wire & Polyak-Ruppert Averaging Effect Cosine Momentum Schedule: 0.99 → 1.00
The teacher never computes gradients. Instead, after each backward step, the Student's updated weights are exponentially blended into the Teacher: \[\lambda_t = 1 - (1 - \lambda_0) \cdot \frac{1 + \cos\left(\frac{\pi t}{T}\right)}{2}, \quad \lambda_0 = 0.99 \to \lambda_T = 1.00\]
  • Polyak-Ruppert Temporal Ensemble: The teacher behaves as an ensemble over thousands of preceding student parameter states: \(\theta_t \approx \sum_{k=0}^t w_k \theta_{s,k}\).
  • Noise Filtering: Transient stochastic mini-batch noise (e.g. abrupt baseline drift, electrode disconnect spikes) is damped out, yielding rock-steady target representations.
  • Trivial Collapse Prevention: Because \(\nabla_{\theta_t} \mathcal{L} = 0\), the optimization cannot solve the loss by simultaneously collapsing both networks into a trivial state \(\theta_s = \theta_t = \mathbf{0}\).
Student θ_s AdamW (∇θ) EMA Transfer λ_t: 0.99 → 1.0 Teacher θ_t No Grad (EMA) Supervisory Target Regression One-way momentum wire • No backpropagation into Teacher
Intermediate Checkpoint: Student vs. Teacher Mini-Batch Allocation (\(B=128\))
Network Branch Input Crops per ECG Total Sequences (\(B=128\)) Selective Masking Forward Mode Memory (Activations) Parameter Update
Student \(\mathbf{f}_{\theta_s}\) \(2\) Globals + \(4\) Locals (\(=6\)) \(128 \times 6 = \mathbf{768}\) sequences \(30\text{--}40\%\) masked (Globals) Train (Autograd graph built) \(\approx 3.8\,\mathrm{GB}\) (gradients stored) AdamW with Layerwise LR Decay
Teacher \(\mathbf{f}_{\theta_t}\) \(2\) Globals only (\(=2\)) \(128 \times 2 = \mathbf{256}\) sequences \(0\%\) masked (100% clean) Eval (torch.no_grad()) \(\approx 0.3\,\mathrm{GB}\) (no graph stored) Exponential Moving Average (EMA)
Pipeline Flow 7 → 8 Representations Assembled for Objective Evaluation: With Student latents \(\hat{\mathbf{z}}_s \in \mathbb{R}^{768 \times 1024}\) and Teacher targets \(\hat{\mathbf{z}}_t \in \mathbb{R}^{256 \times 1024}\) residing in GPU VRAM on the unit hypersphere \(\mathbb{S}^{1023}\), the system executes the core breakthrough of SimDINOv2: closed-form Maximal Coding Rate Reduction (MCR) without heuristic centering or sharpening.
8

Multi-Component SimDINOv2 Loss Formulation: The MCR Objective

Tripartite Loss: Compression + Expansion + Dense Patch
✦ The Paradigm Shift: Why SimDINOv2 Replaces Classic DINO Heuristics Classic DINO (Caron et al., 2021) and DINOv2 (Oquab et al., 2023) prevent representation collapse through delicate empirical balancing acts: a running mean-centering vector \(c \in \mathbb{R}^K\), temperature sharpening (\(\tau_t = 0.04 \to 0.07\)), iterative Sinkhorn-Knopp optimal transport, and enormous projection heads (\(K = 65,536\) prototypes). If temperatures drift, training collapses instantly.
SimDINOv2 (Wu et al., 2025; arXiv:2502.10385) completely discards prototypes, centering vectors, and temperatures. It operates directly on continuous \(\ell_2\)-normalized representations \(\hat{\mathbf{z}} \in \mathbb{S}^{D-1}\) using closed-form Maximal Coding Rate Reduction (MCR):
1. Compression Loss \(\mathcal{L}_{\mathrm{comp}}\)
\(\mathcal{L}_{\mathrm{comp}} = 1 - \operatorname{mean}_{(i,j)} \cos(\hat{\mathbf{z}}_{s,i}, \hat{\mathbf{z}}_{t,j})\)
Pulls matching views together: Enforces that all views (globals & local crops) of the same patient map to identical hypersphere coordinates.
2. Expansion Loss (MCR) \(\mathcal{L}_{\mathrm{expa}}\)
\(\mathcal{L}_{\mathrm{expa}} = - \gamma \cdot R_\varepsilon\big(\operatorname{Cov}[\mathbf{Z}]\big)\)
Pushes batch representations apart: Maximizes the volume (coding rate) of the mini-batch covariance ellipsoid across all \(1024\) dimensions to prevent collapse.
3. Dense Patch Loss \(\mathcal{L}_{\mathrm{patch}}\)
\(\mathcal{L}_{\mathrm{patch}} = \operatorname{mean}_{k \in \mathcal{M}} (1 - \cos(\mathbf{s}_{s,k}, \mathbf{s}_{t,k}))\)
Local waveform reconstruction: iBOT-style token distillation forcing the student to reconstruct masked temporal intervals from contextual leads.
8.1 Compression Loss (\(\mathcal{L}_{\mathrm{comp}}\)): Cross-View Pairwise Alignment Scaled by \(\mathrm{coeff} = 1.0\)
For each ECG recording in the batch, we compute the cosine similarity between every Student view (\(S_{g1}, S_{g2}, S_{l1}, S_{l2}, S_{l3}, S_{l4}\)) and each Teacher global view (\(T_{g1}, T_{g2}\)). Crucially, to prevent trivial shortcut learning, matching a view against its exact identical twin (e.g. \(S_{g1} \leftrightarrow T_{g1}\)) is strictly excluded by zeroing out the diagonal in PyTorch (sim.view(-1, ...)[::(len+1), :].fill_(0)):
Teacher \(\downarrow\) / Student \(\rightarrow\) Student Global 1 (\(S_{g1}\)) Student Global 2 (\(S_{g2}\)) Student Local 1 (\(S_{l1}\)) Student Local 2 (\(S_{l2}\)) Student Local 3 (\(S_{l3}\)) Student Local 4 (\(S_{l4}\))
Teacher Global 1 (\(T_{g1}\)) ❌ Diagonal Skip (Identical View) ✓ \(\cos(S_{g2}, T_{g1})\) ✓ \(\cos(S_{l1}, T_{g1})\) ✓ \(\cos(S_{l2}, T_{g1})\) ✓ \(\cos(S_{l3}, T_{g1})\) ✓ \(\cos(S_{l4}, T_{g1})\)
Teacher Global 2 (\(T_{g2}\)) ✓ \(\cos(S_{g1}, T_{g2})\) ❌ Diagonal Skip (Identical View) ✓ \(\cos(S_{l1}, T_{g2})\) ✓ \(\cos(S_{l2}, T_{g2})\) ✓ \(\cos(S_{l3}, T_{g2})\) ✓ \(\cos(S_{l4}, T_{g2})\)
\[N_{\mathrm{pairs}} = 2 \times 6 - 2 = 10 \text{ active cross-view pairs per ECG sample}\] \[\mathcal{L}_{\mathrm{comp}} = 1 - \frac{1}{10} \sum_{(i,j) \in \mathcal{P}_{\mathrm{active}}} \cos(\hat{\mathbf{z}}_{s,i}, \hat{\mathbf{z}}_{t,j}) = 1 - \frac{1}{10} \sum_{(i,j)} \hat{\mathbf{z}}_{s,i}^\top \hat{\mathbf{z}}_{t,j}\]
Cardiovascular Grounding: Forces local crops containing isolated arrhythmias (e.g. premature ventricular complexes in Lead V1) to project near the global representation of the entire 12-lead recording, learning robust part-to-whole diagnostic invariance.
8.2 Expansion Loss (\(\mathcal{L}_{\mathrm{expa}}\)): Coding Rate Regularization (Anti-Collapse) Distortion \(\varepsilon = 0.05\) • \(\mathrm{expa\_type} = 1\)
If we only minimize compression loss, the entire network will collapse to a single point \(\hat{\mathbf{z}} \equiv \mathbf{c}\) on the hypersphere (where \(\cos(\mathbf{c}, \mathbf{c}) = 1.0 \implies \mathcal{L}_{\mathrm{comp}} = 0.0\)). SimDINOv2 prevents this by directly maximizing the Coding Rate \(R_\varepsilon(\mathbf{Z})\): the volume of the feature space spanned by the mini-batch on the unit hypersphere:
⚠️ Collapsed Subspace (Low Rank) Rank \(\ll 1024\)
Zero Volume • Determinant \(\approx 1.0\) • \(R_\varepsilon \to 0\)
Representations cluster along a 1D line. The covariance matrix has only one non-zero eigenvalue (\(\lambda_1 \gg 0, \lambda_{2\dots 1024} = 0\)). High expansion penalty!
✓ Maximally Dispersed (Full Rank) Full Rank \(= 1024\)
Max Volume • Uniform Eigenvalues • \(R_\varepsilon\) Maximized
Representations spread uniformly across all 1024 orthogonal axes of \(\mathbb{S}^{1023}\). Maximal entropy and maximal information capacity. Minimal expansion penalty!
1. Expansion Feature Mixture (expa_type = 1):
\[\mathbf{Z}_{\mathrm{expa}} = \frac{\hat{\mathbf{Z}}_{s,\mathrm{globals}} + \hat{\mathbf{Z}}_{t,\mathrm{globals}}}{2} \in \mathbb{R}^{m \times D}, \quad m = B \times 2 = 256, \quad D = 1024\]
2. Feature Covariance & Fast Cholesky Log-Determinant:
\[\mathbf{C} = \frac{1}{m} \mathbf{Z}_{\mathrm{expa}}^\top \mathbf{Z}_{\mathrm{expa}} \in \mathbb{R}^{1024 \times 1024}, \quad \mathbf{A} = \mathbf{I}_{1024} + \left(\frac{D}{m \cdot \varepsilon}\right) \mathbf{C}\] \[\mathbf{A} = \mathbf{L} \mathbf{L}^\top \implies \log \det(\mathbf{A}) = 2 \sum_{k=1}^{1024} \ln L_{kk}\]
3. Balancing Factor & Negated Expansion Loss:
\[\gamma = \frac{D + m}{D \cdot m} = \frac{1024 + 256}{1024 \cdot 256} \approx 4.88 \times 10^{-3}, \quad \mathcal{L}_{\mathrm{expa}} = - \gamma \cdot \left(\frac{1}{2} \log \det(\mathbf{A})\right)\]
Numerical Stability Guarantee: Computing \(\log \det\) via Cholesky decomposition \(\mathbf{L}\) runs entirely in GPU Tensor Cores in \(\approx 0.8\,\mathrm{ms}\) and is completely immune to float underflow. Negating the coding rate turns volume maximization into standard gradient descent minimization.
8.3 Dense Patch Loss (\(\mathcal{L}_{\mathrm{patch}}\)): iBOT-Style Token Distillation Selective Masking • Padding-Aware Mask
Global attention pooling captures macro patient-level rhythm, but subtle localized morphological features (e.g. ST-elevation in Lead V2, bifid P-waves, pacemaker spikes) require dense temporal supervision. In the 2 Student Global views, 30–40% of patch tokens were replaced by learnable [MASK] embeddings. The Teacher processed the exact same temporal locations in pristine form. \(\mathcal{L}_{\mathrm{patch}}\) forces the Student to reconstruct these occluded tokens:
\[\mathcal{M}_{\mathrm{valid}} = \Big\{k \;\Big|\; \mathbf{M}_{\mathrm{mask}}[k] = \mathrm{True} \;\land\; \mathbf{M}_{\mathrm{pad}}[k] = \mathrm{False}\Big\}\] \[\mathcal{L}_{\mathrm{patch}} = \frac{1}{|\mathcal{M}_{\mathrm{valid}}|} \sum_{k \in \mathcal{M}_{\mathrm{valid}}} \Big(1 - \cos\big(\mathbf{s}_{s,k}, \mathbf{s}_{t,k}\big)\Big) = \frac{1}{|\mathcal{M}_{\mathrm{valid}}|} \sum_{k \in \mathcal{M}_{\mathrm{valid}}} \left(1 - \frac{\mathbf{s}_{s,k} \cdot \mathbf{s}_{t,k}}{\|\mathbf{s}_{s,k}\|_2 \|\mathbf{s}_{t,k}\|_2}\right)\]
Padding Safety: The vectorized padding mask \(\mathbf{M}_{\mathrm{pad}}\) strictly excludes trailing flatline padding tokens, guaranteeing that gradients are generated only from authentic cardiac depolarization intervals.

✦ The Complete SimDINOv2 Master Objective

Official bench-xecg Objective

The total loss combines cross-view compression, anti-collapse coding rate expansion, and masked patch distillation into a single scalar minimized by the AdamW optimizer:

\[\mathcal{L}_{\mathrm{total}} = \underbrace{\alpha \cdot \mathcal{L}_{\mathrm{comp}}}_{\text{Cross-View Alignment}} + \underbrace{\mathcal{L}_{\mathrm{expa}}}_{\text{Coding Rate Anti-Collapse}} + \underbrace{\mathcal{L}_{\mathrm{patch}}}_{\text{Dense iBOT Reconstruction}}\]
Compression Term (\(\alpha = 1.0\)) Pulls student global and local views toward teacher global targets on \(\mathbb{S}^{1023}\).
Expansion Term (\(\gamma \cdot R_\varepsilon\)) Expands the volume of the feature covariance ellipsoid across all 1024 dimensions.
Dense Patch Term (\(\mathcal{L}_{\mathrm{patch}}\)) Reconstructs occluded cardiac wave complexes at masked temporal intervals.
Pipeline Flow 8 → 9 From Loss Evaluation to System Synthesis: With all mathematical operations defined from raw voltage waveforms to scalar loss backpropagation, we now aggregate the complete system architecture into an end-to-end hardware ledger and comparative paradigm matrix.
9

End-to-End Pipeline Aggregation, Tensor Flow & Hardware Ledger

Mini-Batch Scope: B=128 Complete System Audit
The diagram and ledger below trace the complete life-cycle of a mini-batch of \(B=128\) 12-lead ECGs as it moves through the entire GPU training pipeline—from raw millivolts on disk to backpropagation gradients and EMA momentum parameter updates:
Macro End-to-End Tensor Transformation Pipeline:
1. Raw ECG [128, 12, 5000] 2. Multi-Crop Extraction (6 views) 3. Temporal Patching [12×25 = 300] 4. Linear Proj & Masking
5. 9-Block BiDir xLSTM (sLSTM/mLSTM) 6. AttnPool & \(\ell_2\) Norm 7. Student vs. Teacher Dual Pass
8. Tripartite Loss: \(\mathcal{L}_{\mathrm{comp}} + \mathcal{L}_{\mathrm{expa}} + \mathcal{L}_{\mathrm{patch}}\) 9. AdamW (\(\theta_s\)) & EMA (\(\theta_t\)) Update
Comprehensive Mini-Batch Tensor Ledger (\(B=128\) Patients • Mixed Precision fp16/bf16)
Pipeline Stage Tensor Variable Mathematical Symbol PyTorch Tensor Shape Data Type GPU VRAM Requires Grad
1. Raw Input batch["signals"] \(\mathbf{X}\) [128, 12, 5000] float32 \(30.7\,\mathrm{MB}\) False
2. Global Crops (2×) global_signals \(\mathbf{X}_{\mathrm{global}}\) 2 × [128, 12, 4000] float32 \(49.2\,\mathrm{MB}\) False
2. Local Crops (4×) local_signals \(\mathbf{X}_{\mathrm{local}}\) 4 × [128, 12, 4000] float32 \(98.3\,\mathrm{MB}\) False
3. Sliced Patches patches_unrolled \(\mathbf{P}\) [768, 160, 300] float32 \(147.5\,\mathrm{MB}\) False
4. Linear Embeddings tokens_projected \(\mathbf{Z}_{\mathrm{proj}}\) [768, 160, 1024] float16 \(251.7\,\mathrm{MB}\) True
4. Masked Student Input tokens_masked \(\mathbf{Z}_{\mathrm{stud}}\) [768, 160, 1024] float16 \(251.7\,\mathrm{MB}\) True
4. Clean Teacher Input tokens_teacher \(\mathbf{Z}_{\mathrm{teach}}\) [256, 160, 1024] float16 \(83.9\,\mathrm{MB}\) False
5. Student xLSTM Tokens stud_tokens \(\mathbf{s}_s\) [768, 160, 1024] float16 \(251.7\,\mathrm{MB}\) True
5. Teacher xLSTM Tokens teach_tokens \(\mathbf{s}_t\) [256, 160, 1024] float16 \(83.9\,\mathrm{MB}\) False
6. Student Unit Latents cls_tok_stud_g \(\hat{\mathbf{z}}_s\) [768, 1024] float32 \(3.1\,\mathrm{MB}\) True
6. Teacher Target Latents cls_tok_teacher_g \(\hat{\mathbf{z}}_t\) [256, 1024] float32 \(1.0\,\mathrm{MB}\) False
8. Pairwise Cosine Matrix sim \(\mathbf{S}_{\mathrm{sim}}\) [256, 768] float32 \(0.8\,\mathrm{MB}\) True
8. Covariance Matrix cov_list \(\mathbf{C}\) [2, 1024, 1024] float32 \(8.4\,\mathrm{MB}\) True
8. Cholesky Factor L \(\mathbf{L}\) [2, 1024, 1024] float32 \(8.4\,\mathrm{MB}\) True
8. Final Scalar Loss teacher_student_loss \(\mathcal{L}_{\mathrm{total}}\) [] (scalar) float32 \(< 1\,\mathrm{KB}\) True (Root)
Architectural Comparison: DINO vs. DINOv2 vs. SimDINOv2 for 12-Lead ECG
Architecture Dimension Classic DINO (Caron et al., 2021) DINOv2 (Oquab et al., 2023) SimDINOv2 (Wu et al. 2025 / xECG)
Core Objective Cross-Entropy with Softmax Sharpening Cross-Entropy + KoLeo Regularizer + iBOT Maximal Coding Rate Reduction (MCR)
Anti-Collapse Mechanism Centering Vector \(c\) + Temperature \(\tau_t\) Sinkhorn-Knopp + Centering Vector Log-Determinant Volume Expansion \(\log\det(\mathbf{I} + \alpha \mathbf{C})\)
Projection Head \(3\)-layer MLP \(\to 65,536\) prototypes \(3\)-layer MLP \(\to 65,536\) prototypes Zero Prototypes • Direct \(\ell_2\) Hypersphere Projection
Hyperparameter Count High (\(\tau_s, \tau_t\), centering momentum \(m\)) Very High (\(\tau\), centering, KoLeo \(\epsilon\), Sinkhorn iters) Minimal (Only distortion \(\varepsilon = 0.05\) & \(\alpha = 1.0\))
ECG Backpropagation Stability Moderate (Prone to collapse if baseline drifts) Moderate (Sinkhorn overhead on variable lengths) Extremely High • Mathematically bounded on \(\mathbb{S}^{1023}\)
✦ Summary & Key Architectural Takeaways for bench-xecg: By integrating continuous multi-crop waveform extraction, spatial-temporal multi-lead patch flattening, a 9-block bidirectional xLSTM backbone, and Maximal Coding Rate Reduction, SimDINOv2 achieves state-of-the-art representation learning on 12-lead electrocardiograms without requiring artificial tokens, heuristic clustering, or million-parameter projection heads. The resulting representations \(\hat{\mathbf{z}} \in \mathbb{S}^{1023}\) preserve fine-grained temporal depolarization dynamics alongside global diagnostic cardiac semantics.