Skip to content

Add MedTsLLM full pipelines for LUDB ECG delineation and MIT-BIH anomaly detection (Chan et al., MLHC 2024) - #1594

Draft
lizxiris1995 wants to merge 3 commits into
sunlabuiuc:masterfrom
lizxiris1995:medtsllm-mitbih-ludb
Draft

lizxiris1995 wants to merge 3 commits into
sunlabuiuc:masterfrom
lizxiris1995:medtsllm-mitbih-ludb

Conversation

@lizxiris1995

@lizxiris1995 lizxiris1995 commented Nov 24, 2026 •

Copy link
Copy Markdown

Contributors:

Georgia Tech CSE 6250 (Big Data for Health), Fall 2026

Contribution Type: Full Pipeline (Dataset + Task + Model), reproducibility contribution

Paper: Chan et al., "MedTsLLM: Leveraging LLMs for Multimodal Medical Time Series Analysis," MLHC 2024. https://arxiv.org/abs/2408.07773

Description:
MedTsLLM cuts a medical time series into patches and maps them into a frozen LLM's word-embedding space by cross-attention onto learned text prototypes. A text prompt (dataset, task, optionally patient information) is prepended, and a small head turns the LLM's hidden states into the task output. Only the adapters train. This PR adds two of the paper's ECG tasks end to end, from data loading to evaluation:

ECG delineation (LUDB) ECG anomaly detection (MIT-BIH)
Dataset LUDBDataset, LUDBManifestSplit: prepared 512-sample windows, fixed patient-level 80/20 split MITBIHDataset, MITBIHAnomalyRatioSplit: 48 two-lead records, the paper's 6 train / 4 test record split
Task ECGDelineationLUDB: per-point background / P / QRS / T; unannotated points ignored MITBIHAnomalyDetection: 125 Hz, 128-step two-lead windows, abnormal beats expanded by ±150 ms
Model MedTsLLM: per-point segmentation; prompt parts switchable MedTsLLMAnomaly: reconstruction, a port of the authors' model
Metrics pyhealth.metrics.ecg_delineation: point F1/IoU, segment mIoU pyhealth.metrics.anomaly_detection: the paper's threshold and point adjustment, raw-score AUROC

Both models take any Hugging Face GPT-2- or Llama-style backbone, pretrained or random (frozen). The two parts share no code and change no existing files beyond __init__.py exports and docs indexes.

  • Why two model classes: the tasks need different inputs and heads (univariate 4-class segmentation vs. multichannel unsupervised reconstruction), and each class keeps the behavior behind its experiments.
  • Differences from the authors' code:
    • MedTsLLM keeps the architecture but uses per-window scaling, nn.MultiheadAttention and an interpolated per-patch head (see its docs page).
    • MedTsLLMAnomaly is architecturally identical. The only difference is in the task: it windows each MIT-BIH record separately instead of the concatenated records.
  • MIT-BIH split: the paper does not list its records. Its sample counts (Tables 1 and 11) match exactly 33 MLII+V1 records and a 6 / 4 split by abnormal-beat ratio, which "paper" mode reproduces.

Validation:

  • With the same weights and inputs, MedTsLLMAnomaly and the anomaly metrics give outputs, gradients and scores identical to the authors' code. This was checked with tiny Llama and GPT-2 backbones.

  • The MIT-BIH task's signals and labels match the data of our run of the authors' code (within 3e-6, no label mismatches). That run used Llama-2-7B in the paper configuration with 1 seed:

    Backbone F1 AUROC
    Pretrained Llama-2-7B 95.81 98.36
    Random frozen Llama-2-7B 95.86 98.40
    Paper 94.70 98.52

    The random backbone matches the pretrained one, so on this task the adapters, not the LLM's pretrained knowledge, carry the performance.

  • 62 tests (22 LUDB, 40 MIT-BIH) use synthetic records and tiny offline backbones, each under a second.

Examples and ablations (offline on synthetic data by default; real data and backbones by path or name):

  • examples/ludb_segmentation_medtsllm.py: prompt ablation in nine conditions (no prompt; dataset, task, patient or statistics only; all parts with the correct, a mismatched or no patient; all parts with a random backbone). Each condition runs with 3 seeds on GPT-2 XL and Llama-2-7B.
  • examples/mitbih_anomaly_detection_medtsllm.py: one trained model evaluated under (1) the evaluation protocol and (2) label widths of 50 / 150 / 300 ms. On synthetic data, point adjustment accounts for most of the paper-protocol F1 (0.44 → 0.96), while the threshold-free AUROC is unchanged (results in the docstring).

Files to Review:

  • LUDB
    • pyhealth/datasets/ludb.py, pyhealth/datasets/configs/ludb.yaml - dataset and patient split
    • pyhealth/tasks/ecg_delineation_ludb.py - delineation task
    • pyhealth/models/medtsllm.py - MedTsLLM model
    • pyhealth/metrics/ecg_delineation.py - delineation metrics
    • tests/core/test_ludb.py, tests/core/test_ecg_delineation_ludb.py, tests/core/test_medtsllm.py, tests/core/test_ecg_delineation_metrics.py - test cases
    • examples/ludb_segmentation_medtsllm.py - full pipeline and prompt ablations
  • MIT-BIH
    • pyhealth/datasets/mitbih.py, pyhealth/datasets/configs/mitbih.yaml - dataset and record split
    • pyhealth/tasks/mitbih.py - anomaly detection task
    • pyhealth/models/medtsllm_anomaly.py - MedTsLLMAnomaly model
    • pyhealth/metrics/anomaly_detection.py - anomaly scores, threshold and point adjustment
    • tests/core/test_mitbih.py, tests/core/test_medtsllm_anomaly.py, tests/core/test_anomaly_detection_metrics.py - test cases
    • examples/mitbih_anomaly_detection_medtsllm.py - full pipeline and ablations
  • Docs and registration: one API page per component under docs/api/, entries in docs/api/{datasets,tasks,models,metrics}.rst, exports in pyhealth/{datasets,tasks,models,metrics}/__init__.py

Checklist:

  • Targets master, rebased on the latest upstream master
  • "Allow edits by maintainers" enabled
  • Paper linked; example scripts under examples/ named {dataset}_{task}_{model}.py
  • Unit tests use synthetic data only and each run in under a second
  • tools/check_pr_rules.py passes; code follows PEP 8 with 88-character lines
  • API docs and index entries for every new dataset, task, model and metrics module

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.30% (46156 / 53485 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 84 / 84
pyhealth/datasets/ludb.py 85.14% 63 / 74
pyhealth/datasets/mitbih.py 97.35% 110 / 113
pyhealth/metrics/__init__.py 100.00% 18 / 18
pyhealth/metrics/anomaly_detection.py 97.56% 40 / 41
pyhealth/metrics/ecg_delineation.py 92.00% 92 / 100
pyhealth/models/__init__.py 100.00% 91 / 91
pyhealth/models/medtsllm.py 80.68% 142 / 176
pyhealth/models/medtsllm_anomaly.py 93.14% 190 / 204
pyhealth/tasks/__init__.py 98.10% 103 / 105
pyhealth/tasks/ecg_delineation_ludb.py 80.00% 68 / 85
pyhealth/tasks/mitbih.py 98.41% 62 / 63

Workflow run · 88f9327

lizxiris1995 and others added 3 commits November 23, 2026 22:36
…C 2024)

Reproducibility contribution for MedTsLLM (Chan et al., MLHC 2024),
https://arxiv.org/abs/2408.07773.

- MITBIHDataset: 48 two-lead recordings, one patient per record, YAML
  metadata table, lazy wfdb loading
- MITBIHAnomalyRatioSplit: deterministic record-level split by abnormal-beat
  ratio; "paper" mode reproduces MedTsLLM's 6/4 MLII+V1 split
- MITBIHAnomalyDetection: 125 Hz windows with step- or window-level labels
  (abnormal beats expanded +/-150 ms)
- MedTsLLMAnomaly: port of the authors' MedTsLLM for reconstruction-based
  anomaly detection (RevIN, patch embedding, reprogramming onto text
  prototypes, frozen LLM, dataset/task/patient prompt); identical outputs
  and gradients to the original given the same weights
- pyhealth.metrics.anomaly_detection: reconstruction scores, quantile
  threshold and point adjustment as in the paper, plus threshold-free AUROC
- example examples/mitbih_anomaly_detection_medtsllm.py: full pipeline on
  synthetic data by default, ablations of the evaluation protocol and of the
  label width
- tests with synthetic WFDB records and tiny offline GPT-2/Llama backbones,
  docs

Contributors: Thi Van Trinh Tran and Zexi Li.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Thi Van Trinh Tran <ttran493@gatech.edu>
… as is)

LUDB contribution by Thi Van Trinh Tran (ttran493), imported unchanged from
the team repository (lizxiris1995/MedTsLLM master 66ddb66, LUDB/), which
targets PyHealth ed124e3. Only the new files are copied; the package
__init__ files and docs indexes get the new export and toctree lines rather
than the full-file copies. Compatibility fixes for current master follow in
a separate commit.

- LUDBDataset, LUDBManifestSplit: frozen LUDB 1.0.1 window manifests
- ECGDelineationLUDB: four-class ignore-aware per-point delineation
- MedTsLLM: frozen GPT-2/Llama backbone with trainable ECG adapters
- pyhealth.metrics.ecg_delineation: point metrics and segment mIoU
- tests, docs, examples/ludb_segmentation_medtsllm.py

Contributors: Thi Van Trinh Tran and Zexi Li.
Co-authored-by: Thi Van Trinh Tran <ttran493@gatech.edu>
- ECGDelineationLUDB: pass the now-required timeline to the
  timeseries_multiclass label (sunlabuiuc#1429, merged after ed124e3); without it 11
  LUDB tests fail
- ClassVar annotations on the task schemas and a merged nested if in
  MedTsLLM.forward, for the ruff rules of tools/check_pr_rules.py
- test_ecg_delineation_ludb: replace patch.dict("sys.modules", ...) by a
  swap of sys.modules["wfdb"] only. patch.dict restores the whole dict, so
  modules first imported inside the block (dask/pyarrow parts loaded by
  set_task) were dropped, and later dataset tests in the same run failed
  with dask TokenizationError. Temporary directories ignore cleanup errors
  (Windows keeps the cache files open).
- test_native_dataset_set_task_end_to_end: build the dataset with a threaded
  Dask cluster (as in tests/core/survival_test_utils.py) instead of worker
  processes, which take seconds to start; 3.4 s -> 0.5 s, same checks

No behavior change to the LUDB dataset, task or model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Thi Van Trinh Tran <ttran493@gatech.edu>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant