Skip to content

[BTY-30] Add LLMCodeTransfer for cross-coding-system EHR transfer - #1754

Merged
solarsys merged 1 commit into
sunlabuiuc:masterfrom
tkumar007:feat/bty-30-llm-code-transfer
Nov 30, 2026
Merged

solarsys merged 1 commit into
sunlabuiuc:masterfrom
tkumar007:feat/bty-30-llm-code-transfer

Conversation

@tkumar007

Copy link
Copy Markdown
Contributor

Implements [BTY-30] (LLM Code-Embedding Transfer) from:

Changes

  1. pyhealth/models/llm_code_transfer.py:
    • load_llm_code_embeddings() and build_llm_code_embeddings() for loading precomputed code vectors (dict, .csv/.tsv, .pt/.pth, .npz) or encoding code descriptions with any user-provided text embedding callable.
    • PositionalEncoding1D and PositionalEncoding2D (pure-PyTorch torch.bucketize binned sinusoidal encodings for patient age and continuous measurement values; adapted from mkirchler/grasp under MIT License).
    • LLMCodeEmbedding: Vocabulary-indexed lookup table mapping SequenceProcessor, NestedSequenceProcessor, and MultiHotProcessor vocabularies to frozen (or fine-tunable) LLM code vectors.
    • LLMCodeTransfer(BaseModel): Pre-LN Set Transformer with DropPath, optional LayerScale, padding-masked self-attention (cls_token or global_pool), forward_from_embedding(), and transfer_to_dataset() for zero-shot evaluation across disjoint coding systems (e.g., ICD-9 → ICD-10 or OMOP).
  2. Registration, Docs, & Example:
    • Exported public symbols in pyhealth/models/__init__.py.
    • Added docs/api/models/pyhealth.models.LLMCodeTransfer.rst and linked it in docs/api/models.rst.
    • Added runnable end-to-end training + zero-shot ICD-9 → ICD-10 transfer demo in examples/llm_code_transfer.py.
  3. Tests (tests/core/test_llm_code_transfer.py):
    • 16 offline unit tests covering embedding I/O, positional encodings, processor types, label modes, age/value conditioning, Trainer integration, and zero-shot cross-vocabulary transfer (95% coverage on pyhealth/models/llm_code_transfer.py).

@github-actions github-actions Bot mentioned this pull request Nov 30, 2026
@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 30, 2026
@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 88.42% (59174 / 66922 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 124 / 124
pyhealth/models/llm_code_transfer.py 94.61% 614 / 649

Workflow run · 6b80974

@solarsys

Copy link
Copy Markdown
Collaborator

/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 6b80974

"I50.9": "Heart failure unspecified",
"J18.9": "Pneumonia unspecified organism",
"J45.909": "Unspecified asthma uncomplicated",
"J44.9": "Chronic obstructive pulmonary disease unspecified",

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

freeze_embeddings: Freeze LLM code lookup weights (default ``True``).
normalize_embeddings: L2-normalize loaded LLM code vectors.
unknown_strategy: Fallback for unseen codes: ``"zero"`` or ``"mean"``.
age_key: Optional ``feature_keys`` entry supplying continuous ages.

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] age_key/value_key alignment requirement is undocumented

The auxiliary tensor must match the flattened code sequence length per patient, or _align_aux_tensor raises a ValueError at forward time. Nested-sequence code features combined with per-visit ages will fail this way. The docstring says only "Optional feature_keys entry supplying continuous ages." Document the required shape and alignment, or validate it in the constructor.

llm_embedding_dim=self.llm_embedding_dim,
**cfg,
)
if transferred.code_feature_keys != self.code_feature_keys:

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] transfer_to_dataset does not check that field types match

The check compares code_feature_keys and the label output size, but not the field types (sequence, nested_sequence, multi_hot). A source model trained on sequence codes can be transferred to a multi_hot target, and load_state_dict accepts it because the parameter shapes match. The forward pass then uses different masking semantics than training. Compare transferred._field_types with self._field_types and raise on mismatch.

assert out["logit"].shape == (4, expected_dim)
assert torch.isfinite(out["loss"])

def test_age_and_value_positional_encodings(self):

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] Age/value conditioning is never tested through the DataLoader

test_age_and_value_positional_encodings builds datasets with "tensor" age and value inputs, but it only calls the model with hand-built tensors. It never iterates get_dataloader over those datasets, so the collate padding of ragged auxiliary tensors is untested. Add one test that takes a batch from get_dataloader and runs a forward pass, as tests/core/test_descemb.py does for its cross-feature alignment.

@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. LLMCodeTransfer adds a Pre-LN Set Transformer over frozen LLM code embeddings. It also adds embedding loaders and builders, binned positional encodings, and transfer_to_dataset() for zero-shot transfer across coding systems. The change looks ready to merge.

  • Scope: The model is self-contained. It builds on BaseModel and the existing processors without modifying them. The pyhealth/models/__init__.py change only adds exports.
  • Sources: The paper and the reference repository are cited in the module docstring and the docs page. The MIT attribution for the adapted code is included.
  • Tests: There are 16 offline tests. Coverage is 94.6% for llm_code_transfer.py, above the 80% per-file bar. Total repository coverage is 88.4%, above the 60% bar.
  • Docs: The docs page matches the code.

Optional suggestions:

  • DescEmb: PyHealth already has DescEmb, which also targets cross-coding-system transfer but uses a BiGRU over code descriptions. A sentence in the description or docs on how LLMCodeTransfer differs would help readers choose between them.
  • Example encoder: In examples/llm_code_transfer.py, the keyword toy encoder gives the J44.9 description ("Chronic obstructive pulmonary disease…") no cluster match. The printed zero-shot number therefore says little about transfer. Adding "obstructive" to the respiratory keywords would fix this.
  • Age and value inputs: Document that age_key and value_key tensors must be per-code and aligned with the flattened code sequence.
  • Field types: transfer_to_dataset could also check that the source and target field types match, such as sequence versus multi-hot.
  • Collate path: The age and value tests call the model directly. A test through the DataLoader collate path would catch alignment problems there.

Reviewed commit 6b80974

@solarsys
solarsys merged commit e4e6d98 into sunlabuiuc:master Nov 30, 2026
3 checks passed
solarsys added a commit to solarsys/PyHealth that referenced this pull request Nov 30, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@tkumar007
tkumar007 deleted the feat/bty-30-llm-code-transfer branch November 30, 2026 07:07
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