Repository navigation
[BTY-65] Add CHET model for dynamic disease graphs to pyhealth.models - #1550
Conversation
|
/review |
Test CoverageTotal: 86.62% (47660 / 55022 lines)
|
|
/review |
There was a problem hiding this comment.
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:
- 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.
- 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.
- 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
|
/review |
|
/review |
There was a problem hiding this comment.
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 takesfeat[0]of any tuple input (around lines 74-75), butCHET._extract_codespicks 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=Noneis 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.
- With float times present, the times are cast to code indices, so the default adjacency built when
- Add a test for it.
test_tuple_inputonly covers(codes, mask). Please add a case where the tuple is(time, codes), and check that the adjacency fromcompute_cooccurrence_adjis 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
adjis 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
…ansition and tuple tests
|
/review |
There was a problem hiding this comment.
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:
SingleHeadAttentionLayerinpyhealth/models/chet.pybuildsself.dense_v = nn.Linear(query_size, value_size), so it only works whenvhasquery_sizefeatures. Thevalue_sizeargument and the name suggest the input should havevalue_sizefeatures. The docstring example hides this because it passesquery_size=16with a 16-dimv. Please either make the input size match the intendedvalue_size(for example by adding a separatevalue_input_size) or document the constraint clearly. Please also add a test wherekey_sizeorquery_sizediffers from the value input size.
Optional suggestions:
pyhealth/models/utils.pyalready has anehr_cooccurrence_adjacencyhelper. Mentioning in the description howcompute_cooccurrence_adjdiffers 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=Nonethe 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
…onLayer and add branch execution tests
|
/review |
There was a problem hiding this comment.
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) > 1check). Whenfeature_keys=Noneand the dataset has two or more input features,self.feature_keysis 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 withconditionsandprocedures, so they hit this. To fix it, either:- Set
self.feature_keys = [self.feature_keys[0]]whenfeature_keysis 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.
- Set
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
…nd illustrate train adj
|
/review |
There was a problem hiding this comment.
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:
label_keydoesn't work for multi-label datasets.CHET.__init__acceptslabel_key, and the docstring tells users with multiple labels to pass it. But the constructor (self.label_processor.output_size()) andforward(self.label_processor.activationand.loss) useBaseModel.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__andforward. - Alternatively, remove
label_keyand 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.
- Look up the processor with
Optional suggestions:
- Add an
Argssection to theDotProductAttentiondocstring. - Consider adding a short example script under
examples/.
Reviewed commit 55e8efb
…d DotProductAttention Args docs
|
/review |
There was a problem hiding this comment.
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
|
Thanks Alhibb. This was approved but conflicted with your GAME PR (#1582) in |
|
/review |
| ) | ||
|
|
||
| if feat.dim() == 2: | ||
| feat = feat.unsqueeze(1) # (B, 1, K) |
There was a problem hiding this comment.
[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.
|
|
||
| # Compute or validate adjacency matrix | ||
| if adj is None: | ||
| adj_tensor = compute_cooccurrence_adj(dataset, self.primary_feature_key) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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
SampleDatasetandBaseModel, so it adds no links to other components. The docs say howcompute_cooccurrence_adjdiffers fromehr_cooccurrence_adjacency, so it doesn't duplicate an existing component. - Docs: The docs match the code.
- Coverage:
chet.pyis at 92.8% andmodels/__init__.pyat 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 flatsequencefeatures. That seems reasonable, but please say so in theforwardor class docstring and in the docs.test_2d_flat_sequencecurrently 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
Summary
This pull request implements the CHET (Context-aware Health Event Prediction via Transition Functions on Dynamic Disease Graphs) model in
pyhealth.modelsto 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 (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:label_key.(time, value)and(value, mask), and all-pad patient visits without numerical instability or NaNs.Verification
tests/core/test_chet.pycovering binary, multiclass, and multilabel classification, multi-output datasets with customlabel_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.tools/check_pr_rules.py).