Repository navigation
[BTY-30] Add LLMCodeTransfer for cross-coding-system EHR transfer - #1754
Conversation
Test CoverageTotal: 88.42% (59174 / 66922 lines)
|
|
/review |
| "I50.9": "Heart failure unspecified", | ||
| "J18.9": "Pneumonia unspecified organism", | ||
| "J45.909": "Unspecified asthma uncomplicated", | ||
| "J44.9": "Chronic obstructive pulmonary disease unspecified", |
There was a problem hiding this comment.
[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. |
There was a problem hiding this comment.
[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: |
There was a problem hiding this comment.
[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): |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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
BaseModeland the existing processors without modifying them. Thepyhealth/models/__init__.pychange 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_keyandvalue_keytensors must be per-code and aligned with the flattened code sequence. - Field types:
transfer_to_datasetcould 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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
Implements
[BTY-30](LLM Code-Embedding Transfer) from:Changes
pyhealth/models/llm_code_transfer.py:load_llm_code_embeddings()andbuild_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.PositionalEncoding1DandPositionalEncoding2D(pure-PyTorchtorch.bucketizebinned sinusoidal encodings for patient age and continuous measurement values; adapted frommkirchler/graspunder MIT License).LLMCodeEmbedding: Vocabulary-indexed lookup table mappingSequenceProcessor,NestedSequenceProcessor, andMultiHotProcessorvocabularies to frozen (or fine-tunable) LLM code vectors.LLMCodeTransfer(BaseModel): Pre-LN Set Transformer withDropPath, optionalLayerScale, padding-masked self-attention (cls_tokenorglobal_pool),forward_from_embedding(), andtransfer_to_dataset()for zero-shot evaluation across disjoint coding systems (e.g., ICD-9 → ICD-10 or OMOP).pyhealth/models/__init__.py.docs/api/models/pyhealth.models.LLMCodeTransfer.rstand linked it indocs/api/models.rst.examples/llm_code_transfer.py.tests/core/test_llm_code_transfer.py):Trainerintegration, and zero-shot cross-vocabulary transfer (95% coverage onpyhealth/models/llm_code_transfer.py).