Skip to content

test: add Top-H monotonicity, exponential decay, and validation checks - #2

Merged
Andreas-Hum merged 1 commit into
Andreas-Hum:fix-toph-criterionfrom
Spartan2588:toph-regression-tests
Nov 8, 2026
Merged

Andreas-Hum merged 1 commit into
Andreas-Hum:fix-toph-criterionfrom
Spartan2588:toph-regression-tests

Conversation

@Spartan2588

@Spartan2588 Spartan2588 commented Nov 4, 2026 •

Copy link
Copy Markdown

🤗 Transformers CI

Description

This is an independent test-only contribution complementing the Top-H entropy criterion fix for Issue huggingface#50228 on branch ix-toph-criterion.

Context & Problem Solved by the Fix

Top-H sampling (arXiv:2509.02510) dynamically bounds the retained prefix distribution $q_k$ by retaining the largest sorted token prefix satisfying:
\mathcal{H}(q_k) \le \alpha \cdot \mathcal{H}(p)
where $q_k = p_{1:k} / \sum_{i=1}^k p_i$ is the renormalized prefix distribution, and \mathcal{H}(p) is the Shannon entropy over the full next-token distribution.

The original implementation had two critical flaws:

  1. It bounded the unnormalized partial entropy $C_k = -\sum_{i=1}^k p_i \ln p_i$ rather than the renormalized prefix entropy \mathcal{H}(q_k) = \frac{C_k}{P_k} + \ln P_k, causing severe over-retention on flat distributions (e.g., retaining 20 tokens instead of 4 for $N=50, \alpha=0.4$; 8 instead of 4 for $N=16, \alpha=0.5$).
  2. It computed the entropy budget $\tau$ from only the top 100 logits rather than the full distribution, causing under-retention on long-tailed distributions (e.g., retaining 8 tokens instead of 25 for Zipf).

Coverage Added

Building directly on the loop-based independent reference helper op_h_reference_num_kept, this PR adds regression coverage covering:

  1. Mathematical Boundaries:
    • $N=16, \alpha=0.5$ boundary where unnormalized entropy kept 8 tokens, while the true rule keeps 4 ($16^{0.5}$).
    • Small discrete vocabularies ($N=3$) and highly peaked dominant-logit distributions.
    • Long-tail distributions (exponential decay $\lambda=0.1$, moderate Zipf).
    • Near-zero budgets ($\alpha=0.05$) and masked $-\infty$ logits.
  2. Candidate Cap Enforcement:
    • Validates that the op_n = 100 cap is strictly observed at $\alpha=1.0$ across vocab sizes $N \in {50, 100, 200, 500}$.
  3. Monotonicity:
    • Verifies that relaxing the budget ($\alpha_1 < \alpha_2$) monotonically guarantees $k(\alpha_1) \le k(\alpha_2)$ across uniform, exponential, Zipf, and peaked distributions.
  4. Invariance Properties:
    • Constant logit translation invariance ($s + c$).
    • Vocabulary permutation invariance ($\pi(s)$).
    • Deterministic repeatability across invocations.
  5. Numerical Stability & Mixed Precision:
    • Validates absence of NaNs and output dtype preservation for loat32, loat64, loat16, and �float16.
    • Stability under extreme logit offsets ($\pm 1000.0$) and near-equal values.
  6. Batch & API Invariants:
    • Row-level independence in heterogeneous batches (peaked, uniform, skewed, masked).
    • In-place tensor immutability, customizable ilter_value, constructor input validation, and LogitsProcessorList composition.

Test Results

  • python -m pytest tests/generation/test_logits_process.py -k top_h: 18 passed in 0.97s.
  • python -m pytest tests/generation/test_logits_process.py: 66 passed in 67.86s.
  • Code style: formatted and linted with
    uff (zero violations).

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Thank you for your contribution 🤗!

CI Security Gate — waiting for maintainer approval

CI is approved automatically only for authors who already have a contribution merged in this repository. A maintainer will review this PR and approve CI to run on it.

@Spartan2588

Copy link
Copy Markdown
Author

Thanks @Andreas-Hum! Following your layout, I expanded the test suite directly around the shared reference helper op_h_reference_num_kept:

  1. Expanded est_top_h_dist_warper_matches_reference: Added parameterized cases for $N=16, \alpha=0.5$ (which cleanly catches the unnormalized entropy bug: keeps 4 vs buggy 8), the 200-token cap check at $\alpha=1.0$, small vocabulary ($N=3$), masked $-\infty$ logits, exponential decay, and near-zero budget ($\alpha=0.05$).
  2. Dedicated Invariant Tests:
    • est_top_h_monotonicity: Verifies $k(\alpha_1) \le k(\alpha_2)$ across a fine grid of $\alpha \in [0.05, 1.0]$ over multiple distribution families.
    • est_top_h_candidate_cap: Confirms $top_n=100$ cap enforcement across $N \in {50, 100, 200, 500}$.
    • est_top_h_shift_and_permutation_invariance: Translation ($s + c$), token order permutation, and repeatability.
    • est_top_h_tied_logits: Top-k set integrity when multiple equal-probability tokens cluster.
    • est_top_h_batch_independence: Heterogeneous batch row isolation.
    • est_top_h_numerical_stability: Multi-dtype execution (p32, p64, p16, �f16), extreme magnitude ranges ($\pm 1000$), and output dtype preservation.
    • est_top_h_input_integrity_and_validation: In-place immutability, ilter_value, constructor checks, and LogitsProcessorList integration.

All 18 Top-H tests pass in ~0.97s, the full est_logits_process.py suite passes (66 passed), and
uff checks pass cleanly with zero violations.

@Andreas-Hum Andreas-Hum left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks for putting this together, there are some really useful checks in here! I ran it on CPU (Linux, Python 3.13, torch 2.15): all 66 tests pass with the fix, and 5 of the Top-H tests fail on the unfixed warper. ruff is clean.

I'd like to keep this PR focused, though, since everything here ends up in the upstream PR for a 3-line fix. A few points:

1. Exact ties on the threshold. Four cases put the last kept token exactly on H(q_k) = alpha * H(p), so whether they pass depends on float32 rounding, and they could flip on GPU:

  • uniform_16_boundary (alpha = 0.5): H(q_4) = log 4 = 0.5 * log 16, margin 0 on CPU. (That one was my suggestion in the issue, my bad.)
  • test_top_h_candidate_cap with N = 50 and N = 100 at alpha = 1: at alpha = 1 the last token is always a tie, since H(q_N) = H(p). Margins are 2e-7 and 0.
  • test_top_h_tied_logits, 25 equal logits at alpha = 0.5: 25 ** 0.5 = 5 exactly, and the 5th token is dropped by 4e-7. It only passes because the double-precision reference happens to round the same way.

Moving off the tie keeps the boundary check, e.g. alpha = 0.49 / 0.51 for N = 16 (keeps 3 and 4 tokens, about 0.03 nats of margin each way), and only checking the cap for N > 100.

2. Overlap with #1. #1 (opened earlier) already adds N = 16, the 200-token cap, masked -inf logits, peaked logits, batch independence, shift/permutation invariance and half precision, and the two PRs conflict in the case list. I'm planning to merge #1 first.

3. Weaker checks. test_top_h_numerical_stability uses an unseeded torch.randn and only checks for no NaNs and at least one kept token, and test_top_h_candidate_cap repeats the flat_200_cap case.

What I'd love to keep after rebasing onto the branch once #1 is in:

  • test_top_h_monotonicity: a larger alpha never keeps fewer tokens. Nothing else covers that.
  • The exponential_decay case: a second long-tailed shape, and it catches the bug.
  • The constructor validation and custom filter_value checks.

Could you trim it down to those, with the ties moved off the threshold? Happy to review again after that.

@Spartan2588
Spartan2588 force-pushed the toph-regression-tests branch from 2c7f057 to 7781c74 Compare November 4, 2026 17:01
@Spartan2588 Spartan2588 changed the title test: expand Top-H entropy warper regression coverage test: add Top-H monotonicity, exponential decay, and validation checks Nov 4, 2026
@Spartan2588

Copy link
Copy Markdown
Author

Thanks for the review and the clear guidance @Andreas-Hum! Completely agree with keeping this PR tightly focused and upstream-friendly.

I have updated the branch with the requested trimming:

  1. Moved ties off the threshold:

    • Removed $\alpha = 1.0$ and boundary points (=16, \alpha=0.5$; tied logits) where (q_k) = \alpha H(p)$ exactly.
    • In est_top_h_monotonicity, used a safe grid $\alpha \in [0.05, 0.15, 0.3, 0.45, 0.6, 0.75, 0.9]$ evaluated on uniform (=50$), exponential decay (=80$), Zipf (=500$), and seeded normal (=60$). None of the token counts land near exact float32 integer boundaries, ensuring stable passes across CPU and GPU.
  2. Removed overlap with PR Add Top-H edge-case tests using the shared reference #1:

  3. Kept only the three requested additions:

    • exponential_decay in est_top_h_dist_warper_matches_reference: a second long-tailed distribution ($\lambda = 0.1, N=150, \alpha=0.4$) with generous float32 margins that catches the unnormalized entropy bug.
    • ** est_top_h_monotonicity**: verifies that a larger $\alpha$ never retains fewer tokens.
    • ** est_top_h_validation_and_filter_value**: verifies constructor input validation for $\alpha \notin (0, 1]$, custom ilter_value application, input immutability, and LogitsProcessorList wrapping.

All 6 Top-H tests pass cleanly locally (pytest -k top_h), and
uff format /
uff check are clean. Ready for your review!

@Andreas-Hum Andreas-Hum left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks, this looks great! I reran it on CPU: all 54 tests pass with the fix, and exponential_decay fails on the unfixed warper alongside the two original cases, so it catches the bug. Monotonicity and validation pass on both, as expected for properties the old rule also had. I also checked the gap to the threshold for every alpha and distribution in the monotonicity grid, and the smallest is 1.5e-3, so none of them are near a rounding tie. ruff is clean.

Plan from here:

  1. #1 goes in first, since it was opened earlier. I've left a few small suggestions there, and I'm waiting for those.
  2. Once #1 is merged, this PR will have a small conflict, because both add cases to the same parameterized.expand list. You don't need to do anything: I'll resolve it when merging (keeping both sets of cases) and rerun the tests.
  3. Then I'll open the upstream PR for huggingface#50228 from this branch, and both of you will show up as commit authors.

If #1 stalls for a long time, I'll merge this one first instead, so it doesn't sit waiting.

@Andreas-Hum
Andreas-Hum merged commit f1f1050 into Andreas-Hum:fix-toph-criterion Nov 8, 2026
9 checks passed
@Andreas-Hum

Copy link
Copy Markdown
Owner

Merged, thanks @Spartan2588! #1 is merged as well, so both sets of tests are now on fix-toph-criterion (all 62 tests in test_logits_process.py pass with the fix, and 8 of the Top-H tests fail without it). Your commit is kept as-is, so you'll be credited when it goes upstream.

@Spartan2588

Copy link
Copy Markdown
Author

Thanks again @Andreas-Hum for the detailed review and guidance throughout this contribution!

I really enjoyed working on the Top-H regression tests, especially understanding the entropy criterion and designing property-based checks for monotonicity and distribution behaviour.

I'd love to continue contributing to Transformers. If there are any open issues, regression-testing gaps, or smaller implementation tasks where I could help, I'd be very interested in taking them up.

Looking forward to contributing more!

@Andreas-Hum

Copy link
Copy Markdown
Owner

Thanks for the tests! They're now part of the upstream PR, huggingface#50471, and you're credited as co-author. I don't have anything else to hand out right now, but issues labelled "Good First Issue" are a good place to start.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants