Repository navigation
MedTsLLMAnomaly model, anomaly detection metrics and MIT-BIH example (part 2 of #1594) - #1672
Conversation
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>
Test CoverageTotal: 87.70% (53993 / 61568 lines)
|
|
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 |
# Conflicts: # tests/core/test_mitbih.py
|
/review |
There was a problem hiding this comment.
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 islabels.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 theanomaly_detectiondocs, 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_nameloading path,random_backboneandllm_layerstruncation inmedtsllm_anomaly.pyaren't exercised by the offline tests. A mocked or tiny-config test could cover them. - The
anomaly_detectiondocs 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>
|
/review |
|
|
||
| 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)]) |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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) |
There was a problem hiding this comment.
[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) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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_orderconcatenates 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
wfdbpackage, so mention it under "How to run". - Say in the
reconstruction_anomaly_scoresdocstring thatnormalize_by_featureuses 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
|
/merge |
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 LUDBMedTsLLMon 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.
MedTsLLMAnomalyports 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_detectionfollows 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.Validation:
With the same weights and inputs,
MedTsLLMAnomalyand 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):
MedTsLLMAnomalywith the weights trained aboveA 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.pyruns 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-MedTsLLMAnomalymodelpyhealth/metrics/anomaly_detection.py- anomaly scores, threshold and point adjustmenttests/core/test_medtsllm_anomaly.py,tests/core/test_anomaly_detection_metrics.py- test casesexamples/mitbih_anomaly_detection_medtsllm.py- full pipeline and ablationsdocs/api/models/pyhealth.models.MedTsLLMAnomaly.rst,docs/api/metrics/pyhealth.metrics.anomaly_detection.rst, entries indocs/api/{models,metrics}.rst, exports inpyhealth/{models,metrics}/__init__.pyChecklist:
master, based on the latest upstreammaster(on top of part 1)examples/named{dataset}_{task}_{model}.pytools/check_pr_rules.pypasses; code follows PEP 8 with 88-character lines