Skip to content

[rl] Size generator max_num_seqs per DP rank from the rollouts in flight - #5944

Merged
felipemello1 merged 12 commits into
mainfrom
felipemello1/max-num-seqs-config
Nov 9, 2026
Merged

felipemello1 merged 12 commits into
mainfrom
felipemello1/max-num-seqs-config

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

this max_num_seq was bothering me a bit.

TLDR:

  • we know max num rollouts from buffer size
  • Divide by DP
    ~ this pr
  • Adds a 2x head room

this makes space for adaptive buffer, eval, DP unbalance, etc. It also does it in powers of 2 to make it FA2 friendly, and caps at max_num_batched_tokens which vllm sets at 2k

Agent details

TLDR: Each generator DP rank's max_num_seqs becomes 2x its even share of the training rollouts in flight, rounded up to a power of two (so 2-4x the share) and capped at the token budget. Main gives every rank the whole total, capped at 512, and loads the validation set at setup to count it.

# before (Controller.setup_async)
num_validation_groups = len(self._rollouter.get_validation_samples(async_loop.validation.steps))
rollout_concurrency = max(max_active_rollout_groups * num_samples_per_prompt, num_validation_groups)
max_num_seqs = min(rollout_concurrency, 512)

# after (Controller.Config.max_num_seqs_per_generator_dp_rank)
even_share = math.ceil(max_rollouts_in_flight / num_generator_dp_ranks)
max_num_batched_tokens = self.generator.max_num_batched_tokens or 2048
# power of two, at least budget / 64: FlashAttention-2 workaround
max_num_seqs = 2 ** math.ceil(math.log2(max(2 * even_share, max_num_batched_tokens / 64)))
return min(max_num_seqs, max_num_batched_tokens)

Problem

  1. max_num_seqs is vLLM's cap on the requests one engine DP rank runs at once. Above it, requests wait in vLLM's queue, even when the KV cache has room.
  2. Main gives every generator DP rank min(total rollouts in flight, 512). To count validation prompts in that total, setup loads the whole validation set.
  3. The 512 binds when one rank holds more than 512 rollouts. The Qwen3.5-4B DAPO smoke below has 2,304 in flight on one generator: 512 run and about 1,100 wait. DAPO Qwen3-30B-A3B 8k averages 640 per rank.

Solution

  1. Size each rank from its own share: 2x its even share of the training rollouts in flight. The 2x is headroom for uneven routing. A rank at the cap queues new requests; it doesn't fail.
  2. Round up to a power of two, at least the token budget / 64 (32 for the default 2048). vLLM's memory profile splits the token budget over max_num_seqs dummy requests and adds the remainder to the last one. With FlashAttention-2 (A10G, A100), a dummy request of 65+ tokens writes out of bounds. Example: 3 generators x 64 rollouts gives 44, and the last dummy request gets 70 tokens. A power of two >= budget / 64 splits a power-of-two budget into at most 64 tokens each.
  3. Cap at generator.max_num_batched_tokens, or 2048 when unset. vLLM refuses to start if max_num_seqs is larger, and our engine's unset budget is 2048. A recipe with a larger budget can derive more than 2048; none does today (DAPO Qwen3-30B-A3B sets 8192 and derives 2048).
  4. Controller.Config.max_num_seqs_per_generator_dp_rank computes it. The controller reads it, and so does the GPU parity test, which copies one RL engine. torchtitan.rl.generate is a standalone one-prompt tool with no async loop, so it keeps its --max-num-seqs flag.
  5. Unchanged: how the value reaches vLLM, and the CUDA graph capture sizes (still derived from it).

Results

max_num_seqs per generator DP rank, computed on CPU from each recipe's config:

recipe                                   in flight  generator DP ranks  main  this PR
rl_grpo_qwen35_9b_terminal_bench         1536       8                   512   512
rl_grpo_qwen35_35b_a3b_terminal_bench    1280       4                   512   1024
rl_dapo_qwen3_30b_a3b_math_8k            2560       4                   512   2048
rl_dapo_qwen3_4b_math_8k                 640        6                   512   256
rl_grpo_qwen3_0_6b_varlen                256        1                   256   512
rl_grpo_fsdp2_gen_tp2_compile (CI)       64         3                   64    64
rl_grpo_0_6b_tp4_batch_invariant (CI)    16         1                   20    32

GPU smoke: 2 GB300s (1 trainer + 1 generator), Qwen3.5-4B DAPO Math, FULL CUDA graphs, 2,304 rollouts in flight, 3 steps:

max_num_seqs           512 (main's value)     2048 (this PR)
running at once        512, ~1,100 waiting    up to 1,798
KV cache               237.32 GiB             230.86 GiB   (-2.7%)
CUDA graphs            136                    294
graph capture          48 s                   67 s

You may ask:

  • Why each rank's share and not the total? Main gives every rank the total so the cap can never bind before the KV cache does. But the router moves sessions off a rank once it is well above the mean load, so a rank holds about its share, and 2-4x the share leaves room. Going over the cap only queues requests.
  • Why not a fixed number? A fixed 512 binds on the runs above. A fixed 2048 gives a small run on a small KV cache more slots than a GDN model has Mamba cache blocks (see NOTE).
  • Why no validation term? On main, validation runs before and after training, and it shares the same slots.

NOTE:

  • GDN and KDA models with FULL or FULL_DECODE_ONLY CUDA graphs need one Mamba cache block per running request. vLLM refuses to start if max_num_seqs is larger than the block count. We saw it with a small KV cache: Qwen3.5-27B on one GB300 at gpu_memory_limit 0.25 had 296 blocks. Such a recipe raises gpu_memory_limit or uses more TP. A generator.max_num_seqs override is a TODO, added when a recipe needs it.
  • Values above 512 were measured only in the smoke above. Terminal-Bench 35B (1024) and DAPO Qwen3-30B-A3B (2048) were not run.
  • An open PR changes the unset max_num_batched_tokens to vLLM serve's per-GPU default, and edits the same lines in the parity test. Whichever lands second rebases. 2048 stays the smallest unset budget.

Test plan

pytest tests/rl/unit_tests/cpu -q            # 569 passed, 7 skipped
pre-commit run --files <changed files>       # all pass; pyrefly flags fsdp.py, gdn.py and muse_spark/renderer.py, same on main
  • CPU probe over every recipe in torchtitan_recipes/rl and torchtitan_recipes/tests/rl: each value is a power of two, at most its token budget, and every profile dummy request gets at most 64 tokens.
  • GPU smoke above: starts, trains 3 steps, validates before and after. Exit 0.
  • RL GPU tests run on the ciflow/rl and ciflow/b200 labels, both on this PR.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 8, 2026
@felipemello1 felipemello1 added the ciflow/b200 Trigger B200 CI label Nov 8, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 8, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging (empty human-written summary; the max_num_seqs docstring needs the reason for 512 and a TODO for the FA2 bug). Review ·

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. It's a net deletion (-27 LoC) that replaces a setup-time derivation with a plain config field. The derivation coupled the engine to the controller's batch math and loaded the whole validation set just to count prompts. This touches the RL controller, so a maintainer still needs to review.

What this PR does. It replaces the controller-derived cap, min(max(groups * samples, len(validation)), 512), with Generator.Config.max_num_seqs: int = 512. The generator reads the field directly, and the max_num_seqs argument is removed from Generator, the Monarch actor, and the controller. generate.py and the bitwise-parity test read the same field, and setting it through extra_engine_args now raises an error that points at the config field.

Example.

qwen3_5 debug CI config: 8 prompts x 8 samples, validation.steps=20, gen DP=1
before: max_num_seqs = min(max(max_active_rollout_groups*8, 20), 512) -> small; setup loads validation set
after : max_num_seqs = 512 (Generator.Config default); setup doesn't touch validation data
recipe needing less: Generator.Config(max_num_seqs=64)

Must fix

  1. The PR description's "Summary (human-written)" section is empty. The author needs to fill it in.
  2. torchtitan/rl/generator/generator.py:131 -- the docstring doesn't give the actual reason for 512. It also recommends lowering the value for GDN/KDA without warning about the FlashAttention-2 out-of-bounds write that small caps trigger. That bug is one of the PR's motivations, so it needs a TODO with an upstream issue link (see inline comment).
Details
  • Necessity: the problem is real on main. setup_async calls get_validation_samples only to size this cap, and the validation term no longer makes sense once validation overlaps training. A fixed field is the smallest fix, with no new knob beyond the one that replaces the derivation.
  • Callsites: no other code passes max_num_seqs= to Generator, and the only remaining use of get_validation_samples is the validation pass itself (controller.py:766). async_loop in setup_async is still used.
  • Linear-attention CI configs: rl_grpo_qwen3_5_debug_varlen sets max_num_batched_tokens=seq_len, with seq_len 1024 or 2048, so it stays >= 512. The kimi_k3 configs use FULL_DECODE_ONLY with gpu_memory_limit=0.8 on a debug model, so state blocks should be well above 512.
  • engine.py:67: max_num_seqs is always in engine_kwargs, so the new map entry only changes the error message to name the config field. That's fine.
  • generate.py: --max-num-seqs duplicates the field, but it follows the existing --max-tokens/--temperature pattern, and the CLI has no dotted overrides. Leaving it is reasonable.

Not verified: the GPU runs. That means startup of the qwen3_5/kimi_k3 CI configs at 512 (enough state blocks), and test_bitwise_parity.py at generator.max_num_seqs, which the description lists as pending.

Comment thread torchtitan/rl/generator/generator.py Outdated
Comment on lines +131 to +137
max_num_seqs: int = 512
"""The most requests each engine DP rank runs at once; the rest wait in its queue. It
also sizes per-request buffers and the decode CUDA graphs. 512 is above what small runs
send: against a cap of 64 it cost 1.4 GiB of KV cache and 40 more decode CUDA graphs
(Qwen3.5-4B, one GB300). It must be <= ``max_num_batched_tokens``. Lower it if vLLM
refuses to start a linear-attention model (GDN, KDA) with FULL or FULL_DECODE_ONLY CUDA
graphs: each running request needs one state block."""

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 problems with this docstring:

  1. It doesn't say why the value is 512. "512 is above what small runs send" plus one GB300 measurement is a benchmark note, not a reason. The real reason (from the PR description) is that every large recipe already runs at 512, so they keep their behavior. Say that, and drop the Qwen3.5-4B/GB300 numbers.
  2. It tells users to lower the value for GDN/KDA, but says nothing about the FlashAttention-2 out-of-bounds write the PR description cites as a motivation. vLLM's memory profile splits 2048 tokens over max_num_seqs dummy requests. At 65+ tokens per request the split-KV path writes past softmax_lse. So anyone who follows this advice and goes down to about 31 or less on FA2 hits a silent memory corruption again. That's an upstream bug that torchtitan works around by choosing a default, so per the repo rules it needs a TODO with an upstream issue link (FlashAttention or vLLM), plus a note on the floor.

Sketch:

        max_num_seqs: int = 512
        """The most requests each engine DP rank runs at once; the rest wait in its queue. It
        also sizes per-request buffers and the decode CUDA graphs. 512 matches what large
        recipes run at; a larger cap than a run needs costs little (some KV cache and extra
        decode-only CUDA graphs). Must be <= ``max_num_batched_tokens``. Lower it if vLLM
        refuses to start a linear-attention model (GDN, KDA) with FULL or FULL_DECODE_ONLY
        CUDA graphs: each running request needs one state block.

        TODO(<upstream issue>): with FA2, values below ~32 make vLLM's memory profile hit an
        out-of-bounds write in the varlen + paged-KV split-KV kernel."""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done in 9ae333a. The docstring now says 512 is what large recipes run at, drops the GB300 numbers, and adds a TODO linking the FlashAttention issue (values below ~32 hit the out-of-bounds write in vLLM's memory profile).

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review again (docstring fixed in 9ae333a; the human-written summary is Felipe's to write).

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items below before merging (the docstring fix is resolved; the human-written summary is still empty and Felipe has to write it). Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. The docstring finding is fixed at HEAD, and the new commits add no new problems. The one item left is the human-written summary, which the author has to write. This touches the RL controller, so a maintainer still needs to review.

What this PR does. It replaces the controller-derived cap min(max(groups * samples, len(validation)), 512) with Generator.Config.max_num_seqs: int = 512. The generator, generate.py (when --max-num-seqs is not passed) and the bitwise-parity test all read this field. Setting it through extra_engine_args now raises an error that names the field.

Example.

before: setup loads validation set; max_num_seqs = min(max(G*S, num_validation_groups), 512)
after : max_num_seqs = Generator.Config.max_num_seqs (512); setup doesn't touch validation data
generate.py: --max-num-seqs omitted -> generator.max_num_seqs (was 1)

Earlier findings

  • Resolved: torchtitan/rl/generator/generator.py:131. The docstring now gives the real reason for 512 ("what large recipes run at") and drops the GB300 numbers. The new TODO links Dao-AILab/flash-attention#3117, which is open and titled "FA2 split-KV early exit writes softmax_lse with the padded layout, out of bounds for varlen + paged KV". The "below ~32" floor matches 2048 / 65 tokens per dummy request.
  • Still open: the "Summary (human-written)" section of the PR description is empty. Felipe needs to fill it in before merging.
Details
  • No other callers remain. max_num_seqs / rollout_concurrency no longer appear in torchtitan_recipes/, and no code passes max_num_seqs= to Generator or the Monarch actor. async_loop in setup_async is still used (batcher setup).
  • The parity test no longer divides by gen_dp. It now builds one engine at the same per-rank value the generator uses, which is the right mirror.
  • generate.py: the CLI default goes from 1 to the config value. This is a behavior change for that script, and the PR description states it.

Not verified: GPU startup of the qwen3_5 / kimi_k3 CI configs at 512 (enough state blocks), and the local test_bitwise_parity.py run the description lists as pending.

@felipemello1
felipemello1 force-pushed the felipemello1/max-num-seqs-config branch from 9ae333a to 1957fa8 Compare November 8, 2026 22:27
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review. New design at 1957fa8: max_num_seqs per generator DP rank = 2x its even share of the training rollouts in flight, rounded up to a power of two, clamped to [32, token budget]; generator.max_num_seqs overrides it. The PR body is rewritten for it.

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items below before merging. The PR title is stale and the human-written summary is empty; there's also one optional FA2-floor tweak. Review

@felipemello1 felipemello1 changed the title [rl] Make generator max_num_seqs a fixed config field (default 512) [rl] Size generator max_num_seqs per DP rank from the rollouts in flight Nov 8, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The new design fixes a real cap: main's 512 binds on large recipes. It also stops loading the validation set at setup, and it is a single property with three consumers. What's left is description hygiene plus one small, latent edge in the FA2 workaround. This touches the RL controller, so a maintainer still needs to review.

What this PR does. Controller.Config.max_num_seqs_per_generator_dp_rank replaces the setup-time derivation. It returns generator.max_num_seqs when that is set. Otherwise it takes 2x the rank's even share of max_active_rollout_groups * num_samples_per_prompt over num_generators * data_parallel_degree, rounds up to a power of two, floors at 32 and caps at the token budget (2048 when unset). The controller, generate.py (when --max-num-seqs isn't passed) and the bitwise-parity test all read it. Setting max_num_seqs through extra_engine_args now raises an error that names the config field.

Example.

1280 rollouts in flight, 4 generator DP ranks, budget unset
main:    min(max(1280, num_validation_groups), 512) = 512 per rank; setup loads the validation set
this PR: ceil(1280/4)=320 -> 2x = 640 -> pow2 = 1024 -> min(1024, 2048) = 1024 per rank
recipe override: Generator.Config(max_num_seqs=256) -> 256, used as is

Must fix

  1. The PR title still says "a fixed config field (default 512)". At HEAD the field defaults to None and the value is derived, so the title needs updating. The "Summary (human-written)" section is also still empty, and Felipe has to write it.

Should consider

  • torchtitan/rl/controller/controller.py:481 -- the TODO says a budget above 2048 needs a floor of budget / 64, but the code floors only at 32. Folding that into one expression removes the magic 32 (see inline comment).
Details
  • Earlier findings: the 512-default docstring finding no longer applies, because the new Generator.Config.max_num_seqs docstring was rewritten for None-means-derive and points FA2 users at a power of two >= 32. The empty human-written summary is still open (item 1).
  • Callsites: no code passes max_num_seqs= other than the controller -> Monarch actor -> Generator chain. get_validation_samples is now used only by the validation pass. math is already imported in controller.py. num_generators >= 1 is validated in __post_init__, and data_parallel_degree defaults to 1, so the division is safe.
  • Validation no longer counts toward the cap, so a validation set larger than the cap queues instead of running all at once. The description covers this. It doesn't affect correctness.
  • Overlap with #5952 (budget defaults to vllm serve's per-GPU value): this PR still caps at or 2048 when the budget is unset. After #5952 that is conservative on H100/GB300 (8192/16384 there), and the FA2 GPUs (A10G/A100) stay at 2048, so the floor of 32 stays correct for them. Whichever PR lands second should replace the or 2048 with the resolved budget.
  • RL CI recipes: values move a little (e.g. 20 -> 32 on rl_grpo_0_6b_tp4_batch_invariant). The parity test reads the same property, so generator and test agree.

Not verified: GPU startup at the new larger values on the GDN/KDA hybrids. This means Mamba cache blocks for Qwen3.5-35B-A3B Terminal-Bench at 1024. Separately, CUDA-graph capture time and memory at 2048 for DAPO Qwen3-30B-A3B. The description says neither was run.

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +474 to +484
max_num_seqs = 2 * even_share
# TODO(https://github.com/Dao-AILab/flash-attention/issues/3117): drop the power of
# two and the floor of 32 once fixed. vLLM's memory profile splits the token budget
# over max_num_seqs dummy requests and adds the remainder to the last one. With
# FlashAttention-2, a dummy request of 65+ tokens writes out of bounds. A power of
# two >= 32 splits 2048 tokens evenly, into at most 64 per request. A larger budget
# needs a floor of budget / 64.
max_num_seqs = max(2 ** math.ceil(math.log2(max_num_seqs)), 32)
# vLLM requires max_num_seqs <= max_num_batched_tokens, which defaults to 2048 for
# the engine torchtitan builds.
return min(max_num_seqs, self.generator.max_num_batched_tokens or 2048)

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 TODO says "A larger budget needs a floor of budget / 64", but the code only ever floors at 32. Example: an FA2 GPU (A100), max_num_batched_tokens=8192, and a small run with 64 rollouts in flight on 3 generators. That derives 64, so each profile dummy request gets 128 tokens: the out-of-bounds write this workaround exists to prevent. No recipe hits this today (the DAPO 30B recipe at 8192 derives 2048), so it's latent. But the fix is one expression, and it replaces the magic 32 with the value it stands for (2048 / 64):

Suggested change
max_num_seqs = 2 * even_share
# TODO(https://github.com/Dao-AILab/flash-attention/issues/3117): drop the power of
# two and the floor of 32 once fixed. vLLM's memory profile splits the token budget
# over max_num_seqs dummy requests and adds the remainder to the last one. With
# FlashAttention-2, a dummy request of 65+ tokens writes out of bounds. A power of
# two >= 32 splits 2048 tokens evenly, into at most 64 per request. A larger budget
# needs a floor of budget / 64.
max_num_seqs = max(2 ** math.ceil(math.log2(max_num_seqs)), 32)
# vLLM requires max_num_seqs <= max_num_batched_tokens, which defaults to 2048 for
# the engine torchtitan builds.
return min(max_num_seqs, self.generator.max_num_batched_tokens or 2048)
max_num_batched_tokens = self.generator.max_num_batched_tokens or 2048
# TODO(https://github.com/Dao-AILab/flash-attention/issues/3117): drop the power of
# two and the budget / 64 floor once fixed. vLLM's memory profile splits the token
# budget over max_num_seqs dummy requests and adds the remainder to the last one.
# With FlashAttention-2, a dummy request of 65+ tokens writes out of bounds. A power
# of two >= budget / 64 splits a power-of-two budget evenly, into at most 64 each.
max_num_seqs = 2 ** math.ceil(
math.log2(max(2 * even_share, max_num_batched_tokens / 64))
)
# vLLM requires max_num_seqs <= max_num_batched_tokens, which defaults to 2048 for
# the engine torchtitan builds.
return min(max_num_seqs, max_num_batched_tokens)

Every current recipe gets the same value as at HEAD. That's because the unset or 2048 budget gives a floor of 32, and the 8192 recipe is already above 128. Like the current code, it still assumes a power-of-two budget. A budget like 3000 leaves a remainder on the last dummy request either way.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review again. 01a89ec applies your floor suggestion (budget / 64). The title is updated. The human-written Summary is Felipe's to write.

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the item below before merging. The budget / 64 floor and the new title are resolved; the human-written summary is still empty and Felipe has to write it. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. 01a89ec applies the budget / 64 floor correctly and adds no new problems. The only item left is the human-written summary. This touches the RL controller, so a maintainer still needs to review.

What changed since the last review. The magic floor of 32 is now max_num_batched_tokens / 64, folded into the power-of-two rounding. The TODO and the property docstring now describe this floor.

Example.

A100 (FA2), max_num_batched_tokens=8192, 64 rollouts in flight, 3 generator DP ranks
before 01a89ec73: 2 x 22 = 44 -> pow2 64 -> max(64, 32) = 64   -> 128 tokens per profile dummy request (OOB)
at HEAD:          max(44, 8192/64 = 128) -> pow2 128 -> min(128, 8192) = 128 -> 64 tokens each
unset budget (2048): floor is 32, so every current recipe gets the same value as before

Earlier findings

  • Resolved: controller.py FA2 floor. The code now floors at budget / 64, which matches the TODO. The docstring examples still hold (16 -> 32, 44 -> 64, 384 -> 512).
  • Resolved: the PR title now describes the derived per-rank sizing.
  • Still open: the "Summary (human-written)" section of the description is empty. Felipe needs to write it.
Details
  • Generator.Config.max_num_seqs docstring ("on FlashAttention-2 GPUs, use a power of two >= the token budget / 64") now agrees with the derived path.
  • When the budget is not a power of two, the last dummy request still gets a remainder. Both the TODO ("a power-of-two budget") and the PR description say so, and no recipe sets one.
  • If the cap at the budget binds below a power of two (budget < 2 x share), each dummy request gets 1 token, so the FA2 limit isn't hit.

Not verified: GPU startup at the larger derived values on GDN/KDA hybrids (Mamba cache blocks at 1024 for Qwen3.5-35B-A3B Terminal-Bench), and graph capture at 2048 for DAPO Qwen3-30B-A3B. The description says neither was run.

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +472 to +473
# 2x is headroom for uneven routing: the router moves a session only once its rank
# is well above the mean load. A rank at the cap queues new requests.

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.

Suggested change
# 2x is headroom for uneven routing: the router moves a session only once its rank
# is well above the mean load. A rank at the cap queues new requests.
# 2x is headroom

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Applied in ea86ffd.

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +475 to +480
# TODO(https://github.com/Dao-AILab/flash-attention/issues/3117): drop the power of
# two and the floor of 32 once fixed. vLLM's memory profile splits the token budget
# over max_num_seqs dummy requests and adds the remainder to the last one. With
# FlashAttention-2, a dummy request of 65+ tokens writes out of bounds. A power of
# two >= 32 splits 2048 tokens evenly, into at most 64 per request. A larger budget
# needs a floor of budget / 64.

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.

keep it to 2 lines

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done in ea86ffd: the FA2 TODO is 2 lines.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
# EngineArgs owned by a config field. Some are set only when that field is set (or
# derived from it), so they may be absent from engine_kwargs.
config_field_by_engine_arg = {
"max_num_seqs": "Generator.Config.max_num_seqs",

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 dont think that we ned to expose this knobs. Do we?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Agreed, no recipe sets it. Dropped the field in ea86ffd; engine.py is back to main. A one-line TODO at the property tracks an override for when a recipe needs a smaller value.

Comment thread torchtitan/rl/generator/generator.py Outdated
Comment on lines +135 to +141
max_num_seqs: int | None = None
"""The most requests each engine DP rank runs at once; the rest wait in its queue.
``None`` (default) derives it from the rollouts in flight; see
``Controller.Config.max_num_seqs_per_generator_dp_rank``. A set value is used as is;
on FlashAttention-2 GPUs, use a power of two >= 32. Lower it if vLLM says
"max_num_seqs exceeds available Mamba cache blocks": GDN and KDA models with FULL or
FULL_DECODE_ONLY CUDA graphs need one Mamba cache block per running request."""

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 also dont think that we need to expose this. Do we?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Dropped in ea86ffd (same as the engine.py thread); generator.py is back to main.

Comment thread torchtitan/rl/generator/generator.py Outdated
Comment on lines +135 to +141
max_num_seqs: int | None = None
"""The most requests each engine DP rank runs at once; the rest wait in its queue.
``None`` (default) derives it from the rollouts in flight; see
``Controller.Config.max_num_seqs_per_generator_dp_rank``. A set value is used as is;
on FlashAttention-2 GPUs, use a power of two >= the token budget / 64. Lower it if
vLLM says "max_num_seqs exceeds available Mamba cache blocks": GDN and KDA models with
FULL or FULL_DECODE_ONLY CUDA graphs need one Mamba cache block per running request."""

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.

too many details. Lets be objective. <3 lines. No need to mention FA2. No need to mention the GDN/KDA.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Moot now: the field is gone in ea86ffd. The remaining comments are short and don't mention FA2 outside its TODO.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review again. 63d82dd addresses Felipe's inline comments: the Generator.Config.max_num_seqs override is dropped (generator.py and engine.py match main), comments are shorter, and main is merged in.

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the item below before merging. Felipe's inline comments are resolved at 63d82dd. The human-written summary is still empty, and Felipe has to write it. Review ·

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. 63d82dd resolves Felipe's inline comments and adds no new problems. The only open item is the human-written summary. This touches the RL controller, so a maintainer still needs to review.

What changed since the last review. The Generator.Config.max_num_seqs override is gone, so generator.py and engine.py now match main. A one-line TODO at the property tracks adding the override back when a recipe needs it. The headroom comment and the FA2 TODO are each cut to 1-2 lines. The diff is now 3 files, +41/-34.

Example.

1280 rollouts in flight, 4 generator DP ranks, budget unset
main:    min(max(1280, num_validation_groups), 512) = 512 per rank; setup loads the validation set
HEAD:    ceil(1280/4)=320 -> 2x = 640 -> pow2(max(640, 2048/64)) = 1024 -> min(1024, 2048) = 1024
generate.py: --max-num-seqs omitted -> config.max_num_seqs_per_generator_dp_rank (was 1)

Must fix

  1. The "Summary (human-written)" section of the PR description is still empty. Felipe needs to write it.

Earlier findings

  • Resolved (Felipe): drop the max_num_seqs knob. Neither generator.py nor engine.py appears in the diff, and no code reads generator.max_num_seqs.
  • Resolved (Felipe): the 2-line FA2 TODO and the shorter headroom comment. Both are applied at controller.py:470-474.
  • Resolved: the budget / 64 floor is unchanged at HEAD.
Details
  • The property docstring ("clamped to [token budget / 64, token budget]") matches the code. All three examples still hold.
  • Callsites: the controller (setup_async), generate.py and test_bitwise_parity.py all read the same property. setup_async no longer calls get_validation_samples. data_parallel_degree defaults to 1, and num_generators >= 1 is validated, so the division is safe.
  • or 2048 duplicates _DEFAULT_MAX_NUM_BATCHED_TOKENS in torchtitan/rl/generator/vllm/config.py:27. Importing it from there would pull vLLM into the controller config, and it is a private name, so the literal plus its comment is fine. The open PR that changes the unset budget should update this line too (the description notes this).

Not verified: GPU startup at the larger derived values on GDN/KDA hybrids (Mamba cache blocks at 1024 for Qwen3.5-35B-A3B Terminal-Bench), and graph capture at 2048 for DAPO Qwen3-30B-A3B. The description says neither was run.

@felipemello1
felipemello1 marked this pull request as ready for review November 8, 2026 23:05
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 8, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 8, 2026 23:05
Felipe Mello added 10 commits November 8, 2026 22:26
The controller derived max_num_seqs from the rollouts in flight plus one
validation pass, capped at 512. That read the whole validation set at setup
just to count it, and small runs got small caps.

Generator.Config.max_num_seqs now holds it, default 512, the value large runs
already get.
…ts in flight, clamp [32, 2048]

Generator.Config.max_num_seqs becomes an optional override (default None).
Controller.Config.generator_max_num_seqs resolves it; the controller, generate.py and
the parity test read it. Drops the validation term and the 512 ceiling.
…t; rename to max_num_seqs_per_generator_dp_rank
@felipemello1
felipemello1 force-pushed the felipemello1/max-num-seqs-config branch from 63d82dd to d23133a Compare November 9, 2026 03:26
Comment thread torchtitan/rl/generate.py Outdated
Comment on lines +116 to +120
max_num_seqs = (
config.max_num_seqs_per_generator_dp_rank
if args.max_num_seqs is None
else args.max_num_seqs
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't know how meaningful this change is, in the sense that "does the generate script understand max_num_seqs_per_generator_dp_rank"? The latter requires knowledge about the number of generators, max_rollouts_in_flight in the async loop config, etc. -- are they available to the generate script config?

Please confirm what's a reasonable choice -- worst case let's just keep it as is.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Kept it as on main, reverted in 16aaedd. generate.py uses its --max-num-seqs flag again (default 1).

The fields are on the config generate.py loads, so it could compute the value. But the value is one RL engine's share of all rollouts in flight, split over num_generators x generator DP. generate.py builds one engine for one prompt, with no async loop, so that share doesn't describe it.

The GPU parity test still reads the property. Its helper copies one RL engine on purpose, and main's helper already derived its value from the async loop config.

Felipe Mello and others added 2 commits November 9, 2026 06:48
…(review)

The derived value assumes num_generators engines. generate.py runs one engine.

Co-authored-by: Claude <[email protected]>
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please re-review dc687c6. Change since your last review: torchtitan/rl/generate.py is back to main (its --max-num-seqs flag, default 1), per tianyu-l's comment. Upstream main merged. The PR is now 2 files.

@claude

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- tianyu-l's generate.py comment is resolved (the file is back to main), the human-written summary is now filled in, and nothing is left to fix. 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 -- dc687c6 resolves tianyu-l's generate.py comment and the merge from main adds no new problems. No items remain. This touches the RL controller, so a maintainer still needs to review.

What changed since the last review. torchtitan/rl/generate.py is back to main and no longer in the diff, so it uses its --max-num-seqs flag again (default 1). Upstream main is merged in. The PR is now 2 files, +35/-32.

Example.

1280 rollouts in flight, 4 generator DP ranks, budget unset
main: min(max(1280, num_validation_groups), 512) = 512 per rank; setup loads the validation set
HEAD: ceil(1280/4)=320 -> 2x = 640 -> pow2(max(640, 2048/64)) = 1024 -> min(1024, 2048) = 1024
generate.py: unchanged from main (--max-num-seqs, default 1)

Earlier findings

  • Resolved (tianyu-l): generate.py no longer reads max_num_seqs_per_generator_dp_rank. It is reverted to main.
  • Resolved: the "Summary (human-written)" section is now filled in, and it matches the code (share per DP rank, 2x headroom, power of two, capped at the token budget).
  • Resolved earlier and unchanged at HEAD: the budget / 64 floor, the dropped Generator.Config.max_num_seqs knob, and the short comments.
Details
  • After the merge, _DEFAULT_MAX_NUM_BATCHED_TOKENS in torchtitan/rl/generator/vllm/config.py:27 is still 2048, so the or 2048 at controller.py:472 still matches the engine's unset budget. #5952, which changes that default, has not landed. Whichever PR lands second should update this line.
  • setup_async still uses async_loop (batcher spawn), and get_validation_samples is now called only by the validation pass. data_parallel_degree defaults to 1 (torchtitan/rl/generator/parallelism.py:18), and num_generators >= 1 is validated, so the division is safe.
  • test_bitwise_parity.py reads the same property as the controller, so the test engine matches one RL generator DP rank.

Not verified: GPU startup at the larger derived values on GDN/KDA hybrids (Mamba cache blocks at 1024 for Qwen3.5-35B-A3B Terminal-Bench), and graph capture at 2048 for DAPO Qwen3-30B-A3B. The description says neither was run.

@felipemello1
felipemello1 merged commit 9c7a345 into main Nov 9, 2026
felipemello1 added a commit that referenced this pull request Nov 9, 2026
… own (#5969)

## Summary (human-written)
1) we would like to visualize generatioin metrics for training and
validation separately
2) currently we pass a "metric prefix" and have the generator add the
suffix
3) this doesnt compose well with verifiers
4) we remove this, and let the evaluator add the suffix when they come
back

## Agent details

Stack: main <- #5944 <- this PR <- #5228. Supersedes #5948 (one
`generate_fn` per group, kept in a dict).

**TLDR:** The generate path no longer carries a metrics label.
Generators always name their metrics `generator/*`, and validation
renames its own to `validation_generator/*` after results return, so the
W&B keys stay as on main. #5228 (validation beside training) needs this
first: Verifiers' HTTP server holds one `generate_fn`, so once groups of
both kinds overlap, a request can log under the other kind's label.

```text
main:     validation generate_fn(metrics_prefix="validation_generator") -> router -> generator -> "validation_generator/queue_time_ms"
this PR:  every generate_fn, no label                                    -> router -> generator -> "generator/queue_time_ms"
          validation, after the group returns:  "generator/queue_time_ms" -> "validation_generator/queue_time_ms"
```

**Problem**
1. The controller builds two kinds of `generate_fn`: training's sends
`metrics_prefix="generator"`, validation's `"validation_generator"`.
2. The label travels through 7 layers to name each request's metrics:
controller, `InterGeneratorRouter`, the Monarch router and generator,
`Generator`, engine loop, dispatcher.
3. Verifiers runs its agents against an HTTP server that holds one
`generate_fn` (`GenerationServer.set_generate_fn`). Each group that
starts replaces it.
4. So while a training group and a validation group run at once, a
request uses the function of the group that started last, and logs under
that kind's label. Once validation runs beside training (#5228), that is
most turns of a multi-turn env.
5. On main no logged metric is wrong: validation never overlaps a
running training rollout. A late call from a cancelled rollout lands in
metadata nobody reads. So on main this PR is a cleanup that prevents the
bug.

**Solution**
1. Drop `metrics_prefix` from the generate path. The dispatcher spells
each key: `generator/queue_time_ms`, `generator/num_cached_tokens`, ...
2. `_collect_validation_rollouts` renames its turns' `generator/*`
metrics to `validation_generator/*` after results return.
3. The Verifiers server keeps its one slot. Every group now passes a
function with no label, so replacing it is safe (a comment at the call).
4. Unchanged: the W&B keys (`generator/*` for training,
`validation_generator/*` for validation), the `GenerateFn` contract,
routing and request ids.
5. The logic is in two places: the rename in
`_collect_validation_rollouts` and the spelled keys in
`_prepare_generation_request_metrics`. The other files only delete the
parameter, plus one comment in the Verifiers rollouter and the new test.

You may ask:
- Why not one `generate_fn` per group in the Verifiers server, keyed by
group id (#5948)? It fixes Verifiers only and adds a per-group lifetime.
A function with no label can't be the wrong one, whatever calls it. This
PR replaces #5948.
- Why keep `validation_generator/*` and not `validation/generator/*`?
Dashboards and old runs keep their keys.

NOTE:
- A metric about the whole engine shouldn't ride on one request's
metrics: validation renames every `generator/*` key on its turns, and a
failed group drops its turns' metrics.
- Open PRs that pass `metrics_prefix` need a rebase that drops it.
- The rollout recorder writes no metrics, so `rollout_samples.jsonl` is
unchanged.

**Test plan**
```text
pytest tests/rl/unit_tests/cpu -q --ignore=tests/rl/unit_tests/cpu/test_vllm_wrapper.py
    # 551 passed, 7 skipped (base: 550 passed, 7 skipped)
pytest tests/rl/unit_tests/cpu/test_verifiers*.py tests/rl/unit_tests/cpu/test_model_defaults.py   # in a venv with verifiers
    # 61 passed
pre-commit run --files <changed files>
    # all hooks pass
pyrefly check
    # 1 error, the same on the base: FSDPModule.set_unshard_in_current_stream (torchtitan/distributed/fsdp.py:593)
```
- New:
`test_async_controller.py::test_validation_renames_generator_metrics`.
It fails when the rename is removed.
- `test_generator.py`, `test_engine_loop.py`,
`test_async_controller.py`: the calls drop `metrics_prefix`.
`test_metric_timing_math` now checks `generator/*` keys.

---------

Co-authored-by: Felipe Mello <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI 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