Repository navigation
[BTY-46] Add GAME harmonized medical code embeddings to pyhealth.models - #1582
Conversation
|
/review |
Test CoverageTotal: 86.32% (46109 / 53419 lines)
|
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for contributing GAME. It adds harmonized medical code embedding helpers and a GAME(BaseModel) with GRU/LSTM/Transformer backbones, plus docs and tests. It is close. Coverage is good: game.py is at 87.84% (bar 80%) and the whole repository is at 86.24% (bar 60%).
To get this merged:
- Fix the Transformer head count in
game.py.nheadistotal_input_dim // 64(or 1), with no divisibility check. For example,embedding_dim=100with two features givesd_model=200andnhead=3, which crashesnn.MultiheadAttention. Pick annheadthat dividesd_model, or validate it and raise a clear error. - Fix the NaN risk for fully padded patients with the Transformer backbone.
src_key_padding_maskonnn.TransformerEncodercan produce NaNs when every visit is masked. The mean and attention pooling then carry the NaNs through. This contradicts the "no NaNs" claim in the description. Please handle it, for example by un-masking at least one position and zeroing the output afterwards, and add a test that uses the Transformer with an empty patient. - Say in the description whether
init_embedding_with_gameandGAMEEmbeddingintentionally duplicate the existing pretrained-embedding initialization inpyhealth/models/embedding.py. If this is intended, give the reason. If not, please make the component self-contained or explain the difference.
Optional suggestions:
torch.load(..., weights_only=False)on a user-supplied path can execute arbitrary code. Considerweights_only=True.- Add tests for
code_mapping, for loading GAME from a file path, and for the(time, value)tuple case that the description mentions.
Reviewed commit cc91a6c
…ty-patient NaNs, and use weights_only=True
|
/review |
| dropout=dropout, | ||
| batch_first=True, | ||
| ) | ||
| self.temporal_model = nn.TransformerEncoder( |
There was a problem hiding this comment.
[medium] Transformer backbone ignores visit order
The Transformer branch builds nn.TransformerEncoder over the per-visit representations without any positional encoding. Self-attention is then permutation-invariant over visits, so the model cannot distinguish earlier from later visits, even though the class and docs present the Transformer as temporal modeling. Add a positional encoding over the visit index, or document that the Transformer backbone is order-agnostic and restrict or warn about it. Add a test that reordering visits changes the output for the Transformer, or drop the temporal claim.
| f"Feature '{f_key}' has dimension {raw_feat.dim()} > 3, " | ||
| "which is not supported." | ||
| ) | ||
| if raw_feat.dim() == 2: |
There was a problem hiding this comment.
[medium] 2D flat-sequence input is claimed but untested
The 2D branch that expands (B, L) to (B, L, 1) is described in the PR as robust handling of 2D flat sequences, but every test in tests/core/test_game.py uses input_schema 'nested_sequence'. Add a test with a 'sequence' input schema that checks the forward pass produces finite outputs and the expected shapes, and that padding positions are ignored.
| raise TypeError(f"Unsupported source type: {type(source)}.") | ||
|
|
||
|
|
||
| def init_embedding_with_game( |
There was a problem hiding this comment.
[low] Lookup loop duplicates init_embedding_with_pretrained
init_embedding_with_game repeats the vocabulary-to-vector copy, pad zeroing, normalization and freeze logic of init_embedding_with_pretrained in pyhealth/models/embedding.py. The differences (multi-format loading, code normalization, code_mapping) are real, so this is not redundant, but consider adding the normalizer and format handling as options to the existing function instead of a parallel copy, or state in the description why the copy is kept.
| ) | ||
|
|
||
| # Determine embedding source for this feature | ||
| f_source = game_embeddings |
There was a problem hiding this comment.
[low] Per-feature dict without a feature key fails with an unclear error
When game_embeddings is a dict keyed by feature name and a feature key is missing from it, f_source falls back to the whole outer dict. That dict-of-dicts then reaches torch.tensor(v) in load_game_embeddings and raises a TypeError that does not name the missing feature. Raise a ValueError naming the feature key, or pass None for features with no entry, and add a test.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: approve
Thank you for adding GAME. It brings harmonized medical code embeddings to PyHealth: a flexible loader that handles several file formats, a drop-in initializer, an embedding module and a full BaseModel with GRU, LSTM and Transformer backbones. The change is self-contained, and it's registered in pyhealth/models/init.py with a docs page. The description cites the paper and explains how the change relates to init_embedding_with_pretrained. Coverage is 86.96% for game.py against the 80% bar, and 86.32% for the whole repository against the 60% bar. It looks ready to merge.
Optional suggestions:
- The Transformer backbone has no positional encoding, so visit order isn't used in that mode. Consider adding one, or noting it in the docstring. Also say that hidden_dim sets the feed-forward width there, not the output size.
- The 2D flat-sequence path ((B, L) inputs) has no test, because every current test uses nested_sequence. A short test would back up the robustness claim in the description.
- If game_embeddings is a per-feature dict that omits one feature, the whole dict is passed on for that feature. This ends in a confusing TypeError. A clearer error, or a fallback to random initialization for that feature, would help.
- The docs could say where to get the pretrained GAME vectors, for example by linking the official repository. A small example script would also help.
- init_embedding_with_game repeats part of the lookup loop in init_embedding_with_pretrained. Copying it is fine for keeping components self-contained, so no change is needed.
Reviewed commit f2ead14
Summary
This pull request implements the GAME (Globally Aligned Medical Embeddings for Multi-institutional EHR Data) drop-in embedding initializer and model in
pyhealth.modelsto complete bounty [BTY-46].Paper: Tong Han et al. "Representation learning to advance multi-institutional studies with electronic health record data from US and France." Nature Communications (2025). DOI:10.1038/s41467-025-56837-1. Official repository: celehs/GAME.
Relationship to Existing Pretrained Embedding Initialization (
embedding.py)init_embedding_with_gameandGAMEEmbeddingare specialized harmonized medical code embedding initializers that intentionally complement the general-purpose text-vector loader inpyhealth.models.embedding:init_embedding_with_pretrainedinembedding.pyonly parses GloVe-style whitespace-delimited.txtfiles line by line from disk, GAME code embeddings are released in heterogeneous binary formats across PyTorch.pt/.pthcheckpoints, NumPy.npy/.npzarchives, CSVs, and in-memory Python dictionaries or tensors.normalize_game_code) to reconcile EHR coding schemes across healthcare systems (stripping institutional prefixes such asICD10CM:,CCS:,LOINC:,RxNorm:and standardizing whitespace/case) before token matching.GAMEEmbeddingadditionally bundles optional dimension projection and direct integration into the full longitudinalGAMEmodel.Key Components Implemented
normalize_game_code: Normalizes clinical codes across heterogeneous institutional naming conventions by stripping standard vocabulary tags (ICD10CM:,CCS:,LOINC:,RxNorm:), removing whitespace, and standardizing casing.load_game_embeddings: Flexible loader supporting dictionaries, PyTorch tensors/checkpoints (.pt,.pthloaded safely withweights_only=True), NumPy files/archives (.npy,.npz), and delimited text/CSV files (.csv,.tsv,.txt).init_embedding_with_game: Drop-in initializer that populates annn.Embeddinglayer with GAME harmonized vectors, explicitly zeroing the padding row, handling code normalization, and supporting weight freezing and L2-normalization.GAMEEmbedding: Drop-in embedding module wrappingnn.Embeddingwith GAME pretrained vector loading and optional linear dimension projection.GAME(BaseModel): Full PyHealth BaseModel integrating GAME embeddings across patient visits with:nhead).attention,mean,max, orlastvalid visit.(time, value)and(value, mask), and all-pad empty patient visits without NaNs.Verification
tests/core/test_game.pycovering dictionary/tensor/file embedding loading (.txt, .npy, .pt withweights_only=True), code normalization, embedding layer forward passes, binary/multiclass/multilabel classification tasks, empty patient visits on GRU and Transformer, gradient flow and freezing, tuple inputs(time, value)and(value, mask), customcode_mapping, and parameter validation.pyhealth/models/game.py.ruffand all lines strictlytools/check_pr_rules.py).