Repository navigation
test(version-compat): keep GRPO fake-run logits finite on CPU - #7247
Conversation
The GRPO fake-run test samples completions from a tiny untrained model on CPU. Such a model can emit non-finite logits, so torch.multinomial inside generate() intermittently raises "probability tensor contains either inf, nan or element < 0" -- a nondeterministic sampling failure, not a regression (the Trainer already fixes the seed, but CPU reduction order is not bit-reproducible). Add a forward hook that sanitizes the LM head logits to a finite bounded range before sampling, so the fake run reliably exercises the whole train loop; the test checks the loop runs, not the numerics.
There was a problem hiding this comment.
Code Review
This pull request introduces a _guard_finite_logits helper function to sanitize model logits during CPU training tests, preventing intermittent crashes in torch.multinomial due to non-finite values. The review feedback suggests simplifying the sanitization logic by removing redundant posinf and neginf arguments from torch.nan_to_num, as the subsequent .clamp() call already handles bounding these values.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
|
|
||
| def _finite_logits_hook(_module, _inputs, output): | ||
| logits = getattr(output, "logits", None) | ||
| if logits is None: | ||
| return output | ||
| output.logits = torch.nan_to_num( | ||
| logits, | ||
| nan = 0.0, |
There was a problem hiding this comment.
The posinf and neginf arguments in torch.nan_to_num are redundant because the subsequent .clamp(-30.0, 30.0) call will already clamp any extremely large or infinite values to the [-30.0, 30.0] range. Simplifying this to only handle nan makes the code cleaner and more maintainable.
def _finite_logits_hook(_module, _inputs, output):
logits = getattr(output, "logits", None)
if logits is None:
return output
output.logits = torch.nan_to_num(logits, nan=0.0).clamp(-30.0, 30.0)
return outputReferences
- Do not add redundant try-except blocks for type safety when input types are already guaranteed by early guards (e.g., checking for None) and type annotations.
There was a problem hiding this comment.
Good point, simplified in 000d107. Verified the two forms are identical for nan/inf/-inf/large inputs: torch.nan_to_num(logits).clamp(-30, 30) maps nan to 0 and the infinities to large finite values which clamp then bounds to [-30, 30], so the explicit posinf/neginf were redundant. Dropped them and kept a one-line comment.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 000d10740a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| model.for_training = lambda *a, **k: model.train() | ||
| if not hasattr(model, "for_inference"): | ||
| model.for_inference = lambda *a, **k: model.eval() | ||
| _guard_finite_logits(model) |
There was a problem hiding this comment.
Restrict finite-logit sanitization to the GRPO test
_load_plain() is also used by test_sft_trains_on_cpu and test_dpo_trains_on_cpu, so this forward hook clamps every model output in those canaries as well. If an SFT/DPO regression produces non-finite or extreme logits, the altered outputs can let the fake training run continue rather than exposing it; install the guard only for the GRPO model/test that needs safe sampling.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good call. Moved _guard_finite_logits out of the shared _load_plain() and into test_grpo_trains_on_cpu only, since GRPO is the sole canary that autoregressively samples (and thus the only one that can hit the non-finite-logits torch.multinomial crash). The SFT and DPO canaries now keep asserting against the model's true, unclamped logits. Done in 0d81947.
Only test_grpo_trains_on_cpu autoregressively samples completions, so it is the only canary that can hit the non-finite-logits torch.multinomial crash. Move the _guard_finite_logits hook out of the shared _load_plain() and into test_grpo_trains_on_cpu so the SFT and DPO canaries keep asserting against the model's true, unclamped logits.
* test(version-compat): keep GRPO fake-run logits finite on CPU The GRPO fake-run test samples completions from a tiny untrained model on CPU. Such a model can emit non-finite logits, so torch.multinomial inside generate() intermittently raises "probability tensor contains either inf, nan or element < 0" -- a nondeterministic sampling failure, not a regression (the Trainer already fixes the seed, but CPU reduction order is not bit-reproducible). Add a forward hook that sanitizes the LM head logits to a finite bounded range before sampling, so the fake run reliably exercises the whole train loop; the test checks the loop runs, not the numerics. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * test(version-compat): drop redundant nan_to_num bounds (clamp handles them) * test(version-compat): scope GRPO finite-logits guard to the GRPO test Only test_grpo_trains_on_cpu autoregressively samples completions, so it is the only canary that can hit the non-finite-logits torch.multinomial crash. Move the _guard_finite_logits hook out of the shared _load_plain() and into test_grpo_trains_on_cpu so the SFT and DPO canaries keep asserting against the model's true, unclamped logits. --------- Co-authored-by: Daniel Han <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…hai#7247) * test(version-compat): keep GRPO fake-run logits finite on CPU The GRPO fake-run test samples completions from a tiny untrained model on CPU. Such a model can emit non-finite logits, so torch.multinomial inside generate() intermittently raises "probability tensor contains either inf, nan or element < 0" -- a nondeterministic sampling failure, not a regression (the Trainer already fixes the seed, but CPU reduction order is not bit-reproducible). Add a forward hook that sanitizes the LM head logits to a finite bounded range before sampling, so the fake run reliably exercises the whole train loop; the test checks the loop runs, not the numerics. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * test(version-compat): drop redundant nan_to_num bounds (clamp handles them) * test(version-compat): scope GRPO finite-logits guard to the GRPO test Only test_grpo_trains_on_cpu autoregressively samples completions, so it is the only canary that can hit the non-finite-logits torch.multinomial crash. Move the _guard_finite_logits hook out of the shared _load_plain() and into test_grpo_trains_on_cpu so the SFT and DPO canaries keep asserting against the model's true, unclamped logits. --------- Co-authored-by: Daniel Han <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Problem
tests/version_compat/test_trl_fake_train_cpu.py::test_grpo_trains_on_cpuis intermittently red on the "GRPO fake-run (latest + main TRL, CPU spoof)" job with:The test runs 2 GRPO steps on a tiny untrained random model (
hf-internal-testing/tiny-random-LlamaForCausalLM) on CPU. Driven autoregressively, and nudged by the fake reward's optimizer step between the two steps, such a model can emit non-finite logits, so the sampler insidegenerate()occasionally rejects the distribution. This is a well-known nondeterministic sampling failure (see e.g. huggingface/trl#2205), not an Unsloth/TRL regression: the Trainer already fixes the seed, but CPU reduction order is not bit-reproducible, so the blow-up still surfaces every so often. The failing code path (UnslothGRPOTrainer._generate-> transformers_sample->torch.multinomial) is unrelated to anything under test.Fix
Add a small forward hook (
_guard_finite_logits, installed in_load_plain) that sanitizes the LM head logits to a finite, bounded range (nan_to_num+clamp(-30, 30), out of place so autograd stays valid) before they reach the sampler. The test asserts the train loop runs end to end, not the (deliberately meaningless) numerics, so bounding the logits changes nothing it checks while making the run reliable. Test-only change; no product code is touched.Validation
On a CPU-only torch build matching the CI job:
torch.multinomial(softmax(logits))raises the exact error oninf/nanlogits, and does not afternan_to_num+clamp(the guard).test_grpo_trains_on_cpufails with the exactprobability tensor contains either inf, nancrash (reproduces CI deterministically),test_grpo_trains_on_cpupasses normally with the guard.