Skip to content

[BTY-46] Add GAME harmonized medical code embeddings to pyhealth.models - #1582

Merged
solarsys merged 2 commits into
sunlabuiuc:masterfrom
Alhibb:feat/bty-46-game
Nov 24, 2026
Merged

solarsys merged 2 commits into
sunlabuiuc:masterfrom
Alhibb:feat/bty-46-game

Conversation

@Alhibb

@Alhibb Alhibb commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This pull request implements the GAME (Globally Aligned Medical Embeddings for Multi-institutional EHR Data) drop-in embedding initializer and model in pyhealth.models to 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_game and GAMEEmbedding are specialized harmonized medical code embedding initializers that intentionally complement the general-purpose text-vector loader in pyhealth.models.embedding:

  • Format Flexibility: While init_embedding_with_pretrained in embedding.py only parses GloVe-style whitespace-delimited .txt files line by line from disk, GAME code embeddings are released in heterogeneous binary formats across PyTorch .pt/.pth checkpoints, NumPy .npy/.npz archives, CSVs, and in-memory Python dictionaries or tensors.
  • Code Harmonization: GAME requires clinical code vocabulary harmonization (normalize_game_code) to reconcile EHR coding schemes across healthcare systems (stripping institutional prefixes such as ICD10CM:, CCS:, LOINC:, RxNorm: and standardizing whitespace/case) before token matching.
  • Architecture Integration: GAMEEmbedding additionally bundles optional dimension projection and direct integration into the full longitudinal GAME model.

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, .pth loaded safely with weights_only=True), NumPy files/archives (.npy, .npz), and delimited text/CSV files (.csv, .tsv, .txt).
  • init_embedding_with_game: Drop-in initializer that populates an nn.Embedding layer with GAME harmonized vectors, explicitly zeroing the padding row, handling code normalization, and supporting weight freezing and L2-normalization.
  • GAMEEmbedding: Drop-in embedding module wrapping nn.Embedding with GAME pretrained vector loading and optional linear dimension projection.
  • GAME(BaseModel): Full PyHealth BaseModel integrating GAME embeddings across patient visits with:
    • Intra-visit code pooling (max-pooling non-padding codes).
    • Temporal modeling via recurrent GRU, LSTM, or Transformer sequence backbones with automatically validated divisor head selection (nhead).
    • Visit pooling across time via attention, mean, max, or last valid visit.
    • End-to-end task support across binary, multiclass, and multilabel classification.
    • Robust handling of 2D flat sequences, 3D nested sequences, tuple inputs (time, value) and (value, mask), and all-pad empty patient visits without NaNs.

Verification

  • Added 15 unit tests in tests/core/test_game.py covering dictionary/tensor/file embedding loading (.txt, .npy, .pt with weights_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), custom code_mapping, and parameter validation.
  • All 38 doctests pass across all public classes and functions in pyhealth/models/game.py.
  • Formatted with ruff and all lines strictly $\le 88$ characters.
  • All repository PR contribution rules pass (tools/check_pr_rules.py).

@Alhibb

Alhibb commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot mentioned this pull request Nov 23, 2026
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.32% (46109 / 53419 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 91 / 91
pyhealth/models/delphi.py 95.24% 240 / 252
pyhealth/models/game.py 86.96% 240 / 276
pyhealth/tasks/__init__.py 98.04% 100 / 102
pyhealth/tasks/delphi_trajectory.py 91.28% 157 / 172
pyhealth/tasks/mortality_prediction.py 90.41% 396 / 438
pyhealth/tasks/readmission_prediction.py 94.14% 209 / 222

Workflow run · f2ead14

@jhnwu3 jhnwu3 added the status: automatic The PR will go through automatic review process. label Nov 23, 2026
@jhnwu3

jhnwu3 commented Nov 23, 2026

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.

Previous review

Reviewed commit cc91a6c

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

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:

  1. Fix the Transformer head count in game.py. nhead is total_input_dim // 64 (or 1), with no divisibility check. For example, embedding_dim=100 with two features gives d_model=200 and nhead=3, which crashes nn.MultiheadAttention. Pick an nhead that divides d_model, or validate it and raise a clear error.
  2. Fix the NaN risk for fully padded patients with the Transformer backbone. src_key_padding_mask on nn.TransformerEncoder can 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.
  3. Say in the description whether init_embedding_with_game and GAMEEmbedding intentionally duplicate the existing pretrained-embedding initialization in pyhealth/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. Consider weights_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

@Alhibb

Alhibb commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

/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 f2ead14

Comment thread pyhealth/models/game.py
dropout=dropout,
batch_first=True,
)
self.temporal_model = nn.TransformerEncoder(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread pyhealth/models/game.py
f"Feature '{f_key}' has dimension {raw_feat.dim()} > 3, "
"which is not supported."
)
if raw_feat.dim() == 2:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread pyhealth/models/game.py
raise TypeError(f"Unsupported source type: {type(source)}.")


def init_embedding_with_game(

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

Comment thread pyhealth/models/game.py
)

# Determine embedding source for this feature
f_source = game_embeddings

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

@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 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

@solarsys
solarsys merged commit c70974e into sunlabuiuc:master Nov 24, 2026
3 checks passed
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.

3 participants