Skip to content

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

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

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

Conversation

@lizxiris1995

@lizxiris1995 lizxiris1995 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • MIT-BIH on the real data (paper configuration and evaluation protocol, 1 seed). The task's signals and labels match the data of our run of the authors' code (within 3e-6, no label mismatches):

    Run F1 AUROC
    Paper (Llama-2-7B) 94.70 98.52
    Authors' code on our data, Llama-2-7B 95.81 98.36
    MedTsLLMAnomaly with the weights trained above 95.83 98.38
    This PR's pipeline trained from scratch, GPT-2 95.94 98.42
    Authors' code, random frozen Llama-2-7B 95.86 98.40

    A random frozen backbone and the much smaller GPT-2 match the pretrained Llama, so on this task the adapters, not the LLM's pretrained knowledge, carry the performance.

  • LUDB on the real data (3 seeds, all prompt parts with the correct patient): macro F1 86.08 ± 0.07 and segment mIoU 61.72 ± 1.14 with Llama-2-7B, 84.69 ± 0.34 and 57.06 ± 1.28 with GPT-2 XL (paper: F1 89.89). All conditions are in the example's docstring.

  • 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; results in each docstring):

  • examples/ludb_segmentation_medtsllm.py: nine prompt and backbone conditions, 3 seeds each, on GPT-2 XL and Llama-2-7B (54 runs). Simpler prompts did as well as all prompt parts, correct patient context did not beat removing it, and a random frozen backbone lowered segment mIoU (Llama-2-7B 61.7 → 58.2, GPT-2 XL 57.1 → 44.4).
  • 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 the real data, point adjustment accounts for most of the paper-protocol F1 (45.2 without it, 95.9 with it, GPT-2), and a threshold from the training labels instead of the test labels gives 6.2; the threshold-free AUROC of the raw scores is 80.1.

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: 87.08% (50775 / 58306 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 88 / 88
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% 101 / 101
pyhealth/models/medtsllm.py 80.68% 142 / 176
pyhealth/models/medtsllm_anomaly.py 93.14% 190 / 204
pyhealth/tasks/__init__.py 98.31% 116 / 118
pyhealth/tasks/ecg_delineation_ludb.py 80.00% 68 / 85
pyhealth/tasks/mitbih.py 98.41% 62 / 63

Workflow run · e223c69

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>
tvtrinh-tran and others added 3 commits November 27, 2026 18:18
Updated documentation and usage instructions for LUDB ECG delineation with MedTsLLM. Added details on experimental setup, conditions, and results.
Results of this script on the real MIT-BIH data with GPT-2 (evaluation
protocol and label width ablations), and of the authors'-code Llama-2-7B
weights evaluated with MedTsLLMAnomaly and the PyHealth metrics (F1 95.83 /
AUROC 98.38 vs 95.81 / 98.36 in the authors' code).

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

# Conflicts:
#	docs/api/models.rst
#	pyhealth/datasets/__init__.py
#	pyhealth/tasks/__init__.py
@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: three open PRs add a LUDB dataset and an ECG delineation task: #1593, #1615 and #1594. PyHealth keeps one implementation per component. Our suggestion to the maintainers is to take #1593 (dataset and task only, and the AI suggests approve) as the LUDB base. #1615 and #1594 would then add only their models (UNet3+; MedTsLLM with MIT-BIH) on top of it. The decision is tracked in #1668.

This PR is also about 218,000 characters, over the AI review's limit. Building on #1593's LUDB code and splitting MIT-BIH into its own PR would solve both.

@solarsys

Copy link
Copy Markdown
Collaborator

We compared the three LUDB PRs and picked #1593 as the LUDB base. Your LUDB dataset can't be the base for two reasons:

  • It needs pre-built files (window_manifest.csv, patient_split.csv, masks/*.npz) that nothing in PyHealth produces.
  • It overrides the private _init_cache_dir.

MedTsLLM and MIT-BIH are unique, though, and welcome.

After #1593 merges, please split the rest into PRs under the AI review's 200,000-character limit:

  1. The MIT-BIH dataset and task.
  2. MedTsLLMAnomaly, with the anomaly metrics and the MIT-BIH example.
  3. MedTsLLM, adapted to the merged LUDB task:
    • derive the ignore mask from mask == 255;
    • window in the example, or propose a window option for the task;
    • pass your 80/20 split as a SubjectSplit;
    • trim the delineation metrics to what metrics/segmentation.py lacks;
    • include the LUDB example.

Drop: your LUDB dataset, task, config, LUDBManifestSplit and their tests. Please also keep the upstream MIT copyright notice in the parts ported from flixpar/med-ts-llm.

github-actions Bot pushed a commit that referenced this pull request Nov 28, 2026
…part 1 of #1594) (#1671)

* Add MIT-BIH Arrhythmia dataset and ECG anomaly detection task

MITBIHDataset reads the 48 WFDB records; MITBIHAnomalyDetection makes
the MedTsLLM windows with per-step abnormal-beat labels; and
MITBIHAnomalyRatioSplit is the paper's record-level split. Split out of
#1594 as the maintainers asked.

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

* MIT-BIH: test that changed records get a new cache name; list it in the datasets table

Addresses the AI review: a test rewrites one record's annotations and
checks that the dataset name, the metadata and the loaded event change,
and MIT-BIH is added to the dataset summary table in docs/api/datasets.rst.

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

---------

Co-authored-by: Thi Van Trinh Tran <ttran493@gatech.edu>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
github-actions Bot pushed a commit that referenced this pull request Nov 29, 2026
…(part 2 of #1594) (#1672)

* Add MIT-BIH Arrhythmia dataset and ECG anomaly detection task

MITBIHDataset reads the 48 WFDB records; MITBIHAnomalyDetection makes
the MedTsLLM windows with per-step abnormal-beat labels; and
MITBIHAnomalyRatioSplit is the paper's record-level split. Split out of
#1594 as the maintainers asked.

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

* Add MedTsLLMAnomaly, anomaly detection metrics and MIT-BIH example

MedTsLLMAnomaly ports the authors' reconstruction model (frozen LLM,
trainable reprogramming adapters). The metrics follow the authors'
evaluation; the test-label threshold and point adjustment can each be
turned off. The example runs the full pipeline and its ablations on
synthetic data or the real records. Adds the upstream MIT copyright
notice to the ported files. Split out of #1594 as the maintainers asked;
builds on the MIT-BIH dataset and task PR.

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

* Document the authors' "auto" contamination formula

The example's "auto" threshold divides the test anomalous steps by the test
plus training steps, as in the authors' tasks/anomaly_detection.py. Say so
in the example, the metrics module and its docs page, and note that "auto"
is optimistic because it uses the test labels. Also note that llm_layers
applies only when the LLM is loaded from llm_name. Addresses the AI review;
no code change.

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

---------

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

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

@github-actions

Copy link
Copy Markdown

AI Review

suggestion: not available
decision: not available

This PR is too large for AI review (over 300 files or 200000 diff characters). The label stays as it is: you can make the PR smaller, for example by clearing notebook outputs or splitting it, and comment /review again, or a maintainer can review it as it is.

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

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants