Repository navigation
[rl] Run GRPO on Intel XPU through the stock RL path - #5402
Conversation
|
|
5923c68 to
18acab4
Compare
18acab4 to
3873c4e
Compare
|
@claude please review |
|
Claude finished @felipemello1's task in 2m 48s —— View job Verdict: Request changes -- review |
There was a problem hiding this comment.
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
- PR description -- the template's "Summary (human-written)" section is missing. Add it.
torchtitan/rl/generator/vllm/engine.py:308-312-- the switch to the stock worker isn't guarded. RaiseValueErrornext tovalidate_ep_token_dispatchersfor Dist-MoE,enable_sequence_parallel, EP x TP > 1, andcuda_graph.mode != "NONE"whennot current_platform.is_cuda_alike().torchtitan/rl/generator/vllm/registry.py:103-111-- the generator silently runs a different attention kernel than the trainer, which breaksbatch_invariantbitwise parity. Raise in that mode. Also, the platform choice is split across files, andgenerate.py:155still hardcodes the CUDA worker.tests/rl/unit_tests/cpu/test_provisioner.py-- delete the file. It duplicatestest_shutdown.py:446-447and thetest_tools_utils.pyparametrized 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 parametrizedcuda/xpucase 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, andtorch.cuda.*in the generator), and the fix sits at the right layer. Thetorch.acceleratorswaps 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_typeinget_visible_devices_env_varis 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.
| # 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" | ||
| ), |
There was a problem hiding this comment.
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_tokensis only called by TorchTitan's runner (worker.py:175)._num_valid_tokensstays atINT32_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_tokenshitsassert num_tokens % tp == 0partway 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 asenforce_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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
this is similar to the other comment -- it silently breaks all the invariants we promise
There was a problem hiding this comment.
Fixed: same attention backend as CUDA, so trainer and generator match. Flex works on XPU; varlen raises. GRPO 5/5 on Aurora
| # 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" | ||
| ), |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
this is similar to the other comment -- it silently breaks all the invariants we promise
b2bf6f0 to
722e08d
Compare
|
Reworked per review. PTAL @tianyu-l |
|
@claude review |
There was a problem hiding this comment.
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
torchtitan/rl/generator/vllm/engine.py:111-117-- compressed-cache MLA also calls varlen but gets past the check. Allow onlyFLEX_ATTENTIONoff CUDA.torchtitan/rl/generator/vllm/engine.py:103-106--debug.batch_invariantisn't shown to hold on XPU, so it fails silently. Raise off CUDA.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'sdevice_type. In multi-host mode, an accelerator-less controller hands XPU workersCUDA_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 acceptFLEX_ATTENTION(vllm-project/vllm#69044, which isn't in the pinned vLLM), and you needexpandable_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-21setsexpandable_segments:Trueviasetdefault. The description says XPU needsFalse. 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.
TorchTitanXPUModelRunnerputsTorchTitanGPUModelRunnerahead ofXPUModelRunnerin the MRO, soset_num_valid_tokensand_pad_for_sequence_parallelismstill 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:155hardcoded the CUDA worker: resolved, since it readsTORCHTITAN_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.
| # 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." | ||
| ) |
There was a problem hiding this comment.
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.
| # 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." | |
| ) |
| 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 |
There was a problem hiding this comment.
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).
| @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 |
There was a problem hiding this comment.
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.
| 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 | ||
| ) |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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.
|
@songhappy could you fix new comments from claude bot? thanks! |
## 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.
722e08d to
b2ffe03
Compare
|
@claude review again |
There was a problem hiding this comment.
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
- Compressed-cache MLA got past the check: resolved. Off CUDA, only
FLEX_ATTENTIONis allowed now (engine.py:119). debug.batch_invariantaccepted off CUDA: resolved (engine.py:124).- 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 setexpandable_segments:Trueon 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, onlybatch_invariantguards 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[*].attentionis the same patternregistry.py:276uses. A DeepEP or HybridEP dispatcher on XPU isn't rejected, but it fails at build time, so the error is loud. TORCHTITAN_WORKER_CLSis 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 subclassesTorchTitanGPUModelRunner, 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.
| (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. |
There was a problem hiding this comment.
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.
| @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) | ||
|
|
There was a problem hiding this comment.
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.
## 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]>
… 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.
…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.
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 setsPYTORCH_ALLOC_CONFandPYTORCH_CUDA_ALLOC_CONFtoexpandable_segments:False.Tested:
flex_attentionmatches SDPA, andvarlen_attnisn't implemented on XPU (aten::_flash_attention_forward). That's why varlen raises.torch.acceleratorchanges also ran in our earlier GRPO regression on Aurora, 1-16 nodes.