Skip to content

feat(rollout): segment-based kernel injection for hybrid-engine greedy decode - #8602

Merged
tohtana merged 59 commits into
masterfrom
gma/qwen_ki_expr
Nov 19, 2026
Merged

tohtana merged 59 commits into
masterfrom
gma/qwen_ki_expr

Conversation

@delock

@delock delock commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

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 the in_proj_{qkv,z,b,a} set is picked up without per-model code. Projections carrying TP collectives are never fused (a defensive isinstance check 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-agnostic std::function replay 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 vs reference consistency (GPU, 6 tests): every kernel compared against its kernel_reference.py oracle on identical inputs (dual_gemv, quad_gemv, gdn_gates, triple_gemv, fused_add_norm, decode_attn)
  • Injection invariants (CPU-runnable, 4 tests): injected forward matches un-injected output, no weight copies installed, composite autograd path, backward scatters gradients to the original Parameters
  • Rollout → train → rollout integration (GPU, Qwen3.5-0.8B-Base): generate with graph capture + segKI, one SGD step through the same injected model, generate again with changed output — no inject/eject/sync calls anywhere in between
  • Multi-GPU (AutoTP) validation (planned follow-up)

Notes

  • SYCL/XPU porting: kernel_reference.py serves as the executable spec; decode_loop's std::function interface is backend-agnostic (graph replay or eager forward); SYCL kernels would follow the same op-builder pattern.
  • Related upstream fix split into a standalone PR: fix: attention_unfused alpha missing norm_factor squaring #8666 (attention_unfused alpha squaring).

@delock
delock force-pushed the gma/qwen_ki_expr branch 2 times, most recently from 11231a7 to d41c914 Compare September 26, 2026 07:00
@delock delock changed the title feat(rollout): HybridEngineRollout graph capture + segment-KI for Qwen3.5 hybrid — 67 tok/s (1.14× of vLLM) feat(rollout): segment-based kernel injection for hybrid-engine greedy decode Sep 26, 2026
@delock
delock marked this pull request as ready for review September 28, 2026 06:27

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread csrc/module_inject/decode_loop.cu Resolved
Comment thread deepspeed/module_inject/segment_ki.py Outdated
Comment on lines +184 to +185
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread csrc/module_inject/fused_glu.cu Resolved
Comment thread deepspeed/utils/static_cache.py Resolved
Comment thread csrc/module_inject/decode_loop.cu Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 High severity · 6 Medium severity · 2 Low severity

Open (18)
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.

Comment thread csrc/module_inject/decode_loop.cu Resolved
Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread csrc/module_inject/decode_loop.cu Resolved
@nathon-lee

Copy link
Copy Markdown
Contributor

Hi @delock, thanks for submitting this PR. I have left a few comments and questions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 High severity · 1 Medium severity · 2 Low severity

Open (6)
Resolved since last review (18)

Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread deepspeed/module_inject/segment_ki.py Resolved
Comment thread csrc/module_inject/fused_glu.cu Resolved
Comment thread csrc/module_inject/fused_glu.cu Resolved
@delock

delock commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

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!

@nathon-lee

Copy link
Copy Markdown
Contributor

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:

  • 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 forwards 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.
  • 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.

@delock

delock commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

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 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:

  • 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 forwards 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.
  • 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.

@nathon-lee

nathon-lee commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

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?

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-22T03:22:42.556857Z
We couldn’t complete this review. Comment @codex review to try again.
cc3e804 Draft marked ready
ℹ️ About Codex in GitHub

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

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

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

@delock

delock commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator Author

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?

Hi @nathon-lee , sorry for the late reply, let me check with latest status of master.

@delock

delock commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator Author

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?

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think we should not remove this?

Comment thread accelerator/abstract_accelerator.py Resolved
@phoeenniixx

Copy link
Copy Markdown
Contributor

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.

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>
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>

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you @delock! for the great improvement!
I found one suspicious behavior. Can you check it?

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

delock and others added 3 commits November 17, 2026 09:28
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>
@delock

delock commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Hi @tohtana refresh_weights is now hooked into sync_weights(). Thanks for catching this.

@LiRunGuo For contiguous batching, I forced graph release after weight sync. Survive graph after weight sync can be left to further optimizations. Thanks!

@tohtana

tohtana commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the update!
I noticed one remaining case in segki_refresh(): it looks for the backend only through _ki_gdn_op, while GLU-only models store it in _ki_dual_op. For those models, clear_glu_cat_cache() is never called. This appears to leave the cached gate/up concatenation stale.

@delock

delock commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the update! I noticed one remaining case in segki_refresh(): it looks for the backend only through _ki_gdn_op, while GLU-only models store it in _ki_dual_op. For those models, clear_glu_cat_cache() is never called. This appears to leave the cached gate/up concatenation stale.

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>
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>

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you @delock, it looks good to me!

@tohtana
tohtana added this pull request to the merge queue Nov 19, 2026
Merged via the queue into master with commit 97aa3c1 Nov 19, 2026
20 checks passed
@tohtana
tohtana deleted the gma/qwen_ki_expr branch November 19, 2026 04:09
jinyouzhi added a commit to jinyouzhi/DeepSpeed that referenced this pull request Nov 19, 2026
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>
delock added a commit that referenced this pull request Nov 20, 2026
segKI and PR #8602 have merged; the draft/submission note no longer
applies.

Signed-off-by: Guokai Ma <guokai.ma@intel.com>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 21, 2026
## 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>
jinyouzhi added a commit to jinyouzhi/DeepSpeed that referenced this pull request Nov 21, 2026
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants