Skip to content

[rl] Reject non-positive training sampling temperature - #6356

Merged
felipemello1 merged 1 commit into
pytorch:mainfrom
aswanth-07:fix/rl-reject-nonpositive-training-temperature
Nov 25, 2026
Merged

felipemello1 merged 1 commit into
pytorch:mainfrom
aswanth-07:fix/rl-reject-nonpositive-training-temperature

Conversation

@aswanth-07

@aswanth-07 aswanth-07 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Reject non-positive training sampling temperatures (generator.sampling.temperature <= 0) at config time in Controller.Config.__post_init__. Previously, setting 0.0 (greedy) built without error and produced NaN logprobs, loss, and gradients when compute_logprobs divided logits by temperature, while also repeating identical rollouts with all-zero group-relative advantages. Keeping the check in Controller.Config rather than SamplingConfig leaves greedy validation (async_loop.validation.temperature=0) unaffected, and test_greedy_training_sampling_raises guards against regressions.

Why

SamplingConfig.temperature documents 0.0 = greedy, and Controller.Config accepts it as the training sampling temperature. The controller hands generator.sampling.temperature to the Batcher, which fills every microbatch's temperature[T] with it, and compute_logprobs scores tokens under softmax(logits / temperature). At 0 the trainer's logprobs, loss and gradients become NaN. A greedy group also repeats one rollout, so its group-relative advantages are all 0.

Validation already rejects greedy sampling with more than one sample per prompt (#6266), and the trainer-vs-vLLM parity test in #5928 scores greedy tokens with temperature=None rather than 0. Training has no such check.

Example. rl_grpo_qwen3_5_debug_varlen(seq_len=128) with generator.sampling.temperature=0.0:

main:     the config builds; DAPOLoss with temperature[T] = 0 gives loss=nan,
          non-finite logits gradients and entropy nan (T = 0.8: loss 0.0964, finite)
this PR:  ValueError: generator.sampling.temperature must be positive, got 0.0: the
          trainer divides the logits by it. For greedy validation, set
          async_loop.validation.temperature=0.

What changed

  • Controller.Config.__post_init__ raises ValueError when generator.sampling.temperature <= 0.
  • test_greedy_training_sampling_raises builds the CI recipe with temperature 0 and expects the error. It catches the check being dropped, which would let a greedy training config train on NaN again.

Alternatives considered

User-facing changes

Before After
generator.sampling.temperature=0.0 builds and trains on NaN loss ValueError at config time
async_loop.validation.temperature=0 (greedy validation) unchanged

Testing

WSL2 Ubuntu 24.04, Python 3.12, torch 2.16.0.dev20261123+cpu, vLLM 1.0.0.dev20261107+cu132 with VLLM_TARGET_DEVICE=cpu, base 3f09e7b and this branch.

  • pytest tests/rl/unit_tests/cpu/test_async_controller.py -k greedy_training_sampling: fails on main with DID NOT RAISE <class 'ValueError'>, passes on this branch.
  • pytest tests/rl/unit_tests/cpu --ignore=tests/rl/unit_tests/cpu/test_dapo_math.py --ignore=tests/rl/unit_tests/cpu/test_geometry3k.py: main 702 passed, 1 failed, 10 skipped; this branch 703 passed, 1 failed, 10 skipped. The failure on both is test_controller_requires_a_vision_processor_exactly_for_multimodal_models (No module named 'math_verify' in my environment). The two ignored modules need their example dependencies to collect.
  • Every zero-argument recipe in torchtitan_recipes/rl and torchtitan_recipes/tests/rl that imports without optional packages (43, at temperature 0.8 or 1.0) builds on both main and this branch. Training temperatures 1.0, 0.8 and 1e-3, and greedy validation with a training temperature of 0.8, still build.
  • On this branch merged with current main (8919259): test_async_controller.py 55 passed. With main's controller.py, the new test fails with DID NOT RAISE.
  • pre-commit run --files on the two changed files: flake8, ufmt, pydoclint and codespell pass. Pyrefly reports the same diagnostics on these files on main and this branch (RL packages missing on my Windows checkout).

AI assistance disclosure: AI-assisted development tools were used during investigation, implementation, and regression testing. I personally reviewed the final diff, verified the correctness of the changes and validation results, and take full responsibility for the contribution.

The batcher fills each microbatch's temperature with
generator.sampling.temperature and the loss scores tokens under
softmax(logits / temperature), so a temperature of 0 makes the
trainer's logprobs, loss and gradients NaN. A greedy group also
repeats one rollout, so its advantages are all 0. Raise at config
time; greedy validation stays available through
async_loop.validation.temperature.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 24, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

tianyu-l added a commit that referenced this pull request Nov 25, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
The trainer scores each token under `softmax(logits / T)`, the
distribution the generator sampled from, and `DAPOLoss`/`GRPOLoss` use
the generator's logprob as the old policy: the importance ratio is `p /
q`. SGLang's `SGLANG_RETURN_ORIGINAL_LOGPROB=1` (documented by other RL
frameworks for their own needs) makes SGLang's sampler return
`log_softmax(logits)`, before temperature. Nothing in torchtitan checks
it, so with the variable set every SGLang-generated ratio is silently
wrong whenever `T != 1`.

**Example.** `SGLangEngine`, `SamplingConfig(temperature=0.8)`, a token
with logits `[2.0, 1.0, 0.0]`, sampled token 0:

```
q the trainer expects     = softmax([2, 1, 0] / 0.8)[0] = 0.73
q SGLang returns (env=1)  = softmax([2, 1, 0])[0]       = 0.67
main:     ratio p/q is off by 10% on this token; every token is off, no error
this PR:  ValueError at SGLangEngine init: unset SGLANG_RETURN_ORIGINAL_LOGPROB
```

## What changed
- `SGLangEngine.__init__` raises `ValueError` if
`SGLANG_RETURN_ORIGINAL_LOGPROB` is set. It reads
`sglang.srt.layers.sampler.SGLANG_RETURN_ORIGINAL_LOGPROB`, the module
constant SGLang's sampler itself branches on, so the check can't
disagree with SGLang's parsing of the variable.

## Alternatives considered
- Recompute the returned logprobs from `logits / T` (as the
batch-invariant `TrainerLogprobsSampler` does): extra work on every
decode step to support a setting nobody needs.
- Check at config time: the variable is read in the generator processes,
which may have a different environment than the controller.

## Testing
- No new test: the check reads SGLang's own constant, so a test would
only re-read an environment variable. Verified the import resolves
against the SGLang commit the README pins (`.venv-sglang`).
- `pytest tests/rl/unit_tests/cpu`: 741 passed, 7 skipped (GB300, CPU
only).

## Known issues / follow-ups
First PR of the score centering stack (arXiv 2609.20807, takes over
#5760): score centering also reads SGLang's top-k logprobs, which this
variable would turn pre-temperature too. Training with temperature <= 0
is handled separately by #6356.
@aswanth-07
aswanth-07 marked this pull request as ready for review November 25, 2026 12:26
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 25, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 25, 2026 12:26
Comment on lines +455 to +463
# The loss scores rollouts under softmax(logits / temperature), which is NaN at
# 0, and a greedy group repeats one rollout, so all its advantages are 0.
training_temperature = self.generator.sampling.temperature
if training_temperature <= 0:
raise ValueError(
"generator.sampling.temperature must be positive, got "
f"{training_temperature}: the trainer divides the logits by it. "
"For greedy validation, set async_loop.validation.temperature=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.

having this here is ok. A couple of thoughts:

  1. validation also passes temperature
  2. i believe we allow temperature to change during the rollouts, not 100%. If thats the case, maybe the check should be in the generator, not here. It would take longer to fail, but it would be safer.

@felipemello1

Copy link
Copy Markdown
Contributor

@claude review, consider my comments

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 9s —— View job


Approve: the training temperature is fixed per run, so the config check covers everything that reaches the loss, and the generator can't host the check without breaking greedy validation. I address both of your comments in the review.

@claude claude 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.

Verdict: Approve -- the training temperature is fixed for the whole run today, so a config-time check in Controller.Config covers every value that reaches the loss. The generator can't host this check because it also serves greedy validation and generate.py.

What this PR does. It raises a ValueError in Controller.Config.__post_init__ when generator.sampling.temperature <= 0. At 0 the batcher fills temperature[T] with 0, and compute_logprobs then computes logits / 0, which gives NaN logprobs, loss and gradients.

Example.

generator.sampling.temperature=0.0
  main:    builds; Batcher gets temperature=0 (controller.py:853) -> temperature[T]=0
           (batcher.py:1004) -> loss=nan
  this PR: ValueError at config time
async_loop.validation.temperature=0, num_samples_per_prompt=1
  both:    allowed; the validation sampling is replace(self._sampling, temperature=...)
           (controller.py:1019), and its rollouts are recorded, never batched

On @felipemello1's comments

  1. "Validation also passes temperature": correct, and already handled. ValidationConfig.__post_init__ (controller.py:199-212) rejects negative values and greedy with n > 1. Validation rollouts go to rollout_recorder.record(is_validation=True, ...) (controller.py:1028), never to the batcher, so a validation temperature of 0 never gets divided. The new check reads only generator.sampling.temperature, so greedy validation still works, as the error message says.
  2. "Temperature may change during rollouts, so check in the generator": not today. self._sampling is built once (controller.py:641). Every training group gets the same object (controller.py:1310), and the batcher receives one scalar (controller.py:853) and broadcasts it per token, with a TODO for per-turn temperature (batcher.py:1002-1004). The generator would be the wrong place even if temperature did vary. Generator.generate (generator.py:427) can't tell training requests from validation requests, and generate.py uses greedy decoding legitimately, so rejecting 0 there would break both. When per-turn temperature lands, the check should go where the per-token temperature is recorded (batcher/loss), not in the generator. A custom rollouter that overrides _run_single_rollout with its own sampling already causes a silent trainer/generator temperature mismatch. That is the per-turn TODO, not something this PR introduces.

Nothing else needs fixing. This touches core RL controller config, so a maintainer still needs to review.

@felipemello1
felipemello1 merged commit 7a60bbb into pytorch:main Nov 25, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants