Skip to content

[RL] Enable batch-invariant FlexAttention on ROCm - #5657

Open
rishisinhanj wants to merge 9 commits into
pytorch:mainfrom
rishisinhanj:rocm-flex-batch-invariance-pr
Open

rishisinhanj wants to merge 9 commits into
pytorch:mainfrom
rishisinhanj:rocm-flex-batch-invariance-pr

Conversation

@rishisinhanj

@rishisinhanj rishisinhanj commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • use compiled FlexAttention for ROCm batch-invariant trainer runs while preserving the existing eager fallback for ordinary deterministic ROCm runs
  • allow ROCm batch invariance only when trainer and generator attention layers use FlexAttention
  • align vLLM's paged Flex mask with the trainer through a request-independent page lookup and request-ownership mask

Motivation

TorchTitan currently rejects all ROCm batch-invariant RL configurations and uses eager FlexAttention for deterministic ROCm training. Eager trainer attention cannot match vLLM's compiled paged FlexAttention bit-for-bit.

The original gfx950 compiled-Flex nondeterminism reproduces on the ROCm 7.2 nightly stack. On the tested ROCm 10.0 and 10.1 nightly stacks, the same emitted Triton forward and backward kernels were bitwise stable for 300 iterations.

After enabling compiled trainer FlexAttention, the remaining one-BF16-ULP difference was localized to vLLM's request-indexed physical_to_logical[request, physical_page] lookup. Q/K/V and reconstructed KV-cache contents were already identical. On gfx950, the request-indexed lookup changed the generated reduction order even though the boolean mask was equivalent. The ROCm batch-invariant path instead derives one logical index per physical page and keeps request ownership in an int64 bitmask. This vLLM integration is tracked in vllm-project/vllm#66460.

Standalone generation and the RL engine now share the same process-wide vLLM runtime configuration.

CUDA keeps vLLM's stock mapping because TorchTitan's TestBitwiseParityFlex already passes there.

Running ROCm batch invariance

Use the rl_grpo_qwen3_0_6b_flex_batch_invariant recipe as the base and disable vLLM graph replay for the ROCm run:

config = rl_grpo_qwen3_0_6b_flex_batch_invariant()
config.generator = dataclasses.replace(
    config.generator,
    engine=dataclasses.replace(
        config.generator.engine,
        cuda_graph=dataclasses.replace(
            config.generator.engine.cuda_graph,
            mode="NONE",
        ),
    ),
)

Launch the wrapper recipe in a ROCm 10.0 environment with a vLLM build compatible with the installed Torch:

export HIP_VISIBLE_DEVICES=0,1,2,3
export VLLM_BATCH_INVARIANT=1
export HF_ASSETS_PATH=/path/to/Qwen3-0.6B

python3 -m torchtitan.rl.train \
  --module <module-containing-the-wrapper> \
  --config <wrapper-function> \
  --output-dir outputs/rocm_flex_batch_invariant

Run at least two optimizer steps and verify that each training line reports bit_wise/logprob_diff/max: 0. The second step checks parity after the optimizer update and trainer-to-generator weight transfer.

Validation

Tested on gfx950 (AMD Instinct MI350X) with Torch 2.16.0.dev20261018+rocm10.0, Triton 3.9.0+gitfc8d31a5, and vLLM 0.32.0rc1.dev369+g1b2a66639.rocm100.

A two-step Qwen3-0.6B TitanRL run on the rebased branch completed with:

Train | Step: 1 ... bit_wise/logprob_diff/max: 0
Train | Step: 2 ... bit_wise/logprob_diff/max: 0

Earlier 25-step runs also produced zero maximum logprob difference for Qwen3-0.6B, 1.7B, 4B, and 8B:

Latest focused CPU tests: 31 passed.

Scope

  • plain FlexAttention models only; ROCm varlen remains unsupported
  • requires a PyTorch build tagged for ROCm 10.0 or newer; validated on gfx950 with ROCm 10.0 userspace
  • the ownership mask supports at most 64 concurrent requests
  • ROCm Flex batch invariance currently requires cuda_graph.mode="NONE"; graph replay is tracked in [RL][ROCm] Support vLLM graph replay with batch-invariant FlexAttention #5725

Related: #3960

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

pytorch-bot Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rocm
  • ciflow/rl
  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@pytorch-bot

pytorch-bot Bot commented Oct 28, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rocm
  • ciflow/rl

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@rishisinhanj
rishisinhanj force-pushed the rocm-flex-batch-invariance-pr branch 3 times, most recently from a50276e to 4147255 Compare October 30, 2026 06:02
Comment thread torchtitan/rl/controller/controller.py Outdated
)
for attention in attention_configs
):
raise ValueError(

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.

comment in the code why we need to raise. what happens if we don't

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.

Added

"for every trainer and generator attention layer."
)
if not (
self.trainer.debug.deterministic

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 user needs to set 4 flags.... I think we can use a single flag instead, then here we force these four flags to true, and log a warning or info.

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.

The code already provides a user-facing switch by sharing a batch-invariant deterministic DebugConfig. I think keeping one flag could break some of the existing code by mutating the existing config.

Comment thread torchtitan/rl/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.

is it right to remove these two 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.

Yes, this is intentional: the setup moved into the shared VLLMEngine.configure_runtime path, while generate.py still calls set_batch_invariance immediately before it.


@staticmethod
def _setup(
def configure_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.

intended name change?

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.

Yeah, intended. The method is now shared with standalone generate.py, so it is public rather than an externally called private helper. This keeps standalone generation and the RL engine on same runtime path, but can change back if its cleaner.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
"""Process-wide vLLM setup before the engine build: register the TorchTitan model
and config parser with vLLM, and select vLLM's model runner."""
"""Configure process-wide vLLM state before building an engine."""
attention = model.first_full_attention

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.

these lines are rocm only logic. so wrap them in a separate function.

do we know why cuda graph mode doesn't work for batch invariance? it'd be ideal if you file a bug and add a todo in the check.

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.

On a second thought, do you think this page mapping is also useful for other hardware platforms?

Maybe we can make it a generic flag.

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.

I moved the ROCm-specific setup into _configure_rocm_flex_batch_invariance(). CUDA graph support is tracked in [#5725 (https://github.com//issues/5725)

as for your second comment, CUDA has parity already so this should be ROCm only.

@felipemello1

Copy link
Copy Markdown
Contributor

@claude please review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 4m 30s —— View job


Request changes -- review posted with inline comments.

@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 core fix replaces a private vLLM method with an unexplained, boolean-equivalent mask, with no upstream issue. On top of that, the determinism gate switches on batch_invariant instead of the ROCm version the PR shows is the real cause.

What this PR does. On ROCm it lifts the blanket ban on RL batch invariance when every trainer and generator attention layer uses FlexAttention. In batch-invariant mode the ROCm trainer runs compiled Flex instead of eager (set_determinism). On the generator side it monkeypatches vLLM's FlexAttentionMetadata.get_paged_mask_mod with a request-independent page lookup plus an int64 ownership bitmask, capped at 64 concurrent requests. Standalone generate.py now shares the engine's renamed configure_runtime, which is public because a second module now calls it.

Example.

ROCm, recipe rl_grpo_qwen3_0_6b_flex_batch_invariant
before: Controller.Config -> ValueError "batch_invariant mode is not supported on ROCm"
after:  ROCm 10.x + cuda_graph.mode="NONE"   -> runs, compiled trainer Flex, patched vLLM mask, logprob_diff 0
        ROCm 10.x + default mode="FULL"      -> ValueError, but only inside the generator actor at engine build
        ROCm 7.2                              -> passes validation, runs compiled Flex (nondeterministic per the PR)
        ROCm + varlen (controller)            -> ValueError "requires FlexAttention"

Must fix

  1. torchtitan/rl/generator/vllm/batch_invariance.py:99 -- private vLLM method replaced; the old and new mask_mods return identical booleans, so the 1-ULP root cause (codegen or block-mask?) isn't explained. No TODO or vLLM issue, and no answer to why CUDA doesn't need it.
  2. torchtitan/distributed/utils.py:161 -- gating on batch_invariant instead of the ROCm version allows nondeterministic compiled Flex on ROCm 7.2. Gate on the version and raise at config time below the validated version.
  3. Unanswered maintainer comments from @yuankaichen-amd: "intended name change?" (engine.py:219), "is it right to remove these two lines?" (generate.py:141), and "is this page mapping useful on other hardware?" (overlaps with 1). For the record, the generate.py removal is correct, since configure_runtime now sets VLLM_USE_V2_MODEL_RUNNER and generate() calls set_batch_invariance first. The rename to public is justified by the cross-module call. Please reply on those threads.

Should consider

  • torchtitan/rl/generator/vllm/engine.py:109 -- the cuda_graph.mode check belongs in controller config validation, and cuda_graph_mode: str should use the Literal type.
  • torchtitan/rl/generator/vllm/engine.py:106 -- silent return for ROCm + batch-invariant + non-Flex in standalone generation; raise instead.
  • torchtitan/rl/controller/controller.py:476 -- re-validates only a subset after overrides.
  • torchtitan/rl/generator/vllm/batch_invariance.py:43 -- runtime request-limit check can't fire; delete.
  • torchtitan/rl/generator/vllm/batch_invariance.py:119 -- idempotency sentinels are unnecessary.
  • tests/rl/unit_tests/cpu/test_generator.py:625 -- mock-only test; validation tests are misplaced in test_policy_loss_configs.py.
  • torchtitan/rl/generator/vllm/engine.py:282 -- the comment still says "registered by register_to_vllm in _setup"; update it to configure_runtime.

Questions

  • Under CUDA graph replay, the patched mask_mod closes over fresh tensors (physical_to_logical.amax, physical_request_mask) computed per build, not persistent buffers. Is that part of why #5725 needs mode="NONE", beyond the recompile-limit failure described there?
Details
  • Correctness of the bitmask mask: given vLLM's physical_to_logical (rows filled with -1 and scattered from the valid block-table entries), a shared prefix-cache page always maps to the same logical index, so amax(dim=0) plus the ownership bit equals the original physical_to_logical[q_req, block] >= 0 test. sum over distinct powers of two equals OR, and bit 63 doesn't overflow. Nothing asserts that invariant, so if vLLM ever shares a physical block at different logical positions, the mask would be silently wrong.
  • batch_invariant is only reachable from RL (Trainer.Config.__post_init__ rejects it for SFT), so the set_determinism change only affects ROCm RL trainers.
  • Smaller alternative for 1/2: if the page mapping is valid on all hardware, apply it whenever Flex + batch-invariant is on, delete _configure_rocm_flex_batch_invariance's hardware branch, gate set_determinism's eager fallback on the ROCm version, and do all checks in Controller.Config. That is roughly -30 lines from the current diff.

Not verified: the 1-ULP root cause, determinism on ROCm 7.2 vs 10.x, and the graph-replay interaction. These need a GPU run, and I couldn't read vLLM's upstream get_paged_mask_mod source in this environment. A maintainer still needs to review, since this touches torchtitan/distributed/utils.py.


return global_page_mask_mod

FlexAttentionMetadata.get_paged_mask_mod = get_paged_mask_mod

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 replaces vLLM's FlexAttentionMetadata.get_paged_mask_mod (a private upstream method) with a full re-implementation. Two problems:

  1. The root cause isn't explained. The old and new mask_mods return the same booleans for every (q, kv) pair; the only difference is the gather physical_to_logical[q_req, block] vs. physical_to_logical[block] plus a bitmask test. A boolean-identical mask that changes attention output by 1 BF16 ULP points at Inductor/Triton codegen or block-mask construction (full vs. partial blocks) rather than at the lookup itself. Without that explanation we can't tell whether this fix holds up when vLLM or Triton changes, or whether it only hides the problem for the tested shapes. It's also unclear why CUDA Flex batch invariance reaches 0 diff with the upstream mask but ROCm doesn't (this is yuankaichen-amd's unanswered "useful for other hardware?" question).
  2. It's an upstream patch with no TODO or issue. Per the repo rules, a workaround for a vLLM gap needs a TODO with a vLLM issue link, and the fix should be proposed upstream (e.g. a request-independent paged mask in vLLM's Flex backend). If it's correct on all hardware, the simplest torchtitan-side form is to apply it whenever Flex + batch-invariant is on and drop the ROCm-only branch.

At minimum, add the TODO and upstream issue, and put the codegen-level root cause in the PR description.

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.

Added a TODO linking vllm-project/vllm#66460, and documented the observed gfx950 reduction-order difference despite an equivalent boolean mask. CUDA keeps the upstream mapping because parity already passes there; this override remains scoped to ROCm Flex batch-invariant mode.

# Keep the conservative eager fallback for normal deterministic ROCm
# runs. Batch-invariant mode requires compiled FlexAttention to match
# vLLM's compiled Flex path.
if torch.version.hip is not None and not debug_config.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.

The eager fallback exists because compiled Flex was nondeterministic on ROCm. The PR description says that is still the case on ROCm 7.2 and fixed on ROCm 10.x, but this condition switches on batch_invariant instead of the ROCm version. So a batch-invariant RL run on ROCm 7.2 now passes config validation and runs compiled Flex, which the PR's own investigation shows is nondeterministic. Meanwhile a plain deterministic run on ROCm 10 still pays for eager Flex even though compiled Flex is stable there.

The condition should follow the actual cause. Keep the eager fallback only for ROCm versions where compiled Flex is known to be nondeterministic, and in Controller.Config._validate_batch_invariance raise ValueError for ROCm batch invariance below the validated version. The batch_invariant special case here then disappears.

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.

Partially addressed: Controller.Config now rejects batch-invariant RL below ROCm 10, blocking the unsafe ROCm 7.2 path. Ordinary deterministic ROCm runs intentionally retain the conservative eager fallback; only batch-invariant runs use compiled Flex to match vLLM.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
return

validate_flex_page_mapping_request_limit(max_num_seqs)
if cuda_graph_mode != "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.

cuda_graph.mode is a static config value, but this check only fires inside the generator actor at engine build, after actors are spawned. The default VLLMCudaGraphConfig.mode is "FULL", so anyone who runs rl_grpo_qwen3_0_6b_flex_batch_invariant on ROCm without the override from the description hits this late. Move the check into Controller.Config._validate_batch_invariance next to the Flex check, using self.generator.engine.cuda_graph.mode, so it fails at config time. Also type cuda_graph_mode as the Literal from VLLMCudaGraphConfig.mode (or pass the VLLMCudaGraphConfig itself) instead of str.

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.

The cuda_graph.mode="NONE" check is now also in controller config validation, so RL fails before actors spawn; the engine retains it for standalone generate.py. The runtime helper now receives the typed VLLMCudaGraphConfig, and graph support is tracked in #5725.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
or attention is None
or not isinstance(attention.inner_attention, FlexInnerAttention.Config)
):
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.

ROCm + batch_invariant + non-Flex attention returns silently here. The controller rejects that combination, but torchtitan/rl/generate.py doesn't go through the controller, so standalone generation with varlen on ROCm runs with batch invariance quietly unenforced. Raise ValueError for that case instead of returning.

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: _configure_rocm_flex_batch_invariance now raises for ROCm batch invariance with non-Flex attention instead of returning silently. The standalone path reaches this through configure_runtime, with behavior coverage in test_generator.py.

Comment thread torchtitan/rl/controller/controller.py Outdated
if config.override.imports:
apply_overrides(config.override, config)
# Recipes and overrides may mutate an already-constructed config.
config._validate_batch_invariance()

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 re-runs only the batch-invariance subset of __post_init__ after overrides. Every other check (same model class, generator checkpointer, SP divisibility, RDMA + PP) is still skipped for post-construction mutations, so the comment's reasoning applies equally to them. Either re-run all of __post_init__ here (one line, and it covers overrides generally), or drop this call and the _validate_batch_invariance split. It looks like it mainly exists so test_batch_invariance_requires_matching_generator_debug_config can mutate a built config.

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.

Changed to re-run the full config.__post_init__() after resolve_overrides(), so all controller validations cover post-construction mutations. The batch-invariance-only revalidation call is gone.

return

def get_paged_mask_mod(self):
validate_flex_page_mapping_request_limit(self.num_reqs)

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.

num_reqs <= max_num_seqs, and max_num_seqs is already checked against the limit in _configure_rocm_flex_batch_invariance. This runtime check runs on every mask build and can't fire. Delete it. Then validate_flex_page_mapping_request_limit has a single caller and can be inlined.

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.

Partially addressed: the per-mask-build request-limit check was removed. The named helper remains and runs once during runtime setup against max_num_seqs, keeping the 64-request ownership-mask constraint centralized.


from torchtitan.components.loss import compute_logprobs

if getattr(vllm_logprob, "_torchtitan_batch_invariant", False):

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.

Both patch functions already overwrite the target with the same function, so calling them twice is idempotent without this guard. The _torchtitan_* sentinel attributes (here and at lines 35-40 / 100) and the double-call assertion added to test_batch_invariance.py are "just in case" code. Remove them.

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.

Removed the sentinel attributes and the double-call test assertion. Both patch functions now simply overwrite their targets with the equivalent function, so repeated calls remain idempotent.

)


def test_rocm_flex_batch_invariant_setup_installs_page_mapping(monkeypatch):

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.

Every collaborator is mocked, and the test only asserts that configure_runtime calls two functions. That restates the implementation and doesn't guard a numerics invariant. The ownership-mask test in test_batch_invariance.py is the one worth keeping. Consider dropping this test. Separately, test_rocm_batch_invariance_rejects_varlen_attention and the matching-debug test are controller-config validation tests, but they sit in test_policy_loss_configs.py, whose docstring scopes it to loss/compile recipe selection.

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.

Removed the mock-only setup test. The ownership-mask behavior test remains, while controller validation coverage moved to test_async_controller.py and the standalone runtime guard is covered in test_generator.py.

@rishisinhanj
rishisinhanj force-pushed the rocm-flex-batch-invariance-pr branch from fc476a4 to 5ec5376 Compare November 2, 2026 03:50
@meta-codesync

meta-codesync Bot commented Nov 2, 2026

Copy link
Copy Markdown

@haoyuz has imported this pull request. If you are a Meta employee, you can view this in D129036859.

@rishisinhanj

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews. The latest commits address the outstanding feedback:

  • Documented the gfx950 paged-mask root cause, kept the workaround ROCm-only, and added a TODO linking vLLM #66460. CUDA retains vLLM's stock mapping because parity already passes there.
  • Added config-time ROCm 10+, FlexAttention, and cuda_graph.mode="NONE" validation. Graph replay remains tracked in TorchTitan #5725.
  • Made configure_runtime the shared RL/standalone path; the duplicate setup removed from generate.py is therefore intentional.
  • Re-run full validation after overrides, removed unreachable checks and sentinels, replaced the mock-only test, moved validation tests to the appropriate file, and updated stale comments.

Focused tests: 31 passed. The documented successful GPU runs used VLLM_BATCH_INVARIANT=1.

@claude please review

@rishisinhanj

Copy link
Copy Markdown
Contributor Author

@felipemello1 I have made the changes that claude asked for. Can you rerun the review and add any further feedback. I've created a vLLM issue on the topic as well

@felipemello1

Copy link
Copy Markdown
Contributor

@claude please review again

@claude

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 16s —— View job


Approve: the earlier must-fix items are resolved, three should-consider cleanups remain, and a maintainer still needs to review. See the 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 -- all three earlier must-fix items are resolved at HEAD. What's left is a few small should-consider cleanups, plus a maintainer review because the PR touches torchtitan/distributed/utils.py.

What this PR does. On ROCm 10+ it allows RL batch invariance when every trainer and generator attention layer is FlexAttention and vLLM graph replay is off. The trainer then keeps compiled Flex instead of the eager fallback. On the generator side it overrides vLLM's paged Flex mask with a request-independent page lookup plus an int64 ownership bitmask, capped at 64 requests. Standalone generate.py now goes through the same VLLMEngine.configure_runtime as the RL engine.

Example.

ROCm, recipe rl_grpo_qwen3_0_6b_flex_batch_invariant
torch +rocm7.2                       -> Controller: ValueError "requires PyTorch built for ROCm 10.0"
torch +rocm10.0, cuda_graph FULL     -> Controller: ValueError "cuda_graph.mode='NONE'" (before actors spawn)
torch +rocm10.0, cuda_graph NONE     -> runs; compiled trainer Flex, patched vLLM mask
ROCm varlen batch-invariant recipe   -> ValueError "requires FlexAttention" at config build
CUDA, generator.debug != trainer.debug -> ValueError (new for CUDA as well)

Earlier must-fix items

  1. Private vLLM mask override: resolved. There's now a TODO with vllm-project/vllm#66460, and the docstring records the gfx950 reduction-order root cause.
  2. ROCm 7.2 running compiled Flex: resolved. Controller.Config now rejects batch invariance below ROCm 10, so the batch_invariant gate in set_determinism is only reachable on validated versions.
  3. Unanswered @yuankaichen-amd threads: resolved. Each one has a reply, and the replies match the code.

The earlier should-consider items are also handled: config-time graph-mode check, raise instead of silent return, full __post_init__ re-run, sentinels and the runtime limit check removed, mock-only test dropped, tests moved to test_async_controller.py, comment updated.

Should consider

  • torchtitan/rl/generator/vllm/engine.py:103 -- the Flex and graph-mode checks are duplicated between the controller and the engine and have already drifted (first_full_attention vs. every layer). Generator.Config.__post_init__ is the owner for both paths.
  • torchtitan/rl/controller/controller.py:465 -- the 64-request limit can still fail only inside the generator actor. Its static part (max_active_rollout_groups * num_samples_per_prompt) is checkable here.
  • torchtitan/rl/controller/controller.py:435 -- the ROCm version is parsed from the wheel tag, so source builds are rejected. Gate on a runtime value, or add a comment saying this is intentional.

Not verified: bitwise parity on gfx950 and determinism across ROCm versions (needs a GPU run). ROCm/RL CI workflows are still awaiting approval. A maintainer still needs to review.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +103 to +115
attention = model.first_full_attention
if attention is None or not isinstance(
attention.inner_attention, FlexInnerAttention.Config
):
raise ValueError("batch_invariant mode on ROCm requires FlexAttention")

validate_flex_page_mapping_request_limit(max_num_seqs)
if cuda_graph.mode != "NONE":
# TODO: Support graph replay after
# https://github.com/pytorch/torchtitan/issues/5725 is resolved.
raise ValueError(
"ROCm FlexAttention batch invariance requires cuda_graph.mode='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.

The FlexAttention and cuda_graph.mode checks now live in two places: here and in Controller.Config._validate_batch_invariance. The copies have already drifted. This one checks only model.first_full_attention, while the controller checks every trainer and generator Attention.Config. So standalone generate.py accepts a model whose first full-attention layer is Flex even if a later layer isn't.

Every input to these checks is a generator field (generator.model, generator.engine.cuda_graph, generator.debug.batch_invariant). Generator.Config.__post_init__ already validates batch_invariant against reset_kv_cache_on_model_state_dict_load, and both the RL loop and generate.py construct it. Moving the generator-side Flex check (all layers) and the graph-mode check there gives one config-time check for both paths. Then the controller keeps only the trainer-model and ROCm-version checks, and this block shrinks to the max_num_seqs limit plus enable_rocm_batch_invariant_page_mapping(). test_rocm_batch_invariant_runtime_requires_flex_attention would then become a Generator.Config test or go away.

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.

Consolidated the all-layer Flex check in one shared helper used by Generator.Config, the controller, and the engine backstop. The graph guard remains in the controller and engine because BI config is constructed while graph mode is still FULL, before ROCm overrides set it to NONE.

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +465 to +472
cuda_graph = getattr(self.generator.engine, "cuda_graph", None)
if cuda_graph is not None and cuda_graph.mode != "NONE":
# TODO: Support graph replay after
# https://github.com/pytorch/torchtitan/issues/5725 is resolved.
raise ValueError(
"ROCm FlexAttention batch invariance requires "
"cuda_graph.mode='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.

The 64-request ownership-mask limit is the one ROCm constraint that still fails only after actors spawn. setup_async sets max_num_seqs = min(max(max_active_rollout_groups * num_samples_per_prompt, num_validation_groups), 512). The flex recipe sits exactly at 64 (8 prompts x 8 samples, on-policy), so raising num_prompts_per_train_step or target_offpolicy_steps hits the ValueError inside the generator actor. The static part of that value is known here. Consider rejecting min(self.async_loop.max_active_rollout_groups * self.async_loop.num_samples_per_prompt, 512) > MAX_FLEX_BATCH_INVARIANT_REQUESTS next to the graph-mode check, and keep the engine check for the validation-group term and for generate.py.

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.

Added the static rollout-concurrency check to controller validation, before actors start. The engine retains the final check for validation groups and standalone --max-num-seqs.

Comment on lines +435 to +440
rocm_version = str(torch.__version__).partition("+rocm")[2]
if not rocm_version or int(rocm_version.partition(".")[0]) < 10:
raise ValueError(
"batch_invariant mode requires PyTorch built for "
f"ROCm 10.0 or newer, got torch {torch.__version__}"
)

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 parses the ROCm version out of the wheel's local tag (+rocm10.0). A source build of PyTorch has a +git<sha> tag, or none, so it is rejected with "requires PyTorch built for ROCm 10.0 or newer" even when it was built against ROCm 10. If torch.version.hip (or another runtime query) reliably identifies the ROCm 10 userspace, gating on that would avoid this. If it doesn't (the test pairs hip="7.15.26333" with +rocm10.0), add a one-line comment explaining why the wheel tag is the source of truth and that source builds are intentionally rejected. Then the next reader won't "fix" it.

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.

Added a comment documenting why the +rocm wheel tag is the validated source of truth and why untagged/source builds intentionally fail closed.

@rishisinhanj
rishisinhanj marked this pull request as ready for review November 10, 2026 01:18
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 10, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 10, 2026 01:18
@rishisinhanj
rishisinhanj force-pushed the rocm-flex-batch-invariance-pr branch from 8009459 to 39c7589 Compare November 10, 2026 01:19

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.

There seem to be many hardcoded "rocm" functions, which seems hard to maintain / read. How would you prefer the codebase to be maintained when, say, there are 10+ hardware backends, and each having their own limitations?

@rishisinhanj rishisinhanj Nov 16, 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.

I understand your concern and have consolidated the changes behind one platform validation function and one vLLM runtime entry point. The ROCm-specific implementation and 64-request limit are now private. Once this is supported in vLLM, we can remove the workaround, though that may take some time. Let me know if its agreeable to you

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.

Thanks. I would still question the ROI for this PR:

  • did your users ask for batch invariance on Flex? If it's more for debugging, torchtitan has verified correctness on nvidia chips
  • what if users want to work with varlen attention -- does it work with rocm?
  • can we make some of the code sitting in pytorch / attention-gym?

Or, maybe we can just accelerate fixes on vLLM side?

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.

We want that users who are using AMD GPUs can run with batch-invariance mode to do their own debugging. For now, someone is working on the fix on the vLLM side so that the fix is there and any changes in TorchTitan are minimal. Once that is changed, I can alter this PR to make it very minimal. cc @yuankaichen-amd

Validate all attention layers through one helper, re-run generator validation after overrides, and reject statically known request limits before actor startup.
Keep the temporary vLLM page-mapping workaround behind neutral validation and runtime entry points, validate the actual scheduler capacity, and document its upstream removal path.
@rishisinhanj
rishisinhanj force-pushed the rocm-flex-batch-invariance-pr branch from a602e7a to 230f319 Compare November 16, 2026 03:45
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.

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 ciflow/rocm CLA Signed This label is managed by the Meta Open Source bot. module: rocm

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants