Skip to content

[BTY-72] feat(tpc): add MyBatchNorm1d, per-stay loss, mortality multi… - #1699

Merged
github-actions[bot] merged 3 commits into
sunlabuiuc:masterfrom
tkumar007:feat/tpc-paper-options-multitask
Nov 29, 2026
Merged

github-actions[bot] merged 3 commits into
sunlabuiuc:masterfrom
tkumar007:feat/tpc-paper-options-multitask

Conversation

@tkumar007

Copy link
Copy Markdown
Contributor

Contributor Information

  • Contributors: Tamjit Kumar (tkumar70@gatech.edu), Yi Wang (ywang4715@gatech.edu)
  • Affiliation / NetIDs: Georgia Tech (tkumar70, ywang4715)

Contribution Type

Model Enhancement (pyhealth.models.TPC) — [BTY-72]

Description

Follow-up to #1428, contributing the requested paper-level options on top of the merged TPC model (#1412) in a focused, backward-compatible PR:

  1. MyBatchNorm1d (batchnorm="mybatchnorm"): Adds MyBatchNorm1d mirroring the official TPC repository (EmmaRocheteau/TPC-LoS-prediction, models/tpc_model.py, MIT License notice updated at the top of pyhealth/models/tpc.py), normalizing over batch statistics during eval() while freezing running statistics updates (batchnorm="default" and batchnorm="none" also supported).
  2. Per-stay loss averaging (per_stay_loss, loss_reduction="per_stay", mask_key, min_time): Implements Equation (6) of Rocheteau et al. (ACM CHIL 2021) — averaging per-hour errors within each stay first (excluding padded steps and optional warmup hours < min_time) and then averaging equally across valid stays in the batch.
  3. Mortality multitask head (mortality_key, mortality_loss_weight, forward_mortality_sequence): Adds the parallel two-layer pointwise binary mortality prediction head and weighted multitask BCE objective (loss = los_loss + mortality_loss_weight * mortality_loss, default weight 100.0 per Appendix C of the paper), covering the mortality prediction component of [BTY-72].
  4. Weight-sharing and no-skip ablations (share_weights, use_skip):
    • share_weights=True: shares one (C -> Y) temporal convolution kernel across all R features in each TPCLayer (full-TPC temporal weight sharing; note that the official repository's TempWeightShare script pairs share_weights=True with a temporal-only architecture).
    • use_skip=False: disables raw-input and intermediate pointwise skip connections (TPC (no skip) in Table 3 of the paper, matching temp_pointwise_no_skip in models/tpc_model.py).

Backward Compatibility: No breaking changes. All new parameters are optional keyword arguments whose defaults preserve the existing #1412 TPC and TPCLayer behavior. No core classes or pyhealth/models/__init__.py exports are modified.

Paper & Reference Code

  • Paper: Emma Rocheteau, Pietro Liò, & Stephanie Hyland, Temporal Pointwise Convolutional Networks for Length of Stay Prediction in the Intensive Care Unit, ACM CHIL 2021 (DOI, arXiv:2007.09483)
  • Official Implementation: EmmaRocheteau/TPC-LoS-prediction (MIT License)

Files to Review

  • pyhealth/models/tpc.py — MyBatchNorm1d, per_stay_loss, and optional batchnorm, share_weights, use_skip, loss_reduction/mask_key/min_time, and mortality_key/mortality_loss_weight extensions on TPCLayer and TPC
  • tests/core/test_tpc.py — Unit tests in TestTPCPaperOptions covering all new options, edge cases, causality, and gradient flow on small synthetic data
  • docs/api/models/pyhealth.models.tpc.rst — Updated API documentation for MyBatchNorm1d, per_stay_loss, and the new TPC options

Verification

  • pytest tests/core/test_tpc.py -v: 45 passed (20 subtests passed)
  • Coverage on pyhealth/models/tpc.py: 99% (425 / 428 statements)
  • python -m doctest pyhealth/models/tpc.py: passed
  • python tools/check_pr_rules.py --base upstream/master --head HEAD: passed (0 ruff violations, >>> doctests on all public classes/functions)

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

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 88.18% (57187 / 64853 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 91 / 91
pyhealth/datasets/nhanes.py 96.99% 290 / 299
pyhealth/metrics/motionage.py 98.96% 95 / 96
pyhealth/models/__init__.py 100.00% 120 / 120
pyhealth/models/califorest.py 91.97% 126 / 137
pyhealth/models/ebcl.py 100.00% 93 / 93
pyhealth/models/motionage.py 99.22% 128 / 129
pyhealth/models/tpc.py 99.29% 422 / 425
pyhealth/tasks/__init__.py 98.55% 136 / 138
pyhealth/tasks/nhanes_mortality_prediction.py 96.67% 87 / 90

Workflow run · 65f3075

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 29, 2026
@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.

Previous review

Reviewed commit cfa79b5

Comment thread pyhealth/models/tpc.py Resolved
Comment thread docs/api/models/pyhealth.models.tpc.rst Resolved
Comment thread pyhealth/models/tpc.py Resolved

@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 this contribution. It adds MyBatchNorm1d, Eq. 6 per-stay loss, a mortality multitask head, and the weight-sharing and no-skip ablations to TPC, with defaults unchanged. Coverage is strong: 99.3% on tpc.py and 88% for the repository, both above the bar. The change is close, but two blocking problems remain.

To get this merged:

  1. The docs claim eval-mode predictions are strictly causal (docs rst, around line 45). With batchnorm="mybatchnorm", eval statistics are pooled over the batch and time axes. A prediction at hour t therefore depends on later hours, so the claim is wrong for that option. Please state this exception in the docs and in the TPC docstring. Optionally add a test showing the behaviour. The existing causality test only covers share_weights and use_skip.
  2. The min_time fallback in _resolve_sequence_mask is decided across the whole batch. If at least one stay has post-warmup steps, stays whose valid steps are all inside the warmup get zero weight. If none do, the warmup hours are kept for every stay. A stay's loss therefore depends on which stays share its batch. This is not described in the docs and is untested. Please either make the behaviour per-stay and consistent, or document it clearly, and add a test with a mixed batch.

Optional suggestions:

  • torch.nn.modules.batchnorm._BatchNorm is a private torch import. It works, but it may change between torch versions, so consider noting this in a comment.
  • The docs say the loss uses Eq. 6 warmup. Spelling out the fallback there would help users.

Reviewed commit cfa79b5

Comment thread pyhealth/models/tpc.py Resolved
Comment thread pyhealth/models/tpc.py Resolved
Comment thread docs/api/models/pyhealth.models.tpc.rst Resolved
@tkumar007

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 8f23e87

Comment thread pyhealth/models/tpc.py Resolved
Comment thread pyhealth/models/tpc.py Resolved

@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 this follow-up to #1412. It adds MyBatchNorm1d, per-stay Eq. (6) loss averaging, a mortality multitask head, and the weight-sharing and no-skip ablations. Defaults keep the existing behavior, the tests are thorough, and the docs match the code. Coverage of pyhealth/models/tpc.py is about 99% against the 80% bar, and the whole repository is at 88%, above the 60% bar. The change touches only TPC, its tests and its docs, so I don't see it affecting the core part of the codebase.

To get this merged:

  • Per-hour targets can't reach the per-stay path through a dataset. loss_reduction="per_stay" with mask_key and min_time only takes the sequence branch when y_true has shape (batch, time) or (batch, time, 1).
    • TPC.__init__ requires the label processor to be in regression mode, which gives one scalar per stay. A normal dataset, DataLoader and Trainer flow therefore always falls into the scalar branch.
    • The tests only reach the sequence branch by overwriting batch["los"] by hand.
    • Please either (a) allow a per-hour label schema, for example a tensor label processor for the LoS key when loss_reduction="per_stay", and add a test that goes from dataset to model to loss without patching the batch, or (b) state clearly in the description and docs that sequence targets must be supplied by the caller, and that per_stay_loss is meant to be used directly or with custom batches.
    • In the scalar fallback, mask_key and min_time have no effect. Please say so in the docs too.

Optional suggestions:

  • MyBatchNorm1d with track_running_stats=False can fail in eval() when batch * time == 1, because there are no running statistics to fall back on. A guard or a note in the docstring would help.
  • A short README or example showing how to build a per-hour label dataset would make the new options easier to use.

Reviewed commit 8f23e87

Comment thread pyhealth/models/tpc.py Resolved
Comment thread pyhealth/models/tpc.py Resolved
@tkumar007

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 65f3075

Comment thread pyhealth/models/tpc.py
official code accepts one size per layer).
* No mortality head or multitask loss, and no sequence-length mask in
the loss because windows have a fixed length.
Optional extensions beyond the scalar baseline:

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] Removed caveats from the official-implementation note

The 'Differences from the official implementation' list was deleted from the TPC class note. Three caveats still hold and are no longer documented: forward() predicts only the last hour, temporal and pointwise sizes are the same in every layer, and the default loss has no sequence-length mask. Restore those bullets in the note, or move them to the forward() docstring, so users comparing with the official code still see them.

Comment thread pyhealth/models/tpc.py
bce_elem = F.binary_cross_entropy_with_logits(
mort_logit, mort_true, reduction="none"
)
mort_loss = _reduce_per_stay(bce_elem, eval_mask)

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] Mortality BCE also uses min_time and mask, which is undocumented

In per_stay mode the mortality loss is reduced with the same eval_mask as the LoS loss, so warmup hours (index < min_time) and padded steps are also dropped from the mortality BCE. The min_time and mask_key docs only describe the LoS loss. Add a sentence saying the mortality BCE uses the same per-stay mask and warmup exclusion, or exclude the mortality loss from warmup.

Comment thread pyhealth/models/tpc.py
else:
if (
mortality_key not in self.label_keys
and mortality_key not in self.feature_keys

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] mortality_key may name an input feature without a binary check

The validation accepts mortality_key when it is only an input feature, and the binary check at the label-processor branch only runs for label keys. A non-binary feature used as the target then goes into binary_cross_entropy_with_logits without error. Require mortality_key to be in label_keys with a binary processor, or add a binary check and a test for the feature-key path.

@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 this follow-up to the TPC model. It adds MyBatchNorm1d, Eq. 6 per-stay loss averaging, an optional mortality multitask head, and the share_weights and use_skip ablations. All of the new options default to the earlier behavior, and the paper and reference code are cited.

This looks ready to merge. The change stays inside pyhealth/models/tpc.py, its tests and its docs page. The new TensorProcessor import is used only for an isinstance check. Coverage for tpc.py is 99.3%, above the 80% bar for a changed file. Total repository coverage is 88.2%, above the 60% bar. The docs match the code, including the note that mybatchnorm breaks strict eval-mode causality.

Optional suggestions:

  • The old "Differences from the official implementation" note is gone. Some of its caveats still hold, so you could keep them: forward scores only the last hour by default, layer sizes are the same in every layer, and the default loss has no sequence mask.
  • Document that the mortality BCE also uses mask_key and min_time when loss_reduction="per_stay".
  • mortality_key may name an input feature, and that case gets no binary-label check. Consider validating it.
  • mask_key and min_time are silently ignored with loss_reduction="mean". A warning or an error would make that clearer.
  • With mortality_key set, model.mode may be None, so get_metrics_fn(model.mode) could fail. A short note in the docs, or a fix, would help.
  • A short example script showing the new options would help users.

Reviewed commit 65f3075

@tkumar007

Copy link
Copy Markdown
Contributor Author

/merge

@github-actions
github-actions Bot merged commit 1393edd into sunlabuiuc:master Nov 29, 2026
2 checks passed
@tkumar007
tkumar007 deleted the feat/tpc-paper-options-multitask branch November 29, 2026 18:44
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