Repository navigation
feat(rollout): segment-based kernel injection for hybrid-engine greedy decode - #8602
Conversation
11231a7 to
d41c914
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b31faddfc4
ℹ️ 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".
| from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul | ||
| return self.down_proj(dual_gemv_silu_mul(input, self.gate_proj.weight, self.up_proj.weight)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
Open (18)
Missing CUDA bf16 and pybind functional headers · New Native gdn_gates path cuts off training gradients · New Tensor truth-value check breaks packed-sequence calls · New Custom attention ignores padding masks · New Fused add-norm loses gradients during training · New Unbound GDN slots are skipped without state initialization · New Prompt attention mask is dropped during prefill · New Fallback graph reuses already-consumed recurrent state · New Forward-only graph replay uses uncaptured token buffers · New EOS padding slice ignores prompt-length offset · New Dual-GEMV excludes normal 3D greedy-decode inputs · New Non-CUDA backends incorrectly load CUDA builder · New FP16 models incorrectly enter bf16-only decode kernels · New Decode loop builder is not registered for wheel builds · New Fused GLU builder is not registered for wheel builds · New CUDA-only tests run on unsupported accelerators · New Missing direct coverage for native decode fallback · New Gemma is documented as supported despite GELU rejection · New
What changed in this PR
Adds segment-based kernel injection and native decode acceleration for hybrid-engine greedy rollout.
Changes:
- Adds fused CUDA kernels, reference implementations, and op builders.
- Extends static-cache support for hybrid attention models.
- Integrates graph capture, native decode loops, documentation, and tests.
| 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. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
Hi @delock, thanks for submitting this PR. I have left a few comments and questions. |
There was a problem hiding this comment.
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
Open (6)
Preserve packed-sequence boundaries through causal convolution · New Disable fused QKV projection when any bias is present · New Pass tensor masks for ordinary models during graph capture · New Match torch.argmax first-index tie breaking · New Add direct CUDA coverage for decode_step_graph · New Make live-weight integration test deterministically observe weight changes · New
Resolved since last review (18)
EOS padding slice ignores prompt-length offset Forward-only graph replay uses uncaptured token buffers Fallback graph reuses already-consumed recurrent state Prompt attention mask is dropped during prefill Unbound GDN slots are skipped without state initialization Fused add-norm loses gradients during training Custom attention ignores padding masks Tensor truth-value check breaks packed-sequence calls Native gdn_gates path cuts off training gradients Missing CUDA bf16 and pybind functional headers CUDA-only tests run on unsupported accelerators Fused GLU builder is not registered for wheel builds Decode loop builder is not registered for wheel builds FP16 models incorrectly enter bf16-only decode kernels Non-CUDA backends incorrectly load CUDA builder Dual-GEMV excludes normal 3D greedy-decode inputs Gemma is documented as supported despite GELU rejection Missing direct coverage for native decode fallback
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:
A few additional points to check; I am not treating these as confirmed merge blockers:
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 following up. That was a useful catch: the previous I did notice one issue at |
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. |
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. |
| def total_memory(self, device_index=None): | ||
| ... | ||
|
|
||
| @abc.abstractmethod |
There was a problem hiding this comment.
I think we should not remove this?
|
The new |
The glu_epilogue fallback path (m > 32 decode and all prefill, where M = batch * prompt_len) computed silu via an fp32 decomposition: two upcasts of the [M, inter] gate/up tensors, five elementwise kernels, and a final downcast. Replacing it with F.silu in bf16 eliminates the cast round-trips and three kernels, and is bitwise-equal to HF's activation (the fp32 formula rounds differently -- max 0.5 at bf16 -- so m<=32, m>32 and prefill previously disagreed with HF and each other). Measured on L20 (Ada), Qwen3.5-4B, b=64 greedy decode, interleaved A/B (medians of 3): 1667.3 -> 1765.5 tok/s (+5.9%, non-overlapping ranges). The native op keeps the small-M fused kernel (m <= 32); on Ada its large-M path splits into row-chunked calls / an aten composite with the same fp32 round-trip, so the eager fallback with this epilogue is the fastest large-M implementation on this arch (1765 vs 1623 via the native dispatcher; Hopper keeps the concat-GEMM path). test_segment_ki_kernels.py (the only oracle consumer; compares with fp32 inputs under tolerance) passes: 25/25 on L20. Numerics note: the fp32 single-rounding formula stays documented in the docstring as the spec semantics; the executable path now matches HF instead of exceeding its precision. Signed-off-by: Ma, Guokai <guokai.ma@gmail.com>
Eight conflict hunks in hybrid_engine_rollout.py, resolved semantically: - sampling kwargs -> master's _generation_kwargs helper (it builds on our _hf_sampling_kwargs, so our do_sample/temperature semantics carry over) - repetition penalty -> master's padding-aware upgrade (generation_config param, _repetition_penalty_ignores_padding probe, prompt_attention_mask arg); our old staticmethod copies removed to avoid silent double defs - profiling gate -> keep our ungated enable_profiling stats semantics; the same profile object feeds the bucket planner via the new graph signature (adaptive_prefill gates the planner, not the stats) - remaining hunks (signatures, prefill_cache kwargs) -> master verbatim Validated on L20 (cards 1-2, torch 2.15/tf 5.22): rollout v1 6 failures == the same pre-existing transformers-version set (+1 pass); module_inject 203 passed + 64 subtests, 0 failures; decode bench bit-identical (1242.2 tok/s, same tok_sum); TestTpGradNorm 4 passed locally. Signed-off-by: Ma, Guokai <guokai.ma@gmail.com>
23adb53 to
2603bd3
Compare
HybridEngineRolloutConfig had use_segki and align_decode_fronts inserted before enable_cache_trimming, shifting the legacy positional constructor slots by two -- #8786's test_config_preserves_legacy_positional_arguments caught it (16 silently landing on enable_cache_trimming). align_decode_fronts is an upstream field and returns to its slot; use_segki moves to the end of the dataclass so the positional contract keeps holding. All in-tree construction is keyword-based, so the reorder is behavior-neutral. Signed-off-by: Ma, Guokai <guokai.ma@gmail.com>
| handshake is still under design. | ||
| """ | ||
| from deepspeed.module_inject.segment_ki import segki_refresh | ||
| segki_refresh(self._rollout_module() if hasattr(self, "_rollout_module") else self.module) |
There was a problem hiding this comment.
Should we call refresh_weights from sync_weights()? It's currently no-op. I think we need to invalidate the cache.
We could also add a test to verify that the updated cache is used.
Review finding (Runguo): the script hardcoded the deployment box's checkout path; the installed deepspeed package is the import target. Signed-off-by: Guokai Ma <guokai.ma@intel.com>
Review findings from @runguo-li and @tohtana (all three verified): 1. refresh_weights() read self._rollout_module/self.module, which do not exist -- the rollout holds the model at engine.module. The arena e2e bypassed the method by calling segki_refresh() directly, so the entry point was never exercised. Resolve through the engine (mock-safe for the SimpleNamespace test engines), and state the retained-graph caveat honestly in the docstring (finding 2, design pending). 2. sync_weights() was a no-op: colocated weights are read live so there is nothing to push, but the injected forwards' derived caches go stale after an in-place write. The training-step hook now refreshes, so every sync source invalidates uniformly (tohtana's wiring point). 3. Rollout-path test: inject -> generate -> in-place weight write -> sync_weights -> generate must match a fresh injection bit-for-bit (the arena e2e logic through the public entry point). Replaces test_sync_weights_is_noop, which pinned the old no-op behavior. Validated on L20 (card 4, torch 2.15/tf 5.22): both new tests pass; full test_hybrid_engine_rollout.py 151 passed / 4 skipped. Signed-off-by: Ma, Guokai <guokai.ma@gmail.com>
…im (a)) Runguo's finding 2: a retained continuous-batching graph captures the derived tensors' addresses (TP>1 cat weights, Ampere/Hopper GLU concat cache, GDN gates). refresh_weights drops those tensors, so a surviving graph would replay freed memory. Parameters are covered by the capture signature (in-place writes keep their addresses), but the derived caches are invisible to it, so nothing else invalidates them. Interim fix (a): refresh_weights releases _continuous_graph_state (synchronized, like shutdown) before dropping caches; the next rollout re-captures. Cost: one re-capture per sync. The end-state fix (b) -- refresh refills derived tensors in place so graphs survive by construction -- is deferred by design; remove this release when it lands. The new test pins the contract on any config (asserts the graph is released after sync, then post-sync generation matches a fresh injection). Red on the previous head (the graph survived the sync); config-dependent note: on Ada/dense/TP=1/small-batch the captured graph holds no derived tensor, which is why the hazard never surfaced there. Validated on L20 (card 4): red -> green; full rollout + module_inject 355 passed / 16 skipped / 0 failed. Signed-off-by: Ma, Guokai <guokai.ma@gmail.com>
|
Thanks for the update! |
Hi @tohtana thanks for the comments. I'll fix it. In following PRs I'll investigate whether register a refresh hook for each SegKI op is possible. |
segki_refresh looked up the backend handle only through _ki_gdn_op, but GLU-only models carry theirs on the MLP modules as _ki_dual_op — for those, clear_glu_cat_cache() was never called and the process-wide gate|up concat served stale values after an in-place sync (review finding, Masahiro). Any handle reaches the process-wide cache; scan both attributes. New arena test covers the dense-model branch with a GLU-only model (DS_SEGMENT_KI_GLU_TEST_MODEL, default Qwen/Qwen3-0.6B). Signed-off-by: Guokai Ma <guokai.ma@intel.com>
…LUBuilder The CI formatting run flagged the generator/constructor wrapping in ed86967. The new dense-model test also needs to skip when the accelerator registers no FusedGLUBuilder (NotImplementedBuilder — the CPU accelerator): the injection never happens, so there is no backend cache to stale. A CUDA host whose JIT build fails is an environment defect — the test fails loudly there, not skips. Signed-off-by: Guokai Ma <guokai.ma@intel.com>
36d8a2a to
0aeb3db
Compare
create_op_builder returns an instance; .__name__ exists on the class, not the object — the check raised AttributeError on the CPU CI runner. Read the type name instead (verified against the CPU accelerator directly; a real builder instance does not skip). Signed-off-by: Guokai Ma <guokai.ma@intel.com>
Rebase the static-graph reuse onto the segment-KI decode path from deepspeedai#8602. - Keep the DeepSpeedStaticCache, decode inputs and captured graph across generate() calls with the same decode signature (batch, cache length, device, dtype, parameter layout, training mode, autocast, step-kernel use). AutoTP ranks agree on recapture through an all-reduce. - Without segKI, in-place weight updates are replayed without recapture. With segKI, segki_refresh() bumps a generation in the signature and refresh_weights()/sync_weights() release the graphs, because the injected kernels cache tensors derived from the weights. - Size the decode KV cache from the prefill's local KV tensors again, so AutoTP-sharded and narrowed-head models get the right shape. - Apply the repetition penalty on the graph prefill and Python decode paths again; the b=1 step kernel is used only without a penalty. - Give eager attention an additive mask built inside the graph from the boolean decode mask. Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
segKI and PR #8602 have merged; the draft/submission note no longer applies. Signed-off-by: Guokai Ma <guokai.ma@intel.com>
## Summary Fixes deepspeedai#9126. - Size the static rollout KV cache from the actual local prefill tensors instead of guessed global/TP head counts. - Pass an additive 4-D mask to eager/SDPA attention while retaining a separate boolean mask for the captured step kernel. - Apply repetition penalties on the static graph path, reset capture-time mask mutations before replay, and restrict the full-step kernel to the single-row, unpenalized greedy fast path. ## Root cause The segment-KI rollout change eagerly initialized `DeepSpeedStaticCache` from global configuration head counts. That allocation can disagree with AutoTP's local KV heads, causing either a copy shape failure or silent wrong-token generation. The same change also passed a boolean 4-D mask directly to attention implementations that expect additive masks, while graph/Python token selection bypassed the repetition penalty. Together these account for the nightly static-graph failures in `tests/unit/v1/test_hybrid_engine_rollout_v1.py`. The batched graph step did not need the full-step argmax kernel because Python already selects each row's token. The kernel is now explicitly limited to batch size one; the b=1 EOS check remains amortized over 16 replays because at most 15 trailing steps are padded away, avoiding a synchronization on every replay. Batched decoding continues checking after every step because its dead work is multiplied by the number of active rows. ## Duplicate-work check deepspeedai#9077 is primarily a static graph-reuse performance PR, not the dedicated deepspeedai#9126 fix, but its rebase onto deepspeedai#8602 independently absorbed the same local-KV, additive-mask, and repetition-penalty corrections while preserving that performance work. deepspeedai#9127 remains the isolated hotfix for the nightly regression. If deepspeedai#9127 is merged first, deepspeedai#9077 should rebase onto it and drop the duplicated correctness hunks; its remaining scope is graph reuse and lifecycle. deepspeedai#9079 is stacked on deepspeedai#9077 and separately handles whole-step graph capture, including replacement of the Python token-history loop. ## Validation Hardware: 1x Intel Arc Pro B70 (16 devices visible), Level Zero XPU; driver version is not exposed by the environment. Software: torch `2.14.0.dev20260804+xpu`, Transformers `5.17.0`. ```bash python -m pytest -q -p no:cacheprovider -o addopts= \ tests/unit/utils/test_static_cache.py \ 'tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_static_graph_attention_mask_uses_additive_values' \ 'tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_static_graph_uses_prefill_kv_shape' \ 'tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_static_graph_full_step_kernel_preconditions' \ 'tests/unit/v1/test_hybrid_engine_rollout_v1.py::test_static_graph_matches_native_llama_generation[eager]' # 26 passed in the combined focused set pre-commit run --files \ deepspeed/runtime/rollout/hybrid_engine_rollout.py \ tests/unit/v1/test_hybrid_engine_rollout_v1.py # all hooks passed ``` The broad two-file run produced 34 passes and 17 skips before the added direct regressions; its remaining failures were unsupported Level Zero SDPA/distributed operations (`UR_RESULT_ERROR_UNSUPPORTED_FEATURE`), not assertion regressions in the changed path. The new direct regressions assert that visible positions are additive zero and masked positions are `finfo.min`, and that the full-step kernel is not mounted for repetition penalties or batched decode. Existing end-to-end tests compare generated tokens against Hugging Face and cover the penalty result on CUDA CI. ## Compatibility coverage - Validated: static graph replay on Intel XPU; AutoTP-like local KV head counts 4/2/1; eager Llama attention; greedy decoding; additive mask values; full-step-kernel preconditions; cache replay/position/compaction contracts. - Not validated locally: NVIDIA CUDA, SDPA on CUDA, ROCm, sampled/repetition-penalty end-to-end rollout on a CUDA device, Hybrid/linear-attention models, and multi-rank AutoTP. These require hardware/backend coverage outside this environment. - ZeRO stage/offload are not affected. No public API, config, checkpoint, convergence, throughput, or peak-memory behavior is changed. The per-step `torch.cat` used by repetition penalty remains O(n²), matching the existing continuous rollout implementation. Optimizing only this static path is small (roughly 30–60 minutes plus a focused test), but unifying it with variable-length continuous rollout would take roughly 2–4 hours and require broader compaction/padding/CUDA validation. It is intentionally deferred from this correctness fix and can be handled as a small follow-up performance PR, primarily benefiting `repetition_penalty != 1`; the default penalty path is unaffected. AI assistance was used for investigation, implementation, and test preparation; the submitting human reviewed the final diff and is responsible for the DCO sign-off. --------- Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
Rebase the static-graph reuse onto the segment-KI decode path from deepspeedai#8602. - Keep the DeepSpeedStaticCache, decode inputs and captured graph across generate() calls with the same decode signature (batch, cache length, device, dtype, parameter layout, training mode, autocast, step-kernel use). AutoTP ranks agree on recapture through an all-reduce. - Without segKI, in-place weight updates are replayed without recapture. With segKI, segki_refresh() bumps a generation in the signature and refresh_weights()/sync_weights() release the graphs, because the injected kernels cache tensors derived from the weights. - Size the decode KV cache from the prefill's local KV tensors again, so AutoTP-sharded and narrowed-head models get the right shape. - Apply the repetition penalty on the graph prefill and Python decode paths again; the b=1 step kernel is used only without a penalty. - Give eager attention an additive mask built inside the graph from the boolean decode mask. Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>



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
csrc/module_inject/fused_glu.cucsrc/module_inject/decode_loop.custd::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 stepsdeepspeed/module_inject/segment_ki.pyapply_segment_ki)deepspeed/module_inject/kernel_reference.pydeepspeed/ops/module_inject/{fused_glu,decode_loop}.pydeepspeed/utils/static_cache.pydeepspeed/runtime/rollout/hybrid_engine_rollout.pyPerformance
Qwen3.5-4B, RTX 4080 SUPER, greedy, b=1:
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.