Skip to content

MedTsLLMAnomaly model, anomaly detection metrics and MIT-BIH example (part 2 of #1594) - #1672

Merged
github-actions[bot] merged 4 commits into
sunlabuiuc:masterfrom
lizxiris1995:medtsllm-anomaly
Nov 29, 2026
Merged

github-actions[bot] merged 4 commits into
sunlabuiuc:masterfrom
lizxiris1995:medtsllm-anomaly

Conversation

@lizxiris1995

@lizxiris1995 lizxiris1995 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Contributors:

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

Part 2 of 3 split out of #1594, as the maintainers asked there. This part adds MedTsLLMAnomaly, the anomaly detection metrics and the MIT-BIH example. It builds on part 1, #1671 (MIT-BIH dataset and task), so until that merges this diff also shows part 1's commit. Only the second commit is new here. Part 3 will add the LUDB MedTsLLM on top of #1593 after that PR merges.

Contribution Type: Model (with metrics and example; together with part 1, a full pipeline)

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 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 and task description) is prepended, and a linear head reconstructs the input. Only the adapters train. Steps that reconstruct badly are flagged as anomalies.

  • MedTsLLMAnomaly ports the authors' model in the paper's anomaly detection configuration. It takes any Hugging Face GPT-2- or Llama-style backbone, pretrained or random (frozen).
  • pyhealth.metrics.anomaly_detection follows the authors' evaluation: reconstruction-error scores, a threshold from the test labels ("auto": the authors' formula, test anomalous steps over test plus training steps), and point adjustment. Both of these can be turned off, and the threshold-free AUROC of the raw scores is also reported.
  • The ported files carry the upstream MIT copyright notice (flixpar/med-ts-llm).

Validation:

  • With the same weights and inputs, MedTsLLMAnomaly and the 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):

    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 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.

Example and ablations: examples/mitbih_anomaly_detection_medtsllm.py runs the full pipeline (dataset → task → model → training → evaluation), offline on synthetic data by default and on the real records with --root. It evaluates one trained model 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). A threshold from the training labels instead of the test labels gives 6.2, and the threshold-free AUROC of the raw scores is 80.1. Results are in the docstring.

Files to Review:

  • pyhealth/models/medtsllm_anomaly.py - MedTsLLMAnomaly model
  • pyhealth/metrics/anomaly_detection.py - anomaly scores, threshold and point adjustment
  • 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: docs/api/models/pyhealth.models.MedTsLLMAnomaly.rst, docs/api/metrics/pyhealth.metrics.anomaly_detection.rst, entries in docs/api/{models,metrics}.rst, exports in pyhealth/{models,metrics}/__init__.py

Checklist:

  • Targets master, based on the latest upstream master (on top of part 1)
  • "Allow edits by maintainers" enabled
  • Paper linked; example script under examples/ named {dataset}_{task}_{model}.py
  • Unit tests use synthetic data and tiny offline backbones, each under a second
  • tools/check_pr_rules.py passes; code follows PEP 8 with 88-character lines
  • API docs and index entries for the new model and metrics module

lizxiris1995 and others added 2 commits November 28, 2026 16:42
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
sunlabuiuc#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>
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 sunlabuiuc#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>
@lizxiris1995 lizxiris1995 changed the title MedTsLLMAnomaly model, anomaly detection metrics and MIT-BIH example (part 2 of #1594) MedTsLLMAnomaly model, anomaly detection metrics and MIT-BIH example (part 2 of 3 of #1594) Nov 28, 2026
@lizxiris1995 lizxiris1995 changed the title MedTsLLMAnomaly model, anomaly detection metrics and MIT-BIH example (part 2 of 3 of #1594) MedTsLLMAnomaly model, anomaly detection metrics and MIT-BIH example (part 2 of #1594) Nov 28, 2026
@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.70% (53993 / 61568 lines)

Modified file Coverage Lines
pyhealth/metrics/__init__.py 100.00% 18 / 18
pyhealth/metrics/anomaly_detection.py 97.56% 40 / 41
pyhealth/models/__init__.py 100.00% 109 / 109
pyhealth/models/medtsllm_anomaly.py 93.14% 190 / 204

Workflow run · 2e67640

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 28, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

Thanks for splitting #1594. This PR is stacked on #1671: it carries the same MIT-BIH dataset and task files. To avoid reviewing those files twice, we'll request the AI review after #1671 merges and you rebase this PR onto master. Its diff will then contain only MedTsLLMAnomaly, the anomaly metrics, the example and their tests. If you rebase before that, comment /review yourself; on automatic PRs you can request it.

@lizxiris1995

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 63acb62

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. It adds a port of MedTsLLM for reconstruction-based anomaly detection, a point-wise anomaly metrics module, and a full MIT-BIH example with ablations. The model and metrics are well tested and documented. Coverage is 97.6% for anomaly_detection.py and 93.1% for medtsllm_anomaly.py, and 87.7% for the whole repository. That clears the 80% per-file and 60% overall bar.

It is close, but one documentation mismatch needs fixing.

To get this merged:

  • In examples/mitbih_anomaly_detection_medtsllm.py, the "auto" contamination is labels.sum() / (labels.size + n_train). That is the number of test anomalous steps divided by test steps plus training steps. The PR description, the module docstring and the comment next to it all call it the test labels' anomaly rate. Please make the text match the code. If this is the authors' exact formula, say so in the example docstring, the PR description and the anomaly_detection docs, with a short reason. If it is not intended, change the code to use only the test labels. The example's "auto" results depend on this formula, so the docs should state it.

Optional suggestions:

  • The llm_name loading path, random_backbone and llm_layers truncation in medtsllm_anomaly.py aren't exercised by the offline tests. A mocked or tiny-config test could cover them.
  • The anomaly_detection docs and docstring could say that "auto" is optimistic because it uses test information.

Reviewed commit 63acb62

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>
@lizxiris1995

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 2e67640


def in_time_order(per_window: dict) -> np.ndarray:
"""Concatenates per-window arrays by record, then time (for point adjust)."""
return np.concatenate([per_window[k] for k in sorted(per_window)])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Point adjustment can merge segments across record boundaries

in_time_order concatenates the per-window arrays of all records, so point_adjust treats the end of one record and the start of the next as one segment. An anomalous step at the end of record 100 and one at the start of record 101 are then joined, and a hit in one record fills the other. Apply point adjustment per record (e.g. by computing the adjusted metrics per record and combining them), or at least document that segments can span records.

("V") are wide, inverted and have no P wave. Record ``i`` has ``i``
abnormal beats in 20, so the paper split trains on the least abnormal.
"""
import wfdb

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Synthetic default path needs optional wfdb, not mentioned in How to run

The default offline run calls write_synthetic_records, which imports wfdb directly. wfdb is an optional dependency (pyproject extra), so a plain install fails with a bare ImportError. Add an install note (pip install wfdb) to the How to run section of the docstring.

)
errors = ((pred - true) ** 2).reshape(-1, pred.shape[-1])
if normalize_by_feature:
errors = errors / errors.mean(axis=0, keepdims=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Normalization depends on the set of steps passed in

normalize_by_feature divides each channel by its mean error over everything passed to the call. The same window therefore gets different scores when scored in a different batch or set, and the example relies on scoring the whole test set at once. State in the docstring that the mean is taken over the passed steps and that scores from different calls are not comparable.

for parts in prompts
]
max_len = max(e.shape[1] for e in encoded)
pad_id = torch.tensor(self.tokenizer.pad_token_id, device=self.device)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Missing pad token fails late with an unclear error

encode_prompts calls torch.tensor(self.tokenizer.pad_token_id). If the tokenizer has neither a pad nor an eos token, pad_token_id is None and the error surfaces only at the first forward pass. Validate in _setup_llm (or the constructor) and raise a clear ValueError.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: approve

Thank you for this contribution. It adds MedTsLLMAnomaly, a frozen-LLM reconstruction model for anomaly detection. It also adds a pyhealth.metrics.anomaly_detection module (reconstruction scores, a quantile threshold, point adjustment and metrics), API docs, and a full MIT-BIH example with ablations. The work is carefully validated against the authors' code.

This looks ready to merge. The model and metrics are self-contained. They build only on BaseModel, the existing processors and the Trainer, and the edits to the two init.py files are plain exports. I found no blocking problems. The docs match the code, and the paper is cited. The ported files carry the upstream MIT notice.

Coverage meets the bar. The whole repository is at 87.7%, against a bar of 60%. The new metrics file is at 97.6% and the new model file at 93.1%, against a bar of 80% for each.

Optional suggestions:

  • In the example, in_time_order concatenates windows across records, so point adjustment can merge anomalous segments across record boundaries. A short note in the example would make that clear.
  • The default synthetic path needs the optional wfdb package, so mention it under "How to run".
  • Say in the reconstruction_anomaly_scores docstring that normalize_by_feature uses the mean error over whatever set you pass in.
  • A tokenizer with neither a pad token nor an EOS token only fails at the first forward pass. An earlier, clearer error would help.

Reviewed commit 2e67640

@lizxiris1995

Copy link
Copy Markdown
Contributor Author

/merge

@github-actions
github-actions Bot merged commit 3aabb0d into sunlabuiuc:master Nov 29, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants