WorksComputer Science
HEART: Hierarchical Expert Adaptive Refinement Transformer for ECG Representation Learning
Abstract
Learning robust representations from electrocardiograms (ECGs) is challenging because repeated cardiac cycles coexist with subtle and sparse diagnostic cues in local morphology and rhythm-level context. Existing ECG foundation models commonly rely on Transformerbased patch encoders with uniformly shared dense refinement pathways, limiting adaptive processing across heterogeneous ECG tokens. We propose HEART (Hierarchical Expert Adaptive Refinement Transformer), an ECG foundation model that introduces stage-specific conditional expert refinement during self-supervised pre-training. HEART places a local-level MoE over patch-level representations before temporal contextualization and a global-level MoE over context-integrated token representations after self-attention. Token-level Top-1 routing allows different patches or contextual tokens within the same ECG to follow different expert pathways. On public ECG benchmarks, HEART achieves strong performance under both linear probing and fine-tuning, with particularly large frozen-encoder gains on PTB-XL Form and Rhythm (+6.76 AUROC points each over the strongest protocol-reproduced baseline). Routing analyses provide qualitative evidence of complementary local and global expert specialization. We release our code and pretrained models at https://anonymous.4open.science/r/HEART-5E9F.
Introduction
Cardiovascular diseases (CVDs) remain the leading cause of mortality worldwide, highlighting the need for accurate, scalable, and robust diagnostic tools. The electrocardiogram (ECG), which records the electrical activity of the heart, is one of the most widely used non-invasive modalities for detecting a broad range of cardiac abnormalities [9]. Recently, automated ECG analysis has moved beyond conventional rule-based systems and task-specific convolutional neural networks (CNNs) toward large-scale self-supervised ECG foundation models [16, 20, 21, 29]. These models have shown strong transferability across diverse downstream tasks by learning general-purpose ECG representations from unlabeled data [3, 13, 21, 35].
Despite these advances, ECG representation learning must account for the distinctive multi-level structure of ECG signals. A standard ECG recording consists of repeated cardiac cycles, yet clinically relevant abnormalities are often reflected in subtle variations of waveform morphology, temporal intervals, ST–T or QT patterns, rhythm organization, and inter-lead relationships [14, 23, 32]. These cues naturally span different representation levels: local waveform variations are expressed within short temporal segments, whereas rhythm organization and inter-lead coordination require longer-range contextual integration. Accordingly, effective ECG representation learning requires models that preserve fine-grained local morphology while integrating global temporal and rhythm-level context.
This local-to-global structure has motivated recent ECG foundation models to adopt Transformer-based patch encoders [16, 20, 21, 29]. Temporal patching provides local units that can encode short-range waveform morphology, while self-attention aggregates information across patches to form context-integrated token representations. However, representation refinement within Transformer blocks is still typically performed by shared dense feed-forward modules applied uniformly across tokens. As a result, both patch-level representations and context-integrated token representations are refined through shared transformation pathways, without explicitly adapting capacity to their different local or global characteristics. This shared refinement structure may limit the ability of existing models to handle heterogeneous ECG patterns across representation levels.
To address this limitation, ECG representation learning may benefit from conditional refinement mechanisms that specialize token processing according to representation-level characteristics. Mixture-of-Experts (MoE) architectures provide a natural framework for such specialization by routing tokens to different expert modules. Prior MoE studies have primarily focused on capacity scaling and sparse computation in large models [15, 22, 39]. However, the use of MoE as a representation-level refinement mechanism remains comparatively underexplored in physiological time-series foundation models. We therefore focus on MoE as a stage-specific representation-refinement mechanism aligned with the hierarchy induced by patch tokenization and self-attention.
In this work, we propose HEART (Hierarchical Expert Adaptive Refinement Transformer), a hierarchical ECG foundation model that treats MoE placement as a representation-learning design axis rather than as a generic scaling component. HEART allocates conditional expert capacity to both local and global representation stages within a self-supervised Transformer-based encoder. Specifically, HEART deploys MoE modules at two complementary stages: (i) a local-level expert refinement stage operating on patch embeddings before temporal context is integrated, and (ii) a global-level expert refinement stage operating on post-attention token representations after context-aware representations are formed. The former targets local waveform morphology and signal quality, whereas the latter targets rhythm-level dependencies. Token-wise Top-1 routing encourages different patches or contextual tokens within the same ECG to follow different expert pathways. Following prior hybrid ECG foundation modeling [29], HEART is pretrained with masked reconstruction and contrastive learning, augmented with auxiliary routing regularization for the MoE modules.
To validate the proposed design, we evaluate HEART on public ECG benchmarks using both linear probing and fine-tuning protocols (Table 1–Table 2). HEART achieves strong performance across tasks, with especially large linear-probing gains on PTB-XL Form and Rhythm (+6.76 AUROC points each over the strongest protocol-reproduced baseline). These frozen-encoder results suggest that downstream-relevant structure is already accessible to a linear classifier, while fine-tuning further improves AUPRC in several settings, including PTB-XL Form, PTB-XL Rhythm, and CPSC2018. We further analyze expert routing and utilization patterns to examine how stage-specific MoE refinement organizes representations across local and global stages.
| Dataset | Random Init. | ECGFounder† | SimCLR | CLoCS | COMET | ST-MEM | MAE | CREMA | CREMA-Max | HEART |
| PTB-XL Super | 86.76 | 91.20 | 89.24 | 89.72 | 90.44 | 81.49 | 87.55 | 91.25 | 91.05 | 92.48 (81.73) |
| PTB-XL Sub | 85.40 | 88.03 | 87.13 | 90.43 | 90.57 | 78.52 | 88.10 | 91.37 | 92.06 | 93.96 (54.04) |
| PTB-XL Form | 63.05 | 82.52 | 74.75 | 77.49 | 75.01 | 66.25 | 77.39 | 80.14 | 81.58 | 88.34 (32.68) |
| PTB-XL Rhythm | 86.08 | 93.61 | 83.07 | 86.34 | 86.00 | 82.53 | 87.07 | 88.92 | 87.18 | 95.68 (55.40) |
| PTB-XL Average | 80.32 | 88.84 | 83.55 | 86.00 | 85.51 | 77.20 | 85.03 | 87.92 | 87.96 | 92.62 (55.96) |
| CPSC2018 | 74.30 | 83.18 | 87.03 | 90.24 | 90.28 | 79.05 | 87.72 | 92.78 | 92.16 | 96.50 (83.03) |
Table 1. Linear-probing performance on PTB-XL and CPSC2018 (AUROC; AUPRC in parentheses where available). Linear classifiers are trained on frozen encoders; PTB-XL Average is the mean over four diagnostic subsets. Non-daggered baselines are protocol-reproduced under our setup. † marks external same-dataset references included only for context and not treated as protocol-matched comparisons. Bold and underline indicate the best and second-best results among protocol-reproduced methods only. CREMA-Max is a parameter-comparable dense CREMA variant.
| Dataset | ECGFounder† | SimCLR | CLoCS | COMET | ECGFM† | ECG-FM† | ST-MEM | MAE | CREMA | CREMA-Max | HEART |
| PTB-XL Super | - | 92.28 | 92.09 | 92.30 | - | - | 87.95 | 92.23 | 92.86 | 91.91 | 92.53 (82.77) |
| PTB-XL Sub | - | 92.04 | 90.78 | 92.20 | - | - | 87.84 | 91.12 | 93.35 | 92.43 | 93.42 (51.90) |
| PTB-XL Form | - | 84.66 | 80.43 | 78.98 | - | - | 72.98 | 85.81 | 87.07 | 83.70 | 88.40 (37.32) |
| PTB-XL Rhythm | - | 91.04 | 91.14 | 91.88 | - | - | 90.68 | 91.29 | 91.94 | 90.48 | 95.09 (60.20) |
| PTB-XL Average | 89.77 | 90.01 | 88.84 | 88.61 | 88.85 | 90.29 | 84.86 | 90.11 | 91.31 | 89.63 | 92.36 (58.05) |
| CPSC2018 | - | 94.33 | 93.87 | 94.21 | 91.91 | - | 93.20 | 95.04 | 95.77 | 95.05 | 97.34 (86.17) |
Table 2. Fine-tuning performance on PTB-XL and CPSC2018 (AUROC; AUPRC in parentheses where available). For protocol-reproduced models, all parameters are optimized end-to-end. † marks external same-dataset references included only for context and not treated as protocol-matched comparisons. Bold and underline indicate the best and second-best results among protocol-reproduced methods only.
Our contributions are summarized as follows:
We introduce stage-specific conditional expert refinement into self-supervised ECG representation learning, aligning local expert refinement with patch-level representations and global expert refinement with context-integrated token representations.
We conduct comprehensive evaluations on public ECG benchmarks under both linear probing and fine-tuning protocols, assessing the transferability of MoE-refined representations across downstream tasks.
We provide detailed analyses of expert routing and utilization, offering qualitative evidence that local- and global-level MoE modules exhibit complementary specialization patterns at different representation levels.
Related Work
ECG Foundation Models and Self-Supervised Representation Learning
Self-supervised learning has become a central paradigm for ECG representation learning, supported by the availability of large-scale unlabeled ECG datasets. Prior studies have explored contrastive learning [13, 35], masked reconstruction [20, 21, 38], and hybrid objectives [29] to learn transferable ECG representations. Masked autoencoding frameworks adapted from vision [8] have been particularly effective for learning temporal continuity and waveform structure through reconstruction-based pretraining.
Recent ECG foundation models have further improved transferability by scaling pretraining corpora, strengthening encoder architectures, and incorporating richer supervision sources [16, 20, 29]. This trend is consistent with broader time-series foundation models, such as MOMENT and MOIRAI, which demonstrate the benefit of large-scale pretraining across heterogeneous time-series datasets [6, 36]. ECG representation learning has also expanded toward multimodal ECG-text models that align ECG signals with clinical reports or language-model-derived knowledge for cross-modal reasoning and zero-shot transfer [2, 17, 34]. While these studies have advanced ECG foundation models through improved objectives, scale, and supervision, conditional specialization within the encoder itself remains comparatively less explored.
Multi-scale and Hierarchical ECG Modeling
ECG analysis requires modeling structure across multiple temporal and physiological scales, including local waveform morphology, beat-level organization, rhythm-level temporal patterns, and cross-lead coordination. Transformer architectures are well-suited for capturing long-range dependencies through self-attention [20, 21, 31], and ViT-style patch tokenization [4] has facilitated large-scale ECG modeling in recent foundation models [16, 29].
Several ECG-targeted approaches have incorporated multi-scale or hierarchical inductive biases, including spatio-temporal masked modeling [21], token-to-rhythm ECG-language supervision [34], heartbeat-based ECG language modeling [10], and architectures based on convolutional branches, multi-resolution tokenization, or lead-aware attention [7, 12]. These studies show that ECG representation learning benefits from explicitly modeling both local signal morphology and higher-level temporal organization. HEART addresses a complementary design question: rather than proposing a general replacement for ECG-specific hierarchical architectures, it studies where token-level conditional expert refinement should be introduced within a self-supervised Transformer-based ECG encoder.
Mixture-of-Experts and Conditional Computation
Mixture-of-Experts (MoE) architectures introduce conditional computation by routing inputs to specialized expert networks. Early sparsely gated MoE models and subsequent large-scale variants showed that model capacity can be increased without a proportional increase in computation [5, 15, 27]. Recent studies have further explored alternative routing and assignment mechanisms, including expert-choice routing and soft expert assignment [22, 39].
MoE has also been applied to representation learning and time-series foundation models. For example, Time-MoE scales time-series forecasting models through sparse experts [28], while ECG-related studies have explored expert-style mechanisms for downstream adaptation, task-specific specialization, or model fusion [19, 37]. In contrast to MoE, primarily used for scaling, forecasting, adaptation, or ensemble-style modeling, HEART uses MoE as a conditional refinement mechanism during self-supervised ECG pretraining. By placing expert modules at both local patch-level and global context-integrated stages, HEART investigates stage-specific expert specialization over heterogeneous ECG representations.
Proposed Method: HEART
We propose HEART (Hierarchical Expert Adaptive Refinement Transformer), a self-supervised ECG foundation model that introduces stage-specific conditional expert refinement into a Transformer-based encoder. HEART applies expert refinement at two complementary representation stages: a local-level MoE operates on patch-level representations before temporal contextualization, whereas a global-level MoE operates on context-integrated token representations after self-attention. HEART therefore studies where token-level conditional capacity should be placed within the ECG representation hierarchy, rather than proposing a new routing algorithm or replacing ECG-specific hierarchical architectures. An overview of HEART is shown in Figure 1.

Figure 1. Overview of HEART. Local-level MoE refines patch embeddings, and global-level MoE refines final encoder tokens.
Architecture Overview
Given an input ECG , where denotes the number of leads and denotes the temporal length, HEART first divides the signal into temporal patches:
Each patch is encoded into a patch-level representation:
These patch embeddings define the local representation space before temporal context is aggregated by the Transformer encoder.
Local-level expert refinement. The local-level MoE operates on patch embeddings before self-attention. For each patch representation , the router selects one local expert and produces a refined patch representation:
where denotes the selected local expert and is the routing probability for expert . This stage targets local waveform characteristics, such as morphology and noise patterns, before temporal context is aggregated. Since routing is performed at the patch level, different segments within the same ECG can activate different local experts.
Masking and Transformer encoding. After local expert refinement, positional embeddings are added, and random masking is applied for masked autoencoding. Only visible tokens are passed to the Transformer encoder together with a prepended [CLS] token:
where denotes the [CLS] token, denotes the visible locally processed patch tokens, and is the number of visible patches. The masked positions are not provided to the encoder and are reconstructed by the decoder during pre-training.
Global-level expert refinement. The global-level MoE operates on post-attention token representations. At this stage, each token has incorporated temporal and cross-lead context through the Transformer encoder. In our implementation, global expert refinement is applied as a residual update:
This stage targets context-integrated representations associated with rhythm-level dependencies, distributed temporal patterns, and cross-lead coordination. The [CLS] token participates in global-level routing and serves as the sequence-level representation for downstream classification, but it is not used as a reconstruction target.
MAE-style decoder. For masked reconstruction, after removing the [CLS] token from the encoder output, the visible token representations are projected to the decoder dimension, combined with learnable mask tokens, and reordered to match the original patch sequence. The reordered tokens are processed by Transformer decoder blocks, followed by a linear prediction head that reconstructs each ECG patch. The reconstruction loss is computed only over masked patches, and the decoder is discarded during downstream evaluation.
Unified Token Routing
Both local- and global-level MoE modules use the same Top-1 token routing mechanism. Given a token representation, the router computes expert probabilities and dispatches the token to the expert with the highest probability:
A capacity constraint is applied to prevent expert overloading. For a batch of routed tokens and experts, each expert can process at most
tokens. Tokens exceeding the capacity of their selected expert are not dispatched to that expert. This constraint encourages balanced use of experts during pre-training.
Rationale for Top-1 token routing. We use Top-1 routing as a scoped design choice for clear token-level specialization rather than as a claim of superiority over alternative routing strategies. For ECG representation learning, this assigns each local or contextual token to a single expert pathway while still allowing a single ECG recording to activate multiple experts across its sequence. This is important because many ECG segments may contain recurring beat patterns, whereas diagnostically relevant variations can appear sparsely in specific patches or context-dependent tokens. Thus, Top-1 routing encourages sharper expert specialization at the token level without imposing a one-expert-per-sample partition.
Detailed routing equations, including noisy routing, load balancing, entropy regularization, and router logit regularization, are provided in Appendix § 9.
Training Objective
HEART is trained with generative, contrastive, and auxiliary routing objectives during self-supervised pre-training. The generative and contrastive objectives follow standard formulations from prior hybrid ECG foundation modeling [29]; therefore, we briefly summarize their roles and focus on the routing-specific objective introduced by the MoE modules.
Generative and contrastive objectives. The generative objective follows masked autoencoding [8]: the decoder reconstructs masked ECG patches from visible tokens and learned mask tokens, and the reconstruction loss is computed over masked positions. This objective encourages the encoder to preserve local waveform structure and temporal continuity.
The contrastive objective follows an InfoNCE-style formulation [3, 29]. It is applied to sequence-level [CLS] representations obtained from different ECG views, encouraging globally discriminative ECG embeddings. Together, the generative and contrastive objectives provide complementary supervision for local waveform reconstruction and global representation separability.
Auxiliary routing objective. The MoE modules introduce Top-1 routing, where each token is assigned to a single expert under a capacity constraint. To stabilize routing and reduce expert collapse, HEART uses an auxiliary routing objective consisting of load balancing, routing entropy, and router logit regularization:
where encourages distributed expert utilization, promotes routing exploration, and regularizes the magnitude of router logits. The same auxiliary loss form is applied to both local- and global-level MoE modules during pre-training.
Total pre-training objective. The final pre-training objective is
where and denote the masked reconstruction and contrastive objectives, respectively. The coefficients and control the contributions of contrastive learning and routing regularization. The decoder and auxiliary routing losses are used only during self-supervised pre-training. During downstream evaluation, HEART retains the pretrained encoder, including the local- and global-level MoE modules, and uses a conventional dense classifier head on the final [CLS] representation.
Evaluation
Datasets
Pre-training. We pre-trained HEART using five large-scale ECG datasets available for research use: MIMIC [11], CODE15 [24], UK Biobank [30], SAMI [25], and IKEM [26]. In total, the pre-training corpus comprises approximately 1.29 million ECG recordings from 442,000 patients, covering heterogeneous ECG sources across multiple cohorts and acquisition settings.
Downstream. For downstream evaluation, we use PTB-XL [33], which contains approximately 21,000 ECGs annotated across four diagnostic subsets (Super, Sub, Form, and Rhythm), and CPSC2018 [18], which includes approximately 6,900 ECGs annotated with nine diagnostic labels. For PTB-XL, we follow the official split protocol using folds 1–8 for training, fold 9 for validation, and fold 10 for testing. For CPSC2018, we follow the split protocol used in prior ECG foundation model studies [29]. The same downstream splits are used for HEART and all protocol-reproduced baselines. PTB-XL and CPSC2018 are not included in the pre-training corpus, and no downstream evaluation records are used during pre-training.
Preprocessing. All ECG signals used for both pre-training and downstream evaluation are resampled to 250 Hz and truncated or padded to a fixed duration of 10 seconds. The same preprocessing pipeline is applied to HEART and all protocol-reproduced baselines.
Implementation Details
We implement HEART in PyTorch. Unless otherwise specified, HEART is pre-trained with a batch size of 256 using AdamW (, ), an initial learning rate of , linear warmup, and cosine decay. The contrastive loss weight is set to , while module-specific auxiliary routing weights are selected by hyperparameter optimization. During pre-training, MoE optimization is stabilized using capacity constraints, auxiliary routing regularization, input jitter, and noisy gating. Detailed architectural and optimization hyperparameters are provided in Appendix § 8.
For downstream evaluation, the pre-training decoder is discarded, and the final [CLS] representation is passed to a conventional dense classifier. The pretrained local- and global-level MoE modules are retained as part of the downstream encoder. Auxiliary routing losses are used during pre-training and fine-tuning, but not for linear probing. In linear probing, the pretrained encoder, including the MoE routers and experts, is frozen, and only the classifier is trained. In fine-tuning, the encoder and classifier are updated end-to-end.
Baselines and Comparison Protocol
We separate baseline results into protocol-reproduced baselines and external reference results. For protocol-reproduced baselines, we re-evaluate SimCLR, CLOCS, COMET, ST-MEM, MAE, and CREMA using the available code, following our preprocessing and downstream evaluation protocol when possible [3, 8, 13, 21, 29, 35]. These baselines are used as the primary basis for direct comparison.
For methods whose training code or protocol is not publicly available and directly reproducible in our setting, including ECGFounder, ECGFM, and ECG-FM, we report results from the original publications or public benchmark releases, when available, on the same downstream dataset [1, 16, 20, 38]. Because these results may differ due to label aggregation, data splits, preprocessing, signal windows, or adaptation strategies, they are treated as contextual references rather than protocol-matched baselines. For PTB-XL, this distinction is particularly important because our tables report the four official diagnostic subsets, whereas some external baselines report a single aggregate over the full fine-grained PTB-XL label space.
We additionally construct CREMA-Max as a dense-capacity control. CREMA-Max follows the same pre-training corpus and downstream evaluation protocol as CREMA and HEART, while increasing the encoder dimension from 1024 to 1488, the encoder depth from 4 to 13, and the pre-training decoder depth from 2 to 4. This baseline assesses whether HEART’s improvements are attributable to conditional expert routing rather than dense parameter scaling alone.
Results
Linear probing. Table 1 reports linear-probing performance on PTB-XL and CPSC2018. Linear probing evaluates the quality of pretrained representations by training a linear classifier on top of a frozen encoder.
Across all PTB-XL diagnostic subsets, HEART achieves the highest AUROC among protocol-reproduced methods. Compared with contrastive baselines such as SimCLR, CLoCS, and COMET, and reconstruction-based baselines such as ST-MEM and MAE, HEART shows consistently stronger frozen-encoder performance. The largest gains appear on PTB-XL Form and Rhythm, where HEART improves over the strongest protocol-reproduced baseline by +6.76 AUROC points in both cases, corresponding to relative improvements of +8.29% and +7.60%, respectively. These two subsets are closely related to waveform-form characteristics and rhythm-level temporal organization, making the large margins consistent with HEART’s stage-specific refinement of local and context-integrated representations.
On average, HEART reaches 92.62 AUROC across the four PTB-XL subsets, exceeding the strongest protocol-reproduced baseline by +4.66 AUROC points (+5.30% relative). On CPSC2018, HEART also achieves the highest linear-probing AUROC, reaching 96.50 and improving over the strongest protocol-reproduced baseline by +3.72 AUROC points (+4.01% relative).
Overall, these results suggest that HEART learns representations in which downstream-relevant structure is already accessible to a linear classifier.
Fine-tuning. Table 2 reports fine-tuning results, where all parameters are optimized end-to-end for protocol-reproduced models. Under fine-tuning, several baselines improve substantially, and CREMA remains a strong dense baseline. Nevertheless, HEART achieves the highest AUROC on PTB-XL Sub, Form, Rhythm, and the four-task average, while remaining competitive on Super. On CPSC2018, HEART also achieves the highest AUROC among protocol-reproduced baselines, reaching 97.34.
Fine-tuning mainly improves HEART’s precision–recall behavior in several settings. Compared with linear probing, HEART increases AUPRC on PTB-XL Form from 32.68 to 37.32 (+4.64; +14.20% relative), on PTB-XL Rhythm from 55.40 to 60.20 (+4.80; +8.66% relative), and on CPSC2018 from 83.03 to 86.17 (+3.14; +3.78% relative). The PTB-XL four-task average AUPRC also increases from 55.96 to 58.05 (+2.09; +3.74% relative). These results suggest that end-to-end adaptation can further refine precision–recall trade-offs, especially for tasks where positive-label identification is more sensitive to classifier calibration and task-specific adaptation.
At the same time, HEART’s fine-tuned AUROC remains close to its linear-probing AUROC. This pattern suggests that the pretrained encoder already provides representations in which downstream-relevant structure is accessible to a simple classifier, while fine-tuning further adjusts the decision boundary and precision–recall trade-off for several tasks.
Dense capacity control. To test whether HEART’s gains can be explained by dense parameter scaling alone, we compare against CREMA-Max, a parameter-comparable dense CREMA variant. Across both linear probing and fine-tuning, CREMA-Max does not consistently improve over the original CREMA, whereas HEART achieves stronger average performance. This suggests that the observed gains are more closely associated with stage-specific conditional expert refinement than with uniformly increasing dense model capacity.
Ablation Studies
We conduct ablation studies on CPSC2018 to examine how individual design components in HEART affect representation quality. We use CPSC2018 as a representative controlled setting to isolate the effect of MoE placement under the same data splits and training protocols as the main experiments.
Effect of MoE placement. Table 3 shows that adding either local- or global-level MoE improves over the dense CREMA backbone. The full HEART configuration achieves the best performance across all metrics, supporting the benefit of combining local patch-level transformation with global context-aware refinement. Under the selected expert settings, the local-only variant shows slightly larger gains than the global-only variant, indicating that patch-level conditional transformation is an important contributor to the observed improvement.
| CPSC2018 | AUROC | AUPRC | F1-score | Sensitivity (SPEC=0.98) |
| CREMA | 95.77 | 81.15 | 76.67 | 76.44 |
| Local-level MoE | 96.30 | 85.34 | 79.26 | 77.45 |
| Global-level MoE | 96.04 | 83.59 | 77.83 | 76.78 |
| HEART | 97.34 | 86.17 | 80.55 | 79.67 |
Table 3. MoE placement ablation on CPSC2018 under fine-tuning. CREMA is the dense backbone. Local/Global variants add one MoE at the patch-embedding or context-integrated encoder stage, respectively. HEART uses both local- and global-level MoE modules. Sensitivity is evaluated at specificity = 0.98.
Sensitivity to the number of experts. We examine the sensitivity of HEART to the number of experts by varying local- and global-level expert counts while keeping all other settings fixed. Figure 2 reports AUROC and AUPRC for combinations of {4, 8, 16} experts at each level.

Figure 2. Expert-count sensitivity on CPSC2018. Cells sweep local/global expert counts with all other settings fixed; AUROC (left) is stable, while AUPRC (right) is more capacity-sensitive.
Across configurations, AUROC varies within a narrow range, indicating that ranking-based discrimination is relatively robust to expert count. In contrast, AUPRC shows greater sensitivity to expert capacity. In particular, configurations with more global-level experts tend to improve AUPRC on CPSC2018, suggesting that additional context-aware expert capacity can help improve precision–recall performance in imbalanced settings. Based on these observations, we select the configuration that provides the best overall performance while maintaining reasonable model complexity for the main experiments.
Model efficiency and performance trade-off. Table 4 reports model size, inference latency, and representation quality under the PTB-XL Average linear-probing setting. Latency is measured as encoder forward time with batch size 1 on a single GPU using mixed precision, averaged over 10 runs after warm-up. Compared with the original CREMA, HEART requires more parameters and higher latency, but provides a substantially larger representation gain. Compared with CREMA-Max, HEART achieves substantially higher AUROC with lower latency, suggesting that conditional expert capacity is more effective than uniformly scaling the dense encoder in this setting. Overall, this comparison supports that HEART’s representation gain is unlikely to be explained by parameter count alone.
| Model | Params (M) | Size (MB) | Inference (ms) | AUROC | Δ |
| CREMA | 22.09 | 96.34 | 3.26 | 87.92 | +0.00 |
| CREMA-Max | 177.60 | 677.50 | 13.22 | 87.96 | +0.04 |
| HEART | 161.83 | 633.52 | 9.33 | 92.62 | +4.70 |
Table 4. Model size and inference cost for a 10-second 12-lead ECG. AUROC is PTB-XL Average under linear probing; Δ denotes the AUROC gain over CREMA. Parameter counts follow the pretrained model configuration; latency uses encoder-forward inference.
Qualitative Analysis
To complement the quantitative results, we analyze HEART under the PTB-XL Rhythm linear-probing setting. The frozen-encoder nature of linear probing allows us to examine the representation structure and routing behavior learned during self-supervised pre-training. We focus on the Rhythm subset as it contains temporally organized ECG patterns, making it suitable for analyzing context-integrated representations and expert utilization. The following analyses provide qualitative diagnostics of the pretrained encoder and its stage-specific routing behavior.
Representation space. We first examine whether rhythm-related structure is already present in the pretrained representation. Figure 3 compares UMAP visualizations of frozen encoder [CLS] embeddings and the output space of the trained linear-probing classifier. The frozen encoder embeddings form structured regions associated with rhythm labels, qualitatively suggesting that rhythm-relevant information is already present before task-specific adaptation. After linear probing, several rhythm categories become more clearly separated, while the overall class organization remains qualitatively similar. This pattern is consistent with the strong linear-probing results in Table 1: the classifier appears to sharpen an already informative representation space, rather than relying entirely on classifier-side separation.

Figure 3. UMAP visualization of frozen HEART [CLS] embeddings and the output space of the trained linear-probing classifier on PTB-XL Rhythm.
Temporal allocation of experts. We next visualize how token-level routing operates within an individual ECG recording. Figure 4 shows one 12-lead ECG example together with the Top-1 expert selected for each overlapping temporal patch. The upper waveform panel provides the temporal ECG context, while the lower allocation panels show how local- and global-level expert IDs change along the same time axis.

Figure 4. Patch-wise expert allocation for one ECG example. The top panel overlays the 12-lead ECG waveform, and the lower panels show the Top-1 expert IDs assigned across overlapping temporal patches for the local- and global-level MoE modules. Changes along the temporal axis indicate that different patches or contextual tokens within the same ECG can be routed to different experts.
The selected experts vary across temporal segments, illustrating that HEART does not assign an entire ECG recording to a single expert. Instead, different waveform segments and context-integrated tokens can activate different experts within the same sample. At the local level, routing varies across patch-level waveform segments before temporal contextualization. At the global level, routing is applied after self-attention, where token representations have already integrated temporal and cross-lead context. This example illustrates the intended token-level nature of HEART’s conditional expert processing.
Expert utilization across rhythm labels. To examine whether expert usage differs across rhythm conditions, we aggregate expert assignments across patches and compare the resulting utilization distributions for each rhythm label. Figure 5 and Figure 8 (in the Appendix) provide complementary views of the same analysis: the JS divergence heatmaps summarize pairwise differences between label-conditioned expert-utilization distributions, while the histograms show the corresponding expert-wise utilization profiles for each rhythm label.

Figure 5. Jensen–Shannon divergence between expert-utilization distributions across PTB-XL Rhythm labels. For each target label, positive samples are ECGs annotated with that rhythm label, whereas negative samples are ECGs without that target label. Divergence values are computed from patch-aggregated expert-utilization distributions and shown separately for the local- and global-level MoE modules.
Figure 8. Patch-aggregated expert-utilization histograms across PTB-XL Rhythm labels. Each panel shows how often each expert is selected for positive and negative samples of a target rhythm label, separately for the local- and global-level MoE modules.
As shown in Figure 5, positive groups exhibit larger JS divergence across rhythm labels than the corresponding negative groups. This suggests that target-positive rhythm patterns are associated with more label-specific expert-utilization profiles. The histograms in Figure 8 further show how these differences appear at the expert level: local-level utilization is relatively distributed across experts, whereas global-level utilization is more peaked for several rhythm labels.
By contrast, negative groups show near-zero JS divergence across labels, partly because each negative group is defined by the absence of one target rhythm label and can overlap substantially with negative groups for other labels in a multi-label setting. Thus, the positive–negative contrast is best understood as qualitative support for label-conditioned routing in target-positive samples, without implying that all negative ECGs share a common physiological pattern.
Together, the JS divergence and histogram views are consistent with the intended hierarchy of HEART: local experts tend to exhibit more distributed patch-level usage, while global experts show stronger label-conditioned preferences over context-integrated token representations.
Expert-associated morphological prototypes. Finally, we examine expert-associated ECG patterns using representative routed patches. Each displayed patch contains 60 time points, corresponding to approximately 0.24 seconds of the 250 Hz ECG signal. For each expert, we select the routed token closest to the expert-specific centroid in representation space and visualize its corresponding raw ECG patch, so each prototype is a real ECG segment rather than an averaged waveform. Figure 6 shows each selected 12-lead patch together with its normalized per-lead temporal variance profile. The bar plot summarizes the relative magnitude of temporal variance across leads within the displayed patch.

Figure 6. Representative ECG patch prototypes for each expert. Each panel shows an actual routed ECG patch selected near the expert-specific centroid, together with its normalized per-lead variance profile. The prototype is a real ECG segment rather than an averaged waveform, and the bar plot summarizes relative lead-wise variation rather than causal attribution.
Local-level prototypes correspond to pre-contextualized patch representations and can therefore be interpreted as short patch-scale waveform patterns associated with each local expert. Across local experts, the selected prototypes show visible differences in waveform shape, baseline stability, sharp deflections, and noise-related variation, suggesting separation of short-range morphological and signal-quality patterns. In contrast, global-level prototypes correspond to post-attention tokens; the displayed raw patch is the temporal anchor of a context-integrated representation routed to the expert, rather than the isolated local motif that determined routing. Across global
experts, the anchor patches show distinct waveform motifs and lead-variance profiles, suggesting that context-aware routing is associated with different temporal or cross-lead patterns. Overall, these observations are consistent with complementary local and global expert behavior, while remaining qualitative rather than causal evidence.
Conclusion
We presented HEART, a hierarchical ECG foundation model that introduces stage-specific conditional expert refinement into self-supervised ECG representation learning. By placing MoE modules at both patch-level and context-integrated representation stages, HEART enables token-level specialization within a single ECG recording. Across PTB-XL and CPSC2018, HEART achieves strong performance under both linear probing and fine-tuning, with particularly strong frozen-encoder results suggesting that downstream-relevant structure is already accessible to a linear classifier. The comparison with CREMA-Max further suggests that HEART’s gains are not explained by dense parameter scaling alone. Qualitative analyses illustrate patch-wise routing, label-conditioned expert utilization, and expert-associated waveform motifs, providing complementary evidence for local and global expert specialization. Together, these findings support stage-specific MoE placement as an ECG-motivated design bias for self-supervised representation learning.
Limitations and Future Work
HEART empirically studies stage-specific MoE refinement within a self-supervised Transformer ECG encoder, but does not theoretically characterize how expert specialization emerges. Some external comparisons rely on reported results due to unavailable implementations or checkpoints and should therefore be interpreted as contextual references. Our qualitative analyses are illustrative rather than causal; future work will extend routing analyses across broader ECG tasks and datasets to better understand expert specialization.
References
Implementation Details and Hyperparameter Search
Table 5 summarizes the hyperparameter search space. The final configuration was selected based on validation performance.
| Component | Hyperparameter | Distribution | Range / Categories |
| Network | resnet.kernel_size | choice | |
| Network | resnet.dropout | choice | |
| Network | resnet.num_blocks | choice | |
| Network | encoder_depth | choice | |
| Network | encoder_num_heads | choice | |
| Network | decoder_depth | choice | |
| Network | decoder_num_heads | choice | |
| Local-level MoE | patch_capacity_factor | loguniform | |
| Local-level MoE | patch_router_z_loss_coef | loguniform | |
| Local-level MoE | patch_aux_loss_coef | loguniform | |
| Local-level MoE | patch_jitter_noise | loguniform | |
| Global-level MoE | capacity_factor | loguniform | |
| Global-level MoE | router_z_loss_coef | loguniform | |
| Global-level MoE | aux_loss_coef | loguniform | |
| Global-level MoE | jitter_noise | loguniform | |
| Optimizer (AdamW) | weight_decay | loguniform | |
| Optimizer (AdamW) | lr | loguniform |
Table 5. Hyperparameter search space used for HEART.
The selected HEART configuration uses 12-lead ECGs of 10 seconds at 250 Hz (), divided into patches of size with 50% overlap, yielding 82 temporal patches. The patch embedding module consists of a convolutional stem with a kernel size of 15, followed by a lightweight 1D ResNet. The encoder uses dimension , depth , and attention heads. The local- and global-level MoE modules use 8 and 16 MLP experts, respectively, with GELU activation, RMSNorm, a dropout rate of 0.0, and capacity factors of approximately 1.32 and 1.76. The contrastive loss weight is set to ; the local auxiliary and router -loss weights are 0.005 and 0.0008, while the corresponding global weights are 0.017 and 0.002.
The raw ECG is processed by the convolutional stem and lightweight 1D ResNet patch embedding module before local-level MoE refinement, while the global-level MoE is applied at the context-integrated encoder stage. Both MoE modules use Top-1 routing with input jitter and noisy gating.
Detailed Routing Objective
Both local- and global-level MoE modules use the same routing formulation. For token representation , the router computes base logits with optional input jitter:
With noisy gating, the routing logits, probabilities, and Top-1 assignment are defined as:
Each expert processes at most
tokens, where is the number of routed tokens, is the number of experts, and is the capacity factor. Let denote the final dispatch mask after capacity filtering. For expert , the dispatched token fraction, mean routing probability, and load-balancing loss are:
The auxiliary routing objective further includes routing entropy and router logit regularization:
Here, is computed on the base router logits before Gaussian noise and temperature scaling. For one MoE module, the auxiliary loss is:
The auxiliary routing losses are used only during self-supervised pre-training and are inserted into the total objective in Eq. (9).
Received 23 May 2026
References
- [1]M. A. Al-Masud, Juan Miguel Lopez Alcaraz, and Nils Strotdhoff. 2026. Benchmarking ECG FMs: A Reality Check Across Clinical Tasks. In The Fourteenth International Conference on Learning Representations. https://openreview.net/forum?id=xXRqWpt3Xrarxiv.org/abs/2509.25095
- [2]Jian Chen, Xiaoru Dong, Wei Wang, Shaorui Zhou, Lequan Yu, and Xiping Hu. 2025. DERI: Cross-Modal ECG Representation Learning with Deep ECG-Report Interaction. In Proceedings of the International Joint Conference on Artificial Intelligence.DOI
- [3]Ting Chen, Simon Kornblith, Mohammad Norouzi, and Geoffrey Hinton. 2020. A Simple Framework for Contrastive Learning of Visual Representations. In Proceedings of the International Conference on Machine Learning.arxiv.org/abs/2002.05709
- [4]Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, et al. 2020. An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. arXiv preprint arXiv:2010.11929 (2020).
- [5]William Fedus, Barret Zoph, and Noam Shazeer. 2022. Switch transformers: Scaling to trillion parameter models with simple and efficient sparsity. Journal of Machine Learning Research (2022).
- [6]Mononito Goswami, Konrad Szafer, Arjun Choudhry, Yifu Cai, Shuo Li, and Artur Dubrawski. 2024. MOMENT: A Family of Open Time-Series Foundation Models. In Proceedings of the International Conference on Machine Learning.arxiv.org/abs/2402.03885
- [7]Alexander Hammer, Marc Goettling, Hagen Malberg, Axel Linke, Sergio Richter, Norman Mangner, and Martin Schmidt. 2025. Fusion of automatically learned rhythm and morphology features matches diagnostic criteria and enhances AI explainability. npj Artificial Intelligence 1, Article 19 (2025). doi:10.1038/s44387-025-00022-wDOI
- [8]Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, and Ross Girshick. 2022. Masked Autoencoders are Scalable Vision Learners. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition.arxiv.org/abs/2111.06377
- [9]William Hinton, Andrew McGovern, Rachel Coyle, Thang S Han, Pankaj Sharma, Ana Correa, Filipa Ferreira, and Simon de Lusignan. 2018. Incidence and prevalence of cardiovascular disease in English primary care: a cross-sectional and follow-up study of the Royal College of General Practitioners (RCGP) Research and Surveillance Centre (RSC). British Medical Journal Open (2018).DOI
- [10]Jiarui Jin, Haoyu Wang, Hongyan Li, Jun Li, Jiahui Pan, and Shenda Hong. 2025. Reading Your Heart: Learning ECG Words and Sentences via Pre-training ECG Language Model. In Proceedings of the International Conference on Learning Representations.arxiv.org/abs/2502.10707
- [11]Alistair E W Johnson, Tom J Pollard, Lu Shen, Li-wei H Lehman, Mengling Feng, Mohammad Ghassemi, Benjamin Moody, Peter Szolovits, Leo Anthony Celi, and Roger G Mark. 2016. MIMIC-III, A Freely Accessible Critical Care Database. Scientific Data (2016).DOI
- [12]Chen Kan, Zehao Ye, Houliang Zhou, and Sreekanth R. Cheruku. 2023. DG-ECG: Multi-stream deep graph learning for the recognition of disease-altered patterns in electrocardiogram. Biomedical Signal Processing and Control 80, Article 104388 (2023). doi:10.1016/j.bspc.2022.104388
- [13]Dani Kiyashesh, Tingting Zhu, and David A Clifton. 2020. CloCS: Contrastive Learning of Cardiac Signals. arXiv preprint arXiv:2005.13249 (2020).
- [14]Paul Kligfield, Leonard S. Gettes, Janey J. Bailey, Barbara J. Deal, E. William Hancock, Gerard and Herpen, Jan A. Kors, Peter Macfarlane, David M. Mirvis, Olle Pahlm, Pentti M. Rautaharju, Galen S. Wagner, and Mark Josephson. 2007. Recommendations for the Standardization and Interpretation of the Electrocardiogram: Part I: The Electrocardiogram and Its Technology. Journal of the American College of Cardiology 49, 10 (2007), 1109–1127. doi:10.1016/j.jacc.2007.01.024DOI
- [15]Dmitry Lepikhin, HyoukJoong Lee, Yuanzhong Xu, Dehao Chen, Orhan Firat, Yanping Huang, Maxim Krikun, Noam Shazeer, and Zhifeng Chen. 2020. Gshard: Scaling giant models with conditional computation and automatic sharding. arXiv preprint arXiv:2006.16668 (2020).
- [16]Jun Li, Aaron Aguirre, Junion Moura, Che Liu, Lanhai Zhong, Chenxi Sun, Gari Clifford, Brandon Westover, and Shenda Hong. 2024. An electrocardiogram foundation model built on over 10 million recordings with external evaluation across multiple domains. arXiv preprint arXiv:2410.04133 (2024).arxiv.org/abs/2410.04133
- [17]Che Liu, Zhongwei Wan, Chengyang Anan, Shanh Wai, Benja Bai, and Rossella Arcucci. 2024. Zero-shot ecg classification with multimodal learning and test-time clinical knowledge enhancement. arXiv preprint arXiv:2403.06659 (2024).arxiv.org/abs/2403.06659
- [18]Feifei Liu, Chengyu Liu, Lina Zhao, Xiangyu Zhang, Xiaoling Wu, Xiaoyan Xu, Yulin Liu, Caiyun Ma, Shoushui Wei, Zhiqiang He, et al. 2018. An Open Access Database for Evaluating the Algorithms of Electrocardiogram Rhythm and Morphology Abnormality Detection. Journal of Medical Imaging and Health Informatics (2018).DOI
- [19]Natan Mansourian, Arash Mohammadi, M. Omair Ahmad, and M. N. S. Swamy. 2025. ECG-EmotionNet: Nested Mixture of Expert (NMoE) Adaptation of ECG Foundation Model for Driver Emotion Recognition. arXiv preprint arXiv:2503.01750 (2025).
- [20]Kaden McKeen, Laura Oliva, Sameer Masood, Augustin Toma, Barry Rubin, and Bo Wang. 2024. ECG-FM: An Open Electrocardiogram Foundation Model. arXiv preprint arXiv:2408.05178 (2024).arxiv.org/abs/2408.05178
- [21]Yeongyeon Na, Minje Park, Yunton Tae, and Sunghoon Joo. 2024. Guiding Masked Representation Learning to Capture Spatio-Temporal Relationship of Electrocardiogram. arXiv preprint arXiv:2402.09450 (2024).
- [22]Joan Puigcerver, Carlos Riquelme, Basil Mustafa, and Neil Houlsby. 2023. From sparse to soft mixtures of experts. arXiv preprint arXiv:2308.00951 (2023).arxiv.org/abs/2308.00951
- [23]Pentti M. Rautaharju, Borys Surawicz, Leonard S. Gettes, et al. 2009. AHA/ACCF/HRS Recommendations for the Standardization and Interpretation of the Electrocardiogram: Part IV: The ST Segment, T and U Waves, and the QT Interval. Journal of the American College of Cardiology 53, 11 (2009), 982–991. doi:10.1016/j.jacc.2008.12.014
- [24]Antônio H. Ribeiro, Gabriela M.M. Paixao, EmilIy M. Lima, Manoel Horta Ribeiro, Marcelo M. Pinto Filho, Paulo R. Gomes, Derick M. Oliveira, Wagner Meira Jr, Thömas B Schon, and Antonio Luiz P. Ribeiro. 2021. CODE-15%: A Large Scale Annotated Dataset of 12-lead ECGs. (2021).
- [25]Antonio Luiz P. Ribeiro, Antônio H. Ribeiro, Gabriela M.M. Paixao, EmilIy M. Lima, Manoel Horta Ribeiro, Marcelo M. Pinto Filho, Paulo R. Gomes, Derick M. Oliveira, Wagner Meira Jr, Thömas B Schon, and Ester C Sabino. 2021. SaMi-Trop: 12-lead ECG Traces with Age and Mortality Annotations. (2021).DOI
- [26]Michal Šejak, Jakub Sido, and David Záhoř. 2023. IKEM Dataset v1.0.0. (2023).DOI
- [27]Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. 2017. Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer. arXiv preprint arXiv:1701.06538 (2017).arxiv.org/abs/1701.06538
- [28]Xiangmo Shi, Shiyu Wang, Yuqi Nie, Dianqi Li, Zhou Ye, Qingsong Wen, and Ming Jin. 2025. Time-MoE: Billion-Scale Time Series Foundation Models with Mixture of Experts. In Proceedings of the International Conference on Learning and Representations.
- [29]Junho Song, Jong-Hwan Jang, Byeong Tak Lee, DongGyun Hong, Joon-myoung Kwon, and Yong-Yeon Jo. 2024. Foundation models for ecg: Leveraging hybrid self-supervised learning for advanced cardiac diagnostics. arXiv preprint arXiv:2407.07110 (2024).
- [30]Cathie Sudlow, John Gallacher, Naomi Allen, Valerie Beral, Paul Burton, John Danesh, Paul Downey, Paul Elliott, Jane Green, Martin Landray, et al. 2015. UK Biobank: An Open Access Resource for Identifying the Causes of a Wide Range of Complex Diseases of Middle and Old Age. PLoS Medicine (2015).DOI
- [31]A Vaswani. 2017. Attention is all you need. Advances in Neural Information Processing Systems (2017).arxiv.org/abs/1706.03762
- [32]Galen S. Wagner, Peter Macfarlane, Hein Wellens, Mark Josephson, Anton Gorgels, David M. Mirvis, Olle Pahlm, Borys Surawicz, Paul Kligfield, Rory Childers, Leonard S. Gettes, James J. Bailey, Barbara J. Deal, E. William Hancock, Jan A. Kors, Jay W. Mason, Peter O. P. Pentti M. Rautaharju, and Gerard van Herpen. 2009. AHA/ACCF/HRS Recommendations for the Standardization and Interpretation of the Electrocardiogram: Part VI: Acute Ischemia/Infarction. Journal of the American College of Cardiology 53, 11 (2009), 1003–1011. doi:10.1016/j.jacc.2008.12.016
- [33]Patrick Wagner, Nils Strotdhoff, Ralf-Dieter Bousseljot, Dieter Kreiseler, Fatima I Lunze, Wojciech Samek, and Tobias Schaeffter. 2020. PTB-XL, a large publicly available electrocardiography dataset. Scientific Data (2020).DOI
- [34]Fuying Wang, Jiacheng Hu, and Lequan Yu. 2025. From Token to Rhythm: A Multi-Scale Approach for ECG-Language Pretraining. arXiv preprint arXiv:2506.21803 (2025).arxiv.org/abs/2506.21803
- [35]Yihe Wang, Yu Han, Haishuai Wang, and Xiang Zhang. 2023. Contrast everything: A hierarchical contrastive framework for medical time-series. Advances in Neural Information Processing Systems (2023).arxiv.org/abs/2310.14017
- [36]Gerald Woo, Chansoo Liu, Akshat Kumar, Caiming Xiong, Silvio Savarese, and Doyen Sahoo. 2024. Unified Training of Universal Time Series Forecasting Transformers. In Proceedings of the International Conference on Machine Learning.arxiv.org/abs/2402.02592
- [37]Yuan Xu, Xiaoda Wang, Jiaying Lu, Sirui Ding, Defu Cao, Huaxiu Yao, Yan Liu, Xiao Hu, and Carl Yang. 2025. EnECG: Efficient Ensemble Learning for Electrocardiogram Multi-task Foundation Model. arXiv preprint arXiv:2511.22935 (2025).arxiv.org/abs/2511.22935
- [38]Shaoting Zhang, Yishan Du, Wenji Wang, XianyIng He, Fangfang Cui, Liang Zhao, Bei Wang, Zhiqiang Hu, Ziqiang Wang, Qing Xia, et al. 2025. ECGFM: A foundation model for ECG analysis trained on a multi-center million-ECG dataset. Information Fusion (2025).DOI
- [39]Yanqi Zhou, Tao Lei, Hanxiao Liu, Nan Du, Yanping Huang, Vincent Zhao, Andrew M Dai, Quoc V Le, James Laudon, et al. 2022. Mixture-of-experts with expert choice routing. Advances in Neural Information Processing Systems (2022).arxiv.org/abs/2202.09368
