Skip to content

[BTY-50] Add UDC model for rare disease prediction to pyhealth.models - #1529

Merged
github-actions[bot] merged 5 commits into
sunlabuiuc:masterfrom
Alhibb:feat/bty-50-udc
Nov 19, 2026
Merged

github-actions[bot] merged 5 commits into
sunlabuiuc:masterfrom
Alhibb:feat/bty-50-udc

Conversation

@Alhibb

@Alhibb Alhibb commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This pull request implements the UDC (Unveiling Discrete Clues) model in pyhealth.models to complete bounty [BTY-50].

  • Paper: Chuang Zhao, Hui Tang, Jiheng Zhang, Xiaomeng Li. Unveiling Discrete Clues: Superior Healthcare Predictions for Rare Diseases. The Web Conference (WWW 2025). arXiv:2501.16373
  • Official Code: Data-Designer/UDCHealth

Architectural Highlights

  1. Residual Vector Quantization (ResidualVectorQuantizer):

    • Implements multi-stage Residual Vector Quantization (RVQ) with straight-through gradient estimation.
    • Decomposes continuous clinical representations into discrete codebook prototypes, preventing frequent common conditions from overwhelming subtle, sparse clues indicative of rare diseases.
    • Optimizes joint vector quantization and commitment loss.
  2. Discrete Clue Fusion (DiscreteClueEncoder):

    • Maps continuous representations into prototype latent space.
    • Fuses continuous embeddings with quantized discrete clues via residual addition and LayerNorm:
      $$\mathbf{h} = \text{LayerNorm}(\mathbf{x} + \mathbf{z}_q)$$
  3. Full PyHealth 2.0 Integration (UDC):

    • Subclasses pyhealth.models.BaseModel without altering any core files.
    • Seamlessly uses pyhealth.models.EmbeddingModel to embed input features.
    • Supports 3D nested visit sequences with configurable intra-visit pooling ("sum", "mean", "max", "attention"), as well as 2D sequences.
    • Flexible temporal modeling across longitudinal visits ("gru", "lstm", "transformer").
    • Fully supports "binary", "multiclass", and "multilabel" tasks via self.label_processor.
    • Handles tuple-valued inputs (value, mask) or (time, value) safely.

Changes Made

  • Added pyhealth/models/udc.py (UDC, ResidualVectorQuantizer, DiscreteClueEncoder).
  • Registered exports in pyhealth/models/__init__.py.
  • Added Sphinx documentation in docs/api/models/pyhealth.models.UDC.rst and registered in docs/api/models.rst.
  • Added 21 comprehensive unit tests in tests/core/test_udc.py.

Verification

  • check_pr_rules.py: Passed (all modified lines adhere strictly to ruff rules and line-length limits $\le 88$, docstrings include executable >>> doctests).
  • tests/core/test_udc.py: 21 unit tests pass in 0.18s on CPU.
  • Doctests: All doctests execute and pass.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 85.03% (40203 / 47280 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 64 / 64
pyhealth/datasets/helsinki_neonatal.py 97.06% 66 / 68
pyhealth/datasets/hup_ieeg.py 96.00% 96 / 100
pyhealth/models/__init__.py 100.00% 80 / 80
pyhealth/models/bitenet.py 92.96% 251 / 270
pyhealth/models/daft.py 93.64% 221 / 236
pyhealth/models/udc.py 92.34% 229 / 248
pyhealth/tasks/__init__.py 97.26% 71 / 73
pyhealth/tasks/medmod_decompensation_mimic4.py 95.40% 83 / 87
pyhealth/tasks/seizure_detection_helsinki.py 100.00% 149 / 149
pyhealth/tasks/soz_localization_hup.py 98.96% 190 / 192

Workflow run · d6a3fe0

@Alhibb

Alhibb commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

/review

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

jhnwu3 commented Nov 18, 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 984162b

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

  1. In forward, the visit mask of the first feature isn't padded when the features have different visit counts. A flat sequence feature such as drugs can be longer than a nested visit feature, which is the schema your own tests use. Concatenation then pads the features, but overall_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 to max_t before combining them.
  2. With intra_visit_pooling="max", fully padded visits are filled with -1e9 and then count as valid, because the visit mask is derived from feat != 0. get_last_visit can then select a padding step when visit counts are mixed in a batch. Please build the visit mask from the code mask, for example code_mask.any(-1), and zero out empty visits after pooling.
  3. The mode argument is accepted but never used, although the docstring says it is. Either use it or remove it and fix the docstring.
  4. The description says (time, value) tuples are handled, but the code takes val[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.
  5. 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:

  • **kwargs is silently ignored. Consider removing it or documenting it.
  • A short example script would help users, but it isn't required.

Reviewed commit 984162b

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

Alhibb commented Nov 19, 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 55cb8a4

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

  1. The transformer temporal option calls self.temporal_encoder(fused_visits) with no padding mask. Padded visits are non-zero after feat_proj and LayerNorm, so they take part in attention. A patient's prediction then depends on how much padding the batch has. Please pass src_key_padding_mask=~overall_mask to 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.
  2. test_visit_mask_logic_assertion rebuilds the mask inside the test and asserts on that copy, so it never runs code in udc.py. Please change it to check the model's actual behavior. For example, check that the padded visits of a short patient don't change embed or logit. 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_loss currently includes padded visits. Averaging over valid visits only would be cleaner.
  • The description has a stray 81393 around the LaTeX formula, which you could fix.

Reviewed commit 55cb8a4

@Alhibb

Alhibb commented Nov 19, 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 38b66bf

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

  1. Transformer with an empty patient. With temporal_model="transformer", a patient whose features are all empty has overall_mask all False. src_key_padding_mask=~overall_mask then 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.
  2. Deeper nested inputs. The while feat.dim() > 3 loop accepts inputs with more than four dimensions, such as 5-D deep-nested input. _pool_intra_visit always 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.
  3. vq_indices documentation. The forward docstring says vq_indices is 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
@Alhibb

Alhibb commented Nov 19, 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 32ee6d0

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

  1. Docs don't match the code. pyhealth.models.UDC.rst says loss and vq_loss are returned "during training". In forward, vq_loss is always returned. loss and y_true are returned whenever the label key is in the inputs. Please reword the page to say that.
  2. (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 to val[1]. For a (time, value) tuple, val[1] is the value tensor itself, so it gets used as the visit or code mask. Please make forward ignore 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.
  • **kwargs in 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
@Alhibb

Alhibb commented Nov 19, 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 d6a3fe0

Comment thread pyhealth/models/udc.py
and not second.is_floating_point()
):
# (time, value)
value = second

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

Comment thread pyhealth/models/udc.py
dropout=dropout,
batch_first=True,
)
self.temporal_encoder = 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 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.

Comment thread tests/core/test_udc.py
self.assertEqual(idx_3d.shape, (2, 5, 2))
self.assertTrue(loss_3d.item() >= 0.0)

def test_straight_through_gradients(self):

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

@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 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: forward tells 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

@Alhibb

Alhibb commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

/merge

@github-actions
github-actions Bot merged commit 8f0c0b2 into sunlabuiuc:master Nov 19, 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.

2 participants