Skip to content

[rl] Add generator.max_num_seqs to override the derived engine cap - #6332

Open
wwwjn wants to merge 1 commit into
pytorch:mainfrom
wwwjn:rl-generator-max-num-seqs
Open

wwwjn wants to merge 1 commit into
pytorch:mainfrom
wwwjn:rl-generator-max-num-seqs

Conversation

@wwwjn

@wwwjn wwwjn commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Human Note

  • This is needed because the FA2 has block_size = 256 limitation. In long-term, maybe we should remove FA2 block_size 256 restriction
  • Provide a shortcut to set the geneartor's max_num_seqs to be lower value that derived

TLDR: add Generator.Config.max_num_seqs so a recipe can cap vLLM's max_num_seqs when the value TitanRL derives from rollouts in flight OOMs the generator at startup. Found running Qwen3-8B GSM8K GRPO on 8x A100 80GB.

Problem

  1. TitanRL derives the engine's max_num_seqs from the rollouts in flight: 2x each generator DP rank's share, rounded up to a power of two, clamped to [max_num_batched_tokens / 64, max_num_batched_tokens]. The controller computed it (Controller.Config.max_num_seqs_per_generator_dp_rank) and passed it to each generator. There was no override, just a TODO there.
  2. At startup, vLLM's CUDA graph memory profile allocates a minimal KV cache of one page per sequence: min(max_num_seqs, max_cudagraph_capture_size) pages (_init_minimal_kv_cache_for_profiling).
  3. On GPUs older than SM90, TitanRL's pages hold 256 tokens (block_size=256 in the vLLM engine), because PyTorch's FA2 paged KV requires it: FA2 resolves the page once per key tile of up to 256 keys, so a tile must not straddle a page (Paged KV cache block size must be divisible by 256). Native vLLM's FA2 fork takes 16-token pages; FA3/FA4 have no such limit.
  4. Qwen3-8B GSM8K GRPO (128 prompts x 5 samples, target_offpolicy_steps=2 -> 1,920 rollouts in flight, 2 TP=1 generators) derives 2048. Qwen3-8B holds 144 KiB of KV per token, so the profile asks for 2048 x 256 tokens x 144 KiB = 72 GiB and the generator OOMs on an 80 GB A100 before the first rollout (Tried to allocate 72.00 GiB). With 16-token pages it would be 4.5 GiB, which is why SM90+ recipes never hit it.
  5. 2048 is also more than the engine can run: its KV cache holds 339,200 tokens, ~330 GSM8K sequences in 256-token pages.

Solution

  1. Generator.Config.max_num_seqs: int | None = None.
  2. The generator now sets its engine's max_num_seqs, so the controller no longer reads a generator setting to derive another one. The controller passes only avg_num_seqs_per_generator_dp_rank (each generator DP rank's even share of the rollouts in flight) to Generator. Generator.Config.resolve_max_num_seqs returns max_num_seqs when set, else derives the cap from the average as before.
  3. The override must be in the same range the derivation clamps to: at least max_num_batched_tokens / 64 (FA2 out-of-bounds writes in vLLM's memory profile, flash-attention#3117) and at most max_num_batched_tokens (a vLLM requirement). A value outside that range raises ValueError when the generator starts. The check runs there rather than in __post_init__ so that a value assigned after the config is built is checked too.
  4. Unchanged: None keeps today's derived value for every existing recipe.

Results

  • Qwen3-8B, 2 generators + FSDP 4 trainer, 8x A100 80GB: the derived 2048 OOMs at generator init; max_num_seqs=256 (vLLM's A100 default, which another RL framework's engines on this host also use) needs a 9 GiB profile KV cache and runs 30 steps. In the comparison so far the 256 cap was applied by patching the property in the recipe; this field replaces that patch.

Test

  • tests/rl/unit_tests/cpu/test_generator.py::test_resolve_max_num_seqs checks the derived value (power-of-two rounding and both clamps), that the override wins, and that out-of-range values raise. It fails without this change (AttributeError: 'Config' object has no attribute 'resolve_max_num_seqs'). test_generator.py, test_async_controller.py and test_model_defaults.py pass (126 passed, 4 skipped).
  • pre-commit on the touched files: all hooks pass. pyrefly's CI config excludes torchtitan/rl and tests; run locally on these files it reports no new errors beyond main's.

You may ask

  • Why not derive a cap that fits instead of adding a knob? The controller builds the config before any engine measures its free memory or KV capacity, so a derived cap would be a guess per model and GPU. The TODO this replaces asked for the override.
  • Why not take smaller pages on A100? That needs PyTorch's FA2 to resolve the page per key row instead of per tile (as vLLM's fork does); it would also cut KV fragmentation (up to 255 slots per sequence) and allow prefix reuse below 256 tokens. Out of scope here.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 23, 2026
@wwwjn
wwwjn marked this pull request as ready for review November 23, 2026 21:55
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 23, 2026
@wwwjn

wwwjn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@github-actions
github-actions Bot requested a review from pzhan9 November 23, 2026 21:55
@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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


Verdict: Approve -- review (a maintainer still needs to 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 -- The existing TODO asked for this override, the change is small and opt-in, and unset (None) gives exactly the derived value on every existing recipe. A maintainer still needs to review, since this touches the core RL controller.

What this PR does. It adds Generator.Config.max_num_seqs: int | None. When the field is set, Controller.Config.max_num_seqs_per_generator_dp_rank returns it in place of the derived value (2x the rollouts in flight per DP rank, rounded up to a power of two and clamped). The override must be in [max_num_batched_tokens / 64, max_num_batched_tokens], the same range the derivation clamps to. Otherwise it raises ValueError in setup_async, before any actor is spawned. The derived path is only refactored to reuse min_num_seqs and computes the same value as before.

Example.

Qwen3-8B, 128 prompts x 5 samples, 2 TP=1 generators, A100 (block_size=256)
  before: derived 1920 -> 2048; vLLM's profile asks for 2048 x 256 tok x 144 KiB = 72 GiB -> OOM
  after:  generator.max_num_seqs=256 -> 256 x 256 tok x 144 KiB = 9 GiB -> runs
  generator.max_num_seqs=8 with max_num_batched_tokens=2048 -> ValueError "must be in [32, 2048]"

Should consider

  • torchtitan/rl/generator/generator.py:146 -- Trim the run-specific arithmetic from the field docstring. Also add a TODO with an upstream PyTorch issue for FA2's 256-token page requirement, the real reason this knob is needed (see the inline comment).

Questions

  • No recipe in the repo sets generator.max_num_seqs. Will the Qwen3-8B GSM8K A100 recipe land in torchtitan_recipes/rl/? It would be the in-repo consumer and would drop the property patch mentioned in the description.
Details
  • Where the check lives. The range check runs in the property, not in __post_init__. That is acceptable here. resolve_overrides() applies Python overrides in place after __post_init__, so a __post_init__ check would miss an override that sets generator.max_num_seqs. The property runs at controller.py:785 before _build_actor_system(), so the "before any process starts" claim holds.
  • The bounds are justified. The lower bound guards a silent failure: FA2 writes out of bounds in vLLM's memory profile (flash-attention#3117, TODO kept). The upper bound repeats a vLLM requirement, but surfaces it before any process is spawned.
  • No numerics change. 2 ** ceil(log2(max(x, tokens / 64))) followed by min(..., tokens) matches the old expression exactly.
  • The test is worth its cost. It is a cheap CPU test that covers both the override branch and the range check, and nothing else did. It sits in tests/rl/unit_tests/cpu/, which is the right place.

Comment thread torchtitan/rl/generator/generator.py Outdated
Comment on lines +146 to +153
"""The engine's cap on concurrently scheduled sequences per generator DP rank.
``None`` (default) derives it from the rollouts in flight
(``Controller.Config.max_num_seqs_per_generator_dp_rank``). Set it when the derived
cap does not fit the GPU: vLLM's startup CUDA graph memory profile allocates one KV
page per sequence, and pages hold 256 tokens on GPUs older than SM90 (PyTorch's FA2
paged KV requires it). E.g. Qwen3-8B (144 KiB of KV per token) with 1,920 rollouts in
flight on 2 generators derives 2048 -> 2048 x 256 tokens = 72 GiB, which OOMs an
80 GB A100; 256 needs 9 GiB."""

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.

Two small suggestions for this docstring:

  1. The Qwen3-8B / A100 arithmetic (144 KiB per token, 1,920 rollouts, 72 GiB vs 9 GiB) is a snapshot of one run, and it goes stale as soon as block_size or vLLM's profiling changes. It already lives in the PR description. The field docstring only needs to tell a user when to set it.
  2. The field exists mostly to work around PyTorch FA2's 256-token page requirement. The block_size = 256 site (torchtitan/rl/generator/vllm/engine.py:387) has no TODO or upstream issue, so nothing records that this knob can be revisited once the requirement is lifted. A TODO with a pytorch/pytorch issue link, here or at engine.py:387, would record it.

Also, max_num_seqs reaches SGLang too (max_running_requests), so describing it as only "vLLM's" is narrower than what the field does.

Suggested change
"""The engine's cap on concurrently scheduled sequences per generator DP rank.
``None`` (default) derives it from the rollouts in flight
(``Controller.Config.max_num_seqs_per_generator_dp_rank``). Set it when the derived
cap does not fit the GPU: vLLM's startup CUDA graph memory profile allocates one KV
page per sequence, and pages hold 256 tokens on GPUs older than SM90 (PyTorch's FA2
paged KV requires it). E.g. Qwen3-8B (144 KiB of KV per token) with 1,920 rollouts in
flight on 2 generators derives 2048 -> 2048 x 256 tokens = 72 GiB, which OOMs an
80 GB A100; 256 needs 9 GiB."""
"""The engine's cap on concurrently scheduled sequences per generator DP rank.
``None`` (default) derives it from the rollouts in flight
(``Controller.Config.max_num_seqs_per_generator_dp_rank``). Set it lower when the
derived cap OOMs the generator at startup: vLLM's CUDA graph memory profile allocates
one KV page per sequence, and pages hold 256 tokens on GPUs older than SM90 (PyTorch's
FA2 paged KV requires it, see ``VLLMEngine``)."""

Comment thread torchtitan/rl/controller/controller.py Outdated
@@ -572,12 +591,7 @@ def max_num_seqs_per_generator_dp_rank(self) -> int:
even_share = math.ceil(max_rollouts_in_flight / num_generator_dp_ranks)

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.

Reading generator's max_num_seqs config in controller, and then generate a derived config to send to generator's constructor is ... weird.

I think we should instead:

@wwwjn
wwwjn force-pushed the rl-generator-max-num-seqs branch from 5eff651 to c9d1db1 Compare November 24, 2026 17:58

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

looks great, thanks

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 5s —— View job


Verdict: Approve -- 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 -- @tianyu-l's design comment is addressed: the controller now passes only the even share, and Generator decides max_num_seqs. When the override is unset (None), the result is the same as before. A maintainer has already approved.

What changed since the last automated review. Controller.Config.max_num_seqs_per_generator_dp_rank became avg_num_seqs_per_generator_dp_rank (the rounded-up even share only). The rounding and clamping, the range check on the override, and the startup log line moved into Generator.Config.resolve_max_num_seqs. Generator.__init__ calls it. GeneratorActor and test_bitwise_parity.py pass the new avg_num_seqs_per_dp_rank kwarg.

Example.

1536 rollouts in flight, 8 generator DP ranks, max_num_batched_tokens unset (2048)
  controller: avg_num_seqs_per_generator_dp_rank = 192
  generator:  max_num_seqs=None -> 2**ceil(log2(max(384, 32))) = 512, min(512, 2048) = 512   (same as before)
              max_num_seqs=256  -> 256
              max_num_seqs=16   -> ValueError "must be in [32, 2048]" in Generator.__init__

Earlier findings

  • Field docstring trimmed to "when to set it", engine-agnostic wording: resolved.
  • TODO with an upstream PyTorch issue for FA2's 256-token page requirement: still open (non-blocking). torchtitan/rl/generator/vllm/engine.py:387 still says only "FA2 requires block_size to be a multiple of 256". That requirement is the reason this knob exists, so a TODO(<pytorch issue>) there would record when the knob can be revisited.
  • In-repo consumer: still open. No recipe sets generator.max_num_seqs. If the Qwen3-8B A100 GSM8K recipe isn't landing, say so in the PR so the field's consumer is on record.
Details
  • Callsites audited. The only constructors of Generator/GeneratorActor are the Monarch actor (updated) and spawn_generator_router, which forwards **generator_kwargs from controller.py:807 (updated). No other reference to the old property remains. torchtitan/rl/generate.py builds its engine from its own --max_num_seqs CLI arg and never went through the controller property, so it is unaffected.
  • Where the check fires. The range check now runs in each generator's __init__, after the actors are spawned. Before, it ran in the controller before spawn. A bad override therefore surfaces as an actor-init failure rather than a controller-side error. That is acceptable and matches the description ("raises when the generator starts").
  • Numerics. 2 ** ceil(log2(max(2 * avg, tokens / 64))) followed by min(..., tokens) gives the same value as the old expression.

Not verified: GPU run of test_bitwise_parity.py with the new kwarg.

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

2 participants