Repository navigation
[rl] Reject non-positive training sampling temperature - #6356
felipemello1 merged 1 commit into
Conversation
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.
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
## 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.
| # 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." | ||
| ) |
There was a problem hiding this comment.
having this here is ok. A couple of thoughts:
- validation also passes temperature
- 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.
|
@claude review, consider my comments |
|
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. |
There was a problem hiding this comment.
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
- "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 torollout_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 onlygenerator.sampling.temperature, so greedy validation still works, as the error message says. - "Temperature may change during rollouts, so check in the generator": not today.
self._samplingis 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, andgenerate.pyuses greedy decoding legitimately, so rejecting 0 there would break both. When per-turn temperature lands, the check should go where the per-tokentemperatureis recorded (batcher/loss), not in the generator. A custom rollouter that overrides_run_single_rolloutwith its ownsamplingalready 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.
Summary (human-written)
Reject non-positive training sampling temperatures (
generator.sampling.temperature <= 0) at config time inController.Config.__post_init__. Previously, setting0.0(greedy) built without error and producedNaNlogprobs, loss, and gradients whencompute_logprobsdivided logits by temperature, while also repeating identical rollouts with all-zero group-relative advantages. Keeping the check inController.Configrather thanSamplingConfigleaves greedy validation (async_loop.validation.temperature=0) unaffected, andtest_greedy_training_sampling_raisesguards against regressions.Why
SamplingConfig.temperaturedocuments0.0 = greedy, andController.Configaccepts it as the training sampling temperature. The controller handsgenerator.sampling.temperatureto theBatcher, which fills every microbatch'stemperature[T]with it, andcompute_logprobsscores tokens undersoftmax(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=Nonerather than 0. Training has no such check.Example.
rl_grpo_qwen3_5_debug_varlen(seq_len=128)withgenerator.sampling.temperature=0.0:What changed
Controller.Config.__post_init__raisesValueErrorwhengenerator.sampling.temperature <= 0.test_greedy_training_sampling_raisesbuilds 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
SamplingConfig.__post_init__: validation reuses it throughdataclasses.replace(self._sampling, temperature=validation.temperature), so greedy validation would break.User-facing changes
generator.sampling.temperature=0.0builds and trains on NaN lossValueErrorat config timeasync_loop.validation.temperature=0(greedy validation)Testing
WSL2 Ubuntu 24.04, Python 3.12, torch
2.16.0.dev20261123+cpu, vLLM1.0.0.dev20261107+cu132withVLLM_TARGET_DEVICE=cpu, base3f09e7band this branch.pytest tests/rl/unit_tests/cpu/test_async_controller.py -k greedy_training_sampling: fails onmainwithDID 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:main702 passed, 1 failed, 10 skipped; this branch 703 passed, 1 failed, 10 skipped. The failure on both istest_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.torchtitan_recipes/rlandtorchtitan_recipes/tests/rlthat imports without optional packages (43, at temperature 0.8 or 1.0) builds on bothmainand this branch. Training temperatures 1.0, 0.8 and 1e-3, and greedy validation with a training temperature of 0.8, still build.main(8919259):test_async_controller.py55 passed. Withmain'scontroller.py, the new test fails withDID NOT RAISE.pre-commit run --fileson the two changed files: flake8, ufmt, pydoclint and codespell pass. Pyrefly reports the same diagnostics on these files onmainand 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.