Repository navigation
[BTY-30] Add LLMCodeTransfer for cross-coding-system EHR transfer #1754
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
solarsys
merged 1 commit into
sunlabuiuc:master
from
tkumar007:feat/bty-30-llm-code-transfer
Nov 30, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| pyhealth.models.LLMCodeTransfer | ||
| =============================== | ||
|
|
||
| .. currentmodule:: pyhealth.models | ||
|
|
||
| Overview | ||
| -------- | ||
|
|
||
| LLMCodeTransfer (`Kirchler et al., npj Digital Medicine 2026 <https://doi.org/10.1038/s41746-026-02363-5>`_; | ||
| reference repository `mkirchler/grasp <https://github.com/mkirchler/grasp>`_) | ||
| enables EHR predictive models to transfer zero-shot across disparate medical | ||
| coding systems (such as ICD-9, ICD-10, OMOP, and ATC) by representing clinical | ||
| concepts in a shared, frozen LLM text-embedding space. | ||
|
|
||
| Instead of training random per-code embedding tables from scratch, | ||
| :class:`~pyhealth.models.LLMCodeTransfer`: | ||
|
|
||
| 1. **Encodes medical concepts via LLM text vectors**: Maps codes from any | ||
| vocabulary to precomputed semantic vectors via | ||
| :class:`~pyhealth.models.LLMCodeEmbedding`, loaded from files or any user | ||
| text encoder with :func:`~pyhealth.models.load_llm_code_embeddings` and | ||
| :func:`~pyhealth.models.build_llm_code_embeddings`. | ||
| 2. **Encodes continuous clinical measurements**: Adds optional 1D and 2D | ||
| sinusoidal encodings (:class:`~pyhealth.models.PositionalEncoding1D`, | ||
| :class:`~pyhealth.models.PositionalEncoding2D`) for patient age and numeric | ||
| values. | ||
| 3. **Models event sets with a Pre-LN Transformer**: Applies a Pre-LN Set | ||
| Transformer with stochastic depth (``DropPath``), optional ``LayerScale``, | ||
| and padding-aware attention over clinical events. | ||
| 4. **Transfers zero-shot across vocabularies**: Transfers all trained | ||
| Transformer and head weights to another dataset's coding system via | ||
| :meth:`~pyhealth.models.LLMCodeTransfer.transfer_to_dataset` without | ||
| requiring manual ontology crosswalks. | ||
|
|
||
| API Reference | ||
| ------------- | ||
|
|
||
| .. autofunction:: pyhealth.models.load_llm_code_embeddings | ||
|
|
||
| .. autofunction:: pyhealth.models.build_llm_code_embeddings | ||
|
|
||
| .. autoclass:: pyhealth.models.PositionalEncoding1D | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: | ||
|
|
||
| .. autoclass:: pyhealth.models.PositionalEncoding2D | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: | ||
|
|
||
| .. autoclass:: pyhealth.models.LLMCodeEmbedding | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: | ||
|
|
||
| .. autoclass:: pyhealth.models.LLMCodeTransfer | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| """Cross-coding-system EHR transfer with LLMCodeTransfer. | ||
|
|
||
| Demonstrates training ``LLMCodeTransfer`` on a source coding system (e.g., ICD-9) | ||
| via PyHealth's standard ``Trainer`` and transferring zero-shot to an unseen target | ||
| coding system (e.g., ICD-10 / OMOP) without retraining. | ||
|
|
||
| Reference: | ||
| Kirchler et al., "Transferring EHR predictors across coding systems via | ||
| large language model embeddings", npj Digital Medicine (2026). | ||
| https://doi.org/10.1038/s41746-026-02363-5 | ||
| """ | ||
|
|
||
| import numpy as np | ||
| import torch | ||
|
|
||
| from pyhealth.datasets import create_sample_dataset, get_dataloader, split_by_patient | ||
| from pyhealth.models import LLMCodeTransfer, build_llm_code_embeddings | ||
| from pyhealth.trainer import Trainer | ||
|
|
||
|
|
||
| def _synthetic_semantic_encoder(texts: list[str]) -> np.ndarray: | ||
| """Deterministic toy text encoder mapping clinical keywords to 8-D vectors. | ||
|
|
||
| In real workflows, replace this function with any OpenAI, HuggingFace, or | ||
| SentenceTransformers batch embedding call. | ||
| """ | ||
| cardiac_kw = ("hypertension", "coronary", "heart", "cardiac", "angina") | ||
| respiratory_kw = ("pneumonia", "asthma", "copd", "respiratory", "bronchitis") | ||
| vecs = np.zeros((len(texts), 8), dtype=np.float32) | ||
| for i, text in enumerate(texts): | ||
| lower = text.lower() | ||
| if any(k in lower for k in cardiac_kw): | ||
| vecs[i, :4] = 1.0 | ||
| elif any(k in lower for k in respiratory_kw): | ||
| vecs[i, 4:] = 1.0 | ||
| else: | ||
| vecs[i] = 0.1 | ||
| return vecs | ||
|
|
||
|
|
||
| def main() -> None: | ||
| torch.manual_seed(0) | ||
|
|
||
| icd9_descriptions = { | ||
| "401.9": "Unspecified essential hypertension", | ||
| "414.01": "Coronary atherosclerosis of native coronary artery", | ||
| "428.0": "Congestive heart failure unspecified", | ||
| "486": "Pneumonia organism unspecified", | ||
| "493.90": "Asthma unspecified", | ||
| "496": "Chronic airway obstruction COPD", | ||
| } | ||
| icd10_descriptions = { | ||
| "I10": "Essential (primary) hypertension", | ||
| "I25.10": "Atherosclerotic heart disease without angina pectoris", | ||
| "I50.9": "Heart failure unspecified", | ||
| "J18.9": "Pneumonia unspecified organism", | ||
| "J45.909": "Unspecified asthma uncomplicated", | ||
| "J44.9": "Chronic obstructive pulmonary disease unspecified", | ||
| } | ||
|
|
||
| icd9_embs = build_llm_code_embeddings( | ||
| icd9_descriptions.keys(), | ||
| encoder_fn=_synthetic_semantic_encoder, | ||
| code_descriptions=icd9_descriptions, | ||
| normalize=True, | ||
| ) | ||
| icd10_embs = build_llm_code_embeddings( | ||
| icd10_descriptions.keys(), | ||
| encoder_fn=_synthetic_semantic_encoder, | ||
| code_descriptions=icd10_descriptions, | ||
| normalize=True, | ||
| ) | ||
|
|
||
| # Build a small ICD-9 source dataset (label=1 for cardiac history, 0 for respiratory) | ||
| cardiac_icd9 = ["401.9", "414.01", "428.0"] | ||
| resp_icd9 = ["486", "493.90", "496"] | ||
| source_samples = [] | ||
| for i in range(40): | ||
| pos = i % 2 == 0 | ||
| codes = cardiac_icd9 if pos else resp_icd9 | ||
| source_samples.append( | ||
| { | ||
| "patient_id": f"src_{i}", | ||
| "codes": codes[: 2 + (i % 2)], | ||
| "label": int(pos), | ||
| } | ||
| ) | ||
|
|
||
| source_ds = create_sample_dataset( | ||
| samples=source_samples, | ||
| input_schema={"codes": "sequence"}, | ||
| output_schema={"label": "binary"}, | ||
| dataset_name="icd9_source_demo", | ||
| ) | ||
| train_ds, val_ds, _ = split_by_patient(source_ds, [0.75, 0.25, 0.0], seed=42) | ||
| train_loader = get_dataloader(train_ds, batch_size=8, shuffle=True) | ||
| val_loader = get_dataloader(val_ds, batch_size=8, shuffle=False) | ||
|
|
||
| model = LLMCodeTransfer( | ||
| dataset=source_ds, | ||
| code_embeddings=icd9_embs, | ||
| embed_dim=16, | ||
| depth=2, | ||
| num_heads=4, | ||
| ) | ||
| trainer = Trainer(model=model, metrics=["roc_auc", "accuracy"]) | ||
| trainer.train( | ||
| train_dataloader=train_loader, | ||
| val_dataloader=val_loader, | ||
| epochs=15, | ||
| optimizer_params={"lr": 5e-3}, | ||
| monitor="roc_auc", | ||
| ) | ||
|
|
||
| # Zero-shot transfer to ICD-10 without retraining on target labels | ||
| cardiac_icd10 = ["I10", "I25.10", "I50.9"] | ||
| resp_icd10 = ["J18.9", "J45.909", "J44.9"] | ||
| target_samples = [ | ||
| { | ||
| "patient_id": f"tgt_{i}", | ||
| "codes": (cardiac_icd10 if i % 2 == 0 else resp_icd10)[: 2 + (i % 2)], | ||
| "label": int(i % 2 == 0), | ||
| } | ||
| for i in range(20) | ||
| ] | ||
| target_ds = create_sample_dataset( | ||
| samples=target_samples, | ||
| input_schema={"codes": "sequence"}, | ||
| output_schema={"label": "binary"}, | ||
| dataset_name="icd10_target_demo", | ||
| ) | ||
| target_model = model.transfer_to_dataset(target_ds, icd10_embs) | ||
| target_loader = get_dataloader(target_ds, batch_size=8, shuffle=False) | ||
| zero_shot_metrics = Trainer( | ||
| model=target_model, metrics=["roc_auc", "accuracy"] | ||
| ).evaluate(target_loader) | ||
| print(f"Zero-shot ICD-9 -> ICD-10 metrics: {zero_shot_metrics}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[low] Toy encoder gives J44.9 no semantic cluster, weakening the demo
The keyword encoder in _synthetic_semantic_encoder (line 28) has no keyword matching "Chronic obstructive pulmonary disease unspecified", so J44.9 falls back to the uniform 0.1 vector and is not placed in the respiratory cluster. The zero-shot metric printed by this demo therefore reflects this mismatch, and because the toy encoder encodes the label clusters directly, the number is not evidence of LLM-based transfer. Add "pulmonary" or "obstructive" to respiratory_kw, and state in the docstring that the metric only shows the pipeline runs.