Skip to content

[rl] Run GRPO on Intel XPU through the stock RL path - #5402

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
songhappy:rl-xpu-support
Nov 22, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
songhappy:rl-xpu-support

Conversation

@songhappy

@songhappy songhappy commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Part of the RFC #5401 (GRPO on Intel XPU) to run the stock RL path on XPU; CUDA behavior is unchanged.

torchtitan RL ran only on CUDA: spawned processes got CUDA_VISIBLE_DEVICES, and the generator assumed CUDA's vLLM worker and attention backends. On XPU the generator now keeps TorchTitan's runner and asks for the same attention backend as on CUDA, so trainer and generator run the same kernel. CUDA-only features (CUDA graphs, varlen attention, MLA with a compressed cache, GDN/KDA linear attention, batch-invariant mode) raise a clear error instead of silently running a different path; the RL README's "Run on Intel XPU" section lists them.

On XPU, flex attention also needs vLLM's XPU platform to accept FLEX_ATTENTION (vllm-project/vllm#69044), and the launch environment sets PYTORCH_ALLOC_CONF and PYTORCH_CUDA_ALLOC_CONF to expandable_segments:False.

Tested:

  • CPU unit tests for the device table and the platform checks.
  • On an Intel GPU Max tile: flex_attention matches SDPA, and varlen_attn isn't implemented on XPU (aten::_flash_attention_forward). That's why varlen raises.
  • On ALCF Aurora, 1 node (torch 2.15.0+xpu, vLLM 9f03b510c with that vLLM change): Qwen3-0.6B GRPO trains 5/5 steps, with TorchTitan's runner and flex attention on both trainer and generator.
  • The device-visibility and torch.accelerator changes also ran in our earlier GRPO regression on Aurora, 1-16 nodes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 15, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@songhappy songhappy changed the title [rl] Run GRPO on Intel XPU through the stock RL path [rl] Run GRPO on accelerators other than CUDA through the stock RL path Nov 18, 2026
@songhappy
songhappy marked this pull request as ready for review November 18, 2026 00:27
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 18, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 18, 2026 00:28
@felipemello1

Copy link
Copy Markdown
Contributor

@claude please review

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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


Verdict: 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 -- off CUDA, the PR swaps in vLLM's stock worker and attention backend with no error. Configs it says are unsupported there (Dist-MoE, generator SP, EP with TP > 1, CUDA graphs, batch-invariant mode) still start, then crash partway through generation or give wrong results. They should raise at config time.

What this PR does. It picks the visible-devices env var per device type (CUDA_VISIBLE_DEVICES or ZE_AFFINITY_MASK) for Monarch-spawned procs, and replaces two torch.cuda calls with torch.accelerator. On platforms that aren't CUDA-like, vLLM now uses its own worker ("auto") and its own attention backend instead of TorchTitan's runner and FLEX/CUSTOM backends. CUDA and ROCm behavior is unchanged.

Example. A Qwen3 MoE generator with dist_moe_runtime set and TP 2, run on XPU:

main: TORCHTITAN_WORKER_CLS -> fails at vLLM worker init (CUDA-only runner)
PR:   worker_cls="auto" -> engine starts; set_num_valid_tokens is never called,
      padding rows are routed as real tokens, and an odd-sized eager step hits
      `assert num_tokens % tp == 0` in _dist_moe_num_local_input_tokens.

Must fix

  1. PR description -- the template's "Summary (human-written)" section is missing. Add it.
  2. torchtitan/rl/generator/vllm/engine.py:308-312 -- the switch to the stock worker isn't guarded. Raise ValueError next to validate_ep_token_dispatchers for Dist-MoE, enable_sequence_parallel, EP x TP > 1, and cuda_graph.mode != "NONE" when not current_platform.is_cuda_alike().
  3. torchtitan/rl/generator/vllm/registry.py:103-111 -- the generator silently runs a different attention kernel than the trainer, which breaks batch_invariant bitwise parity. Raise in that mode. Also, the platform choice is split across files, and generate.py:155 still hardcodes the CUDA worker.
  4. tests/rl/unit_tests/cpu/test_provisioner.py -- delete the file. It duplicates test_shutdown.py:446-447 and the test_tools_utils.py parametrized test.

Should consider

  • torchtitan/tools/utils.py:113-114 -- the sentence about nested masks describes behavior the code doesn't use, and its CUDA half looks wrong. Delete it, or state the PBS pre-masked case concretely.
  • tests/unit_tests/cpu/tools/test_tools_utils.py -- the parametrized cuda/xpu case only re-reads the constant table. The unknown-device rejection test is enough.
Details
  • Gate: the problem is real (main hardcodes CUDA_VISIBLE_DEVICES, TorchTitanGPUWorker, and torch.cuda.* in the generator), and the fix sits at the right layer. The torch.accelerator swaps and the env-var table are fine. The problem is only with the fallbacks: CLAUDE.md principle 8 says unsupported configurations raise and don't silently fall back to a different path. Here the silent paths are routing correctness (Dist-MoE padding mask) and trainer/generator numerics (attention kernel).
  • device_type in get_visible_devices_env_var is resolved on the controller at import time. On an accelerator-less controller host it defaults to "cuda", so on such a host the XPU launch depends on the controller seeing XPU. That's fine for the Aurora single-node setup described, but worth knowing for multi-host launches.
  • The total size of the asked-for changes is roughly +15 / -42 LoC (validation block, deleted test file, trimmed comment).

Not verified: whether vLLM's XPU worker at the pinned commit honors enforce_eager=False, and whether TorchTitan's linear-attention (GDN/KDA) backend runs on XPU. I couldn't run on XPU. A maintainer still needs to review.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +308 to +312
# TorchTitan's runner (CUDA graphs, sequence-parallel padding) is
# CUDA-only; elsewhere (e.g. XPU) vLLM uses the platform's worker.
worker_cls=(
TORCHTITAN_WORKER_CLS if current_platform.is_cuda_alike() else "auto"
),

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.

Swapping to "auto" silently drops everything TorchTitanGPUModelRunner does, but nothing rejects the configs that depend on it. The PR description lists them as unsupported off CUDA, yet they still start:

  • Dist-MoE (dist_moe_runtime is not None): set_num_valid_tokens is only called by TorchTitan's runner (worker.py:175). _num_valid_tokens stays at INT32_MAX, so the padding mask is all-false and padded rows get routed as real tokens. With TP > 1 there's also no _pad_for_sequence_parallelism, so _dist_moe_num_local_input_tokens hits assert num_tokens % tp == 0 partway through generation.
  • parallelism.enable_sequence_parallel, or EP > 1 with TP > 1: the round-up-to-TP padding is gone.
  • cuda_graph.mode != "NONE": still passed as enforce_eager=False. The description says XPU needs "NONE", but that's only enforced by the recipe.

Fix (about 10 lines): raise a ValueError in __init__ next to validate_ep_token_dispatchers when not current_platform.is_cuda_alike() and any of those hold. That makes "not covered off CUDA" a clear config-time error instead of a crash or wrong routing at runtime.

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 would mean all the code in https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/generator/vllm/worker.py is not used. Technically this is incorrect, right?

If you don't support certain features, consider erroring out in post_init of config classes.

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.

Reworked: XPU now uses TorchTitan's runner. CUDA-only features (CUDA graphs, varlen) raise at engine init. That's not in post_init, since stock recipes set cuda_graph.mode="FULL" before an XPU recipe can change it.

Comment on lines +103 to +111
if isinstance(
kernel_config, (FlexInnerAttention.Config, VarlenInnerAttention.Config)
):
from vllm.platforms import current_platform

# vLLM's FLEX_ATTENTION and TorchTitan's CUSTOM backend are CUDA-only;
# elsewhere (e.g. XPU) vLLM picks the platform's own backend.
if not current_platform.is_cuda_alike():
return 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.

Returning None here means the generator runs vLLM's own XPU Flash Attention, while the trainer still runs the flex/varlen kernel from the model config. That's a silent switch to a different kernel. Under debug.batch_invariant=True it breaks the trainer/generator bitwise parity that BITWISE_PARITY.md relies on ("the two paths must match op-for-op") with no error.

Fix: raise ValueError when batch-invariant mode is on and the platform isn't CUDA-like, in the same check as the engine.py validation. Also say in the PR that off CUDA the generator's logprobs come from a different attention kernel than the trainer's.

A smaller point: the platform decision is now split between this file and engine.py:311, and generate.py:155 still hardcodes TORCHTITAN_WORKER_CLS while it picks up this backend change. On XPU, standalone generation would get the stock attention backend with the CUDA worker. Put the worker choice next to TORCHTITAN_WORKER_CLS and use it from both engine.py and generate.py.

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 is similar to the other comment -- it silently breaks all the invariants we promise

@songhappy songhappy Nov 20, 2026 •

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.

Fixed: same attention backend as CUDA, so trainer and generator match. Flex works on XPU; varlen raises. GRPO 5/5 on Aurora

Comment thread torchtitan/tools/utils.py Resolved
Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +308 to +312
# TorchTitan's runner (CUDA graphs, sequence-parallel padding) is
# CUDA-only; elsewhere (e.g. XPU) vLLM uses the platform's worker.
worker_cls=(
TORCHTITAN_WORKER_CLS if current_platform.is_cuda_alike() else "auto"
),

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 would mean all the code in https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/generator/vllm/worker.py is not used. Technically this is incorrect, right?

If you don't support certain features, consider erroring out in post_init of config classes.

Comment on lines +103 to +111
if isinstance(
kernel_config, (FlexInnerAttention.Config, VarlenInnerAttention.Config)
):
from vllm.platforms import current_platform

# vLLM's FLEX_ATTENTION and TorchTitan's CUSTOM backend are CUDA-only;
# elsewhere (e.g. XPU) vLLM picks the platform's own backend.
if not current_platform.is_cuda_alike():
return 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 is similar to the other comment -- it silently breaks all the invariants we promise

@songhappy

Copy link
Copy Markdown
Contributor Author

Reworked per review. PTAL @tianyu-l

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 36s —— View job


Verdict: 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 -- the rework fixes the design: XPU now runs TorchTitan's runner and the same attention backend as CUDA. But the new _validate_platform still lets two unsupported XPU configs through: compressed-cache MLA, and batch-invariant mode. Both fixes are a few lines each.

What this PR does. It picks the visible-devices env var per device type (CUDA_VISIBLE_DEVICES / ZE_AFFINITY_MASK) for Monarch-spawned procs, and swaps two torch.cuda calls for torch.accelerator. On XPU, TORCHTITAN_WORKER_CLS points at a new TorchTitanXPUWorker, which wraps vLLM's XPUModelRunner with TorchTitanGPUModelRunner's overrides. Engine init raises off CUDA for cuda_graph.mode != "NONE" and for the varlen (CUSTOM) backend. CUDA and ROCm are unchanged.

Example.

XPU, Qwen3 + FlexInnerAttention, cuda_graph NONE  -> runs (Aurora 5/5 GRPO steps)
XPU, Qwen3 + VarlenInnerAttention                 -> ValueError at engine init
XPU, DeepSeek V3 (MLA, compressed cache)          -> passes validation, then
    TorchTitanMLAPrefillBackend -> varlen_attn -> aten::_flash_attention_forward: not implemented
XPU, debug.batch_invariant=True                   -> runs; NCCL_ALGO pinning is ignored by XCCL

Must fix

  1. torchtitan/rl/generator/vllm/engine.py:111-117 -- compressed-cache MLA also calls varlen but gets past the check. Allow only FLEX_ATTENTION off CUDA.
  2. torchtitan/rl/generator/vllm/engine.py:103-106 -- debug.batch_invariant isn't shown to hold on XPU, so it fails silently. Raise off CUDA.
  3. tests/rl/unit_tests/cpu/test_generator.py:745-766 -- an XPU-only test in the CPU suite that never runs. Delete it.

Should consider

  • tests/rl/unit_tests/cpu/test_generator.py:724-734 -- the test that flex is accepted adds nothing. Trim to one rejection test.
  • torchtitan/rl/actors/monarch/provisioning.py:84 -- the env var comes from the controller's device_type. In multi-host mode, an accelerator-less controller hands XPU workers CUDA_VISIBLE_DEVICES, and the procs silently see every tile.
  • torchtitan/rl/README.md -- the XPU requirements are only written in the PR description: vLLM's XPU platform must accept FLEX_ATTENTION (vllm-project/vllm#69044, which isn't in the pinned vLLM), and you need expandable_segments:False. Put them in the RL README so users can run this path. Add a TODO with the vLLM link where XPU flex depends on it.
  • Title: "accelerators other than CUDA" overstates it. Only XPU gets a worker; any other device falls through to TorchTitanGPUWorker.

Questions

  • torchtitan/rl/_env.py:20-21 sets expandable_segments:True via setdefault. The description says XPU needs False. What fails on XPU with the default? If it fails at startup, the stock path needs an XPU default, or at least a clear error, instead of relying on the user to set an env var.
Details

Earlier automated review, status at HEAD:

  • Missing human-written summary: resolved.
  • Silent switch to vLLM's stock worker (Dist-MoE, SP, EP x TP padding): resolved. TorchTitanXPUModelRunner puts TorchTitanGPUModelRunner ahead of XPUModelRunner in the MRO, so set_num_valid_tokens and _pad_for_sequence_parallelism still run.
  • Silent attention-kernel switch: resolved, because the same backend runs on both sides. The batch-invariant part is still open (must-fix 2).
  • generate.py:155 hardcoded the CUDA worker: resolved, since it reads TORCHTITAN_WORKER_CLS.
  • test_provisioner.py, the parametrized env-var test, and the "Nested" comment: resolved.

@tianyu-l's comments: the worker.py point is resolved, since its code now runs on XPU. On "error out in __post_init__": the author's engine-init placement holds up. VLLMEngine.Config doesn't hold the model config, so it can't check attention. Controller.Config.__post_init__ runs on the controller, whose device_type may not match the generator hosts. And VLLMCudaGraphConfig defaults to "FULL", so a device check in its __post_init__ would reject every stock recipe on XPU before an override could apply. The check sits next to validate_ep_token_dispatchers, which already uses this pattern.

Size of the asked-for changes: about +6 / -30 LoC (validation condition, batch-invariant raise, deleted tests).

Not verified: whether batch_invariant_ops registers on the CUDA key only, and whether TorchTitan's GDN/KDA linear-attention kernels run on XPU (Qwen3.5-style hybrids). I couldn't run on XPU. A maintainer still needs to review.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +111 to +117
# TorchTitan's CUSTOM backend runs varlen_attn, which calls
# aten::_flash_attention_forward: CUDA-only (e.g. not implemented on XPU).
if vllm_attention_backend(model) is AttentionBackendEnum.CUSTOM:
raise ValueError(
f"varlen attention is not supported on {device_type}; use flex attention "
"(FlexInnerAttention) for the generator model."
)

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 only rejects CUSTOM, so the other varlen path gets through. For MLA with a compressed cache (DeepSeek V3, Kimi when batch-invariant mode is off), vllm_attention_backend returns None (registry.py:104-105). That model then runs TorchTitanMLAPrefillBackend, which calls activate_cuda_flash_attention_impl() and varlen_attn (attention/mla.py:192,206). That's the same aten::_flash_attention_forward you found unimplemented on XPU. So the config passes validation and then crashes at the first prefill.

Off CUDA only flex attention is known to work, so allow only that. You'll need to update the match= string in test_varlen_attention_rejected_off_cuda.

Suggested change
# TorchTitan's CUSTOM backend runs varlen_attn, which calls
# aten::_flash_attention_forward: CUDA-only (e.g. not implemented on XPU).
if vllm_attention_backend(model) is AttentionBackendEnum.CUSTOM:
raise ValueError(
f"varlen attention is not supported on {device_type}; use flex attention "
"(FlexInnerAttention) for the generator model."
)
# Off CUDA only flex attention runs: TorchTitan's CUSTOM backend and the
# compressed-MLA prefill both call varlen_attn ->
# aten::_flash_attention_forward, which is CUDA-only (e.g. not on XPU).
if vllm_attention_backend(model) is not AttentionBackendEnum.FLEX_ATTENTION:
raise ValueError(
f"Only flex attention (FlexInnerAttention) is supported on {device_type}; "
"varlen attention and MLA with a compressed cache need CUDA."
)

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +103 to +106
def _validate_platform(config: VLLMEngine.Config, model: Decoder.Config) -> None:
"""Reject what TorchTitan's vLLM path supports only on CUDA (and ROCm)."""
if device_type == "cuda":
return

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.

debug.batch_invariant=True is still accepted off CUDA, but nothing shows it holds there. set_batch_invariance pins the TP all-reduce order only through NCCL_ALGO=allreduce:tree and NCCL_MAX_NCHANNELS=1 (distributed/batch_invariant.py:124-128). XCCL ignores both, so on XPU the generator's TP all-reduce order isn't pinned. Also (unverified), batch_invariant_ops looks like it registers its mm/addmm/log_softmax/mean overrides on the CUDA dispatch key, so they would never run on XPU. In both cases trainer/generator bitwise parity (BITWISE_PARITY.md) breaks with no error.

Unless you've checked parity on XPU, reject it here. The engine already has debug:

def _validate_platform(
    config: VLLMEngine.Config, model: Decoder.Config, *, batch_invariant: bool
) -> None:
    ...
    if batch_invariant:
        raise ValueError(f"debug.batch_invariant is only verified on CUDA, got {device_type}.")

and call it as _validate_platform(config, model, batch_invariant=debug.batch_invariant).

Comment on lines +745 to +766
@pytest.mark.skipif(
not hasattr(vllm_worker, "TorchTitanXPUWorker"),
reason="the XPU worker is defined on XPU only",
)
def test_xpu_worker_builds_torchtitan_runner(monkeypatch):
import vllm.v1.worker.xpu_worker as vllm_xpu_worker
from vllm.v1.worker.xpu_model_runner import XPUModelRunner

runner_cls = vllm_worker.TorchTitanXPUModelRunner
mro = runner_cls.__mro__
assert mro.index(TorchTitanGPUModelRunner) < mro.index(XPUModelRunner)
built = []
monkeypatch.setattr(
vllm_xpu_worker.XPUWorker,
"init_device",
lambda self: built.append(vllm_xpu_worker.XPUModelRunner),
)
worker = object.__new__(vllm_worker.TorchTitanXPUWorker)
worker.use_v2_model_runner = False
worker.init_device()
assert built == [runner_cls]
assert vllm_xpu_worker.XPUModelRunner is XPUModelRunner

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 test never runs in CI. It's in the CPU suite, and it's skipped unless device_type == "xpu", because TorchTitanXPUWorker is only defined on XPU hosts. tests.md says: "Don't put GPU-only tests in CPU-only suites: they never run." The Aurora GRPO run already shows that the XPU worker builds TorchTitan's runner. Delete the test, along with the vllm_worker import it adds at line 42.

Comment on lines +724 to +734
def test_flex_attention_accepted_off_cuda(monkeypatch):
monkeypatch.setattr("torchtitan.rl.generator.vllm.engine.device_type", "xpu")
model = SimpleNamespace(
first_full_attention=SimpleNamespace(
inner_attention=FlexInnerAttention.Config()
),
max_context_length=1024,
)
_validate_platform(
VLLMEngine.Config(cuda_graph=VLLMCudaGraphConfig(mode="NONE")), model
)

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 only checks that a valid config doesn't raise. If the check regressed, you'd get a loud failure on XPU, not a silent one. Four test cases for a ~12-line validator is more than the invariant needs. Drop this one, and consider keeping one rejection test (e.g. the attention check) instead of the attention test plus two parametrized CUDA-graph cases.

def __init__(self, total_gpus: int = 8):
self.total_gpus = total_gpus
self.next_gpu = 0
self.env_var = get_visible_devices_env_var()

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.

The env var is picked from the controller's device_type, and the masks are applied on the worker hosts. In multi-host mode (host_meshes is not None), a controller without an accelerator resolves device_type to "cuda" (tools/utils.py:103). XPU workers would then get CUDA_VISIBLE_DEVICES, which Level Zero ignores. Every trainer and generator proc would see all tiles, and nothing would report an error.

If XPU controllers can run on a non-accelerator node (e.g. a login node), fix it. One option is to set both CUDA_VISIBLE_DEVICES and ZE_AFFINITY_MASK in allocate, which also removes the lookup table. You'd need to confirm that vLLM's XPU platform ignores CUDA_VISIBLE_DEVICES (unverified). If the controller always runs on an accelerator node, say so in the docstring.

@tianyu-l

Copy link
Copy Markdown
Contributor

@songhappy could you fix new comments from claude bot? thanks!

tianyu-l pushed a commit that referenced this pull request Nov 21, 2026
## Summary (human-written)

Part of the RFC #5401 (GRPO on Intel XPU). RL recipes on main can only
be launched on SLURM clusters, so PBS systems like Aurora had no
supported launcher.

`PBSLauncher` adds one next to `SlurmLauncher`, on the launcher
interface from #5572, using Monarch's `PBSJob`. It only handles what PBS
does differently: it submits with `qsub -V`, since PBS doesn't pass the
submit environment, and it copies the job state Monarch writes to a
per-job path, since PBS has no `--chdir` (removable once
meta-pytorch/monarch#5414 lands). The README's PBS section shows a
launch recipe and the site settings PBS clusters need: `python_exe` as a
script that loads the environment, and a short `TMPDIR`
(meta-pytorch/monarch#5415).

Tested:
- `test_launcher.py`: the job is built correctly, hosts are acquired,
invalid `pbs_args` are rejected.
- On ALCF Aurora (PBS Pro, Cray PALS) with current Monarch main: a
1-node job submits, the controller attaches, and with #5402 Qwen3-0.6B
GRPO trains 5/5 steps through `PBSLauncher`.
- Earlier 2-node jobs placed the trainer and generators on the planned
nodes and tiles.

Needs a Monarch with meta-pytorch/monarch#5273 (`PBSJob` without
`rank_env`).
XPU keeps TorchTitan's vLLM runner and attention backend; what only CUDA supports raises at engine init.
@songhappy songhappy changed the title [rl] Run GRPO on accelerators other than CUDA through the stock RL path [rl] Run GRPO on Intel XPU through the stock RL path Nov 22, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 12s —— View job


Verdict: Approve (earlier must-fix items resolved; two should-consider items left) -- 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 -- every must-fix from the last review is resolved at b2ffe03, and the CUDA path is unchanged: _validate_platform returns early when device_type == "cuda", which includes ROCm. Two items are left to consider before merging.

What this PR does. Monarch-spawned procs get their device mask from get_visible_devices_env_var() (CUDA_VISIBLE_DEVICES / ZE_AFFINITY_MASK). Two torch.cuda calls become torch.accelerator calls. On XPU, TORCHTITAN_WORKER_CLS points at TorchTitanXPUWorker, which runs TorchTitanGPUModelRunner's overrides on vLLM's XPUModelRunner. Off CUDA, engine init raises for CUDA graphs, any attention backend other than flex, debug.batch_invariant, and GDN/KDA layers.

Example.

XPU, Qwen3 + FlexInnerAttention, cuda_graph NONE     -> runs (Aurora, 5/5 GRPO steps)
XPU, DeepSeek V3 (compressed-cache MLA)              -> ValueError "Only flex attention ..."
XPU, debug.batch_invariant=True                      -> ValueError at engine init
XPU, Qwen3.5-style GDN hybrid                        -> ValueError at engine init
XPU, launched without the two allocator env vars     -> expandable_segments:True (see below)

Resolved since the last review

  1. Compressed-cache MLA got past the check: resolved. Off CUDA, only FLEX_ATTENTION is allowed now (engine.py:119).
  2. debug.batch_invariant accepted off CUDA: resolved (engine.py:124).
  3. XPU-only test in the CPU suite: resolved, it's deleted.
  • Controller/worker device mismatch: the docstring now states that the controller runs on a node with the same accelerator (provisioning.py:79-81).
  • XPU requirements and vLLM TODO: added to the RL README and engine.py:118. The title is narrowed to XPU.

Should consider

  • torchtitan/rl/README.md:268 -- the stock env defaults still set expandable_segments:True on XPU. If that fails silently, enforce the setting at startup instead of only documenting it (inline comment).
  • tests/rl/unit_tests/cpu/test_generator.py:731 -- of the four rejection cases, only batch_invariant guards a silent failure. Keep that one and drop the other three, along with _GDN_MODEL_CONFIG (inline comment).
Details
  • I checked the new GDN/KDA check: model.layers[*].attention is the same pattern registry.py:276 uses. A DeepEP or HybridEP dispatcher on XPU isn't rejected, but it fails at build time, so the error is loud.
  • TORCHTITAN_WORKER_CLS is resolved on the generator host, so it picks the generator's device type, not the controller's.
  • @tianyu-l's earlier comments (the stock worker bypassing worker.py, and the silent attention switch) are resolved: the XPU runner subclasses TorchTitanGPUModelRunner, and the attention backend matches the trainer's.

Not verified: what fails on XPU with expandable_segments:True, and whether the XPU worker's MRO behaves at the pinned vLLM. I couldn't run on XPU. This touches core tools/utils.py, so a maintainer still needs to review.

Comment thread torchtitan/rl/README.md
Comment on lines +268 to +270
(vllm-project/vllm#69044). Set `PYTORCH_ALLOC_CONF=expandable_segments:False`
and `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False` in the launch
environment: expandable segments invalidate the memory oneCCL registers.

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 makes the stock path on XPU depend on the user setting two env vars by hand. If they forget, apply_env_defaults() (rl/_env.py:20-21, which also runs in every spawned proc through _preimport_torch) uses setdefault to turn on expandable_segments:True, and that's the setting this paragraph says breaks oneCCL's registered memory.

What does that failure look like? If it's a crash at the first collective, documenting it is enough. If it can hang, or give wrong collective results with no error, the stock path should enforce it instead. The smallest version is a startup check off CUDA, e.g. in _validate_platform: raise ValueError when "expandable_segments:True" is in PYTORCH_ALLOC_CONF. The trainer would need the same check. Another way is to have PerHostProvisioner.allocate return the XPU allocator setting together with ZE_AFFINITY_MASK, since it already builds the per-device launch env.

Comment on lines +731 to +766
@pytest.mark.parametrize(
("model", "engine_config", "batch_invariant", "match"),
[
(
_MODEL_CONFIG,
VLLMEngine.Config(cuda_graph=VLLMCudaGraphConfig(mode="NONE")),
False,
"Only flex attention",
),
(
_FLEX_MODEL_CONFIG,
VLLMEngine.Config(cuda_graph=VLLMCudaGraphConfig(mode="FULL")),
False,
"cuda_graph.mode='NONE'",
),
(
_FLEX_MODEL_CONFIG,
VLLMEngine.Config(cuda_graph=VLLMCudaGraphConfig(mode="NONE")),
True,
"batch_invariant",
),
(
_GDN_MODEL_CONFIG,
VLLMEngine.Config(cuda_graph=VLLMCudaGraphConfig(mode="NONE")),
False,
"GDN/KDA",
),
],
)
def test_cuda_only_features_rejected_off_cuda(
monkeypatch, model, engine_config, batch_invariant, match
):
monkeypatch.setattr("torchtitan.rl.generator.vllm.engine.device_type", "xpu")
with pytest.raises(ValueError, match=match):
_validate_platform(engine_config, model, batch_invariant=batch_invariant)

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.

Last round suggested trimming this to one rejection test; it now has four cases instead. Three of them guard regressions that would fail loudly on XPU anyway: varlen hits aten::_flash_attention_forward not implemented, CUDA graphs fail at capture, and GDN/KDA fail in the kernels. Only batch_invariant would break silently, since parity is lost with no error.

Keep the batch_invariant case and drop the other three. That also removes _GDN_MODEL_CONFIG and its GDN.Config.__new__(GDN.Config) construction, which skips the config's required fields.

@tianyu-l
tianyu-l merged commit a75b09a into pytorch:main Nov 22, 2026
22 of 25 checks passed
felipemello1 added a commit that referenced this pull request Nov 24, 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. -->

## Agent details

**TLDR:** Trainer microbatches now go over Monarch RDMA by default:
`async_loop.batcher.rdma_min_tensor_bytes` goes from `None` (by value)
to `1024`. On one host, a 1 GiB microbatch takes 0.55 s by RDMA over
ibverbs vs 1.9 s by value, and every read was byte-exact.
`rdma_min_tensor_bytes=None` keeps the by-value message.

**Problem**
1. The RDMA path for trainer microbatches is opt-in: by default each
trainer rank gets its column of the batch inside the `forward_backward`
RPC message.
2. By value, the controller pickles every microbatch, Monarch copies it,
and the rank unpickles it.
3. That grows with the microbatch: 16 MiB takes 21 ms per call by value
vs 8.4 ms by RDMA, and 1 GiB 1.9 s vs 0.55 s (ibverbs, one host).

**Solution**
1. `Batcher.Config.rdma_min_tensor_bytes` defaults to 1024: tensors of
at least 1 KiB stay in the batcher as RDMA buffers; smaller ones (token
counts) stay in the message.
2. If Monarch has no RDMA backend (`monarch.rdma.get_rdma_backend() ==
"none"`), `MonarchActorSystem.spawn_batcher` raises and says to set
`rdma_min_tensor_bytes=None`. Otherwise Monarch uses ibverbs where the
host has it, else TCP (Monarch's TCP fallback is on by default).
3. RDMA with trainer pipeline parallelism still raises. The error now
says to set `rdma_min_tensor_bytes=None`, and the PP=2 `alphabet_sort`
test recipe sets it.
4. Every RL recipe sets `preprocess_microbatch_groups_lazily=True` (they
already turn accelerator graphs off), so each trainer rank reads its
next microbatches while it trains on the current one.
5. `None` sends microbatches by value, as before.

**Results**

Stress, one host (H100 devserver, CPU tensors, Monarch 0.7): the owner
registers a fresh microbatch with random bytes each step, a reader
process reads it, the owner drops the previous one. 5 steps per size,
medians of steps 2-5. Every read was byte-exact. Read = reader side,
fresh destination included. Call = one actor call, RDMA vs the same
microbatch by value:
```text
per microbatch   read, ibverbs   read, TCP   call: ibverbs / TCP / by value
1023 B           0.12 ms         0.19 ms     2.5 / 3.1 / 2.7 ms     (below 1 KiB: by value)
1 KiB            7.8 ms          0.5 ms      11 / 2.9 / 3.2 ms
1 MiB            6.4 ms          1.9 ms      12 / 7.8 / 5.5 ms
16 MiB           3.6 ms          15 ms       8.4 / 19 / 21 ms
256 MiB          83 ms           449 ms      0.17 / 0.49 / 0.56 s
1 GiB            334 ms          1.6 s       0.55 / 1.8 / 1.9 s
```
- 4 readers, 256 MiB each, at once: 81 ms over ibverbs (13 GB/s
together), 630 ms over TCP.
- Registering (in the batcher, at pack time) pins memory over ibverbs:
26 ms at 256 MiB, 264 ms at 1 GiB; under 1 ms over TCP.
- Up to 1 MiB, an ibverbs read costs 6-8 ms, a few ms more than by
value.

GPU, Qwen3-0.6B, H100, batch invariant, lockstep, trainer DP 1 + one TP
1 generator (2 GPUs), 4,096-token microbatches, 5 steps:
```text
                                    loss/mean, step 5   bit_wise/logprob_diff/max   read_microbatches/max, steps 1-5
None (by value)                     0.00061             0                           -
1024 (default), ibverbs             0.00061             0                           126, 36, 12, 19, 21 ms
1024, TCP                           0.00061             0                           57, 15, 10, 14, 17 ms
```
- `loss/mean` is bitwise equal across the three runs at all 5 steps.
Step 1 includes RDMA setup.
- TCP = `MONARCH_RDMA_DISABLE_IBVERBS=1
MONARCH_RDMA_ALLOW_TCP_FALLBACK=1`. The `None` run is from an earlier
build of this change; `None` runs none of the changed code.
- Measured on an earlier version of this PR, before main moved the RDMA
code behind the actor system. Not re-run since.

End to end at recipe size: H100, Qwen3-0.6B, batch invariant, lockstep,
10 steps, one TP 1 generator, 4,096-token microbatches (0.16 MB).
Measured on the opt-in version of this path:
```text
forward_backward                 trainer DP 1   trainer DP 2
by value                         1.393 s        0.909 s
RDMA, reads before compute       1.414 s        0.910 s
RDMA, reads overlapped (lazy)    1.399 s        0.932 s
```
- The rows differ by run-to-run noise.
- At 5.2 GB per step (CPU Monarch, one host, TCP, 4 ranks, reads
included): 9.1-11.1 s by value vs 3.3-4.1 s by RDMA.

You may ask:
- **Why not probe ibverbs at startup?** A failed registration leaves
Monarch's RDMA manager dead in its process, so a probe needs a child
process. Like TorchStore, we only check that Monarch has an RDMA
backend.
- **What about a host that lists ibverbs devices it can't use?** It
fails at the first batch: set `rdma_min_tensor_bytes=None`, or
`MONARCH_RDMA_DISABLE_IBVERBS=1` for TCP in every process (weight sync
included). The docstring says so.
- **Why 1 KiB?** Registering a buffer costs far more than sending a few
bytes, and `RDMABuffer` rejects empty tensors.
- **Isn't RDMA slower for small microbatches?** Per call, by a few ms
(stress table, 1 KiB-1 MiB). End to end at recipe size it is within
noise (table above).

NOTE:
- Builds on main's #6199 (torchmonarch 0.8.0, which removed the
CUDA-context workaround).
- The RL GPU CI now takes the RDMA path (ibverbs or TCP, whichever its
containers have).
- A config that passes its own `TrainingConfig` without
`preprocess_microbatch_groups_lazily=True` reads each microbatch before
compute, ~6-8 ms each over ibverbs at small sizes.
- Lazy on vs off at an earlier head of this PR (6aed435), Qwen3-0.6B
alphabet_sort, trainer TP 1 + one TP 1 generator, 4,096-token
microbatches, 8 steps, RDMA over TCP: `forward_backward` median over
steps 3-8 is 1.84 s with lazy and 1.64 s without. Per microbatch it is
353 vs 396 ms. The two runs sampled different rollouts (3-6 microbatches
per step), so these differences are noise. Lazy can only overlap the
RDMA reads and the input preprocessing, which take 30-60 ms per step
here (~2-4% of `forward_backward`). A lockstep, batch-invariant rerun
was not done: another job took the GPUs.
- Not tested on more than one host, on Intel XPU (#5402, GRPO on XPU) or
on PBS clusters (#5403, the PBS launcher). If the first batch fails
there, set `rdma_min_tensor_bytes=None`.

**Test plan**
- `pytest tests/rl/unit_tests/cpu
tests/unit_tests/cpu/components/test_renderer.py
tests/unit_tests/cpu/config` (repo root, Monarch 0.8.0): 965 passed, 7
skipped. With Verifiers 0.4.0 installed: 1049 passed, 1 skipped. Same
counts as main (a7887db). The skips are skipped on main too.
- `test_rdma_microbatch.py`: by value with `None`; 4 rank processes read
their columns byte-exact over real Monarch TCP across 3 released
batches.
- At an earlier head of this PR (6aed435): every zero-argument RL
recipe that builds here (54 of 56; the other 2 need a torchao nightly or
sglang), rebuilt and validated with `__post_init__` as `ConfigLoader`
does: none fails on RDMA, and all end with lazy preprocessing on and
accelerator graphs off.
- `test_batcher_actor.py`: the batcher process on the default config
sends `input` by RDMA and token counts by value.
- In-process batchers in the tests set `rdma_min_tensor_bytes=None`:
only an actor system provides RDMA registration.
- The stress script and GPU runs above (earlier heads of this PR).

Co-authored-by: Felipe Mello <[email protected]>
felipemello1 added a commit that referenced this pull request Nov 24, 2026
… vLLM generator

One conflict, in torchtitan/rl/generator/vllm/worker.py: the PR adds
TorchTitanEagleProposer and _alias_draft_weight after TorchTitanGPUWorker;
main (#5402) adds the XPU worker block at the same spot. Both kept: the
drafter classes first, then main's `if device_type == "xpu":` block.
songhappy added a commit to songhappy/torchtitan that referenced this pull request Nov 30, 2026
…orch#5404 closed

pytorch#5402 rebased and made device-generic; pytorch#5403 is now PBSLauncher on upstream's scheduler launchers; the allocator and vLLM-eager settings move to the launcher and recipe.
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