Repository navigation
Add CUDA graph support for HybridEngine generation - #8271
Merged
Merged
Conversation
Token generation in the HybridEngine is bound by CPU work, not by the GPU. A single decode step issues on the order of 1300 kernel launches, and the kernels finish well before the host can queue the next step. Measured on opt-1.3b with an H100, per-decode-step latency is essentially flat from batch 1 to batch 32 (5.00ms -> 5.37ms) while the GPU work grows 32x, and the model forward accounts for 4.52ms of the 5.22ms step. Capture the decode forward into CUDA graphs, behind a new opt-in `hybrid_engine.enable_cuda_graph` config flag. Two properties of the inference kernels shape the design. The kernels read the current sequence length from a host-side counter (`InferenceContext::current_tokens()`) and pass it to kernels as a launch parameter, which graph capture freezes, so one graph is captured per decode position rather than one overall. That counter is also advanced from host code and is not reachable from Python, so a replay leaves it behind and an eager decode step after a replay would use a stale sequence length. Eager and replayed steps therefore must not be mixed within a sequence, and the choice is made once per sequence in `begin_sequence()` from the pinned generation length. Graphs are refused, with a warning, where captured pointers would not stay valid: ZeRO stage 3 gathers parameters into fresh buffers per generate, `release_inference_cache` frees the buffers graphs write into, and inference tensor parallelism is untested. Capture failures fall back to eager execution rather than failing the job. Measured on opt-1.3b, ZeRO-2, batch 8, 256-token prompt, 128 new tokens, single H100, over an RLHF-style loop: generate 676.7ms -> 360.8ms (1.88x) iteration 812.8ms -> 503.5ms (1.61x) Generated tokens are unchanged: 1024/1024 token agreement with the eager path across all 8 sequences. Peak memory grows by 132 MiB for 127 captured positions. The first generation captures the graphs and is a one-time cost of about 12s. Signed-off-by: Zhipeng Wang <[email protected]>
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
sfc-gh-truwase
approved these changes
Aug 19, 2026
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Aug 19, 2026
Merged
via the queue into
deepspeedai:master
with commit Aug 19, 2026
80c8e5b
15 of 19 checks passed
Collaborator
|
Is it possible to change flag name from |
Collaborator
Author
Let me submit another PR to change it. Thanks for flagging it out:) |
This was referenced Oct 28, 2026
Closed
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 1, 2026
…elerators (deepspeedai#8933) ## Summary The HybridEngine graph-capture paths (per-position decode graphs from deepspeedai#8271 and the continuous-rollout graphs from deepspeedai#8732) were gated on CUDA in several places: a device-name check, an input device-type check, and hard-coded "CUDA graph" naming. This PR replaces them with accelerator capability hooks so any backend that implements graph capture (`create_graph()` returning a graph, `capture_to_graph`, `replay_graph`, and `is_current_stream_capturing`) takes the same code path as CUDA. Two accelerator-specific fixes ride along to make the NPU path actually work: * NPU inference attention switches to the graph-mode flash attention variant (`npu_fusion_attention_v3`): the v1/v2 variants launch work on an internal secondary stream that CANN capture rejects at `capture_end` (error 107025). * The NPU inference shim grows its KV-cache table on demand: `layer_id` is derived from `DeepSpeedSelfAttention.num_layers`, a process-wide counter that only ever grows, so any process that builds a second engine would otherwise index out of bounds. ## Design **Capability gates instead of name gates.** `validate_cuda_graph_support` becomes `validate_graph_capture_support` and rejects backends with `get_accelerator().create_graph() is None` instead of comparing `device_name()` with `"cuda"`. The continuous-rollout path uses the same capability check. Its capture guard (`is_current_stream_capturing`, used by `DeepSpeedStaticCache` to skip host-side bounds checks while recording) already routes through the accelerator abstraction since deepspeedai#8732 (CUDA implementation, safe `False` default); this PR adds the NPU implementation. **Naming.** Internal names, docstrings, and error messages drop the "CUDA" prefix (`validate_graph_capture_support`, "continuous graph capture", "per-position graph"). The config key is renamed to `hybrid_engine.enable_graph_capture` so the flag reads as a backend capability rather than a CUDA-specific feature, following the rename request in deepspeedai#8271's thread. The old `hybrid_engine.enable_cuda_graph` key still works as a deprecated alias: its value migrates to the new field with a warning (the existing DeepSpeed deprecated-field machinery), so existing config files keep working. **NPU flash attention.** `NPUInference._softmax_context` calls `torch_npu.npu_fusion_attention_v3`, the graph-mode variant. The v1/v2 variants rejected capture with "capture model contains a stream that was not joined to the original stream" (107025); after the failed capture the fallback eager path then hit a secondary failure (561103) because host-side counters had already advanced. v3 captures cleanly in the BSH layout (the docs only promise BNSD), and both failure modes disappear together. ## Safety The existing refusals are preserved and remain device-agnostic: ZeRO stage 3, `release_inference_cache`, `inference_tp_size > 1`, and unpinned generation lengths all refuse graphs with a warning and fall back to eager, as do capture failures at runtime. The continuous-rollout path keeps its explicit rejections of aligned decode fronts, cache trimming, and `flash_attention_2` implementations. ## Results ### Old container path (`deepspeedai#8271` methodology) `facebook/opt-1.3b` local weights, ZeRO-2, FP16, single Ascend NPU, 256-token prompt, 128 new tokens: | batch | ms / decode step | tok/s | | ----: | ---------------: | ----: | | 1 | 7.16 | 140 | | 4 | 10.86 | 368 | | 8 | 12.27 | 652 | | 16 | 15.77 | 1015 | | 32 | 22.37 | 1431 | Throughput scales 10.2× over a 32× batch increase. Batch 8, averaged over 4 measured iterations of an RLHF-style loop (eval → generate → train → forward/backward/step): | phase | eager | graph | speedup | | ----------- | -------- | -------- | ------- | | generate | 5436.0 ms | 1578.4 ms | 3.44× | | train step | 797.7 ms | 797.7 ms | 1.00× | | **iteration** | **6233.7 ms** | **2376.1 ms** | **2.62×** | * Generated tokens are unchanged: 1024/1024 token agreement with the eager path (8 sequences × 128 tokens, same input). * Peak memory: 8.94 → 9.04 GiB (+0.10 GiB for 127 captured positions). * One-time capture cost: 8.9 s for the first generation; every later generation replays. ### Continuous rollouts (`deepspeedai#8732` methodology) `gpt2` local weights, FP16, batch 1, 32-token prompt, 32 new tokens, greedy, continuous batching on a single Ascend NPU, two warmup calls and five steady-state measurements: | Mode | Median latency | Throughput | | ----------------- | -------------: | ---------: | | Eager | 1060.44 ms | 30 tokens/s | | Graph reuse | 177.59 ms | 180 tokens/s | That is a 5.97× steady-state speedup, with the first call (including capture) at 395.5 ms reported separately. Two different prompts (seeds 1234/1235) produced token-identical eager and graph outputs (32/32 tokens each) while reusing one capture. ## Tests `tests/unit/hybrid_engine/test_he_graph.py` (renamed from `test_he_cuda_graph.py`): * 16 CPU-only tests covering the generation-length gate, the ZeRO-3 / `release_inference_cache` / `inference_tp_size` rejections, the dispatch state machine, capture-failure fallback, and invalidation on length change. * One end-to-end test (`seq_inference` marker) asserting a graphed generation is token-identical to the same generation run eagerly. Continuous-rollout suite, run on NPU with Transformers 4.57.6: ``` pytest -q \ tests/unit/runtime/rollout/test_continuous_batching.py \ tests/unit/runtime/rollout/test_hybrid_engine_rollout.py \ tests/unit/v1/test_hybrid_engine_rollout_v1.py # 55 passed, 3 skipped ``` NPU end-to-end validation ran locally on a single Ascend NPU (PyTorch 2.10 + torch_npu 2.10.0.post7; Transformers 4.57.6): both paths capture and replay correctly with token-identical outputs, and the eager path is unchanged. The three HybridEngine scripts in DeepSpeedExamples (TODO: fill in the script names) were also run end-to-end on NPU with graph capture enabled. ## Scope The graph flag remains opt-in and off by default; nothing changes for CUDA, whose eager path measured identically before and after. Only ZeRO-2 with `inference_tp_size=1` was benchmarked on the container path, matching the upstream guards. Known limitations carried over or found while measuring: * The NPU train step was measured over 2 iterations: ZeRO-2 on NPU retains ~4.9 GiB of live device memory per train step (not freed by `del`/GC), so a 4-step loop exhausts the 32 GB card. This is unrelated to graph capture and tracked separately. * Generate and train were measured in separate processes (iteration = sum of means; the eval↔train switch overhead is ~0.07% per deepspeedai#8271). * The continuous path on Transformers 5.x still needs the `get_query_offset` Cache-API compatibility work, tracked in deepspeedai#8852; this PR does not include it. ## Related work * deepspeedai#8271 added the per-position decode graphs for CUDA; this PR implements its comment thread's `enable_graph_capture` rename request. * deepspeedai#8732 added the continuous-rollout graphs for CUDA and routed the capture-state check through the accelerator abstraction. * deepspeedai#8852 (open) adds the Transformers 5.x `get_query_offset` support this PR depends on for newer Transformers versions. * Fixes deepspeedai#8932 — the accompanying feature request ([REQUEST][Hybrid Engine] support hybrid engine for non-CUDA), which frames the motivation and the hard-coding analysis. --------- Signed-off-by: Zizhao Tang <[email protected]> Co-authored-by: Ma, Guokai <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
Token generation dominates a HybridEngine RLHF iteration, and it is bound by CPU work rather than by the GPU.
Measured on
facebook/opt-1.3b, ZeRO-2, single H100, 256-token prompt, 128 new tokens:32× the batch costs 1.07× the latency. The GPU is idle waiting on the host. A single decode step issues roughly 1300 kernel launches, and of the 5.22 ms step, 4.52 ms is the model forward while summed kernel time is only ~2.75 ms.
Replaying a captured CUDA graph replaces those launches with one call.
Design
Adds an opt-in
hybrid_engine.enable_cuda_graphflag. Two properties of the inference kernels shape the design.One graph per decode position. The kernels read the current sequence length from a host-side counter (
InferenceContext::current_tokens()incsrc/transformer/inference/csrc/pt_binding.cpp) and pass it to kernels as a launch parameter. Capture freezes launch parameters, so a single graph would keep reading and writing one position forever. Host code does run during capture, so capturing one graph per position records the correct sequence offsets into each.All-or-nothing per sequence. That counter is advanced from host code (
advance_tokens()) and is not exposed to Python. Replay runs no host code, so it leaves the counter behind, and an eager decode step after a replay would use a stale sequence length and corrupt the KV cache. Eager and replayed steps therefore must never be mixed within a sequence.begin_sequence()makes the decision once, up front, from the pinned generation length, before any decode step runs.Capture is followed immediately by a replay, since capture records work without executing it; the replay is what actually fills the KV cache for that position.
Safety
Graphs are refused, with a warning, wherever captured pointers would not stay valid:
attn_qkvw is None). A graph would replay whichever buffers existed at capture time, which is silently wrong rather than merely slow.release_inference_cache— frees the workspace buffers the graphs write into.inference_tp_size > 1— untested here.min_new_tokens == max_new_tokens.Capture failures fall back to eager execution and disable graphs, rather than failing the training job.
Weight updates were verified explicitly:
reset_params()writes into the same inference buffers in place, so the captured pointers stay valid across optimizer steps. After a step that moved the logits by 11.75, replay matched a fresh eager forward to within 0.09 and differed from the pre-step result by the full 11.75 — i.e. graphs track updated weights rather than replaying stale ones.Results
facebook/opt-1.3b, ZeRO-2, batch 8, 256-token prompt, 128 new tokens, single H100, averaged over 4 measured iterations of an RLHF-style loop (eval→generate→train→ forward/backward/step):Tests
tests/unit/hybrid_engine/test_he_cuda_graph.py:release_inference_cache/inference_tp_sizerejections, and the dispatch state machine (unknown length, over-long length, prompt forwards, and invalidation when the generation length changes).seq_inferencemarker,opt-125m) asserting that a graphed generation is token-identical to the same generation run eagerly.Docs: a Hybrid Engine section added to
docs/_pages/config-json.md, covering the config block and the new flag's requirements and restrictions.Scope
Default is off, so nothing changes unless the flag is set; the eager path measured identically before and after this change (676.7 ms generate both ways). Only ZeRO-2 with
inference_tp_size=1was benchmarked, which is what the guards allow.