Skip to content

Fix under-coverage in CovariateLabel's finite-sample correction - #1223

Open
lehendo wants to merge 6 commits into
sunlabuiuc:masterfrom
lehendo:covariateshiftfix
Open

lehendo wants to merge 6 commits into
sunlabuiuc:masterfrom
lehendo:covariateshiftfix

Conversation

@lehendo

@lehendo lehendo commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

test_forward_with_embeddings_uses_per_point_weight failed on CI (0.3241... == 0.3241...). Root cause: a test point's KDE-derived weight is always a small fraction of total calibration weight, so whether it shifts the selected quantile index is essentially a coin flip depending on random model init

_query_weighted_quantile added the test point's reserved weight only to
the normalizing denominator, never inserting it as an actual point in
the weighted empirical distribution. Verified against Corollary 1 of
Tibshirani, Barber, Candes, and Ramdas, "Conformal Prediction Under
Covariate Shift" (NeurIPS 2019, arXiv:1904.06019): before this fix, the
"corrected" quantile under-covered relative to target (0.81-0.89 vs a
0.90 target in Monte Carlo simulation) -- worse than no correction at
all. Fix: prepend the reserved weight to the cumulative sum before
dividing, matching the paper's construction exactly (confirmed via a
hand-computed example and against a from-scratch reference
implementation of the paper's formula).

Also fix a related gap: calibrate() computed a single threshold using
the *mean* calibration likelihood ratio as a stand-in for a test
point's own w(x), but Corollary 1 defines the threshold per test point
using that point's actual weight. forward() now accepts an optional
test_embeddings argument to compute the real per-point threshold
matching the paper exactly; omitting it keeps the old single-threshold
behavior as a documented, explicitly-warned approximation, since not
every wrapped model exposes an embedding extraction path.

18 tests pass (4 new), including a deterministic regression test
against a hand-computed Corollary 1 example and new coverage of the
forward() per-point/fallback paths.
@lehendo lehendo changed the title Fix Covariate Shift CP Fix Fix under-coverage in CovariateLabel's finite-sample correction Aug 31, 2026
CI failed on test_forward_with_embeddings_uses_per_point_weight
(AssertionError: 0.3241... == 0.3241...). Root-caused this to a real
design flaw, not just missing randomness control: a test point's
likelihood-ratio weight is drawn from the same KDE-derived distribution
as the calibration weights, so by construction it can never be more than
a small fraction of total calibration weight mass. Whether prepending it
shifts _query_weighted_quantile's selected order-statistic index depends
entirely on where the alpha-quantile boundary happens to fall relative to
the (data-dependent, effectively random given the model's unseeded init)
distribution of calibration weights along the sorted-score axis.

Confirmed this wasn't just 'rare bad luck': reproduced the exact failure
deterministically for multiple fixed seeds, and directly inspected the
internals (total_weight, cum_weights) showing the two test points'
weights (0.05 vs 10.0) simply didn't straddle a boundary for that data --
an inherent fragility in comparing *output values* for two randomly-KDE
-derived weights, not a bug in the underlying Corollary-1 implementation.

Replaced the flaky output-comparison with two more precise checks:
1. Spy on _query_weighted_quantile during a real forward() call and
   verify it's invoked once per test point with that exact point's own
   weight -- directly verifies the claim ('forward uses per-point
   weight') without depending on the resulting threshold *values*
   differing.
2. A new, fully hand-computed unit test proving test_weight does change
   _query_weighted_quantile's result in general (by forcing the
   documented -inf fallback with a deliberately large weight), isolated
   from any KDE/model randomness.

Also seeded _build_pointwise_setup()'s model init for reproducibility.
@lehendo lehendo changed the title Fix Fix under-coverage in CovariateLabel's finite-sample correction Fix under-coverage in CovariateLabel's finite-sample correction Aug 31, 2026
@fbonc

fbonc commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

The threshold should be calculated separately for each test patient, using that patient's embedding. However, Trainer.inference() only passes the data batch to the model, not test_embeddings. Since the example uses Trainer.inference(), it always falls back to one shared, approximate threshold for every patient.

I think put the embeddings in each batch or compute them inside CovariateLabel.forward(). Also raise an error when the number of embeddings does not match the batch size instead of ignoring extras.

@DarylOkeke

DarylOkeke commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Another boundary issue -- Corollary 1 includes scores equal to the threshold. Since larger scores should be included, this should use >= instead of >.. Tied scores at the threshold are excluded and can under-cover. Switch it to >= and add a tie test

Two independent bugs, both flagged in review:

1. forward() included a class only if conformity_score > threshold
   (strict). _query_weighted_quantile defines the threshold as the
   smallest score whose cumulative weight reaches alpha, so that score's
   own mass is part of what clears the target -- excluding it with a
   strict comparison silently under-covers whenever a real score lands
   on a calibration tie. scores.py's own all_class_conformity_scores
   docstring already documents ">=" as the intended convention for this
   sign convention; forward() just didn't follow it. Fixed to ">=", and
   added a length-mismatch check for test_embeddings (previously extra
   rows were silently ignored rather than raising).

2. The per-test-point thresholding path (forward(test_embeddings=...),
   the actual Corollary 1 construction from Tibshirani et al. 2019) has
   existed since the previous commit on this branch, but
   examples/conformal_eeg/tuev_covariate_shift_conformal.py evaluated it
   via Trainer(model=cov_predictor).inference(test_loader, ...), which
   calls model(**batch) with no way to also supply a per-batch
   test_embeddings slice. So the example -- meant to demonstrate and
   validate this exact PR's fix -- silently only ever exercised the
   approximate mean-weight fallback, never the real per-point guarantee.
   Replaced with a manual inference loop that slices test_embeddings in
   the same fixed order test_loader yields batches in (mirroring
   Trainer.inference()'s own logic) and passes each batch's slice
   through.

Added a regression test for (1) that directly forces a conformity score
equal to the threshold and checks it's included.
@lehendo

lehendo commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

@fbonc @DarylOkeke , fixed. pls review again.

@DarylOkeke

Copy link
Copy Markdown
Contributor

The standalone example uses the new per-patient threshold path, but the main class example and in-file demo still use the old inference path. That gives everyone one approximate threshold, so those examples should use the per-patient path too.

@fbonc

fbonc commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

@lehendo what he said

@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 69.11% (17769 / 25711 lines)

Modified file Coverage Lines
pyhealth/autoimprove/__init__.py 100.00% 6 / 6
pyhealth/autoimprove/evaluate.py 92.07% 151 / 164
pyhealth/autoimprove/improver.py 95.63% 372 / 389
pyhealth/autoimprove/llm.py 90.62% 29 / 32
pyhealth/autoimprove/proposers.py 93.91% 108 / 115
pyhealth/autoimprove/space.py 95.31% 122 / 128
pyhealth/calib/predictionset/covariate/covariate_label.py 50.00% 114 / 228
pyhealth/datasets/base_dataset.py 90.82% 465 / 512
pyhealth/datasets/omop.py 100.00% 18 / 18
pyhealth/metrics/calibration.py 65.00% 52 / 80
pyhealth/metrics/multiclass.py 25.00% 26 / 104
pyhealth/models/__init__.py 100.00% 52 / 52
pyhealth/models/micron.py 83.23% 129 / 155
pyhealth/models/survival_mdn.py 93.83% 213 / 227
pyhealth/processors/deep_nested_sequence_processor.py 91.37% 180 / 197
pyhealth/processors/nested_sequence_processor.py 92.94% 158 / 170
pyhealth/processors/sequence_processor.py 95.77% 68 / 71
pyhealth/processors/stagenet_processor.py 84.08% 169 / 201

Workflow run · 483f59c

_query_weighted_quantile used `p_test >= alpha` and
searchsorted(side="left"), which picks one rank too low whenever the
cumulative weight hits alpha exactly. With equal weights that happens
whenever alpha*(n+1) is an integer (n=19, alpha=0.1: coverage 0.95
instead of 0.90). Corollary 1 of Tibshirani et al. (2019) keeps that
score, so use `p_test > alpha` and side="right". With equal weights the
threshold now equals standard split conformal's (BaseConformal/LABEL),
which a new test checks for n in {9, 19, 20, 49, 99, 100}.

The class docstring example and the in-file demo evaluate through
Trainer.inference(), which cannot pass test_embeddings. Say plainly that
this uses the mean-weight fallback and warns, and point to the example
script for the per-test-point path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015ntMLEmFsQEQJKTmPGGw4T
@solarsys

Copy link
Copy Markdown
Collaborator

Thanks @lehendo, the main fix is right. Master added the test point's reserved mass only to the denominator, so it picked one rank too high and under-covered (for example 0.857 instead of 0.905 with 20 calibration points). Counting that mass in the cumulative sum, as in Corollary 1 of Tibshirani et al. (2019), fixes it. Thanks also to @fbonc and @DarylOkeke for the reviews.

I pushed one small commit on top so we can merge this:

  1. Exact tie handling in the quantile. The PR used p_test >= alpha and searchsorted(..., side="left"). That picks one rank too low whenever the cumulative weight lands exactly on alpha. With equal weights this happens whenever alpha*(n+1) is a whole number: with n=19 and alpha=0.1, coverage was 0.95 instead of 0.90. The paper keeps that score, so it is now p_test > alpha and side="right". With equal weights the threshold now matches standard split conformal (BaseConformal/LABEL) exactly. A new test checks this for several n. In a simulation, coverage matched theory: 0.90 at n=19, 0.905 at n=20, 0.90 at n=99.
  2. The class docstring example, as @DarylOkeke pointed out. It evaluates through Trainer.inference(), which can't pass test_embeddings. That path uses the single mean-weight threshold and warns. The example and the in-file demo now say this plainly and point to examples/conformal_eeg/tuev_covariate_shift_conformal.py for the per-test-point path.

Possible follow-up, not needed for this PR: compute the embeddings inside forward() with model(..., embed=True), as ClusterLabel and NeighborhoodLabel already do. Then Trainer.inference() would get per-point thresholds directly, with no extra argument, no custom loop and no warning.

All 21 covariate-label tests and the other calibration tests pass, and so do the contribution-rules check and ruff. I'll merge it once CI and the review pass.

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

AI review: findings

The PR changes CovariateLabel (pyhealth/calib/predictionset/covariate/covariate_label.py) in three ways. First, the weighted quantile now inserts the test point's reserved mass as an actual point (Corollary 1), uses side="right", and uses a ">=" tie rule in forward(). Second, forward() gains an optional test_embeddings argument that computes a per-test-point threshold from that point's own KDE weight. Third, it emits a one-time UserWarning when that argument is omitted. The base classes (SetPredictor, BaseConformal) are unchanged. The new unit tests cover split-conformal equivalence, the tie rule and the per-point call pattern, and the example is updated to run the per-point path. Blocking problems: (1) the PR description only explains a flaky CI test, but the diff changes CovariateLabel's default thresholds and sets for every existing user (covariate_label.py:248), and none of that is described; (2) the per-point test in tests/core/test_covariate_label.py:472 only checks the helper's call arguments, so a regression that ignored the per-point thresholds in y_predset would still pass; (3) the class docstring's main workflow (covariate_label.py:356) evaluates through Trainer.inference, which cannot pass test_embeddings, so the advertised guarantee does not hold on the documented path; (4) if a user passes KDEs in init and custom cal_weights to calibrate(), forward(test_embeddings=...) silently mixes KDE test weights with custom calibration weights (covariate_label.py:644). Non-blocking: the new warning tells custom-weight users to pass test_embeddings, which raises for them, and the new _query_weighted_quantile duplicates a same-named helper in base_conformal with a different tie rule. No existing component in the repo implements this covariate-shift correction, so the change is not redundant. Overall risk is medium: the core math checks out on reading, but default outputs change without being described and the new per-point path is not tested end to end.

Findings outside the diff

  • [medium] Documented main workflow cannot reach the per-point threshold the docs promise pyhealth/calib/predictionset/covariate/covariate_label.py:356
    The class docstring example (and the main block near line 786) evaluates with Trainer(...).inference(), which calls model(**batch) and cannot pass test_embeddings. That path always uses the mean-weight fallback, so the example does not produce the Corollary 1 guarantee the new notes in docs/api/calib.rst describe. examples/cxr/covid19cxr_conformal.py:190 uses the same path and is not updated. Fix: either give Trainer/inference a supported way to pass per-batch extra inputs, or change the docstring and the covid example to use a per-batch loop like the one in examples/conformal_eeg/tuev_covariate_shift_conformal.py, and say plainly that Trainer.inference gives the approximation.
  • [low] Second _query_weighted_quantile with the same name and a different tie rule pyhealth/calib/predictionset/covariate/covariate_label.py:178
    pyhealth/calib/predictionset/base_conformal/init.py:71 defines a _query_weighted_quantile with no test-mass term and side="left", and NeighborhoodLabel still imports it. This new function is an extension of that helper rather than a pure duplicate, so it is not redundant. However, two functions with the same name in sibling modules now disagree on the tie rule. Fix: add a test_weight argument to the base helper and import it here, or rename this one so the two are clearly distinct.

Reviewed commit 483f59c

# side="right" keeps a score whose mass below it equals alpha exactly
# (the paper's quantile); side="left" would be one rank too
# conservative whenever alpha*(n+1) is an integer.
idx = np.searchsorted(cum_weights, alpha, side="right")

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] Default threshold and set semantics change for all CovariateLabel users; PR description does not say so

The fix changes the default fixed-threshold path, which every existing CovariateLabel user gets. It adds the reserved test mass to the cumulative weights, switches searchsorted to side="right", and changes forward() from ">" to ">=". Together these shift thresholds and prediction-set sizes, so previously reported coverage and set sizes will not reproduce. The PR description only explains a flaky CI test and mentions none of this. Fix: describe the behavior change in the PR description and changelog, and add a regression test pinning the new default-path output for a fixed seed (for example, a small fixed-weight example whose y_predset differs between the old and new code).

N, K = conformity_scores.shape

if test_embeddings is not None:
if self.kde_test is None or self.kde_cal is None:

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] Pre-fitted KDEs combined with custom cal_weights silently produce wrong per-point thresholds

calibrate(cal_weights=...) stores custom weights as the calibration likelihood ratios but leaves self.kde_test/self.kde_cal in place if they were passed to init. forward(test_embeddings=...) then scores test points with those KDEs and compares them against the custom calibration weights, which are on a different scale. The guard only checks for missing KDEs, and its message assumes that custom weights mean no KDEs, so this case is not caught. Fix: record in calibrate() whether the stored weights came from the KDEs (for example, a flag set in the KDE branch), and raise in forward() when the per-point path is requested without KDE-derived weights. Add a test for that combination.

any("approximation of Corollary 1" in str(w.message) for w in caught)
)

def test_forward_with_embeddings_uses_per_point_weight(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.

[medium] The per-point threshold feature is only tested through call arguments, not through y_predset

test_forward_with_embeddings_uses_per_point_weight spies on _query_weighted_quantile and checks that it is called once per test point with the right weight. No test checks that y_predset is computed from those per-point thresholds. A regression that computed the thresholds and then used self.t (or dropped them) would still pass. Fix: add a test with a hand-computed expectation where the per-point threshold changes at least one prediction, and assert on y_predset. The fake KDE in _build_pointwise_setup (line 392) also takes a median over its input batch, so it is not a density function. Make it a fixed function of each point so the per-point weights do not depend on batch composition.

)
else:
if not self._warned_fixed_threshold:
warnings.warn(

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] Fallback warning gives advice that raises for custom-weight users

The warning says to pass test_embeddings to get the paper's guarantee. When calibrate() was given only cal_weights, forward(test_embeddings=...) raises ValueError at line 645, and this warning fires for those users with no way to avoid it. Fix: when no KDEs are available, word the warning to say that the guarantee cannot be obtained with these weights, or skip the warning in that case.

@github-actions github-actions Bot added status: manual Pending maintainer's review and removed status: automatic The PR will go through automatic review process. labels Oct 25, 2026

@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: human review
decision: not available

Haiku found that this change needs a human review: The change alters the output of a public class: thresholds and y_predset for every CovariateLabel user change (">=" tie rule, side="right", reserved-mass insertion). It also adds a forward() parameter and a new UserWarning. Other code and examples depend on CovariateLabel's output, so this is an API contract change, not a self-contained component change. The base classes are not modified.

Reviewed commit 483f59c

@solarsys solarsys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @lehendo, and thanks @fbonc and @DarylOkeke for the careful reviews. Everything raised has been addressed:

  • the per-point path;
  • >= at the threshold;
  • the exact-tie quantile;
  • the docstring and demo note about Trainer.inference.

I re-checked the quantile against Corollary 1, and with equal weights it gives exactly the split-conformal threshold. Two small follow-ups would be welcome in a new PR:

  • an end-to-end y_predset test for the per-point path;
  • an error when pre-fitted KDEs are combined with custom cal_weights.

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.

5 participants