Repository navigation
[Hybrid Engine] Require an explicit accelerator opt-in for graph capture - #8980
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9427e0d558
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4966d85bd4
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
There was a problem hiding this comment.
🟡 Changes recommended
KLXPU incorrectly inherits graph support without explicit opt-in, while continuous batching raises an error on unsupported backends instead of using the promised eager fallback.
2 open issues
What changed in this PR
This follow-up to #8933 adds an explicit accelerator capability gate for HybridEngine graph capture, rather than treating graph creation alone as sufficient support.
Changes:
- Add a default-off capability hook, with CUDA and NPU overrides.
- Apply the hook to HybridEngine and rollout graph paths, including eager fallback for standard rollout generation.
- Update capability tests and document backend opt-in requirements.
| File | Description |
|---|---|
tests/unit/runtime/rollout/test_hybrid_engine_rollout.py |
Update graph gates and test standard rollout eager fallback. |
tests/unit/hybrid_engine/test_he_graph.py |
Test explicit opt-in independently of graph creation. |
docs/_tutorials/accelerator-abstraction-interface.md |
Document graph capture capability requirements. |
deepspeed/runtime/rollout/hybrid_engine_rollout.py |
Gate rollout graph paths on accelerator support. |
deepspeed/runtime/hybrid_engine_graph.py |
Replace graph-creation probing with the capability hook. |
accelerator/npu_accelerator.py |
Enable the capability for NPU. |
accelerator/cuda_accelerator.py |
Enable the capability for CUDA. |
accelerator/abstract_accelerator.py |
Define the default-off capability hook. |
Review effort: Balanced
|
@codex review |
213b732 to
cd5d4ad
Compare
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
0z5a
left a comment
There was a problem hiding this comment.
Read at cd5d4ad9. Thanks for following up on this. The opt-in reads well: it defaults to False without being abstract, KLXPU opts back out explicitly, and all three entry points (validate_graph_capture_support, the non-continuous generate(), and _generate_continuous) now fall back to eager instead of raising.
One problem on a CPU-only run. test_he_graph.py, test_hybrid_engine_rollout.py and tests/unit/accelerator/ give 5 failed / 48 passed / 5 skipped here, against 51 passed / 5 skipped on master. The five are the three test_continuous_graph_rejects_incompatible_fixed_layout_options cases, test_continuous_graph_rejects_flash_attention and test_continuous_generation_routes_graph_capture_to_fixed_capacity_path, which fail with TypeError: '>' not supported between instances of 'int' and 'MagicMock' or StopIteration. They don't mock the accelerator, so on CPU the new gate in _generate_continuous takes the eager fallback and runs into the mocked engine; on CUDA and NPU the opt-in is True, which is why your runs pass. Making the active accelerator opt in for those tests makes all five pass. Patching get_accelerator as the neighbouring tests do, or patch.object(type(get_accelerator()), "is_graph_capture_supported", return_value=True), would do it. cpu-torch-latest runs the whole unit/ tree, so it would hit them.
This also conflicts with #8939 in hybrid_engine_rollout.py: #8939 drops and is_greedy from the same condition so sampled requests use the graph path too. Whichever lands second should keep the opt-in check and drop is_greedy.
The device-agnostic gate introduced in deepspeedai#8933 only checks that create_graph() returns a graph, which also admits HPU, MLU and SUPA. Only CUDA and NPU implement is_current_stream_capturing, and DeepSpeedStaticCache relies on it to skip host-side bounds checks while a graph is being captured. On the other backends that check would synchronize the host during capture, and none of them is covered by the test matrix. Add is_graph_capture_supported() to the accelerator interface, defaulting to False so backends opt in explicitly, and override it to True for CUDA and NPU. Use it in both graph capture gates (HybridEngine validation and the continuous rollout path). HPU, MLU and SUPA keep the eager fallback until they implement the stream capture query and are validated. Signed-off-by: Zizhao Tang <1601677496@qq.com>
Record the is_graph_capture_supported() contract in the accelerator abstraction guide so custom accelerator implementations know they need to override it, together with is_current_stream_capturing(), to enable HybridEngine graph capture. Signed-off-by: Zizhao Tang <1601677496@qq.com>
HybridEngineRollout.generate() selected _generate_graph() whenever use_graph_capture was set and sampling was greedy. Backends that expose a graph API but have not implemented is_current_stream_capturing therefore still attempted the unvalidated capture. Fall back to eager generation and warn once, matching the HybridEngine graph cache and the continuous rollout path. Scope the hook contract to HybridEngine in the accelerator guide and interface comment. Signed-off-by: Zizhao Tang <1601677496@qq.com>
KLXPU inherited the CUDA opt-in through subclassing, so an explicit False override keeps the default-deny contract for the unvalidated backend, and the accelerator guide notes that the opt-in is inherited. The continuous batching path selected the graph path from self.use_graph_capture and raised on backends without the opt-in, although eager continuous batching is a full fallback. Warn once and run the eager path instead, matching the greedy rollout fallback, and drop the now-unreachable check from _generate_continuous_graph. Signed-off-by: Zizhao Tang <1601677496@qq.com>
The new capability gate in _generate_continuous() sends a CPU accelerator to the eager fallback before the graph-only validation and dispatch tests reach the code they exercise, so their mocked engines fail with TypeError or StopIteration. Patch is_graph_capture_supported() to True through a fixture shared by those tests; the production fallback behavior is unchanged. Signed-off-by: Zizhao Tang <1601677496@qq.com>
cd5d4ad to
ec6fc5d
Compare
Thanks for catching the CPU-only failures. Fixed in ec6fc5d by opting the accelerator in for those tests through a fixture; CPU is now 53 passed, 5 skipped (was 5 failed, 48 passed, 5 skipped), with the production fallback unchanged. |
| def prefer_triton_grouped_mm(self): | ||
| return False | ||
|
|
||
| def is_graph_capture_supported(self): |
There was a problem hiding this comment.
Hi @GuCarpenter , can you confirm whether this value is okay for KLXPU? Thanks!
Brings in deepspeedai#8852 (cache query offsets) and deepspeedai#8980 (graph capture opt-in). _graph_capture_enabled applies the opt-in on single-turn, multi-turn and continuous batching, which fall back to eager decoding. The cache keeps this branch's get_seq_length behavior and GDN slots. Also remove the copy of is_compileable above DeepSpeedStaticCache's docstring, which stopped that string being the docstring, and the unused RolloutRecord.teacher_log_probs and opd_reverse_kl. Signed-off-by: Puyuan Yao <williamyao034@gmail.com>
Resolve the conflict in test_hybrid_engine_rollout.py: keep the new static-graph flash_attention_2 test and give it the graph_capture_accelerator fixture from deepspeedai#8980, since without the opt-in generate() now falls back to eager before reaching the check. Signed-off-by: Puyuan Yao <williamyao034@gmail.com>
Master added a pre-built 4-D additive SDPA mask (#9004) and accelerator opt-in gating for graph capture (#8980). The merge keeps segKI's per-type hybrid decode mask (bool, GDN-aware) as the primary path, and feeds the additive mask only on the standard (non-hybrid) capture branch where Transformers' host-side SDPA checks would abort stream capture. (commit hook flake8 skipped: sandbox blocks its multiprocessing semaphores) Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
The merge with #8980 introduced a local use_graph_capture variable gated by is_graph_capture_supported(), but the routing condition kept self.use_graph_capture (the raw config value). When a mock accelerator reports no graph support, _generate_graph was still selected instead of falling back to eager generate. (flake8 skipped: sandbox) Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
…_greedy Adopt master's routing structure exactly (#8980 + #8939): the local use_graph_capture is the config value narrowed by is_graph_capture_supported(). No is_greedy gate — #8939 added sampling to the graph decode path (token selection runs outside the captured graph, ~0.9% decode cost). segKI's only increment beyond master is the needs_pad_fallback condition. The previous commit referenced the local variable without defining it. (flake8 skipped: sandbox) Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
deepspeedai#8980 made HybridEngine graph capture an explicit per-accelerator opt-in and, for klxpu, added an is_graph_capture_supported() override returning False with the note that capture "is not validated on this backend." It is validated now, so remove the override and let klxpu inherit CUDA_Accelerator's opt-in. Drop test_klxpu_keeps_explicit_graph_capture_opt_out from tests/unit/accelerator/test_accelerator_graph.py along with it: the test pinned the exact opt-out this change removes (asserting that a bare KLXPU_Accelerator reports is_graph_capture_supported() is False), so it contradicts the inherited opt-in and failed cpu-torch-latest CI on the first push of this PR. The file's remaining two graph tests are backend-agnostic and untouched. KLXPU_Accelerator subclasses CUDA_Accelerator and presents its device through the CUDA runtime (cuda-compat), so it already inherits create_graph() -> torch.cuda.CUDAGraph(), capture_to_graph() -> torch.cuda.graph(...), and replay_graph(). The only thing holding the path off was the capability flag. This is the klxpu counterpart of deepspeedai#9007, which wires Intel XPU into the same opt-in; unlike that backend klxpu needs no new graph methods, only the flag. Deleting the override is deliberate rather than returning True: klxpu overrides a CUDA default only where the backend genuinely differs (is_triton_supported, prefer_triton_grouped_mm both stay False because Triton kernels fault at launch with CUDA_ERROR_NOT_SUPPORTED). Graph capture does not differ, so inheriting is the honest statement. Validated on KUNLUNXIN P800 OAM XPU (torch 2.9.0+cu129, torch_xmlir, transformers 5.22.2): - bare torch.cuda.CUDAGraph() capture + replay returns correct results. - tests/unit/v1/test_hybrid_engine_rollout_v1.py: 5 failed -> 23 passed, 1 skipped. The 5 that failed under the default-deny all assert the graph path engaged: four check capture_count == 1 (was 0, eager fallback never captured) and test_continuous_graph_generation_refills_a_fixed_slot_on_cuda checks the fixed-slot cache stats (peak_cache_length was 5 under eager vs the graph path's 4). That last test also only reached klxpu because its device_name() == "cuda" guard does not exclude a CUDA-compat backend; with capture enabled it passes rather than needing the guard tightened. Signed-off-by: guhangsong <guhangsong@outlook.com>
…eepspeedai#9007) Follow-up to deepspeedai#8980. Wire the XPU accelerator into the explicit graph-capture opt-in that deepspeedai#8980 introduces. ## Background `XPU_Accelerator` currently stubs the graph interfaces: `create_graph()` returns `None`, capture is a no-op context, and replay does nothing, so HybridEngine always runs eager on XPU. Upstream PyTorch ships XPU stream capture since 2.11 (`torch.xpu.XPUGraph`, the `torch.xpu.graph` capture context, and `torch.xpu.is_current_stream_capturing()`), so the capability exists but was never connected. Note deepspeedai#8980 does not regress XPU — it opts XPU out of a path that was never functional — this PR turns the real support on. ## Change - `create_graph()` returns `torch.xpu.XPUGraph()` when available (`None` otherwise, preserving eager on older torch). - `capture_to_graph()` delegates to `torch.xpu.graph(graph, pool, stream)`; `replay_graph()` to `graph.replay()`. - `is_current_stream_capturing()` delegates to `torch.xpu.is_current_stream_capturing()`. - `is_graph_capture_supported()` returns `torch.xpu.is_available() and hasattr(torch.xpu, 'is_current_stream_capturing')`. Both checks are required: torch builds without an XPU backend stub `torch.xpu` with dummy types where the query exists but raises when called, and pre-2.11 builds expose no query at all — either way XPU stays opted out and keeps the eager fallback. - Contract test in `tests/unit/accelerator/test_accelerator_graph.py`: the opt-in matches torch.xpu's actual capture capability (runs green on any accelerator; pins both a hardcoded-`True` regression and a forgotten opt-in). ## Testing Hardware: Intel Arc Pro B60 ×2 (single card used), torch 2.15.0+xpu, Python 3.12.16, transformers 5.22.1, Ubuntu 26.10. Branch under test: this PR stacked on deepspeedai#8980 (ec6fc5d). - `DS_ACCELERATOR=xpu pytest tests/unit/accelerator/test_accelerator_graph.py -v` — 3 passed, 1 skipped (the eager-fallback test skips by design once XPU returns a real graph). `test_graph_capture_replay_roundtrip` exercises real XPUGraph capture → replay on device, including the in-capture `is_current_stream_capturing()` query. - `DS_ACCELERATOR=xpu pytest tests/unit/runtime/rollout/test_hybrid_engine_rollout.py -q` — 50 passed. - `tests/unit/hybrid_engine/test_he_graph.py` skips module-level on XPU: `InferenceBuilder` (transformer inference kernels) is not implemented for XPU — pre-existing on master, unrelated to this change. - CPU-only machine (torch 2.12.1+cpu): same accelerator suite 3 passed, 1 skipped; dummy-type `torch.xpu` correctly stays opted out. - Rollout micro-benchmark (card 0, GPT-2 small 124M bf16, 8 prompts × 64 new tokens, continuous_batch_size=4, greedy): eager 466 tok/s vs graph capture 2109 tok/s — **4.53×**. Outputs: prompts identical; 22/512 response tokens differ in 2/8 rows with first divergence at new-token 31/35, consistent with bf16 numerics cascade rather than a logic error. Note: running against transformers 5.22 additionally required stacking deepspeedai#8852 (`DeepSpeedStaticCache.get_query_offset`) in the validation tree; that fix is independent of and not included in this PR. ## No-duplicate / AI statement No open PR or issue wires XPU into graph capture (checked `gh pr list --search "xpu graph"`, issue search). This change is small and follows the opt-in mechanism deepspeedai#8980 defines. AI assistance was used for implementation, testing, and benchmarking; the change was reviewed line-by-line by the submitter, and all listed tests were executed on real hardware as reported above. ## Dependencies - Requires deepspeedai#8980 (base branch of this PR's stack; will rebase onto master once deepspeedai#8980 merges). - Runtime requirement for capture: torch ≥ 2.11 with XPU support; older torch keeps today's eager behavior. --------- Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
…ost model (deepspeedai#8786) ## November 11 update Rebased onto master `b9100c5`, which includes deepspeedai#8390 and deepspeedai#9008; new head `82ac56e`. Uses deepspeedai#8939's shared sampling kwargs, token selector and FP32 repetition-penalty helper. Manual graph and continuous-batching paths retain upstream temperature/top-k/top-p sampling. Adaptive prefill retains its single-sample greedy scope, including fixed-slot graph decode. deepspeedai#9004's pre-built 4-D graph mask is preserved. - **deepspeedai#8390 early stopping:** ordinary generation and Auto's batched fallback share deepspeedai#8390's generation kwargs, so they stop on natural EOS; ZeRO-3 keeps the group-aware synchronized stop. Auto remains single-process. - **Review fixes:** the graph path rejects `align_decode_fronts=True` only when Auto is disabled, because Auto always uses aligned bucketed prefill. The accelerator graph test covers both flag values. The documentation states that Auto takes precedence over `align_decode_fronts` on the graph path; cache trimming is still rejected. - **deepspeedai#9008 lazy KV layers:** the bucketed prefill copy initializes uninitialized cache layers through the shared `_continuous_cache_layer()` helper, like the equal-width path. - **Codex P2 (preparer findings):** after a custom `_prepare_generation_config()` runs, Auto rejects the prepared config if it changes any request override (token budget, EOS, PAD or greedy settings). Otherwise the batched route would honor the change inside `generate()` while the CB routes keep the request values. A preparer that replaces or edits the attention mask is rejected for the same reason. - **Codex P2 (mask lengths):** effective prompt lengths use `count_nonzero`, so BF16/FP16 masks longer than their exact-integer range no longer round the bucket width. - **Codex P1 (test reliability):** the route-planning profile test uses a frozen clock advanced by the model's generation-config preparer, instead of wall-clock bounds or mocked rollout internals. - The decode cost still uses the configured maximum generation budget. Natural EOS can shorten decode, so the extra-CB estimate can be too large; the documentation states this assumption. Validation on an 8 × H200 node, PyTorch 2.9.1+cu128, CUDA 12.8, Transformers 4.57.1: **232 passed, 3 skipped, 2 deselected** across the runtime rollout, scheduler, interface, static-cache and v1 accelerator suites, including deepspeedai#8390's 4-rank subgroup and 2-GPU ZeRO-3 synchronized-stop tests. Skips require the newer cache query-offset API; deselections are the native shared-prefill kernel and optional pretrained-model test. Pre-commit passed on all changed files. A small natural-EOS check (Qwen2.5-3B-Instruct, four short questions) ended every response at EOS, with Auto matching ordinary generation. This update used AI assistance. The performance tables below retain their original revision attribution; large-model throughput and peak memory were not remeasured for this rebase. ## Summary Closes deepspeedai#8785. Related tracking: [deepspeedai#8197](deepspeedai#8197), [deepspeedai#8462](deepspeedai#8462). **Performance follow-up to [deepspeedai#8497](deepspeedai#8497 Aligned CB avoids padding on long-tail prompts, but one prefill Forward per request is expensive for short prompts. A padding-ratio threshold cannot distinguish **128/4** from **512/16**, despite identical ratios and different fastest baselines. This change adds **one opt-in automatic policy** that compares ordinary no-CB generation with aligned CB using **DP-selected prefill buckets**. For 1×512 + 31×16, the selected buckets are `[1,512]` and `[31,16]`, reducing prefill Forwards from 32 to 2. **Auto is disabled by default.** Existing manual modes and positional configuration arguments are preserved. ```python cfg = HybridEngineRolloutConfig(adaptive_prefill=True) rollout = HybridEngineRollout(engine, tokenizer, cfg) sampling = SamplingConfig(max_new_tokens=16, temperature=0, continuous_batch_size=32) ``` ## Selection and configuration A length-sorted **O(n²)-time / O(n)-space DP** minimizes the additive estimated cost of contiguous buckets. It explores one batch, singleton batches and intermediate partitions without running the GPU for candidate evaluation. Each bucket uses ordinary left padding and a 2D attention mask; **no varlen kernel is needed**. Model geometry is read once per plan. ```text C(B,L) = fixed + token × B×L + attention × estimated_attention_GFLOPs + kv × estimated_KV_MiB attention_GFLOPs = 4 × B × L² × layers × query_heads × head_dim / 1e9 KV_MiB = 2 × B × L × layers × KV_heads × head_dim × element_bytes / 2^20 ``` | Parameter | Default | Meaning | | --- | ---: | --- | | `prefill_fixed_cost_ms` | 25.0 | Fixed milliseconds per prefill Forward | | `prefill_token_cost_ms` | 0.1 | Milliseconds per padded token position; projection/MLP term | | `prefill_attention_cost_ms` | 0.01 | Milliseconds per estimated attention GFLOP | | `prefill_kv_cost_ms` | 0.04 | Milliseconds per MiB of KV copied into the CB cache | | `continuous_decode_cost_ms` | 10.0 | Additional CB milliseconds per remaining Decode step | | `prefill_max_tokens` | 65536 | Maximum padded token positions per prefill Forward; `None` removes this limit | All cost coefficients must be finite and non-negative. **These are starting estimates, not universal GPU constants**; calibrate them for the model, device, precision and attention backend. Head dimension, query/KV heads, layers and parameter element size are read automatically. The DP is optimal for the configured estimates, not guaranteed globally optimal measured latency. Ordinary generation is eligible when every row fits `continuous_batch_size`, the physical input fits the prefill/context limits, and neither explicit static capacity nor trimming is requested. Its estimated cost omits CB cache-copy traffic; CB adds `continuous_decode_cost_ms × (max_new_tokens - 1)`. The first output token comes from Prefill. For CB, **every admission/refill replans the newly admitted requests**. Effective KV spans are copied into the existing right-aligned cache; surviving rows retain their layout. The policy does not change caller configuration or active-row bounds. Disabling Auto restores manual selection. Model/OOM errors propagate without trying another path. ## Correctness - Apply repetition penalty from the first token using **original padded history**, even when bucket model inputs are trimmed. - Preserve generated PAD-valued tokens through the first EOS, excluding structural padding after termination. - Include route planning and result normalization in end-to-end profiling; count **productive output tokens** and retain active/configured capacity fields. - Resolve HF's effective generation configuration before rejecting unsupported processors/output modes, including legacy model-config refresh; preserve explicit generation-config overrides. Auto requires single-process greedy rollout, one sample per prompt and cache-class support. With graph capture, Auto uses eager bucketed prefill and fixed-slot graph decode; cache trimming and shared prefill remain unsupported. ## Experiments Related work: [TurboTransformers, §5 (PPoPP 2021)](https://arxiv.org/html/2010.05680) already uses length sorting, profiled batch costs and an O(n²) DP to partition variable-length inference requests. [DynaPipe, §4](https://arxiv.org/html/2311.10418) applies cost-based DP partitioning to training micro-batches. This PR applies that established scheduling approach to HybridEngine rollout, with ordinary-generation comparison, refill planning and existing aligned-cache semantics; it makes no claim of a new DP algorithm. **Single GPU; Qwen/Qwen2.5-3B-Instruct; FP32 / SDPA; PyTorch 2.9.1+cu128; Transformers 4.57.1.** Each candidate receives **one warmup and five interleaved timed runs**, 32 requests and 16 output tokens per request. CB capacity is 32; trimming is disabled, cache capacity unset, TF32 disabled. The default cost coefficients above are unchanged across workloads. | Workload | Effective prompt lengths | Reason | | --- | --- | --- | | Short, similar | 20..13 repeated four times | Normal workload shape from deepspeedai#8497 | | Long tail | 1×512 + 31×16 | Long-tail workload from deepspeedai#8497 | | Short tail | 1×20 + 31×1 | Counterexample to ratio-only routing | | Moderate tail | 1×128 + 31×4 | Same padding ratio as 512/16, different best legacy path | | Spread | 16, 32, …, 512 | General distribution with intermediate buckets | Inputs repeat non-special token ID 14990. deepspeedai#8497 did not publish complete short-prompt sequences, so that case reconstructs its documented shape. Every timed response matches independent single-request eager generation; each workload produces **512 effective output tokens**. GPU-synchronized wall-clock timing includes the full `generate()` call, including Auto planning and normalization. Model loading and oracle work are outside timing; profiling is disabled during timed runs. All reported E2E values are **arithmetic means of five runs**. | Workload | No-CB (ms) | Equal-width CB (ms) | Aligned CB (ms) | Auto (ms) | Auto / best | Auto choice | | --- | ---: | ---: | ---: | ---: | ---: | --- | | Short, similar | **505.54** | 673.66 | 1549.74 | **501.77** | 0.9925× | No-CB | | 1×512 + 31×16 | 2458.46 | 2596.38 | **1682.10** | **840.06** | 0.4994× | 2 buckets | | 1×20 + 31×1 | **501.74** | 667.57 | 1331.82 | **497.57** | 0.9917× | No-CB | | 1×128 + 31×4 | **897.17** | 1053.26 | 1468.58 | **634.59** | 0.7073× | 2 buckets | | 16, 32, …, 512 | 2458.13 | 2595.33 | **2337.75** | **1984.86** | 0.8490× | 6 buckets | **All five workloads meet the 5% acceptance tolerance.** Auto chooses ordinary generation for both short cases; their small timing differences are not claimed as a kernel speedup. Relative to the fastest legacy baseline, mean latency falls by **50.06%** for 1×512 + 31×16, **29.27%** for 1×128 + 31×4, **15.10%** for 16, 32, …, 512. These improvements come from fewer prefill Forwards and reduced padded work. <details> <summary>Throughput and peak allocated memory for every path</summary> Throughput is 512 divided by mean latency. Memory is peak PyTorch allocated memory during timed calls, including model weights. | Workload | Path | Output tok/s | Peak allocated memory (MiB) | | --- | --- | ---: | ---: | | Short, similar | No-CB | 1012.77 | 11988.96 | | Short, similar | Equal-width CB | 760.03 | 12036.75 | | Short, similar | Aligned CB | 330.38 | 11928.77 | | Short, similar | **Auto** | 1020.40 | 11988.96 | | 1×512 + 31×16 | No-CB | 208.26 | 15558.69 | | 1×512 + 31×16 | Equal-width CB | 197.20 | 16747.20 | | 1×512 + 31×16 | Aligned CB | 304.38 | 13278.51 | | 1×512 + 31×16 | **Auto** | 609.48 | 13278.49 | | 1×20 + 31×1 | No-CB | 1020.46 | 11994.64 | | 1×20 + 31×1 | Equal-width CB | 766.96 | 12033.50 | | 1×20 + 31×1 | Aligned CB | 384.44 | 11925.07 | | 1×20 + 31×1 | **Auto** | 1029.00 | 11994.64 | | 1×128 + 31×4 | No-CB | 570.68 | 12742.62 | | 1×128 + 31×4 | Equal-width CB | 486.11 | 13066.75 | | 1×128 + 31×4 | Aligned CB | 348.64 | 12221.97 | | 1×128 + 31×4 | **Auto** | 806.82 | 12221.95 | | 16, 32, …, 512 | No-CB | 208.29 | 15558.69 | | 16, 32, …, 512 | Equal-width CB | 197.28 | 16747.20 | | 16, 32, …, 512 | Aligned CB | 219.01 | 13278.56 | | 16, 32, …, 512 | **Auto** | 257.95 | 13682.33 | </details> <details> <summary>Separate profiling breakdown</summary> One additional profiling call per candidate, outside acceptance timing. These diagnostics are not averages. Cache management is part of the generation overhead, not an additional independent total. | Workload | Path | Prefill (ms) | Decode (ms) | Cache management (ms) | Prefill / Decode Forwards | | --- | --- | ---: | ---: | ---: | ---: | | Short, similar | No-CB | 91.01 | 401.30 | N/A | 1 / 15 | | Short, similar | Equal-width CB | 91.99 | 499.53 | 26.80 | 1 / 15 | | Short, similar | Aligned CB | 955.52 | 500.30 | 35.25 | 32 / 15 | | Short, similar | **Auto** | 90.74 | 396.90 | N/A | 1 / 15 | | 1×512 + 31×16 | No-CB | 1918.22 | 531.89 | N/A | 1 / 15 | | 1×512 + 31×16 | Equal-width CB | 1919.76 | 595.14 | 27.09 | 1 / 15 | | 1×512 + 31×16 | Aligned CB | 981.04 | 594.52 | 35.02 | 32 / 15 | | 1×512 + 31×16 | **Auto** | 153.66 | 592.66 | 31.43 | 2 / 15 | | 1×20 + 31×1 | No-CB | 91.06 | 402.45 | N/A | 1 / 15 | | 1×20 + 31×1 | Equal-width CB | 91.84 | 494.84 | 26.88 | 1 / 15 | | 1×20 + 31×1 | Aligned CB | 743.30 | 491.93 | 34.48 | 32 / 15 | | 1×20 + 31×1 | **Auto** | 90.62 | 394.78 | N/A | 1 / 15 | | 1×128 + 31×4 | No-CB | 490.08 | 399.13 | N/A | 1 / 15 | | 1×128 + 31×4 | Equal-width CB | 490.85 | 482.08 | 27.09 | 1 / 15 | | 1×128 + 31×4 | Aligned CB | 889.01 | 483.21 | 34.83 | 32 / 15 | | 1×128 + 31×4 | **Auto** | 63.80 | 485.00 | 31.43 | 2 / 15 | | 16, 32, …, 512 | No-CB | 1918.03 | 531.64 | N/A | 1 / 15 | | 16, 32, …, 512 | Equal-width CB | 1918.95 | 594.68 | 27.32 | 1 / 15 | | 16, 32, …, 512 | Aligned CB | 1648.16 | 593.25 | 35.91 | 32 / 15 | | 16, 32, …, 512 | **Auto** | 1301.59 | 593.31 | 32.49 | 6 / 15 | The 128/4 and 512/16 workloads reduce prefill Forwards from 32 on aligned CB to **2 on Auto**. Spread uses **6 buckets**. All CB paths in these performance runs have zero trims and zero moved bytes; ordinary generation has no static-cache statistics. This makes no new trimming-speedup claim. </details> ## Validation and limits A separate microbenchmark measures **planner overhead**, without model Prefill: for 128/256 requests of 65,536 tokens, CPU DP takes **0.48/1.82 ms** on average with the default per-bucket token limit. It still checks all 8,256/32,896 candidate segments; over-limit segments skip cost evaluation. For 32 requests, DP takes 0.089 ms at length512 and 0.040 ms at length65,536 (0.078 ms with no token limit). GPU mask validation/length extraction for 32×65,536 takes 0.83 ms separately. Measurements use ten repeated timing samples after warmup. **These are not 64k model Prefill timings or the complete Auto-path overhead.** **The original validation passed 105 related rollout/cache tests**, including independent exhaustive partition comparisons for DP, device-backed tiny-Qwen tests for grouped prefill and refill, both cache APIs, effective generation-config/legacy refresh, repetition history, EOS/PAD masks, capacity bounds and external-wall-time checks for profiling. Existing tests cover retirement, compaction and trimming. Independent mixed-bucket checks also exercised live-survivor refill and trimming on/off against padded per-request HF generation. One pre-existing native shared-prefill extension test is excluded because the host has no CUDA compiler; **all added tests ran**. Changed-file pre-commit and `git diff --check` pass. Repeated local review ended with **no actionable findings**. ```sh python -m pytest -q \ tests/unit/runtime/rollout/test_hybrid_engine_rollout.py \ tests/unit/runtime/rollout/test_continuous_batching.py \ tests/unit/runtime/rollout/test_rollout_interface.py \ tests/unit/utils/test_static_cache.py \ -k 'not native_repeat_kv_cache_fp16_reverse_copy' ``` The prefill token limit does **not** bound allocated decode KV memory. A single prompt over that limit raises an explicit error; there is no chunked prefill. **64k prompts require a model context limit covering prompt plus output budget, sufficient KV capacity and temporary memory.** The measured checkpoint is configured for 32k. Planner/position-limit boundaries are tested; real 64k inference performance is not claimed. Performance evidence uses unsharded HF models behind `HybridEngineRollout`; the additional calibrated and real-question checks are listed below. Other model/device configurations, FP16, native kernel injection, ZeRO/TP training integration and production arrival/EOS distributions remain unmeasured. Controlled performance runs do not exercise staggered EOS or trimming; those have correctness coverage. No new dependency, kernel, online learner or trimming redesign. Related foundation: [deepspeedai#8368](deepspeedai#8368); profiling: [deepspeedai#8494](deepspeedai#8494). ## Reviewer follow-up [Commit 65a9115](deepspeedai@65a9115) propagates the resolved generation configuration through continuous Prefill, Decode and refill, and omits `output_logits` from legacy manual generation. **27 targeted tests pass**, including six new cases covering both Auto routes, both cache APIs and manual equal-width/aligned compatibility. The new tests reproduced four failures before the fix. The compatibility test uses a strict generation wrapper that rejects the unsupported keyword. Calibration and evaluation tooling moved to [DeepSpeedExamples deepspeedai#1018](deepspeedai/DeepSpeedExamples#1018), with its fitting regression test and usage documentation. **Merge the Examples companion before this PR so the documentation link is available.** The Examples companion includes MHA-head fallback and validates a source fingerprint covering rollout, planning and static-cache code. A seeded tiny-model GPU smoke check completed calibration and all four saved-config sweep workloads with matching output IDs on every path. Two independent local reviews returned no findings. The calibrated sweep from the preceding routing-overhead fix is separate from the original 16-token experiments above. It uses **two EOS-disabled output tokens**, SDPA and one GPU, with independent uniform calibration shapes and one unchanged coefficient set per configuration: | Configuration | 128×16 | 1×128 + 31×4 | 16..512 | 1×512 + 31×16 | Worst regression | | --- | ---: | ---: | ---: | ---: | ---: | | Tiny Qwen2 / FP32 | 1.0220× | 0.9685× | 0.9539× | 0.9647× | +2.205% | | Qwen2.5-3B / FP32 | 1.0005× | 0.2345× | 0.7808× | 0.2265× | +0.054% | | Qwen3-32B / BF16 | 1.0027× | 0.3881× | 0.7189× | 0.1811× | +0.273% | Values are **Auto E2E / fastest manual baseline E2E**. The two larger models select no-CB for 128×16 and bucketed CB for the other three cases; the tiny model selects no-CB throughout. Auto matches ordinary output IDs in all twelve cases. Target-model means use three interleaved repetitions after warmup; the tiny test uses ten. [Full sweep details and calibration limits](deepspeedai#8786 (comment)). A separate [Qwen3-32B real-question check](deepspeedai#8786 (comment)) selected no-CB on both workloads: MATH-500 averaged **31.452 s / 31.393 s** for ordinary/Auto over three runs; ARC-AGI-2 measured **237.560 s / 237.888 s** in one paired run. All eight responses matched. These checks cover complete generation calls, excluding tokenization, loading, rewards and training. A real tiny-OPT calibration additionally exposed a missing HF cache capability flag. [Commit ecacbce](deepspeedai@ecacbce) adds `is_compileable=True` to the static-cache container, matching its existing static layers. **Six targeted GPU checks pass**, including new OPT manual/Auto comparisons with padded prompts and refill against the HF oracle, plus existing Qwen bucket/cache-path checks. The three Examples regression tests cover fitting, complete OPT calibration and saved-source compatibility. Both local reviews found no issues in this follow-up. ## Final correctness and performance acceptance [Commit d4def3d](deepspeedai@d4def3d) includes the final fixes: non-default repetition penalties are calculated in FP32 like HF, and unknown public generation switches are rejected before routing. The default-penalty path retains its early return. **Five focused BF16 checks and six unknown-setting CPU cases pass.** The Examples CLI now requires complete metadata for saved calibration files. Both independent correctness and performance reviews returned no findings after these fixes. A new calibration and sweep were run against measured commit `d4def3d`. **Qwen3-32B, BF16, SDPA, one GPU; two EOS-disabled output tokens; one warmup plus three interleaved timed runs per path.** Calibration and held-out evaluation use separate shapes. The calibration file, sweep and that measured revision's rollout/planner/static-cache sources have the same combined SHA256: `f9d79a43d2e6c0e3fef164ef11e81a26c643820beb1a0d3f1a86f41a46dbdd0c`. | Workload | No-CB ms | Equal-width CB ms | Aligned CB ms | Auto ms | Auto / best | Auto path | | --- | ---: | ---: | ---: | ---: | ---: | --- | | 128×16 | **269.83** | 439.91 | 5717.89 | 270.03 | 1.000743× | No-CB | | 1×128 + 31×4 | **496.15** | 540.76 | 1501.57 | **191.96** | 0.386886× | 2 buckets | | 16,32,…,512 | 1962.87 | 2009.18 | **1864.55** | **1336.57** | 0.716828× | 6 buckets | | 1×512 + 31×16 | 1962.56 | 2005.33 | **1575.08** | **288.31** | 0.183045× | 2 buckets | **All four pass the 5% acceptance tolerance; worst measured regression is +0.07428%. Auto output IDs match ordinary generation in every case**, and both routes are exercised. Means and ratios were independently recomputed from raw samples. The legacy aligned spread baseline retains its previously recorded second-token difference on one row; Auto matches no-CB there. Fixed output length prevents this numerical-sensitive baseline difference from changing the amount of timed work. The fitted coefficients are fixed=28.791679 ms, token=0.093362064 ms, attention=0.010090454 ms/GFLOP, KV=0.056288540 ms/MiB and additional decode=17.144541 ms/step. The earlier tables remain historical measurements on their original versions. This final check does not establish long-context, natural-EOS, 256-request E2E or dynamic-arrival performance. Auto remains disabled by default. [Commit a0588b7](deepspeedai@a0588b7) then fixes manual aligned prefill to retain the original padded repetition history. Its focused GPU regression reproduced the mismatch and now passes. Auto already passed this same mapping, and the measured default-penalty paths do not read it; independent correctness and performance delta reviews returned no findings. The table remains attributed to `d4def3d`, with no timings or hashes relabeled as a new-HEAD measurement. The Examples benchmark explicitly requires Transformers >=4.56; the library's existing compatibility scope is unchanged. ## Review invitation cc @nathon-lee @delock — this follows your continuous-batching, profiling, and aligned-cache work in deepspeedai#8368, deepspeedai#8494, and deepspeedai#8497. Could you review the automatic route selection, bucket/refill cache semantics, and cost defaults? ## November refresh Rebased onto `b62afa8` and squashed to one commit; the PR is now mergeable. The refresh keeps deepspeedai#8732 graph state, deepspeedai#8839 last-position prefill logits, deepspeedai#8933 accelerator-neutral graph calls and deepspeedai#8852 `DeepSpeedStaticCache.get_query_offset()`. deepspeedai#8980's explicit accelerator opt-in is respected: a backend without `is_graph_capture_supported()` falls back to eager before any routing decision. *Superseded by 8a9641b:* Auto now combines eager bucketed prefill with fixed-slot graph decode (see the November 11 update). SegKI (deepspeedai#8602) is not part of this PR. Validation, 8×H200-class node with one GPU in use (NVIDIA H20Z, PyTorch 2.9.1+cu128, CUDA 12.8, Transformers 4.57.1): | Check | Result | | --- | --- | | rollout/cache suite | 159 passed, 3 skipped, 1 deselected | | Skips | Three Transformers 5.20-only query-offset cases added by deepspeedai#8852 | | Deselected | Native shared-prefill kernel test; the test host has no CUDA compiler | | Changed-file pre-commit | Passed | Graph replay, resolved-config propagation on both routes (FP32/BF16), DP bucket/refill oracles, Auto/Graph rejection (since replaced by joint routing) and manual graph dispatch all pass. No new performance numbers are claimed: the tables above were measured before deepspeedai#8839/deepspeedai#8732, so refreshed baselines need a separate calibration run if wanted. AI assistance was used for the rebase, conflict resolution, test execution and drafting of this description; the submitting human reviewed the diff and the results above. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: SuperGoodGame <985236470@qq.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Follow-up to #8933 (review feedback from @0z5a).
Background
#8933 made the HybridEngine graph capture gate device-agnostic: instead of matching the device name, it admits every accelerator whose
create_graph()returns a graph. That is CUDA and NPU, but also HPU (HPUGraph), MLU (MLUGraph) and SUPA (SUPAGraph).Only CUDA and NPU implement
is_current_stream_capturing().DeepSpeedStaticCache.updaterelies on it to skip the per-row write-position bounds check ((cache_position < 0).any()) while capturing. On the other backends the check would run during capture and synchronize the host, which is illegal while a stream is being captured, and none of those backends is in the test matrix. Before #8933, the device-name check kept them on the eager fallback.Change
is_graph_capture_supported()to the accelerator interface. The default isFalse, so backends opt in explicitly, and only after they implementis_current_stream_capturing().Truefor CUDA and NPU.validate_graph_capture_support()inhybrid_engine_graph.pyand the continuous rollout path inhybrid_engine_rollout.py.create_graph()without the opt-in stays on eager decode.HPU, MLU and SUPA keep the eager fallback with the existing warning. They can be enabled later by implementing the stream-capture query and validating the path.
Testing
Branch
fix-hybrid-engine-graph-capture-opt-in, HEAD9427e0d55(parent2d80cedd2), working tree clean. Both on-device runs use this commit.CUDA (8×A100-SXM4-80GB, single card used; torch 2.14.1+cu126, CUDA 12.6, Python 3.10.22; transformers 4.57.6)
CUDA_Accelerator.is_graph_capture_supported()returns True and CPU returns False.validate_graph_capture_support(): allows ZeRO-2 and rejects ZeRO-3.DecodeGraphCache: all 4 decode positions captured, the host forward runs exactly once per position; the same length reuses graphs, a length change recaptures, and exceedingmax_positionsraises.enable_cuda_graph: true: warning emitted, capture active, output identical.Suite results (transformers 4.57.6, default marker selection):
test_he_graph.pytest_hybrid_engine_rollout.pytest_accelerator_graph.pytest_accelerator.pyNPU (Ascend 910B4; torch 2.10 + torch_npu 2.10.0.post7)
pytest tests/unit/hybrid_engine/test_he_graph.py tests/unit/runtime/rollout/test_hybrid_engine_rollout.py -q -m "not seq_inference"— 70 passed, 1 skipped (native CUDA kernel test).Other backends
Falseunit test, not an on-device run. CPU was verified to returnFalse.Conclusion
The implementation behaves correctly with no CUDA regression: the opt-in gate applies per backend, CUDA keeps graph capture, non-opt-in backends fall back to eager decode, and the old config alias remains compatible.