Skip to content

[rl] generator: batch-invariant patches for vLLM's V2 sampler - #5972

Open
felipemello1 wants to merge 29 commits into
felipemello1/vllm-v2/1-moe-padding-maskfrom
felipemello1/vllm-v2/2-sampler-patches
Open

felipemello1 wants to merge 29 commits into
felipemello1/vllm-v2/1-moe-padding-maskfrom
felipemello1/vllm-v2/2-sampler-patches

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

By @wwwjn

  • Need some patches for batch invariant mode. Switch vllm's function to use our implementation

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.

# vLLM's v2 sampler, in batch-invariant mode
logprob.compute_token_logprobs         -> trainer's compute_logprobs   (already patched)
prompt_logprob.compute_token_logprobs  -> trainer's compute_logprobs   (new: imported by name, so the old patch missed it)
gumbel.apply_temperature               -> logits.div_(temperature)     (new: where the kernel is defined)
states.apply_temperature               -> logits.div_(temperature)     (new: imported by name from gumbel.py)

Problem

  1. Batch-invariant mode needs the generator's logprobs to match the trainer's bit for bit.
  2. vLLM's V2 sampler computes logprobs and divides by the temperature in Triton kernels, not in the trainer's PyTorch ops. The logprob kernel skips the batch-invariant aten overrides.
  3. TorchTitan already replaces compute_token_logprobs in logprob.py. prompt_logprob.py imports it by name, so prompt token-id logprobs still run the kernel. Top-k prompt logprobs call logprob.py's compute_topk_scores, which the old patch already covered.
  4. The temperature kernel's fp32 division differs from PyTorch's: 15% of logits differ by up to 1 ulp. On V2, Kimi K3 RL's logprob diff was 9.5e-07 instead of 0.

Solution

  1. force_trainer_logprobs_for_batch_invariance (main's name, which SGLang's patch shares) also replaces apply_temperature.
  2. The patch rebinds the four module-level names that hold the two kernels: where they are defined (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_temperature has no caller yet, and rebinding it keeps a future call inside gumbel.py from reaching the kernel. A CPU test imports vLLM's V2 runner and fails if any loaded vLLM module still holds either kernel.
  3. The bitwise parity test now applies the patch in its flex arm too (before: only varlen), as the engine does. generate.py builds through VLLMEngine, so it gets the patch there.
  4. Unchanged on today's V1 runner: it never calls these functions, as with today's logprob patch.

Results

Numerics (V2 runner, vLLM main, GB300; runs from the V2 runner port):
  Kimi K3 batch-invariant RL, 3 steps        logprob diff max 0 (9.5e-07 without the temperature patch)
  temperature kernel vs logits / temperature  fp32 logits [64, 163840], temperature 0.8: 15% of elements differ, by at most 1 ulp

vLLM 0.33.0 (this stack's pin), V1 runner, GB300
  tests/rl/unit_tests/cpu                    563 passed, 7 skipped
  the patch on vLLM 0.33's real modules      gumbel, logprob, prompt_logprob, states hold the PyTorch versions; no loaded
                                             vLLM module holds either kernel (same on vLLM 0.34.0)
  on V1 the patch changes nothing:          Kimi K3 bitwise parity 4 passed, test_gdn_cudagraph.py 4 passed

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

  • A temperature 0.8 arm in a bitwise parity test, so CI checks the temperature patch. The TODO in test_bitwise_parity.py links the open draft that adds it.

You may ask:

  • Why land this before the V2 port? On V2, batch-invariant RL needs it for a logprob diff of 0. No CI test checks that diff today. On V1 it changes nothing, and this keeps the port smaller.

Test plan

  • CUDA_VISIBLE_DEVICES= pytest tests/rl/unit_tests/cpu
  • python -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::TestBitwiseParityKimiK3DebugVarlen
  • TORCHTITAN_QWEN3_5_0_8B_HF_PATH=<Qwen3.5-0.8B> pytest tests/rl/unit_tests/gpu/test_gdn_cudagraph.py

At aada6cf (main a75b09a merged in through the PRs below), tests/rl/unit_tests/cpu on 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:

check                                                         GPUs  result
tests/rl/unit_tests/cpu                                       -     679 passed, 8 skipped
GPU rows at 8577d0dc7 (later commits: comments, one assert and the shared padding helper in the PRs below):
GPU unit tests, -m "not multi_gpu"                            1     27 passed, 1 skipped
Qwen3.5 debug bitwise parity                                  2     5 passed
Kimi K3 bitwise parity + Dist-MoE MXFP8 test, under torchrun  1     4 passed, 1 skipped

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 9, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 9, 2026
@felipemello1
felipemello1 added this pull request to stack #5973 November 9, 2026 03:50
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 45s —— View job


Approve -- please address the items before merging: 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 -- 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

  1. PR description: the "Summary (human-written)" section is empty. The author needs to fill it in.
  2. 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_path now also covers the temperature replacement and the binding guard. A name like test_vllm_sampler_kernel_patch would 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:

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +85 to +96
# 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"
)

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@felipemello1
felipemello1 force-pushed the felipemello1/vllm-v2/2-sampler-patches branch from cd88b31 to 5327270 Compare November 9, 2026 04:25
@felipemello1

Copy link
Copy Markdown
Contributor Author

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 (test_vllm_sampler_patch_uses_trainer_ops). Your other points:

  • Temperature on GPU: a TODO in test_bitwise_parity.py and a follow-up in the description. A temperature arm needs processed logprobs and the trainer's logits / T in that test, so it is its own change.
  • Landing ahead of the port: this PR sits right below the port in the native stack, and the existing logprob patch already works this way on V1. It can merge together with the port if maintainers prefer.

@claude

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging: 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 -- 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-99 now goes through sys.modules and rebinds every vllm* module whose own __dict__ holds the original function. The hardcoded importer list is gone. Modules imported later pick up the patched attribute from logprob/gumbel. The CPU test's new_importer covers this.
  • Upstream TODO: resolved, without a link. The TODO at batch_invariance.py:17 says 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:513 and 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

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

Comment on lines +177 to +181
# 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

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done in b5c3dd8: the five lines are gone.

@felipemello1
felipemello1 force-pushed the felipemello1/vllm-v2/2-sampler-patches branch from 5327270 to b5c3dd8 Compare November 9, 2026 08:49
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review. b5c3dd8 drops the closure-identity asserts, as you suggested; the new_importer assert stays.

@claude

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 39s —— View job


Approve -- please address the items before merging: 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 -- 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. The new_importer assert at line 175 still checks that every vLLM importer gets the PyTorch version.
  • I re-read batch_invariance.py at HEAD. The sys.modules rebind loop (lines 88-98) is the same as in the last review and has no new problems.

Must fix

  1. 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:17 has 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.

Felipe Mello added 3 commits November 9, 2026 12:22
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.
@felipemello1
felipemello1 force-pushed the felipemello1/vllm-v2/2-sampler-patches branch from b5c3dd8 to 56b080e Compare November 9, 2026 20:45
@felipemello1

Copy link
Copy Markdown
Contributor Author

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

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 57s —— View job


Approve -- please address the items before merging: 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 -- 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.modules rebind loop in batch_invariance.py:87-98, and the same tests.
  • The callsites survived main's move of the model build out of vllm/. engine.py:231-234 still calls the patch in _setup right after register_to_vllm and the runner selection. generate.py:138-141 calls it right after set_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 name force_logprobs_fn_for_batch_invariance is left in the repo.

Must fix

  1. 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 RuntimeError if vLLM moved a function. f84e91a replaced that check with the sys.modules rebind. 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:17 has 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.

Felipe Mello added 7 commits November 11, 2026 20:58
…] 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.
- 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.
("apply_temperature", vllm_gumbel, generator_apply_temperature),
):
original = getattr(defining_module, name)
for module in list(sys.modules.values()):

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.

This replacement might be too hacky

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.

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.

@wwwjn
wwwjn marked this pull request as ready for review December 2, 2026 00:16
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Dec 2, 2026
@github-actions
github-actions Bot requested a review from pzhan9 December 2, 2026 00:16
@wwwjn

wwwjn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

from claude: @claude review

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 2m 42s —— View job


Request changes: 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: 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_logprobs becomes the trainer's compute_logprobs.
  • apply_temperature becomes logits.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

  1. torchtitan/rl/generator/vllm/batch_invariance.py:88-100 -- @wwwjn's comment: replace the sys.modules scan with explicit assignments to logprob, gumbel and states, and drop the prompt_logprob rebind, which nothing calls (see inline). I suggested the scan two rounds ago, and I'm withdrawing that suggestion.
  2. PR description, Solution item 3: "generate.py ... apply the patch too" no longer matches the diff. generate.py isn't changed. It gets the patch through engine.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:17 has no vLLM issue link. Root-cause fix: under VLLM_BATCH_INVARIANT, vLLM's V2 apply_temperature should 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 RuntimeError check 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 (see rl/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 matches engine.py, which patches whatever the attention backend.
  • The engine.py call-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.

Comment on lines +88 to +100
# 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)

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.

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_temperature

Then 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.

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.

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.

wwwjn added 2 commits December 1, 2026 18:09
…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.
@wwwjn wwwjn changed the title [rl] generator: batch-invariant patches for vLLM's V2 sampler [WIP] [rl] generator: batch-invariant patches for vLLM's V2 sampler Dec 2, 2026
@wwwjn

wwwjn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

from claude: @claude review

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 1m 29s —— View job


Approve -- please address the item before merging (the vLLM TODO at batch_invariance.py:16 needs an upstream issue link): 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 -- 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_logprobs becomes the trainer's compute_logprobs.
  • apply_temperature becomes logits.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.modules scan): resolved. The scan is replaced by explicit rebinds at batch_invariance.py:89-92, and import sys is gone from the module.
  • Keeping prompt_logprob: resolved, my earlier suggestion was wrong. _PREFILL_PARAMS requests prompt_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

  1. 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 (under VLLM_BATCH_INVARIANT, have the V2 apply_temperature and compute_token_logprobs use torch ops) and link it.

Should consider

  • tests/rl/unit_tests/cpu/test_batch_invariance.py:213-214 -- the gumbel allowlist misses a future call made inside gumbel.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.

Comment on lines +213 to +214
# gumbel.py defines apply_temperature but never calls it.
assert unpatched == ["vllm.v1.worker.gpu.sample.gumbel.apply_temperature"]

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.

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
Suggested change
# 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.

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.

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.
@wwwjn wwwjn changed the title [WIP] [rl] generator: batch-invariant patches for vLLM's V2 sampler [rl] generator: batch-invariant patches for vLLM's V2 sampler Dec 2, 2026
@wwwjn

wwwjn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

from claude: @claude review

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 46s —— View job


Approve -- please address the item before merging (the vLLM TODO at batch_invariance.py:16 still needs an upstream issue link): 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 -- 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_logprobs becomes the trainer's compute_logprobs.
  • apply_temperature becomes logits.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)

  • gumbel allowlist in test_vllm_sampler_patch_covers_every_vllm_caller: resolved. batch_invariance.py:94 rebinds gumbel.apply_temperature, and the assert is now unpatched == []. The monkeypatch restore loop at test_batch_invariance.py:202-205 covers gumbel too, because before the patch it holds the original. The fake-module test (:111, :137-138) now registers gumbel. That keeps it from failing on the new import.
  • Description, Solution item 2, now lists the four names and matches the code.

Must fix

  1. 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 RuntimeError check 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.

@wwwjn

wwwjn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

from claude: On the sampler extension point: vLLM 0.33 and 0.34's V2 runner has ModelState.custom_sampler(sampler), which replaces the whole Sampler (and the rejection sampler). It doesn't reach prompt logprobs: PromptLogprobsWorker is built separately and calls prompt_logprob.compute_token_logprobs itself. Using it would also need a TorchTitan ModelState subclass plus copies of the sampler methods that call the two kernels, so the patch stays at the four names until vLLM's batch-invariant mode runs these kernels as torch ops (the TODO).

@tianyu-l tianyu-l 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.

to confirm one thing

Comment on lines +85 to +87
row_temperature = temperature[expanded_idx_mapping]
row_temperature = torch.where(row_temperature == 0.0, 1.0, row_temperature)
logits.div_(row_temperature.unsqueeze(-1))

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.

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.

This branch has not been deployed

No deployments
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.

3 participants