AnyECG: Foundational Models for Multitask Cardiac Analysis in Real-World Settings

Yue Wang, Xu Cao, Yaojun Hu, Haochao Ying, Hongxia Xu, Ruijia Wu, James Matthew Rehg, Jimeng Sun, Jian Wu, Jintai Chen

TL;DR

AnyECG is a new foundational model family designed to handle the messy reality of real-world electrocardiogram (ECG) data, which varies wildly across recording devices, noise levels, and patient demographics. By combining a vector-quantized "Rhythm Quantizer" with a specialized sparse attention mechanism, AnyECG learns robust, device-agnostic cardiac representations. It achieves state-of-the-art performance across diverse clinical tasks, including anomaly detection, arrhythmia classification, and ultra-long ECG analysis.

What Problem Does This Paper Address?

Electrocardiograms (ECGs) are indispensable for diagnosing cardiac conditions, but applying deep learning to them in the real world is notoriously difficult. Unlike curated clinical datasets, real-world ECG data suffers from three major challenges:

  1. Heterogeneity: Data comes from various sources—ranging from single-lead smartwatches to standard 12-lead clinical machines. They feature vastly different sampling rates (100 to 1000 Hz) and recording lengths (from a few seconds to 24-hour Holter monitors), which distorts temporal patterns and overwhelms standard neural architectures.
  2. Low Signal-to-Noise Ratio (SNR): Real-world recordings are plagued by muscle noise, movement artifacts, and baseline wander. Models often accidentally prioritize learning these noisy artifacts over subtle, diagnostically vital cardiac waveforms (like the ST-T segment).
  3. Demographic Shifts: Normal heart rhythms look different depending on a patient's age, sex, and ethnicity, causing standard models to generalize poorly across diverse populations.

Existing methods typically rely on specialized architectures tailored to single datasets. AnyECG aims to bridge this gap by serving as a unified, robust foundation model for any ECG signal.

Methods

AnyECG introduces a two-stage pre-training pipeline designed to turn noisy, continuous signals into clean, semantic representations.

Fig. 1. Overall architecture and pre-training pipeline of AnyECG. AnyECG is pre-trained in two steps. The Rhythm Quantizer is pre-trained through proxy tasks to embed morphology, frequency, and demography into tokens (up). Then, the entire AnyECG, along with the ECG Tokenizer, is further pre-trained by predicting the code indices of the masked tokens to learn the semantic relationships between tokens (bottom-left). The Cardio-Sparse approach restricts interactions of patches from the same lead or from the same position across different leads (bottom-right). LN: LayerNorm, Conv: 1D convolution with kernel size of 15.

1. Stage 1: The Rhythm Quantizer

Instead of feeding raw waveforms directly into a Transformer, AnyECG segments the signal into fixed-duration patches and passes them through an ECG Tokenizer. This tokenizer maps the continuous features to discrete "Rhythm Codes" from a learned codebook. To ensure these codes capture true physiology rather than noise, the process is guided by a Multi-View Synergistic Decoder optimized for three proxy tasks:

  • Morphology Decoder: Reconstructs the original time-domain waveform (e.g., QRS complexes).
  • Frequency Decoder: Uses Discrete Wavelet Transform (DWT) to capture localized time-frequency patterns, balancing the model's spectral sensitivity.
  • Demography Decoder: Predicts patient attributes (age and sex), forcing the model to internalize and adjust for demographic variations.

2. Stage 2: Masked Pre-training

Once the signal is tokenized into discrete rhythm codes, the model undergoes masked language modeling (similar to BERT). Random patches are masked, and the network learns to predict the missing rhythm code indices based on global context, capturing the broader semantic relationships of cardiac events.

3. Cardio-Sparse Attention (CSA)

Standard self-attention scales quadratically, making the processing of ultra-long, multi-lead ECGs computationally impossible. AnyECG introduces CSA, a sparse attention mechanism that restricts patch interactions to either the same lead over time or the same temporal position across different leads. This mimics how human clinicians read ECGs and drastically cuts computational costs.

Datasets

To build a truly foundational model, the authors pre-trained and evaluated AnyECG on a massive, combined dataset from seven distinct sources:

  • CPSC & CPSC-Extra: 12-lead recordings (6–60 seconds) with a balanced sex distribution.
  • INCART: High-resolution 30-minute Holter records (257 Hz) ideal for arrhythmia classification.
  • PTB & PTB-XL: Large clinical datasets containing a wide range of cardiac pathologies.
  • Georgia 12-lead ECG Challenge (G12EC): Adds demographic diversity from the Southeastern United States.
  • Undisclosed Dataset: A geographically distinct set of 10,000 recordings used as an isolated test set to ensure no data leakage occurred.

Key Insights and Ideas

  • Discretization as a Denoising Filter: Mapping continuous, noisy signals to a discrete codebook acts as a natural bottleneck. High-frequency noise and artifacts fail to map to the clean "rhythm primitives" in the codebook, effectively purifying the signal before it reaches the core Transformer.
  • Multi-View Alignment Prevents Feature Bias: Deep learning models naturally gravitate toward high-frequency, high-amplitude features like the QRS complex. Forcing the model to simultaneously satisfy time, frequency (wavelet), and demographic decoders ensures it doesn't neglect subtle, low-frequency features like T-wave variations.
  • Clinician-Inspired Sparsity: Cardio-Sparse Attention proves that "all-to-all" attention is redundant for multi-channel time-series data. Restricting attention to spatial alignments and temporal contexts preserves diagnostic accuracy while enabling the processing of hours-long recordings.

Key Results

The authors evaluated three model sizes: AnyECG-B (254M parameters), AnyECG-L (500M), and AnyECG-XL (1.7B).

Fig. 2. Downstream Task of the ECG Foundation Model. The framework demonstrates fine-tuning AnyECG on heterogeneous ECG datasets, including portable devices, Holter monitors, standard 12-lead recordings, and Event monitor, to address four critical tasks: (1) Anomaly Detection (binary classification of normal vs. abnormal rhythms), (2) Arrhythmia Classification, (3) Ultra-Long ECG Analysis (continuous monitoring for ultra-long ECG event detection), and (4) Corrupted Lead Generation. AnyECG achieves task-specific adaptability through fine-tuning while preserving pre-learned cardiac semantics.

AnyECG achieved an average 6% performance improvement across four critical downstream tasks:

  • Anomaly Detection: AnyECG-XL achieved the highest accuracy (82.55%) and AUROC (85.50%), substantially outperforming existing models like ECG-FM.
  • Arrhythmia Classification: The model demonstrated robust handling of complex cardiac rhythms, outperforming traditional CNN and RNN baselines.
  • Corrupted Lead Generation: When reconstructing missing or noisy channels, AnyECG-L achieved superior Peak Signal-to-Noise Ratio (PSNR: 32.73 dB) and Structural Similarity (SSIM: 0.8738) compared to specialized GANs.
  • Ultra-Long ECG Analysis: Using a hierarchical sliding window approach, AnyECG-XL maintained high accuracy (80.55%) on hours-long recordings where other foundation models failed due to sequence length limitations.

Limitations and Future Work

Despite its strong performance, the authors acknowledge a few limitations:

  • The Healthcare Data Gap: While large, the pre-training dataset is still orders of magnitude smaller than the internet-scale datasets used to train text or vision LLMs.
  • Model Scale: At 1.7B parameters, AnyECG-XL is small compared to modern multi-billion parameter models, restricted primarily by the scarcity of massive, unified medical datasets.
  • Fine-Grained Pixel Errors: In lead generation tasks, AnyECG prioritizes abstract rhythmic and morphological integrity over pixel-level perfection, resulting in a slightly higher Mean Absolute Error (MAE) than specialized GANs.

Future work will focus on scaling up the model size, acquiring more extensive healthcare datasets, and exploring the trade-offs between computational cost and downstream performance.

Summary updated

BibTeX
@misc{wang2024anyecg,
  author = {Yue Wang and Xu Cao and Yaojun Hu and Haochao Ying and Hongxia Xu and Ruijia Wu and James Matthew Rehg and Jimeng Sun and Jian Wu and Jintai Chen},
  title = {{AnyECG: Foundational Models for Multitask Cardiac Analysis in Real-World Settings}},
  year = {2024},
  eprint = {2411.17711},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2411.17711},
}
Figure