Repository navigation
Conversation
The evaluation loss was the plain mean of the per-batch mean losses, so a small last batch counted as much as a full one and the reported loss changed with the batch size (23 samples: 0.661 in one batch, 0.597 with batches of 22 and 1). Weight each batch's loss by its number of samples. Metrics were already computed once on the pooled predictions. Refs sunlabuiuc#859 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
|
/review |
Test CoverageTotal: 86.76% (48425 / 55814 lines)
|
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. Weighting the evaluation loss by batch size makes the reported loss independent of the eval batch size, and the before/after table and tests make the bug easy to see. It is close.
To get this merged:
- The
_batch_sizefallback (used when there is nopatient_id) can return the wrong count for PyHealth's own collated jagged and timeseries fields. These are flat concatenations rather than batch-first tensors, so the first tensor or tuple field may give the number of columns or the total record count instead of the number of samples. The loss weighting then goes wrong without any error. Please make the fallback reliable for these fields, or say clearly in the description and docstring which batches it supports. Please also add a test that exercises the fallback on such a batch.
Optional suggestions:
- Weighted loss values will change for every model on uneven batches. This could shift early-stopping or best-checkpoint decisions that monitor loss. A short note in the description would help.
- Coverage: the whole repository is at 86.74%, which meets the 60% bar.
pyhealth/trainer.pyis at 77.85%, slightly below the 80% guideline. The new code paths appear to be covered by your tests, so a few extra tests elsewhere in the file would bring it up.
This change touches Trainer, the shared base class that every model uses. evaluate and inference now return a different loss value, a sample-weighted mean instead of a mean of batch means. Training-loop evaluation and external callers consume that value. Because of this, a maintainer needs to review it and it can't be approved automatically.
Reviewed commit a52739e
… paths _batch_size reads patient_id / visit_id and otherwise weights batches equally: jagged and timeseries fields are flattened, so their first dimension is not the number of samples (AI review). Tests for inference with extra outputs and patient ids, inference without a label processor, and train with a checkpoint and a test loader bring trainer.py to 82%. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
|
/review |
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: human review
Thank you for this fix. Weighting the evaluation loss by batch size makes the reported loss independent of the evaluation batch size. The write-up is clear, and the tests show the problem and the fix with concrete numbers.
The diff looks correct and complete. The _batch_size helper falls back to 1 when there is no id list, so behaviour there is unchanged. The docstring for inference matches the code. Coverage meets the bar: pyhealth/trainer.py is at 82.11% (bar 80%) and the whole repository is at 86.76% (bar 60%).
This touches the core part of the codebase. Trainer.inference and Trainer.evaluate in pyhealth/trainer.py are shared by every model, and the loss value they return changes for any run whose last batch is smaller than the others. That can change early-stopping or best-checkpoint choices. A maintainer therefore has to make the final decision, so this can't be approved automatically. To me the change looks ready to merge.
Optional suggestions:
- For models whose loss is a token-level mean instead of a per-sample mean (for example
joint_seq_image), the weighted value is a sample-weighted average of batch means. It is not the exact per-sample mean. You could add a short note to the docstring saying so. - A blank line is missing between
_batch_sizeandmodel_metrics_kwargs. PEP 8 asks for two.
Reviewed commit 2ef18cd
Refs #859
Bug
Trainer.evaluate(andTrainer.inference) reportlossas the plain mean of the per-batch mean losses. A small last batch therefore counts as much as a full one, and the reported loss changes with the evaluation batch size. On 23 synthetic samples with an untrained RNN:The metrics are not affected: master already concatenates all batches and computes them once (the part of #859 that #1197 addressed). This is the remaining piece mentioned when #1197 was closed.
Fix
Weight each batch's mean loss by its number of samples, in both
inference(labelled models) and theevaluatebranch for models without a single label processor. A small private helper,_batch_size, reads the count from a per-sample id list (patient_id, elsevisit_id), which collation keeps as one entry per sample and which PyHealth samples carry. It never guesses from feature fields, because jagged and timeseries fields are flattened and their first dimension need not be the number of samples. Without an id list it returns 1, so batches are weighted equally, exactly as before.Effect on training: the reported validation loss changes slightly for any model whose last batch is smaller than the others. Runs that monitor
lossfor early stopping or best-checkpoint selection may pick a different epoch than before; the new value is the true per-sample mean.Testing
New
tests/core/test_trainer_eval_loss.py:_batch_sizereadspatient_id/visit_id, and returns 1 for batches without them (including a flattened jagged field);inferencewithadditional_outputsandreturn_patient_ids,inferencefor a model without a label processor, andtrainwithcheckpoint_pathand atest_dataloader, which also bringstrainer.pycoverage above 80%.The tests of other modules that use
Trainerpass (89 tests: early stopping, model mode, RNN_V2, APN, MeMe).tools/check_pr_rules.pypasses.Labeled
status: manualbecauseTraineris shared by every model.🤖 Generated with Claude Code
https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt