← Back to Pull requests

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

Open
delock opened this pull request with 5302 lines diff across 20 files
View on GitHub
delock delock commented on Sep 20, 2026 01:40 UTC
Author

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: #8666 (attention_unfused alpha squaring).
  • Diff: 5302 lines (+5258 / -44) across 20 files Reviewer: delock Review duration: 67016m
    All Vouch review confidence checks passed
    Residual risk 0.20 = Change Risk (0.93) × (1 − Review Confidence (0.79)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.93 · 5302 lines diff across 20 files
    0.93
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    78%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    49 items
    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Sep 28, 2026 06:32 UTC
    Reviewer

    💡 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

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

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    csrc/module_inject/decode_loop.cu:1
    @@ -0,0 +1,145 @@
    +// SPDX-License-Identifier: Apache-2.0

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

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,596 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and kernel_op is not None:
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            grad_gate_w = torch.matmul(grad_gate_coef.t(), hidden)
    +            grad_up_w = torch.matmul(grad_up_coef.t(), hidden)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and kernel_op is not None:
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))

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

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,596 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and kernel_op is not None:
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            grad_gate_w = torch.matmul(grad_gate_coef.t(), hidden)
    +            grad_up_w = torch.matmul(grad_up_coef.t(), hidden)

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

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,596 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and kernel_op is not None:
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            grad_gate_w = torch.matmul(grad_gate_coef.t(), hidden)
    +            grad_up_w = torch.matmul(grad_up_coef.t(), hidden)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and kernel_op is not None:
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))
    +
    +
    +@dataclass
    +class GDNSegment:
    +    """A GatedDeltaNet middle segment for hybrid families (e.g. Qwen3.5).
    +
    +    The four input projections share one input and are comm-free under TP, so
    +    they collapse into a single GEMM. Everything from conv1d through the FLA
    +    scan kernel to out_proj is delegated untouched: the ecosystem kernels are
    +    already state of the art and the trailing out_proj is the collective
    +    boundary."""
    +    parent: torch.nn.Module
    +    in_proj_qkv: torch.nn.Module
    +    in_proj_z: torch.nn.Module
    +    in_proj_b: torch.nn.Module
    +    in_proj_a: torch.nn.Module
    +
    +
    +def find_gdn_segments(root: torch.nn.Module) -> List[GDNSegment]:
    +    """Detect GatedDeltaNet blocks by structure (in_proj attribute set)."""
    +    segments = []
    +    names = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
    +    for module, p in _find_fusable_projections(root, names):
    +        segments.append(GDNSegment(parent=module, **{n: p[n] for n in names}))
    +    return segments
    +
    +
    +def _fused_gdn_forward(self, hidden_states, *args, **kwargs):
    +    """GDN block forward with the four input projections fused into one GEMM.
    +
    +    Mirrors the native flow (transformers Qwen3_5GatedDeltaNet.forward) while
    +    delegating conv1d, the delta-rule scan, the gated norm, and the
    +    collective-bearing out_proj to the untouched original submodules."""
    +    from transformers.models.qwen3_5.modeling_qwen3_5 import apply_mask_to_padding_states
    +
    +    # Consume the layer-level kwargs so they cannot leak into the scan call
    +    # (the native forward's named parameters absorb them; ours must too).
    +    attention_mask = kwargs.pop("attention_mask", None)
    +    cache_params = kwargs.pop("cache_params", None) or (args[0] if args else None)
    +    hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
    +
    +    batch_size, seq_len, _ = hidden_states.shape
    +    use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
    +
    +    # Fused [qkv | z | b | a] projection reading the original weights (b=1
    +    # quad_gemv kernel, b>1 on-the-fly concat) — no weight copies.
    +    gdn_kernel_op = getattr(self, "_ki_gdn_op", None)
    +    if batch_size == 1 and seq_len == 1:
    +        fused = GDNInputProj.apply(
    +            hidden_states.squeeze(0).squeeze(0), self.in_proj_qkv.weight, self.in_proj_z.weight, self.in_proj_b.weight,
    +            self.in_proj_a.weight, gdn_kernel_op).view(1, 1, -1)

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

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,596 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and kernel_op is not None:
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            grad_gate_w = torch.matmul(grad_gate_coef.t(), hidden)
    +            grad_up_w = torch.matmul(grad_up_coef.t(), hidden)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and kernel_op is not None:
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))
    +
    +
    +@dataclass
    +class GDNSegment:
    +    """A GatedDeltaNet middle segment for hybrid families (e.g. Qwen3.5).
    +
    +    The four input projections share one input and are comm-free under TP, so
    +    they collapse into a single GEMM. Everything from conv1d through the FLA
    +    scan kernel to out_proj is delegated untouched: the ecosystem kernels are
    +    already state of the art and the trailing out_proj is the collective
    +    boundary."""
    +    parent: torch.nn.Module
    +    in_proj_qkv: torch.nn.Module
    +    in_proj_z: torch.nn.Module
    +    in_proj_b: torch.nn.Module
    +    in_proj_a: torch.nn.Module
    +
    +
    +def find_gdn_segments(root: torch.nn.Module) -> List[GDNSegment]:
    +    """Detect GatedDeltaNet blocks by structure (in_proj attribute set)."""
    +    segments = []
    +    names = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
    +    for module, p in _find_fusable_projections(root, names):
    +        segments.append(GDNSegment(parent=module, **{n: p[n] for n in names}))
    +    return segments
    +
    +
    +def _fused_gdn_forward(self, hidden_states, *args, **kwargs):
    +    """GDN block forward with the four input projections fused into one GEMM.
    +
    +    Mirrors the native flow (transformers Qwen3_5GatedDeltaNet.forward) while
    +    delegating conv1d, the delta-rule scan, the gated norm, and the
    +    collective-bearing out_proj to the untouched original submodules."""
    +    from transformers.models.qwen3_5.modeling_qwen3_5 import apply_mask_to_padding_states
    +
    +    # Consume the layer-level kwargs so they cannot leak into the scan call
    +    # (the native forward's named parameters absorb them; ours must too).
    +    attention_mask = kwargs.pop("attention_mask", None)
    +    cache_params = kwargs.pop("cache_params", None) or (args[0] if args else None)
    +    hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
    +
    +    batch_size, seq_len, _ = hidden_states.shape
    +    use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
    +
    +    # Fused [qkv | z | b | a] projection reading the original weights (b=1
    +    # quad_gemv kernel, b>1 on-the-fly concat) — no weight copies.
    +    gdn_kernel_op = getattr(self, "_ki_gdn_op", None)
    +    if batch_size == 1 and seq_len == 1:
    +        fused = GDNInputProj.apply(
    +            hidden_states.squeeze(0).squeeze(0), self.in_proj_qkv.weight, self.in_proj_z.weight, self.in_proj_b.weight,
    +            self.in_proj_a.weight, gdn_kernel_op).view(1, 1, -1)
    +    else:
    +        fused = GDNInputProj.apply(hidden_states, self.in_proj_qkv.weight, self.in_proj_z.weight,
    +                                   self.in_proj_b.weight, self.in_proj_a.weight, gdn_kernel_op)
    +    key_dim, value_dim = self.key_dim, self.value_dim
    +    qkv_end = key_dim * 2 + value_dim
    +    z_end = qkv_end + value_dim
    +    b_end = z_end + self.num_v_heads
    +    # One explicit repack of the qkv slice into the [b, conv_dim, s] layout
    +    # conv1d consumes; handing FLA a non-contiguous view triggers a slower
    +    # multi-op internal path (measured as ~40 extra launches per layer).
    +    mixed_qkv = fused[..., :qkv_end].transpose(1, 2).contiguous()
    +    z = fused[..., qkv_end:z_end].reshape(batch_size, seq_len, -1, self.head_v_dim)
    +    b = fused[..., z_end:b_end]
    +    a = fused[..., b_end:]
    +
    +    if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past:
    +        conv_state = cache_params.layers[self.layer_idx].conv_states[0]
    +        mixed_qkv = self._ki_gdn_conv_update(mixed_qkv, conv_state)
    +    else:
    +        if cache_params is not None:
    +            mixed_qkv = cache_params.update_conv_state(mixed_qkv,
    +                                                       self.layer_idx,
    +                                                       conv_kernel_size=self.conv_kernel_size)
    +        mixed_qkv = self._ki_gdn_conv_fn(mixed_qkv, **kwargs)
    +        if cache_params is not None:
    +            mixed_qkv = mixed_qkv[:, :, -seq_len:]
    +
    +    mixed_qkv = mixed_qkv.transpose(1, 2)
    +    query, key, value = torch.split(mixed_qkv, [key_dim, key_dim, value_dim], dim=-1)
    +    query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
    +
    +    gdn_op = getattr(self, "_ki_gdn_op", None)
    +    from deepspeed.accelerator import get_accelerator
    +    if gdn_op is not None and get_accelerator().on_accelerator(a):
    +        a_log_f = self.A_log.detach().float().contiguous()
    +        dt_f = self.dt_bias.detach().float().contiguous()
    +        # gdn_gates accepts row-strided a/b, so the fused-output slices go in
    +        # without contiguous copies.
    +        beta, g = gdn_op.gdn_gates(a, b, a_log_f, dt_f)
    +    else:
    +        beta = b.sigmoid()
    +        g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
    +    if self.num_v_heads // self.num_k_heads > 1:
    +        query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +        key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +
    +    recurrent_state = cache_params.layers[self.layer_idx].recurrent_states[0] if use_precomputed_states else None
    +    # Whitelist the scan inputs: transformers threads unrelated layer kwargs
    +    # (use_cache, cache_position, ...) down to every block and the fused
    +    # kernel signatures reject unknown names.
    +    scan_kwargs = dict(g=g,
    +                       beta=beta,
    +                       initial_state=recurrent_state,
    +                       output_final_state=cache_params is not None,
    +                       use_qk_l2norm_in_kernel=True)
    +    cu_seqlens = kwargs.get("cu_seq_lens_q") or kwargs.get("cu_seqlens")
    +    if cu_seqlens is not None:
    +        scan_kwargs["cu_seqlens"] = cu_seqlens
    +    core_attn_out, last_recurrent_state = self._ki_gdn_scan(query, key, value, **scan_kwargs)
    +    if cache_params is not None:
    +        cache_params.update_recurrent_state(last_recurrent_state, self.layer_idx)
    +
    +    core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
    +    z = z.reshape(-1, self.head_v_dim)
    +    core_attn_out = self.norm(core_attn_out, z)
    +    core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
    +    return self.out_proj(core_attn_out)
    +
    +
    +def _install_gdn_segment(seg: GDNSegment) -> bool:
    +    """Wire the fused forward onto a GDN block, binding its original helpers.
    +
    +    The conv/scan callables are captured from the transformers module so the
    +    replacement keeps using the exact kernels (FLA/causal-conv1d paths and
    +    their cache contracts) that the native forward would have selected."""
    +    import transformers.models.qwen3_5.modeling_qwen3_5 as m5
    +
    +    conv_update = getattr(m5, "causal_conv1d_update", None)
    +    conv_fn = getattr(m5, "causal_conv1d_fn", None)
    +    if conv_update is None or conv_fn is None:
    +        return False
    +
    +    parent = seg.parent
    +
    +    def conv_update_with_weights(mixed_qkv, conv_state):
    +        return conv_update(mixed_qkv, conv_state, parent.conv1d.weight.squeeze(1), parent.conv1d.bias,
    +                           parent.activation)
    +
    +    def conv_fn_with_weights(mixed_qkv, **kw):
    +        # causal_conv1d_fn does not accept HF generation kwargs; filter them
    +        # the same way the scan closure does.
    +        kw.pop("use_cache", None)
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        return conv_fn(mixed_qkv,
    +                       parent.conv1d.weight.squeeze(1),
    +                       parent.conv1d.bias,
    +                       activation=parent.activation,
    +                       **kw)
    +
    +    def scan(query, key, value, **kw):
    +        # Route through the block's own instance-bound kernels: transformers
    +        # binds the FLA fused implementations onto the module when available
    +        # (recurrent_gated_delta_rule/chunk_gated_delta_rule) and only falls
    +        # back to the pure-torch references otherwise. Calling the module-level
    +        # torch_* functions directly forces the slow fallback on every layer.
    +        single = kw.get("initial_state") is not None and query.shape[1] == 1
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        fn = parent.recurrent_gated_delta_rule if single else parent.chunk_gated_delta_rule
    +        return fn(query, key, value, **kw)
    +
    +    kernel_op = None
    +    try:
    +        from deepspeed.accelerator import get_accelerator
    +        if get_accelerator().device_name() != "cpu":
    +            from deepspeed.ops.module_inject import get_fused_glu_op
    +            kernel_op = get_fused_glu_op()
    +    except Exception:
    +        kernel_op = None
    +    parent._ki_gdn_op = kernel_op
    +    parent._ki_gdn_conv_update = conv_update_with_weights
    +    parent._ki_gdn_conv_fn = conv_fn_with_weights
    +    parent._ki_gdn_scan = scan
    +    parent.forward = _fused_gdn_forward.__get__(parent, type(parent))
    +    return True
    +
    +
    +def apply_segment_ki(model: torch.nn.Module) -> dict:
    +    """Install segment kernels on ``model`` (post-AutoTP, pre-generate).
    +
    +    Uses the native CUDA op when a non-cpu accelerator backend is active;
    +    falls back to the torch composite reference otherwise.
    +
    +    Returns a small report so callers (tests, journals) can assert what was
    +    found and replaced without introspecting the module tree again.
    +    """
    +    kernel_op = None
    +    from deepspeed.accelerator import get_accelerator
    +    if get_accelerator().device_name() != "cpu":
    +        from deepspeed.ops.module_inject import get_fused_glu_op
    +        kernel_op = get_fused_glu_op()
    +
    +    report = {"backend": "cuda" if kernel_op is not None else "composite"}
    +
    +    segments = find_glu_segments(model)
    +    replaced = 0
    +    for seg in segments:
    +        seg.parent._ki_dual_op = kernel_op if kernel_op is not None and hasattr(kernel_op,
    +                                                                                "dual_gemv_silu_mul") else None
    +        seg.parent.forward = _dual_weight_glu_forward.__get__(seg.parent, type(seg.parent))
    +        replaced += 1
    +    report["fused_glu"] = {"segments_found": len(segments), "segments_replaced": replaced}
    +
    +    gdn_segments = find_gdn_segments(model)
    +    gdn_replaced = sum(1 for seg in gdn_segments if _install_gdn_segment(seg))
    +    report["fused_gdn"] = {"segments_found": len(gdn_segments), "segments_replaced": gdn_replaced}
    +
    +    return report
    +
    +
    +# ─── Custom b=1 decode attention: replace SDPA in full-attention layers ───
    +
    +
    +def _decode_attn_forward(self,
    +                         hidden_states,
    +                         position_embeddings=None,
    +                         attention_mask=None,
    +                         past_key_values=None,
    +                         **kwargs):
    +    """Replacement forward for full-attention layers: run the custom
    +    decode_attn kernel at b=1, seq_len=1 instead of SDPA-with-mask (which
    +    falls into the slow mem_efficient backend against the full-width static
    +    cache buffer).
    +
    +    Everything except the attention core is a verbatim replay of the HF
    +    forward (q_proj 2x-wide gate split, per-head q/k norms, RoPE, KV cache
    +    update, gate multiply, o_proj), so numerics match the original path.
    +    The kernel reads the valid KV length from the same GPU-resident
    +    write_pos tensor the cache update writes through, keeping the whole
    +    step CUDA-graph replayable."""
    +    if (hidden_states.shape[0] != 1 or hidden_states.shape[1] > 1 or past_key_values is None
    +            or getattr(self, "_ki_attn_op", None) is None
    +            or getattr(past_key_values, "_write_position", None) is not self._ki_write_pos):
    +        # Prefill, batched decode, or a non-graph cache (e.g. DynamicCache
    +        # inside module.generate): the original forward is the correct path.
    +        return self._ki_orig_attn_forward(hidden_states, position_embeddings, attention_mask, past_key_values,
    +                                          **kwargs)
    +
    +    input_shape = hidden_states.shape[:-1]
    +    hidden_shape = (*input_shape, -1, self.head_dim)
    +
    +    qkv_op = getattr(self, "_ki_qkv_op", None)
    +    if qkv_op is not None:
    +        # One GEMV launch over q/k/v weights directly — replaces the
    +        # three separate F.linear launches. q_proj keeps its 2x-wide
    +        # query|gate layout, so the gate split below is unchanged from HF.
    +        q_out, k_out, v_out = qkv_op.triple_gemv(hidden_states.view(-1), self.q_proj.weight, self.k_proj.weight,
    +                                                 self.v_proj.weight)
    +        query_states, gate = torch.chunk(q_out.view(*input_shape, -1, self.head_dim * 2), 2, dim=-1)
    +        gate = gate.reshape(*input_shape, -1)
    +        query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
    +        key_states = self.k_norm(k_out.view(hidden_shape)).transpose(1, 2)
    +        value_states = v_out.view(hidden_shape).transpose(1, 2)
    +    else:
    +        query_states, gate = torch.chunk(self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2),
    +                                         2,
    +                                         dim=-1)
    +        gate = gate.reshape(*input_shape, -1)
    +
    +        query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
    +        key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
    +        value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
    +
    +    cos, sin = position_embeddings
    +    query_states, key_states = self._ki_rope(query_states, key_states, cos, sin)
    +
    +    key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
    +
    +    num_q_heads, num_kv_heads, head_dim = self._ki_num_q_heads, self._ki_num_kv_heads, self.head_dim
    +    out = torch.empty(num_q_heads, head_dim, dtype=hidden_states.dtype, device=hidden_states.device)
    +    self._ki_attn_op.decode_attn(query_states.reshape(num_q_heads, head_dim), key_states[0], value_states[0],
    +                                 self._ki_write_pos, out, num_q_heads, num_kv_heads, head_dim, key_states.shape[2])
    +
    +    attn_output = out.view(*input_shape, -1) * torch.sigmoid(gate)
    +    return self.o_proj(attn_output), None
    +
    +
    +def install_decode_attention(model: torch.nn.Module, write_pos: torch.Tensor, kernel_op) -> int:
    +    """Patch full-attention layers to use the custom decode_attn kernel.
    +
    +    Detection mirrors find_glu_segments: structural (q/k/v/o projections
    +    plus per-head q_norm/k_norm present, q_proj carrying the 2x-wide
    +    query|gate layout), cross-checked against the config's layer_types so
    +    linear-attention blocks are never touched. Returns the patched count;
    +    layers whose GQA ratio the kernel cannot serve are left native."""
    +    if kernel_op is None or not hasattr(kernel_op, "decode_attn"):
    +        return 0
    +    try:
    +        from transformers.models.qwen3_5.modeling_qwen3_5 import apply_rotary_pos_emb
    +    except ImportError:
    +        return 0
    +
    +    patched = 0
    +    for module in model.modules():
    +        projections = [getattr(module, name, None) for name in ("q_proj", "k_proj", "v_proj", "o_proj")]
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections):
    +            continue
    +        if not all(isinstance(getattr(module, name, None), torch.nn.Module) for name in ("q_norm", "k_norm")):
    +            continue
    +        head_dim = module.head_dim
    +        num_q_heads = projections[0].out_features // (2 * head_dim)
    +        num_kv_heads = projections[1].out_features // head_dim
    +        if num_q_heads * head_dim * 2 != projections[0].out_features:
    +            continue  # not the 2x-wide query|gate layout this forward replays
    +        layer_types = getattr(getattr(module, "config", None), "layer_types", None)
    +        if layer_types is not None and layer_types[module.layer_idx] != "full_attention":
    +            continue
    +        # Kernel contract: supported head dims and a GQA ratio that divides
    +        # its 16 warps-per-block KV split.
    +        if head_dim not in (64, 128, 256) or 16 % (num_q_heads // num_kv_heads) != 0:
    +            continue
    +        if getattr(module, "_ki_orig_attn_forward", None) is None:
    +            module._ki_orig_attn_forward = module.forward
    +        module._ki_attn_op = kernel_op
    +        module._ki_qkv_op = kernel_op if (hasattr(kernel_op, "triple_gemv")
    +                                          and os.environ.get("DS_TIER2", "1") == "1") else None
    +        module._ki_write_pos = write_pos
    +        module._ki_rope = apply_rotary_pos_emb
    +        module._ki_num_q_heads = num_q_heads
    +        module._ki_num_kv_heads = num_kv_heads
    +        module.forward = _decode_attn_forward.__get__(module, type(module))
    +        patched += 1
    +    return patched
    +
    +
    +# ─── Fused residual-add + RMSNorm in the decoder-layer forward ───
    +
    +
    +def _fused_norm_layer_forward(self,
    +                              hidden_states,
    +                              position_embeddings,
    +                              attention_mask=None,
    +                              position_ids=None,
    +                              past_key_values=None,
    +                              **kwargs):
    +    """Replacement forward for decoder layers at b=1, seq_len=1: the
    +    post-attention residual-add + RMSNorm pair runs through the
    +    fused_add_norm kernel (one launch updates the residual stream in-place
    +    and produces the normalized MLP input) instead of two launches. The
    +    pre-attention norm stays native — the HF layer normifies the raw hidden
    +    state there, with no add to fuse — and the final post-MLP add stays a
    +    plain add for the same reason. Attention and MLP are called unchanged,
    +    so attention-level patches (decode_attn / triple_gemv) still apply."""
    +    if (hidden_states.shape[0] != 1 or hidden_states.shape[1] > 1 or hidden_states.dtype is not torch.bfloat16
    +            or not hidden_states.is_contiguous() or getattr(self, "_ki_norm_op", None) is None):
    +        # Prefill, batched decode, or a non-graph path: the original forward
    +        # is the correct path.
    +        return self._ki_orig_layer_forward(hidden_states, position_embeddings, attention_mask, position_ids,
    +                                           past_key_values, **kwargs)
    +
    +    op = self._ki_norm_op
    +    residual = hidden_states
    +    hidden_states = self.input_layernorm(hidden_states)
    +
    +    if self.block_type == "linear_attention":
    +        hidden_states = self.linear_attn(
    +            hidden_states=hidden_states,
    +            cache_params=past_key_values,
    +            attention_mask=attention_mask,
    +            **kwargs,
    +        )
    +    else:
    +        hidden_states, _ = self.self_attn(
    +            hidden_states=hidden_states,
    +            attention_mask=attention_mask,
    +            position_ids=position_ids,
    +            past_key_values=past_key_values,
    +            position_embeddings=position_embeddings,
    +            **kwargs,
    +        )
    +
    +    # fused_add_norm mutates its first argument in-place into the new
    +    # residual stream and returns the normalized input to the MLP — keep
    +    # both handles, the final add must go through the residual stream.
    +    new_residual = hidden_states
    +    mlp_input = op.fused_add_norm(new_residual, residual, self._ki_postattn_scale, self.post_attention_layernorm.eps)
    +    hidden_states = self.mlp(mlp_input)
    +    hidden_states = hidden_states + new_residual
    +
    +    return hidden_states
    +
    +
    +def install_fused_norm(model: torch.nn.Module, kernel_op) -> int:
    +    """Patch decoder layers to use fused_add_norm at b=1 decode.
    +
    +    Detection is structural (block_type + mlp + both layernorms), so it
    +    covers full-attention and linear-attention layers alike. Pre-computes
    +    the 1+w RMSNorm scale into a persistent contiguous buffer (the HF norm
    +    multiplies by 1+weight; the kernel multiplies by its weight argument
    +    directly) so the captured graph never rebuilds it. Returns the patched
    +    count."""
    +    if kernel_op is None or not hasattr(kernel_op, "fused_add_norm") or os.environ.get("DS_TIER1", "1") != "1":
    +        return 0
    +    patched = 0
    +    for module in model.modules():
    +        norms = [getattr(module, name, None) for name in ("input_layernorm", "post_attention_layernorm")]
    +        if not all(isinstance(n, torch.nn.Module) and hasattr(n, "weight") and hasattr(n, "eps") for n in norms):
    +            continue
    +        if getattr(module, "block_type", None) not in ("linear_attention", "full_attention"):
    +            continue
    +        if getattr(module, "_ki_orig_layer_forward", None) is None:
    +            module._ki_orig_layer_forward = module.forward
    +        module._ki_norm_op = kernel_op
    +        module._ki_postattn_scale = torch.add(1.0, norms[1].weight.detach()).contiguous()
    +        module.forward = _fused_norm_layer_forward.__get__(module, type(module))

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

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    deepspeed/runtime/rollout/hybrid_engine_rollout.py:1
    @@ -799,51 +874,146 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id,
                     for _ in range(3):
                         out = module(
                             static_token,
    -                        attention_mask=static_attn,
    +                        attention_mask={
    +                            "full_attention": static_attn,
    +                            "linear_attention": None
    +                        },
                             past_key_values=ds_cache,
                             use_cache=True,
    -                        cache_position=static_cache_pos,
    -                        position_ids=static_pos_ids,
                         )
                 get_accelerator().current_stream().wait_stream(s)
    +            restore_gdn_states()
    +
    +            # Capture: full-step graph (forward + argmax + buffer updates).
    +            # The step-update kernel indexes token_buf via write_pos (a GPU
    +            # tensor the kernel itself advances), so no host-side step counter
    +            # is needed — the graph is fully self-contained for replay.
    +            graph_op = None
    +            try:
    +                from deepspeed.ops.module_inject import get_fused_glu_op
    +                candidate = get_fused_glu_op()
    +                if hasattr(candidate, "decode_step_graph"):
    +                    graph_op = candidate
    +            except Exception:
    +                graph_op = None
     
    -            # Capture
                 graph = get_accelerator().create_graph()
                 with get_accelerator().capture_to_graph(graph):
                     out = module(
                         static_token,
    -                    attention_mask=static_attn,
    +                    attention_mask={
    +                        "full_attention": static_attn,
    +                        "linear_attention": None
    +                    },
                         past_key_values=ds_cache,
                         use_cache=True,
    -                    cache_position=static_cache_pos,
    -                    position_ids=static_pos_ids,
                     )
    -            static_logits = out.logits
    +                static_logits = out.logits
    +                # decode_step_graph kernel is b=1 only (single-sequence argmax);
    +                # for b>1 the graph captures forward only and Python handles
    +                # argmax + buffer updates outside the graph.
    +                if graph_op is not None and batch_size == 1:
    +                    graph_op.decode_step_graph(static_logits[:, -1, :].contiguous(), static_token.view(batch_size, 1),
    +                                               write_pos, static_attn, full_token_buf)

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

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    csrc/module_inject/fused_glu.cu:1
    @@ -0,0 +1,741 @@
    +// SPDX-License-Identifier: Apache-2.0
    +
    +// DeepSpeed Team
    +
    +// Native CUDA kernel for the segment-KI fused_glu op: computes
    +// out = silu(hidden[:, :k]) * hidden[:, k:2k] on the fused gate|up GEMM
    +// output without materializing chunked views. hidden is contiguous
    +// [N, 2k]; out is contiguous [N, k]. Activation math runs in fp32 with a
    +// single rounding to the storage dtype (torch opmath convention).
    +
    +#include <ATen/cuda/CUDAContext.h>
    +#include <cooperative_groups.h>
    +#include <cuda_bf16.h>
    +#include <cuda_runtime.h>
    +#include <torch/extension.h>
    +#include <algorithm>
    +
    +#define SILU(x) ((x) / (1.0f + expf(-(x))))
    +
    +// GDN gating for the segment-KI fused_gdn op: per-token, per-value-head
    +//   beta = sigmoid(b);  g = -exp(A_log) * softplus(a + dt_bias)
    +// computed in fp32 regardless of storage dtype (matches the native forward's
    +// .float() upcast, which keeps A from reaching -inf in fp16/bf16).
    +__global__ void gdn_gates_kernel(const __nv_bfloat16* __restrict__ a,
    +                                 const __nv_bfloat16* __restrict__ b,
    +                                 const float* __restrict__ a_log,
    +                                 const float* __restrict__ dt_bias,
    +                                 __nv_bfloat16* __restrict__ beta_out,
    +                                 __nv_bfloat16* __restrict__ g_out,
    +                                 int64_t total,
    +                                 int num_heads,
    +                                 int64_t row_stride)
    +{
    +    int64_t i = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
    +    if (i < total) {
    +        int64_t tok = i / num_heads;
    +        int h = (int)(i - tok * num_heads);
    +        // a/b arrive as [tokens, num_heads] slices of the fused GEMM output,
    +        // contiguous within each row but with a fused-width row stride.
    +        int64_t off = tok * row_stride + h;
    +        float av = __bfloat162float(a[off]);
    +        float bv = __bfloat162float(b[off]);
    +        float sp_x = av + dt_bias[h];
    +        // Numerically stable softplus: for large x, log(1+exp(x)) == x to fp32
    +        // precision and the naive form loses significant digits.
    +        float sp = (sp_x > 20.0f) ? sp_x : logf(1.0f + expf(sp_x));
    +        beta_out[i] = __float2bfloat16(1.0f / (1.0f + expf(-bv)));
    +        g_out[i] = __float2bfloat16(-expf(a_log[h]) * sp);
    +    }
    +}
    +
    +std::vector<at::Tensor> gdn_gates(at::Tensor a, at::Tensor b, at::Tensor a_log, at::Tensor dt_bias)
    +{
    +    TORCH_CHECK(a.is_cuda() && b.is_cuda(), "gdn_gates is CUDA-only");
    +    TORCH_CHECK(a.stride(-1) == 1 && b.stride(-1) == 1, "a/b must be unit-stride in the last dim");
    +    auto beta = at::empty_like(a);
    +    auto g = at::empty_like(b);
    +    int64_t total = a.numel();
    +    if (total == 0) return {beta, g};
    +    int heads = (int)dt_bias.size(0);
    +    auto stream = at::cuda::getCurrentCUDAStream();
    +    const int threads = 256;
    +    int64_t blocks = (total + threads - 1) / threads;
    +    gdn_gates_kernel<<<blocks, threads, 0, stream>>>(
    +        reinterpret_cast<const __nv_bfloat16*>(a.data_ptr<at::BFloat16>()),
    +        reinterpret_cast<const __nv_bfloat16*>(b.data_ptr<at::BFloat16>()),
    +        a_log.data_ptr<float>(),
    +        dt_bias.data_ptr<float>(),
    +        reinterpret_cast<__nv_bfloat16*>(beta.data_ptr<at::BFloat16>()),
    +        reinterpret_cast<__nv_bfloat16*>(g.data_ptr<at::BFloat16>()),
    +        total,
    +        heads,
    +        (int64_t)a.stride(-2));
    +    C10_CUDA_KERNEL_LAUNCH_CHECK();
    +    return {beta, g};
    +}
    +
    +// Fused decode step: argmax(logits) -> write token -> advance write_pos ->
    +// reveal mask -> record token in output buffer. Eliminates 6 Python->CUDA
    +// dispatches per decode step into one kernel call.
    +__global__ void decode_step_kernel(const __nv_bfloat16* __restrict__ logits,
    +                                   int64_t* __restrict__ token_out,
    +                                   int64_t* __restrict__ write_pos,
    +                                   bool* __restrict__ mask,
    +                                   int64_t* __restrict__ out_buf,
    +                                   int step,
    +                                   int vocab_size,
    +                                   int max_len)
    +{
    +    __shared__ int s_idx[1024];
    +    __shared__ float s_val[1024];
    +
    +    int tid = threadIdx.x;
    +    int local_idx = 0;
    +    float local_val = -INFINITY;
    +
    +    for (int v = tid; v < vocab_size; v += blockDim.x) {
    +        float val = __bfloat162float(logits[v]);
    +        if (val > local_val) {
    +            local_val = val;
    +            local_idx = v;
    +        }
    +    }
    +    s_idx[tid] = local_idx;
    +    s_val[tid] = local_val;
    +    __syncthreads();
    +
    +    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
    +        if (tid < stride) {
    +            if (s_val[tid + stride] > s_val[tid]) {
    +                s_val[tid] = s_val[tid + stride];
    +                s_idx[tid] = s_idx[tid + stride];
    +            }
    +        }
    +        __syncthreads();
    +    }
    +
    +    if (tid == 0) {
    +        int64_t best = (int64_t)s_idx[0];
    +        token_out[0] = best;
    +        out_buf[step] = best;
    +        int64_t new_pos = write_pos[0] + 1;
    +        write_pos[0] = new_pos;
    +        if (new_pos + 1 < max_len) { mask[new_pos + 1] = true; }
    +    }
    +}
    +
    +void decode_step(at::Tensor logits,
    +                 at::Tensor token_out,
    +                 at::Tensor write_pos,
    +                 at::Tensor mask,
    +                 at::Tensor out_buf,
    +                 int64_t step)
    +{
    +    TORCH_CHECK(logits.is_cuda() && logits.scalar_type() == at::ScalarType::BFloat16,
    +                "logits must be CUDA bf16");
    +    TORCH_CHECK(logits.is_contiguous(), "logits must be contiguous");
    +    int vocab = (int)logits.numel();
    +    int max_len = (int)mask.size(-1);
    +    auto stream = at::cuda::getCurrentCUDAStream();
    +    decode_step_kernel<<<1, 1024, 0, stream>>>(
    +        reinterpret_cast<const __nv_bfloat16*>(logits.data_ptr<at::BFloat16>()),
    +        token_out.data_ptr<int64_t>(),
    +        write_pos.data_ptr<int64_t>(),
    +        mask.data_ptr<bool>(),
    +        out_buf.data_ptr<int64_t>(),
    +        (int)step,
    +        vocab,
    +        max_len);
    +    C10_CUDA_KERNEL_LAUNCH_CHECK();
    +}
    +
    +// Graph-capturable variant: no host-side step parameter. The token output
    +// index is derived from the GPU-resident write_pos, which the kernel itself
    +// advances, making the whole step self-contained for CUDA graph replay.
    +__global__ void decode_step_graph_kernel(const __nv_bfloat16* __restrict__ logits,
    +                                         int64_t* __restrict__ token_out,
    +                                         int64_t* __restrict__ write_pos,
    +                                         bool* __restrict__ mask,
    +                                         int64_t* __restrict__ out_buf,
    +                                         int vocab_size,
    +                                         int max_len)
    +{
    +    __shared__ int s_idx[1024];
    +    __shared__ float s_val[1024];
    +
    +    int tid = threadIdx.x;
    +    int local_idx = 0;
    +    float local_val = -INFINITY;
    +
    +    for (int v = tid; v < vocab_size; v += blockDim.x) {
    +        float val = __bfloat162float(logits[v]);
    +        if (val > local_val) {
    +            local_val = val;
    +            local_idx = v;
    +        }
    +    }
    +    s_idx[tid] = local_idx;
    +    s_val[tid] = local_val;
    +    __syncthreads();
    +
    +    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
    +        if (tid < stride) {
    +            if (s_val[tid + stride] > s_val[tid]) {
    +                s_val[tid] = s_val[tid + stride];
    +                s_idx[tid] = s_idx[tid + stride];
    +            }
    +        }
    +        __syncthreads();
    +    }
    +
    +    if (tid == 0) {
    +        int64_t best = (int64_t)s_idx[0];
    +        token_out[0] = best;
    +        // The output token becomes the NEXT step's input; write it one
    +        // position ahead so it does not overwrite the current position
    +        // (which holds the token being processed this step).
    +        int64_t new_pos = write_pos[0] + 1;
    +        write_pos[0] = new_pos;
    +        out_buf[new_pos] = best;
    +        if (new_pos + 1 < max_len) { mask[new_pos + 1] = true; }

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

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    deepspeed/utils/static_cache.py:1
    @@ -204,7 +267,14 @@ def __init__(
             self.config = config
             text_config = getattr(config, "text_config", config)
             num_layers = getattr(text_config, "num_hidden_layers", 1)
    -        self._layers = [DeepSpeedStaticLayer(max_cache_len) for _ in range(num_layers)]
    +        # Hybrid families (e.g. qwen3_5) mix full_attention and
    +        # linear_attention blocks behind one decoder-layer list; mirror the
    +        # split so KV slots and GDN pass-through slots line up by index.
    +        layer_types = getattr(text_config, "layer_types", None) or ["full_attention"] * num_layers
    +        self._layers = [
    +            DSStaticGDNSlot(max_cache_len) if t == "linear_attention" else DeepSpeedStaticLayer(max_cache_len)
    +            for t in layer_types

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

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 28, 2026 06:32 UTC
    Code Review
    csrc/module_inject/decode_loop.cu:1
    @@ -0,0 +1,145 @@
    +// SPDX-License-Identifier: Apache-2.0
    +// DeepSpeed Team
    +
    +// C++ decode loop: runs the full generation loop in a single C++ call.
    +// The replay callable is a std::function<void()> — it can wrap a CUDA
    +// graph replay, a SYCL submission, an eager PyTorch forward, or any
    +// backend-specific mechanism. The C++ loop is agnostic to the backend.
    +//
    +// Per-step overhead: replay_fn() ≈ 2-5μs (pybind11 dispatch)
    +// vs Python for-loop ≈ 30-50μs.
    +// The fused step-update kernel launch is pure C++ (zero Python).
    +
    +#include <ATen/cuda/CUDAContext.h>
    +#include <cuda_runtime.h>
    +#include <torch/extension.h>
    +#include <functional>
    +
    +__global__ void ds_loop_step_kernel(const __nv_bfloat16* __restrict__ logits,
    +                                    int64_t* __restrict__ token_out,
    +                                    int64_t* __restrict__ write_pos,
    +                                    bool* __restrict__ mask,
    +                                    int64_t* __restrict__ out_buf,
    +                                    int step,
    +                                    int vocab_size,
    +                                    int max_len)
    +{
    +    __shared__ int s_idx[1024];
    +    __shared__ float s_val[1024];
    +
    +    int tid = threadIdx.x;
    +    int local_idx = 0;
    +    float local_val = -INFINITY;
    +
    +    for (int v = tid; v < vocab_size; v += blockDim.x) {
    +        float val = __bfloat162float(logits[v]);
    +        if (val > local_val) {
    +            local_val = val;
    +            local_idx = v;
    +        }
    +    }
    +    s_idx[tid] = local_idx;
    +    s_val[tid] = local_val;
    +    __syncthreads();
    +
    +    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
    +        if (tid < stride) {
    +            if (s_val[tid + stride] > s_val[tid]) {
    +                s_val[tid] = s_val[tid + stride];
    +                s_idx[tid] = s_idx[tid + stride];
    +            }
    +        }
    +        __syncthreads();
    +    }
    +
    +    if (tid == 0) {
    +        int64_t best = (int64_t)s_idx[0];
    +        token_out[0] = best;
    +        out_buf[step] = best;
    +        int64_t new_pos = write_pos[0] + 1;
    +        write_pos[0] = new_pos;
    +        if (new_pos + 1 < max_len) { mask[new_pos + 1] = true; }
    +    }
    +}
    +
    +int64_t ds_decode_loop(std::function<void()> replay_fn,
    +                       at::Tensor logits,
    +                       at::Tensor token_out,
    +                       at::Tensor write_pos,
    +                       at::Tensor mask,
    +                       at::Tensor out_buf,
    +                       int64_t max_steps,
    +                       int64_t eos_token_id,
    +                       int64_t pad_token_id,
    +                       int64_t eos_check_every)
    +{
    +    TORCH_CHECK(logits.is_cuda() && logits.scalar_type() == at::ScalarType::BFloat16,
    +                "logits must be CUDA bf16");
    +    TORCH_CHECK(logits.is_contiguous(), "logits must be contiguous");
    +
    +    // Accept [batch, vocab] 2D tensors. The kernel
    +    // currently supports batch_size=1 only; select(0,0) is a zero-copy view.
    +    // When the kernel gains batch support, this check will be lifted without
    +    // any interface change on the Python side.
    +    TORCH_CHECK(logits.dim() == 2 && logits.size(0) == 1,
    +                "decode_loop currently supports batch_size=1, got batch=",
    +                logits.dim() == 2 ? logits.size(0) : -1);
    +    auto logits_1d = logits.select(0, 0);
    +    auto token_1d = token_out.dim() == 2 ? token_out.select(0, 0) : token_out;
    +    auto out_buf_1d = out_buf.dim() == 2 ? out_buf.select(0, 0) : out_buf;
    +
    +    auto stream = at::cuda::getCurrentCUDAStream().stream();
    +    int vocab = (int)logits_1d.numel();
    +    int max_len = (int)mask.size(-1);
    +
    +    const __nv_bfloat16* log_ptr =
    +        reinterpret_cast<const __nv_bfloat16*>(logits_1d.data_ptr<at::BFloat16>());
    +    int64_t* tok_ptr = token_1d.data_ptr<int64_t>();
    +    int64_t* wp_ptr = write_pos.data_ptr<int64_t>();
    +    bool* mask_ptr = mask.data_ptr<bool>();
    +    int64_t* buf_ptr = out_buf_1d.data_ptr<int64_t>();
    +
    +    int64_t steps_done = 0;
    +
    +    for (int64_t step = 1; step < max_steps; step++) {
    +        // 1) Invoke the replay callable (graph replay, eager forward, or
    +        // any backend-specific mechanism — the C++ loop is agnostic)
    +        replay_fn();
    +
    +        // 2) Fused step-update kernel (pure C++, zero Python)
    +        ds_loop_step_kernel<<<1, 1024, 0, stream>>>(
    +            log_ptr, tok_ptr, wp_ptr, mask_ptr, buf_ptr, (int)step, vocab, max_len);
    +
    +        steps_done = step + 1;
    +
    +        // 3) Periodic EOS check (D2H sync, amortized over N steps)
    +        if (eos_token_id >= 0 && step % eos_check_every == 0) {
    +            int64_t token;
    +            cudaMemcpyAsync(&token, tok_ptr, sizeof(int64_t), cudaMemcpyDeviceToHost, stream);
    +            cudaStreamSynchronize(stream);
    +            if (token == eos_token_id) {
    +                for (int64_t i = step + 1; i < max_steps; i++) { buf_ptr[i] = pad_token_id; }
    +                break;
    +            }
    +        }
    +    }
    +
    +    return steps_done;

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

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    csrc/module_inject/decode_loop.cu:1
    @@ -0,0 +1,163 @@
    +// SPDX-License-Identifier: Apache-2.0
    +// DeepSpeed Team
    +
    +// C++ decode loop: runs the full generation loop in a single C++ call.
    +// The replay callable is a std::function<void()> — it can wrap a CUDA
    +// graph replay, a SYCL submission, an eager PyTorch forward, or any
    +// backend-specific mechanism. The C++ loop is agnostic to the backend.
    +//
    +// Per-step overhead: replay_fn() ≈ 2-5μs (pybind11 dispatch)
    +// vs Python for-loop ≈ 30-50μs.
    +// The fused step-update kernel launch is pure C++ (zero Python).
    +
    +#include <ATen/cuda/CUDAContext.h>
    +#include <cuda_runtime.h>
    +#include <torch/extension.h>
    +#include <functional>

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,628 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def _is_silu_activation(act) -> bool:
    +    """True when ``act`` is SiLU as a torch module, the plain function, or
    +    transformers' SiLUActivation wrapper (what Qwen3.5 MLPs carry)."""
    +    if isinstance(act, torch.nn.SiLU):
    +        return True
    +    if act is torch.nn.functional.silu:
    +        return True
    +    return type(act).__name__ == "SiLUActivation"
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        # The fused replacement hardcodes SiLU, while the name-based selector
    +        # also matches GELU-gated families (e.g. Gemma). Only fuse when the
    +        # module's own activation is positively identified as SiLU.
    +        activations = [getattr(module, name, None) for name in ("act_fn", "activation_fn", "activation_func")]
    +        if not any(_is_silu_activation(act) for act in activations if act is not None):
    +            continue
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +def _native_kernel_ready(kernel_op, hidden, *weights) -> bool:
    +    """The CUDA kernels read raw BFloat16 pointers only, so anything else
    +    (fp16 weights, non-contiguous views) must take the composite reference
    +    path instead of raising inside the binding."""
    +    if kernel_op is None:
    +        return False
    +    if not hidden.is_contiguous() or hidden.dtype is not torch.bfloat16:
    +        return False
    +    return all(w.is_contiguous() and w.dtype is torch.bfloat16 for w in weights)
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, gate_w, up_w):
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            # Training activations are [batch, seq, hidden]; .t() only works
    +            # on 2-D, so flatten the leading dims as the GDN backward does.
    +            flat_hidden = hidden.reshape(-1, hidden.shape[-1])
    +            grad_gate_w = torch.matmul(grad_gate_coef.reshape(-1, grad_gate_coef.shape[-1]).t(),
    +                                       flat_hidden).view_as(gate_w)
    +            grad_up_w = torch.matmul(grad_up_coef.reshape(-1, grad_up_coef.shape[-1]).t(), flat_hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, w_qkv, w_z, w_b, w_a):
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))
    +
    +
    +@dataclass
    +class GDNSegment:
    +    """A GatedDeltaNet middle segment for hybrid families (e.g. Qwen3.5).
    +
    +    The four input projections share one input and are comm-free under TP, so
    +    they collapse into a single GEMM. Everything from conv1d through the FLA
    +    scan kernel to out_proj is delegated untouched: the ecosystem kernels are
    +    already state of the art and the trailing out_proj is the collective
    +    boundary."""
    +    parent: torch.nn.Module
    +    in_proj_qkv: torch.nn.Module
    +    in_proj_z: torch.nn.Module
    +    in_proj_b: torch.nn.Module
    +    in_proj_a: torch.nn.Module
    +
    +
    +def find_gdn_segments(root: torch.nn.Module) -> List[GDNSegment]:
    +    """Detect GatedDeltaNet blocks by structure (in_proj attribute set)."""
    +    segments = []
    +    names = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
    +    for module, p in _find_fusable_projections(root, names):
    +        segments.append(GDNSegment(parent=module, **{n: p[n] for n in names}))
    +    return segments
    +
    +
    +def _fused_gdn_forward(self, hidden_states, *args, **kwargs):
    +    """GDN block forward with the four input projections fused into one GEMM.
    +
    +    Mirrors the native flow (transformers Qwen3_5GatedDeltaNet.forward) while
    +    delegating conv1d, the delta-rule scan, the gated norm, and the
    +    collective-bearing out_proj to the untouched original submodules."""
    +    from transformers.models.qwen3_5.modeling_qwen3_5 import apply_mask_to_padding_states
    +
    +    # Consume the layer-level kwargs so they cannot leak into the scan call
    +    # (the native forward's named parameters absorb them; ours must too).
    +    attention_mask = kwargs.pop("attention_mask", None)
    +    cache_params = kwargs.pop("cache_params", None) or (args[0] if args else None)
    +    hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
    +
    +    batch_size, seq_len, _ = hidden_states.shape
    +    use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
    +
    +    # Fused [qkv | z | b | a] projection reading the original weights (b=1
    +    # quad_gemv kernel, b>1 on-the-fly concat) — no weight copies.
    +    gdn_kernel_op = getattr(self, "_ki_gdn_op", None)
    +    if batch_size == 1 and seq_len == 1:
    +        fused = GDNInputProj.apply(
    +            hidden_states.squeeze(0).squeeze(0), self.in_proj_qkv.weight, self.in_proj_z.weight, self.in_proj_b.weight,
    +            self.in_proj_a.weight, gdn_kernel_op).view(1, 1, -1)
    +    else:
    +        fused = GDNInputProj.apply(hidden_states, self.in_proj_qkv.weight, self.in_proj_z.weight,
    +                                   self.in_proj_b.weight, self.in_proj_a.weight, gdn_kernel_op)
    +    key_dim, value_dim = self.key_dim, self.value_dim
    +    qkv_end = key_dim * 2 + value_dim
    +    z_end = qkv_end + value_dim
    +    b_end = z_end + self.num_v_heads
    +    # One explicit repack of the qkv slice into the [b, conv_dim, s] layout
    +    # conv1d consumes; handing FLA a non-contiguous view triggers a slower
    +    # multi-op internal path (measured as ~40 extra launches per layer).
    +    mixed_qkv = fused[..., :qkv_end].transpose(1, 2).contiguous()
    +    z = fused[..., qkv_end:z_end].reshape(batch_size, seq_len, -1, self.head_v_dim)
    +    b = fused[..., z_end:b_end]
    +    a = fused[..., b_end:]
    +
    +    if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past:
    +        conv_state = cache_params.layers[self.layer_idx].conv_states[0]
    +        mixed_qkv = self._ki_gdn_conv_update(mixed_qkv, conv_state)
    +    else:
    +        if cache_params is not None:
    +            mixed_qkv = cache_params.update_conv_state(mixed_qkv,
    +                                                       self.layer_idx,
    +                                                       conv_kernel_size=self.conv_kernel_size)
    +        mixed_qkv = self._ki_gdn_conv_fn(mixed_qkv, **kwargs)
    +        if cache_params is not None:
    +            mixed_qkv = mixed_qkv[:, :, -seq_len:]
    +
    +    mixed_qkv = mixed_qkv.transpose(1, 2)
    +    query, key, value = torch.split(mixed_qkv, [key_dim, key_dim, value_dim], dim=-1)
    +    query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
    +
    +    gdn_op = getattr(self, "_ki_gdn_op", None)
    +    from deepspeed.accelerator import get_accelerator
    +    if gdn_op is not None and get_accelerator().on_accelerator(a):
    +        a_log_f = self.A_log.detach().float().contiguous()
    +        dt_f = self.dt_bias.detach().float().contiguous()
    +        # gdn_gates accepts row-strided a/b, so the fused-output slices go in
    +        # without contiguous copies.
    +        beta, g = gdn_op.gdn_gates(a, b, a_log_f, dt_f)

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

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,628 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def _is_silu_activation(act) -> bool:
    +    """True when ``act`` is SiLU as a torch module, the plain function, or
    +    transformers' SiLUActivation wrapper (what Qwen3.5 MLPs carry)."""
    +    if isinstance(act, torch.nn.SiLU):
    +        return True
    +    if act is torch.nn.functional.silu:
    +        return True
    +    return type(act).__name__ == "SiLUActivation"
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        # The fused replacement hardcodes SiLU, while the name-based selector
    +        # also matches GELU-gated families (e.g. Gemma). Only fuse when the
    +        # module's own activation is positively identified as SiLU.
    +        activations = [getattr(module, name, None) for name in ("act_fn", "activation_fn", "activation_func")]
    +        if not any(_is_silu_activation(act) for act in activations if act is not None):
    +            continue
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +def _native_kernel_ready(kernel_op, hidden, *weights) -> bool:
    +    """The CUDA kernels read raw BFloat16 pointers only, so anything else
    +    (fp16 weights, non-contiguous views) must take the composite reference
    +    path instead of raising inside the binding."""
    +    if kernel_op is None:
    +        return False
    +    if not hidden.is_contiguous() or hidden.dtype is not torch.bfloat16:
    +        return False
    +    return all(w.is_contiguous() and w.dtype is torch.bfloat16 for w in weights)
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, gate_w, up_w):
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            # Training activations are [batch, seq, hidden]; .t() only works
    +            # on 2-D, so flatten the leading dims as the GDN backward does.
    +            flat_hidden = hidden.reshape(-1, hidden.shape[-1])
    +            grad_gate_w = torch.matmul(grad_gate_coef.reshape(-1, grad_gate_coef.shape[-1]).t(),
    +                                       flat_hidden).view_as(gate_w)
    +            grad_up_w = torch.matmul(grad_up_coef.reshape(-1, grad_up_coef.shape[-1]).t(), flat_hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, w_qkv, w_z, w_b, w_a):
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))
    +
    +
    +@dataclass
    +class GDNSegment:
    +    """A GatedDeltaNet middle segment for hybrid families (e.g. Qwen3.5).
    +
    +    The four input projections share one input and are comm-free under TP, so
    +    they collapse into a single GEMM. Everything from conv1d through the FLA
    +    scan kernel to out_proj is delegated untouched: the ecosystem kernels are
    +    already state of the art and the trailing out_proj is the collective
    +    boundary."""
    +    parent: torch.nn.Module
    +    in_proj_qkv: torch.nn.Module
    +    in_proj_z: torch.nn.Module
    +    in_proj_b: torch.nn.Module
    +    in_proj_a: torch.nn.Module
    +
    +
    +def find_gdn_segments(root: torch.nn.Module) -> List[GDNSegment]:
    +    """Detect GatedDeltaNet blocks by structure (in_proj attribute set)."""
    +    segments = []
    +    names = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
    +    for module, p in _find_fusable_projections(root, names):
    +        segments.append(GDNSegment(parent=module, **{n: p[n] for n in names}))
    +    return segments
    +
    +
    +def _fused_gdn_forward(self, hidden_states, *args, **kwargs):
    +    """GDN block forward with the four input projections fused into one GEMM.
    +
    +    Mirrors the native flow (transformers Qwen3_5GatedDeltaNet.forward) while
    +    delegating conv1d, the delta-rule scan, the gated norm, and the
    +    collective-bearing out_proj to the untouched original submodules."""
    +    from transformers.models.qwen3_5.modeling_qwen3_5 import apply_mask_to_padding_states
    +
    +    # Consume the layer-level kwargs so they cannot leak into the scan call
    +    # (the native forward's named parameters absorb them; ours must too).
    +    attention_mask = kwargs.pop("attention_mask", None)
    +    cache_params = kwargs.pop("cache_params", None) or (args[0] if args else None)
    +    hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
    +
    +    batch_size, seq_len, _ = hidden_states.shape
    +    use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
    +
    +    # Fused [qkv | z | b | a] projection reading the original weights (b=1
    +    # quad_gemv kernel, b>1 on-the-fly concat) — no weight copies.
    +    gdn_kernel_op = getattr(self, "_ki_gdn_op", None)
    +    if batch_size == 1 and seq_len == 1:
    +        fused = GDNInputProj.apply(
    +            hidden_states.squeeze(0).squeeze(0), self.in_proj_qkv.weight, self.in_proj_z.weight, self.in_proj_b.weight,
    +            self.in_proj_a.weight, gdn_kernel_op).view(1, 1, -1)
    +    else:
    +        fused = GDNInputProj.apply(hidden_states, self.in_proj_qkv.weight, self.in_proj_z.weight,
    +                                   self.in_proj_b.weight, self.in_proj_a.weight, gdn_kernel_op)
    +    key_dim, value_dim = self.key_dim, self.value_dim
    +    qkv_end = key_dim * 2 + value_dim
    +    z_end = qkv_end + value_dim
    +    b_end = z_end + self.num_v_heads
    +    # One explicit repack of the qkv slice into the [b, conv_dim, s] layout
    +    # conv1d consumes; handing FLA a non-contiguous view triggers a slower
    +    # multi-op internal path (measured as ~40 extra launches per layer).
    +    mixed_qkv = fused[..., :qkv_end].transpose(1, 2).contiguous()
    +    z = fused[..., qkv_end:z_end].reshape(batch_size, seq_len, -1, self.head_v_dim)
    +    b = fused[..., z_end:b_end]
    +    a = fused[..., b_end:]
    +
    +    if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past:
    +        conv_state = cache_params.layers[self.layer_idx].conv_states[0]
    +        mixed_qkv = self._ki_gdn_conv_update(mixed_qkv, conv_state)
    +    else:
    +        if cache_params is not None:
    +            mixed_qkv = cache_params.update_conv_state(mixed_qkv,
    +                                                       self.layer_idx,
    +                                                       conv_kernel_size=self.conv_kernel_size)
    +        mixed_qkv = self._ki_gdn_conv_fn(mixed_qkv, **kwargs)
    +        if cache_params is not None:
    +            mixed_qkv = mixed_qkv[:, :, -seq_len:]
    +
    +    mixed_qkv = mixed_qkv.transpose(1, 2)
    +    query, key, value = torch.split(mixed_qkv, [key_dim, key_dim, value_dim], dim=-1)
    +    query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
    +
    +    gdn_op = getattr(self, "_ki_gdn_op", None)
    +    from deepspeed.accelerator import get_accelerator
    +    if gdn_op is not None and get_accelerator().on_accelerator(a):
    +        a_log_f = self.A_log.detach().float().contiguous()
    +        dt_f = self.dt_bias.detach().float().contiguous()
    +        # gdn_gates accepts row-strided a/b, so the fused-output slices go in
    +        # without contiguous copies.
    +        beta, g = gdn_op.gdn_gates(a, b, a_log_f, dt_f)
    +    else:
    +        beta = b.sigmoid()
    +        g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
    +    if self.num_v_heads // self.num_k_heads > 1:
    +        query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +        key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +
    +    recurrent_state = cache_params.layers[self.layer_idx].recurrent_states[0] if use_precomputed_states else None
    +    # Whitelist the scan inputs: transformers threads unrelated layer kwargs
    +    # (use_cache, cache_position, ...) down to every block and the fused
    +    # kernel signatures reject unknown names.
    +    scan_kwargs = dict(g=g,
    +                       beta=beta,
    +                       initial_state=recurrent_state,
    +                       output_final_state=cache_params is not None,
    +                       use_qk_l2norm_in_kernel=True)
    +    cu_seqlens = kwargs.get("cu_seq_lens_q") or kwargs.get("cu_seqlens")
    +    if cu_seqlens is not None:
    +        scan_kwargs["cu_seqlens"] = cu_seqlens

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,628 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def _is_silu_activation(act) -> bool:
    +    """True when ``act`` is SiLU as a torch module, the plain function, or
    +    transformers' SiLUActivation wrapper (what Qwen3.5 MLPs carry)."""
    +    if isinstance(act, torch.nn.SiLU):
    +        return True
    +    if act is torch.nn.functional.silu:
    +        return True
    +    return type(act).__name__ == "SiLUActivation"
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        # The fused replacement hardcodes SiLU, while the name-based selector
    +        # also matches GELU-gated families (e.g. Gemma). Only fuse when the
    +        # module's own activation is positively identified as SiLU.
    +        activations = [getattr(module, name, None) for name in ("act_fn", "activation_fn", "activation_func")]
    +        if not any(_is_silu_activation(act) for act in activations if act is not None):
    +            continue
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +def _native_kernel_ready(kernel_op, hidden, *weights) -> bool:
    +    """The CUDA kernels read raw BFloat16 pointers only, so anything else
    +    (fp16 weights, non-contiguous views) must take the composite reference
    +    path instead of raising inside the binding."""
    +    if kernel_op is None:
    +        return False
    +    if not hidden.is_contiguous() or hidden.dtype is not torch.bfloat16:
    +        return False
    +    return all(w.is_contiguous() and w.dtype is torch.bfloat16 for w in weights)
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, gate_w, up_w):
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            # Training activations are [batch, seq, hidden]; .t() only works
    +            # on 2-D, so flatten the leading dims as the GDN backward does.
    +            flat_hidden = hidden.reshape(-1, hidden.shape[-1])
    +            grad_gate_w = torch.matmul(grad_gate_coef.reshape(-1, grad_gate_coef.shape[-1]).t(),
    +                                       flat_hidden).view_as(gate_w)
    +            grad_up_w = torch.matmul(grad_up_coef.reshape(-1, grad_up_coef.shape[-1]).t(), flat_hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, w_qkv, w_z, w_b, w_a):
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))
    +
    +
    +@dataclass
    +class GDNSegment:
    +    """A GatedDeltaNet middle segment for hybrid families (e.g. Qwen3.5).
    +
    +    The four input projections share one input and are comm-free under TP, so
    +    they collapse into a single GEMM. Everything from conv1d through the FLA
    +    scan kernel to out_proj is delegated untouched: the ecosystem kernels are
    +    already state of the art and the trailing out_proj is the collective
    +    boundary."""
    +    parent: torch.nn.Module
    +    in_proj_qkv: torch.nn.Module
    +    in_proj_z: torch.nn.Module
    +    in_proj_b: torch.nn.Module
    +    in_proj_a: torch.nn.Module
    +
    +
    +def find_gdn_segments(root: torch.nn.Module) -> List[GDNSegment]:
    +    """Detect GatedDeltaNet blocks by structure (in_proj attribute set)."""
    +    segments = []
    +    names = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
    +    for module, p in _find_fusable_projections(root, names):
    +        segments.append(GDNSegment(parent=module, **{n: p[n] for n in names}))
    +    return segments
    +
    +
    +def _fused_gdn_forward(self, hidden_states, *args, **kwargs):
    +    """GDN block forward with the four input projections fused into one GEMM.
    +
    +    Mirrors the native flow (transformers Qwen3_5GatedDeltaNet.forward) while
    +    delegating conv1d, the delta-rule scan, the gated norm, and the
    +    collective-bearing out_proj to the untouched original submodules."""
    +    from transformers.models.qwen3_5.modeling_qwen3_5 import apply_mask_to_padding_states
    +
    +    # Consume the layer-level kwargs so they cannot leak into the scan call
    +    # (the native forward's named parameters absorb them; ours must too).
    +    attention_mask = kwargs.pop("attention_mask", None)
    +    cache_params = kwargs.pop("cache_params", None) or (args[0] if args else None)
    +    hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
    +
    +    batch_size, seq_len, _ = hidden_states.shape
    +    use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
    +
    +    # Fused [qkv | z | b | a] projection reading the original weights (b=1
    +    # quad_gemv kernel, b>1 on-the-fly concat) — no weight copies.
    +    gdn_kernel_op = getattr(self, "_ki_gdn_op", None)
    +    if batch_size == 1 and seq_len == 1:
    +        fused = GDNInputProj.apply(
    +            hidden_states.squeeze(0).squeeze(0), self.in_proj_qkv.weight, self.in_proj_z.weight, self.in_proj_b.weight,
    +            self.in_proj_a.weight, gdn_kernel_op).view(1, 1, -1)
    +    else:
    +        fused = GDNInputProj.apply(hidden_states, self.in_proj_qkv.weight, self.in_proj_z.weight,
    +                                   self.in_proj_b.weight, self.in_proj_a.weight, gdn_kernel_op)
    +    key_dim, value_dim = self.key_dim, self.value_dim
    +    qkv_end = key_dim * 2 + value_dim
    +    z_end = qkv_end + value_dim
    +    b_end = z_end + self.num_v_heads
    +    # One explicit repack of the qkv slice into the [b, conv_dim, s] layout
    +    # conv1d consumes; handing FLA a non-contiguous view triggers a slower
    +    # multi-op internal path (measured as ~40 extra launches per layer).
    +    mixed_qkv = fused[..., :qkv_end].transpose(1, 2).contiguous()
    +    z = fused[..., qkv_end:z_end].reshape(batch_size, seq_len, -1, self.head_v_dim)
    +    b = fused[..., z_end:b_end]
    +    a = fused[..., b_end:]
    +
    +    if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past:
    +        conv_state = cache_params.layers[self.layer_idx].conv_states[0]
    +        mixed_qkv = self._ki_gdn_conv_update(mixed_qkv, conv_state)
    +    else:
    +        if cache_params is not None:
    +            mixed_qkv = cache_params.update_conv_state(mixed_qkv,
    +                                                       self.layer_idx,
    +                                                       conv_kernel_size=self.conv_kernel_size)
    +        mixed_qkv = self._ki_gdn_conv_fn(mixed_qkv, **kwargs)
    +        if cache_params is not None:
    +            mixed_qkv = mixed_qkv[:, :, -seq_len:]
    +
    +    mixed_qkv = mixed_qkv.transpose(1, 2)
    +    query, key, value = torch.split(mixed_qkv, [key_dim, key_dim, value_dim], dim=-1)
    +    query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
    +
    +    gdn_op = getattr(self, "_ki_gdn_op", None)
    +    from deepspeed.accelerator import get_accelerator
    +    if gdn_op is not None and get_accelerator().on_accelerator(a):
    +        a_log_f = self.A_log.detach().float().contiguous()
    +        dt_f = self.dt_bias.detach().float().contiguous()
    +        # gdn_gates accepts row-strided a/b, so the fused-output slices go in
    +        # without contiguous copies.
    +        beta, g = gdn_op.gdn_gates(a, b, a_log_f, dt_f)
    +    else:
    +        beta = b.sigmoid()
    +        g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
    +    if self.num_v_heads // self.num_k_heads > 1:
    +        query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +        key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +
    +    recurrent_state = cache_params.layers[self.layer_idx].recurrent_states[0] if use_precomputed_states else None
    +    # Whitelist the scan inputs: transformers threads unrelated layer kwargs
    +    # (use_cache, cache_position, ...) down to every block and the fused
    +    # kernel signatures reject unknown names.
    +    scan_kwargs = dict(g=g,
    +                       beta=beta,
    +                       initial_state=recurrent_state,
    +                       output_final_state=cache_params is not None,
    +                       use_qk_l2norm_in_kernel=True)
    +    cu_seqlens = kwargs.get("cu_seq_lens_q") or kwargs.get("cu_seqlens")
    +    if cu_seqlens is not None:
    +        scan_kwargs["cu_seqlens"] = cu_seqlens
    +    core_attn_out, last_recurrent_state = self._ki_gdn_scan(query, key, value, **scan_kwargs)
    +    if cache_params is not None:
    +        cache_params.update_recurrent_state(last_recurrent_state, self.layer_idx)
    +
    +    core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
    +    z = z.reshape(-1, self.head_v_dim)
    +    core_attn_out = self.norm(core_attn_out, z)
    +    core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
    +    return self.out_proj(core_attn_out)
    +
    +
    +def _install_gdn_segment(seg: GDNSegment) -> bool:
    +    """Wire the fused forward onto a GDN block, binding its original helpers.
    +
    +    The conv/scan callables are captured from the transformers module so the
    +    replacement keeps using the exact kernels (FLA/causal-conv1d paths and
    +    their cache contracts) that the native forward would have selected."""
    +    import transformers.models.qwen3_5.modeling_qwen3_5 as m5
    +
    +    conv_update = getattr(m5, "causal_conv1d_update", None)
    +    conv_fn = getattr(m5, "causal_conv1d_fn", None)
    +    if conv_update is None or conv_fn is None:
    +        return False
    +
    +    parent = seg.parent
    +
    +    def conv_update_with_weights(mixed_qkv, conv_state):
    +        return conv_update(mixed_qkv, conv_state, parent.conv1d.weight.squeeze(1), parent.conv1d.bias,
    +                           parent.activation)
    +
    +    def conv_fn_with_weights(mixed_qkv, **kw):
    +        # causal_conv1d_fn does not accept HF generation kwargs; filter them
    +        # the same way the scan closure does.
    +        kw.pop("use_cache", None)
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        return conv_fn(mixed_qkv,
    +                       parent.conv1d.weight.squeeze(1),
    +                       parent.conv1d.bias,
    +                       activation=parent.activation,
    +                       **kw)
    +
    +    def scan(query, key, value, **kw):
    +        # Route through the block's own instance-bound kernels: transformers
    +        # binds the FLA fused implementations onto the module when available
    +        # (recurrent_gated_delta_rule/chunk_gated_delta_rule) and only falls
    +        # back to the pure-torch references otherwise. Calling the module-level
    +        # torch_* functions directly forces the slow fallback on every layer.
    +        single = kw.get("initial_state") is not None and query.shape[1] == 1
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        fn = parent.recurrent_gated_delta_rule if single else parent.chunk_gated_delta_rule
    +        return fn(query, key, value, **kw)
    +
    +    kernel_op = None
    +    try:
    +        from deepspeed.accelerator import get_accelerator
    +        if get_accelerator().device_name() != "cpu":
    +            from deepspeed.ops.module_inject import get_fused_glu_op
    +            kernel_op = get_fused_glu_op()
    +    except Exception:
    +        kernel_op = None
    +    parent._ki_gdn_op = kernel_op
    +    parent._ki_gdn_conv_update = conv_update_with_weights
    +    parent._ki_gdn_conv_fn = conv_fn_with_weights
    +    parent._ki_gdn_scan = scan
    +    parent.forward = _fused_gdn_forward.__get__(parent, type(parent))
    +    return True
    +
    +
    +def apply_segment_ki(model: torch.nn.Module) -> dict:
    +    """Install segment kernels on ``model`` (post-AutoTP, pre-generate).
    +
    +    Uses the native CUDA op when a non-cpu accelerator backend is active;
    +    falls back to the torch composite reference otherwise.
    +
    +    Returns a small report so callers (tests, journals) can assert what was
    +    found and replaced without introspecting the module tree again.
    +    """
    +    kernel_op = None
    +    from deepspeed.accelerator import get_accelerator
    +    if get_accelerator().device_name() != "cpu":
    +        from deepspeed.ops.module_inject import get_fused_glu_op
    +        kernel_op = get_fused_glu_op()
    +
    +    report = {"backend": "cuda" if kernel_op is not None else "composite"}
    +
    +    segments = find_glu_segments(model)
    +    replaced = 0
    +    for seg in segments:
    +        seg.parent._ki_dual_op = kernel_op if kernel_op is not None and hasattr(kernel_op,
    +                                                                                "dual_gemv_silu_mul") else None
    +        seg.parent.forward = _dual_weight_glu_forward.__get__(seg.parent, type(seg.parent))
    +        replaced += 1
    +    report["fused_glu"] = {"segments_found": len(segments), "segments_replaced": replaced}
    +
    +    gdn_segments = find_gdn_segments(model)
    +    gdn_replaced = sum(1 for seg in gdn_segments if _install_gdn_segment(seg))
    +    report["fused_gdn"] = {"segments_found": len(gdn_segments), "segments_replaced": gdn_replaced}
    +
    +    return report
    +
    +
    +# ─── Custom b=1 decode attention: replace SDPA in full-attention layers ───
    +
    +
    +def _decode_attn_forward(self,
    +                         hidden_states,
    +                         position_embeddings=None,
    +                         attention_mask=None,
    +                         past_key_values=None,
    +                         **kwargs):
    +    """Replacement forward for full-attention layers: run the custom
    +    decode_attn kernel at b=1, seq_len=1 instead of SDPA-with-mask (which
    +    falls into the slow mem_efficient backend against the full-width static
    +    cache buffer).
    +
    +    Everything except the attention core is a verbatim replay of the HF
    +    forward (q_proj 2x-wide gate split, per-head q/k norms, RoPE, KV cache
    +    update, gate multiply, o_proj), so numerics match the original path.
    +    The kernel reads the valid KV length from the same GPU-resident
    +    write_pos tensor the cache update writes through, keeping the whole
    +    step CUDA-graph replayable."""
    +    if (hidden_states.shape[0] != 1 or hidden_states.shape[1] > 1 or past_key_values is None
    +            or getattr(self, "_ki_attn_op", None) is None
    +            or getattr(past_key_values, "_write_position", None) is not self._ki_write_pos):
    +        # Prefill, batched decode, or a non-graph cache (e.g. DynamicCache
    +        # inside module.generate): the original forward is the correct path.
    +        return self._ki_orig_attn_forward(hidden_states, position_embeddings, attention_mask, past_key_values,
    +                                          **kwargs)
    +
    +    input_shape = hidden_states.shape[:-1]
    +    hidden_shape = (*input_shape, -1, self.head_dim)
    +
    +    qkv_op = getattr(self, "_ki_qkv_op", None)
    +    if qkv_op is not None:
    +        # One GEMV launch over q/k/v weights directly — replaces the
    +        # three separate F.linear launches. q_proj keeps its 2x-wide
    +        # query|gate layout, so the gate split below is unchanged from HF.
    +        q_out, k_out, v_out = qkv_op.triple_gemv(hidden_states.view(-1), self.q_proj.weight, self.k_proj.weight,
    +                                                 self.v_proj.weight)
    +        query_states, gate = torch.chunk(q_out.view(*input_shape, -1, self.head_dim * 2), 2, dim=-1)
    +        gate = gate.reshape(*input_shape, -1)
    +        query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
    +        key_states = self.k_norm(k_out.view(hidden_shape)).transpose(1, 2)
    +        value_states = v_out.view(hidden_shape).transpose(1, 2)
    +    else:
    +        query_states, gate = torch.chunk(self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2),
    +                                         2,
    +                                         dim=-1)
    +        gate = gate.reshape(*input_shape, -1)
    +
    +        query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
    +        key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
    +        value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
    +
    +    cos, sin = position_embeddings
    +    query_states, key_states = self._ki_rope(query_states, key_states, cos, sin)
    +
    +    key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
    +
    +    num_q_heads, num_kv_heads, head_dim = self._ki_num_q_heads, self._ki_num_kv_heads, self.head_dim
    +    out = torch.empty(num_q_heads, head_dim, dtype=hidden_states.dtype, device=hidden_states.device)
    +    self._ki_attn_op.decode_attn(query_states.reshape(num_q_heads, head_dim), key_states[0], value_states[0],
    +                                 self._ki_write_pos, out, num_q_heads, num_kv_heads, head_dim, key_states.shape[2])

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,628 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def _is_silu_activation(act) -> bool:
    +    """True when ``act`` is SiLU as a torch module, the plain function, or
    +    transformers' SiLUActivation wrapper (what Qwen3.5 MLPs carry)."""
    +    if isinstance(act, torch.nn.SiLU):
    +        return True
    +    if act is torch.nn.functional.silu:
    +        return True
    +    return type(act).__name__ == "SiLUActivation"
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        # The fused replacement hardcodes SiLU, while the name-based selector
    +        # also matches GELU-gated families (e.g. Gemma). Only fuse when the
    +        # module's own activation is positively identified as SiLU.
    +        activations = [getattr(module, name, None) for name in ("act_fn", "activation_fn", "activation_func")]
    +        if not any(_is_silu_activation(act) for act in activations if act is not None):
    +            continue
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +def _native_kernel_ready(kernel_op, hidden, *weights) -> bool:
    +    """The CUDA kernels read raw BFloat16 pointers only, so anything else
    +    (fp16 weights, non-contiguous views) must take the composite reference
    +    path instead of raising inside the binding."""
    +    if kernel_op is None:
    +        return False
    +    if not hidden.is_contiguous() or hidden.dtype is not torch.bfloat16:
    +        return False
    +    return all(w.is_contiguous() and w.dtype is torch.bfloat16 for w in weights)
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, gate_w, up_w):
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            # Training activations are [batch, seq, hidden]; .t() only works
    +            # on 2-D, so flatten the leading dims as the GDN backward does.
    +            flat_hidden = hidden.reshape(-1, hidden.shape[-1])
    +            grad_gate_w = torch.matmul(grad_gate_coef.reshape(-1, grad_gate_coef.shape[-1]).t(),
    +                                       flat_hidden).view_as(gate_w)
    +            grad_up_w = torch.matmul(grad_up_coef.reshape(-1, grad_up_coef.shape[-1]).t(), flat_hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, w_qkv, w_z, w_b, w_a):
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))
    +
    +
    +@dataclass
    +class GDNSegment:
    +    """A GatedDeltaNet middle segment for hybrid families (e.g. Qwen3.5).
    +
    +    The four input projections share one input and are comm-free under TP, so
    +    they collapse into a single GEMM. Everything from conv1d through the FLA
    +    scan kernel to out_proj is delegated untouched: the ecosystem kernels are
    +    already state of the art and the trailing out_proj is the collective
    +    boundary."""
    +    parent: torch.nn.Module
    +    in_proj_qkv: torch.nn.Module
    +    in_proj_z: torch.nn.Module
    +    in_proj_b: torch.nn.Module
    +    in_proj_a: torch.nn.Module
    +
    +
    +def find_gdn_segments(root: torch.nn.Module) -> List[GDNSegment]:
    +    """Detect GatedDeltaNet blocks by structure (in_proj attribute set)."""
    +    segments = []
    +    names = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
    +    for module, p in _find_fusable_projections(root, names):
    +        segments.append(GDNSegment(parent=module, **{n: p[n] for n in names}))
    +    return segments
    +
    +
    +def _fused_gdn_forward(self, hidden_states, *args, **kwargs):
    +    """GDN block forward with the four input projections fused into one GEMM.
    +
    +    Mirrors the native flow (transformers Qwen3_5GatedDeltaNet.forward) while
    +    delegating conv1d, the delta-rule scan, the gated norm, and the
    +    collective-bearing out_proj to the untouched original submodules."""
    +    from transformers.models.qwen3_5.modeling_qwen3_5 import apply_mask_to_padding_states
    +
    +    # Consume the layer-level kwargs so they cannot leak into the scan call
    +    # (the native forward's named parameters absorb them; ours must too).
    +    attention_mask = kwargs.pop("attention_mask", None)
    +    cache_params = kwargs.pop("cache_params", None) or (args[0] if args else None)
    +    hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
    +
    +    batch_size, seq_len, _ = hidden_states.shape
    +    use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
    +
    +    # Fused [qkv | z | b | a] projection reading the original weights (b=1
    +    # quad_gemv kernel, b>1 on-the-fly concat) — no weight copies.
    +    gdn_kernel_op = getattr(self, "_ki_gdn_op", None)
    +    if batch_size == 1 and seq_len == 1:
    +        fused = GDNInputProj.apply(
    +            hidden_states.squeeze(0).squeeze(0), self.in_proj_qkv.weight, self.in_proj_z.weight, self.in_proj_b.weight,
    +            self.in_proj_a.weight, gdn_kernel_op).view(1, 1, -1)
    +    else:
    +        fused = GDNInputProj.apply(hidden_states, self.in_proj_qkv.weight, self.in_proj_z.weight,
    +                                   self.in_proj_b.weight, self.in_proj_a.weight, gdn_kernel_op)
    +    key_dim, value_dim = self.key_dim, self.value_dim
    +    qkv_end = key_dim * 2 + value_dim
    +    z_end = qkv_end + value_dim
    +    b_end = z_end + self.num_v_heads
    +    # One explicit repack of the qkv slice into the [b, conv_dim, s] layout
    +    # conv1d consumes; handing FLA a non-contiguous view triggers a slower
    +    # multi-op internal path (measured as ~40 extra launches per layer).
    +    mixed_qkv = fused[..., :qkv_end].transpose(1, 2).contiguous()
    +    z = fused[..., qkv_end:z_end].reshape(batch_size, seq_len, -1, self.head_v_dim)
    +    b = fused[..., z_end:b_end]
    +    a = fused[..., b_end:]
    +
    +    if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past:
    +        conv_state = cache_params.layers[self.layer_idx].conv_states[0]
    +        mixed_qkv = self._ki_gdn_conv_update(mixed_qkv, conv_state)
    +    else:
    +        if cache_params is not None:
    +            mixed_qkv = cache_params.update_conv_state(mixed_qkv,
    +                                                       self.layer_idx,
    +                                                       conv_kernel_size=self.conv_kernel_size)
    +        mixed_qkv = self._ki_gdn_conv_fn(mixed_qkv, **kwargs)
    +        if cache_params is not None:
    +            mixed_qkv = mixed_qkv[:, :, -seq_len:]
    +
    +    mixed_qkv = mixed_qkv.transpose(1, 2)
    +    query, key, value = torch.split(mixed_qkv, [key_dim, key_dim, value_dim], dim=-1)
    +    query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
    +
    +    gdn_op = getattr(self, "_ki_gdn_op", None)
    +    from deepspeed.accelerator import get_accelerator
    +    if gdn_op is not None and get_accelerator().on_accelerator(a):
    +        a_log_f = self.A_log.detach().float().contiguous()
    +        dt_f = self.dt_bias.detach().float().contiguous()
    +        # gdn_gates accepts row-strided a/b, so the fused-output slices go in
    +        # without contiguous copies.
    +        beta, g = gdn_op.gdn_gates(a, b, a_log_f, dt_f)
    +    else:
    +        beta = b.sigmoid()
    +        g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
    +    if self.num_v_heads // self.num_k_heads > 1:
    +        query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +        key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +
    +    recurrent_state = cache_params.layers[self.layer_idx].recurrent_states[0] if use_precomputed_states else None
    +    # Whitelist the scan inputs: transformers threads unrelated layer kwargs
    +    # (use_cache, cache_position, ...) down to every block and the fused
    +    # kernel signatures reject unknown names.
    +    scan_kwargs = dict(g=g,
    +                       beta=beta,
    +                       initial_state=recurrent_state,
    +                       output_final_state=cache_params is not None,
    +                       use_qk_l2norm_in_kernel=True)
    +    cu_seqlens = kwargs.get("cu_seq_lens_q") or kwargs.get("cu_seqlens")
    +    if cu_seqlens is not None:
    +        scan_kwargs["cu_seqlens"] = cu_seqlens
    +    core_attn_out, last_recurrent_state = self._ki_gdn_scan(query, key, value, **scan_kwargs)
    +    if cache_params is not None:
    +        cache_params.update_recurrent_state(last_recurrent_state, self.layer_idx)
    +
    +    core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
    +    z = z.reshape(-1, self.head_v_dim)
    +    core_attn_out = self.norm(core_attn_out, z)
    +    core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
    +    return self.out_proj(core_attn_out)
    +
    +
    +def _install_gdn_segment(seg: GDNSegment) -> bool:
    +    """Wire the fused forward onto a GDN block, binding its original helpers.
    +
    +    The conv/scan callables are captured from the transformers module so the
    +    replacement keeps using the exact kernels (FLA/causal-conv1d paths and
    +    their cache contracts) that the native forward would have selected."""
    +    import transformers.models.qwen3_5.modeling_qwen3_5 as m5
    +
    +    conv_update = getattr(m5, "causal_conv1d_update", None)
    +    conv_fn = getattr(m5, "causal_conv1d_fn", None)
    +    if conv_update is None or conv_fn is None:
    +        return False
    +
    +    parent = seg.parent
    +
    +    def conv_update_with_weights(mixed_qkv, conv_state):
    +        return conv_update(mixed_qkv, conv_state, parent.conv1d.weight.squeeze(1), parent.conv1d.bias,
    +                           parent.activation)
    +
    +    def conv_fn_with_weights(mixed_qkv, **kw):
    +        # causal_conv1d_fn does not accept HF generation kwargs; filter them
    +        # the same way the scan closure does.
    +        kw.pop("use_cache", None)
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        return conv_fn(mixed_qkv,
    +                       parent.conv1d.weight.squeeze(1),
    +                       parent.conv1d.bias,
    +                       activation=parent.activation,
    +                       **kw)
    +
    +    def scan(query, key, value, **kw):
    +        # Route through the block's own instance-bound kernels: transformers
    +        # binds the FLA fused implementations onto the module when available
    +        # (recurrent_gated_delta_rule/chunk_gated_delta_rule) and only falls
    +        # back to the pure-torch references otherwise. Calling the module-level
    +        # torch_* functions directly forces the slow fallback on every layer.
    +        single = kw.get("initial_state") is not None and query.shape[1] == 1
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        fn = parent.recurrent_gated_delta_rule if single else parent.chunk_gated_delta_rule
    +        return fn(query, key, value, **kw)
    +
    +    kernel_op = None
    +    try:
    +        from deepspeed.accelerator import get_accelerator
    +        if get_accelerator().device_name() != "cpu":
    +            from deepspeed.ops.module_inject import get_fused_glu_op
    +            kernel_op = get_fused_glu_op()
    +    except Exception:
    +        kernel_op = None
    +    parent._ki_gdn_op = kernel_op
    +    parent._ki_gdn_conv_update = conv_update_with_weights
    +    parent._ki_gdn_conv_fn = conv_fn_with_weights
    +    parent._ki_gdn_scan = scan
    +    parent.forward = _fused_gdn_forward.__get__(parent, type(parent))
    +    return True
    +
    +
    +def apply_segment_ki(model: torch.nn.Module) -> dict:
    +    """Install segment kernels on ``model`` (post-AutoTP, pre-generate).
    +
    +    Uses the native CUDA op when a non-cpu accelerator backend is active;
    +    falls back to the torch composite reference otherwise.
    +
    +    Returns a small report so callers (tests, journals) can assert what was
    +    found and replaced without introspecting the module tree again.
    +    """
    +    kernel_op = None
    +    from deepspeed.accelerator import get_accelerator
    +    if get_accelerator().device_name() != "cpu":
    +        from deepspeed.ops.module_inject import get_fused_glu_op
    +        kernel_op = get_fused_glu_op()
    +
    +    report = {"backend": "cuda" if kernel_op is not None else "composite"}
    +
    +    segments = find_glu_segments(model)
    +    replaced = 0
    +    for seg in segments:
    +        seg.parent._ki_dual_op = kernel_op if kernel_op is not None and hasattr(kernel_op,
    +                                                                                "dual_gemv_silu_mul") else None
    +        seg.parent.forward = _dual_weight_glu_forward.__get__(seg.parent, type(seg.parent))
    +        replaced += 1
    +    report["fused_glu"] = {"segments_found": len(segments), "segments_replaced": replaced}
    +
    +    gdn_segments = find_gdn_segments(model)
    +    gdn_replaced = sum(1 for seg in gdn_segments if _install_gdn_segment(seg))
    +    report["fused_gdn"] = {"segments_found": len(gdn_segments), "segments_replaced": gdn_replaced}
    +
    +    return report
    +
    +
    +# ─── Custom b=1 decode attention: replace SDPA in full-attention layers ───
    +
    +
    +def _decode_attn_forward(self,
    +                         hidden_states,
    +                         position_embeddings=None,
    +                         attention_mask=None,
    +                         past_key_values=None,
    +                         **kwargs):
    +    """Replacement forward for full-attention layers: run the custom
    +    decode_attn kernel at b=1, seq_len=1 instead of SDPA-with-mask (which
    +    falls into the slow mem_efficient backend against the full-width static
    +    cache buffer).
    +
    +    Everything except the attention core is a verbatim replay of the HF
    +    forward (q_proj 2x-wide gate split, per-head q/k norms, RoPE, KV cache
    +    update, gate multiply, o_proj), so numerics match the original path.
    +    The kernel reads the valid KV length from the same GPU-resident
    +    write_pos tensor the cache update writes through, keeping the whole
    +    step CUDA-graph replayable."""
    +    if (hidden_states.shape[0] != 1 or hidden_states.shape[1] > 1 or past_key_values is None
    +            or getattr(self, "_ki_attn_op", None) is None
    +            or getattr(past_key_values, "_write_position", None) is not self._ki_write_pos):
    +        # Prefill, batched decode, or a non-graph cache (e.g. DynamicCache
    +        # inside module.generate): the original forward is the correct path.
    +        return self._ki_orig_attn_forward(hidden_states, position_embeddings, attention_mask, past_key_values,
    +                                          **kwargs)
    +
    +    input_shape = hidden_states.shape[:-1]
    +    hidden_shape = (*input_shape, -1, self.head_dim)
    +
    +    qkv_op = getattr(self, "_ki_qkv_op", None)
    +    if qkv_op is not None:
    +        # One GEMV launch over q/k/v weights directly — replaces the
    +        # three separate F.linear launches. q_proj keeps its 2x-wide
    +        # query|gate layout, so the gate split below is unchanged from HF.
    +        q_out, k_out, v_out = qkv_op.triple_gemv(hidden_states.view(-1), self.q_proj.weight, self.k_proj.weight,
    +                                                 self.v_proj.weight)
    +        query_states, gate = torch.chunk(q_out.view(*input_shape, -1, self.head_dim * 2), 2, dim=-1)
    +        gate = gate.reshape(*input_shape, -1)
    +        query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
    +        key_states = self.k_norm(k_out.view(hidden_shape)).transpose(1, 2)
    +        value_states = v_out.view(hidden_shape).transpose(1, 2)
    +    else:
    +        query_states, gate = torch.chunk(self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2),
    +                                         2,
    +                                         dim=-1)
    +        gate = gate.reshape(*input_shape, -1)
    +
    +        query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
    +        key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
    +        value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
    +
    +    cos, sin = position_embeddings
    +    query_states, key_states = self._ki_rope(query_states, key_states, cos, sin)
    +
    +    key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
    +
    +    num_q_heads, num_kv_heads, head_dim = self._ki_num_q_heads, self._ki_num_kv_heads, self.head_dim
    +    out = torch.empty(num_q_heads, head_dim, dtype=hidden_states.dtype, device=hidden_states.device)
    +    self._ki_attn_op.decode_attn(query_states.reshape(num_q_heads, head_dim), key_states[0], value_states[0],
    +                                 self._ki_write_pos, out, num_q_heads, num_kv_heads, head_dim, key_states.shape[2])
    +
    +    attn_output = out.view(*input_shape, -1) * torch.sigmoid(gate)
    +    return self.o_proj(attn_output), None
    +
    +
    +def install_decode_attention(model: torch.nn.Module, write_pos: torch.Tensor, kernel_op) -> int:
    +    """Patch full-attention layers to use the custom decode_attn kernel.
    +
    +    Detection mirrors find_glu_segments: structural (q/k/v/o projections
    +    plus per-head q_norm/k_norm present, q_proj carrying the 2x-wide
    +    query|gate layout), cross-checked against the config's layer_types so
    +    linear-attention blocks are never touched. Returns the patched count;
    +    layers whose GQA ratio the kernel cannot serve are left native."""
    +    if kernel_op is None or not hasattr(kernel_op, "decode_attn"):
    +        return 0
    +    try:
    +        from transformers.models.qwen3_5.modeling_qwen3_5 import apply_rotary_pos_emb
    +    except ImportError:
    +        return 0
    +
    +    patched = 0
    +    for module in model.modules():
    +        projections = [getattr(module, name, None) for name in ("q_proj", "k_proj", "v_proj", "o_proj")]
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections):
    +            continue
    +        if not all(isinstance(getattr(module, name, None), torch.nn.Module) for name in ("q_norm", "k_norm")):
    +            continue
    +        head_dim = module.head_dim
    +        num_q_heads = projections[0].out_features // (2 * head_dim)
    +        num_kv_heads = projections[1].out_features // head_dim
    +        if num_q_heads * head_dim * 2 != projections[0].out_features:
    +            continue  # not the 2x-wide query|gate layout this forward replays
    +        layer_types = getattr(getattr(module, "config", None), "layer_types", None)
    +        if layer_types is not None and layer_types[module.layer_idx] != "full_attention":
    +            continue
    +        # Kernel contract: supported head dims and a GQA ratio that divides
    +        # its 16 warps-per-block KV split.
    +        if head_dim not in (64, 128, 256) or 16 % (num_q_heads // num_kv_heads) != 0:
    +            continue
    +        if getattr(module, "_ki_orig_attn_forward", None) is None:
    +            module._ki_orig_attn_forward = module.forward
    +        module._ki_attn_op = kernel_op
    +        module._ki_qkv_op = kernel_op if (hasattr(kernel_op, "triple_gemv")
    +                                          and os.environ.get("DS_TIER2", "1") == "1") else None
    +        module._ki_write_pos = write_pos
    +        module._ki_rope = apply_rotary_pos_emb
    +        module._ki_num_q_heads = num_q_heads
    +        module._ki_num_kv_heads = num_kv_heads
    +        module.forward = _decode_attn_forward.__get__(module, type(module))
    +        patched += 1
    +    return patched
    +
    +
    +# ─── Fused residual-add + RMSNorm in the decoder-layer forward ───
    +
    +
    +def _fused_norm_layer_forward(self,
    +                              hidden_states,
    +                              position_embeddings,
    +                              attention_mask=None,
    +                              position_ids=None,
    +                              past_key_values=None,
    +                              **kwargs):
    +    """Replacement forward for decoder layers at b=1, seq_len=1: the
    +    post-attention residual-add + RMSNorm pair runs through the
    +    fused_add_norm kernel (one launch updates the residual stream in-place
    +    and produces the normalized MLP input) instead of two launches. The
    +    pre-attention norm stays native — the HF layer normifies the raw hidden
    +    state there, with no add to fuse — and the final post-MLP add stays a
    +    plain add for the same reason. Attention and MLP are called unchanged,
    +    so attention-level patches (decode_attn / triple_gemv) still apply."""
    +    if (hidden_states.shape[0] != 1 or hidden_states.shape[1] > 1 or hidden_states.dtype is not torch.bfloat16
    +            or not hidden_states.is_contiguous() or getattr(self, "_ki_norm_op", None) is None):
    +        # Prefill, batched decode, or a non-graph path: the original forward
    +        # is the correct path.
    +        return self._ki_orig_layer_forward(hidden_states, position_embeddings, attention_mask, position_ids,
    +                                           past_key_values, **kwargs)

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

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/runtime/rollout/hybrid_engine_rollout.py:1
    @@ -573,6 +600,11 @@ def _continuous_prefill(self,
             cache_offset = cache_position - prompt_len
             for layer_idx, prefill_layer in enumerate(prefill_cache.layers):
                 target_layer = cache.layers[layer_idx]
    +            # Hybrid caches put pass-through GDN slots in the layer list;
    +            # they keep no keys/values and their state travels inside the
    +            # model's GDN modules, so there is nothing to copy per row.
    +            if not hasattr(target_layer, "keys") or not hasattr(prefill_layer, "keys"):
    +                continue

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/runtime/rollout/hybrid_engine_rollout.py:1
    @@ -741,19 +773,22 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id,
     
             # --- Prefill with HF StaticCache (correct attention semantics) ---
             prefill_cache = self._create_static_cache(StaticCache, module.config, batch_size, max_len, device, model_dtype)
    -        prefill_attn = torch.ones(batch_size, prompt_len, dtype=torch.long, device=device)
    -        prefill_attn[:, :prompt_len] = prompt_attn
    +        # Mirror generate's hybrid-model kwargs exactly: a per-type mask dict
    +        # (GDN must see None) and no explicit cache_position. A 2D mask here
    +        # corrupts the GDN conv-state initialization and collapses decode.
             prefill_out = module(
                 prompt_ids,
    -            attention_mask=prefill_attn,
    +            attention_mask={
    +                "full_attention": None,
    +                "linear_attention": None
    +            },

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/runtime/rollout/hybrid_engine_rollout.py:1
    @@ -799,51 +879,149 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id,
                     for _ in range(3):
                         out = module(
                             static_token,
    -                        attention_mask=static_attn,
    +                        attention_mask={
    +                            "full_attention": static_attn,
    +                            "linear_attention": None
    +                        },
                             past_key_values=ds_cache,
                             use_cache=True,
    -                        cache_position=static_cache_pos,
    -                        position_ids=static_pos_ids,
                         )
                 get_accelerator().current_stream().wait_stream(s)
    +            restore_gdn_states()
    +
    +            # Capture: full-step graph (forward + argmax + buffer updates).
    +            # The step-update kernel indexes token_buf via write_pos (a GPU
    +            # tensor the kernel itself advances), so no host-side step counter
    +            # is needed — the graph is fully self-contained for replay.
    +            graph_op = None
    +            try:
    +                from deepspeed.ops.module_inject import get_fused_glu_op
    +                candidate = get_fused_glu_op()
    +                if hasattr(candidate, "decode_step_graph"):
    +                    graph_op = candidate
    +            except Exception:
    +                graph_op = None
     
    -            # Capture
                 graph = get_accelerator().create_graph()
                 with get_accelerator().capture_to_graph(graph):
                     out = module(
                         static_token,
    -                    attention_mask=static_attn,
    +                    attention_mask={
    +                        "full_attention": static_attn,
    +                        "linear_attention": None
    +                    },
                         past_key_values=ds_cache,
                         use_cache=True,
    -                    cache_position=static_cache_pos,
    -                    position_ids=static_pos_ids,
                     )
    -            static_logits = out.logits
    +                static_logits = out.logits
    +                # decode_step_graph kernel is b=1 only (single-sequence argmax);
    +                # for b>1 the graph captures forward only and Python handles
    +                # argmax + buffer updates outside the graph. The kernel also
    +                # only accepts CUDA bf16 logits — fp16 models must keep the
    +                # PyTorch argmax path instead of failing during capture.
    +                if (graph_op is not None and batch_size == 1 and static_logits.dtype is torch.bfloat16
    +                        and get_accelerator().on_accelerator(static_logits)):
    +                    graph_op.decode_step_graph(static_logits[:, -1, :].contiguous(), static_token.view(batch_size, 1),
    +                                               write_pos, static_attn, full_token_buf)
    +
    +            if graph_op is not None:
    +                # The capture run advanced the GDN conv/recurrent states (its
    +                # forward consumed static_token) and mutated write_pos; without
    +                # this restore every batch size would re-feed the first decode
    +                # token to the GDN layers, double-counting it and derailing the
    +                # whole trajectory at b>1.
    +                restore_gdn_states()
    +                write_pos.fill_(prompt_len)
    +                static_token.copy_(next_token)

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/runtime/rollout/hybrid_engine_rollout.py:1
    @@ -799,51 +879,149 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id,
                     for _ in range(3):
                         out = module(
                             static_token,
    -                        attention_mask=static_attn,
    +                        attention_mask={
    +                            "full_attention": static_attn,
    +                            "linear_attention": None
    +                        },
                             past_key_values=ds_cache,
                             use_cache=True,
    -                        cache_position=static_cache_pos,
    -                        position_ids=static_pos_ids,
                         )
                 get_accelerator().current_stream().wait_stream(s)
    +            restore_gdn_states()
    +
    +            # Capture: full-step graph (forward + argmax + buffer updates).
    +            # The step-update kernel indexes token_buf via write_pos (a GPU
    +            # tensor the kernel itself advances), so no host-side step counter
    +            # is needed — the graph is fully self-contained for replay.
    +            graph_op = None
    +            try:
    +                from deepspeed.ops.module_inject import get_fused_glu_op
    +                candidate = get_fused_glu_op()
    +                if hasattr(candidate, "decode_step_graph"):
    +                    graph_op = candidate
    +            except Exception:
    +                graph_op = None
     
    -            # Capture
                 graph = get_accelerator().create_graph()
                 with get_accelerator().capture_to_graph(graph):
                     out = module(
                         static_token,
    -                    attention_mask=static_attn,
    +                    attention_mask={
    +                        "full_attention": static_attn,
    +                        "linear_attention": None
    +                    },
                         past_key_values=ds_cache,
                         use_cache=True,
    -                    cache_position=static_cache_pos,
    -                    position_ids=static_pos_ids,
                     )
    -            static_logits = out.logits
    +                static_logits = out.logits
    +                # decode_step_graph kernel is b=1 only (single-sequence argmax);
    +                # for b>1 the graph captures forward only and Python handles
    +                # argmax + buffer updates outside the graph. The kernel also
    +                # only accepts CUDA bf16 logits — fp16 models must keep the
    +                # PyTorch argmax path instead of failing during capture.
    +                if (graph_op is not None and batch_size == 1 and static_logits.dtype is torch.bfloat16
    +                        and get_accelerator().on_accelerator(static_logits)):
    +                    graph_op.decode_step_graph(static_logits[:, -1, :].contiguous(), static_token.view(batch_size, 1),
    +                                               write_pos, static_attn, full_token_buf)
    +
    +            if graph_op is not None:
    +                # The capture run advanced the GDN conv/recurrent states (its
    +                # forward consumed static_token) and mutated write_pos; without
    +                # this restore every batch size would re-feed the first decode
    +                # token to the GDN layers, double-counting it and derailing the
    +                # whole trajectory at b>1.
    +                restore_gdn_states()
    +                write_pos.fill_(prompt_len)
    +                static_token.copy_(next_token)
             finally:
                 module._forward_pre_hooks.update(saved_pre)
                 module._forward_hooks.update(saved_post)
     
    -        # --- Decode loop ---
    +        # --- Decode loop: full-step graph (b=1) > graph+Python (b>1) > fallbacks ---
    +        if graph is not None and batch_size > 1:
    +            # Graph forward + Python argmax for b>1: the graph eliminates kernel
    +            # launch overhead for the forward pass; argmax and buffer updates
    +            # stay in Python (PyTorch argmax is batch-native).  The Python
    +            # overhead (~50us/step) is a smaller fraction of the larger GPU
    +            # workload at higher batch.
    +            eos_mask = torch.zeros(batch_size, dtype=torch.bool, device=device)
    +            for step in range(max_new_tokens - 1):
    +                if eos_mask.all():
    +                    output_ids.append(torch.full((batch_size, 1), pad_token_id, dtype=torch.long, device=device))
    +                    continue
    +                static_token.copy_(next_token)
    +                pos = prompt_len + step
    +                write_pos.fill_(pos)
    +                # Reveal only the current token's own slot: the pos+1 slot has
    +                # not been written yet (warmup/capture leftovers), and SDPA at
    +                # b>1 attends every slot the mask reveals.
    +                static_attn[:, :, :, pos] = True
    +                get_accelerator().replay_graph(graph)
    +                next_token = static_logits[:, -1, :].argmax(dim=-1, keepdim=True)
    +                output_ids.append(next_token)
    +                eos_mask |= (next_token.view(batch_size) == eos_token_id)
    +            return torch.cat(output_ids, dim=1)
    +
    +        if graph_op is not None:
    +            # Full-step graph: one replay = forward + argmax + buffer updates.
    +            # Python only does replay + periodic EOS check (every 16 steps).
    +            eos_check_every = 16
    +            for step in range(max_new_tokens - 1):
    +                get_accelerator().replay_graph(graph)

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/runtime/rollout/hybrid_engine_rollout.py:1
    @@ -799,51 +879,149 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id,
                     for _ in range(3):
                         out = module(
                             static_token,
    -                        attention_mask=static_attn,
    +                        attention_mask={
    +                            "full_attention": static_attn,
    +                            "linear_attention": None
    +                        },
                             past_key_values=ds_cache,
                             use_cache=True,
    -                        cache_position=static_cache_pos,
    -                        position_ids=static_pos_ids,
                         )
                 get_accelerator().current_stream().wait_stream(s)
    +            restore_gdn_states()
    +
    +            # Capture: full-step graph (forward + argmax + buffer updates).
    +            # The step-update kernel indexes token_buf via write_pos (a GPU
    +            # tensor the kernel itself advances), so no host-side step counter
    +            # is needed — the graph is fully self-contained for replay.
    +            graph_op = None
    +            try:
    +                from deepspeed.ops.module_inject import get_fused_glu_op
    +                candidate = get_fused_glu_op()
    +                if hasattr(candidate, "decode_step_graph"):
    +                    graph_op = candidate
    +            except Exception:
    +                graph_op = None
     
    -            # Capture
                 graph = get_accelerator().create_graph()
                 with get_accelerator().capture_to_graph(graph):
                     out = module(
                         static_token,
    -                    attention_mask=static_attn,
    +                    attention_mask={
    +                        "full_attention": static_attn,
    +                        "linear_attention": None
    +                    },
                         past_key_values=ds_cache,
                         use_cache=True,
    -                    cache_position=static_cache_pos,
    -                    position_ids=static_pos_ids,
                     )
    -            static_logits = out.logits
    +                static_logits = out.logits
    +                # decode_step_graph kernel is b=1 only (single-sequence argmax);
    +                # for b>1 the graph captures forward only and Python handles
    +                # argmax + buffer updates outside the graph. The kernel also
    +                # only accepts CUDA bf16 logits — fp16 models must keep the
    +                # PyTorch argmax path instead of failing during capture.
    +                if (graph_op is not None and batch_size == 1 and static_logits.dtype is torch.bfloat16
    +                        and get_accelerator().on_accelerator(static_logits)):
    +                    graph_op.decode_step_graph(static_logits[:, -1, :].contiguous(), static_token.view(batch_size, 1),
    +                                               write_pos, static_attn, full_token_buf)
    +
    +            if graph_op is not None:
    +                # The capture run advanced the GDN conv/recurrent states (its
    +                # forward consumed static_token) and mutated write_pos; without
    +                # this restore every batch size would re-feed the first decode
    +                # token to the GDN layers, double-counting it and derailing the
    +                # whole trajectory at b>1.
    +                restore_gdn_states()
    +                write_pos.fill_(prompt_len)
    +                static_token.copy_(next_token)
             finally:
                 module._forward_pre_hooks.update(saved_pre)
                 module._forward_hooks.update(saved_post)
     
    -        # --- Decode loop ---
    +        # --- Decode loop: full-step graph (b=1) > graph+Python (b>1) > fallbacks ---
    +        if graph is not None and batch_size > 1:
    +            # Graph forward + Python argmax for b>1: the graph eliminates kernel
    +            # launch overhead for the forward pass; argmax and buffer updates
    +            # stay in Python (PyTorch argmax is batch-native).  The Python
    +            # overhead (~50us/step) is a smaller fraction of the larger GPU
    +            # workload at higher batch.
    +            eos_mask = torch.zeros(batch_size, dtype=torch.bool, device=device)
    +            for step in range(max_new_tokens - 1):
    +                if eos_mask.all():
    +                    output_ids.append(torch.full((batch_size, 1), pad_token_id, dtype=torch.long, device=device))
    +                    continue
    +                static_token.copy_(next_token)
    +                pos = prompt_len + step
    +                write_pos.fill_(pos)
    +                # Reveal only the current token's own slot: the pos+1 slot has
    +                # not been written yet (warmup/capture leftovers), and SDPA at
    +                # b>1 attends every slot the mask reveals.
    +                static_attn[:, :, :, pos] = True
    +                get_accelerator().replay_graph(graph)
    +                next_token = static_logits[:, -1, :].argmax(dim=-1, keepdim=True)
    +                output_ids.append(next_token)
    +                eos_mask |= (next_token.view(batch_size) == eos_token_id)
    +            return torch.cat(output_ids, dim=1)
    +
    +        if graph_op is not None:
    +            # Full-step graph: one replay = forward + argmax + buffer updates.
    +            # Python only does replay + periodic EOS check (every 16 steps).
    +            eos_check_every = 16
    +            for step in range(max_new_tokens - 1):
    +                get_accelerator().replay_graph(graph)
    +                if step % eos_check_every == eos_check_every - 1:
    +                    tok_val = static_token.view(-1)[0].item()
    +                    if tok_val == eos_token_id:
    +                        full_token_buf[step + 2:] = pad_token_id
    +                        break

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,628 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def _is_silu_activation(act) -> bool:
    +    """True when ``act`` is SiLU as a torch module, the plain function, or
    +    transformers' SiLUActivation wrapper (what Qwen3.5 MLPs carry)."""
    +    if isinstance(act, torch.nn.SiLU):
    +        return True
    +    if act is torch.nn.functional.silu:
    +        return True
    +    return type(act).__name__ == "SiLUActivation"
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        # The fused replacement hardcodes SiLU, while the name-based selector
    +        # also matches GELU-gated families (e.g. Gemma). Only fuse when the
    +        # module's own activation is positively identified as SiLU.
    +        activations = [getattr(module, name, None) for name in ("act_fn", "activation_fn", "activation_func")]
    +        if not any(_is_silu_activation(act) for act in activations if act is not None):
    +            continue
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +def _native_kernel_ready(kernel_op, hidden, *weights) -> bool:
    +    """The CUDA kernels read raw BFloat16 pointers only, so anything else
    +    (fp16 weights, non-contiguous views) must take the composite reference
    +    path instead of raising inside the binding."""
    +    if kernel_op is None:
    +        return False
    +    if not hidden.is_contiguous() or hidden.dtype is not torch.bfloat16:
    +        return False
    +    return all(w.is_contiguous() and w.dtype is torch.bfloat16 for w in weights)
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, gate_w, up_w):
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            # Training activations are [batch, seq, hidden]; .t() only works
    +            # on 2-D, so flatten the leading dims as the GDN backward does.
    +            flat_hidden = hidden.reshape(-1, hidden.shape[-1])
    +            grad_gate_w = torch.matmul(grad_gate_coef.reshape(-1, grad_gate_coef.shape[-1]).t(),
    +                                       flat_hidden).view_as(gate_w)
    +            grad_up_w = torch.matmul(grad_up_coef.reshape(-1, grad_up_coef.shape[-1]).t(), flat_hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, w_qkv, w_z, w_b, w_a):
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,628 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def _is_silu_activation(act) -> bool:
    +    """True when ``act`` is SiLU as a torch module, the plain function, or
    +    transformers' SiLUActivation wrapper (what Qwen3.5 MLPs carry)."""
    +    if isinstance(act, torch.nn.SiLU):
    +        return True
    +    if act is torch.nn.functional.silu:
    +        return True
    +    return type(act).__name__ == "SiLUActivation"
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        # The fused replacement hardcodes SiLU, while the name-based selector
    +        # also matches GELU-gated families (e.g. Gemma). Only fuse when the
    +        # module's own activation is positively identified as SiLU.
    +        activations = [getattr(module, name, None) for name in ("act_fn", "activation_fn", "activation_func")]
    +        if not any(_is_silu_activation(act) for act in activations if act is not None):
    +            continue
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +def _native_kernel_ready(kernel_op, hidden, *weights) -> bool:
    +    """The CUDA kernels read raw BFloat16 pointers only, so anything else
    +    (fp16 weights, non-contiguous views) must take the composite reference
    +    path instead of raising inside the binding."""
    +    if kernel_op is None:
    +        return False
    +    if not hidden.is_contiguous() or hidden.dtype is not torch.bfloat16:
    +        return False
    +    return all(w.is_contiguous() and w.dtype is torch.bfloat16 for w in weights)
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, gate_w, up_w):
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            # Training activations are [batch, seq, hidden]; .t() only works
    +            # on 2-D, so flatten the leading dims as the GDN backward does.
    +            flat_hidden = hidden.reshape(-1, hidden.shape[-1])
    +            grad_gate_w = torch.matmul(grad_gate_coef.reshape(-1, grad_gate_coef.shape[-1]).t(),
    +                                       flat_hidden).view_as(gate_w)
    +            grad_up_w = torch.matmul(grad_up_coef.reshape(-1, grad_up_coef.shape[-1]).t(), flat_hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, w_qkv, w_z, w_b, w_a):
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))
    +
    +
    +@dataclass
    +class GDNSegment:
    +    """A GatedDeltaNet middle segment for hybrid families (e.g. Qwen3.5).
    +
    +    The four input projections share one input and are comm-free under TP, so
    +    they collapse into a single GEMM. Everything from conv1d through the FLA
    +    scan kernel to out_proj is delegated untouched: the ecosystem kernels are
    +    already state of the art and the trailing out_proj is the collective
    +    boundary."""
    +    parent: torch.nn.Module
    +    in_proj_qkv: torch.nn.Module
    +    in_proj_z: torch.nn.Module
    +    in_proj_b: torch.nn.Module
    +    in_proj_a: torch.nn.Module
    +
    +
    +def find_gdn_segments(root: torch.nn.Module) -> List[GDNSegment]:
    +    """Detect GatedDeltaNet blocks by structure (in_proj attribute set)."""
    +    segments = []
    +    names = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
    +    for module, p in _find_fusable_projections(root, names):
    +        segments.append(GDNSegment(parent=module, **{n: p[n] for n in names}))
    +    return segments
    +
    +
    +def _fused_gdn_forward(self, hidden_states, *args, **kwargs):
    +    """GDN block forward with the four input projections fused into one GEMM.
    +
    +    Mirrors the native flow (transformers Qwen3_5GatedDeltaNet.forward) while
    +    delegating conv1d, the delta-rule scan, the gated norm, and the
    +    collective-bearing out_proj to the untouched original submodules."""
    +    from transformers.models.qwen3_5.modeling_qwen3_5 import apply_mask_to_padding_states
    +
    +    # Consume the layer-level kwargs so they cannot leak into the scan call
    +    # (the native forward's named parameters absorb them; ours must too).
    +    attention_mask = kwargs.pop("attention_mask", None)
    +    cache_params = kwargs.pop("cache_params", None) or (args[0] if args else None)
    +    hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
    +
    +    batch_size, seq_len, _ = hidden_states.shape
    +    use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
    +
    +    # Fused [qkv | z | b | a] projection reading the original weights (b=1
    +    # quad_gemv kernel, b>1 on-the-fly concat) — no weight copies.
    +    gdn_kernel_op = getattr(self, "_ki_gdn_op", None)
    +    if batch_size == 1 and seq_len == 1:
    +        fused = GDNInputProj.apply(
    +            hidden_states.squeeze(0).squeeze(0), self.in_proj_qkv.weight, self.in_proj_z.weight, self.in_proj_b.weight,
    +            self.in_proj_a.weight, gdn_kernel_op).view(1, 1, -1)
    +    else:
    +        fused = GDNInputProj.apply(hidden_states, self.in_proj_qkv.weight, self.in_proj_z.weight,
    +                                   self.in_proj_b.weight, self.in_proj_a.weight, gdn_kernel_op)
    +    key_dim, value_dim = self.key_dim, self.value_dim
    +    qkv_end = key_dim * 2 + value_dim
    +    z_end = qkv_end + value_dim
    +    b_end = z_end + self.num_v_heads
    +    # One explicit repack of the qkv slice into the [b, conv_dim, s] layout
    +    # conv1d consumes; handing FLA a non-contiguous view triggers a slower
    +    # multi-op internal path (measured as ~40 extra launches per layer).
    +    mixed_qkv = fused[..., :qkv_end].transpose(1, 2).contiguous()
    +    z = fused[..., qkv_end:z_end].reshape(batch_size, seq_len, -1, self.head_v_dim)
    +    b = fused[..., z_end:b_end]
    +    a = fused[..., b_end:]
    +
    +    if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past:
    +        conv_state = cache_params.layers[self.layer_idx].conv_states[0]
    +        mixed_qkv = self._ki_gdn_conv_update(mixed_qkv, conv_state)
    +    else:
    +        if cache_params is not None:
    +            mixed_qkv = cache_params.update_conv_state(mixed_qkv,
    +                                                       self.layer_idx,
    +                                                       conv_kernel_size=self.conv_kernel_size)
    +        mixed_qkv = self._ki_gdn_conv_fn(mixed_qkv, **kwargs)
    +        if cache_params is not None:
    +            mixed_qkv = mixed_qkv[:, :, -seq_len:]
    +
    +    mixed_qkv = mixed_qkv.transpose(1, 2)
    +    query, key, value = torch.split(mixed_qkv, [key_dim, key_dim, value_dim], dim=-1)
    +    query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
    +
    +    gdn_op = getattr(self, "_ki_gdn_op", None)
    +    from deepspeed.accelerator import get_accelerator
    +    if gdn_op is not None and get_accelerator().on_accelerator(a):
    +        a_log_f = self.A_log.detach().float().contiguous()
    +        dt_f = self.dt_bias.detach().float().contiguous()
    +        # gdn_gates accepts row-strided a/b, so the fused-output slices go in
    +        # without contiguous copies.
    +        beta, g = gdn_op.gdn_gates(a, b, a_log_f, dt_f)
    +    else:
    +        beta = b.sigmoid()
    +        g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
    +    if self.num_v_heads // self.num_k_heads > 1:
    +        query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +        key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +
    +    recurrent_state = cache_params.layers[self.layer_idx].recurrent_states[0] if use_precomputed_states else None
    +    # Whitelist the scan inputs: transformers threads unrelated layer kwargs
    +    # (use_cache, cache_position, ...) down to every block and the fused
    +    # kernel signatures reject unknown names.
    +    scan_kwargs = dict(g=g,
    +                       beta=beta,
    +                       initial_state=recurrent_state,
    +                       output_final_state=cache_params is not None,
    +                       use_qk_l2norm_in_kernel=True)
    +    cu_seqlens = kwargs.get("cu_seq_lens_q") or kwargs.get("cu_seqlens")
    +    if cu_seqlens is not None:
    +        scan_kwargs["cu_seqlens"] = cu_seqlens
    +    core_attn_out, last_recurrent_state = self._ki_gdn_scan(query, key, value, **scan_kwargs)
    +    if cache_params is not None:
    +        cache_params.update_recurrent_state(last_recurrent_state, self.layer_idx)
    +
    +    core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
    +    z = z.reshape(-1, self.head_v_dim)
    +    core_attn_out = self.norm(core_attn_out, z)
    +    core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
    +    return self.out_proj(core_attn_out)
    +
    +
    +def _install_gdn_segment(seg: GDNSegment) -> bool:
    +    """Wire the fused forward onto a GDN block, binding its original helpers.
    +
    +    The conv/scan callables are captured from the transformers module so the
    +    replacement keeps using the exact kernels (FLA/causal-conv1d paths and
    +    their cache contracts) that the native forward would have selected."""
    +    import transformers.models.qwen3_5.modeling_qwen3_5 as m5
    +
    +    conv_update = getattr(m5, "causal_conv1d_update", None)
    +    conv_fn = getattr(m5, "causal_conv1d_fn", None)
    +    if conv_update is None or conv_fn is None:
    +        return False
    +
    +    parent = seg.parent
    +
    +    def conv_update_with_weights(mixed_qkv, conv_state):
    +        return conv_update(mixed_qkv, conv_state, parent.conv1d.weight.squeeze(1), parent.conv1d.bias,
    +                           parent.activation)
    +
    +    def conv_fn_with_weights(mixed_qkv, **kw):
    +        # causal_conv1d_fn does not accept HF generation kwargs; filter them
    +        # the same way the scan closure does.
    +        kw.pop("use_cache", None)
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        return conv_fn(mixed_qkv,
    +                       parent.conv1d.weight.squeeze(1),
    +                       parent.conv1d.bias,
    +                       activation=parent.activation,
    +                       **kw)
    +
    +    def scan(query, key, value, **kw):
    +        # Route through the block's own instance-bound kernels: transformers
    +        # binds the FLA fused implementations onto the module when available
    +        # (recurrent_gated_delta_rule/chunk_gated_delta_rule) and only falls
    +        # back to the pure-torch references otherwise. Calling the module-level
    +        # torch_* functions directly forces the slow fallback on every layer.
    +        single = kw.get("initial_state") is not None and query.shape[1] == 1
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        fn = parent.recurrent_gated_delta_rule if single else parent.chunk_gated_delta_rule
    +        return fn(query, key, value, **kw)
    +
    +    kernel_op = None
    +    try:
    +        from deepspeed.accelerator import get_accelerator
    +        if get_accelerator().device_name() != "cpu":
    +            from deepspeed.ops.module_inject import get_fused_glu_op
    +            kernel_op = get_fused_glu_op()
    +    except Exception:
    +        kernel_op = None
    +    parent._ki_gdn_op = kernel_op
    +    parent._ki_gdn_conv_update = conv_update_with_weights
    +    parent._ki_gdn_conv_fn = conv_fn_with_weights
    +    parent._ki_gdn_scan = scan
    +    parent.forward = _fused_gdn_forward.__get__(parent, type(parent))
    +    return True
    +
    +
    +def apply_segment_ki(model: torch.nn.Module) -> dict:
    +    """Install segment kernels on ``model`` (post-AutoTP, pre-generate).
    +
    +    Uses the native CUDA op when a non-cpu accelerator backend is active;
    +    falls back to the torch composite reference otherwise.
    +
    +    Returns a small report so callers (tests, journals) can assert what was
    +    found and replaced without introspecting the module tree again.
    +    """
    +    kernel_op = None
    +    from deepspeed.accelerator import get_accelerator
    +    if get_accelerator().device_name() != "cpu":
    +        from deepspeed.ops.module_inject import get_fused_glu_op
    +        kernel_op = get_fused_glu_op()

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/module_inject/segment_ki.py:1
    @@ -0,0 +1,628 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""Segment-style kernel injection (KI) prototype.
    +
    +Architecture contract (see experiments/segment-ki-proto.md):
    +
    +1. The sharding plane (AutoTP) is the sole owner of tensor-parallel structure.
    +   This module never shards, gathers, or re-partitions weights; it only
    +   consumes what AutoTP already produced.
    +2. Kernel replacement happens strictly inside comm-free segments: a segment is
    +   a contiguous run of submodules whose forwards execute no collectives. Any
    +   module whose forward carries a collective (e.g. ``*Allreduce`` layers) is a
    +   hard segment boundary and is left untouched.
    +3. Weight-layout transforms (e.g. fusing gate/up shards) happen per shard and
    +   are legal only because both projections are column-parallel with the same
    +   input: concatenating along the output dim inside one shard never crosses a
    +   shard boundary.
    +4. Module protocols (return types, HF Cache updates) stay native: this module
    +   swaps computation, not the surrounding HF module contracts.
    +
    +This prototype implements one kernel: ``fused_glu`` (gate+up GEMM merge with
    +SiLU-mul), applied to structurally-detected gated MLPs. Detection is by
    +structure (attribute names + collective markers), not by HF class names, so
    +the same pattern serves every family that lays out its MLP as
    +gate_proj/up_proj/down_proj.
    +"""
    +
    +import os
    +from dataclasses import dataclass
    +from typing import List
    +
    +import torch
    +import torch.nn.functional as F
    +
    +# AutoTP layer classes whose forward performs an output all-reduce. These are
    +# the canonical segment boundaries. Importing layers lazily keeps this module
    +# importable in builds without AutoTP materialized.
    +from deepspeed.module_inject.layers import LinearAllreduce, SubParamLinearAllreduce
    +
    +# Only list base classes here — isinstance() covers all subclasses
    +# automatically (e.g., Yuan_LinearAllreduce and Conv_LinearALlreduce are
    +# caught via LinearAllreduce). Do not add subclasses to this tuple.
    +_ALLREDUCE_LAYERS = (LinearAllreduce, SubParamLinearAllreduce)
    +
    +
    +def carries_collective(module: torch.nn.Module) -> bool:
    +    """True if the module's own forward executes a collective."""
    +    return isinstance(module, _ALLREDUCE_LAYERS)
    +
    +
    +@dataclass
    +class GLUSegment:
    +    """A gated-MLP segment: gate/up are comm-free projections, down is the
    +    collective-bearing boundary that must be delegated to untouched."""
    +    parent: torch.nn.Module
    +    gate: torch.nn.Module
    +    up: torch.nn.Module
    +    down: torch.nn.Module
    +
    +
    +def _find_fusable_projections(root: torch.nn.Module, attr_names: tuple) -> dict:
    +    """Yield (module, projections_dict) for each module under ``root`` whose
    +    named projections are all plain, bias-free, comm-free nn.Linear.
    +
    +    Rejecting non-Linear types guards against AutoTP sharded wrappers:
    +    fusing across a shard/full-layout mismatch needs shard-aware slicing,
    +    which is out of scope.
    +    """
    +    for module in root.modules():
    +        projections = {name: getattr(module, name, None) for name in attr_names}
    +        if not all(isinstance(p, torch.nn.Linear) for p in projections.values()):
    +            continue
    +        if any(p.bias is not None for p in projections.values()):
    +            continue
    +        if any(carries_collective(p) for p in projections.values()):
    +            continue
    +        yield module, projections
    +
    +
    +def _is_silu_activation(act) -> bool:
    +    """True when ``act`` is SiLU as a torch module, the plain function, or
    +    transformers' SiLUActivation wrapper (what Qwen3.5 MLPs carry)."""
    +    if isinstance(act, torch.nn.SiLU):
    +        return True
    +    if act is torch.nn.functional.silu:
    +        return True
    +    return type(act).__name__ == "SiLUActivation"
    +
    +
    +def find_glu_segments(root: torch.nn.Module) -> List[GLUSegment]:
    +    """Detect gated MLPs by structure (gate_proj/up_proj/down_proj attribute set)."""
    +    segments = []
    +    for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj", "down_proj")):
    +        # The fused replacement hardcodes SiLU, while the name-based selector
    +        # also matches GELU-gated families (e.g. Gemma). Only fuse when the
    +        # module's own activation is positively identified as SiLU.
    +        activations = [getattr(module, name, None) for name in ("act_fn", "activation_fn", "activation_func")]
    +        if not any(_is_silu_activation(act) for act in activations if act is not None):
    +            continue
    +        segments.append(GLUSegment(parent=module, gate=p["gate_proj"], up=p["up_proj"], down=p["down_proj"]))
    +    return segments
    +
    +
    +def _native_kernel_ready(kernel_op, hidden, *weights) -> bool:
    +    """The CUDA kernels read raw BFloat16 pointers only, so anything else
    +    (fp16 weights, non-contiguous views) must take the composite reference
    +    path instead of raising inside the binding."""
    +    if kernel_op is None:
    +        return False
    +    if not hidden.is_contiguous() or hidden.dtype is not torch.bfloat16:
    +        return False
    +    return all(w.is_contiguous() and w.dtype is torch.bfloat16 for w in weights)
    +
    +
    +class DualWeightGluGEMV(torch.autograd.Function):
    +    """silu(hidden @ gate_w.T) * (hidden @ up_w.T) reading weights directly.
    +
    +    Forward (b=1): fused kernel (one warp per output feature, coalesced
    +    reads from both weight matrices, fp32 accumulation).
    +    Forward (b>1): two GEMMs + elementwise activation.
    +    Backward: standard PyTorch ops — gradients flow to the
    +    original gate.weight / up.weight Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, gate_w, up_w, kernel_op):
    +        ctx.save_for_backward(hidden, gate_w, up_w)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, gate_w, up_w):
    +            out = torch.empty(gate_w.shape[0], dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.dual_gemv_silu_mul(hidden, gate_w, up_w, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul
    +        return dual_gemv_silu_mul(hidden, gate_w, up_w)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, gate_w, up_w = ctx.saved_tensors
    +        gate_out = torch.matmul(hidden, gate_w.t())
    +        up_out = torch.matmul(hidden, up_w.t())
    +        sig = torch.sigmoid(gate_out)
    +        silu_prime = sig * (1.0 + gate_out * (1.0 - sig))
    +        grad_gate_coef = silu_prime * up_out * grad_out
    +        grad_up_coef = (gate_out * sig) * grad_out
    +        if hidden.dim() == 1:
    +            grad_gate_w = torch.outer(grad_gate_coef, hidden).view_as(gate_w)
    +            grad_up_w = torch.outer(grad_up_coef, hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        else:
    +            # Training activations are [batch, seq, hidden]; .t() only works
    +            # on 2-D, so flatten the leading dims as the GDN backward does.
    +            flat_hidden = hidden.reshape(-1, hidden.shape[-1])
    +            grad_gate_w = torch.matmul(grad_gate_coef.reshape(-1, grad_gate_coef.shape[-1]).t(),
    +                                       flat_hidden).view_as(gate_w)
    +            grad_up_w = torch.matmul(grad_up_coef.reshape(-1, grad_up_coef.shape[-1]).t(), flat_hidden).view_as(up_w)
    +            grad_hidden = torch.matmul(grad_gate_coef, gate_w) + torch.matmul(grad_up_coef, up_w)
    +        return grad_hidden, grad_gate_w, grad_up_w, None
    +
    +
    +class GDNInputProj(torch.autograd.Function):
    +    """GDN input projections (qkv|z|b|a) reading the four original weights.
    +
    +    Forward (b=1): quad_gemv kernel — one warp per output row across all
    +    four weight matrices, no concatenation.
    +    Forward (b>1): four GEMMs concatenated on the fly.
    +    Backward: standard PyTorch ops — gradients flow to the original
    +    in_proj_qkv/z/b/a Parameters.
    +    """
    +
    +    @staticmethod
    +    def forward(ctx, hidden, w_qkv, w_z, w_b, w_a, kernel_op):
    +        ctx.save_for_backward(hidden, w_qkv, w_z, w_b, w_a)
    +        if hidden.dim() == 1 and _native_kernel_ready(kernel_op, hidden, w_qkv, w_z, w_b, w_a):
    +            total = w_qkv.shape[0] + w_z.shape[0] + w_b.shape[0] + w_a.shape[0]
    +            out = torch.empty(total, dtype=hidden.dtype, device=hidden.device)
    +            kernel_op.quad_gemv(hidden, w_qkv, w_z, w_b, w_a, out)
    +            return out
    +        from deepspeed.module_inject.kernel_reference import gdn_input_proj
    +        return gdn_input_proj(hidden, w_qkv, w_z, w_b, w_a)
    +
    +    @staticmethod
    +    def backward(ctx, grad_out):
    +        hidden, w_qkv, w_z, w_b, w_a = ctx.saved_tensors
    +        rows = (w_qkv.shape[0], w_z.shape[0], w_b.shape[0], w_a.shape[0])
    +        # Slice grad_out back per weight, then standard GEMM backward.
    +        g0 = grad_out[..., :rows[0]]
    +        g1 = grad_out[..., rows[0]:rows[0] + rows[1]]
    +        g2 = grad_out[..., rows[0] + rows[1]:rows[0] + rows[1] + rows[2]]
    +        g3 = grad_out[..., rows[0] + rows[1] + rows[2]:]
    +        if hidden.dim() == 1:
    +            grads_w = tuple(
    +                torch.outer(g, hidden).view_as(w) for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        else:
    +            flat = hidden.reshape(-1, hidden.shape[-1])
    +            grads_w = tuple(
    +                torch.matmul(g.reshape(-1, g.shape[-1]).t(), flat).view_as(w)
    +                for g, w in ((g0, w_qkv), (g1, w_z), (g2, w_b), (g3, w_a)))
    +            grad_hidden = (torch.matmul(g0, w_qkv) + torch.matmul(g1, w_z) + torch.matmul(g2, w_b) +
    +                           torch.matmul(g3, w_a))
    +        return (grad_hidden, ) + grads_w + (None, )
    +
    +
    +def _dual_weight_glu_forward(self, input):
    +    """Replacement forward: reads gate_proj.weight and up_proj.weight
    +    directly (zero copies).  b=1 uses the fused dual-weight GEMV kernel;
    +    b>1 falls through to the original projections.  Gradients flow to the
    +    original Parameters through autograd.Function — train and generate share
    +    the same path with no forward switching."""
    +    if input.shape[0] == 1 and input.dim() == 2 and getattr(self, "_ki_dual_op", None) is not None:
    +        out = DualWeightGluGEMV.apply(input.squeeze(0), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op)
    +        return self.down_proj(out.unsqueeze(0))
    +    # b>1 or no kernel: original forward (gradients also correct here)
    +    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))
    +
    +
    +@dataclass
    +class GDNSegment:
    +    """A GatedDeltaNet middle segment for hybrid families (e.g. Qwen3.5).
    +
    +    The four input projections share one input and are comm-free under TP, so
    +    they collapse into a single GEMM. Everything from conv1d through the FLA
    +    scan kernel to out_proj is delegated untouched: the ecosystem kernels are
    +    already state of the art and the trailing out_proj is the collective
    +    boundary."""
    +    parent: torch.nn.Module
    +    in_proj_qkv: torch.nn.Module
    +    in_proj_z: torch.nn.Module
    +    in_proj_b: torch.nn.Module
    +    in_proj_a: torch.nn.Module
    +
    +
    +def find_gdn_segments(root: torch.nn.Module) -> List[GDNSegment]:
    +    """Detect GatedDeltaNet blocks by structure (in_proj attribute set)."""
    +    segments = []
    +    names = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")
    +    for module, p in _find_fusable_projections(root, names):
    +        segments.append(GDNSegment(parent=module, **{n: p[n] for n in names}))
    +    return segments
    +
    +
    +def _fused_gdn_forward(self, hidden_states, *args, **kwargs):
    +    """GDN block forward with the four input projections fused into one GEMM.
    +
    +    Mirrors the native flow (transformers Qwen3_5GatedDeltaNet.forward) while
    +    delegating conv1d, the delta-rule scan, the gated norm, and the
    +    collective-bearing out_proj to the untouched original submodules."""
    +    from transformers.models.qwen3_5.modeling_qwen3_5 import apply_mask_to_padding_states
    +
    +    # Consume the layer-level kwargs so they cannot leak into the scan call
    +    # (the native forward's named parameters absorb them; ours must too).
    +    attention_mask = kwargs.pop("attention_mask", None)
    +    cache_params = kwargs.pop("cache_params", None) or (args[0] if args else None)
    +    hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
    +
    +    batch_size, seq_len, _ = hidden_states.shape
    +    use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
    +
    +    # Fused [qkv | z | b | a] projection reading the original weights (b=1
    +    # quad_gemv kernel, b>1 on-the-fly concat) — no weight copies.
    +    gdn_kernel_op = getattr(self, "_ki_gdn_op", None)
    +    if batch_size == 1 and seq_len == 1:
    +        fused = GDNInputProj.apply(
    +            hidden_states.squeeze(0).squeeze(0), self.in_proj_qkv.weight, self.in_proj_z.weight, self.in_proj_b.weight,
    +            self.in_proj_a.weight, gdn_kernel_op).view(1, 1, -1)
    +    else:
    +        fused = GDNInputProj.apply(hidden_states, self.in_proj_qkv.weight, self.in_proj_z.weight,
    +                                   self.in_proj_b.weight, self.in_proj_a.weight, gdn_kernel_op)
    +    key_dim, value_dim = self.key_dim, self.value_dim
    +    qkv_end = key_dim * 2 + value_dim
    +    z_end = qkv_end + value_dim
    +    b_end = z_end + self.num_v_heads
    +    # One explicit repack of the qkv slice into the [b, conv_dim, s] layout
    +    # conv1d consumes; handing FLA a non-contiguous view triggers a slower
    +    # multi-op internal path (measured as ~40 extra launches per layer).
    +    mixed_qkv = fused[..., :qkv_end].transpose(1, 2).contiguous()
    +    z = fused[..., qkv_end:z_end].reshape(batch_size, seq_len, -1, self.head_v_dim)
    +    b = fused[..., z_end:b_end]
    +    a = fused[..., b_end:]
    +
    +    if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past:
    +        conv_state = cache_params.layers[self.layer_idx].conv_states[0]
    +        mixed_qkv = self._ki_gdn_conv_update(mixed_qkv, conv_state)
    +    else:
    +        if cache_params is not None:
    +            mixed_qkv = cache_params.update_conv_state(mixed_qkv,
    +                                                       self.layer_idx,
    +                                                       conv_kernel_size=self.conv_kernel_size)
    +        mixed_qkv = self._ki_gdn_conv_fn(mixed_qkv, **kwargs)
    +        if cache_params is not None:
    +            mixed_qkv = mixed_qkv[:, :, -seq_len:]
    +
    +    mixed_qkv = mixed_qkv.transpose(1, 2)
    +    query, key, value = torch.split(mixed_qkv, [key_dim, key_dim, value_dim], dim=-1)
    +    query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
    +    value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
    +
    +    gdn_op = getattr(self, "_ki_gdn_op", None)
    +    from deepspeed.accelerator import get_accelerator
    +    if gdn_op is not None and get_accelerator().on_accelerator(a):
    +        a_log_f = self.A_log.detach().float().contiguous()
    +        dt_f = self.dt_bias.detach().float().contiguous()
    +        # gdn_gates accepts row-strided a/b, so the fused-output slices go in
    +        # without contiguous copies.
    +        beta, g = gdn_op.gdn_gates(a, b, a_log_f, dt_f)
    +    else:
    +        beta = b.sigmoid()
    +        g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
    +    if self.num_v_heads // self.num_k_heads > 1:
    +        query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +        key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
    +
    +    recurrent_state = cache_params.layers[self.layer_idx].recurrent_states[0] if use_precomputed_states else None
    +    # Whitelist the scan inputs: transformers threads unrelated layer kwargs
    +    # (use_cache, cache_position, ...) down to every block and the fused
    +    # kernel signatures reject unknown names.
    +    scan_kwargs = dict(g=g,
    +                       beta=beta,
    +                       initial_state=recurrent_state,
    +                       output_final_state=cache_params is not None,
    +                       use_qk_l2norm_in_kernel=True)
    +    cu_seqlens = kwargs.get("cu_seq_lens_q") or kwargs.get("cu_seqlens")
    +    if cu_seqlens is not None:
    +        scan_kwargs["cu_seqlens"] = cu_seqlens
    +    core_attn_out, last_recurrent_state = self._ki_gdn_scan(query, key, value, **scan_kwargs)
    +    if cache_params is not None:
    +        cache_params.update_recurrent_state(last_recurrent_state, self.layer_idx)
    +
    +    core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
    +    z = z.reshape(-1, self.head_v_dim)
    +    core_attn_out = self.norm(core_attn_out, z)
    +    core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
    +    return self.out_proj(core_attn_out)
    +
    +
    +def _install_gdn_segment(seg: GDNSegment) -> bool:
    +    """Wire the fused forward onto a GDN block, binding its original helpers.
    +
    +    The conv/scan callables are captured from the transformers module so the
    +    replacement keeps using the exact kernels (FLA/causal-conv1d paths and
    +    their cache contracts) that the native forward would have selected."""
    +    import transformers.models.qwen3_5.modeling_qwen3_5 as m5
    +
    +    conv_update = getattr(m5, "causal_conv1d_update", None)
    +    conv_fn = getattr(m5, "causal_conv1d_fn", None)
    +    if conv_update is None or conv_fn is None:
    +        return False
    +
    +    parent = seg.parent
    +
    +    def conv_update_with_weights(mixed_qkv, conv_state):
    +        return conv_update(mixed_qkv, conv_state, parent.conv1d.weight.squeeze(1), parent.conv1d.bias,
    +                           parent.activation)
    +
    +    def conv_fn_with_weights(mixed_qkv, **kw):
    +        # causal_conv1d_fn does not accept HF generation kwargs; filter them
    +        # the same way the scan closure does.
    +        kw.pop("use_cache", None)
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        return conv_fn(mixed_qkv,
    +                       parent.conv1d.weight.squeeze(1),
    +                       parent.conv1d.bias,
    +                       activation=parent.activation,
    +                       **kw)
    +
    +    def scan(query, key, value, **kw):
    +        # Route through the block's own instance-bound kernels: transformers
    +        # binds the FLA fused implementations onto the module when available
    +        # (recurrent_gated_delta_rule/chunk_gated_delta_rule) and only falls
    +        # back to the pure-torch references otherwise. Calling the module-level
    +        # torch_* functions directly forces the slow fallback on every layer.
    +        single = kw.get("initial_state") is not None and query.shape[1] == 1
    +        kw.pop("cu_seqlens", None)
    +        kw.pop("cu_seq_lens_q", None)
    +        fn = parent.recurrent_gated_delta_rule if single else parent.chunk_gated_delta_rule
    +        return fn(query, key, value, **kw)
    +
    +    kernel_op = None
    +    try:
    +        from deepspeed.accelerator import get_accelerator
    +        if get_accelerator().device_name() != "cpu":
    +            from deepspeed.ops.module_inject import get_fused_glu_op
    +            kernel_op = get_fused_glu_op()
    +    except Exception:
    +        kernel_op = None
    +    parent._ki_gdn_op = kernel_op
    +    parent._ki_gdn_conv_update = conv_update_with_weights
    +    parent._ki_gdn_conv_fn = conv_fn_with_weights
    +    parent._ki_gdn_scan = scan
    +    parent.forward = _fused_gdn_forward.__get__(parent, type(parent))
    +    return True
    +
    +
    +def apply_segment_ki(model: torch.nn.Module) -> dict:
    +    """Install segment kernels on ``model`` (post-AutoTP, pre-generate).
    +
    +    Uses the native CUDA op when a non-cpu accelerator backend is active;
    +    falls back to the torch composite reference otherwise.
    +
    +    Returns a small report so callers (tests, journals) can assert what was
    +    found and replaced without introspecting the module tree again.
    +    """
    +    kernel_op = None
    +    from deepspeed.accelerator import get_accelerator
    +    if get_accelerator().device_name() != "cpu":
    +        from deepspeed.ops.module_inject import get_fused_glu_op
    +        kernel_op = get_fused_glu_op()
    +
    +    report = {"backend": "cuda" if kernel_op is not None else "composite"}
    +
    +    segments = find_glu_segments(model)
    +    replaced = 0
    +    for seg in segments:
    +        seg.parent._ki_dual_op = kernel_op if kernel_op is not None and hasattr(kernel_op,
    +                                                                                "dual_gemv_silu_mul") else None
    +        seg.parent.forward = _dual_weight_glu_forward.__get__(seg.parent, type(seg.parent))
    +        replaced += 1
    +    report["fused_glu"] = {"segments_found": len(segments), "segments_replaced": replaced}
    +
    +    gdn_segments = find_gdn_segments(model)
    +    gdn_replaced = sum(1 for seg in gdn_segments if _install_gdn_segment(seg))
    +    report["fused_gdn"] = {"segments_found": len(gdn_segments), "segments_replaced": gdn_replaced}
    +
    +    return report
    +
    +
    +# ─── Custom b=1 decode attention: replace SDPA in full-attention layers ───
    +
    +
    +def _decode_attn_forward(self,
    +                         hidden_states,
    +                         position_embeddings=None,
    +                         attention_mask=None,
    +                         past_key_values=None,
    +                         **kwargs):
    +    """Replacement forward for full-attention layers: run the custom
    +    decode_attn kernel at b=1, seq_len=1 instead of SDPA-with-mask (which
    +    falls into the slow mem_efficient backend against the full-width static
    +    cache buffer).
    +
    +    Everything except the attention core is a verbatim replay of the HF
    +    forward (q_proj 2x-wide gate split, per-head q/k norms, RoPE, KV cache
    +    update, gate multiply, o_proj), so numerics match the original path.
    +    The kernel reads the valid KV length from the same GPU-resident
    +    write_pos tensor the cache update writes through, keeping the whole
    +    step CUDA-graph replayable."""
    +    if (hidden_states.shape[0] != 1 or hidden_states.shape[1] > 1 or past_key_values is None
    +            or getattr(self, "_ki_attn_op", None) is None
    +            or getattr(past_key_values, "_write_position", None) is not self._ki_write_pos):

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/ops/module_inject/decode_loop.py:1
    @@ -0,0 +1,31 @@
    +# SPDX-License-Identifier: Apache-2.0
    +
    +# DeepSpeed Team
    +"""op_builder module for the C++ decode loop (graph replay + step update)."""
    +
    +from ..op_builder.builder import CUDAOpBuilder
    +
    +
    +class DecodeLoopBuilder(CUDAOpBuilder):
    +    BUILD_VAR = "DS_BUILD_DECODE_LOOP"
    +    NAME = "decode_loop"

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    deepspeed/ops/module_inject/fused_glu.py:1
    @@ -0,0 +1,30 @@
    +# SPDX-License-Identifier: Apache-2.0
    +# DeepSpeed Team
    +"""op_builder for the segment-KI fused_glu native CUDA kernel."""
    +
    +from ..op_builder.builder import CUDAOpBuilder
    +
    +
    +class FusedGLUBuilder(CUDAOpBuilder):
    +    BUILD_VAR = "DS_BUILD_FUSED_GLU"
    +    NAME = "fused_glu"

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    tests/unit/module_inject/test_segment_ki_kernels.py:1
    @@ -0,0 +1,260 @@
    +# SPDX-License-Identifier: Apache-2.0
    +# DeepSpeed Team
    +"""Contract tests for segment-KI kernels and rollout co-location.
    +
    +Three groups:
    +
    +1. Kernel vs reference consistency (GPU): every fused_glu CUDA kernel must
    +   match its pure-PyTorch specification in kernel_reference.py within bf16
    +   tolerance on identical inputs.  A regression here catches numerical
    +   drift in any kernel rewrite.
    +2. Composite paths and injection invariants (CPU): the autograd.Function
    +   fallbacks and apply_segment_ki must work without a GPU, and injection
    +   must not materialize weight copies.
    +3. Rollout -> train -> rollout integration (GPU, gated on model
    +   availability): the RL-loop contract — generate, take one optimizer
    +   step through the injected model, generate again, and observe different
    +   output — with no inject/eject/sync calls anywhere in between.
    +"""
    +
    +import os
    +
    +import pytest
    +import torch
    +
    +from deepspeed.accelerator import get_accelerator
    +
    +from deepspeed.module_inject.kernel_reference import decode_attn as ref_decode_attn
    +from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul as ref_dual_gemv
    +from deepspeed.module_inject.kernel_reference import fused_add_norm as ref_add_norm
    +from deepspeed.module_inject.kernel_reference import gdn_gates as ref_gdn_gates
    +from deepspeed.module_inject.kernel_reference import gdn_input_proj as ref_gdn_proj
    +from deepspeed.module_inject.kernel_reference import triple_gemv as ref_triple_gemv
    +
    +DEV = get_accelerator().device_name()
    +GPU_AVAILABLE = DEV != "cpu"

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    csrc/module_inject/decode_loop.cu:1
    @@ -0,0 +1,163 @@
    +// SPDX-License-Identifier: Apache-2.0
    +// DeepSpeed Team
    +
    +// C++ decode loop: runs the full generation loop in a single C++ call.
    +// The replay callable is a std::function<void()> — it can wrap a CUDA
    +// graph replay, a SYCL submission, an eager PyTorch forward, or any
    +// backend-specific mechanism. The C++ loop is agnostic to the backend.
    +//
    +// Per-step overhead: replay_fn() ≈ 2-5μs (pybind11 dispatch)
    +// vs Python for-loop ≈ 30-50μs.
    +// The fused step-update kernel launch is pure C++ (zero Python).
    +
    +#include <ATen/cuda/CUDAContext.h>
    +#include <cuda_runtime.h>
    +#include <torch/extension.h>
    +#include <functional>
    +
    +__global__ void ds_loop_step_kernel(const __nv_bfloat16* __restrict__ logits,
    +                                    int64_t* __restrict__ token_out,
    +                                    int64_t* __restrict__ write_pos,
    +                                    bool* __restrict__ mask,
    +                                    int64_t* __restrict__ out_buf,
    +                                    int step,
    +                                    int vocab_size,
    +                                    int max_len)
    +{
    +    __shared__ int s_idx[1024];
    +    __shared__ float s_val[1024];
    +
    +    int tid = threadIdx.x;
    +    int local_idx = 0;
    +    float local_val = -INFINITY;
    +
    +    for (int v = tid; v < vocab_size; v += blockDim.x) {
    +        float val = __bfloat162float(logits[v]);
    +        if (val > local_val) {
    +            local_val = val;
    +            local_idx = v;
    +        }
    +    }
    +    s_idx[tid] = local_idx;
    +    s_val[tid] = local_val;
    +    __syncthreads();
    +
    +    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
    +        if (tid < stride) {
    +            if (s_val[tid + stride] > s_val[tid]) {
    +                s_val[tid] = s_val[tid + stride];
    +                s_idx[tid] = s_idx[tid + stride];
    +            }
    +        }
    +        __syncthreads();
    +    }
    +
    +    if (tid == 0) {
    +        int64_t best = (int64_t)s_idx[0];
    +        token_out[0] = best;
    +        out_buf[step] = best;
    +        int64_t new_pos = write_pos[0] + 1;
    +        write_pos[0] = new_pos;
    +        // new_pos is the slot the token just written occupies during the
    +        // next replay; revealing new_pos+1 masks the current slot for
    +        // layers still on native SDPA.
    +        if (new_pos < max_len) { mask[new_pos] = true; }
    +    }
    +}
    +
    +// Fills buf[from, len) with pad on the device — used after an early EOS exit.
    +__global__ void pad_tail_kernel(int64_t* __restrict__ buf, int64_t from, int64_t len, int64_t pad)
    +{
    +    int64_t i = from + (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
    +    if (i < len) { buf[i] = pad; }
    +}
    +
    +int64_t ds_decode_loop(std::function<void()> replay_fn,
    +                       at::Tensor logits,
    +                       at::Tensor token_out,
    +                       at::Tensor write_pos,
    +                       at::Tensor mask,
    +                       at::Tensor out_buf,
    +                       int64_t max_steps,
    +                       int64_t eos_token_id,
    +                       int64_t pad_token_id,
    +                       int64_t eos_check_every)

    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.

    Copilot Copilot commented on code on Sep 28, 2026 22:00 UTC
    Code Review
    docs/code-docs/source/inference-engine.rst:1
    @@ -74,6 +74,28 @@ one token. It cannot be combined with CUDA graph capture or
     ``release_inference_cache``. Sampling still happens independently for every
     response branch after the shared prompt forward.
     
    +Segment-Based Kernel Injection (experimental)
    +---------------------------------------------
    +
    +``HybridEngineRolloutConfig(use_segki=True)`` accelerates greedy decode by
    +injecting native CUDA kernels into comm-free segments of the model at rollout
    +construction. Segments are detected structurally, by attribute names, so 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. Unsupported

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Sep 28, 2026 22:00 UTC
    Reviewer

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

  • <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> [Missing CUDA bf16 and pybind functional headers](#discussion_r4127430296) · New

  • <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> [Native gdn_gates path cuts off training gradients](#discussion_r4127430358) · New

  • <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> [Tensor truth-value check breaks packed-sequence calls](#discussion_r4127430391) · New

  • <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> [Custom attention ignores padding masks](#discussion_r4127430421) · New

  • <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> [Fused add-norm loses gradients during training](#discussion_r4127430458) · New

  • <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> [Unbound GDN slots are skipped without state initialization](#discussion_r4127430490) · New

  • <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> [Prompt attention mask is dropped during prefill](#discussion_r4127430518) · New

  • <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> [Fallback graph reuses already-consumed recurrent state](#discussion_r4127430542) · New

  • <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> [Forward-only graph replay uses uncaptured token buffers](#discussion_r4127430571) · New

  • <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> [EOS padding slice ignores prompt-length offset](#discussion_r4127430619) · New

  • <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> [Dual-GEMV excludes normal 3D greedy-decode inputs](#discussion_r4127430669) · New

  • <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> [Non-CUDA backends incorrectly load CUDA builder](#discussion_r4127430701) · New

  • <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> [FP16 models incorrectly enter bf16-only decode kernels](#discussion_r4127430733) · New

  • <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> [Decode loop builder is not registered for wheel builds](#discussion_r4127430774) · New

  • <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> [Fused GLU builder is not registered for wheel builds](#discussion_r4127430812) · New

  • <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> [CUDA-only tests run on unsupported accelerators](#discussion_r4127430850) · New

  • <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> [Missing direct coverage for native decode fallback](#discussion_r4127430881) · New

  • <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> [Gemma is documented as supported despite GELU rejection](#discussion_r4127430923) · New

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

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

    delock delock commented on code on Oct 05, 2026 10:58 UTC
    Code Review
    docs/code-docs/source/inference-engine.rst:1
    @@ -74,6 +74,28 @@ one token. It cannot be combined with CUDA graph capture or
     ``release_inference_cache``. Sampling still happens independently for every
     response branch after the shared prompt forward.
     
    +Segment-Based Kernel Injection (experimental)
    +---------------------------------------------
    +
    +``HybridEngineRolloutConfig(use_segki=True)`` accelerates greedy decode by
    +injecting native CUDA kernels into comm-free segments of the model at rollout
    +construction. Segments are detected structurally, by attribute names, so 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. Unsupported

    gemma is removed from support list

    delock delock commented on code on Oct 05, 2026 10:59 UTC
    Code Review
    csrc/module_inject/decode_loop.cu:1
    @@ -0,0 +1,163 @@
    +// SPDX-License-Identifier: Apache-2.0
    +// DeepSpeed Team
    +
    +// C++ decode loop: runs the full generation loop in a single C++ call.
    +// The replay callable is a std::function<void()> — it can wrap a CUDA
    +// graph replay, a SYCL submission, an eager PyTorch forward, or any
    +// backend-specific mechanism. The C++ loop is agnostic to the backend.
    +//
    +// Per-step overhead: replay_fn() ≈ 2-5μs (pybind11 dispatch)
    +// vs Python for-loop ≈ 30-50μs.
    +// The fused step-update kernel launch is pure C++ (zero Python).
    +
    +#include <ATen/cuda/CUDAContext.h>
    +#include <cuda_runtime.h>
    +#include <torch/extension.h>
    +#include <functional>
    +
    +__global__ void ds_loop_step_kernel(const __nv_bfloat16* __restrict__ logits,
    +                                    int64_t* __restrict__ token_out,
    +                                    int64_t* __restrict__ write_pos,
    +                                    bool* __restrict__ mask,
    +                                    int64_t* __restrict__ out_buf,
    +                                    int step,
    +                                    int vocab_size,
    +                                    int max_len)
    +{
    +    __shared__ int s_idx[1024];
    +    __shared__ float s_val[1024];
    +
    +    int tid = threadIdx.x;
    +    int local_idx = 0;
    +    float local_val = -INFINITY;
    +
    +    for (int v = tid; v < vocab_size; v += blockDim.x) {
    +        float val = __bfloat162float(logits[v]);
    +        if (val > local_val) {
    +            local_val = val;
    +            local_idx = v;
    +        }
    +    }
    +    s_idx[tid] = local_idx;
    +    s_val[tid] = local_val;
    +    __syncthreads();
    +
    +    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
    +        if (tid < stride) {
    +            if (s_val[tid + stride] > s_val[tid]) {
    +                s_val[tid] = s_val[tid + stride];
    +                s_idx[tid] = s_idx[tid + stride];
    +            }
    +        }
    +        __syncthreads();
    +    }
    +
    +    if (tid == 0) {
    +        int64_t best = (int64_t)s_idx[0];
    +        token_out[0] = best;
    +        out_buf[step] = best;
    +        int64_t new_pos = write_pos[0] + 1;
    +        write_pos[0] = new_pos;
    +        // new_pos is the slot the token just written occupies during the
    +        // next replay; revealing new_pos+1 masks the current slot for
    +        // layers still on native SDPA.
    +        if (new_pos < max_len) { mask[new_pos] = true; }
    +    }
    +}
    +
    +// Fills buf[from, len) with pad on the device — used after an early EOS exit.
    +__global__ void pad_tail_kernel(int64_t* __restrict__ buf, int64_t from, int64_t len, int64_t pad)
    +{
    +    int64_t i = from + (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
    +    if (i < len) { buf[i] = pad; }
    +}
    +
    +int64_t ds_decode_loop(std::function<void()> replay_fn,
    +                       at::Tensor logits,
    +                       at::Tensor token_out,
    +                       at::Tensor write_pos,
    +                       at::Tensor mask,
    +                       at::Tensor out_buf,
    +                       int64_t max_steps,
    +                       int64_t eos_token_id,
    +                       int64_t pad_token_id,
    +                       int64_t eos_check_every)

    decode_loop.cu is removed since fused_glu already support full-step graph path, so this path is not necessary for performance.

    delock delock commented on code on Oct 05, 2026 11:00 UTC
    Code Review
    tests/unit/module_inject/test_segment_ki_kernels.py:1
    @@ -0,0 +1,260 @@
    +# SPDX-License-Identifier: Apache-2.0
    +# DeepSpeed Team
    +"""Contract tests for segment-KI kernels and rollout co-location.
    +
    +Three groups:
    +
    +1. Kernel vs reference consistency (GPU): every fused_glu CUDA kernel must
    +   match its pure-PyTorch specification in kernel_reference.py within bf16
    +   tolerance on identical inputs.  A regression here catches numerical
    +   drift in any kernel rewrite.
    +2. Composite paths and injection invariants (CPU): the autograd.Function
    +   fallbacks and apply_segment_ki must work without a GPU, and injection
    +   must not materialize weight copies.
    +3. Rollout -> train -> rollout integration (GPU, gated on model
    +   availability): the RL-loop contract — generate, take one optimizer
    +   step through the injected model, generate again, and observe different
    +   output — with no inject/eject/sync calls anywhere in between.
    +"""
    +
    +import os
    +
    +import pytest
    +import torch
    +
    +from deepspeed.accelerator import get_accelerator
    +
    +from deepspeed.module_inject.kernel_reference import decode_attn as ref_decode_attn
    +from deepspeed.module_inject.kernel_reference import dual_gemv_silu_mul as ref_dual_gemv
    +from deepspeed.module_inject.kernel_reference import fused_add_norm as ref_add_norm
    +from deepspeed.module_inject.kernel_reference import gdn_gates as ref_gdn_gates
    +from deepspeed.module_inject.kernel_reference import gdn_input_proj as ref_gdn_proj
    +from deepspeed.module_inject.kernel_reference import triple_gemv as ref_triple_gemv
    +
    +DEV = get_accelerator().device_name()
    +GPU_AVAILABLE = DEV != "cpu"

    better way to detect by detect whether related op builder can be loaded, no need to detect specific GPU type

    nathon-lee nathon-lee commented on Oct 06, 2026 15:41 UTC
    Contributor

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

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 07, 2026 04:34 UTC
    Reviewer

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

  • <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> [Preserve packed-sequence boundaries through causal convolution](#discussion_r4203086055) · New

  • <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> [Disable fused QKV projection when any bias is present](#discussion_r4203086091) · New

  • <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> [Pass tensor masks for ordinary models during graph capture](#discussion_r4203086101) · New

  • <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> [Match torch.argmax first-index tie breaking](#discussion_r4203086120) · New

  • <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> [Add direct CUDA coverage for decode_step_graph](#discussion_r4203086135) · New

  • <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> [Make live-weight integration test deterministically observe weight changes](#discussion_r4203086166) · New

  • </details>

    <details>
    <summary><strong>Resolved since last review (18)</strong></summary>

  • <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> [EOS padding slice ignores prompt-length offset](#discussion_r4127430619)

  • <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> [Forward-only graph replay uses uncaptured token buffers](#discussion_r4127430571)

  • <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> [Fallback graph reuses already-consumed recurrent state](#discussion_r4127430542)

  • <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> [Prompt attention mask is dropped during prefill](#discussion_r4127430518)

  • <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> [Unbound GDN slots are skipped without state initialization](#discussion_r4127430490)

  • <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> [Fused add-norm loses gradients during training](#discussion_r4127430458)

  • <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> [Custom attention ignores padding masks](#discussion_r4127430421)

  • <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> [Tensor truth-value check breaks packed-sequence calls](#discussion_r4127430391)

  • <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> [Native gdn_gates path cuts off training gradients](#discussion_r4127430358)

  • <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> [Missing CUDA bf16 and pybind functional headers](#discussion_r4127430296)

  • <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> [CUDA-only tests run on unsupported accelerators](#discussion_r4127430850)

  • <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> [Fused GLU builder is not registered for wheel builds](#discussion_r4127430812)

  • <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> [Decode loop builder is not registered for wheel builds](#discussion_r4127430774)

  • <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> [FP16 models incorrectly enter bf16-only decode kernels](#discussion_r4127430733)

  • <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> [Non-CUDA backends incorrectly load CUDA builder](#discussion_r4127430701)

  • <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> [Dual-GEMV excludes normal 3D greedy-decode inputs](#discussion_r4127430669)

  • <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> [Gemma is documented as supported despite GELU rejection](#discussion_r4127430923)

  • <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> [Missing direct coverage for native decode fallback](#discussion_r4127430881)

  • </details>

    delock delock commented on Oct 08, 2026 00:29 UTC
    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 nathon-lee commented on Oct 10, 2026 14:41 UTC
    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 on Oct 15, 2026 23:18 UTC
    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 on Oct 17, 2026 14:28 UTC
    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[bot] chatgpt-codex-connector[bot] commented on Oct 22, 2026 03:21 UTC
    Bot

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

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

    </details>

    delock delock commented on Oct 22, 2026 03:23 UTC
    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 on Oct 22, 2026 06:35 UTC
    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.

    phoeenniixx phoeenniixx commented on Oct 25, 2026 09:53 UTC
    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.

    delock delock commented on Oct 29, 2026 15:20 UTC
    Author

    @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_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.

    delock delock commented on Nov 03, 2026 00:32 UTC
    Author

    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

    delock delock commented on Nov 03, 2026 05:58 UTC
    Author

    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.

    delock delock commented on Nov 03, 2026 10:05 UTC
    Author

    customAR is moved into #8997 as a separate PR, as it is releatively independent.

    anyadontfly anyadontfly commented on Nov 04, 2026 01:50 UTC
    Contributor

    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.

    delock delock commented on Nov 05, 2026 10:58 UTC
    Author

    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.

    Reviewers
    Assignees
    delock delock
    Labels
    risk: low confidence: 78.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 92.5% (HIGH) · Higher = larger blast radius
    92.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 78.5% · Lower = rushed or shallow review
    78.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 19.9% · Safe to merge
    19.9%