Skip to content

[BTY-65] Add CHET model for dynamic disease graphs to pyhealth.models - #1550

Merged
solarsys merged 8 commits into
sunlabuiuc:masterfrom
Alhibb:feat/bty-65-chet
Nov 27, 2026
Merged

solarsys merged 8 commits into
sunlabuiuc:masterfrom
Alhibb:feat/bty-65-chet

Conversation

@Alhibb

@Alhibb Alhibb commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This pull request implements the CHET (Context-aware Health Event Prediction via Transition Functions on Dynamic Disease Graphs) model in pyhealth.models to complete bounty [BTY-65].

Paper: Chang Lu, Tian Han, Yue Ning. "Context-aware Health Event Prediction via Transition Functions on Dynamic Disease Graphs." Proceedings of the AAAI Conference on Artificial Intelligence (AAAI 2022). arXiv:2112.05195.

Key Components Implemented

  • compute_cooccurrence_adj: Dataset helper that computes row-normalized co-occurrence adjacency matrices from sample dataset sequences with the padding index explicitly zeroed. Users should provide training split samples to prevent data leakage.
  • SingleHeadAttentionLayer: Single-head attention layer used for transition dynamics between historical states and emerging/unrelated condition groups ($M_2, M_3$), with configurable value_input_size.
  • DotProductAttention: Masked dot-product attention mechanism to aggregate longitudinal visit embeddings into a patient representation.
  • CHET(BaseModel): Full PyHealth BaseModel integration featuring:
    • Dual graph convolution over center and 1-hop neighbor code embeddings.
    • Transition decomposition into persistent conditions ($M_1$ updated via GRU), emerging neighbor conditions ($M_2$ updated via attention), and novel unrelated conditions ($M_3$ updated via attention).
    • Code-level max pooling and visit-level dot-product attention.
    • Full task head integration supporting binary, multiclass, and multilabel classification, including datasets with multiple output targets via target label_key.
    • Robust handling of 2D flat sequences, 3D nested sequences, tuple inputs (time, value) and (value, mask), and all-pad patient visits without numerical instability or NaNs.
    • Transparent handling of feature keys: emits a warning only when multiple feature keys are explicitly passed.

Verification

  • Added 18 unit tests in tests/core/test_chet.py covering binary, multiclass, and multilabel classification, multi-output datasets with custom label_key, adjacency matrix generation, exact values, tuple variations, custom graph adjacency, empty/all-pad patient visits, 2D sequences, tuple inputs, gradient flow, parameter validation, differing query/key/value attention dimensions, exact M1/M2/M3 branch execution, and explicit multiple feature key warnings.
  • All 31 doctests pass across all public classes and functions.
  • Verified line lengths ($\le 88$ chars) and ruff formatting/linting.
  • All repository PR contribution rules pass (tools/check_pr_rules.py).

@Alhibb

Alhibb commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

/review

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

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.62% (47660 / 55022 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 94 / 94
pyhealth/models/chet.py 92.80% 245 / 264

Workflow run · a68624d

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

jhnwu3 commented Nov 19, 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 1f6ba5b

@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 the CHET model. It adds dynamic disease graph transition modeling to PyHealth, with docs, doctests and 12 unit tests. Coverage meets the bar: chet.py is at 92% and the whole repository is at 85%. The change is self-contained, and the exports in init.py are registration only.

To get this merged:

  1. Fix the mismatch between the docs and the code on graph initialization. docs/api/models/pyhealth.models.CHET.rst says the adjacency can be "dynamically initialized with an identity graph". The code never does this. With adj=None it calls compute_cooccurrence_adj. Please change the docs to say so, or implement the identity option.
  2. Fix the author citations. The PR description and the docs page say "Chang Lu and Chandan K. Reddy". The chet.py docstrings say "Chang Lu, Tian Han, Yue Ning". Please check the arXiv paper (2112.05195) and use the same authors everywhere.
  3. Resolve how feature_keys is handled. The constructor accepts feature_keys and the docstring says it is a "list of feature keys to use". The model only uses feature_keys[0], so any further keys, such as procedures, are silently ignored. Either support multiple features, or raise an error or clearly document that only the first key is used, and say so in the docstring.

Optional suggestions:

  • label_key will not work as a selector on datasets with several outputs, because label_processor raises. Consider documenting this.
  • The per-visit dense N x N adjacency matmul will be slow at MIMIC-sized vocabularies. A note in the docs would help.
  • test_compute_cooccurrence_adj could check actual values, such as row normalization, and not only the zeroed pad row and finiteness.
  • compute_cooccurrence_adj uses every sample passed to it. Note in the docs that you should pass only training data to avoid leaking evaluation inputs.
  • An example script would help users.

Reviewed commit 1f6ba5b

@Alhibb

Alhibb commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

/review

@Alhibb

Alhibb commented Nov 23, 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.

Previous review

Reviewed commit cd2b6ed

@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 adding CHET to pyhealth.models. The model, its two attention layers, the co-occurrence helper, the docs page and the 13 tests make a thorough contribution. Coverage is good: chet.py is at 92.5% against the 80% bar, and the repository total is 86.3% against 60%. The change is close to ready.

To get this merged:

  • Fix tuple handling in compute_cooccurrence_adj. The helper takes feat[0] of any tuple input (around lines 74-75), but CHET._extract_codes picks the first non-floating-point tensor. They disagree for time-first tuples such as (time, values), which StageNet-style processors produce.
    • With float times present, the times are cast to code indices, so the default adjacency built when adj=None is silently wrong.
    • With time set to None, it crashes.
    • Please use the same extraction logic in both places. You could reuse the model's approach in a small shared function, or copy it into the helper.
  • Add a test for it. test_tuple_input only covers (codes, mask). Please add a case where the tuple is (time, codes), and check that the adjacency from compute_cooccurrence_adj is correct.

Optional suggestions:

  • Add a test that checks actual adjacency values on a tiny example, and one that exercises the M1/M2/M3 transition branches. The current tests check shapes, finiteness and gradients, but not that logic.
  • Document that a user-supplied adj is expected to be row-normalized with the padding row and column zeroed.
  • Consider adding an example script for the diagnosis-prediction task mentioned in the bounty.
  • The per-visit, per-patient Python loop is slow. You already note the N x N cost in the docs. A short note about speed would help too.

Reviewed commit cd2b6ed

@Alhibb

Alhibb commented Nov 23, 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.

Previous review

Reviewed commit be7caf7

@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 adding CHET, a dynamic disease-graph model with a co-occurrence adjacency helper, two attention layers, docs and tests. The model is self-contained and coverage is good (chet.py 92.49%, repository total 86.26%). It is close.

To get this merged:

  1. SingleHeadAttentionLayer in pyhealth/models/chet.py builds self.dense_v = nn.Linear(query_size, value_size), so it only works when v has query_size features. The value_size argument and the name suggest the input should have value_size features. The docstring example hides this because it passes query_size=16 with a 16-dim v. Please either make the input size match the intended value_size (for example by adding a separate value_input_size) or document the constraint clearly. Please also add a test where key_size or query_size differs from the value input size.

Optional suggestions:

  • pyhealth/models/utils.py already has an ehr_cooccurrence_adjacency helper. Mentioning in the description how compute_cooccurrence_adj differs would help reviewers.
  • The M1/M2/M3 transition test only checks that outputs are finite. Asserting which branches fire, for example by mocking or counting indices, would make it stronger.
  • With adj=None the adjacency is built from whatever dataset is passed, so the training-split advice is not enforced. A short note in the docs is enough.
  • An example script would be a nice addition.

Reviewed commit be7caf7

@Alhibb

Alhibb commented Nov 23, 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.

Previous review

Reviewed commit c96e101

@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 adding CHET. The model, its co-occurrence adjacency helper and the two attention layers are a useful addition, and the docs and tests are thorough. Coverage is good: pyhealth/models/chet.py is at 92.5%, above the 80% bar, and the whole repository is at 86.3%, above the 60% bar. The model is self-contained: it uses only BaseModel and SampleDataset, and the init.py change is registration only. I found no overlap with an existing component.

To get this merged:

  • Spurious warning in the constructor (chet.py, the len(self.feature_keys) > 1 check). When feature_keys=None and the dataset has two or more input features, self.feature_keys is every dataset feature. The UserWarning then fires even though the user passed nothing. The warning text also says "Multiple feature keys were provided". This contradicts the docstring ("Defaults to the first feature key in dataset") and the PR description. The tests build datasets with conditions and procedures, so they hit this. To fix it, either:
    • Set self.feature_keys = [self.feature_keys[0]] when feature_keys is None, and warn only when the user explicitly passes more than one key.
    • Or change the docs to say the warning also fires for the default.

Optional suggestions:

  • The description says 13 unit tests, but the file has 17. Please update the count.
  • With adj=None, co-occurrence is computed over whatever dataset you pass. In the usual PyHealth pattern that is the full dataset, so test-split codes enter the graph. You document this, but a short example in the docstring showing how to pass a training-split adjacency would make it easier to follow.
  • Consider adding an example script that shows CHET running on a real task.

Reviewed commit c96e101

@Alhibb

Alhibb commented Nov 23, 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.

Previous review

Reviewed commit 55e8efb

@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 CHET. It's a faithful, well-documented implementation of the AAAI 2022 model. It has a co-occurrence adjacency helper, two attention layers, a docs page and 17 tests. Coverage is above the bar: chet.py is at 92.55% against 80%, and the repository total is 86.26% against 60%. The description also explains how compute_cooccurrence_adj differs from ehr_cooccurrence_adjacency, which is helpful.

You're close. One blocking problem remains.

To get this merged:

  1. label_key doesn't work for multi-label datasets. CHET.__init__ accepts label_key, and the docstring tells users with multiple labels to pass it. But the constructor (self.label_processor.output_size()) and forward (self.label_processor.activation and .loss) use BaseModel.label_processor. That property raises when the dataset has more than one label processor, so the documented path fails at construction.
    • Look up the processor with self.dataset.output_processors[self.label_key] instead, and use it in __init__ and forward.
    • Alternatively, remove label_key and its docstring text, and state that only single-label datasets are supported.
    • Please add a test for whichever you choose. For the first option, use a dataset with two output keys and pass label_key.

Optional suggestions:

  • Add an Args section to the DotProductAttention docstring.
  • Consider adding a short example script under examples/.

Reviewed commit 55e8efb

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

Previous review

Reviewed commit 75d89af

github-actions[bot]
github-actions Bot previously approved these changes Nov 24, 2026

@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: approve
decision: approve

Thank you for contributing CHET. It adds a dynamic disease graph model for health event prediction, with a co-occurrence adjacency helper, two attention layers, a docs page and 18 unit tests.

The change looks ready to merge. CHET is self-contained. It builds only on BaseModel and SampleDataset, and the init.py change only adds exports. The docs match the code, and the paper is cited. Coverage meets the bar. pyhealth/models/chet.py is at 92.8% against the 80% target, and the whole repository is at 86.26% against the 60% target.

Optional suggestions:

  • Say briefly in the description why SingleHeadAttentionLayer and DotProductAttention are exported publicly. If they are only CHET internals, you could leave them out of the package exports.
  • The default adj=None builds co-occurrence from whatever dataset is passed. If that is the full dataset, evaluation-split data leaks into the graph. You document this, and a short usage example showing the train-split workflow would help.
  • Per-visit dense N x N multiplications inside Python loops will likely be slow at MIMIC-sized vocabularies. You already note this in the docs. An example script or a benchmark would help users judge it.

Reviewed commit 75d89af

# Conflicts:
#	docs/api/models.rst
#	pyhealth/models/__init__.py
@solarsys

Copy link
Copy Markdown
Collaborator

Thanks Alhibb. This was approved but conflicted with your GAME PR (#1582) in pyhealth/models/__init__.py and docs/api/models.rst, so I merged master and kept both CHET and GAME. No other changes; test_chet passes. It should merge once the build and a fresh review pass.

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

Comment thread pyhealth/models/chet.py
)

if feat.dim() == 2:
feat = feat.unsqueeze(1) # (B, 1, K)

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 code sequences are treated as one visit, so transition logic never runs

For a 2D input (B, K) the model adds a single visit axis (feat = feat.unsqueeze(1)), so all codes of a patient land in one visit. Each element of a flat sequence feature is a step in PyHealth (the (batch, steps) code tensor is what a sequence processor produces), so the input should be T visits of one code each. As written, the GRU, the M1/M2/M3 transitions and the visit-level attention never see time, and test_2d_flat_sequence only checks the output shape. The description advertises 2D handling as robust but does not say this interpretation was chosen. Fix: treat (B, T) as T single-code visits (e.g. unsqueeze(-1)), or raise a clear error for 2D input and document it. Add a test that the GRU runs once per step, similar to test_transition_branches_m1_m2_m3.

Comment thread pyhealth/models/chet.py

# Compute or validate adjacency matrix
if adj is None:
adj_tensor = compute_cooccurrence_adj(dataset, self.primary_feature_key)

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] Default adjacency is built from whatever dataset is passed, which can leak

With adj=None the co-occurrence graph is computed from every sample in the dataset given to the constructor. If the full dataset is passed (common when the model is built before splitting), validation and test patients' input codes shape the graph. Labels do not leak, and the docstring warns about this, but the default path is leak-prone. Consider requiring the training split in the example or making adj a required argument for split workflows.

@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 contributing CHET. It adds a transition-function model on dynamic disease graphs, with a co-occurrence adjacency helper, two attention layers, a docs page and 18 unit tests. It looks ready to merge.

  • Self-contained: The model only imports SampleDataset and BaseModel, so it adds no links to other components. The docs say how compute_cooccurrence_adj differs from ehr_cooccurrence_adjacency, so it doesn't duplicate an existing component.
  • Docs: The docs match the code.
  • Coverage: chet.py is at 92.8% and models/__init__.py at 100%. Both clear the 80% per-file bar. The whole repository is at 86.6%, above the 60% bar.

Optional suggestions:

  • A 2D (B, K) input is treated as a single visit, so the GRU and the M1/M2/M3 transitions never see time for flat sequence features. That seems reasonable, but please say so in the forward or class docstring and in the docs. test_2d_flat_sequence currently only checks the output shape.
  • With adj=None, the adjacency is built from whatever dataset you pass in. Your docs already warn about this, and the model docstring could repeat it.
  • The per-patient and per-visit Python loops and the dense N×N multiplications will be slow on large vocabularies. You've documented that. A small example script would help users.

Reviewed commit a68624d

@solarsys
solarsys merged commit d5c9829 into sunlabuiuc:master Nov 27, 2026
2 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