Skip to content

Perf/rollout multiple graph captures - #9153

Open
omersajid9 wants to merge 4 commits into
deepspeedai:masterfrom
omersajid9:perf/rollout-multiple-graph-captures
Open

omersajid9 wants to merge 4 commits into
deepspeedai:masterfrom
omersajid9:perf/rollout-multiple-graph-captures

Conversation

@omersajid9

Copy link
Copy Markdown

What

Adds a decode bucket ladder to continuous rollout graph capture: decode
graphs are captured lazily at powers-of-two widths (plus max_batch_size)
and each decode step replays the smallest captured width covering the
rows doing work, instead of always replaying the full-batch graph. A
failed capture falls back to an eager forward for that bucket; new stats
report captures, bucket widths, and padded rows.

Why

A multi-turn rollout re-submits every conversation with the tokens it
just generated, and conversations end turns at different times, so the
live batch drains over the run. A single max-batch-sized graph pays
full-width padding on every late step; the ladder only pads to the next
captured width.

Results (1x A100-SXM4-40GB, driver 595.71.05, torch 2.15.0+cu132, bf16;

16 conversations x 4 staggered turns, 256 new tokens/turn, max_batch_size 16,
seed 0, best of 5 after 2 warmups)

model wide tok/s ladder tok/s speedup row-steps pad rows
Qwen3-4B 294.5 388.8 1.32x 16320 -> 11220 (0.69x) 6120 -> 1020
Qwen3-8B 254.7 323.7 1.27x 16320 -> 11220 (0.69x) 6120 -> 1020

KV-cache footprint is unchanged (same max-batch static cache in both
configurations); only the replayed width per step shrinks.

Tests

  • python benchmarks/rollout/bench_graph_capture_ladder.py --model Qwen/Qwen3-4B --device cuda --dtype bf16 --conversations 16 --turns 4 --max-batch-size 16 --max-new-tokens 256 --trials 5 --warmup 2

Capture decode graphs lazily at powers-of-two widths and replay the
smallest width that covers the rows doing work, instead of always
replaying the full-batch graph. A failed capture falls back to an eager
forward for that bucket; new stats report captures, widths and padding.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T19:47:56.454311Z afd8e88 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: afd8e8878c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +219 to +223
for _ in range(max(0, args.warmup)):
run_once(args, model, conversations, ladder, graph_capture, device)
best = None
for _ in range(max(1, args.trials)):
run = run_once(args, model, conversations, ladder, graph_capture, device)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Warm the same rollout that is timed

With real graph capture, every call to run_once constructs a fresh rollout and starts its timer before the first generate, where the lazy bucket graphs are captured. These separate warmup calls discard their graph state, so measured total ms/tokens/s includes one wide capture versus multiple ladder captures rather than the advertised steady-state generation; warm and then measure the same rollout (or explicitly label this as cold-start timing).

AGENTS.md reference: AGENTS.md:L34-L37

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed: warmup and trials now share one rollout, so the lazy ladder captures are absorbed by the warmup and the measured pass is steady-state

device = torch.device(args.device if args.device != "auto" else (
accelerator.current_device_name() if accelerator.is_available() else "cpu"))
dtype = DTYPES[args.dtype] if args.dtype else (torch.bfloat16 if device.type == "cuda" else torch.float32)
graph_capture = device.type == "cuda" and accelerator.create_graph() is not None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Detect graph capture through the accelerator

With --graph auto on XPU or NPU, --device auto selects that backend but device.type is not "cuda", so this silently disables capture and compares two eager runs even though deepspeed/accelerator/xpu_accelerator.py:339-358 and npu_accelerator.py:250-262 implement graph capture. Query the accelerator capability/create-graph API rather than hard-coding CUDA so the benchmark actually exercises the ladder on supported vendor devices.

AGENTS.md reference: AGENTS.md:L40-L40

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed: --graph auto now checks device.type == accelerator.device_name() and accelerator.is_graph_capture_supported() and accelerator.create_graph() is not None, so XPU/NPU with --device auto exercise the ladder instead of silently comparing two eager runs. Devices without capture support still print the NOTE and run both configurations eagerly.

# PR-local switches; kept after every upstream field so the legacy
# positional constructor contract (#8786's test) keeps holding
use_segki: bool = False
graph_capture_batch_sizes: Optional[Tuple[int, ...]] = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Document the capture-ladder option

This adds a user-configurable tuning field and changes the default graph behavior, but a repo-wide rg for graph_capture_batch_sizes under docs and examples finds no entry; only the implementation docstring and benchmark mention it. Add user/API documentation covering accepted widths, the powers-of-two default, memory/capture tradeoffs, and an override example.

AGENTS.md reference: AGENTS.md:L71-L71

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Documented under docs/code-docs/source/inference-engine.rst

Comment on lines +445 to +447
assert HybridEngineRollout._graph_capture_ladder(1) == (1, )
assert HybridEngineRollout._graph_capture_ladder(5) == (1, 2, 4, 5)
assert HybridEngineRollout._graph_capture_ladder(8) == (1, 2, 4, 8)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Test bucket selection through the public rollout contract

These new assertions call private helpers and pin their exact tuple representation, so a correct refactor that preserves configured/default bucket dispatch can still fail the tests. Exercise the same cases through generate and observable stats (as the later dispatch test already does), rather than asserting private method return values.

AGENTS.md reference: AGENTS.md:L76-L78

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Rewritten to go through generate() and the reported stats: graph_capture_ladder covers defaults and overrides, decode_bucket_widths / decode_padded_rows / graph_captures cover rounding and padding, and validation errors are checked via generate() + pytest.raises. No private helper is asserted anymore; the shared _RetiringModel / _ladder_stats helpers also collapsed the existing dispatch test. Verified: pytest tests/unit/runtime/rollout/ → 186 passed, 4 skipped.

…ures.

Signed-off-by: omersajid9 <omersajid.777@gmail.com>
Source
- Measure cache_memory_bytes after the graph decode loop: the cache
  layers are allocated lazily from the first forward, so measuring the
  footprint up front read an uninitialized cache and dropped the KV
  term from the reported graph-path footprint. The eager path already
  measures after the loop; the graph path now matches it and both
  decode paths report the same cache footprint.

Benchmark
- Seed through the accelerator API (manual_seed_all) so the file
  passes the check-torchcuda changed-file gate and non-CUDA backends
  are seeded through their own API.
- Warmup and trials share one rollout, so the lazy ladder captures are
  absorbed by the warmup and the measured pass is steady-state (caps
  0); the bench also pins continuous_cache_capacity so the captured
  ladder stays valid as prompts grow across turns. --warmup 0 is
  documented as a cold-start measurement.
- Detect graph capture through the accelerator capability API so
  --graph auto exercises the ladder on XPU/NPU instead of silently
  comparing two eager runs.
- Report the captures charged to the measured pass as a caps column.

Tests
- Update the CUDA v1 capture-count assertions to the ladder's public
  behavior: per-call captures of [0, 2, 2] on the refill workload,
  [2, 0, 0, 2, 2] across the recapture scenarios, and 2 total captures
  on the bucketed-prefill refill test.
- Rewrite the ladder unit tests to exercise defaults, overrides,
  rounding/padding, and validation through generate() and the reported
  stats instead of private helpers.

Docs
- Document graph_capture_batch_sizes in inference-engine.rst: accepted
  widths, the powers-of-two default, lazy capture with eager fallback,
  the sparse-vs-dense tradeoff, an override example, and the new stats
  fields.

Signed-off-by: omersajid9 <omersajid.777@gmail.com>
@delock
delock self-requested a review November 24, 2026 02:41
@delock

delock commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

Hi @omersajid9 , as I understand this PR would try to capture for certain bucket size and if there is OOM that caused capture failure, it will fallback to eager for this bucket size. My question is what happens if some rank captured a bucket size and some rank OOMed and fallback to eager? If graph capture needs to forward several times that warm up then there likely to have a forward number mismatch.

@delock

delock commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

Hi @omersajid9 , thanks for your PR. The following is my review comments. I think one blocking issue is a failed capture would cause deadlock between ranks. There are also two followups worth to consider after this PR.

PR #9153 — Review

Verdict: Request changes

deepspeedai/DeepSpeed#9153 · head 3b1022926 · 5 files, +715/−72
OPEN · REVIEW_REQUIRED · BLOCKED · DCO failing

The ladder itself is clean: bucket buffers are zero-copy views, capture is deferred until the
step's buffers are filled, and the signature/state lifecycle still holds. The open issues are
one distributed-correctness defect plus documentation that does not yet describe the code.

Blocking

1. A failed capture on one rank desynchronizes TP collectives

The capture runs 3 warmup + 1 record forward, and each forward issues TP collectives.
If one rank OOMs and silently falls back to eager (:1183) while its peers capture, that
step carries 4 collective groups on one rank and 1 on the other; NCCL pairs by order, so
tokens silently diverge and the rollout hangs at drain. Fix: reuse #9077's
_group_needs_capture all-reduce (or re-raise when world_size > 1) plus a 2-rank test.

2. Public invariants do not match the implementation

:17 promises "never replays a wider graph than the rows it is running", but :996 picks by
max(slot)+1 and slots are never compacted: a retired middle slot leaves a hole (8 slots,
7 retired, one row still replays width 8; measured pad = 14). Say "highest occupied row",
rename _bucket_width's required argument, add a middle-row retirement test, and note that
bucket views must start at row 0. The padding this costs is tracked as a follow-up.

Non-blocking

3. Three docstrings contradict the code

set_write_position says it must be called before each graph replay; _run_bucket
deliberately does not, because the captured graph keeps the address. The base class says
sync_weights is a no-op when co-located, but HybridEngineRollout drops the graphs there.
The re-capture cost sentence in refresh_weights is stale (see Follow-up).

4. Two observability gaps (plus two nits)

decode_padded_rows (:1020) mixes ladder rounding with slot holes — split out
decode_hole_rows. Capture time is excluded from decode_forward_ms (:999) and has no key
of its own — add graph_capture_ms. Nits: graph_capture_batch_sizes=(True,) is accepted
(isinstance(True, int)), and the default ladder has no bound above 128 where gaps stay 2x.

Follow-up

  • Slot-hole padding. Bucket width follows the highest occupied slot, so retiring a middle
    slot keeps the replay wide even when one row is live. Closing it needs compaction (which must
    rebuild slot_by_request, write_positions and static_attention together, and preserve the
    row-0 view invariant) or a scheduler that squeezes survivors — design work, not a doc fix.

  • Per-sync recapture cost. refresh_weights (:258) drops the whole state, so a ladder
    costs up to ⌈log2 B⌉+1 captures per training step instead of one (~124 row-forwards at B=16,
    about 12% of a four-conversation rollout). Worth revisiting once derived tensors can be
    refilled in place — the same end state this and Reuse the static rollout decode graph across calls #9077 both wait for.

Process

DCO is failing: 11fffe9b and afd8e887 have no Signed-off-by. There is no proposal issue,
the Tests section lists only the benchmark command, and every GPU CI job was skipped, so the
unit tests have no executed evidence.

@delock delock left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The blocking issues stated in comments needs to be fixed: graph capture path may not be the same between ranks which may cause deadlock.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants