Repository navigation
[BTY-50] Add UDC model for rare disease prediction to pyhealth.models - #1529
Conversation
Test CoverageTotal: 85.03% (40203 / 47280 lines)
|
|
/review |
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for contributing UDC, a residual-vector-quantization model for rare disease prediction, with docs and 15 unit tests. It is close. Coverage is good: udc.py is at 93.78% and the whole repository at 84.77%. The model is self-contained and uses EmbeddingModel and get_last_visit, which the description explains.
To get this merged:
- In
forward, the visit mask of the first feature isn't padded when the features have different visit counts. A flatsequencefeature such asdrugscan be longer than a nested visit feature, which is the schema your own tests use. Concatenation then pads the features, butoverall_mask = visit_masks[0]keeps its original length and is OR-ed with longer padded masks, so this can raise a shape error. Pad every mask tomax_tbefore combining them. - With
intra_visit_pooling="max", fully padded visits are filled with -1e9 and then count as valid, because the visit mask is derived fromfeat != 0.get_last_visitcan then select a padding step when visit counts are mixed in a batch. Please build the visit mask from the code mask, for examplecode_mask.any(-1), and zero out empty visits after pooling. - The
modeargument is accepted but never used, although the docstring says it is. Either use it or remove it and fix the docstring. - The description says
(time, value)tuples are handled, but the code takesval[0]as the value. For a(time, value)tuple this would be the time tensor. Handle that case correctly, or narrow the claim in the description to(value, mask)tuples. - Please add tests for these paths: batches with unequal visit counts across features, "max" pooling with padded visits, and an assertion on the visit-mask logic. The current tests use only equal-length batches and check only
isfinite.
Optional suggestions:
**kwargsis silently ignored. Consider removing it or documenting it.- A short example script would help users, but it isn't required.
Reviewed commit 984162b
…visits, mode removal
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for contributing UDC. It adds a residual vector quantization model for rare disease prediction, with docs and tests. It is self-contained, and its only reuse is EmbeddingModel, which your description names, and the shared get_last_visit utility. Coverage for udc.py is 96.7% and the repo total is 85%, both above the bar. The paper is cited. You are close, with two blocking problems.
To get this merged:
- The
transformertemporal option callsself.temporal_encoder(fused_visits)with no padding mask. Padded visits are non-zero afterfeat_projand LayerNorm, so they take part in attention. A patient's prediction then depends on how much padding the batch has. Please passsrc_key_padding_mask=~overall_maskto the transformer. Also mask padded visits out of the VQ loss and the quantizer path. Add a test that a patient's output doesn't change when the batch is padded further. test_visit_mask_logic_assertionrebuilds the mask inside the test and asserts on that copy, so it never runs code inudc.py. Please change it to check the model's actual behavior. For example, check that the padded visits of a short patient don't changeembedorlogit. Or expose the mask and assert on it.
Optional suggestions:
- The docs say inference returns
vq_indices, but the code returns it only when the label key is absent. Please align the docs and code, or always return it. vq_losscurrently includes padded visits. Averaging over valid visits only would be cleaner.- The description has a stray
81393around the LaTeX formula, which you could fix.
Reviewed commit 55cb8a4
…s, add padding invariance test
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for adding UDC. The residual vector quantizer, the discrete clue encoder and the BaseModel integration are a useful addition, and the tests and docs are thorough. Coverage is 96.8% for udc.py and 85% for the repository, which clears the bar. The change is close, but I found a few problems to fix first.
To get this merged:
- Transformer with an empty patient. With
temporal_model="transformer", a patient whose features are all empty hasoverall_maskall False.src_key_padding_mask=~overall_maskthen masks every position in that row, and attention over a fully masked row typically gives NaN. That NaN can spread into the batch loss. Please guard this case. For example, force at least one position to be unmasked and zero its output afterwards. Please also add a test for it, because no test covers an empty patient with the transformer. - Deeper nested inputs. The
while feat.dim() > 3loop accepts inputs with more than four dimensions, such as 5-D deep-nested input._pool_intra_visitalways pools over dim 2, so the visit axis would be pooled and the embeddings would be silently wrong. Please either raise a clear error for unsupported dimensionality or pool correctly. A test for the chosen behavior would help. vq_indicesdocumentation. Theforwarddocstring saysvq_indicesis returned "during inference", and the rst says the same. The code returns it every time. Please correct both so they match the code.
Optional suggestions:
- Add an example script or notebook, as other recent models have.
- Make the max-pooling test stricter than
embed > -1e5.
Reviewed commit 38b66bf
…ures, correct vq_indices docs, and strengthen max-pooling test
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for adding UDC. The residual vector quantization model comes with a docs page and a thorough test suite. Coverage is good: pyhealth/models/udc.py is at 96.12%, which is above the 80% bar, and the whole repository is at 85.05%, which is above the 60% bar. The model is self-contained: it subclasses BaseModel and only uses the shared EmbeddingModel and get_last_visit. It looks close, but two items need fixing first.
To get this merged:
- Docs don't match the code. pyhealth.models.UDC.rst says
lossandvq_lossare returned "during training". Inforward,vq_lossis always returned.lossandy_trueare returned whenever the label key is in the inputs. Please reword the page to say that. - (time, value) tuple inputs. The description says these are handled safely. In
forward, when the processor schema has no "mask" entry, the mask falls back toval[1]. For a (time, value) tuple,val[1]is the value tensor itself, so it gets used as the visit or code mask. Please makeforwardignore the mask for schemas without a "mask" field, so the mask is computed from the embeddings instead. Add a test for that path, or narrow the description's claim.
Optional suggestions:
- Check the outputs of the different intra_visit_pooling modes. The current test only checks that the loss is finite.
- Remove the extra trailing blank line in models/init.py.
**kwargsin UDC.init is silently ignored. Consider removing it or documenting it.- Add a short usage example script.
Reviewed commit 32ee6d0
…ify vq_loss and loss return docs, and test pooling outputs
|
/review |
| and not second.is_floating_point() | ||
| ): | ||
| # (time, value) | ||
| value = second |
There was a problem hiding this comment.
[medium] Tuple inputs are misread by dtype, so the mask can be used as values
For a 2-tuple, the branch at lines 553-560 treats (floating value, non-floating second) as (time, value) and sets value = second. A (float values, int mask) pair is therefore fed to the embedding as values, the real values are dropped, and no error is raised. No current processor emits this exact pair, which is why it is latent, but the description says tuple inputs are handled safely. Fix: when the processor schema is known, pick value, mask and time by schema() index for any tuple, not only time/value pairs. Also move the len(val) >= 3 branch below the schema branch, because a schema-known 3-tuple without a time/value pair currently takes val[1] as the value.
| dropout=dropout, | ||
| batch_first=True, | ||
| ) | ||
| self.temporal_encoder = nn.TransformerEncoder( |
There was a problem hiding this comment.
[medium] Transformer temporal model has no positional information
The visit sequence reaching nn.TransformerEncoder (lines 457-461) carries no position or order information: visit_repr and fused_visits are per-visit vectors with no positional encoding. The transformer output is therefore invariant to the order of visits, and the last-visit readout does not reflect temporal order, although the description presents 'transformer' as longitudinal modeling. Fix: add sinusoidal or learned position embeddings to fused_visits before the encoder, as behrt.py does, or document the limitation on the transformer option.
| self.assertEqual(idx_3d.shape, (2, 5, 2)) | ||
| self.assertTrue(loss_3d.item() >= 0.0) | ||
|
|
||
| def test_straight_through_gradients(self): |
There was a problem hiding this comment.
[low] RVQ tests do not check codebook learning or mask handling
test_straight_through_gradients only checks that x.grad is finite. Nothing checks that codebook weights receive gradients from vq_loss, that the indices reproduce quantized, or that masked-out visits are excluded from the VQ loss. Those are the properties the component exists for. Add one test that codebook weights get a nonzero gradient after backward, and one that changing a masked-out visit does not change vq_loss.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: approve
Thank you for adding UDC. The model has a residual vector quantizer, a discrete clue encoder, and GRU, LSTM and Transformer temporal options. It supports binary, multiclass and multilabel tasks, and it comes with docs and 21 tests. It looks ready to merge. The new file udc.py has 92% coverage, which is above the 80% bar, and total repository coverage is 85%, above the 60% bar. I couldn't run the tests myself, so I'm relying on the coverage report for that.
The model is self-contained. It subclasses BaseModel and uses EmbeddingModel and get_last_visit as documented, and __init__.py only gains the new exports.
Optional suggestions:
- Transformer positions: The Transformer temporal encoder has no positional encoding, so visit order is only reflected through the last-valid-visit readout. Adding a positional or time encoding would make the longitudinal modeling stronger. Otherwise, a short docstring note would make the limitation clear.
- Tuple inputs:
forwardtells a(value, mask)tuple from a(time, value)tuple by dtype. A float value paired with an integer mask would be read as(time, value), so the mask would be used as the values. Checking the processor schema first, or documenting the expected tuple formats, would remove the ambiguity. - Extra tests: A test that masked visits are excluded from the VQ loss would be useful. So would one that codebook entries move during training.
- Example script: A short example script on one of the target datasets would help users.
Reviewed commit d6a3fe0
|
/merge |
Summary
This pull request implements the UDC (Unveiling Discrete Clues) model in
pyhealth.modelsto complete bounty [BTY-50].Architectural Highlights
Residual Vector Quantization (
ResidualVectorQuantizer):Discrete Clue Fusion (
DiscreteClueEncoder):Full PyHealth 2.0 Integration (
UDC):pyhealth.models.BaseModelwithout altering any core files.pyhealth.models.EmbeddingModelto embed input features."sum","mean","max","attention"), as well as 2D sequences."gru","lstm","transformer")."binary","multiclass", and"multilabel"tasks viaself.label_processor.(value, mask)or(time, value)safely.Changes Made
pyhealth/models/udc.py(UDC,ResidualVectorQuantizer,DiscreteClueEncoder).pyhealth/models/__init__.py.docs/api/models/pyhealth.models.UDC.rstand registered indocs/api/models.rst.tests/core/test_udc.py.Verification
check_pr_rules.py: Passed (all modified lines adhere strictly toruffrules and line-length limits>>>doctests).tests/core/test_udc.py: 21 unit tests pass in 0.18s on CPU.