Repository navigation
[rl] generator: batch-invariant patches for vLLM's V2 sampler - #5972
felipemello1 wants to merge 29 commits into
Conversation
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 2m 45s —— View job Approve -- please address the items before merging: review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The patch is small and contained in the vLLM subpackage. The new temperature replacement does the same division as the trainer. What's left is a description gap and a missing upstream TODO.
What this PR does. In batch-invariant mode, the existing patch that swaps vLLM V2 sampler's Triton compute_token_logprobs for the trainer's compute_logprobs grows in two ways. It also rebinds prompt_logprob.compute_token_logprobs, which is imported by name and so was missed before. It also replaces apply_temperature (in gumbel and states) with logits.div_(temperature[idx]). Before rebinding, it checks that each importer's binding is still the same object as the defining module's, and raises otherwise. generate.py and the GPU parity test now call the patch too. On today's V1 runner (VLLM_USE_V2_MODEL_RUNNER=0) none of these functions run, so nothing changes there.
Example.
V2 runner, batch_invariant, temperature=0.8, fp32 logits row x
before: gen = triton_apply_temperature(x) # ~15% of elements off by 1 ulp
train = x / temperature.expand_as(x) # loss.py:530
-> logprob diff 9.5e-07
after: gen = x.div_(temperature[idx].unsqueeze(-1)) # same IEEE tensor/tensor div as trainer
-> logprob diff 0
I checked that the trainer divides by a tensor rather than a Python scalar (components/loss.py:530). PyTorch can turn a CPU-scalar divide into a multiply by the reciprocal, which would break parity. Tensor-by-tensor division in eager mode gives the same bits with or without expand_as, so the generator side matches.
Must fix
- PR description: the "Summary (human-written)" section is empty. The author needs to fill it in.
torchtitan/rl/generator/vllm/batch_invariance.py:16: add a TODO with a vLLM issue link for this workaround (see inline).
Should consider
torchtitan/rl/generator/vllm/batch_invariance.py:85-96: the binding guard catches a removed importer but not a new one (see inline).- No test covers the temperature path on GPU: the bitwise parity tests sample greedily, as the description says. The 0 vs 9.5e-07 result can regress silently. In the V2 port PR, set temperature 0.8 in an existing parity test (e.g.
TestBitwiseParityKimiK3DebugVarlen) rather than adding a new one. tests/rl/unit_tests/cpu/test_batch_invariance.py:test_vllm_logprob_patch_keeps_trainer_fallback_pathnow also covers the temperature replacement and the binding guard. A name liketest_vllm_sampler_kernel_patchwould say that.
Questions
- This code, like the existing logprob patch, does nothing until the V2 port lands (the "current consumer" rule in
rules/design.md). Are maintainers fine landing it ahead of the port as a stacked PR, or should it go in with the port?
Not verified: the signature and return contract of vLLM's apply_temperature(logits, expanded_idx_mapping, temperature), and whether any other vLLM module imports either function by name. I couldn't read the vLLM source here, so I relied on the author's V2 GB300 run. This touches the RL generator, so a maintainer still needs to review.
|
|
||
| def force_logprobs_fn_for_batch_invariance() -> None: | ||
| """Make vLLM's v2 logprob path dispatch. | ||
| def patch_vllm_logprob_and_temperature_kernels() -> None: |
There was a problem hiding this comment.
This now monkeypatches four vLLM module bindings to work around a vLLM gap: vLLM's batch-invariant mode doesn't cover the V2 sampler's Triton logprob and temperature kernels. CLAUDE.md principle 3 asks for a TODO with an upstream issue link for workarounds like this. Without one, nobody knows when this can be deleted, and the binding list will keep growing as vLLM refactors. Please add something like:
# TODO: delete once vLLM's batch-invariant mode routes the V2 sampler's logprob and
# temperature kernels through aten ops (<vLLM issue link>).There was a problem hiding this comment.
Reply from claude: Added the TODO in 5327270. It names the vLLM change that deletes the patch. No vLLM issue link: the author decided not to open upstream vLLM work for now, as with the TODOs in the V2 port.
| # prompt_logprob.py and states.py import these functions by name, so their | ||
| # bindings are patched too. If vLLM moved a function, patching the old binding | ||
| # would leave its Triton kernel running with no error, so check first. | ||
| for importer, name, defining_module in ( | ||
| (vllm_prompt_logprob, "compute_token_logprobs", vllm_logprob), | ||
| (vllm_sampling_states, "apply_temperature", vllm_gumbel), | ||
| ): | ||
| if getattr(importer, name, None) is not getattr(defining_module, name): | ||
| raise RuntimeError( | ||
| f"{importer.__name__}.{name} is not {defining_module.__name__}.{name}: " | ||
| "vLLM moved it, so update this patch" | ||
| ) |
There was a problem hiding this comment.
Should consider: the guard catches one failure mode: a listed importer stops importing the function. It misses the other: vLLM adds a new from .gumbel import apply_temperature somewhere else (spec decode, a new sampler module). That module keeps the Triton kernel and nothing errors, which is the silent miss this check is meant to prevent. Modules imported after the patch pick up the patched attribute anyway, so the stale bindings can only be in vllm.* modules already in sys.modules. Rebinding every module there that holds the original function would cover all importers, and you could drop the hardcoded importer list. If you'd rather keep the list explicit, the comment should say it only covers the importers known in vLLM 0.33/main. Unverified: I couldn't read the vLLM source in this environment to check for other importers today.
There was a problem hiding this comment.
Reply from claude: Done in 5327270, as you suggested. The patch rebinds the name in every loaded vLLM module that holds vLLM's function; the fixed list and its check are gone. It reads vars(module), so a module with a lazy __getattr__ is not triggered. The CPU test adds a third importer. On vLLM 0.33 and on main, the real modules that end up patched are gumbel, logprob, prompt_logprob and states.
cd88b31 to
5327270
Compare
|
Reply from claude: @claude please review. New since your last review (5327270): the patch rebinds every loaded vLLM module that holds the original function, the TODO, and the test rename (
|
|
Claude finished @felipemello1's task in 1m 18s —— View job Approve -- please address the items before merging: review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The new commit (5327270) fixes the binding-guard gap, and it has no new correctness problems. What's left is the empty human-written summary.
Earlier items at HEAD
- Binding guard misses new importers: resolved.
batch_invariance.py:88-99now goes throughsys.modulesand rebinds everyvllm*module whose own__dict__holds the original function. The hardcoded importer list is gone. Modules imported later pick up the patched attribute fromlogprob/gumbel. The CPU test'snew_importercovers this. - Upstream TODO: resolved, without a link. The TODO at
batch_invariance.py:17says what change in vLLM would let us delete the patch. The author chose not to open a vLLM issue. Maintainers can decide whether that's acceptable for this stack. - Test name: resolved (
test_vllm_sampler_patch_uses_trainer_ops). - Temperature coverage on GPU: deferred, with a TODO at
test_bitwise_parity.py:513and a follow-up listed in the description. That's fine: a temperature arm needs processed logprobs on the trainer side, so it is its own change. - Landing before the port: the author answered. It's the maintainers' call.
Example (re-patching across engines).
call 1: original = vllm gumbel.apply_temperature (Triton)
gumbel, states, <any vllm.* importer> -> closure_1
call 2: original = closure_1 (read back from gumbel)
every module holding closure_1 -> closure_2
Each call reads original back from the defining module. So the second engine's call finds the first call's bindings and replaces them, and no importer is left on the Triton kernel. I also checked the trainer side again: components/loss.py:530 divides by the tensor temperature.unsqueeze(-1).expand_as(logits). The generator replacement also divides by a fp32 tensor, row_temperature.unsqueeze(-1).
Must fix
- PR description: the "Summary (human-written)" section is still empty. The author has to fill it in. An agent can't write it.
Should consider
tests/rl/unit_tests/cpu/test_batch_invariance.py:177-181: the re-patch assertions only check closure identity (see inline).
Not verified: the contract of vLLM's apply_temperature (in place, temperature 0 = greedy), and that no vLLM code keeps these functions anywhere other than a module global, such as a class attribute or a dict. I couldn't read the vLLM source here. This touches the RL generator, so a maintainer still needs to review.
| # A second call (one per engine) patches every binding again. | ||
| batch_invariance.patch_vllm_logprob_and_temperature_kernels() | ||
| repatched = modules[f"{sample}.gumbel"].apply_temperature | ||
| assert repatched is not patched | ||
| assert modules[f"{sample}.states"].apply_temperature is repatched |
There was a problem hiding this comment.
Should consider: these lines don't guard anything a user would notice. The second call's closures do the same thing as the first call's. If a second call left states bound to the first-call closure, numerics wouldn't change. So repatched is not patched only pins down which closure object each module holds. The binding check that matters, that every importer gets the PyTorch version, is already covered by the new_importer assert above. I'd delete these five lines.
There was a problem hiding this comment.
Reply from claude: Done in b5c3dd8: the five lines are gone.
5327270 to
b5c3dd8
Compare
|
Claude finished @felipemello1's task in 39s —— View job Approve -- please address the items before merging: review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. b5c3dd8 only deletes test lines, and nothing new needs fixing. The one open item is the empty human-written summary.
Since the last review (b5c3dd8)
- Closure-identity asserts in
tests/rl/unit_tests/cpu/test_batch_invariance.py: resolved. The five re-patch lines are gone. Thenew_importerassert at line 175 still checks that every vLLM importer gets the PyTorch version. - I re-read
batch_invariance.pyat HEAD. Thesys.modulesrebind loop (lines 88-98) is the same as in the last review and has no new problems.
Must fix
- PR description: the "Summary (human-written)" section is still the template placeholder. The author has to write it. An agent can't (see "AI-assisted contributions" in
CONTRIBUTING.md).
Still open (maintainers' call, as before)
- The TODO at
batch_invariance.py:17has no vLLM issue link. The author chose not to open one. - Whether to land this ahead of the V2 runner port, since nothing on V1 calls these functions.
- There's no GPU test with temperature != 1 yet. It's deferred to a follow-up, with a TODO in
test_bitwise_parity.py.
Not verified: the contract of vLLM's apply_temperature. I couldn't read the vLLM source here. This touches the RL generator, so a maintainer still needs to review.
In batch-invariant mode, replace two more Triton kernels of vLLM's V2 sampler with the trainer's PyTorch ops: - prompt logprobs: prompt_logprob.py imports compute_token_logprobs by name, so the existing patch missed it. - temperature: apply_temperature's fp32 division differs from PyTorch's by up to 1 ulp (15% of logits at temperature 0.8, GB300). Rename the patch to patch_vllm_logprob_and_temperature_kernels. Before patching a module that imports a function by name, check it still holds vLLM's function, and raise RuntimeError if vLLM moved it. generate.py and the flex parity test now apply the patch too. Today's V1 runner doesn't call these functions; the V2 runner port needs them for bitwise parity.
The binding check caught a listed importer that stopped importing a function, but missed a new importer, which would keep running the Triton kernel. Rebind the name in every loaded vLLM module that holds vLLM's function instead of a fixed list. Also add the TODO for the vLLM change that deletes this patch, a TODO for a temperature arm in the parity test, and a test name that says what the test checks.
b5c3dd8 to
56b080e
Compare
|
Reply from claude: @claude please review. The stack is rebased onto main 2805bd6: it picks up the GDN batch-invariant scan fix (it fixes CI's flaky Qwen3.5 parity test) and resolves conflicts with main's move of the model build out of vllm/. No logic changed: 10 of the stack's 15 commits are identical, and the other 5 differ only around main's moved code. |
|
Claude finished @felipemello1's task in 57s —— View job Approve -- please address the items before merging: review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The rebase onto main 2805bd6 didn't change this PR's diff. The one open item is still the empty human-written summary.
Since the last review (rebase only)
- The diff against the base branch matches what I reviewed at b5c3dd8: the same 7 files, the same
sys.modulesrebind loop inbatch_invariance.py:87-98, and the same tests. - The callsites survived main's move of the model build out of
vllm/.engine.py:231-234still calls the patch in_setupright afterregister_to_vllmand the runner selection.generate.py:138-141calls it right afterset_batch_invariance. Both parity tests call it too (test_bitwise_parity.py:229-236,test_gdn_cudagraph.py:282-283). No caller of the old nameforce_logprobs_fn_for_batch_invarianceis left in the repo.
Must fix
- PR description: the "Summary (human-written)" section is still the template placeholder. The author has to write it. An agent can't (see "AI-assisted contributions" in
CONTRIBUTING.md).
Should consider
- Commit 6cb48d4's message still says the patch checks each importer and raises
RuntimeErrorif vLLM moved a function. f84e91a replaced that check with thesys.modulesrebind. If the stack lands commit by commit rather than squashed, reword that message so the history doesn't describe code that never landed.
Still open (maintainers' call, as before)
- The TODO at
batch_invariance.py:17has no vLLM issue link. The author chose not to open one. - Whether to land this ahead of the V2 runner port, since nothing on V1 calls these functions.
- There's no GPU test with temperature != 1 yet. It's deferred, with a TODO at
test_bitwise_parity.py:520.
Not verified: the contract of vLLM's apply_temperature on vLLM 0.33. I couldn't import vLLM here. This touches the RL generator, so a maintainer still needs to review.
…] generator: batch-invariant patches for vLLM's V2 sampler Conflicts: main renamed force_logprobs_fn_for_batch_invariance to force_trainer_logprobs_for_batch_invariance, the name this PR changed. This merge keeps the PR's code; the next commit takes main's name.
…ariance Main gave vLLM's logprob patch the same name as SGLang's sampler patch. The vLLM function now also replaces the temperature kernel and keeps that name, so the two engines' patches still share one name.
…] generator: batch-invariant patches
…l] generator: batch-invariant patches
- force_trainer_logprobs_for_batch_invariance: a table of what replaces what, instead of a prose docstring; the call sites drop comments that restated it. - generator_apply_temperature: an Example of the row -> request mapping. - The GPU test's TODO says how to add the temperature arm.
…] generator: batch-invariant patches
| ("apply_temperature", vllm_gumbel, generator_apply_temperature), | ||
| ): | ||
| original = getattr(defining_module, name) | ||
| for module in list(sys.modules.values()): |
There was a problem hiding this comment.
This replacement might be too hacky
There was a problem hiding this comment.
from claude: Replaced in 727aeb1 with three explicit rebinds: logprob.compute_token_logprobs, prompt_logprob.compute_token_logprobs and states.apply_temperature. A CPU test fails if any other loaded vLLM module still holds either kernel.
|
from claude: @claude review |
There was a problem hiding this comment.
Verdict: Request changes -- @wwwjn's "too hacky" comment on the sys.modules rebind loop is unaddressed. I agree with it, and the smaller explicit version needs another look from the maintainer.
What this PR does. In batch-invariant mode, force_trainer_logprobs_for_batch_invariance now replaces two Triton kernels in vLLM's V2 sampler with PyTorch ops:
compute_token_logprobsbecomes the trainer'scompute_logprobs.apply_temperaturebecomeslogits.div_(T[idx]).
It then scans sys.modules and rebinds the name in every vllm* module that holds vLLM's original function. The flex parity test now applies the patch too. Today's V1 runner (VLLM_USE_V2_MODEL_RUNNER=0, engine.py:378) never calls either function, so nothing changes on main.
Example.
V2 runner, batch_invariant, temperature 0.8
before: gen = triton apply_temperature(x) -> ~15% of fp32 logits off by 1 ulp -> logprob diff 9.5e-07
after: gen = x.div_(T[idx].unsqueeze(-1))
train = x / T.unsqueeze(-1).expand_as(x) (components/loss.py:530) -> diff 0 (author's GB300 run)
Must fix
torchtitan/rl/generator/vllm/batch_invariance.py:88-100-- @wwwjn's comment: replace thesys.modulesscan with explicit assignments tologprob,gumbelandstates, and drop theprompt_logprobrebind, which nothing calls (see inline). I suggested the scan two rounds ago, and I'm withdrawing that suggestion.- PR description, Solution item 3: "
generate.py... apply the patch too" no longer matches the diff.generate.pyisn't changed. It gets the patch throughengine.build->_setup(engine.py:380). Item 2 and the "prompt token-id logprobs" line in the TLDR also need updating once item 1 lands.
Still open (from earlier reviews)
- The TODO at
batch_invariance.py:17has no vLLM issue link. Root-cause fix: underVLLM_BATCH_INVARIANT, vLLM's V2apply_temperatureshould use a torch division. That is likely a few lines in vLLM and would delete this temperature patch. - Commit 6cb48d4's message describes the rename and the
RuntimeErrorcheck that were later reverted. This only matters if the stack lands without a squash.
Questions
- Does vLLM's V2 runner offer a sampler extension point like SGLang's
register_sampler_backend(seerl/generator/sglang/batch_invariance.py:63)? If it does, subclassing the sampler would replace module-global patching altogether.
Details
- Overlap search:
gh pr list --search "batch_invariance vllm"found no other open PRs. #5928 (temperature 0.8 parity arm) is the tracked GPU coverage follow-up. test_bitwise_parity.py:230-235: moving the patch out of the non-flex branch matchesengine.py, which patches whatever the attention backend.- The
engine.pycall-site comment removal is fine: the docstring now says why the patch exists. - The human-written summary is now filled in by @wwwjn, which also answers the earlier "land ahead of the V2 port" question.
Not verified: which vLLM modules look up apply_temperature on the V2 sample path, and whether prompt_logprob is reached without prompt_logprobs requested. I couldn't read the vLLM source here. This touches the RL generator, so a maintainer still needs to review.
| # vLLM modules import these functions by name (e.g. prompt_logprob.py, states.py), | ||
| # so rebind the name in every loaded vLLM module that holds vLLM's function. | ||
| # Modules loaded later import the patched function. | ||
| for name, defining_module, replacement in ( | ||
| ("compute_token_logprobs", vllm_logprob, generator_compute_token_logprobs), | ||
| ("apply_temperature", vllm_gumbel, generator_apply_temperature), | ||
| ): | ||
| original = getattr(defining_module, name) | ||
| for module in list(sys.modules.values()): | ||
| if getattr(module, "__name__", "").startswith("vllm") and ( | ||
| vars(module).get(name) is original | ||
| ): | ||
| setattr(module, name, replacement) |
There was a problem hiding this comment.
Must fix (re @wwwjn's "too hacky"): I agree, and I'm reversing my earlier suggestion. I proposed this sys.modules scan to catch a vLLM module that might import these functions by name in the future. That guards a hypothetical importer, and it costs a loop that rewrites globals in every vllm* module based on object identity and import order. rules/design.md treats monkeypatching as a sign of the wrong layer, so the patch should stay as small and greppable as possible.
The smallest version names the bindings that RL actually reaches:
import vllm.v1.worker.gpu.sample.gumbel as vllm_gumbel
import vllm.v1.worker.gpu.sample.logprob as vllm_logprob
import vllm.v1.worker.gpu.sample.states as vllm_states
...
vllm_logprob.compute_token_logprobs = generator_compute_token_logprobs
vllm_gumbel.apply_temperature = generator_apply_temperature
# states.py imports apply_temperature by name.
vllm_states.apply_temperature = generator_apply_temperatureThen drop import sys and, in the CPU test, new_importer.
I left out the prompt_logprob rebind on purpose. Nothing in torchtitan requests prompt logprobs: the only mention is prompt_logprobs: None in rl/examples/verifiers/generation_server.py:317. So that rebind has no consumer. Add it back only if an RL path needs prompt logprobs.
You don't need the scan as a safety net for a future vLLM importer. The temperature-0.8 arm planned in #5928 would show a nonzero logprob diff if one is missed.
Unverified: I couldn't read the vLLM source here, so please confirm that gumbel and states are the only places the V2 sample path looks up apply_temperature.
There was a problem hiding this comment.
from claude: Done in 727aeb1, with two differences. prompt_logprob.compute_token_logprobs stays: the bitwise parity test requests prompt_logprobs=1 (test_bitwise_parity.py:489), which runs it. gumbel.apply_temperature is not rebound: in vLLM 0.33 and 0.34 only states.py calls it, through its by-name import (gumbel.py's other apply_temperature is a bool argument). import sys and new_importer are gone.
…all names Replace the sys.modules scan with explicit rebinds of the names vLLM calls the kernels through (logprob.py, prompt_logprob.py and states.py; the same in vLLM 0.33.0 and 0.34.0). A CPU test against the installed vLLM fails if an upgrade imports either kernel by name anywhere else.
|
from claude: @claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. 727aeb1 fixes both must-fix items from my last review. The remaining item is a TODO link.
What this PR does. In batch-invariant mode, force_trainer_logprobs_for_batch_invariance replaces two Triton kernels in vLLM's V2 sampler with PyTorch ops:
compute_token_logprobsbecomes the trainer'scompute_logprobs.apply_temperaturebecomeslogits.div_(T[idx]).
The patch reassigns three module-level names. A new CPU test imports the real V2 runner and fails if any other loaded vLLM module still holds either kernel. The V1 runner never calls these functions.
Example.
batch_invariance.py:89-92, after this commit
logprob.compute_token_logprobs = generator_compute_token_logprobs # decode logprobs
prompt_logprob.compute_token_logprobs = generator_compute_token_logprobs # prompt_logprobs=1 (test_bitwise_parity.py:489)
states.apply_temperature = generator_apply_temperature # temperature != 1
vLLM upgrade adds `from .gumbel import apply_temperature` in spec_decode.py
-> test_vllm_sampler_patch_covers_every_vllm_caller fails in RL CPU CI (vLLM is installed there, unit_test_cpu_rl.yaml:54)
Earlier items at HEAD
- @wwwjn's "too hacky" (
sys.modulesscan): resolved. The scan is replaced by explicit rebinds atbatch_invariance.py:89-92, andimport sysis gone from the module. - Keeping
prompt_logprob: resolved, my earlier suggestion was wrong._PREFILL_PARAMSrequestsprompt_logprobs=1(test_bitwise_parity.py:489), so that binding is used. - Description, Solution item 3 (
generate.py): resolved. - Commit 6cb48d4's message: still open. It only matters if the stack lands without a squash.
- Question about a vLLM sampler extension point like SGLang's
register_sampler_backend: still unanswered. It isn't blocking.
Must fix
torchtitan/rl/generator/vllm/batch_invariance.py:16-- still open: this monkeypatch works around a vLLM gap, and CLAUDE.md principle 3 requires the TODO to link an upstream issue. It has no link. File a vLLM issue (underVLLM_BATCH_INVARIANT, have the V2apply_temperatureandcompute_token_logprobsuse torch ops) and link it.
Should consider
tests/rl/unit_tests/cpu/test_batch_invariance.py:213-214-- thegumbelallowlist misses a future call made insidegumbel.py(see inline).
Not verified: which vLLM 0.33/0.34 modules call apply_temperature. I couldn't import vLLM here. The new CPU test checks this in CI. This touches the RL generator, so a maintainer still needs to review.
| # gumbel.py defines apply_temperature but never calls it. | ||
| assert unpatched == ["vllm.v1.worker.gpu.sample.gumbel.apply_temperature"] |
There was a problem hiding this comment.
Should consider: the allowlist exempts gumbel from the exact failure this test is meant to catch. Suppose a vLLM upgrade calls apply_temperature(...) from inside gumbel.py, for example fused into gumbel_sample. That call looks up gumbel's own global, which still holds the Triton kernel, and this assert still passes. The 1-ulp temperature diff then comes back silently.
The smallest fix is one line in batch_invariance.py plus this assert:
vllm_gumbel.apply_temperature = generator_apply_temperature # defining module| # gumbel.py defines apply_temperature but never calls it. | |
| assert unpatched == ["vllm.v1.worker.gpu.sample.gumbel.apply_temperature"] | |
| assert unpatched == [] |
That also drops the special-case comment. If you'd rather not rebind a name nothing calls today, keep the allowlist, but say in the comment that a future call inside gumbel.py would slip through.
There was a problem hiding this comment.
from claude: Done in c7a80e1: gumbel.apply_temperature is rebound too, and the test asserts unpatched == [].
gumbel.py defines apply_temperature and nothing calls it there today, but a future call inside gumbel.py would look up its own global and run the Triton kernel again. Rebinding the defining module too lets the caller test assert that no loaded vLLM module still holds either kernel.
|
from claude: @claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. c7a80e1 fixes the gumbel gap from my last review. The only item left is the vLLM issue link on the TODO.
What this PR does. In batch-invariant mode, force_trainer_logprobs_for_batch_invariance swaps two Triton kernels in vLLM's V2 sampler for PyTorch ops:
compute_token_logprobsbecomes the trainer'scompute_logprobs.apply_temperaturebecomeslogits.div_(T[idx]).
The patch now rebinds four module-level names explicitly. A CPU test imports the real V2 runner. It fails if any loaded vLLM module still holds either kernel. The V1 runner never calls these functions.
Example.
batch_invariance.py:92-95 at c7a80e10b
logprob.compute_token_logprobs -> generator_compute_token_logprobs (defining module)
prompt_logprob.compute_token_logprobs -> generator_compute_token_logprobs (by-name import)
gumbel.apply_temperature -> generator_apply_temperature (defining module, new)
states.apply_temperature -> generator_apply_temperature (by-name import)
Say a vLLM upgrade fuses a call to apply_temperature into gumbel.py:
before: gumbel's own global still pointed at the Triton kernel, and the test's allowlist hid it
after: the call reaches the PyTorch division, and test_batch_invariance.py:215 asserts unpatched == []
Since the last review (c7a80e1)
gumbelallowlist intest_vllm_sampler_patch_covers_every_vllm_caller: resolved.batch_invariance.py:94rebindsgumbel.apply_temperature, and the assert is nowunpatched == []. Themonkeypatchrestore loop attest_batch_invariance.py:202-205coversgumbeltoo, because before the patch it holds the original. The fake-module test (:111,:137-138) now registersgumbel. That keeps it from failing on the new import.- Description, Solution item 2, now lists the four names and matches the code.
Must fix
torchtitan/rl/generator/vllm/batch_invariance.py:16-- still open: the TODO needs a vLLM issue link (CLAUDE.md principle 3).
Still open (non-blocking)
- Commit 6cb48d4's message describes a rename and a
RuntimeErrorcheck that were later reverted. This only matters if the stack lands without a squash. - Does vLLM's V2 runner have a sampler extension point like SGLang's
register_sampler_backend? Still unanswered.
Not verified: which vLLM 0.33/0.34 modules call apply_temperature. I couldn't import vLLM here, and the new CPU test checks this in RL CPU CI. This touches the RL generator, so a maintainer still needs to review.
|
from claude: On the sampler extension point: vLLM 0.33 and 0.34's V2 runner has |
| row_temperature = temperature[expanded_idx_mapping] | ||
| row_temperature = torch.where(row_temperature == 0.0, 1.0, row_temperature) | ||
| logits.div_(row_temperature.unsqueeze(-1)) |
There was a problem hiding this comment.
I guess this matches trainer behavior in batch-invariant way? https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/loss.py#L530
Even though the trainer has inductor compiling loss region, I can confirm we only need to worry about eager mode, because https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/loss.py#L494 clearly says the compilation won't generate batch invariant results.
Summary (human-written)
By @wwwjn
Agent details
Written with Claude Code.
TLDR: In batch-invariant mode, two more Triton kernels of vLLM's V2 sampler now run as the trainer's PyTorch ops: prompt token-id logprobs and temperature. On the V2 runner, Kimi K3 RL's trainer-vs-generator logprob diff goes from 9.5e-07 to 0. Today's V1 runner doesn't call these functions. The V2 runner port does.
Problem
compute_token_logprobsinlogprob.py.prompt_logprob.pyimports it by name, so prompt token-id logprobs still run the kernel. Top-k prompt logprobs calllogprob.py'scompute_topk_scores, which the old patch already covered.Solution
force_trainer_logprobs_for_batch_invariance(main's name, which SGLang's patch shares) also replacesapply_temperature.logprob.compute_token_logprobs,gumbel.apply_temperature) and the by-name imports (prompt_logprob.compute_token_logprobs,states.apply_temperature), the same on vLLM 0.33 and 0.34. vLLM calls three of them today;gumbel.apply_temperaturehas no caller yet, and rebinding it keeps a future call insidegumbel.pyfrom reaching the kernel. A CPU test imports vLLM's V2 runner and fails if any loaded vLLM module still holds either kernel.generate.pybuilds throughVLLMEngine, so it gets the patch there.Results
At c7a80e1 (the four explicit rebinds),
tests/rl/unit_tests/cpu: 771 passed, 8 skipped on vLLM 0.33.0; the PR above (vLLM 0.34.0) passes the new caller test too.CI's bitwise parity tests sample greedily, so they never run the temperature kernel. Only a run with temperature != 1 shows the 9.5e-07.
Follow up / TODO
test_bitwise_parity.pylinks the open draft that adds it.You may ask:
Test plan
CUDA_VISIBLE_DEVICES= pytest tests/rl/unit_tests/cpupython -c "from torchtitan.rl.generator.vllm.batch_invariance import force_trainer_logprobs_for_batch_invariance as p; p(); p()"(CPU, vLLM 0.33)torchrun --nproc-per-node=1 -m pytest tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityKimiK3DebugVarlenTORCHTITAN_QWEN3_5_0_8B_HF_PATH=<Qwen3.5-0.8B> pytest tests/rl/unit_tests/gpu/test_gdn_cudagraph.pyAt aada6cf (main a75b09a merged in through the PRs below),
tests/rl/unit_tests/cpuon vLLM 0.33.0: 703 passed, 8 skipped. Earlier runs:Runs at 8ff888e (main b1c259c merged in through the PRs below), vLLM 0.33.0, GB300, 2026-11-20: