Skip to content

test(version-compat): keep GRPO fake-run logits finite on CPU - #7247

Merged
danielhanchen merged 4 commits into
mainfrom
fix/grpo-cpu-fake-run-finite-logits
Jul 19, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
fix/grpo-cpu-fake-run-finite-logits

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

tests/version_compat/test_trl_fake_train_cpu.py::test_grpo_trains_on_cpu is intermittently red on the "GRPO fake-run (latest + main TRL, CPU spoof)" job with:

torch.multinomial(probs, num_samples=1)
RuntimeError: probability tensor contains either `inf`, `nan` or element < 0

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 inside generate() 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:

  • Unit proof: torch.multinomial(softmax(logits)) raises the exact error on inf/nan logits, and does not after nan_to_num + clamp (the guard).
  • Integration proof (inject non-finite logits into the real GRPO generation path):
    • guard removed -> test_grpo_trains_on_cpu fails with the exact probability tensor contains either inf, nan crash (reproduces CI deterministically),
    • guard present -> passes.
  • No regression: test_grpo_trains_on_cpu passes normally with the guard.

shimmyshimmer and others added 2 commits July 19, 2026 10:53
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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +178 to +185

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

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 output
References
  1. 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@danielhanchen
danielhanchen merged commit ecd97a9 into main Jul 19, 2026
24 checks passed
@danielhanchen
danielhanchen deleted the fix/grpo-cpu-fake-run-finite-logits branch July 19, 2026 11:54
danielhanchen added a commit that referenced this pull request Jul 19, 2026
* 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>
VectorCipher pushed a commit to VectorCipher/unsloth that referenced this pull request Jul 20, 2026
…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>
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