feat(rollout): segment-based kernel injection for hybrid-engine greedy decode #8602
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b31faddfc4
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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".
</details>
<sub><sub>!P1 Badge</sub></sub> Add the required Signed-off-by trailer
This non-merge commit's stored message has no Signed-off-by trailer, so it violates the repository's mandatory commit-signoff requirement and can be rejected by DCO/CI checks.
AGENTS.md reference: AGENTS.md:L8-L9
Useful? React with 👍 / 👎.
<sub><sub>!P1 Badge</sub></sub> Preserve the original MLP activation
The structural selector accepts every bias-free module with these three projection names, but this replacement always computes SiLU. A GELU-gated MLP such as Gemma satisfies that selector and will therefore silently produce different logits whenever use_segki=True; constrain detection to SiLU MLPs or retain/call the module's configured activation.
Useful? React with 👍 / 👎.
<sub><sub>!P1 Badge</sub></sub> Flatten GLU activations before computing gradients
For normal decoder MLP inputs shaped [batch, sequence, hidden], this branch is used during backward, but Tensor.t() only accepts tensors with at most two dimensions. Consequently, a training step through any injected GLU with a 3-D activation fails at this expression; flatten the leading dimensions as the GDN backward path does before forming the weight gradients.
Useful? React with 👍 / 👎.
<sub><sub>!P1 Badge</sub></sub> Fall back when segment-KI inputs are not bf16
A CUDA use_segki=True rollout installs the native GDN op regardless of model dtype, and the b=1 decode path passes it here. quad_gemv unconditionally obtains BFloat16 data pointers, so ordinary fp16 Qwen3.5 inference raises instead of using the composite path; gate native dispatch on bf16 (and contiguous compatible weights) or provide an fp16 kernel.
Useful? React with 👍 / 👎.
<sub><sub>!P1 Badge</sub></sub> Keep fused RMSNorm scale tied to its Parameter
This creates a detached, independent copy of the RMSNorm scale at injection time. After a co-located training step updates post_attention_layernorm.weight, graph decode still multiplies by the stale copy, so rollout no longer reflects the trained model; compute the scale from the live parameter in the forward path or refresh it after updates.
Useful? React with 👍 / 👎.
<sub><sub>!P1 Badge</sub></sub> Do not invoke the bf16 graph kernel for fp16 logits
The graph-step op is loaded and used for every batch-one graph capture, even when use_segki is false, but decode_step_graph rejects logits that are not CUDA bf16. Existing fp16 graph-capture rollouts therefore fail during capture rather than reaching a fallback; only add this node for bf16 logits or retain the PyTorch argmax/update path.
Useful? React with 👍 / 👎.
<sub><sub>!P1 Badge</sub></sub> Reveal the current KV slot after graph replay
After the first captured decode forward, new_pos is the slot that will hold the next input token, but this reveals new_pos + 1. Thus any full-attention layer that remains on native SDPA sees its current KV slot masked and an unwritten future slot unmasked on the next replay, corrupting generation for models not patched by install_decode_attention; reveal new_pos instead.
Useful? React with 👍 / 👎.
<sub><sub>!P1 Badge</sub></sub> Keep hybrid cache slots compatible with continuous batching
For hybrid configurations this now substitutes DSStaticGDNSlot into the cache layer list, but continuous batching still iterates every layer and unconditionally copies target_layer.keys and target_layer.values in _continuous_prefill. The first admitted request on a model with a linear_attention layer therefore raises AttributeError; skip/pass through linear slots in that prefill and compaction path.
Useful? React with 👍 / 👎.
<sub><sub>!P2 Badge</sub></sub> Pad the CUDA output buffer from device code
When an EOS is found at a periodic check, buf_ptr is a CUDA device pointer, yet this host-side loop dereferences it directly. On normal CUDA allocations this is an invalid host memory access (and can crash) precisely when EOS is encountered; launch a padding kernel or use a device tensor operation instead.
Useful? React with 👍 / 👎.
Two required declarations are missing here: __nv_bfloat16 comes from <cuda_bf16.h>, and binding a Python callable to std::function<void()> requires pybind11's functional type caster. Without these headers the new extension cannot reliably compile/bind the replay callable.
The native gdn_gates pybind op has no autograd implementation, and A_log/dt_bias are explicitly detached immediately below. Because this branch is also taken during training, gradients to the a/b projections, A_log, and dt_bias are cut off, contradicting the co-located training contract. Use the differentiable PyTorch path whenever grad mode is enabled (or add a custom backward).
Using or on cu_seq_lens_q evaluates the truth value of that tensor. A normal multi-element cumulative-length tensor raises RuntimeError: Boolean value of Tensor with more than one value is ambiguous, so packed-sequence calls fail before reaching the scan.
The custom attention kernel receives only Q/K/V and write_pos; it never receives attention_mask. Thus a batch-1 request with left/right padding attends cached keys for padded prompt positions, unlike the original SDPA path, and produces different logits. Either pass/apply the valid-position mask in the kernel or disable this patch whenever the prompt mask is not all valid.
This patch remains installed after rollout, and this condition also accepts a one-token training forward. fused_add_norm is a raw pybind CUDA op without an autograd registration, so such training silently loses gradients through the residual/norm path. Keep grad-enabled calls on the original forward (or provide autograd support).
A newly created DSStaticGDNSlot starts unbound, and this continuous-prefill branch now skips exactly those slots without binding or copying their per-row conv/recurrent state. The next hybrid-model decode calls through __getattr__ and raises DSStaticGDNSlot not bound; compaction would also need to preserve/reorder that state rather than treating it as row-free.
This drops prompt_attn entirely. For padded prompts, full-attention prefill now attends padding, and GDN receives None even though its native forward uses the 2-D mask to zero padding states; the resulting KV/recurrent state and first token are incorrect. Build the same per-layer mask mapping from prompt_attn that the model normally builds rather than replacing both entries with None.
The capture forward advances GDN conv/recurrent buffers regardless of whether decode_step_graph exists, but restoration is conditional on graph_op. If the native op cannot load, the fallback graph starts from a state that already consumed the first decode token and then consumes it again, corrupting hybrid-model generation.
graph_op being available does not mean its step kernel was captured: the condition at lines 922-923 excludes fp16 logits (and non-b=1 inputs), yet this branch still replays the forward-only graph as if token/position buffers were updated. For batch 1 fp16 this returns a mostly zero token buffer. Track a full_step_captured boolean from the actual capture condition and use it here.
full_token_buf contains the prompt prefix, so step + 2 is response-relative while this slice is buffer-absolute. On an EOS checkpoint this pads from inside the prompt/early response and can erase valid tokens (including the detected EOS); offset the slice by prompt_len.
Decode activations reach an HF MLP as [batch, seq, hidden], so the input.dim() == 2 check excludes the normal [1, 1, hidden] greedy-decode case. Consequently the advertised dual-GEMV kernel is never used in the path this PR is intended to accelerate; accept any input containing exactly one hidden vector and preserve its leading shape.
This does not implement the documented composite fallback: every non-CPU backend (including XPU/HPU) attempts to load a CUDA builder, and a CUDA installation without a usable JIT toolchain propagates the load exception out of rollout construction. Restrict the native load to CUDA and fall back when it is unavailable.
The decode attention and triple-GEMV kernels unconditionally interpret buffers as bf16, but this guard allows fp16 models through. With use_segki=True, an fp16 model therefore fails during warmup/capture (hidden must be CUDA bf16) instead of taking the original attention path.
This builder is outside the op_builder package scanned by setup.py/op_builder/all_ops.py:22-32, so DS_BUILD_DECODE_LOOP=1 is never discovered during wheel installation. The op is forced to JIT-build on the target machine despite declaring a build variable. Register it in op_builder and use the accelerator-provided builder path like existing ops.
This builder is outside the op_builder package scanned by setup.py/op_builder/all_ops.py:22-32, so DS_BUILD_FUSED_GLU=1 is never discovered during wheel installation. The op can only JIT-build at runtime, which fails on deployment hosts that have a CUDA runtime but no compiler. Put/register the builder in op_builder and import it here through deepspeed.ops.op_builder, matching the repository's other builders.
This test treats every non-CPU accelerator as CUDA, but _op() builds CUDA-only sources. On XPU, HPU, NPU, or MPS CI the tests run rather than skip and fail while loading the op; gate them specifically on an available CUDA accelerator, as the other CUDA-only test modules do.
There is no automated test that invokes this new native decode loop (or its EOS/padding behavior); the optional model integration takes the full-step graph path when fused_glu loads, so it does not exercise this fallback. Add a direct CUDA contract test with a deterministic replay callable, including early EOS and tail padding.
The documentation lists Gemma as supported, but find_glu_segments deliberately rejects GELU-gated modules (and the new test explicitly verifies this) because the replacement hardcodes SiLU. Leaving Gemma in this list tells users injection occurs when the implementation reports zero replacements.
<!-- ccr-overview-v2 -->
Copilot review overview
🟡 Changes recommended
Several paths currently break gradients, padded prompts, fallback decoding, hybrid continuous batching, and native-op compilation or packaging.
Review effort: Balanced
Findings: 10 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> · 6 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> · 2 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture>
<details open>
<summary><strong>Open (18)</strong></summary>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
Adds segment-based kernel injection and native decode acceleration for hybrid-engine greedy rollout.
Changes:
| File | Description |
| ---- | ----------- |
| csrc/module_inject/fused_glu.cu | Implements fused CUDA kernels. |
| csrc/module_inject/decode_loop.cu | Implements the native decode loop. |
| deepspeed/module_inject/segment_ki.py | Detects and injects fused model segments. |
| deepspeed/module_inject/kernel_reference.py | Provides PyTorch kernel references. |
| deepspeed/ops/module_inject/__init__.py | Exports native-op builders. |
| deepspeed/ops/module_inject/fused_glu.py | Adds the fused-kernel builder. |
| deepspeed/ops/module_inject/decode_loop.py | Adds the decode-loop builder. |
| deepspeed/utils/static_cache.py | Adds hybrid cache slots and position semantics. |
| deepspeed/runtime/rollout/hybrid_engine_rollout.py | Integrates injection and accelerated decoding. |
| tests/unit/module_inject/test_segment_ki_kernels.py | Tests kernels and injection behavior. |
| tests/unit/utils/test_static_cache.py | Updates static-cache expectations. |
| docs/code-docs/source/inference-engine.rst | Documents segment-based injection. |
</details>
---
💡 <a href="/deepspeedai/DeepSpeed/new/master?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a code-review agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>
gemma is removed from support list
decode_loop.cu is removed since fused_glu already support full-step graph path, so this path is not necessary for performance.
better way to detect by detect whether related op builder can be loaded, no need to detect specific GPU type
Hi @delock, thanks for submitting this PR. I have left a few comments and questions.
<!-- ccr-overview-v2 -->
Copilot review overview
🟡 Changes recommended
Graph compatibility, packed GDN execution, projection bias handling, and deterministic argmax behavior have unresolved correctness issues.
Review effort: Balanced
Findings: 3 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> · 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> · 2 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture>
<details open>
<summary><strong>Open (6)</strong></summary>
</details>
<details>
<summary><strong>Resolved since last review (18)</strong></summary>
</details>
Hi @delock, thanks for submitting this PR. I have left a few comments and questions.
Hi @nathon-lee , kindly reminder in case you didn't submit your review comments. Thanks!
Hi, @delock Thanks for the PR and for addressing the earlier comments. I recommend addressing these two points before merging:
1. _generate_graph() no longer passes cache_position or position_ids. A minimal CUDA test with PyTorch 2.9.1, Transformers 4.57.1, and a tiny LLaMA succeeds with explicit position tensors but fails without them with operation not permitted when stream is capturing. This path also runs with use_segki=False. Please preserve the existing compatibility and add a regression test.
2. Most of the numerical tests compare the new kernels with the new reference implementations. Please also compare outputs and gradients directly against the original HF forward, with explicit BF16 tolerances. Bit-for-bit agreement is not necessary, but changes such as the intermediate rounding order in fused residual-add + RMSNorm should be evaluated against the original implementation.
A few additional points to check; I am not treating these as confirmed merge blockers:
logf(1 + expf(x)) loses precision for negative inputs; for example, the FP32 expression produces 0 at x=-20. Please use a stable implementation and check the effect of changing g from FP32 to BF16.
seq_idx, while the scan receives cu_seq_lens_q/cu_seqlens. Please confirm that the supported convolution implementation still receives the packed-sequence boundaries. If packed training is supported, a test comparing outputs and gradients from separate and packed execution would help. Otherwise, please document the limitation.
generate() call, so it does not cover that case. If graph reuse is out of scope, please clarify this in the documentation.
The position-handling regression is reproduced with the versions above. The other points are requests for testing or clarification, not confirmed runtime failures.
Hi @nathon-lee , thanks for the review comments. I have followup them with subsequent commits. There is one finding, fused_add_norm didn't act correctly with BS>1, and it is found by comparing with HF forward.
Hi, @delock Thanks for the PR and for addressing the earlier comments. I recommend addressing these two points before merging:
> 1._generate_graph()no longer passescache_positionorposition_ids. A minimal CUDA test with PyTorch 2.9.1, Transformers 4.57.1, and a tiny LLaMA succeeds with explicit position tensors but fails without them withoperation not permitted when stream is capturing. This path also runs withuse_segki=False. Please preserve the existing compatibility and add a regression test.
2. Most of the numerical tests compare the new kernels with the new reference implementations. Please also compare outputs and gradients directly against the original HF forward, with explicit BF16 tolerances. Bit-for-bit agreement is not necessary, but changes such as the intermediate rounding order in fused residual-add + RMSNorm should be evaluated against the original implementation.
> A few additional points to check; I am not treating these as confirmed merge blockers:
> The GDN softplus expression logf(1 + expf(x)) loses precision for negative inputs; for example, the FP32 expression produces 0 at x=-20. Please use a stable implementation and check the effect of changing g from FP32 to BF16.
The GDN convolution wrapper only forwardsseq_idx, while the scan receivescu_seq_lens_q/cu_seqlens. Please confirm that the supported convolution implementation still receives the packed-sequence boundaries. If packed training is supported, a test comparing outputs and gradients from separate and packed execution would help. Otherwise, please document the limitation.
Is reusing a captured graph after a training step intended to be supported? The current test captures a new graph on each generate() call, so it does not cover that case. If graph reuse is out of scope, please clarify this in the documentation.
Some native-op loading failures fall back silently. Please log the reason at least once so users can tell which path is running.
* Please clarify whether throughput counts executed decode steps or valid response tokens, and report capture overhead separately from steady-state decode performance. Please also update the PR description to reflect the removal of the standalone C++ decode loop.
> The position-handling regression is reproduced with the versions above. The other points are requests for testing or clarification, not confirmed runtime failures.
Hi @delock, thanks for following up. That was a useful catch: the previous fused_add_norm kernel only indexed row 0, leaving the other output rows unwritten for BS > 1. The per-row indexing fix addresses that, and the multi-row kernel check passes here. Good to see the HF comparison caught it.
I did notice one issue at 6647fb30: static_cache.py:103 calls get_accelerator().is_stream_capturing(), but the accelerator interface and implementations do not define it. The existing per-row cache tests fail with AttributeError on both CPU and CUDA; the LLaMA graph path also fails with use_segki=False. Could you include the missing implementation?
<!-- codex-pull-request-review-summary -->
<!-- codex-review-state:v1 {"code_review":{"commit_sha":"cc3e804280ec1a42e0a6143ad092fa56f9a7764c","has_any_findings":true,"has_unresolved_findings":true,"status":"failed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->
Codex Review Summary
This comment shows the latest Codex review activity on this pull request.
| Review | Status | Commit | Review trigger |
| --- | --- | --- | --- |
| 📝 Code Review | ⚠️ Failed <relative-time datetime="2026-10-22T03:22:42.556857Z">2026-10-22T03:22:42.556857Z</relative-time><br/>We couldn’t complete this review. Comment @codex review to try again. | cc3e804 | Draft marked ready |
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Your 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.
</details>
Hi @delock, thanks for following up. That was a useful catch: the previous fused_add_norm kernel only indexed row 0, leaving the other output rows unwritten for BS > 1. The per-row indexing fix addresses that, and the multi-row kernel check passes here. Good to see the HF comparison caught it.
> I did notice one issue at6647fb30:static_cache.py:103callsget_accelerator().is_stream_capturing(), but the accelerator interface and implementations do not define it. The existing per-row cache tests fail withAttributeErroron both CPU and CUDA; the LLaMA graph path also fails withuse_segki=False. Could you include the missing implementation?
Hi @nathon-lee , sorry for the late reply, let me check with latest status of master.
> Hi @delock, thanks for following up. That was a useful catch: the previous fused_add_norm kernel only indexed row 0, leaving the other output rows unwritten for BS > 1. The per-row indexing fix addresses that, and the multi-row kernel check passes here. Good to see the HF comparison caught it.
> I did notice one issue at6647fb30:static_cache.py:103callsget_accelerator().is_stream_capturing(), but the accelerator interface and implementations do not define it. The existing per-row cache tests fail withAttributeErroron both CPU and CUDA; the LLaMA graph path also fails withuse_segki=False. Could you include the missing implementation?
> Hi @nathon-lee , sorry for the late reply, let me check with latest status of master.
Hi @nathon-lee , the latest code should contain this missing implementation. Sorry for inconvience.
The new _ki_prompt_padded check routes every padded batch to HF generate, including with use_segki=False and for non-hybrid models. On master, the graph path handled padded prompts through the attention mask, so this looks like a regression for existing use_graph_capture users. Could the fallback be limited to the cases that need it (segKI kernels and hybrid/GDN models)? Since most rollout batches with different prompts are padded, supporting padding on the segKI path would also matter for real speedups, but that seems fine as a follow-up.
@phoeenniixx Good catch — confirmed on hardware and fixed in 539598ba2. The fallback is now narrowed to exactly the two cases you called out: hybrid models (graph prefill feeds GDN a None mask) and segKI-injected decodes (the decode-attention kernel attends every cached slot unconditionally). Standard use_graph_capture users keep master's padded-batch behavior — the mask flows through prefill and the decode static_attn buffer. Verified on 2×A40 with a padded batch: standard + use_segki=False takes the graph path again with master-identical output; segki and unpadded cases unchanged. Agreed the segKI padding support is the follow-up that matters for mixed-length rollout batches.
The new_ki_prompt_paddedcheck routes every padded batch to HF generate, including withuse_segki=Falseand for non-hybrid models. On master, the graph path handled padded prompts through the attention mask, so this looks like a regression for existinguse_graph_captureusers. Could the fallback be limited to the cases that need it (segKI kernels and hybrid/GDN models)? Since most rollout batches with different prompts are padded, supporting padding on the segKI path would also matter for real speedups, but that seems fine as a follow-up.
A note from external channel: on SegKI: with a ZeRO-3 trainer or a disaggregated rollout, could the injected forward read a separate persistent weight copy (arena views)? Then it would run on top of the resharding path unchanged
Resolved in 9cc11f5a8 (+ e2e in 4e384a201): the injected forward keeps reading the module weights directly — bind param.data to arena views and it runs unchanged on top of the resharding path. One provisional addition while the final handshake is under design: after any in-place weight write, the sync path calls rollout.refresh_weights() to drop derived weight caches (marked PROVISIONAL in the docstrings; the mechanism may change). Verified bitwise-equal-to-fresh-injection at three levels — reshard semantics, arena-view binding, and a real ZeRO-3 loop (tests/integration/zero3_arena_e2e.py) — with captured CUDA graphs staying valid across syncs.
customAR is moved into #8997 as a separate PR, as it is releatively independent.
Hi @delock, while evaluating performance on a single GPU, I found that greedy output on the seg-KI + graph path doesn't match a plain forward of the same model. I traced down to 3 points with help of AI. I tested on 9e7e8dd30. I haven't rerun on the current head 47d426d95, but the same lines are unchanged there.
Hi @anyadontfly thanks for reporting the issues. I can reproduce the first one, and it is being fixed. For the second and third one, I'm still trying to reproduce it, will update here when its done.
delock
Summary
Adds a segment-KI framework that accelerates greedy decode in the hybrid-engine rollout by injecting native CUDA kernels into comm-free segments of the model, plus a C++ decode loop that runs the full autoregressive generation with near-zero per-step Python overhead.
Segment detection: structural, not per-model
Detection is attribute-name based: any HF family whose gated MLP uses
gate_proj/up_proj/down_proj(LLaMA, Qwen, Mistral, DeepSeek, Gemma...) or whose GatedDeltaNet block uses thein_proj_{qkv,z,b,a}set is picked up without per-model code. Projections carrying TP collectives are never fused (a defensiveisinstancecheck against the Allreduce layer hierarchy).Co-location by construction
Both GLU (dual-weight GEMV) and GDN (quad-weight GEMV) replacements read the original weight Parameters directly through
autograd.Functions with exact backward, so training and generation share one forward path: zero weight copies, no inject/eject switching between rollout and training. Verified end-to-end by an integration test (below): generate → train one step → generate, output changes, no sync calls.Components
| File | Role |
|---|---|
|
csrc/module_inject/fused_glu.cu| dual/quad-weight GEMV (MLP / GDN input projections), GDN gates, decode attention (warp-per-head, KV split-K, online softmax), fused residual+RMSNorm, triple QKV GEMV, graph-capturable decode step ||
csrc/module_inject/decode_loop.cu| C++ generation loop taking a backend-agnosticstd::functionreplay callable (CUDA graph, eager forward, or future SYCL); argmax and buffer updates run as a private kernel; EOS checked via amortized D2H sync every 16 steps ||
deepspeed/module_inject/segment_ki.py| segment detection + forward replacement (apply_segment_ki) ||
deepspeed/module_inject/kernel_reference.py| pure-PyTorch executable specifications for every kernel — test oracle, runtime fallback, porting reference ||
deepspeed/ops/module_inject/{fused_glu,decode_loop}.py| op builders (JIT compile, lazy load) ||
deepspeed/utils/static_cache.py| hybrid-slot static cache: real static KV layers for full attention, pass-through slot reusing HF's cudagraph-safe GDN state buffers by reference ||
deepspeed/runtime/rollout/hybrid_engine_rollout.py| prefill → cache setup → graph capture → C++ decode loop, with layered fallback (full-step graph for b=1, graph+argmax for b>1, C++ loop, Python loop) |Performance
Qwen3.5-4B, RTX 4080 SUPER, greedy, b=1:
| | tok/s | relative |
|---|---|---|
| HF eager | 22.5 | 1.0× |
| DeepSpeed (this PR) | 69.4 | 3.1× |
| vLLM | 74.9 | — |
Tests
tests/unit/module_inject/test_segment_ki_kernels.py— 11 tests, all passing (executed on RTX 4080 SUPER):kernel_reference.pyoracle on identical inputs (dual_gemv, quad_gemv, gdn_gates, triple_gemv, fused_add_norm, decode_attn)Notes
kernel_reference.pyserves as the executable spec;decode_loop'sstd::functioninterface is backend-agnostic (graph replay or eager forward); SYCL kernels would follow the same op-builder pattern.