Skip to content

Trainer.evaluate: weight the mean loss by batch size - #1628

Open
solarsys wants to merge 2 commits into
sunlabuiuc:masterfrom
solarsys:fix/trainer-loss-weighted-by-batch
Open

solarsys wants to merge 2 commits into
sunlabuiuc:masterfrom
solarsys:fix/trainer-loss-weighted-by-batch

Conversation

@solarsys

@solarsys solarsys commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #859

Bug

Trainer.evaluate (and Trainer.inference) report loss as 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:

eval batch size batches reported loss (master)
23 one batch 0.6614
8 8 + 8 + 7 0.6615
22 22 + 1 0.5974

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 the evaluate branch for models without a single label processor. A small private helper, _batch_size, reads the count from a per-sample id list (patient_id, else visit_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 loss for 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:

  • an RNN evaluated with batch sizes 23, 8 and 22 reports the same loss (to 5 places); on master the 22 + 1 split is off by 0.064;
  • a model without a label processor, batches of 3 and 1 with values 1, 1, 1, 10: loss 3.25 (the sample mean), where master gives 5.5;
  • _batch_size reads patient_id / visit_id, and returns 1 for batches without them (including a flattened jagged field);
  • inference with additional_outputs and return_patient_ids, inference for a model without a label processor, and train with checkpoint_path and a test_dataloader, which also brings trainer.py coverage above 80%.

The tests of other modules that use Trainer pass (89 tests: early stopping, model mode, RNN_V2, APN, MeMe). tools/check_pr_rules.py passes.

Labeled status: manual because Trainer is shared by every model.

🤖 Generated with Claude Code

https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt

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

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.76% (48425 / 55814 lines)

Modified file Coverage Lines
pyhealth/trainer.py 82.11% 234 / 285

Workflow run · 2ef18cd

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

@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: 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_size fallback (used when there is no patient_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.py is 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
@solarsys

Copy link
Copy Markdown
Collaborator 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.

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_size and model_metrics_kwargs. PEP 8 asks for two.

Reviewed commit 2ef18cd

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant