Skip to content

[rl] generator: paged attention runs FlashAttention, not cuDNN - #6001

Merged
tianyu-l merged 1 commit into
mainfrom
sglang-1-paged-attn-flash
Nov 10, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
sglang-1-paged-attn-flash

Conversation

@tianyu-l

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

The generator's paged attention (paged_varlen_attention_out, called by the vLLM and SGLang engines' attention backends) is documented as running "PyTorch's FlashAttention, the kernel the trainer's VarlenInnerAttention runs". Outside batch-invariant mode it runs cuDNN instead:

  • torch.nn.attention.varlen tries cuDNN first, before FlashAttention, and with cuDNN >= 9.24 (the RL environment has 9.26) cuDNN accepts paged-KV calls with power-of-two pages, including vLLM's 128-token FA4 pages and SGLang's 1-token pages.
  • Batch-invariant mode is unaffected: it passes num_splits=1, which cuDNN rejects, so those calls already run FlashAttention.

cuDNN is much slower on the generator's shapes.

Example. One mixed step, 100 decode rows plus one 650-token prefill row, ~9,000 KV tokens each, 24 query / 4 KV heads, head dim 256 (Qwen3.5-27B's attention), 128-token pages, GB300. Profiling paged_varlen_attention_out:

before: cudnn_generated_fort_native_sdpa_sm100_flash_fprop_...   6.64 ms
after:  flash_attncute...FlashAttentionForwardSm100...            2.97 ms

What changed

  • torchtitan/rl/generator/attention/attention.py: paged_varlen_attention_out runs the varlen call under sdpa_kernel([SDPBackend.FLASH_ATTENTION]). 5 lines plus a comment.

User-facing changes

Before After
Generator paged attention outside batch-invariant mode: cuDNN on SM90/SM100 FlashAttention (FA3/FA4), as the docstring already says

Numerics

  • Batch-invariant mode: unchanged (it already ran FlashAttention); the vLLM bitwise parity tests pass.
  • Outside batch-invariant mode, the generator's logprobs change in the last bits (a different kernel); no bitwise contract applies there.

Performance

Kernel time per call through torch's varlen API, CUDA-graph replay, GB300, 128-token pages, ~9,000 KV tokens per sequence (cuDNN = before, FA4 = after; flash-attn-4 4.0.0b38):

Shape (q / kv heads, head dim) Batch cuDNN FA4
24 / 4, 256 100 decode rows 1.70 ms 0.51 ms
24 / 4, 256 one 650-token prefill 0.17 ms 0.09 ms
24 / 4, 256 100 decode + 650 prefill, split as in #5941 1.93 ms 0.72 ms
32 / 8, 128 100 decode rows 0.75 ms 0.51 ms
32 / 8, 128 100 decode + 650 prefill, split 0.87 ms 0.64 ms

Not measured: end-to-end generation throughput.

Testing

  • Kernel profile above: the call runs FA4 after the change.
  • vLLM tests on GB300, launched as CI launches them:
    • TestBitwiseParityVarlen (2 GPUs): 3 passed.
    • TestBitwiseParityQwen35DebugVarlen (2 GPUs): 5 passed.
    • test_generator_uneven_decode.py (4 GPUs): 1 passed.
    • test_generator_dp_cudagraph.py, both tests the H100 job runs (2 GPUs each): passed.
  • No new test: the backend choice is a performance property, and a test that greps the profiler for kernel names would be brittle.

Known issues / follow-ups

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 10, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 10, 2026 06:41
@tianyu-l
tianyu-l added this pull request to stack #6002 November 10, 2026 06:41
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 10, 2026
torch's varlen_attn prefers cuDNN wherever cuDNN accepts the call, and with
cuDNN >= 9.24 it accepts the generator's paged-KV calls (power-of-two pages)
outside batch-invariant mode, whose num_splits=1 it rejects. So the vLLM
engine's and SGLang engine's paged attention ran cuDNN there, which on GB300
is 1.5-15x slower than FA4 on the generator's decode, prefill and mixed
batches (e.g. 100 decode rows at head dim 256: 1.70 vs 0.51 ms).

paged_varlen_attention_out now selects FlashAttention only. Batch-invariant
mode already ran FlashAttention, so its numerics are unchanged.
@tianyu-l
tianyu-l force-pushed the sglang-1-paged-attn-flash branch from b6f4a7b to ac9e714 Compare November 10, 2026 19:38
@tianyu-l
tianyu-l merged commit 39b6fc2 into main Nov 10, 2026
tianyu-l added a commit that referenced this pull request Nov 10, 2026
Stacked on #6001 (the generator's paged attention runs FlashAttention,
not cuDNN).

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

experimental alternative generation engine support

## Why
The RL generator runs only on vLLM today. SGLang's scheduler (radix
prefix
cache, overlap scheduling, breakable prefill CUDA graphs,
session-referenced
KV, host KV offload) is a strong fit for RL rollouts, especially
multi-turn
agentic ones. This PR adds an `SGLangEngine` behind the existing
`GenerationEngine` interface. As with `VLLMEngine`, SGLang runs the
trainer's
TorchTitan model and attention kernel; it owns only KV cache management
and
scheduling.

Maintainer decision (@tianyu-l): torchtitan keeps SGLang as an
alternative
generation backend next to vLLM, not only as an experiment. Its tests
run in
the B200 RL job (`integration_test_rl_b200.yaml`), added here.

**Example.**
```python
# before: vLLM only
generator=Generator.Config(..., engine=VLLMEngine.Config())
# after: pick the engine by config type
generator=Generator.Config(..., engine=SGLangEngine.Config())
```
```
SGLangEngine (every rank, in-process; no tokenizer/detokenizer processes)
  add_requests ----> Scheduler.process_input_requests
  step ------------> one iteration of Scheduler.event_loop_overlap
                       TorchTitan Decoder, attention -> RadixAttention ->
                       trainer's varlen FlashAttention on SGLang's paged KV
  load_model_state_dict -> ModelStateDictLoader (in place, CUDA graphs stay valid)
```

## What changed
- `torchtitan/rl/generator/sglang/` (new):
- `engine.py`: `SGLangEngine`. It builds SGLang's `Scheduler` in-process
per
TP rank and steps one overlap-loop iteration per `step()`. It also does:
    - request admission and rejection;
    - incremental output collection;
- model state dict loads, with and without a KV reset (retract, flush,
      continue);
    - policy-version `cache_salt`;
    - session references;
    - seeded sampling.
    - prompt-length limits matching vLLM's: SGLang rejects prompts of
`context_len - 6` tokens or more, so the engine sets SGLang's context
length to
`max_context_length + 6` (`registry.CONTEXT_LENGTH_MARGIN`) and caps
each
request's output at `max_context_length` tokens in total. Prompts of up
to
`max_context_length - 1` tokens run, as in vLLM; without the margin,
prompts of
      65,530-65,535 tokens at a 64K context were rejected.
- `model_wrapper.py`: the TorchTitan model as an SGLang model class,
with
    `_DecoderBody`, the module SGLang's prefill CUDA graphs capture.
- `attention.py`: `SGLangInnerAttention`, plus a FlashAttention-backend
    subclass that calls the shared `paged_varlen_attention_out`.
  - `registry.py`: model class, config parser and attention backend
    registration.
  - `batch_invariance.py`: the trainer's `compute_logprobs` for returned
    logprobs.
  - `README.md`.
- `inference_model.compute_logits`: the lm_head plus TP gather, now
shared by
the vLLM and SGLang wrappers. For vLLM this is mechanical (the same
code,
  moved).
- `inference_model.route_tp_all_reduce`: the routing half of the vLLM
wrapper's
`_patch_vllm_all_reduce`, moved and shared. Outside batch-invariant
mode, the
  SGLang wrapper routes the model's TP sum all-reduces through SGLang's
`tensor_model_parallel_all_reduce` (SGLang's custom all-reduce) instead
of NCCL.
For vLLM this is mechanical, with two differences: the
`registered=False`
override now also applies to a rebuilt engine's communicator, and the
docstring's
reason for routing `spmd.redistribute` directly is corrected (its
all-reduce
reaches the op swap through funcol; the direct route is about 2-3%
faster for
  vLLM decode at TP 2).
- `torchtitan_recipes/rl/alphabet_sort.py`: new recipe
`rl_grpo_qwen3_0_6b_varlen_sglang`: `rl_grpo_qwen3_0_6b_varlen`
(generator TP 4
  plus trainer TP 2, 6 GPUs) with the SGLang engine.
- Per-request metrics (queue time, time to first token, prefill and
decode times,
preemptions) come from the timestamps SGLang's scheduler stamps on each
request,
as the vLLM engine reports them. The queue time starts at admission,
since SGLang
  restamps its wait-queue entry time when it retracts a request.
- `test_sglang_bitwise_parity.py` (new). `test_model_defaults.py` lists
the
  SGLang recipe as needing an optional package.
- Docs: `generator.py` and `torchtitan/rl/README.md` mention the new
engine.
- `scripts/install_rl_env.sh --sglang` (new flag): installs SGLang at
the pinned
commit with a git-URL install, keeping the environment's PyTorch (uv
overrides)
  and dropping torchaudio, which the engine never imports.
- CI: the B200 RL job (`integration_test_rl_b200.yaml`) gains a last
step. It
installs SGLang with `scripts/install_rl_env.sh --sglang` on top of the
job's RL
environment and runs `test_sglang_bitwise_parity.py` on 2 GPUs. The
README's
environment steps use the same flag, so the SGLang commit is pinned in
one
place. The step runs after the job's other tests, so installing SGLang
cannot
  affect them, and it adds about 2 minutes to a job that takes 16-26.

Supported: dense softmax attention with the varlen backend (Qwen3, Llama
3),
any TP, decode plus breakable prefill CUDA graphs, batch-invariant mode,
session KV, and CPU KV offload (SGLang HiCache, through
`extra_server_args`).
These raise at build: DP > 1, EP / Dist-MoE, SP, flex attention, sliding
window,
sinks, MLA and GDN.

Review fixes (19e4b88):
- `step()` runs under `torch.no_grad()`, as SGLang's own loops and the
vLLM engine
  do, so the model's TP all-reduces take their fast path in eager steps.
- `add_requests` rejects empty prompts and token ids outside the vocab
(SGLang
checks only the length; at TP > 1 a bad id would embed as zeros
silently).
- `extra_server_args` cannot set `page_size` (the engine sets 1, with
the reason)
or any key containing `cuda_graph`: SGLang applies its per-phase graph
keys over
`disable_cuda_graph`, so they could turn on graphs the engine's checks
assume
  are off.
- The trainer-logprobs sampler is registered with SGLang's
  `register_sampler_backend` instead of patching `Sampler.forward`.
- A load without a KV reset clears SGLang's watchdog batch before the
fetch.
- Docstrings and comments: the output collector (no tokenization runs),
the cache
  salt, `page_size`.

Workarounds of SGLang APIs, each with a TODO in code:
- single-iteration loop (mirrors `event_loop_overlap`);
- an in-process output sink replacing the detokenizer and tokenizer
sockets;
- a hook to plug a kernel into SGLang's FA metadata;
- skipping SGLang's own aten batch-invariant overrides in deterministic
mode;
- registering the trainer-logprobs sampler for every built-in sampling
backend;
- registering a model class built at runtime;
- the layer attribute path its prefill graphs use to find attention.

## User-facing changes
| Before | After |
| --- | --- |
| `Generator.Config.engine`: `VLLMEngine.Config` only | also
`SGLangEngine.Config(cuda_graph=..., extra_server_args=...)` |
| - | recipe `rl_grpo_qwen3_0_6b_varlen_sglang` |
| - | `scripts/install_rl_env.sh --sglang`: also installs SGLang into
the RL environment |
| `force_logprobs_fn_for_batch_invariance` (vLLM) | renamed
`force_trainer_logprobs_for_batch_invariance`, the SGLang helper's name
|

## Numerics
Batch-invariant mode matches the trainer bitwise.

| Check | Hardware | Result |
| --- | --- | --- |
| `test_sglang_bitwise_parity.py`: trainer prefill vs SGLang decode;
decode bsz 1 vs 5 with the prompt cached; trainer vs SGLang after an
in-place model state dict load of perturbed weights | 2x GB300, SGLang
`851642ade` | 3 passed, max delta 0 (a no-op load fails it: delta 19.5)
|
| E2E `rl_grpo_qwen3_0_6b_varlen_batch_invariant` with SGLang (1
generator TP 2 + trainer TP 2), 10 steps | 4x GB300 | `logprob_diff/max`
= 0 every step |
| Multi-turn workload (192 sessions x 4 turns), batch-invariant, HiCache
on vs off | 2x GB300 | identical tokens for every session |
| Outside batch-invariant mode, Qwen3-0.6B TP 2, 32 greedy requests x 64
tokens, SGLang's vs NCCL's all-reduce | 2x GB300 | identical tokens and
logprobs |

Outside batch-invariant mode, `logprob_diff/max` on the default recipe
(10 steps) is in vLLM's range: SGLang 0.4-18.5, vLLM 0.4-12.4. Across
other runs it varies: SGLang reached 4.9, 7.4 and 11.1; vLLM reached
9.8.

## Performance
Qwen3-0.6B, generator TP 2, 2x GB300. Same `GenerationEngine` calls;
temperature
1; fixed-length outputs.

| Workload | vLLM | SGLang |
| --- | --- | --- |
| Decode: 512 requests, 256 in / 1024 out | 18.0 s (29.1k out tok/s) |
10.9 s (48.0k out tok/s) |
| Prefill: 512 requests, 1536 in / 128 out | 4.1-4.6 s | 3.1 s |
| Shared prefix: 512 requests, 1536 in (1280 shared) / 256 out | 4.9 s |
3.7 s |
| Multi-turn: 192 sessions x 4 turns (1024 + 4 x (256 obs + 128 gen)),
KV pool 300K tokens | 6.96 s, 21% prefix hits; 6.22 s, 30% with
`session_kv_holder` | 6.24 s, 37% |
| Multi-turn, KV pool 450K tokens (fits) | 5.8-6.2 s | 5.5 s |
| Peak GPU memory at `gpu_memory_limit=0.8` | 81.2% | 81.1% |

End to end, `alphabet_sort` with generator TP 2 + trainer TP 2 (4x
GB300, 10
steps): trainer tokens/s over steps 3-9 is 1682 and 1693 for vLLM (two
runs), and
1632 and 1758 for SGLang (two runs). The shipped recipe uses generator
TP 4 (6
GPUs, as the vLLM recipe); it was not run, since this host has 4 GPUs.

The table and these E2E runs were measured before the TP all-reduce
routing. With
the routing, one more SGLang run of the same E2E (RL environment, so
`expandable_segments`; decode and breakable prefill CUDA graphs) reached
1763
trainer tokens/s over steps 3-9. SGLang's custom all-reduce registered
the graph
buffers through FABRIC handles, so capture works on that memory. With a
separate
local benchmark (perf mode, temperature 1, decode and breakable prefill
CUDA graphs,
the RL environment defaults including `expandable_segments`, median of 2
runs;
Qwen3-0.6B TP 2, 2x GB300):

| Workload | SGLang, NCCL all-reduce | SGLang, SGLang all-reduce | vLLM
|
| --- | --- | --- | --- |
| Decode 64 requests x 512 tokens, ms/step | 2.85 | 2.12 | 3.57 |
| Decode 256 requests x 512 tokens, ms/step | 4.30 | 3.56 | 7.9 |
| GRPO 16 prompts x 8 samples (1024 in, 256 out), s | 1.25 | 1.04 | 1.46
|

Most of the decode gap to vLLM is not SGLang's scheduling. The vLLM
engine's
default `FULL` CUDA graphs capture one graph per size for mixed
prefill/decode
batches, with prefill-sized attention parameters, so decode steps run
FlashAttention
4's non-persistent varlen scheduler: 1.99 ms of decode attention per
step at 256
requests, against 0.75 ms in SGLang and 0.70 ms in vLLM with
`FULL_DECODE_ONLY`.
vLLM's decode step is also mostly host time.

Three engine fixes were needed to get there:
- Breakable prefill CUDA graphs: eager prefill was CPU-bound, at 114 ms
of host
  time against 16 ms of GPU time per 16K-token chunk.
- `gc.freeze()` after the build: SGLang's ~1.5M objects made the engine
loop's
  `gc.collect()` after each load take 1.2 s.
- KV-pool bookkeeping on SGLang's schedule stream.

## Testing
- `test_sglang_bitwise_parity.py` at 19e4b88: 5 passed on 2x GB300,
including
the new `test_sglang_decode_across_model_state_dict_load` (a load of the
same
weights at step 10, mid-decode, leaves tokens and logprobs identical).
Earlier
revisions: 3 passed in a fresh environment built the way the CI step
builds it.
- `scripts/install_rl_env.sh --sglang`'s SGLang install, in a fresh venv
with the
RL environment's torch: installs SGLang at the pin, torch unchanged, no
  torchaudio.
- The new CI step, run locally the way CI runs it (the step's own
commands, in the fresh
environment): 3 passed. On B200: [run
42015554306](https://github.com/pytorch/torchtitan/actions/runs/42015554306),
3 passed on both ranks; the step took 2 minutes, SGLang install
included.
- Engine checks (local script) at TP 1 and TP 2, each with
  `reset_kv_cache_on_model_state_dict_load` off and on:
  - a too-long prompt is rejected;
- a mid-generation reload of the same weights leaves outputs identical;
  - reset mode passes 6 of 6 repeats at TP 2.
- `pytest tests/rl/unit_tests/cpu`: 546 passed (581 at the top of the
stack after
  the review fixes).
- vLLM `TestBitwiseParityVarlen`: 3 passed (it covers the shared
  `compute_logits`).
- E2E runs as above.
- `test_context_length_limits` (new, in
`TestSGLangBitwiseParityVarlen`): a prompt of
`max_context_length - 1` tokens runs and stops at `max_context_length`
tokens in
total, and a prompt of `max_context_length` tokens is rejected. Without
the margin
it fails (the first prompt is rejected). With it, all 4 tests of the
class pass on
  2x GB300.

## Known issues / follow-ups
- SGLang's custom all-reduce was checked only on GB300 (NVLink, its V2
implementation). Where SGLang falls back to its legacy custom
all-reduce, CUDA
  graph capture on `expandable_segments` memory is unverified.
- Only the B200 RL job runs the SGLang tests. The engine is unverified
on the A10G
  runners of the other RL GPU jobs.
- Upstream SGLang issues for the workarounds above, linked from their
TODOs:
  - a public single-iteration step API: sgl-project/sglang#48472;
  - an in-process output sink: sgl-project/sglang#48473;
- seeded sampling without SGLang's kernel overrides, and ignoring the
generation
    config's EOS ids: sgl-project/sglang#48474;
- extension points for out-of-tree models (registration, attention
lookup,
    attention kernels, sampler logprobs): sgl-project/sglang#48475;
  - DP replicas in one torch world: sgl-project/sglang#48476;
- per-request time stats without `enable_metrics`:
sgl-project/sglang#48482.
- FlashAttention 4 JIT-compiles prefill kernel variants on first use,
which
  costs about 6 s of stalls once per run.
- A request whose last batch is in flight during a model state dict load
is
  reported at the new policy version (TODO in `load_model_state_dict`).
- In reset mode, requests retracted by a load lose their session
reference
  (their next turn recomputes the prefix).
- HiCache costs more than it saves for Qwen3-0.6B, where recompute is
cheaper;
  it needs evaluation on larger models.
- Next phase: MoE / EP, DP > 1, GPT-OSS, GDN / MLA, flex attention.
- With continuous arrivals (one 300-token prompt per step, 256 requests
x 150
tokens), SGLang's median request latency is 3.0 s against vLLM's 0.9 s.
Each
step that admits a prompt is an extend step of about 17 ms whatever the
prompt
length (vLLM: 7-9 ms), a fixed per-step cost. SGLang also does not mix
decode rows
into a prefill batch when requests return logprobs (TODO in its
scheduler);
allowing it in a local SGLang patch moved p90 latency from 4.7 to 2.8 s,
the
  median only from 2.9 to 2.5 s. Follow-up.
- The vLLM engine's `FULL` CUDA graphs run decode attention with
prefill-sized
  parameters (see Performance); follow-up on the vLLM path.
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