diff --git a/csrc/module_inject/fused_glu.cu b/csrc/module_inject/fused_glu.cu new file mode 100644 index 000000000000..9a6f257f045a --- /dev/null +++ b/csrc/module_inject/fused_glu.cu @@ -0,0 +1,1861 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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: 1+exp(x) rounds to 1 in fp32 for + // strongly negative x (log(1+exp(-20)) == 0), so use log1p there; + // for large x, log(1+exp(x)) == x to fp32 precision. + float sp = (sp_x > 20.0f) ? sp_x + : (sp_x < -10.0f) ? log1pf(expf(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 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<<>>( + reinterpret_cast(a.data_ptr()), + reinterpret_cast(b.data_ptr()), + a_log.data_ptr(), + dt_bias.data_ptr(), + reinterpret_cast<__nv_bfloat16*>(beta.data_ptr()), + reinterpret_cast<__nv_bfloat16*>(g.data_ptr()), + 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_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, + int pos_stride) +{ + // One block per row: each block argmaxes its row's logits and advances + // its own write_pos entry (pos_stride 1); a scalar pos (stride 0) is + // only valid with a single block. + __shared__ int s_idx[1024]; + __shared__ float s_val[1024]; + + const int row = blockIdx.x; + const __nv_bfloat16* lg = logits + (long)row * vocab_size; + 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(lg[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) { + // torch.argmax picks the lowest index on ties. + if (s_val[tid + stride] > s_val[tid] || + (s_val[tid + stride] == s_val[tid] && s_idx[tid + stride] < s_idx[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[row] = 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[row * pos_stride] + 1; + if (pos_stride != 0 || row == 0) write_pos[row * pos_stride] = new_pos; + out_buf[(long)row * max_len + new_pos] = best; + // new_pos is the slot the token just written will occupy during the + // NEXT replay, matching the Python loop's reveal-before-replay + // convention; revealing new_pos+1 would unmask an unwritten slot + // and mask the current one for layers still on native SDPA. + if (new_pos < max_len) { mask[(long)row * max_len + new_pos] = true; } + } +} + +void decode_step_graph(at::Tensor logits, + at::Tensor token_out, + at::Tensor write_pos, + at::Tensor mask, + at::Tensor out_buf) +{ + TORCH_CHECK(logits.is_cuda() && logits.scalar_type() == at::ScalarType::BFloat16, + "logits must be CUDA bf16"); + TORCH_CHECK(logits.dim() == 2, "logits must be [batch, vocab]"); + const int batch = (int)logits.size(0); + int vocab = (int)logits.size(1); + int max_len = (int)mask.size(-1); + TORCH_CHECK(token_out.numel() == batch, "token_out must have one entry per row"); + TORCH_CHECK(mask.numel() == (int64_t)batch * max_len, "mask must be [batch, ..., max_len]"); + TORCH_CHECK(out_buf.numel() == (int64_t)batch * max_len, "out_buf must be [batch, max_len]"); + TORCH_CHECK(write_pos.numel() == batch || (write_pos.numel() == 1 && batch == 1), + "write_pos must have one entry per row (a scalar only for batch 1)"); + const int pos_stride = write_pos.numel() == batch ? 1 : 0; + auto stream = at::cuda::getCurrentCUDAStream(); + decode_step_graph_kernel<<>>( + reinterpret_cast(logits.data_ptr()), + token_out.data_ptr(), + write_pos.data_ptr(), + mask.data_ptr(), + out_buf.data_ptr(), + vocab, + max_len, + pos_stride); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +// ─── Dual-weight GEMV (b=1 decode) ─── +// Reads gate.weight and up.weight directly — no concat, no weight copies. +// Each warp handles one output feature: lanes cooperatively compute two +// dot products (gate row and up row share the same hidden vector read), +// then applies silu(a)*b. Memory-bound at b=1; coalesced reads achieve +// near-peak HBM bandwidth with zero tiling or tensor-core complexity. + +// Lane-local partial dot product of hidden[0..n) with a weight row; +// 8 bf16 per 16-byte load per lane (n and the pointers are multiples of +// 8 / 16B-aligned, enforced by the wrappers). The caller reduces across +// the warp. +__device__ __forceinline__ float dot_partial_v8(const __nv_bfloat16* __restrict__ hidden, + const __nv_bfloat16* __restrict__ w_row, + int n, + int lane) +{ + float acc = 0.0f; + for (int i = lane * 8; i < n; i += 256) { + uint4 hv = *reinterpret_cast(hidden + i); + uint4 wv = *reinterpret_cast(w_row + i); + const __nv_bfloat16* h8 = reinterpret_cast(&hv); + const __nv_bfloat16* w8 = reinterpret_cast(&wv); +#pragma unroll + for (int e = 0; e < 8; e++) acc += __bfloat162float(h8[e]) * __bfloat162float(w8[e]); + } + return acc; +} + +__global__ void dual_gemv_silu_mul_kernel(const __nv_bfloat16* __restrict__ hidden, + const __nv_bfloat16* __restrict__ gate_w, + const __nv_bfloat16* __restrict__ up_w, + __nv_bfloat16* __restrict__ out, + int out_features, + int in_features) +{ + int warp_id = (blockIdx.x * blockDim.x + threadIdx.x) >> 5; + int lane = threadIdx.x & 31; + if (warp_id >= out_features) return; + + const __nv_bfloat16* gate_row = gate_w + (long)warp_id * in_features; + const __nv_bfloat16* up_row = up_w + (long)warp_id * in_features; + + // 8 bf16 per lane per 16-byte load; 32 lanes cover 256 elements/iter + float gate_acc = dot_partial_v8(hidden, gate_row, in_features, lane); + float up_acc = dot_partial_v8(hidden, up_row, in_features, lane); + + // Warp-level reduction for both dot products simultaneously. + for (int offset = 16; offset > 0; offset >>= 1) { + gate_acc += __shfl_down_sync(0xffffffff, gate_acc, offset); + up_acc += __shfl_down_sync(0xffffffff, up_acc, offset); + } + + if (lane == 0) { + float activated = SILU(gate_acc); + out[warp_id] = __float2bfloat16_rn(activated * up_acc); + } +} + +void dual_gemv_silu_mul(at::Tensor hidden, at::Tensor gate_w, at::Tensor up_w, at::Tensor out) +{ + TORCH_CHECK(hidden.size(-1) % 8 == 0, "in_features must be a multiple of 8"); + TORCH_CHECK((reinterpret_cast(hidden.data_ptr()) & 15) == 0, + "hidden must be 16B aligned"); + TORCH_CHECK(hidden.is_cuda() && hidden.scalar_type() == at::ScalarType::BFloat16, + "hidden must be CUDA bf16"); + TORCH_CHECK(gate_w.is_contiguous() && up_w.is_contiguous(), "weights must be contiguous"); + TORCH_CHECK(gate_w.size(0) == up_w.size(0) && gate_w.size(1) == up_w.size(1), + "gate|up weight shapes must match"); + int out_f = (int)gate_w.size(0); + int in_f = (int)gate_w.size(1); + int warps_per_block = 8; // 256 threads + int blocks = (out_f + warps_per_block - 1) / warps_per_block; + auto stream = at::cuda::getCurrentCUDAStream(); + dual_gemv_silu_mul_kernel<<>>( + reinterpret_cast(hidden.data_ptr()), + reinterpret_cast(gate_w.data_ptr()), + reinterpret_cast(up_w.data_ptr()), + reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), + out_f, + in_f); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +// ─── Quad-weight GEMV (b=1 GDN input projections) ─── +// Reads the four original GDN projection weights directly (qkv|z|b|a) — no +// concat, no weight copies, gradient-safe for train/generate co-location. +// Same warp-per-row scheme as the dual-weight GEMV: the global row index +// selects which weight matrix the row lives in; output is one contiguous +// [rows0+rows1+rows2+rows3] buffer that the caller slices. + +__global__ void quad_gemv_kernel(const __nv_bfloat16* __restrict__ hidden, + const __nv_bfloat16* __restrict__ w0, + const __nv_bfloat16* __restrict__ w1, + const __nv_bfloat16* __restrict__ w2, + const __nv_bfloat16* __restrict__ w3, + __nv_bfloat16* __restrict__ out, + int rows0, + int rows1, + int rows2, + int rows3, + int in_features) +{ + int warp_id = (blockIdx.x * blockDim.x + threadIdx.x) >> 5; + int lane = threadIdx.x & 31; + int total = rows0 + rows1 + rows2 + rows3; + if (warp_id >= total) return; + + const __nv_bfloat16* row; + int row_idx; + if (warp_id < rows0) { + row = w0 + (long)warp_id * in_features; + row_idx = warp_id; + } else if (warp_id < rows0 + rows1) { + row_idx = warp_id - rows0; + row = w1 + (long)row_idx * in_features; + } else if (warp_id < rows0 + rows1 + rows2) { + row_idx = warp_id - rows0 - rows1; + row = w2 + (long)row_idx * in_features; + } else { + row_idx = warp_id - rows0 - rows1 - rows2; + row = w3 + (long)row_idx * in_features; + } + + float acc = dot_partial_v8(hidden, row, in_features, lane); + for (int offset = 16; offset > 0; offset >>= 1) { + acc += __shfl_down_sync(0xffffffff, acc, offset); + } + if (lane == 0) { out[warp_id] = __float2bfloat16_rn(acc); } +} + +void quad_gemv(at::Tensor hidden, + at::Tensor w0, + at::Tensor w1, + at::Tensor w2, + at::Tensor w3, + at::Tensor out) +{ + TORCH_CHECK(hidden.is_cuda() && hidden.scalar_type() == at::ScalarType::BFloat16, + "hidden must be CUDA bf16"); + TORCH_CHECK( + w0.is_contiguous() && w1.is_contiguous() && w2.is_contiguous() && w3.is_contiguous(), + "weights must be contiguous"); + TORCH_CHECK(w0.size(1) % 8 == 0, "in_features must be a multiple of 8"); + TORCH_CHECK((reinterpret_cast(hidden.data_ptr()) & 15) == 0, + "hidden must be 16B aligned"); + int rows0 = (int)w0.size(0), rows1 = (int)w1.size(0); + int rows2 = (int)w2.size(0), rows3 = (int)w3.size(0); + int in_f = (int)w0.size(1); + int total = rows0 + rows1 + rows2 + rows3; + int warps_per_block = 8; // 256 threads + int blocks = (total + warps_per_block - 1) / warps_per_block; + auto stream = at::cuda::getCurrentCUDAStream(); + quad_gemv_kernel<<>>( + reinterpret_cast(hidden.data_ptr()), + reinterpret_cast(w0.data_ptr()), + reinterpret_cast(w1.data_ptr()), + reinterpret_cast(w2.data_ptr()), + reinterpret_cast(w3.data_ptr()), + reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), + rows0, + rows1, + rows2, + rows3, + in_f); +} + +// ─── Custom decode attention (batched, graph-compatible, no mask) ─── +// Streams softmax(q @ K[0:pos]^T / sqrt(d)) @ V[0:pos] with GQA, for any +// batch size. The valid KV length comes from a GPU-resident write_pos +// tensor (shared scalar or per-row), so the kernel is CUDA-graph +// replayable (addresses fixed, only the values change per step). +// One block per KV head; its 8 warps split as (query head, KV chunk): +// warp w handles query head w % q_per_kv over KV positions strided by +// split = 8 / q_per_kv, then per-head partial online-softmax states are +// merged through shared memory. Each lane owns a contiguous 16B slice of +// the head dimension (HEAD_DIM/32 elements) for coalesced K/V row loads. + +template +__global__ void __launch_bounds__(512) + decode_attn_kernel(const __nv_bfloat16* __restrict__ q, + __nv_bfloat16* __restrict__ K, + __nv_bfloat16* __restrict__ V, + const int64_t* __restrict__ write_pos, + __nv_bfloat16* __restrict__ out, + int num_q_heads, + int num_kv_heads, + long q_hs, + long q_rs, + int max_len, + float scale, + int pos_stride, + const float* __restrict__ q_norm_w, // [HEAD_DIM], pre-scaled (1+w) + const float* __restrict__ cos_t, // [max_len, rope_dim] + const float* __restrict__ sin_t, // [max_len, rope_dim] + const __nv_bfloat16* __restrict__ gate, // q layout + const __nv_bfloat16* __restrict__ k_raw, // this step's K, pre-norm/rope + const __nv_bfloat16* __restrict__ v_raw, // this step's V + const float* __restrict__ k_norm_w, // [HEAD_DIM], pre-scaled (1+w) + float eps, + int rope_dim) +{ + constexpr int EPL = HEAD_DIM / 32; // head-dim elements owned per lane + const int q_per_kv = num_q_heads / num_kv_heads; + const int warps_per_block = blockDim.x >> 5; + const int split = warps_per_block; // KV chunks per query head + + // One block per (row, query head): all the block's warps split that + // head's KV range, giving enough independent streams to cover HBM latency. + const int row = blockIdx.x / num_q_heads; + const int q_head = blockIdx.x % num_q_heads; + const int kv_head = q_head / q_per_kv; + const int warp_id = threadIdx.x >> 5; + const int lane = threadIdx.x & 31; + const int s = warp_id; + + // valid KV positions: 0..pos inclusive; a shared scalar when pos_stride + // is 0, one per row otherwise + const int pos = (int)write_pos[row * pos_stride]; + + __nv_bfloat16* Kg = K + ((long)(row * num_kv_heads + kv_head)) * max_len * HEAD_DIM; + __nv_bfloat16* Vg = V + ((long)(row * num_kv_heads + kv_head)) * max_len * HEAD_DIM; + // q/gate may be sliced out of a wider fused row block (e.g. fused[:, :qn] + // of a q|k|v concat), so rows advance by the caller-provided row stride, + // not the packed num_q_heads * q_hs + const __nv_bfloat16* q_row = q + (long)row * q_rs + (long)q_head * q_hs; + const __nv_bfloat16* g_row = gate + (long)row * q_rs + (long)q_head * q_hs; + + float q_reg[EPL]; +#pragma unroll + for (int e = 0; e < EPL; e++) q_reg[e] = __bfloat162float(q_row[lane * EPL + e]); + + if (q_norm_w != nullptr) { + // Fused q-side preprocessing (the eager path's biggest elementwise + // contributors): per-head RMSNorm with the (1+w) weight, then + // rotate-half RoPE at this row's position. Both live in registers; + // the RoPE pairing exchanges EPL values with lane^16 (element j + // pairs with j +/- HEAD_DIM/2, always 16 lanes away for EPL=H/32). + float ss = 0.0f; +#pragma unroll + for (int e = 0; e < EPL; e++) ss += q_reg[e] * q_reg[e]; +#pragma unroll + for (int off = 16; off > 0; off >>= 1) ss += __shfl_down_sync(0xffffffff, ss, off); + const float inv_norm = rsqrtf(__shfl_sync(0xffffffff, ss, 0) / HEAD_DIM + eps); +#pragma unroll + for (int e = 0; e < EPL; e++) q_reg[e] = q_reg[e] * inv_norm * q_norm_w[lane * EPL + e]; + // Partial RoPE (HF convention): rotate_half only over [0, rope_dim), + // elements past rope_dim pass through. Lanes holding rope elements + // pair with the lane half a rope region away. + // All lanes execute the shuffle (a warp-wide sync op cannot sit in a + // divergent branch); non-rope lanes swap with themselves harmlessly. + const int j0 = lane * EPL; + const int half_lanes = rope_dim > 0 ? (rope_dim / 2) / EPL : 0; + const int partner = (j0 < rope_dim / 2) ? lane + half_lanes + : (j0 < rope_dim) ? lane - half_lanes + : lane; + float pair[EPL]; +#pragma unroll + for (int e = 0; e < EPL; e++) pair[e] = __shfl_sync(0xffffffff, q_reg[e], partner); + if (j0 < rope_dim) { + const bool first_half = j0 < rope_dim / 2; + const float* crow = cos_t + (long)pos * rope_dim + j0; + const float* srow = sin_t + (long)pos * rope_dim + j0; +#pragma unroll + for (int e = 0; e < EPL; e++) + q_reg[e] = q_reg[e] * crow[e] + (first_half ? -pair[e] : pair[e]) * srow[e]; + } + } + + if (k_norm_w != nullptr) { + // Fused K-side preprocessing (mirror of the q side): per-head RMSNorm, + // partial RoPE, and the cache-slot write for this position. Each lane + // writes exactly the elements it reads back at idx == pos, so + // same-thread visibility holds without fences; the sibling q-head + // blocks of this kv head redundantly write identical values. + float k_reg[EPL]; + const __nv_bfloat16* k_in_row = k_raw + ((long)(row * num_kv_heads + kv_head)) * HEAD_DIM; +#pragma unroll + for (int e = 0; e < EPL; e++) k_reg[e] = __bfloat162float(k_in_row[lane * EPL + e]); + float kss = 0.0f; +#pragma unroll + for (int e = 0; e < EPL; e++) kss += k_reg[e] * k_reg[e]; +#pragma unroll + for (int off = 16; off > 0; off >>= 1) kss += __shfl_down_sync(0xffffffff, kss, off); + const float k_inv = rsqrtf(__shfl_sync(0xffffffff, kss, 0) / HEAD_DIM + eps); +#pragma unroll + for (int e = 0; e < EPL; e++) k_reg[e] = k_reg[e] * k_inv * k_norm_w[lane * EPL + e]; + const int kj0 = lane * EPL; + const int khalf_lanes = rope_dim > 0 ? (rope_dim / 2) / EPL : 0; + const int kpartner = (kj0 < rope_dim / 2) ? lane + khalf_lanes + : (kj0 < rope_dim) ? lane - khalf_lanes + : lane; + float kpair[EPL]; +#pragma unroll + for (int e = 0; e < EPL; e++) kpair[e] = __shfl_sync(0xffffffff, k_reg[e], kpartner); + if (kj0 < rope_dim) { + const bool kfirst = kj0 < rope_dim / 2; + const float* kcrow = cos_t + (long)pos * rope_dim + kj0; + const float* ksrow = sin_t + (long)pos * rope_dim + kj0; +#pragma unroll + for (int e = 0; e < EPL; e++) + k_reg[e] = k_reg[e] * kcrow[e] + (kfirst ? -kpair[e] : kpair[e]) * ksrow[e]; + } + __nv_bfloat16* k_slot = Kg + (long)pos * HEAD_DIM; + __nv_bfloat16* v_slot = Vg + (long)pos * HEAD_DIM; + const __nv_bfloat16* v_in_row = v_raw + ((long)(row * num_kv_heads + kv_head)) * HEAD_DIM; +#pragma unroll + for (int e = 0; e < EPL; e++) { + k_slot[lane * EPL + e] = __float2bfloat16_rn(k_reg[e]); + v_slot[lane * EPL + e] = v_in_row[lane * EPL + e]; + } + } + + float max_score = -INFINITY; + float sum_exp = 0.0f; + float out_reg[EPL]; +#pragma unroll + for (int e = 0; e < EPL; e++) out_reg[e] = 0.0f; + + // UNROLL positions in flight so their K loads overlap and hide HBM latency. + constexpr int UNROLL = 4; + for (int base = s; base <= pos; base += UNROLL * split) { + float k_reg[UNROLL][EPL]; + int idx[UNROLL]; +#pragma unroll + for (int u = 0; u < UNROLL; u++) { + idx[u] = base + u * split; + if (idx[u] <= pos) { + const __nv_bfloat16* krow = Kg + (long)idx[u] * HEAD_DIM; +#pragma unroll + for (int e = 0; e < EPL; e++) k_reg[u][e] = __bfloat162float(krow[lane * EPL + e]); + } + } +#pragma unroll + for (int u = 0; u < UNROLL; u++) { + if (idx[u] > pos) continue; // uniform across the warp + float dot = 0.0f; +#pragma unroll + for (int e = 0; e < EPL; e++) dot += q_reg[e] * k_reg[u][e]; +#pragma unroll + for (int off = 16; off > 0; off >>= 1) dot += __shfl_down_sync(0xffffffff, dot, off); + float score = __shfl_sync(0xffffffff, dot, 0) * scale; + + float new_max = fmaxf(max_score, score); + float rescale = expf(max_score - new_max); // 0 when max_score is still -inf + float weight = expf(score - new_max); + sum_exp = sum_exp * rescale + weight; +#pragma unroll + for (int e = 0; e < EPL; e++) out_reg[e] *= rescale; + const __nv_bfloat16* vrow = Vg + (long)idx[u] * HEAD_DIM; +#pragma unroll + for (int e = 0; e < EPL; e++) + out_reg[e] += weight * __bfloat162float(vrow[lane * EPL + e]); + max_score = new_max; + } + } + + // Merge the per-chunk partial softmax states (max, sum, weighted V) in + // shared memory; an empty chunk contributes 0 via exp(-inf - M). + __shared__ float s_max[16]; + __shared__ float s_sum[16]; + __shared__ float s_out[16][HEAD_DIM]; + + s_max[warp_id] = max_score; + s_sum[warp_id] = sum_exp; +#pragma unroll + for (int e = 0; e < EPL; e++) s_out[warp_id][lane * EPL + e] = out_reg[e]; + __syncthreads(); + + if (s == 0) { // the first chunk's warp combines all chunks for its head + float M = -INFINITY; + for (int t = 0; t < split; t++) M = fmaxf(M, s_max[t]); + float S = 0.0f; + float acc[EPL]; +#pragma unroll + for (int e = 0; e < EPL; e++) acc[e] = 0.0f; + for (int t = 0; t < split; t++) { + float wm = expf(s_max[t] - M); + S += s_sum[t] * wm; +#pragma unroll + for (int e = 0; e < EPL; e++) acc[e] += s_out[t][lane * EPL + e] * wm; + } + float inv = 1.0f / S; +#pragma unroll + for (int e = 0; e < EPL; e++) { + float v = acc[e] * inv; + if (gate != nullptr) + v *= 1.0f / (1.0f + expf(-__bfloat162float(g_row[lane * EPL + e]))); + out[((long)(row * num_q_heads + q_head)) * HEAD_DIM + lane * EPL + e] = + __float2bfloat16_rn(v); + } + } +} + +void decode_attn(at::Tensor q, + at::Tensor K, + at::Tensor V, + at::Tensor write_pos, + at::Tensor out, + int64_t num_q_heads, + int64_t num_kv_heads, + int64_t head_dim, + int64_t max_len, + at::Tensor q_norm_w, + at::Tensor cos_t, + at::Tensor sin_t, + at::Tensor gate, + at::Tensor k_raw, + at::Tensor v_raw, + at::Tensor k_norm_w, + double eps, + int64_t rope_dim) +{ + TORCH_CHECK(q.is_cuda() && q.scalar_type() == at::ScalarType::BFloat16, "q must be CUDA bf16"); + // accept packed or chunked-[q|gate] layouts: last dim dense, uniform + // head stride (the kernel indexes through q_hs) + TORCH_CHECK(q.stride(-1) == 1, "q last dim must be dense"); + const long q_hs = q.stride(-2); + // row stride: [B, H, D] carries it in stride(0); a packed 2-D view's + // rows are already num_q_heads * q_hs apart + const long q_rs = (q.dim() == 3) ? q.stride(0) : num_q_heads * q_hs; + TORCH_CHECK(gate.defined() ? (gate.stride(-1) == 1 && gate.stride(-2) == q_hs && + (gate.dim() != 3 || gate.stride(0) == q_rs)) + : true, + "gate layout must match q"); + TORCH_CHECK(K.is_contiguous() && V.is_contiguous(), "K/V must be contiguous"); + TORCH_CHECK(write_pos.is_cuda() && write_pos.scalar_type() == at::ScalarType::Long, + "write_pos must be a CUDA int64 tensor"); + TORCH_CHECK(num_q_heads % num_kv_heads == 0, + "GQA requires num_q_heads divisible by num_kv_heads"); + int q_per_kv = (int)(num_q_heads / num_kv_heads); + TORCH_CHECK(head_dim % 32 == 0, "head_dim must be a multiple of 32, got ", head_dim); + // 16 warps/block (512 threads) so each query head gets a 4-way KV split + // — the per-warp stream is otherwise latency-bound at these sizes. More + // warps than this exhaust registers with __launch_bounds__(512). + const int warps_per_block = 16; + TORCH_CHECK(warps_per_block % q_per_kv == 0, + "q heads per KV head (", + q_per_kv, + ") must divide ", + warps_per_block); + + // Any leading batch dims flatten to rows: q [b, hq, d], K/V [b, hkv, L, d]. + const int64_t batch = q.numel() / (num_q_heads * head_dim); + TORCH_CHECK(batch >= 1 && q.numel() == batch * num_q_heads * head_dim, "q shape mismatch"); + TORCH_CHECK(K.numel() == batch * num_kv_heads * max_len * head_dim, "K shape mismatch"); + TORCH_CHECK(V.numel() == batch * num_kv_heads * max_len * head_dim, "V shape mismatch"); + TORCH_CHECK(out.numel() == q.numel(), "out shape mismatch"); + TORCH_CHECK(write_pos.numel() == 1 || write_pos.numel() == batch, + "write_pos must be a scalar or one entry per row"); + const int pos_stride = write_pos.numel() == 1 ? 0 : 1; + + // Optional fused q-side preprocessing: q_norm_w [head_dim] fp32 + // (pre-scaled 1+w), cos/sin tables [max_len, head_dim] fp32, gate with + // q's layout. Nullptr tensors disable each piece. + const bool fuse_q = q_norm_w.defined() && q_norm_w.numel() == head_dim; + const bool use_gate = gate.defined() && gate.numel() == q.numel(); + const bool fuse_k = k_raw.defined() && k_raw.numel() > 0 && k_norm_w.defined(); + TORCH_CHECK(!fuse_k || (k_raw.is_contiguous() && v_raw.is_contiguous()), + "k_raw/v_raw must be contiguous"); + TORCH_CHECK(!fuse_k || (fuse_q), "fused K requires the fused Q path (shared cos/sin)"); + // gate rides the same strided [b,H,hd] layout as q (checked above) + TORCH_CHECK( + !fuse_q || (cos_t.defined() && sin_t.defined() && + cos_t.numel() == (int64_t)max_len * rope_dim && sin_t.numel() == cos_t.numel()), + "fused q path needs cos/sin tables of [max_len, rope_dim]"); + TORCH_CHECK(!fuse_q || (rope_dim % (2 * (head_dim / 32)) == 0), + "rope_dim/2 must be a multiple of the per-lane element count"); + + float scale = 1.0f / sqrtf((float)head_dim); + auto stream = at::cuda::getCurrentCUDAStream(); + auto q_ptr = reinterpret_cast(q.data_ptr()); + auto k_ptr = reinterpret_cast<__nv_bfloat16*>(K.data_ptr()); + auto v_ptr = reinterpret_cast<__nv_bfloat16*>(V.data_ptr()); + auto o_ptr = reinterpret_cast<__nv_bfloat16*>(out.data_ptr()); + auto k_raw_ptr = fuse_k ? reinterpret_cast(k_raw.data_ptr()) + : nullptr; + auto v_raw_ptr = fuse_k ? reinterpret_cast(v_raw.data_ptr()) + : nullptr; + auto k_norm_ptr = fuse_k ? k_norm_w.data_ptr() : nullptr; + auto qn_ptr = fuse_q ? q_norm_w.data_ptr() : nullptr; + auto cos_ptr = fuse_q ? cos_t.data_ptr() : nullptr; + auto sin_ptr = fuse_q ? sin_t.data_ptr() : nullptr; + auto g_ptr = use_gate ? reinterpret_cast(gate.data_ptr()) + : nullptr; + + switch (head_dim) { + case 64: + decode_attn_kernel<64><<<(int)(batch * num_q_heads), warps_per_block * 32, 0, stream>>>( + q_ptr, + k_ptr, + v_ptr, + write_pos.data_ptr(), + o_ptr, + (int)num_q_heads, + (int)num_kv_heads, + q_hs, + q_rs, + (int)max_len, + scale, + pos_stride, + qn_ptr, + cos_ptr, + sin_ptr, + g_ptr, + k_raw_ptr, + v_raw_ptr, + k_norm_ptr, + (float)eps, + (int)rope_dim); + break; + case 128: + decode_attn_kernel<128> + <<<(int)(batch * num_q_heads), warps_per_block * 32, 0, stream>>>( + q_ptr, + k_ptr, + v_ptr, + write_pos.data_ptr(), + o_ptr, + (int)num_q_heads, + (int)num_kv_heads, + q_hs, + q_rs, + (int)max_len, + scale, + pos_stride, + qn_ptr, + cos_ptr, + sin_ptr, + g_ptr, + k_raw_ptr, + v_raw_ptr, + k_norm_ptr, + (float)eps, + (int)rope_dim); + break; + case 256: + decode_attn_kernel<256> + <<<(int)(batch * num_q_heads), warps_per_block * 32, 0, stream>>>( + q_ptr, + k_ptr, + v_ptr, + write_pos.data_ptr(), + o_ptr, + (int)num_q_heads, + (int)num_kv_heads, + q_hs, + q_rs, + (int)max_len, + scale, + pos_stride, + qn_ptr, + cos_ptr, + sin_ptr, + g_ptr, + k_raw_ptr, + v_raw_ptr, + k_norm_ptr, + (float)eps, + (int)rope_dim); + break; + default: TORCH_CHECK(false, "Unsupported head_dim: ", head_dim); + } + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +// ─── Fused residual add + RMSNorm (b=1 decode) ─── +// One kernel replaces the two PyTorch ops per norm site (hidden += residual, +// then RMSNorm(hidden) * weight). hidden is updated in-place to hold the new +// residual stream; the normalized output is written to a separate tensor that +// feeds the next sublayer. One thread block covers the whole row so the +// sum-of-squares reduction stays block-local. +__global__ void fused_add_norm_kernel(__nv_bfloat16* __restrict__ hidden, + const __nv_bfloat16* __restrict__ residual, + const __nv_bfloat16* __restrict__ weight, + __nv_bfloat16* __restrict__ out, + float eps, + int dim) +{ + extern __shared__ float s_data[]; + __shared__ float s_reduce[32]; + + int tid = threadIdx.x; + int n_threads = blockDim.x; + // one block per row (the original kernel indexed a single row only; + // multi-row launches silently left rows 1+ of `out` uninitialized) + const long row = blockIdx.x; + __nv_bfloat16* hrow = hidden + row * dim; + const __nv_bfloat16* rrow = residual + row * dim; + __nv_bfloat16* orow = out + row * dim; + + float local_ss = 0.0f; + for (int i = tid; i < dim; i += n_threads) { + float h = __bfloat162float(hrow[i]) + __bfloat162float(rrow[i]); + s_data[i] = h; + hrow[i] = __float2bfloat16_rn(h); + local_ss += h * h; + } + + // Warp then cross-warp reduction of the sum of squares. + for (int offset = 16; offset > 0; offset >>= 1) + local_ss += __shfl_down_sync(0xffffffff, local_ss, offset); + int warp_id = tid >> 5; + if ((tid & 31) == 0) s_reduce[warp_id] = local_ss; + __syncthreads(); + if (warp_id == 0) { + float v = (tid < (n_threads >> 5)) ? s_reduce[tid] : 0.0f; + for (int offset = 16; offset > 0; offset >>= 1) + v += __shfl_down_sync(0xffffffff, v, offset); + if (tid == 0) s_reduce[0] = rsqrtf(v / dim + eps); + } + __syncthreads(); + float rms = s_reduce[0]; + + for (int i = tid; i < dim; i += n_threads) + orow[i] = __float2bfloat16_rn(s_data[i] * rms * __bfloat162float(weight[i])); +} + +__device__ __forceinline__ float silu_f(float v) { return v / (1.0f + expf(-v)); } + +// GDN z-gated output norm: y = (w * x * rsqrt(mean(x^2)+eps)) * silu(z), +// weight applied directly (no 1+w here, no residual stream). +__global__ void gated_norm_kernel(const __nv_bfloat16* __restrict__ x, + const __nv_bfloat16* __restrict__ z, + const __nv_bfloat16* __restrict__ w, + __nv_bfloat16* __restrict__ out, + float eps, + int dim) +{ + extern __shared__ float s_data[]; + __shared__ float s_reduce[32]; + + int tid = threadIdx.x; + int n_threads = blockDim.x; + const long row = blockIdx.x; + const __nv_bfloat16* xr = x + row * dim; + const __nv_bfloat16* zr = z + row * dim; + __nv_bfloat16* orow = out + row * dim; + + float local_ss = 0.0f; + for (int i = tid; i < dim; i += n_threads) { + float v = __bfloat162float(xr[i]); + s_data[i] = v; + local_ss += v * v; + } + for (int offset = 16; offset > 0; offset >>= 1) + local_ss += __shfl_down_sync(0xffffffff, local_ss, offset); + int warp_id = tid >> 5; + if ((tid & 31) == 0) s_reduce[warp_id] = local_ss; + __syncthreads(); + if (warp_id == 0) { + float v = (tid < (n_threads >> 5)) ? s_reduce[tid] : 0.0f; + for (int offset = 16; offset > 0; offset >>= 1) + v += __shfl_down_sync(0xffffffff, v, offset); + if (tid == 0) s_reduce[0] = rsqrtf(v / dim + eps); + } + __syncthreads(); + float rms = s_reduce[0]; + for (int i = tid; i < dim; i += n_threads) + orow[i] = __float2bfloat16_rn(s_data[i] * rms * __bfloat162float(w[i]) * + silu_f(__bfloat162float(zr[i]))); +} + +at::Tensor fused_add_norm(at::Tensor hidden, at::Tensor residual, at::Tensor weight, double eps) +{ + TORCH_CHECK(hidden.is_cuda() && hidden.scalar_type() == at::ScalarType::BFloat16, + "hidden/residual/weight must be CUDA bf16"); + TORCH_CHECK(hidden.is_contiguous() && residual.is_contiguous() && weight.is_contiguous(), + "inputs must be contiguous"); + int64_t rows = hidden.numel() / hidden.size(-1); + int dim = (int)hidden.size(-1); + TORCH_CHECK(residual.numel() == hidden.numel() && weight.numel() == dim, "shape mismatch"); + TORCH_CHECK((int64_t)dim * sizeof(float) <= 48 * 1024, + "dim too large for one-block shared memory: ", + dim); + auto out = at::empty_like(hidden); + auto stream = at::cuda::getCurrentCUDAStream(); + int threads = std::min(1024, ((dim + 31) / 32) * 32); + if (threads == 0) threads = 32; + fused_add_norm_kernel<<<(int)rows, threads, (size_t)dim * sizeof(float), stream>>>( + reinterpret_cast<__nv_bfloat16*>(hidden.data_ptr()), + reinterpret_cast(residual.data_ptr()), + reinterpret_cast(weight.data_ptr()), + reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), + (float)eps, + dim); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + return out; +} + +// ─── Triple-weight QKV GEMV (b=1 decode) ─── +// Reads q_proj/k_proj/v_proj weights directly — no concat, no weight copies +// (gradient-safe). One warp per output row across all three +// matrices, so a single launch covers the whole QKV projection. +__global__ void triple_gemv_kernel(const __nv_bfloat16* __restrict__ hidden, + const __nv_bfloat16* __restrict__ q_w, + const __nv_bfloat16* __restrict__ k_w, + const __nv_bfloat16* __restrict__ v_w, + __nv_bfloat16* __restrict__ q_out, + __nv_bfloat16* __restrict__ k_out, + __nv_bfloat16* __restrict__ v_out, + int q_out_f, + int kv_out_f, + int in_f) +{ + int total_rows = q_out_f + 2 * kv_out_f; + for (int warp_id = (blockIdx.x * blockDim.x + threadIdx.x) >> 5; warp_id < total_rows; + warp_id += (gridDim.x * blockDim.x) >> 5) { + int lane = threadIdx.x & 31; + const __nv_bfloat16* w_ptr; + __nv_bfloat16* out_ptr; + int row; + if (warp_id < q_out_f) { + w_ptr = q_w; + out_ptr = q_out; + row = warp_id; + } else if (warp_id < q_out_f + kv_out_f) { + w_ptr = k_w; + out_ptr = k_out; + row = warp_id - q_out_f; + } else { + w_ptr = v_w; + out_ptr = v_out; + row = warp_id - q_out_f - kv_out_f; + } + + float acc = dot_partial_v8(hidden, w_ptr + (long)row * in_f, in_f, lane); + for (int offset = 16; offset > 0; offset >>= 1) + acc += __shfl_down_sync(0xffffffff, acc, offset); + if (lane == 0) out_ptr[row] = __float2bfloat16_rn(acc); + } +} + +std::vector triple_gemv(at::Tensor hidden, + at::Tensor q_w, + at::Tensor k_w, + at::Tensor v_w) +{ + TORCH_CHECK(hidden.is_cuda() && hidden.scalar_type() == at::ScalarType::BFloat16, + "hidden must be CUDA bf16"); + TORCH_CHECK(q_w.is_contiguous() && k_w.is_contiguous() && v_w.is_contiguous(), + "weights must be contiguous"); + TORCH_CHECK(q_w.size(1) == k_w.size(1) && k_w.size(1) == v_w.size(1), + "in_features must match across q/k/v"); + TORCH_CHECK(q_w.size(1) % 8 == 0, "in_features must be a multiple of 8"); + TORCH_CHECK((reinterpret_cast(hidden.data_ptr()) & 15) == 0, + "hidden must be 16B aligned"); + int q_out_f = (int)q_w.size(0); + int kv_out_f = (int)k_w.size(0); + TORCH_CHECK(v_w.size(0) == kv_out_f, "v/k weight shapes must match"); + int in_f = (int)q_w.size(1); + auto q_out = at::empty({q_out_f}, hidden.options()); + auto k_out = at::empty({kv_out_f}, hidden.options()); + auto v_out = at::empty({kv_out_f}, hidden.options()); + int total_rows = q_out_f + 2 * kv_out_f; + int warps_per_block = 8; + int blocks = (total_rows + warps_per_block - 1) / warps_per_block; + auto stream = at::cuda::getCurrentCUDAStream(); + triple_gemv_kernel<<>>( + reinterpret_cast(hidden.data_ptr()), + reinterpret_cast(q_w.data_ptr()), + reinterpret_cast(k_w.data_ptr()), + reinterpret_cast(v_w.data_ptr()), + reinterpret_cast<__nv_bfloat16*>(q_out.data_ptr()), + reinterpret_cast<__nv_bfloat16*>(k_out.data_ptr()), + reinterpret_cast<__nv_bfloat16*>(v_out.data_ptr()), + q_out_f, + kv_out_f, + in_f); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + return {q_out, k_out, v_out}; +} + +// Grouped linear for small batches (2..32): one launch covers up to four +// weight matrices, each weight element streamed exactly once (the +// activation tile rides in shared memory). Replaces the separate cuBLAS +// GEMMs the composite fallback issues per matrix; no weight copies. +static constexpr int GRP_MT = 32; // max batch rows +static constexpr int GRP_NT = 64; // Ada default (2 WMMA tiles per warp) +static constexpr int GRP_NT_AMPERE = 128; // A100: more smem (164KB) + bandwidth +static constexpr int GRP_KT = 128; // k-chunk staged through smem +static constexpr int GRP_TPB = 256; // threads per block (8 warps, one 16x16 tile each) +static constexpr int GRP_KT_GLU = 64; // GLU stages gate+up tiles: smaller KT fits 99KB + +constexpr int GRP_SMEM_BYTES = + (2 * GRP_MT * (GRP_KT + 8) + 2 * GRP_NT * (GRP_KT + 8)) * 2 + GRP_MT * (GRP_NT + 8) * 4; +constexpr int GRP_SMEM_BYTES_AMPERE = + (2 * GRP_MT * (GRP_KT + 8) + 2 * GRP_NT_AMPERE * (GRP_KT + 8)) * 2 + + GRP_MT * (GRP_NT_AMPERE + 8) * 4; +constexpr int GRP_GLU_SMEM_BYTES = + (2 * GRP_MT * (GRP_KT_GLU + 8) + 4 * GRP_NT * (GRP_KT_GLU + 8)) * 2 + + 2 * GRP_MT * (GRP_NT + 8) * 4; + +struct GrpSeg { + int mat; // which weight matrix + int lrow; // row within that matrix +}; + +__device__ __forceinline__ const __nv_bfloat16* wgs_ptr(int mat, + const __nv_bfloat16* w0, + const __nv_bfloat16* w1, + const __nv_bfloat16* w2, + const __nv_bfloat16* w3) +{ + return mat == 0 ? w0 : mat == 1 ? w1 : mat == 2 ? w2 : w3; +} + +__device__ __forceinline__ GrpSeg grp_map_row(int row, int f0, int f1, int f2, int f3, int n_mat) +{ + GrpSeg s{0, row}; + int fs[4] = {f0, f1, f2, f3}; + for (int i = 0; i < n_mat && i < 4; i++) { + if (s.lrow < fs[i]) { + s.mat = i; + return s; + } + s.lrow -= fs[i]; + } + s.mat = 0; // unreachable for well-formed launches + return s; +} + +template +__global__ void grouped_linear_kernel(const __nv_bfloat16* __restrict__ x, + const __nv_bfloat16* __restrict__ w0, + const __nv_bfloat16* __restrict__ w1, + const __nv_bfloat16* __restrict__ w2, + const __nv_bfloat16* __restrict__ w3, + __nv_bfloat16* __restrict__ o0, + __nv_bfloat16* __restrict__ o1, + __nv_bfloat16* __restrict__ o2, + __nv_bfloat16* __restrict__ o3, + int f0, + int f1, + int f2, + int f3, + int M, + int K, + int total_out, + int concat_mode) +{ +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 + // bf16 WMMA needs sm80+; see the note above the kernel + + using namespace nvcuda; + // dynamic smem: xs[2][MT][KT+8] | ws[2][NT][KT+8] | out_s[MT][NT+8] + extern __shared__ char smem_raw[]; + const int XS_STRIDE = GRP_KT + 8; + __nv_bfloat16* xs = reinterpret_cast<__nv_bfloat16*>(smem_raw); + __nv_bfloat16* ws = xs + 2 * GRP_MT * XS_STRIDE; + float* out_s = reinterpret_cast(ws + 2 * NT_TILE * XS_STRIDE); + __shared__ GrpSeg seg_tab[NT_TILE]; + + int tid = threadIdx.x; + int warp = tid >> 5; + int lane = tid & 31; + int n0 = blockIdx.x * NT_TILE; + if (n0 >= total_out) return; + + for (int c = tid; c < NT_TILE; c += GRP_TPB) { + seg_tab[c] = (n0 + c < total_out) ? grp_map_row(n0 + c, f0, f1, f2, f3, 4) : GrpSeg{0, 0}; + } + __syncthreads(); + + int m0w = (warp >> 2) * (GRP_MT / 2); + int n0w = (warp & 3) * 16; // one 16x16 tile per warp (8 warps = 2x4 grid) + + wmma::fragment acc; + wmma::fill_fragment(acc, 0.f); + wmma::fragment fa; + wmma::fragment fb; + + const int nchunks = (K + GRP_KT - 1) / GRP_KT; + // async-stage chunk c into buffer slot c&1; compute overlaps the next load + auto stage = [&](int c) { + int k0 = c * GRP_KT; + int kn = min(GRP_KT, K - k0); + int kn8 = kn >> 3; + __nv_bfloat16* xbuf = xs + (long)(c & 1) * GRP_MT * XS_STRIDE; + __nv_bfloat16* wbuf = ws + (long)(c & 1) * NT_TILE * XS_STRIDE; + for (int idx = tid; idx < M * kn8; idx += GRP_TPB) { + int m = idx / kn8, j = idx % kn8; + __pipeline_memcpy_async( + xbuf + (long)m * XS_STRIDE + j * 8, x + (long)m * K + k0 + (long)j * 8, 16); + } + for (int idx = tid; idx < NT_TILE * kn8; idx += GRP_TPB) { + int r = idx / kn8, j = idx % kn8; + if (n0 + r < total_out) { + GrpSeg g = seg_tab[r]; + __pipeline_memcpy_async( + wbuf + (long)r * XS_STRIDE + j * 8, + wgs_ptr(g.mat, w0, w1, w2, w3) + (long)g.lrow * K + k0 + (long)j * 8, + 16); + } + } + __pipeline_commit(); + }; + + stage(0); + for (int c = 0; c < nchunks; c++) { + if (c + 1 < nchunks) stage(c + 1); + __pipeline_wait_prior(c + 1 < nchunks ? 1 : 0); + __syncthreads(); + int kn = min(GRP_KT, K - c * GRP_KT); + if (kn < GRP_KT) { + // partial final chunk: zero the tail so wmma sees zeros + __nv_bfloat16* xbuf = xs + (long)(c & 1) * GRP_MT * XS_STRIDE; + __nv_bfloat16* wbuf = ws + (long)(c & 1) * NT_TILE * XS_STRIDE; + for (int idx = tid; idx < GRP_MT * GRP_KT; idx += GRP_TPB) { + int r = idx / GRP_KT, cc = idx % GRP_KT; + if (cc >= kn && r < M) xbuf[r * XS_STRIDE + cc] = __float2bfloat16_rn(0.f); + } + for (int idx = tid; idx < NT_TILE * GRP_KT; idx += GRP_TPB) { + int r = idx / GRP_KT, cc = idx % GRP_KT; + if (cc >= kn && n0 + r < total_out) + wbuf[r * XS_STRIDE + cc] = __float2bfloat16_rn(0.f); + } + __syncthreads(); + } + __nv_bfloat16* xbuf = xs + (long)(c & 1) * GRP_MT * XS_STRIDE; + __nv_bfloat16* wbuf = ws + (long)(c & 1) * NT_TILE * XS_STRIDE; +#pragma unroll 4 + for (int kk = 0; kk < GRP_KT; kk += 16) { + wmma::load_matrix_sync(fa, xbuf + m0w * XS_STRIDE + kk, XS_STRIDE); + wmma::load_matrix_sync(fb, wbuf + n0w * XS_STRIDE + kk, XS_STRIDE); + wmma::mma_sync(acc, fa, fb, acc); + } + __syncthreads(); + } + + wmma::store_matrix_sync( + out_s + m0w * (NT_TILE + 8) + n0w, acc, NT_TILE + 8, wmma::mem_row_major); + __syncthreads(); + + __nv_bfloat16* ogs[4] = {o0, o1, o2, o3}; + int fs2[4] = {f0, f1, f2, f3}; + for (int idx = tid; idx < M * NT_TILE; idx += GRP_TPB) { + int m = idx / NT_TILE, c = idx % NT_TILE; + if (n0 + c >= total_out) continue; + GrpSeg g = seg_tab[c]; + float v = out_s[m * (NT_TILE + 8) + c]; + __nv_bfloat16* o = ogs[g.mat]; + if (concat_mode) { + int base = 0; + for (int i = 0; i < g.mat; i++) base += fs2[i]; + o[(long)m * total_out + base + g.lrow] = __float2bfloat16_rn(v); + } else { + o[(long)m * fs2[g.mat] + g.lrow] = __float2bfloat16_rn(v); + } + } +#endif +} + +// Paired-matrix GLU GEMM: out = silu(x@g^T) * (x@u^T). cp.async tile +// stream: per k-chunk two weight tiles (gate, up) flow through a double +// buffer while the x tile rides its own pair; compute overlaps loads. +template +__global__ void glu_gemm_kernel(const __nv_bfloat16* __restrict__ x, + const __nv_bfloat16* __restrict__ g_w, + const __nv_bfloat16* __restrict__ u_w, + __nv_bfloat16* __restrict__ out, + int M, + int N, + int K) +{ +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 + // bf16 WMMA needs sm80+; see the note above the kernel + + using namespace nvcuda; + // dynamic smem: xs[2][MT][KT+8] | ws[2][NT][KT+8] | out_s, out_u [MT][NT+8] + extern __shared__ char smem_raw[]; + const int XS_STRIDE = GRP_KT_GLU + 8; + __nv_bfloat16* xs = reinterpret_cast<__nv_bfloat16*>(smem_raw); + __nv_bfloat16* ws = xs + 2 * GRP_MT * XS_STRIDE; + // ws holds 2 slots x (gate,up) tiles = 4*NT rows before the outputs + float* out_s = reinterpret_cast(ws + 4 * NT_TILE * XS_STRIDE); + float* out_u = out_s + GRP_MT * (NT_TILE + 8); + + int tid = threadIdx.x; + int warp = tid >> 5; + int n0 = blockIdx.x * NT_TILE; + if (n0 >= N) return; + int m0w = (warp >> 2) * (GRP_MT / 2); + int n0w = (warp & 3) * 16; + + wmma::fragment accg, accu; + wmma::fill_fragment(accg, 0.f); + wmma::fill_fragment(accu, 0.f); + wmma::fragment fa; + wmma::fragment fb; + + const int nchunks = (K + GRP_KT_GLU - 1) / GRP_KT_GLU; + // stage chunk c: x into xs[c&1], gate tile into ws[0], up tile into ws[1] + // (both weight tiles for the chunk issue together; the slot pair rotates + // per chunk so chunk c+1 lands while chunk c computes) + auto stage = [&](int c) { + int k0 = c * GRP_KT_GLU; + int kn = min(GRP_KT_GLU, K - k0); + int kn8 = kn >> 3; + __nv_bfloat16* xbuf = xs + (long)(c & 1) * GRP_MT * XS_STRIDE; + __nv_bfloat16* gw_buf = ws + (long)(c & 1) * 2 * NT_TILE * XS_STRIDE; + __nv_bfloat16* uw_buf = gw_buf + (long)NT_TILE * XS_STRIDE; + for (int idx = tid; idx < M * kn8; idx += GRP_TPB) { + int m = idx / kn8, j = idx % kn8; + __pipeline_memcpy_async( + xbuf + (long)m * XS_STRIDE + j * 8, x + (long)m * K + k0 + (long)j * 8, 16); + } + for (int idx = tid; idx < NT_TILE * kn8; idx += GRP_TPB) { + int r = idx / kn8, j = idx % kn8; + if (n0 + r < N) { + __pipeline_memcpy_async(gw_buf + (long)r * XS_STRIDE + j * 8, + g_w + (long)(n0 + r) * K + k0 + (long)j * 8, + 16); + __pipeline_memcpy_async(uw_buf + (long)r * XS_STRIDE + j * 8, + u_w + (long)(n0 + r) * K + k0 + (long)j * 8, + 16); + } + } + if (kn < GRP_KT_GLU) { + // partial chunk: zero tails (plain stores; synced below) + for (int idx = tid; idx < GRP_MT * GRP_KT_GLU; idx += GRP_TPB) { + int r = idx / GRP_KT_GLU, cc = idx % GRP_KT_GLU; + if (cc >= kn && r < M) xbuf[r * XS_STRIDE + cc] = __float2bfloat16_rn(0.f); + } + for (int idx = tid; idx < 2 * NT_TILE * GRP_KT_GLU; idx += GRP_TPB) { + int r = idx / GRP_KT_GLU, cc = idx % GRP_KT_GLU; + if (cc >= kn && n0 + (r % NT_TILE) < N) + gw_buf[r * XS_STRIDE + cc] = __float2bfloat16_rn(0.f); + } + } + __pipeline_commit(); + }; + + stage(0); + for (int c = 0; c < nchunks; c++) { + if (c + 1 < nchunks) stage(c + 1); + __pipeline_wait_prior(c + 1 < nchunks ? 1 : 0); + __syncthreads(); + __nv_bfloat16* xbuf = xs + (long)(c & 1) * GRP_MT * XS_STRIDE; + __nv_bfloat16* gw_buf = ws + (long)(c & 1) * 2 * NT_TILE * XS_STRIDE; + __nv_bfloat16* uw_buf = gw_buf + (long)NT_TILE * XS_STRIDE; +#pragma unroll 4 + for (int kk = 0; kk < GRP_KT_GLU; kk += 16) { + wmma::load_matrix_sync(fa, xbuf + m0w * XS_STRIDE + kk, XS_STRIDE); + wmma::load_matrix_sync(fb, gw_buf + n0w * XS_STRIDE + kk, XS_STRIDE); + wmma::mma_sync(accg, fa, fb, accg); + } +#pragma unroll 4 + for (int kk = 0; kk < GRP_KT_GLU; kk += 16) { + wmma::load_matrix_sync(fa, xbuf + m0w * XS_STRIDE + kk, XS_STRIDE); + wmma::load_matrix_sync(fb, uw_buf + n0w * XS_STRIDE + kk, XS_STRIDE); + wmma::mma_sync(accu, fa, fb, accu); + } + __syncthreads(); + } + + wmma::store_matrix_sync( + out_s + m0w * (NT_TILE + 8) + n0w, accg, NT_TILE + 8, wmma::mem_row_major); + wmma::store_matrix_sync( + out_u + m0w * (NT_TILE + 8) + n0w, accu, NT_TILE + 8, wmma::mem_row_major); + __syncthreads(); + + for (int idx = tid; idx < M * NT_TILE; idx += GRP_TPB) { + int m = idx / NT_TILE, c = idx % NT_TILE; + if (n0 + c < N) { + float v = silu_f(out_s[m * (NT_TILE + 8) + c]) * out_u[m * (NT_TILE + 8) + c]; + out[(long)m * N + n0 + c] = __float2bfloat16_rn(v); + } + } +#endif +} + +std::vector grouped_gemm_impl(at::Tensor x, + at::Tensor w0, + at::Tensor w1, + at::Tensor w2, + at::Tensor w3, + int64_t n_mat, + bool want_separate) +{ + TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::ScalarType::BFloat16, "x must be CUDA bf16"); + TORCH_CHECK(x.is_contiguous(), "x must be contiguous"); + TORCH_CHECK(x.dim() == 2 && x.size(0) > 1 && x.size(0) <= GRP_MT, "batch must be 2..32"); + int M = (int)x.size(0), K = (int)x.size(1); + at::Tensor ws[4] = {w0, w1, w2, w3}; + // the vectorized smem staging does 16-byte transactions + TORCH_CHECK(K % 8 == 0, "K must be a multiple of 8"); + TORCH_CHECK((reinterpret_cast(x.data_ptr()) & 15) == 0, + "x pointer must be 16B aligned"); + for (int i = 0; i < n_mat; i++) { + TORCH_CHECK(ws[i].is_cuda() && ws[i].scalar_type() == at::ScalarType::BFloat16, + "weights must be CUDA bf16"); + TORCH_CHECK(ws[i].is_contiguous(), "weights must be contiguous"); + TORCH_CHECK(ws[i].size(1) == K, "weight K mismatch"); + TORCH_CHECK((reinterpret_cast(ws[i].data_ptr()) & 15) == 0, + "weight pointer must be 16B aligned"); + } + int fs[4] = {0, 0, 0, 0}; + int total = 0; + for (int i = 0; i < n_mat; i++) { + fs[i] = (int)ws[i].size(0); + total += fs[i]; + } + auto stream = at::cuda::getCurrentCUDAStream(); + int blocks = (total + GRP_NT - 1) / GRP_NT; // grid covers both variants + auto opts = x.options(); + std::vector outs; + at::Tensor o0, o1, o2, o3; + if (want_separate) { + for (int i = 0; i < n_mat; i++) outs.push_back(at::empty({M, fs[i]}, opts)); + o0 = n_mat > 0 ? outs[0] : at::Tensor(); + o1 = n_mat > 1 ? outs[1] : at::Tensor(); + o2 = n_mat > 2 ? outs[2] : at::Tensor(); + o3 = n_mat > 3 ? outs[3] : at::Tensor(); + } else { + o0 = at::empty({M, total}, opts); + outs.push_back(o0); + } + at::Tensor dummy = o0.defined() ? o0 : x; // unused slots point at a live buffer + static bool grp_attr_set = false; + if (!grp_attr_set) { + cudaFuncSetAttribute(grouped_linear_kernel, + cudaFuncAttributeMaxDynamicSharedMemorySize, + GRP_SMEM_BYTES); + grp_attr_set = true; + } + grouped_linear_kernel<<>>( + (const __nv_bfloat16*)x.data_ptr(), + (const __nv_bfloat16*)(n_mat > 0 ? w0 : dummy).data_ptr(), + (const __nv_bfloat16*)(n_mat > 1 ? w1 : dummy).data_ptr(), + (const __nv_bfloat16*)(n_mat > 2 ? w2 : dummy).data_ptr(), + (const __nv_bfloat16*)(n_mat > 3 ? w3 : dummy).data_ptr(), + (__nv_bfloat16*)(want_separate && o0.defined() ? o0 : o0).data_ptr(), + (__nv_bfloat16*)(want_separate && o1.defined() ? o1 : o0).data_ptr(), + (__nv_bfloat16*)(want_separate && o2.defined() ? o2 : o0).data_ptr(), + (__nv_bfloat16*)(want_separate && o3.defined() ? o3 : o0).data_ptr(), + fs[0], + fs[1], + fs[2], + fs[3], + M, + K, + total, + want_separate ? 0 : 1); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + return outs; +} + +// Single-token gated-delta-rule recurrent update, IN PLACE on the cache +// state. Mirrors FLA's fused_recurrent_gated_delta_rule for T=1 with +// precomputed beta/g and in-kernel qk-l2norm; the state rides in shared +// memory so the four passes (FLA read+write, HF copy-back read+write) +// collapse to one read + one write. +__global__ void gdn_recurrent_step_kernel(const __nv_bfloat16* __restrict__ q, + const __nv_bfloat16* __restrict__ k, + const __nv_bfloat16* __restrict__ v, + const __nv_bfloat16* __restrict__ g, + const __nv_bfloat16* __restrict__ beta, + float* __restrict__ state, + __nv_bfloat16* __restrict__ out, + int K, + int V) +{ + // Only q/k/v stage in shared memory (~1.5KB); the state streams + // straight from global. Columns are independent, so the 64KB smem + // staging of the original version only capped occupancy at 2 + // blocks/SM on A100 — removing it raises residency ~8x and lets the + // coalesced per-row segments (h[i*V + j..j+31]) saturate bandwidth. + extern __shared__ float smem[]; // q[K], k[K], v[V] + float* qs = smem; + float* ks = qs + K; + float* vs = ks + K; + + const int bh = blockIdx.x; // (batch, v-head) flattened + const int tid = threadIdx.x; + const float scale = rsqrtf((float)K); + float* g_state = state + (long)bh * K * V; + for (int i = tid; i < K; i += blockDim.x) { + qs[i] = __bfloat162float(q[(long)bh * K + i]); + ks[i] = __bfloat162float(k[(long)bh * K + i]); + } + for (int i = tid; i < V; i += blockDim.x) vs[i] = __bfloat162float(v[(long)bh * V + i]); + __syncthreads(); + + // l2-normalize q (scaled) and k; eps matches FLA + __shared__ float s_red[2]; + if (tid == 0) { + s_red[0] = 0.f; + s_red[1] = 0.f; + } + __syncthreads(); + float sq = 0.f, sk = 0.f; + for (int i = tid; i < K; i += blockDim.x) { + sq += qs[i] * qs[i]; + sk += ks[i] * ks[i]; + } + atomicAdd(&s_red[0], sq); + atomicAdd(&s_red[1], sk); + __syncthreads(); + const float inv_qq = rsqrtf(s_red[0] + 1e-6f) * scale; + const float inv_kk = rsqrtf(s_red[1] + 1e-6f); + + const float decay = __expf(__bfloat162float(g[bh])); + const float b_beta = __bfloat162float(beta[bh]); + + // one thread per state column j: kv = k^T (decay*h), then the + // outer-add update and the output dot, reading/writing the column's + // state elements directly (each warp covers one contiguous row + // segment per iteration — fully coalesced) + if (tid < V) { + const int j = tid; + float kv = 0.f; + for (int i = 0; i < K; i++) kv += ks[i] * g_state[i * V + j]; + kv *= decay * inv_kk; + const float bvj = b_beta * (vs[j] - kv); + float o = 0.f; + for (int i = 0; i < K; i++) { + const float khat = ks[i] * inv_kk; + const float hij = decay * g_state[i * V + j] + khat * bvj; + g_state[i * V + j] = hij; + o += qs[i] * inv_qq * hij; + } + out[(long)bh * V + j] = __float2bfloat16_rn(o); + } +} + +void gdn_recurrent_step(at::Tensor q, + at::Tensor k, + at::Tensor v, + at::Tensor g, + at::Tensor beta, + at::Tensor state, + at::Tensor out) +{ + TORCH_CHECK(q.is_cuda() && q.scalar_type() == at::ScalarType::BFloat16, "q must be CUDA bf16"); + TORCH_CHECK(q.is_contiguous() && k.is_contiguous() && v.is_contiguous(), + "q/k/v must be contiguous"); + TORCH_CHECK(state.is_contiguous() && state.scalar_type() == at::ScalarType::Float, + "state must be fp32 contiguous"); + const int B = (int)q.size(0), H = (int)q.size(1), K = (int)q.size(2), V = (int)v.size(2); + TORCH_CHECK(k.sizes() == q.sizes() && v.size(0) == B && v.size(1) == H && v.size(2) == V, + "shape mismatch"); + TORCH_CHECK( + state.size(0) == B && state.size(1) == H && state.size(2) == K && state.size(3) == V, + "state must be [B,H,K,V]"); + TORCH_CHECK(V <= 1024, "V must fit one-thread-per-column"); + const int smem = (2 * K + V) * 4; + auto stream = at::cuda::getCurrentCUDAStream(); + gdn_recurrent_step_kernel<<>>( + (const __nv_bfloat16*)q.data_ptr(), + (const __nv_bfloat16*)k.data_ptr(), + (const __nv_bfloat16*)v.data_ptr(), + (const __nv_bfloat16*)g.data_ptr(), + (const __nv_bfloat16*)beta.data_ptr(), + (float*)state.data_ptr(), + (__nv_bfloat16*)out.data_ptr(), + K, + V); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +py::dict segki_capabilities() +{ + py::dict d; + d["version"] = 1; + d["dtypes"] = py::make_tuple("bf16"); + d["max_grouped_batch"] = GRP_MT; // above this the dispatcher routes to aten + d["fused_glu_epilogue"] = true; + d["fused_rope_q"] = true; + d["fused_rope_k"] = true; + d["fused_cache_write"] = true; + d["inplace_recurrent"] = true; + return d; +} + +at::Tensor single_gemm(at::Tensor x, at::Tensor w) +{ + return grouped_gemm_impl(x, w, w, w, w, 1, true)[0]; +} + +std::vector triple_gemm(at::Tensor x, at::Tensor qw, at::Tensor kw, at::Tensor vw) +{ + return grouped_gemm_impl(x, qw, kw, vw, qw, 3, true); +} + +at::Tensor quad_gemm(at::Tensor x, at::Tensor w_qkv, at::Tensor w_z, at::Tensor w_b, at::Tensor w_a) +{ + return grouped_gemm_impl(x, w_qkv, w_z, w_b, w_a, 4, false)[0]; +} + +at::Tensor dual_gemm_silu_mul(at::Tensor x, at::Tensor gate_w, at::Tensor up_w) +{ + TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::ScalarType::BFloat16, "x must be CUDA bf16"); + TORCH_CHECK(x.is_contiguous() && gate_w.is_contiguous() && up_w.is_contiguous(), + "inputs must be contiguous"); + TORCH_CHECK(x.dim() == 2 && x.size(0) > 1 && x.size(0) <= GRP_MT, "batch must be 2..32"); + int M = (int)x.size(0), K = (int)x.size(1), N = (int)gate_w.size(0); + TORCH_CHECK(K % 8 == 0, "K must be a multiple of 8"); + TORCH_CHECK((reinterpret_cast(x.data_ptr()) & 15) == 0 && + (reinterpret_cast(gate_w.data_ptr()) & 15) == 0 && + (reinterpret_cast(up_w.data_ptr()) & 15) == 0, + "inputs must be 16B aligned"); + TORCH_CHECK(up_w.size(0) == N && gate_w.size(1) == K && up_w.size(1) == K, "shape mismatch"); + auto out = at::empty({M, N}, x.options()); + auto stream = at::cuda::getCurrentCUDAStream(); + int blocks = (N + GRP_NT - 1) / GRP_NT; + static bool glu_attr_set = false; + if (!glu_attr_set) { + cudaFuncSetAttribute(glu_gemm_kernel, + cudaFuncAttributeMaxDynamicSharedMemorySize, + GRP_GLU_SMEM_BYTES); + glu_attr_set = true; + } + glu_gemm_kernel<<>>( + (const __nv_bfloat16*)x.data_ptr(), + (const __nv_bfloat16*)gate_w.data_ptr(), + (const __nv_bfloat16*)up_w.data_ptr(), + (__nv_bfloat16*)out.data_ptr(), + M, + N, + K); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + return out; +} + +namespace { +// GLU epilogue as a standalone native kernel: bf16 in/out, fp32 +// sigmoid in registers — no dtype round-trip through gmem. +__global__ void silu_mul_kernel(const __nv_bfloat16* __restrict__ gu, + __nv_bfloat16* __restrict__ out, + long long rows, + int n) +{ + long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + const long long total = rows * n; + for (; i < total; i += (long long)gridDim.x * blockDim.x) { + const long long r = i / n; + const int j = (int)(i % n); + const long long base = r * 2 * n; + const float g = __bfloat162float(gu[base + j]); + const float u = __bfloat162float(gu[base + n + j]); + out[i] = __float2bfloat16(g / (1.0f + __expf(-g)) * u); + } +} +} // namespace + +at::Tensor silu_mul(at::Tensor gu, int64_t n) +{ + auto out = at::empty({gu.size(0), n}, gu.options()); + const long long total = (long long)gu.size(0) * n; + auto stream = at::cuda::getCurrentCUDAStream(); + const int blocks = (int)((total + 255) / 256); + silu_mul_kernel<<>>( + (const __nv_bfloat16*)gu.data_ptr(), (__nv_bfloat16*)out.data_ptr(), gu.size(0), (int)n); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + return out; +} + +// Pointer-keyed cache of concatenated GLU weights (see grouped_linear). +// In-place weight writes (arena/reshard syncs) keep their addresses, so +// the sync path calls clear_glu_cat_cache() to drop stale concats. +struct PairKey { + uint64_t a, b; + bool operator==(const PairKey& o) const { return a == o.a && b == o.b; } +}; +struct PairHash { + size_t operator()(const PairKey& k) const { return std::hash()(k.a ^ (k.b << 1)); } +}; +static std::unordered_map g_glu_cat_cache; + +void clear_glu_cat_cache() { g_glu_cat_cache.clear(); } + +// Arch-adaptive batch routing threshold: on Ada the WMMA grouped kernel +// beats cuBLAS for M<=32 (launch overhead dominates); on Ampere cuBLAS +// is fast enough to win at any M>1 (profiled on A100 SXM4: our WMMA at +// 39.7% of step vs cuBLAS composite scaling better). Same interface, +// same kernels — only the crossover point moves. +static int64_t grouped_wmma_threshold() +{ + static int64_t thr = -1; + if (thr < 0) { + int dev; + cudaGetDevice(&dev); + int smem; + cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + thr = (smem > 100 * 1024) ? 1 : GRP_MT; // Ampere -> 1, Ada -> GRP_MT + } + return thr; +} + +// Portable segKI interface: one dispatcher routes by weight count and +// batch size to this backend's private kernels (gemv / WMMA grouped / +// aten composite), so other accelerators can expose the same entry with +// an entirely different internal split. +std::vector grouped_linear(at::Tensor x, + std::vector weights, + bool glu_epilogue) +{ + const size_t n = weights.size(); + TORCH_CHECK(n >= 1 && n <= 6, "grouped_linear takes 1..6 weight matrices"); + if (n == 6) { + // TP block-sliced GDN in_proj [q, k, v, z, b, a]: route through this + // interface so TP=1 (fused 4-mat) and TP=2 (block-sliced 6-mat) + // share one dispatch path in the forward + auto qkv = grouped_linear(x, {weights[0], weights[1], weights[2]}, false); + auto zba = grouped_linear(x, {weights[3], weights[4], weights[5]}, false); + at::Tensor fused = at::cat({qkv[0], qkv[1], qkv[2], zba[0], zba[1], zba[2]}, -1); + return {fused}; + } + const int64_t K = weights[0].size(1); + // M == 1 rides the flat GEMV kernels (1-D input or a single row) + if (x.numel() == K) { + at::Tensor flat = x.reshape({-1}); + if (glu_epilogue && n == 2) { + auto out = at::empty({weights[0].size(0)}, x.options()); + dual_gemv_silu_mul(flat, weights[0], weights[1], out); + return {out}; + } + if (!glu_epilogue && n == 3) return triple_gemv(flat, weights[0], weights[1], weights[2]); + if (!glu_epilogue && n == 4) { + auto out = at::empty( + {weights[0].size(0) + weights[1].size(0) + weights[2].size(0) + weights[3].size(0)}, + x.options()); + quad_gemv(flat, weights[0], weights[1], weights[2], weights[3], out); + return {out}; + } + // n == 1 or n == 2 without epilogue: aten composite + std::vector outs; + for (auto& w : weights) outs.push_back(at::matmul(flat, w.t())); + if (glu_epilogue && n == 2) { + at::Tensor g = at::silu(outs[0].to(at::kFloat)).to(outs[0].scalar_type()); + outs = {g * outs[1]}; + } + if (!glu_epilogue && n == 4) outs = {at::cat(outs, -1)}; // quad contract: concatenated + return outs; + } + at::Tensor x2 = x.reshape({-1, K}); + const int64_t M = x2.size(0); + // GLU routing by architecture (the dispatcher owns the choice): + // - Ampere: one wide cuBLAS GEMM over the concat-cached gate|up weight + // plus the native silu_mul epilogue — cuBLAS tiles [M,2N,K] better + // than our WMMA at these shapes and silu_mul costs one tiny kernel + // (no fp32 round-trip, unlike the composite compared in loop 3). + // - Ada: the WMMA fused kernel keeps the in-register epilogue (it wins + // there); M in (GRP_MT, 2*GRP_MT] rides two row-chunked calls. + if (glu_epilogue && n == 2) { + if (grouped_wmma_threshold() > 1) { + if (M <= GRP_MT) return {dual_gemm_silu_mul(x2, weights[0], weights[1])}; + if (M <= 2 * GRP_MT) { + const int64_t half = GRP_MT; + at::Tensor out = at::empty({M, weights[0].size(0)}, x2.options()); + auto o1 = dual_gemm_silu_mul(x2.narrow(0, 0, half), weights[0], weights[1]); + auto o2 = dual_gemm_silu_mul(x2.narrow(0, half, M - half), weights[0], weights[1]); + out.narrow(0, 0, half).copy_(o1); + out.narrow(0, half, M - half).copy_(o2); + return {out}; + } + } else { + // Ampere: weights are static across the rollout — cache the + // concatenated [gate; up] matrix keyed by the weight pointers + // (g_glu_cat_cache; cleared by clear_glu_cat_cache() when an + // arena/reshard sync writes weights in place) + const PairKey key{(uint64_t)(uintptr_t)weights[0].data_ptr(), + (uint64_t)(uintptr_t)weights[1].data_ptr()}; + auto it = g_glu_cat_cache.find(key); + if (it == g_glu_cat_cache.end()) { + auto cat = at::cat({weights[0], weights[1]}, 0).contiguous(); + it = g_glu_cat_cache.emplace(key, cat).first; + } + auto gu = at::matmul(x2, it->second.t()); + return {silu_mul(gu, weights[0].size(0))}; + } + } + if (M > grouped_wmma_threshold()) { + // large batches: cuBLAS/aten composite (this backend's measured choice) + std::vector outs; + for (auto& w : weights) outs.push_back(at::matmul(x2, w.t())); + if (glu_epilogue && n == 2) { + at::Tensor g = at::silu(outs[0].to(at::kFloat)).to(outs[0].scalar_type()); + outs = {g * outs[1]}; + } + if (!glu_epilogue && n == 4) outs = {at::cat(outs, -1)}; // quad contract: concatenated + return outs; + } + TORCH_CHECK(x2.is_contiguous(), "grouped_linear needs a contiguous [M,K] view"); + if (glu_epilogue && n == 2) return {dual_gemm_silu_mul(x2, weights[0], weights[1])}; + if (!glu_epilogue && n == 3) return triple_gemm(x2, weights[0], weights[1], weights[2]); + if (!glu_epilogue && n == 4) + return {quad_gemm(x2, weights[0], weights[1], weights[2], weights[3])}; + if (!glu_epilogue && n == 1) return {single_gemm(x2, weights[0])}; + // glu with n != 2 or multi-output without epilogue at n == 2: composite + std::vector outs; + for (auto& w : weights) outs.push_back(at::matmul(x2, w.t())); + if (glu_epilogue && n == 2) { + at::Tensor g = at::silu(outs[0].to(at::kFloat)).to(outs[0].scalar_type()); + outs = {g * outs[1]}; + } + return outs; +} + +namespace { +// Head-repeat for the GDN scan's v-head layout: out[b,s,hv,d] = in[b,s,hv/ratio,d]. +// One launch covers BOTH q and k (idx space 2*total), replacing two eager +// repeat_interleave copies per layer. +__global__ void repeat_qk_kernel(const __nv_bfloat16* __restrict__ q, + const __nv_bfloat16* __restrict__ k, + __nv_bfloat16* __restrict__ q_out, + __nv_bfloat16* __restrict__ k_out, + long long src_rows, + int dk, + int hv, + int ratio, + long long total) +{ + long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x; + const bool is_k = idx >= total; + const long long i = is_k ? idx - total : idx; + if (i >= total) return; + const int d = (int)(i % dk); + long long t = i / dk; + const int h = (int)(t % hv); + t /= hv; // flat [B*S] row + const long long src = (t * src_rows + h / ratio) * dk + d; + if (is_k) + k_out[i] = k[src]; + else + q_out[i] = q[src]; +} +} // namespace + +std::vector repeat_qk(at::Tensor q, at::Tensor k, int64_t ratio) +{ + const auto sz = q.sizes(); + TORCH_CHECK(q.is_contiguous() && k.is_contiguous(), "repeat_qk needs contiguous q/k"); + const long long B = sz[0], S = sz[1], Hk = sz[2]; + const int dk = (int)sz[3]; + const int hv = (int)(Hk * ratio); + auto q_out = at::empty({B, S, (long long)hv, (long long)dk}, q.options()); + auto k_out = at::empty_like(q_out); + const long long total = B * S * hv * dk; + auto stream = at::cuda::getCurrentCUDAStream(); + const int blocks = (int)((2 * total + 255) / 256); + repeat_qk_kernel<<>>((const __nv_bfloat16*)q.data_ptr(), + (const __nv_bfloat16*)k.data_ptr(), + (__nv_bfloat16*)q_out.data_ptr(), + (__nv_bfloat16*)k_out.data_ptr(), + Hk, + dk, + hv, + (int)ratio, + total); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + return {q_out, k_out}; +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) +{ + // two explicit overloads: at::Tensor() pybind defaults proved fragile + // in this toolchain (the 9-arg call failed to bind) + m.def( + "decode_attn", + [](at::Tensor q, + at::Tensor K, + at::Tensor V, + at::Tensor write_pos, + at::Tensor out, + int64_t num_q_heads, + int64_t num_kv_heads, + int64_t head_dim, + int64_t max_len) { + return decode_attn(q, + K, + V, + write_pos, + out, + num_q_heads, + num_kv_heads, + head_dim, + max_len, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + 1e-6, + 0); + }, + "batched decode attention (GQA, valid-length)", + py::arg("q"), + py::arg("K"), + py::arg("V"), + py::arg("write_pos"), + py::arg("out"), + py::arg("num_q_heads"), + py::arg("num_kv_heads"), + py::arg("head_dim"), + py::arg("max_len")); + m.def("grouped_linear", + &grouped_linear, + "portable segKI projection: 1..4 original weight matrices, one " + "launch per group, GLU epilogue optional; routes internally by " + "batch to gemv / grouped WMMA / aten composite", + py::arg("x"), + py::arg("weights"), + py::arg("glu_epilogue") = false); + m.def("repeat_qk", &repeat_qk, "fused q/k head-repeat for the scan (one launch)"); + m.def("silu_mul", &silu_mul, "native GLU epilogue: silu(g)*u from a [M,2N] buffer"); + m.def("clear_glu_cat_cache", + &clear_glu_cat_cache, + "drop stale concat caches after in-place weight writes"); + m.def("capabilities", &segki_capabilities, "segKI backend capability report"); + m.def("gdn_recurrent_step", + &gdn_recurrent_step, + "in-place single-token gated-delta-rule recurrent update", + py::arg("q"), + py::arg("k"), + py::arg("v"), + py::arg("g"), + py::arg("beta"), + py::arg("state"), + py::arg("out")); + m.def("decode_attn", + &decode_attn, + "batched decode attention (GQA, valid-length, fused q-norm/rope/gate)", + py::arg("q"), + py::arg("K"), + py::arg("V"), + py::arg("write_pos"), + py::arg("out"), + py::arg("num_q_heads"), + py::arg("num_kv_heads"), + py::arg("head_dim"), + py::arg("max_len"), + py::arg("q_norm_w"), + py::arg("cos_t"), + py::arg("sin_t"), + py::arg("gate"), + py::arg("k_raw"), + py::arg("v_raw"), + py::arg("k_norm_w"), + py::arg("eps"), + py::arg("rope_dim")); + m.def("decode_step_graph", &decode_step_graph, "graph-capturable decode step (CUDA)"); + m.def("gdn_gates", &gdn_gates, "fused GDN beta/g gating (CUDA)"); + m.def("fused_add_norm", + &fused_add_norm, + "fused residual add + RMSNorm, in-place residual update (CUDA)"); + m.def( + "gated_norm", + [](at::Tensor x, at::Tensor z, at::Tensor w, at::Tensor out, double eps) { + TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::ScalarType::BFloat16, + "x must be CUDA bf16"); + TORCH_CHECK( + x.is_contiguous() && z.is_contiguous() && w.is_contiguous() && out.is_contiguous(), + "inputs must be contiguous"); + TORCH_CHECK( + z.numel() == x.numel() && out.numel() == x.numel() && w.numel() == x.size(-1), + "shape mismatch"); + int64_t rows = x.numel() / x.size(-1); + int dim = (int)x.size(-1); + TORCH_CHECK((int64_t)dim * sizeof(float) <= 48 * 1024, + "dim too large for shared memory"); + auto stream = at::cuda::getCurrentCUDAStream(); + int threads = std::min(1024, ((dim + 31) / 32) * 32); + if (threads == 0) threads = 32; + gated_norm_kernel<<<(int)rows, threads, (size_t)dim * sizeof(float), stream>>>( + reinterpret_cast(x.data_ptr()), + reinterpret_cast(z.data_ptr()), + reinterpret_cast(w.data_ptr()), + reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), + (float)eps, + dim); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }, + "GDN z-gated output norm: (w * rms(x)) * silu(z)", + py::arg("x"), + py::arg("z"), + py::arg("w"), + py::arg("out"), + py::arg("eps")); +} diff --git a/deepspeed/module_inject/kernel_reference.py b/deepspeed/module_inject/kernel_reference.py new file mode 100644 index 000000000000..ca6bb24fc847 --- /dev/null +++ b/deepspeed/module_inject/kernel_reference.py @@ -0,0 +1,104 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +"""Reference implementations (executable specifications) for segment-KI kernels. + +Each function here defines the mathematically correct output for its +corresponding interface method (the m.def entries on the loaded extension). +Custom kernels (CUDA today, SYCL/XPU in the future) must produce results +equivalent to these functions within bf16 tolerance. Three roles in one: + +1. **Specification**: an agent porting kernels to a new backend reads these + to understand what each interface method must compute. +2. **Runtime fallback**: the forward paths in segment_ki call these when no + custom kernel is available (e.g. CPU-only, XPU without compiled kernels). +3. **Test oracle**: unit tests compare custom kernel output against these + functions on identical inputs. + +All implementations use only standard PyTorch ops — no custom kernels — so +they are correct by construction and run on any device. +""" + +import math + +import torch +import torch.nn.functional as F + + +def grouped_linear(x, weights, glu_epilogue=False): + """Unified projection: matmul against each weight, optional GLU epilogue. + + The portable interface's single entry point for all GEMV/GEMM paths + (flat single-row, small-batch grouped, large-batch composite). Returns + a list of per-weight outputs; the GLU variant folds silu(gate)*up into + the first output. + """ + outs = [F.linear(x, w) for w in weights] + if glu_epilogue: + # bf16-native silu: bitwise-equal to HF's activation (the fp32 + # decomposition rounds differently) and skips its extra casts + outs = [F.silu(outs[0]) * outs[1]] + return outs + + +def gdn_gates(a, b, a_log, dt_bias): + """GDN gating: beta = sigmoid(b), g = -exp(a_log) * softplus(a + dt_bias).""" + beta = torch.sigmoid(b) + g = -torch.exp(a_log.float()) * F.softplus(a.float() + dt_bias.float()) + return beta, g.to(b.dtype) + + +def decode_attn(q, K, V, pos): + """Single-query attention over valid KV positions, batched. + + q: [b, num_heads, head_dim] + K, V: [b, num_kv_heads, max_len, head_dim] + pos: int or LongTensor [b] (valid positions, 0-indexed inclusive; + an int applies to every row) + + Returns [b, num_heads, head_dim] with GQA (K/V heads shared across query + heads). + """ + num_q_heads = q.shape[-2] + num_kv_heads = K.shape[-3] + head_dim = q.shape[-1] + n_rep = num_q_heads // num_kv_heads + scale = 1.0 / math.sqrt(head_dim) + + lens = (pos + 1).tolist() if torch.is_tensor(pos) else [pos + 1] * q.shape[0] + out = torch.empty(q.shape, dtype=torch.float32, device=q.device) + for r in range(q.shape[0]): + K_valid = K[r, :, :lens[r], :] # [nkv, len, hd] + V_valid = V[r, :, :lens[r], :] + if n_rep > 1: + K_valid = K_valid.repeat_interleave(n_rep, dim=0) + V_valid = V_valid.repeat_interleave(n_rep, dim=0) + scores = torch.einsum('hd,hld->hl', q[r].float(), K_valid.float()) * scale + weights = torch.softmax(scores, dim=-1) + out[r] = torch.einsum('hl,hld->hd', weights, V_valid.float()) + return out.to(q.dtype) + + +def silu_mul(gu, n): + """GLU epilogue on a [M, 2n] buffer: silu(g) * u.""" + g = gu[:, :n].float() + u = gu[:, n:].float() + return (g / (1.0 + torch.exp(-g)) * u).to(gu.dtype) + + +def repeat_qk(q, k, ratio): + """Head-repeat for the GDN scan's v-head layout: out[...,hv,:] = in[...,hv/ratio,:].""" + return q.repeat_interleave(ratio, dim=-2), k.repeat_interleave(ratio, dim=-2) + + +def gated_norm(x, z, weight, eps=1e-5): + """GDN z-gated output norm: (weight * rms(x)) * silu(z), weight direct.""" + xf = x.float() + xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps) + return (xf * weight.float() * torch.nn.functional.silu(z.float())).to(x.dtype) + + +def fused_add_norm(hidden, residual, weight, eps=1e-5): + """Residual add + RMSNorm: rms_norm(hidden + residual) * weight.""" + combined = hidden.float() + residual.float() + rms = torch.rsqrt(combined.pow(2).mean(dim=-1, keepdim=True) + eps) + return (combined * rms * weight.float()).to(hidden.dtype) diff --git a/deepspeed/module_inject/segki_design.md b/deepspeed/module_inject/segki_design.md new file mode 100644 index 000000000000..6de34f1a9f39 --- /dev/null +++ b/deepspeed/module_inject/segki_design.md @@ -0,0 +1,378 @@ +# segKI Design Document + +**Status: draft — to be submitted after PR #8602 merges.** +**Audience: AI coding agents (and humans who want the reasoning, not just the what).** + +This document is the design guide for segKI. Agents and humans modifying +segKI are expected to read it before making changes, and the implementation +must stay in sync with it: any design-level change ships together with the +corresponding update to this document. + +--- + +## 1. What segKI is + +segKI injects hand-written, per-architecture-tuned kernels into +communication-free segments of hybrid models (e.g., Qwen3.5: full-attention + +gated-delta-net linear attention) for hybrid-engine rollout decode. segKI is +**accelerator-agnostic by design**: the contract is the opbuilder interface +(§2.1) plus the executable reference (§2.2), and any accelerator can implement +it with its own opbuilder backend (SYCL/XPU/... — see the porting guide in +§5). It is +storage-agnostic: weights are read through `param.data` wherever it points +(including arena views bound by the resharding side, #9045), and the only +sync-time obligation is dropping derived-weight caches (`segki_refresh()`). + +Layer map: + +``` +csrc/module_inject/fused_glu.cu CUDA kernels (compute) + dispatcher +csrc/comm/custom_collective.cu one-shot P2P all-reduce (PR #8997 owns it) +op_builder/fused_glu.py build description (JIT/prebuilt) +op_builder/custom_collective.py build description (#8997) +deepspeed/ops/module_inject/fused_glu.py runtime lazy loader (process singleton) +deepspeed/module_inject/segment_ki.py injection: installers, fused forwards, + segki_refresh, TP guards +deepspeed/module_inject/kernel_reference.py executable specification (7 fns) +deepspeed/utils/static_cache.py graph-capture KV cache + GDN pass-through +deepspeed/runtime/rollout/hybrid_engine_rollout.py engine: prefill/graph/continuous +``` + +## 2. The contracts (in order of authority) + +### 2.1 The opbuilder interface — 10 exposed methods + +The `.cu` file exposes exactly 10 `m.def` entries. Internal kernels (the gemv/gemm +variants the dispatcher routes to) are **not** exposed — routing is the +dispatcher's job and other backends must not see internal kernels leak through +the boundary. + +| method | kind | notes | +|---|---|---| +| `grouped_linear` | compute | single entry for ALL GEMV/GEMM paths; flat / WMMA / composite routing inside | +| `decode_attn` | compute | single-query attention, GQA, fused partial-RoPE + q-norm + output gate | +| `gdn_gates` | compute | beta/g gating | +| `gated_norm` | compute | z-gated RMSNorm (multi-line lambda m.def — grep accordingly) | +| `fused_add_norm` | compute | residual add + RMSNorm | +| `gdn_recurrent_step` | compute | in-place recurrent update (TP=1 path; FLA wins at TP) | +| `decode_step_graph` | compute | single-token full step incl. argmax (b=1) | +| `repeat_qk`, `silu_mul` | glue | have `hasattr` eager fallbacks | +| `capabilities`, `refresh_weights` | mgmt | backend-owned derived-state invalidation (`clear_glu_cat_cache` is its alias; optional — a stateless backend omits it, §2.4) | + +A backend porting segKI implements these methods — nothing else is the contract. + +### 2.2 kernel_reference.py — the executable specification + +Exactly 7 functions, one per compute interface method (gdn_recurrent_step's +oracle is FLA's public API; decode_step_graph is contract-tested). Three roles: +(1) specification for a porting agent, (2) runtime fallback when no kernel, +(3) test oracle. **Tests anchor on these, never on inline math** — when a +reference was added for `repeat_qk`, it caught a real stride bug (B*S stride +vs Hk stride, masked by B=1) that months of e2e parity had missed. + +### 2.3 Weight shape is the interface + +Kernels derive per-rank dimensions from `weight.shape` and read through +`data_ptr()`. The storage underneath (regular params, arena views, resharded +buffers) is invisible. This is what makes the arena integration zero-code on +our side: `param.data = arena_view` just works, and CUDA graphs stay valid +because in-place writes keep addresses. + +### 2.4 The refresh_weights mechanism (PROVISIONAL — see #9109) + +Derived caches (concat groups, conv slices, fp32 gate constants) are keyed by +weight identity/pointer. In-place syncs keep keys valid while values change. +The mechanism to drop stale ones is single-trigger, two-tier by which side of +the opbuilder boundary the cache lives on: + +- **Python-side caches** (`_ki_*` module attributes): each injector registers + a refresh callback **on the module it injects into, at injection time** — + registration co-located with cache creation, so a new injection path + *structurally cannot* forget its refresh logic. Module-level (not + model-level): lifecycle automatic (callbacks die with the module), zero + added cost (`segki_refresh` already walks `model.modules()`). +- **Backend-side caches** (inside the compiled extension): invisible to the + Python registry by design — reaching in would expose internal state. The + backend owns them and implements a uniform `refresh_weights()` opbuilder + method (`clear_glu_cat_cache` becomes its alias). The dispatcher calls it + once; what it clears and how is private knowledge. A stateless backend + simply does not implement it (hasattr discovery): *no derived state, no + refresh obligation; own a cache, own its invalidation.* + +`segki_refresh()` (engine entry: `refresh_weights`) is the pure dispatcher +over both tiers. Known interim flaws, both tracked: + +- the current centralized cache-name list vs distributed installers (the bug + class #9109 fixes with the registered callbacks above); +- continuous-batching graphs bake derived-tensor addresses; the interim fix + releases the graph on refresh (option (a)); option (b) — address-stable + in-place refill — aligns better with the end state. + +**End state, two tiers:** + +1. **Mandatory: the refresh framework as fallback.** Refresh survives, + wherever the direct-write assumption breaks: + - **non-affine derived tensors** — e.g. quantized weight caches: + absmax/scale is not an affine map, cannot be a sync target; invalidate + and recompute on weight change; + - **weight writes that bypass the sync path** — manual loads, EMA + overwrites, test code mutating `param.data` — do not know about targets, + so values go stale unless a callback fires. +2. **Optional: affine direct-write via an `affine_targets()` opbuilder + method.** A backend that keeps affine derived caches may publish them as + opaque target descriptors — (source weights, affine map, destination) — + and the sync executor then maintains them directly. The map crosses the + boundary; the layout does not, so derived tensors may live in the arena + *or* in backend-private memory — host choice is implementation freedom. + Costs the backend two promises: destination address stability across + syncs (no realloc/rehash) and single-writer discipline (sync writes, the + kernel only reads). Backends that do not implement it keep the + refresh-and-recompute path; implementing it removes the recompute. + +With tier 2, "nothing derived → nothing cached → nothing to refresh" holds +for sync-driven updates: affine targets are written in place, and the +registered callbacks for them degrade to no-ops. + +## 3. Design decisions and their reasoning + +### 3.1 Hand-written kernels; implementation language is the accelerator owner's choice + +The default opbuilder implementation uses native kernel language (CUDA) — this +is deliberate: it leaves the liberty to each accelerator owner to decide the +language to implement segKI kernels. An op can be implemented by any of the +following, all could be wrapped behind the opbuilder mechanism: + +a. native kernel language (the default opbuilder implementation); +b. PyTorch ops, then optimized by a compiler; +c. an accelerator-specific library; +d. a portable kernel language such as Triton or TileLang. + +Accelerator owners pick the most appropriate way per op — the contract (§2.1) +only fixes the 10 exposed methods, not how they are built. + +External components (libraries, frameworks) are legitimate **only in "bring +your own pointers" mode**: they may lend math, never take ownership of state +or weights. State slots (KV/recurrent caches) belong to the upstream cache +(§3.3) — their addresses are what CUDA graphs bake (§6) and what the +native/fallback switch shares per call (§3.7); a library that insists on +managing its own KV or weight buffers would turn every architecture seam — +graph validity, per-call degradation, module lifecycle, state verifiability +— into a bidirectional sync problem. Math can be outsourced; the seams +cannot. + +### 3.2 Unfused arena layout (checkpoint lingua franca) + +The arena speaks HF-checkpoint layout; concat derivation is segKI-internal +(e.g., GLU cat ~2GB/rank on 4B — measured, acceptable). Pre-fused layouts were +deferred for two reasons. First, they turn storage into a three-party contract +(trainer maps, reshard, kernels) for a one-time ~ms concat. Second, and more +fundamental: pre-fusion would puncture the opbuilder boundary itself. Fusion +grouping is internal state today; with a pre-fused arena it leaks into the +storage format — writers must know it, `weight.shape` (§2.3) stops being a +self-describing interface, the eager fallback (HF modules expecting natural +shapes) needs a second layout, and whichever backend's fusion choices got +baked into storage would lock out other backends' implementation liberty +(§3.1). The end state (§2.4) supersedes this cleanly via affine target maps — +fusion stays declared by segKI as an affine target, so the layout knowledge +never leaves the kernel side — revisit only with measured memory pressure. + +### 3.3 Stateful layer slots: pass-through binding, not native state management + +segKI targets hybrid models generally; any stateful layer variant (GDN today; +Mamba/RWKV-class linears later) follows the same slot strategy. When the +upstream implementation is already graph-safe by construction, our slot binds +it **by reference** (`__getattr__` forwarding) — zero state-management code, +single source of truth, graph addresses = the prefill buffers. The upstream +dependency surface = the same few protocol names the model code itself uses; +no wider. DSStaticGDNSlot is the first instance of this pattern, not a +GDN-specific design. + +### 3.4 Collective and compute: separate ops, separate component + +Collectives and compute are separate ops by design, at two levels: + +- **In the graph**: the collective is graph-capturable and is captured as its + own op in the same stream as the compute kernels — the one-shot P2P + all-reduce uses static buffers and flag-based signaling, so once its lazy + init has run before capture, its addresses never change and the captured + graph stays valid. It is never fused into `decode_step_graph`: the + one-shot AR's essence is waiting on peers (spin); fusing it into a compute + mega-kernel would pin SMs in a wait state and bake the blocking point in, + and the fused op would no longer be implementable per-accelerator behind + the §2.1 boundary. +- **At the interface**: segKI's only touchpoint is the + `dist.inference_all_reduce` hook — a contract, not a dependency on any + implementation. Backends fill the slot however they load (builder, + accelerator library, plain NCCL); transport and topology evolve without + touching segKI. + +### 3.5 Arch-adaptive routing is transparent to the opbuilder interface + +`grouped_linear` routes by batch/weight-count/arch (flat GEMV at M=1; WMMA ≤ +threshold; cuBLAS composite above; Ada keeps WMMA for GLU at M≤32, Ampere +prefers composite+concat-cache) — all inside the method, behind the §2.1 +boundary. The interface exposes a single `grouped_linear` entry regardless of +what routes underneath, so callers never route and a porting backend is free +to route differently for its own silicon. Every Python call site goes through +`grouped_linear` (the interface cleanup, 38ee22cd6). Known wart: +return format is inconsistent (n=4 flat concatenates into one tensor; other +paths return per-weight lists) — callers use the `_as_concat` normalization; +fixing the format is a small breaking change for a quiet day. + +### 3.6 Layout assumptions of injected paths must be asserted loudly + +An injected forward's weight-layout expectations are violated silently, not +crashingly — wrong partitioning yields wrong numbers, not an error. So every +layout expectation is asserted at config time, raising with the fix pattern +in the message. First (transient) instance: the injected GDN forward slices +per-rank head ranges out of FULL in_proj blocks, so `in_proj_qkv/z/b/a` (and +conv1d) must stay replicated — AutoTP specs mark them `partition_type: +"skip"`; a guard raises if they are sharded. Per-rank in_proj sharding (the +better TP efficiency end state) retires this guard. + +### 3.7 Injection is model-agnostic: structural discovery + config cross-check + +Injection never dispatches on model names. Installers walk `model.modules()` +and match **structural signatures** — attribute sets (`in_proj_qkv/z/b/a` +identifies a GDN segment), protocol shapes (`q_norm`/`k_norm` as modules, +norms with weight+eps), base-class isinstance for collective points — then +cross-check the config's own declaration (`config.layer_types[i]` must say +`full_attention` before an attention installer may take the module). The +replacement installed is per **segment type**, not per model: the fused +forward mirrors that segment family's native flow. A model is supported iff +every segment type it contains has an injection path — new models reusing +known segments are near-zero cost. + +Discipline: a structural match is necessary, not sufficient. A future model +with the same attribute names but different gating semantics would match +structurally and be **silently mis-injected** (wrong numbers, no error — the +same failure class as §3.6). Hence: every installer includes the config-level +identity cross-check, and a new model family must pass greedy parity (§6) +before its structural hits are trusted — structure grants injection +eligibility, parity confirms semantic equivalence. + +### 3.8 Dual train/rollout without phase switches + +Every native-kernel takeover is gated on `not torch.is_grad_enabled()`. No +inject/eject between training and rollout phases (RL contract test pins this). +The composite/fallback paths preserve autograd for training. + +## 4. Lineage: how segKI relates to inference V1/V2 + +DeepSpeed shipped two prior inference stacks; both had to answer the same +question — who holds the model knowledge that maps a model to kernels — and +answered it differently: + +- **V1** (`module_inject`'s replace_module path, kernel inject): replace module + classes in the HF model. Model knowledge lives in a user-supplied + `injection_policy` dict or in hardcoded per-model replacement tables. + Weights are reshaped into the fused layout the kernels want at injection + time — the pre-fused storage §3.2 rejects, learned from this lineage. +- **V2** (`inference/v2`, ragged engine): no injection — per-model-family + policies (`model_implementations//`) instantiate a DeepSpeed-native + implementation and map checkpoint parameters into it. Model knowledge is + explicit, one policy directory per family. +- **segKI**: no model list at all. Injection discovers segments by structural + signature (attribute sets, cross-checked against `config.layer_types`) and + replaces forwards in place; model knowledge is pushed down to per-segment + protocol contracts. + +| dimension | V1 | V2 | segKI | +|---|---|---|---| +| model→kernel mapping | user dict / hardcoded class tables | per-family policy directory (model rebuilt) | segment structural discovery (model-name-free) | +| intrusion | replaces module classes | no injection: native impl + param mapping | in-place forward swap, modules untouched | +| weight layout | reshaped to fused layout at inject | checkpoint engine maps into native impl | checkpoint layout preserved; derivation internal (§3.2) | +| relation to training | inference-only | inference-only | dual train/rollout, no phase switches (§3.8); storage-agnostic + refresh | +| portability | CUDA-centric builders | torch-op composites, fairly portable | opbuilder contract + executable reference + `hasattr` degradation | +| cost of a new model | one replacement table / user config | one policy directory | near-zero if segments reused; new segment shape = reference-first kernel (§5) | + +The essential difference is not the injection mechanism but the problem +domain: V1/V2 are pure inference engines that load weights once — segKI lives +in the RL train/rollout alternation, which is why it carries §2.3 +storage-agnosticity, §2.4 refresh, and the arena/reshard handshake at all. +Conversely, V2's ragged continuous-batch scheduling is what segKI currently +approximates with graph capture. segKI's structural discovery + `layer_types` +cross-check is effectively V1's "trust the user's injection_policy" replaced +by "trust the model's own config declaration". + +### Possible evolution: declarative segment manifests (a possibility, not a plan) + +Pure structural discovery has known pressure points that grow with the model +zoo: same-name/different-semantics false hits, heterogeneous per-family config +declarations (cross-checks accumulating per-family knowledge — the registry +creeping back in through the side door), and no authoritative "which families +are verified" list. One candidate answer — recorded here as a possibility to +be weighed when the pressure is real, not a commitment — is an optional +per-family **declarative manifest**: the family binds its blocks to segment +types from the closed contract vocabulary, with pinned protocol versions. + +The key property would be a trust inversion: the declaration becomes the +primary judgement, and structural discovery is demoted to verifying that +declared segments look like what they claim (mismatch fails loudly). Models +without a manifest keep the structural-only path unchanged — the manifest is +a layer of determinism on top, not a new admission requirement. + +In lineage terms this borrows V2's knowledge management (explicit, curated, +versioned, independently testable per family) on top of V1's injection +mechanism (in-place forward swap, model untouched), while staying distinct +from both: mappings target a closed vocabulary with mathematical definitions +(§2.1/§2.2) instead of arbitrary classes; the artifact is optional and +layered instead of a hard prerequisite; dual train/rollout and checkpoint +layout preservation are unaffected. Declared layout expectations (the §3.6 +guard data, today scattered in AutoTP specs) have a natural home here too. + +If pursued, the same caveats apply as to any registry: manifests rot +(upstream refactors outpace declarations — version pins must turn staleness +into loud errors), and parity (§6) remains the gatekeeper — a manifest grants +admission, never correctness. + +## 5. Agent extension guides + +### Porting to a new accelerator (SYCL/XPU/...) +1. Read the 7 `kernel_reference.py` functions — that is the entire math contract. +2. Implement the 10 interface methods behind a builder + (`get_accelerator().create_op_builder(...)` discovery). +3. `hasattr` discovery means partial implementations degrade to eager fallback + — ship the high-value ops first (grouped_linear, decode_attn). +4. Validate against the reference tests (they are device-agnostic) and the + greedy-parity harness (§6). + +### Adding a kernel +1. Reference function in `kernel_reference.py` FIRST. +2. Direct reference-matched unit test NEXT (this ordering caught repeat_qk). +3. Then the CUDA kernel + dispatcher routing. +4. No new `m.def` unless it joins the portable contract. + +### Adding an injection path +1. Installer sets `_ki_*` attributes on the target module. +2. Register the path's refresh callback per #9109 (module-level) — the + centralized list is the bug class, do not extend it. +3. Wire the `hasattr` eager fallback (composite path must keep autograd). + +### Adding a new model +1. Audit its segment composition (§3.7): every segment type needs an + existing injection path. If all segments are known types, wiring is + config-only — no code. +2. For each structural hit, verify the config identity check matches the + model's `layer_types`/`block_type` declarations; extend the cross-check + if the family declares itself differently. +3. If the model redefines a segment's math (new attention variant, new + linear-attention recurrence), that is a new op family: follow "Adding a + kernel" above — reference first, kernel second, new `m.def`/opbuilder type + only if it joins the portable contract. +4. Gate support on greedy parity (§6) for the new family — structure granted + injection; parity confirms semantics. + +## 6. Verification pyramid + +1. **Reference consistency** (unit, any device): kernel vs `kernel_reference`, + multiple shapes/batches, bitwise where layout permits. +2. **Contract tests**: RL no-switch loop, graph-capture ordering, arena views. +3. **Greedy parity**: segKI+graph generate == HF `model.generate` greedy, + b=1..8, per-row match rates (this is the harness that surfaced #9017 — + graph-capture batch-size bug; keep it in CI-adjacent reach). +4. **End-to-end train/rollout loop**: train → weight sync (in-place write) → + refresh → generate, verified against a fresh injection. This is the level + that catches integration bugs no unit test can (e.g. stale derived caches, + graph/address invalidation) — the storage-agnosticity and refresh + contracts (§2.3, §2.4) are only proven here. diff --git a/deepspeed/module_inject/segment_ki.py b/deepspeed/module_inject/segment_ki.py new file mode 100644 index 000000000000..3acfa6f4e0db --- /dev/null +++ b/deepspeed/module_inject/segment_ki.py @@ -0,0 +1,1177 @@ +# 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. +""" + +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 bias-free, comm-free linear-like layers with a + 2-D weight. + + Duck-typed (weight + bias attrs): AutoTP replaces nn.Linear with a + LinearLayer wrapper that still exposes both. Shard-aware fusion is + unnecessary — the kernels derive per-rank shapes from weight.shape, + so sharded weights work unchanged at any TP degree. + """ + for module in root.modules(): + projections = {name: getattr(module, name, None) for name in attr_names} + if not all(p is not None and hasattr(p, "weight") and hasattr(p, "bias") for p in projections.values()): + continue + if any(p.weight is None or p.weight.dim() != 2 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 = [] + # Only gate/up are fused (read directly by the kernel); down_proj is + # delegated to its own forward, so it may carry a collective — under + # AutoTP it is a LinearAllreduce and must stay excluded from the + # comm-free check above. + for module, p in _find_fusable_projections(root, ("gate_proj", "up_proj")): + down = getattr(module, "down_proj", None) + if down is None or not hasattr(down, "weight"): + continue + # 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=down)) + 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 + from deepspeed.accelerator import get_accelerator + if not get_accelerator().on_accelerator(hidden): + 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 _native_kernel_ready(kernel_op, hidden, gate_w, up_w): + if hidden.dim() == 1: + # grouped_linear's flat path dispatches M=1 to the GEMV + # kernels internally + return kernel_op.grouped_linear(hidden, [gate_w, up_w], True)[0] + if hidden.dim() == 2: + # Route through grouped_linear: the backend dispatcher owns + # the WMMA-vs-composite crossover (arch-adaptive since loop 2) + return kernel_op.grouped_linear(hidden, [gate_w, up_w], True)[0] + from deepspeed.module_inject.kernel_reference import grouped_linear + return grouped_linear(hidden, [gate_w, up_w], True)[0] + + @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): flat GEMV path (dispatched by grouped_linear); b>1 + 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 _native_kernel_ready(kernel_op, hidden, w_qkv, w_z, w_b, w_a): + if hidden.dim() == 1: + return kernel_op.grouped_linear(hidden, [w_qkv, w_z, w_b, w_a], False)[0] + if hidden.dim() == 3 and hidden.shape[1] == 1: + # decode activations arrive [B,1,H]; flatten for the grouped kernel + x2 = hidden.reshape(hidden.shape[0], -1) + out = kernel_op.grouped_linear(x2, [w_qkv, w_z, w_b, w_a], False)[0] + return out.view(hidden.shape[0], 1, -1) + if hidden.dim() == 2: + return kernel_op.grouped_linear(hidden, [w_qkv, w_z, w_b, w_a], False)[0] + from deepspeed.module_inject.kernel_reference import grouped_linear + parts = grouped_linear(hidden, [w_qkv, w_z, w_b, w_a], False) + return torch.cat(parts, dim=-1) if len(parts) > 1 else parts[0] + + @classmethod + def apply6(cls, x, q_w, k_w, v_w, z_w, b_w, a_w, kernel_op): + """TP block-sliced GDN in_proj through the same grouped_linear + interface as the fused 4-mat form (path consistency TP=1/TP=2). + Callers that pre-concatenated pass the same tensor for q/k/v and + for z/b/a: identical weights collapse to a 2-mat group.""" + if q_w is k_w and k_w is v_w and z_w is b_w and b_w is a_w: + ws = [q_w, z_w] + else: + ws = [q_w, k_w, v_w, z_w, b_w, a_w] + if _native_kernel_ready(kernel_op, x, *ws): + if hasattr(kernel_op, "grouped_linear"): + out = kernel_op.grouped_linear(x, ws, False) + if len(out) == 2: + return torch.cat(out, -1) + return out[0] + return torch.cat([torch.nn.functional.linear(x, w) for w in ws], dim=-1) + + @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.""" + # One hidden vector in any [*, 1, hidden] / [1, hidden] / [hidden] + # shape — HF decode activations arrive as [1, 1, hidden], so keying on + # dim()==2 would exclude the exact greedy-decode case this fusion + # targets. The kernel op handles a flat vector; reshape on the way out. + m = input.numel() // input.shape[-1] + if input.numel() == input.shape[-1] and getattr(self, "_ki_dual_op", None) is not None: + out = DualWeightGluGEMV.apply(input.reshape(-1), self.gate_proj.weight, self.up_proj.weight, self._ki_dual_op) + return self.down_proj(out.reshape(*input.shape[:-1], -1)) + if 1 < m <= 32 and getattr(self, "_ki_dual_op", None) is not None: + out = DualWeightGluGEMV.apply(input.reshape(m, -1), self.gate_proj.weight, self.up_proj.weight, + self._ki_dual_op) + return self.down_proj(out.reshape(*input.shape[:-1], -1)) + # other batches or no kernel: the composite reference (gradients also + # correct there); measured faster than the batched GEMV kernels + from deepspeed.module_inject.kernel_reference import grouped_linear + glu = grouped_linear(input, [self.gate_proj.weight, self.up_proj.weight], True)[0] + return self.down_proj(glu) + + +@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) + # Shard-aware dims: under TP the in_proj weights are head-sharded, so all + # split boundaries and head counts derive from the per-rank shapes (the + # config values are the global ones). The colwise/rowwise GDN partition + # keeps the whole block rank-local (per-head math); out_proj's AllReduce + # is the layer's only collective. + import deepspeed.comm as dist + tp_size = dist.get_world_size() if dist.is_initialized() else 1 + r = dist.get_rank() if dist.is_initialized() else 0 + key_dim = self.key_dim // tp_size + value_dim = self.value_dim // tp_size + num_v_heads = self.num_v_heads // tp_size + num_k_heads = self.num_k_heads // tp_size + + # Fused [qkv | z | b | a] projection reading the original weights (b=1 + # flat GEMV path, b>1 on-the-fly concat) — no weight copies. + gdn_kernel_op = getattr(self, "_ki_gdn_op", None) + if tp_size > 1: + # The fused [q|k|v] weight cannot be column-sharded head-aligned + # (a contiguous row split lands mid-block), so it stays replicated + # and each rank slices its own head ranges per block — zero-copy + # views, no gather. z/b/a are single-block weights and shard + # head-aligned under AutoTP. + nq = self.key_dim // tp_size + nv = value_dim + qkv_w = self.in_proj_qkv.weight + q_w = qkv_w[r * nq:(r + 1) * nq] + k_w = qkv_w[self.key_dim + r * nq:self.key_dim + (r + 1) * nq] + v_w = qkv_w[2 * self.key_dim + r * nv:2 * self.key_dim + (r + 1) * nv] + x2 = hidden_states.reshape(-1, hidden_states.shape[-1]) + # Cache the per-rank concatenated weights (static during rollout): + # one wide GEMM per group lets the backend's cuBLAS tile better + # than six skinny row-slice GEMMs. Still routed through + # grouped_linear — the backend owns the kernel choice. + cw = getattr(self, "_ki_tp_cat_w", None) + if cw is None or cw[0] is not self.in_proj_qkv.weight: + # z/b/a stay replicated as well; slice this rank's head range out + # of the full [v-head | per-head scalar | per-head scalar] blocks + # so the fused layout matches the local endpoint arithmetic. + vz = value_dim + z_w = self.in_proj_z.weight[r * vz:(r + 1) * vz] + b_w = self.in_proj_b.weight[r * num_v_heads:(r + 1) * num_v_heads] + a_w = self.in_proj_a.weight[r * num_v_heads:(r + 1) * num_v_heads] + zba_w = torch.cat([z_w, b_w, a_w]) + cw = (self.in_proj_qkv.weight, torch.cat([q_w, k_w, v_w]), zba_w) + self._ki_tp_cat_w = cw + fused = GDNInputProj.apply6(x2, cw[1], cw[1], cw[1], cw[2], cw[2], cw[2], + gdn_kernel_op).view(batch_size, seq_len, -1) + elif 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) + qkv_end = key_dim * 2 + value_dim + z_end = qkv_end + value_dim + b_end = z_end + 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). + # varlen keeps the transposed view: the conv package only accepts + # seq_idx with the native memory format. + qkv_view = fused[..., :qkv_end].transpose(1, 2) + mixed_qkv = qkv_view if kwargs.get("seq_idx") is not None else qkv_view.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 + # The native gdn_gates op has no autograd registration, so a training + # step through this branch would silently cut gradients to the a/b + # projections, A_log, and dt_bias. The kernel's win is decode launch + # overhead (a no-grad path); training runs the composite ops instead. + # It also reads raw BFloat16 pointers only — fp16 models must take the + # composite path rather than raise inside the binding. + if (gdn_op is not None and get_accelerator().on_accelerator(a) and not torch.is_grad_enabled() + and a.dtype is torch.bfloat16): + # A_log/dt_bias are static across the rollout — cache the fp32 + # rank slice once instead of re-casting every decode step + hv = self.num_v_heads + cached = getattr(self, "_ki_gates_cache", None) + if cached is None or cached[0] is not self.A_log: + sl = (lambda t: t.detach().reshape(-1)[r * num_v_heads:(r + 1) * num_v_heads]) if hv > num_v_heads \ + else (lambda t: t.detach()) + cached = (self.A_log, sl(self.A_log).float().contiguous(), sl(self.dt_bias).float().contiguous()) + self._ki_gates_cache = cached + a_log_f, dt_f = cached[1], cached[2] + # gdn_gates accepts row-strided a/b, so the fused-output slices go in + # without contiguous copies. Routed through the torch.library op so + # inductor fuses the glue around it (route A). + beta, g = gdn_op.gdn_gates(a, b, a_log_f, dt_f) + else: + beta = b.sigmoid() + hv = self.num_v_heads + a_log_l = self.A_log.reshape(-1)[r * num_v_heads:(r + 1) * num_v_heads] if hv > num_v_heads else self.A_log + dt_l = self.dt_bias.reshape(-1)[r * num_v_heads:(r + 1) * num_v_heads] if hv > num_v_heads else self.dt_bias + g = -a_log_l.float().exp() * F.softplus(a.float() + dt_l) + if num_v_heads // num_k_heads > 1: + rep_op = getattr(self, "_ki_gdn_op", None) + if (rep_op is not None and hasattr(rep_op, "repeat_qk") and not torch.is_grad_enabled() + and query.dtype is torch.bfloat16 and query.is_contiguous() and key.is_contiguous()): + query, key = rep_op.repeat_qk(query, key, num_v_heads // num_k_heads) + else: + query = query.repeat_interleave(num_v_heads // num_k_heads, dim=2) + key = key.repeat_interleave(num_v_heads // 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) + # The dict.get default avoids truth-value evaluation: `or` on a + # multi-element cu-seqlens tensor raises "ambiguous boolean value". + cu_seqlens = kwargs.get("cu_seq_lens_q", 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 and last_recurrent_state 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) + gdn2_op = getattr(self, "_ki_gdn_op", None) + if (gdn2_op is not None and hasattr(gdn2_op, "gated_norm") and not torch.is_grad_enabled() + and core_attn_out.is_contiguous() and z.is_contiguous() and core_attn_out.dtype is torch.bfloat16): + normed = torch.empty_like(core_attn_out) + norm_eps = getattr(self.norm, "variance_epsilon", None) or self.norm.eps + gdn2_op.gated_norm(core_attn_out, z, self.norm.weight, normed, norm_eps) + core_attn_out = normed + else: + 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 _bypass_parity_ok(query, key, value, kw): + """One-shot behavioral gate for the in-place recurrent launch. + + Runs the wrapper and the direct launch on clones of the live decode + tensors and compares outputs and final states. Any FLA build whose + kernel contract differs (packing, grid layout) fails here once per + process and per shape, and the scan keeps using the wrapper. The probe + writes only to clones, never to the cache slot.""" + import logging + try: + from fla.ops.gated_delta_rule import fused_recurrent_gated_delta_rule + h0 = kw.get("initial_state") + if h0 is None: + return False + common = dict(g=kw.get("g"), + beta=kw.get("beta"), + use_qk_l2norm_in_kernel=kw.get("use_qk_l2norm_in_kernel", False)) + with torch.no_grad(): + o_ref, ht_ref = fused_recurrent_gated_delta_rule(query, + key, + value, + initial_state=h0.clone(), + output_final_state=True, + **common) + slot = h0.clone() + o_b, _ = _fla_recurrent_inplace(query, key, value, initial_state=slot, **common) + ok = (torch.allclose(o_b.float(), o_ref.float(), atol=1e-2, rtol=1e-2) + and torch.allclose(slot.float(), ht_ref.float(), atol=1e-2, rtol=1e-2)) + if not ok: + logging.getLogger(__name__).warning( + "segKI FLA recurrent bypass disabled: parity probe failed on this FLA build; using the wrapper") + return ok + except Exception: + return False + + +def _fla_recurrent_inplace(query, key, value, **kw): + """FLA's fused recurrent with the final state written in place. + + Mirrors fla.ops.gated_delta_rule.fused_recurrent's forward wrapper — + same grid, metaparams, and kernel — except ht is the caller's cache + slot (== h0) instead of a fresh allocation. Assumes the decode shape + (T==1, no cu_seqlens, gating precomputed) of the scan call site. + """ + import triton + from fla.ops.gated_delta_rule.fused_recurrent import fused_recurrent_gated_delta_rule_fwd_kernel + + # input_guard equivalent: the kernel indexes packed layouts only, and the + # decode q/k/v arrive as strided views of the fused projection (batch + # stride = full fused width). Pack without copying already-dense inputs. + q = query if query.is_contiguous() else query.contiguous() + k = key if key.is_contiguous() else key.contiguous() + v = value if value.is_contiguous() else value.contiguous() + g = kw.get("g") + beta = kw.get("beta") + if g is not None and not g.is_contiguous(): + g = g.contiguous() + if beta is not None and not beta.is_contiguous(): + beta = beta.contiguous() + slot = kw["initial_state"] + B, T, H, K = k.shape + V = v.shape[-1] + HV = v.shape[2] + o = torch.empty_like(v) + BK = triton.next_power_of_2(K) + # the outer (bypassed) wrapper computes this default; the Triton + # kernel cannot branch on a None host value + scale = kw.get("scale") + if scale is None: scale = K**-0.5 + BV = min(8, triton.next_power_of_2(V)) + NV = triton.cdiv(V, BV) + fused_recurrent_gated_delta_rule_fwd_kernel[(NV * B * HV, )]( + q=q, + k=k, + v=v, + g=g, + gk=None, + gv=None, + beta=beta, + A_log=None, + dt_bias=None, + o=o, + h0=slot, + ht=slot, # in-place: each program reads its tile before writing it + cu_seqlens=None, + scale=scale, + T=T, + H=H, + HV=HV, + K=K, + V=V, + BK=BK, + BV=BV, + IS_BETA_HEADWISE=beta.ndim != v.ndim, + USE_QK_L2NORM_IN_KERNEL=kw.get("use_qk_l2norm_in_kernel", False), + APPLY_BETA_SIGMOID=False, + ALLOW_NEG_EIGVAL=kw.get("allow_neg_eigval", False), + STATE_V_FIRST=False, + num_warps=1, + num_stages=3, + ) + return o, None # None: the state is already in the cache slot + + +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 _local_conv_wb(): + # The conv weight channels follow the fused [q|k|v] block order; a + # rank's local channels are one range per block, so the local weight + # is the cat of the three rank-indexed block rows (cached — tiny). + import deepspeed.comm as dist + tp_sz = dist.get_world_size() if dist.is_initialized() else 1 + if tp_sz == 1: + return parent.conv1d.weight.squeeze(1), parent.conv1d.bias + rk = dist.get_rank() + nq = parent.key_dim // tp_sz + nv = parent.value_dim // tp_sz + w = parent.conv1d.weight.squeeze(1) + cached = getattr(parent, "_ki_conv_w_local", None) + if cached is not None and cached[2] == (rk, tp_sz): + return cached[0], cached[1] + key_dim = parent.key_dim + wl = torch.cat([ + w[rk * nq:(rk + 1) * nq], w[key_dim + rk * nq:key_dim + (rk + 1) * nq], + w[2 * key_dim + rk * nv:2 * key_dim + (rk + 1) * nv] + ]) + bl = None + if parent.conv1d.bias is not None: + b = parent.conv1d.bias + bl = torch.cat([ + b[rk * nq:(rk + 1) * nq], b[key_dim + rk * nq:key_dim + (rk + 1) * nq], + b[2 * key_dim + rk * nv:2 * key_dim + (rk + 1) * nv] + ]) + parent._ki_conv_w_local = (wl.contiguous(), bl, (rk, tp_sz)) + return wl.contiguous(), bl + + def conv_update_with_weights(mixed_qkv, conv_state): + w, bias = _local_conv_wb() + return conv_update(mixed_qkv, conv_state, w, bias, parent.activation) + + def conv_fn_with_weights(mixed_qkv, **kw): + # seq_idx carries the packed-sequence boundaries; the conv takes + # nothing else from the layer kwargs (matching the native call). + w, bias = _local_conv_wb() + return conv_fn(mixed_qkv, w, bias, activation=parent.activation, seq_idx=kw.get("seq_idx")) + + def scan(query, key, value, **kw): + init_state = kw.get("initial_state") + # decode (single token) with a live state: the in-place recurrent + # kernel updates the cache buffer directly — no FLA output tensor, + # no HF copy-back, half the state traffic + step_op = getattr(parent, "_ki_gdn_op", None) + # TP block-sliced q/k/v arrive as strided views; the in-place + # kernel loses to FLA at TP head counts even after the occupancy + # retune (smem staging removed: 998/2650/4161 vs 1001/2856/4238) + # — keep the strided-view rejection so TP decodes route to FLA; + # the re-tuned kernel still serves the TP=1 path where it wins + if (init_state is not None and query.shape[1] == 1 and step_op is not None + and hasattr(step_op, "gdn_recurrent_step") and not torch.is_grad_enabled() + and query.shape[0] >= 16 # below that our block count starves vs FLA's tiling + and query.is_contiguous() and key.is_contiguous() and value.is_contiguous() + and init_state.is_contiguous() and init_state.dtype is torch.float32): + b_sz, _, h, dk = query.shape + dv = value.shape[-1] + out = torch.empty(b_sz, 1, h, dv, dtype=query.dtype, device=query.device) + step_op.gdn_recurrent_step(query.squeeze(1), key.squeeze(1), value.squeeze(1), kw["g"], kw["beta"], + init_state, out.squeeze(1)) + return out, None + # 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. Newer transformers + # (5.19+) no longer bind them per-layer; fall back to the module-level + # torch_* implementations there. + single = kw.get("initial_state") is not None and query.shape[1] == 1 + import os as _os + # The raw-kernel launch must not trust its own view of FLA's kernel + # contract: the wrapper packs strided inputs (the decode q/k/v are + # views of the fused projection with a wider batch stride) and FLA + # releases have changed the kernel's grid layout (0.5.2 reads a 2-D + # grid, 0.6.0 a flattened 1-D). _fla_recurrent_inplace therefore + # packs its inputs itself, and a one-time parity probe against the + # wrapper gates the bypass per shape: the direct launch must + # reproduce the wrapper on live tensors before it may replace it, + # which silently rejects incompatible FLA builds. FLA_BYPASS=0 + # forces the wrapper path. + _bypass = _os.environ.get("FLA_BYPASS", "1") == "1" + if single and not torch.is_grad_enabled() and _bypass: + shape_key = (query.shape[-2], value.shape[-2], query.shape[-1], value.shape[-1]) + verdicts = getattr(parent, "_ki_bypass_verdicts", None) + if verdicts is None: + verdicts = parent._ki_bypass_verdicts = {} + if shape_key not in verdicts: + verdicts[shape_key] = _bypass_parity_ok(query, key, value, kw) + if verdicts[shape_key]: + # The verified in-place launch writes the cache slot directly + # (h0 == ht: each program reads its state tile before writing + # it), dropping the wrapper's fresh-allocation + copy-back + # round trip (~35us/layer/step). + try: + out = _fla_recurrent_inplace(query, key, value, **kw) + return out + except (ImportError, AttributeError): + pass # FLA layout changed — fall through to the wrapper + try: + # The per-layer FLA bindings are gone on transformers 5.19+, so a + # missing attribute is normal there; the real degradation signal is + # fla-core itself being absent -- every GDN scan (decode and prefill) + # then runs the eager torch decomposition, correct but ~1.6x slower + # end-to-end (measured on Qwen3.5-4B, b=32 decode), silently. + from fla.ops.gated_delta_rule import fused_recurrent_gated_delta_rule # noqa: F401 + except ImportError: + from deepspeed.utils import logger as _ds_logger + _ds_logger.warning_once("fla-core is not installed: GDN scans run the eager torch " + "decompositions (~1.6x slower end-to-end); pip install fla-core") + fn_name = "recurrent_gated_delta_rule" if single else "chunk_gated_delta_rule" + fn = getattr(parent, fn_name, None) + if fn is None: + import sys + fn = getattr(sys.modules[type(parent).__module__], f"torch_{fn_name}", None) + if fn is None: + raise AttributeError(f"GDN scan unavailable: neither {fn_name} nor torch_{fn_name}") + return fn(query, key, value, **kw) + + # The TP branch slices per-rank head ranges out of the FULL [q|k|v] + # blocks, which requires all four GDN input projections to have stayed + # replicated. AutoTP's generic column split lands mid-block (no rank + # holds a valid local layout); refuse loudly instead of computing on a + # garbage layout. + import deepspeed.comm as dist + tp_size = dist.get_world_size() if dist.is_initialized() else 1 + if tp_size > 1: + expected = { + "in_proj_qkv": 2 * parent.key_dim + parent.value_dim, + "in_proj_z": parent.value_dim, + "in_proj_b": parent.num_v_heads, + "in_proj_a": parent.num_v_heads, + } + expected["conv1d"] = 2 * parent.key_dim + parent.value_dim + bad = [n for n, rows in expected.items() if getattr(parent, n).weight.shape[0] != rows] + if bad: + raise RuntimeError(f"segKI GDN injection requires the GDN input projections " + f"replicated under TP (its forward slices per-rank head ranges " + f"out of the full blocks); sharded weights found for {bad}. " + f"Exclude linear_attn.in_proj_* from AutoTP sharding with SKIP " + f"layer specs (patterns like " + fr"r'.*\.linear_attn\.in_proj_qkv\.weight$', " + f"partition_type=skip).") + + parent._ki_gdn_op = _load_native_op() + parent._ki_gdn_conv_update = conv_update_with_weights + parent._ki_gdn_conv_fn = conv_fn_with_weights + parent._ki_gdn_scan = scan + fwd = _fused_gdn_forward.__get__(parent, type(parent)) + + parent.forward = fwd + return True + + +_NATIVE_OP_LOAD_WHY = None + + +def segki_refresh(model: torch.nn.Module) -> None: + """Drop every derived-weight cache after an in-place weight write. + + The injected forwards cache tensors derived from the weights (concat + groups, sliced conv weights, fp32 gate constants) keyed by weight + identity/pointer. An arena or reshard sync that updates weights in + place keeps those keys valid while the VALUES change, so the caches + would serve stale copies mixed with fresh direct reads. Call this + after every in-place weight update; a fresh injection rebuilds the + same state automatically. + + NOTE: this explicit-call contract is PROVISIONAL — the final + weight-sync handshake (automatic detection vs explicit call vs a + redesigned cache scheme) is still under design; expect this entry + point to change. + """ + op = None + for module in model.modules(): + for attr in ("_ki_tp_cat_w", "_ki_attn_cat_w", "_ki_conv_w_local", "_ki_gates_cache"): + if hasattr(module, attr): + delattr(module, attr) + op = op if op is not None else getattr(module, "_ki_gdn_op", None) + # the GLU concat cache is process-wide in the backend; any injected + # backend handle reaches it. GLU-only models carry theirs on the MLP + # modules as _ki_dual_op (no GDN layers exist to hold _ki_gdn_op). + gdn_op = op or next((getattr(m, attr, None) + for m in model.modules() + for attr in ("_ki_gdn_op", "_ki_dual_op") + if getattr(m, attr, None) is not None), None) + if gdn_op is not None and hasattr(gdn_op, "clear_glu_cat_cache"): + gdn_op.clear_glu_cat_cache() + + +def _load_native_op(): + """Best-effort load of the segment-KI native op; None → composite. + + Ask the accelerator whether it registers this builder — the kernels are + CUDA source today, so other backends answer NotImplemented and skip the + futile JIT attempt, while a backend that implements the op later is + picked up automatically. A registered builder whose JIT toolchain is + unusable on this host falls back instead of raising through rollout + construction. The fallback reason is logged once so users can tell + which path is running.""" + global _NATIVE_OP_LOAD_WHY + from deepspeed.accelerator import get_accelerator + import logging + logger = logging.getLogger(__name__) + try: + builder = get_accelerator().get_op_builder("FusedGLUBuilder") + except Exception as e: + _NATIVE_OP_LOAD_WHY = f"builder lookup failed: {e}" + logger.warning("segment-KI native op disabled (%s); using composite fallback", _NATIVE_OP_LOAD_WHY) + return None + if builder is None or builder.__name__ == "NotImplementedBuilder": + _NATIVE_OP_LOAD_WHY = f"accelerator registers no FusedGLUBuilder ({builder.__name__ if builder else 'None'})" + logger.warning("segment-KI native op disabled (%s); using composite fallback", _NATIVE_OP_LOAD_WHY) + return None + try: + return builder().load() + except Exception as e: + _NATIVE_OP_LOAD_WHY = f"JIT load failed: {e}" + logger.warning("segment-KI native op disabled (%s); using composite fallback", _NATIVE_OP_LOAD_WHY) + return None + + +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 = _load_native_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, "grouped_linear") 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[1] > 1 or hidden_states.dtype is not torch.bfloat16 or not hidden_states.is_contiguous() + or past_key_values is None or getattr(self, "_ki_attn_op", None) is None + or getattr(self, "_ki_prompt_padded", False) + or getattr(past_key_values, "_write_position", None) is not self._ki_write_pos): + # Prefill, a non-graph cache (e.g. DynamicCache + # inside module.generate), or a padded prompt: the original forward + # is the correct path. The kernel attends every cached slot up to + # write_pos unconditionally, so padded prompt positions would leak + # into the softmax; SDPA masks them natively via attention_mask. + 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) + + # b=1: flat GEMV; 1 < b <= 32: grouped WMMA (both via grouped_linear) + # grouped kernel (same weights, one launch); larger batches use the + # projections as-is. + batch = hidden_states.shape[0] + qkv_op = getattr(self, "_ki_qkv_op", None) + # every branch yields the raw (pre-norm, pre-rope) flat K/V so the + # fused-K path can hand them to the kernel + if qkv_op is not None and hasattr(qkv_op, "grouped_linear"): + # single dispatcher entry; the backend routes by batch internally. + # The projections are static across the rollout — cache the + # concatenated weight so one wide GEMM replaces three skinny ones. + cw = getattr(self, "_ki_attn_cat_w", None) + if cw is None or cw[0] is not self.q_proj.weight: + cw = (self.q_proj.weight, torch.cat([self.q_proj.weight, self.k_proj.weight, self.v_proj.weight])) + self._ki_attn_cat_w = cw + fused = qkv_op.grouped_linear(hidden_states.reshape(-1, hidden_states.shape[-1]), [cw[1]], False)[0] + if fused.dim() == 1: + fused = fused.view(1, -1) # flat GEMV path returns [N] for M=1 + qn, kn = self.q_proj.weight.shape[0], self.k_proj.weight.shape[0] + # decode_attn needs contiguous k/v; the tiny materialization (B*k_dims + # bf16) is far cheaper than the two extra GEMM launches it replaces + q_out = fused[:, :qn] + k_flat = fused[:, qn:qn + kn].contiguous() + v_flat = fused[:, qn + kn:].contiguous() + query_states, gate = torch.chunk(q_out.reshape(*input_shape, -1, self.head_dim * 2), 2, dim=-1) + elif qkv_op is not None and batch == 1: + # 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_flat, v_flat = qkv_op.grouped_linear(hidden_states.view(-1), + [self.q_proj.weight, self.k_proj.weight, self.v_proj.weight], + False) + query_states, gate = torch.chunk(q_out.view(*input_shape, -1, self.head_dim * 2), 2, dim=-1) + elif qkv_op is not None: + q_out, k_flat, v_flat = qkv_op.grouped_linear(hidden_states.reshape(-1, hidden_states.shape[-1]), + [self.q_proj.weight, self.k_proj.weight, self.v_proj.weight], + False) + query_states, gate = torch.chunk(q_out.view(*input_shape, -1, self.head_dim * 2), 2, dim=-1) + else: + query_states, gate = torch.chunk(self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), + 2, + dim=-1) + k_flat = self.k_proj(hidden_states).reshape(batch, -1) + v_flat = self.v_proj(hidden_states).reshape(batch, -1) + + num_q_heads, num_kv_heads, head_dim = self._ki_num_q_heads, self._ki_num_kv_heads, self.head_dim + batch = hidden_states.shape[0] + out = torch.empty(batch, num_q_heads, head_dim, dtype=hidden_states.dtype, device=hidden_states.device) + fuse_q = getattr(self, "_ki_q_norm_w", None) is not None + fuse_k = fuse_q and getattr(self, "_ki_k_norm_w", None) is not None + if fuse_k: + # The kernel norms + ropes K and writes both K/V cache slots itself; + # skip the eager k_norm, rope helper, and cache update. Cache tensors + # are taken directly (update() would only copy what the kernel writes). + slot = past_key_values._layers[self.layer_idx] + key_states = slot.keys + value_states = slot.values + else: + key_states = self.k_norm(k_flat.view(hidden_shape)).transpose(1, 2) + value_states = v_flat.view(hidden_shape).transpose(1, 2) + # K keeps the eager norm + RoPE (the cache stores post-rope keys from + # prefill, so the kernel cannot re-derive them); the q side's norm, + # partial RoPE, and output gate are fused into the decode_attn kernel. + # The model uses partial RoPE (rotary_dim < head_dim), so K rides the + # upstream helper verbatim — only its output is kept. + cos, sin = position_embeddings + _, 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) + + if fuse_q: + # chunk() leaves query strided ([q|gate] interleaved layout); the + # kernel indexes packed memory, so materialize it explicitly + query_states = query_states.reshape(batch, num_q_heads, head_dim) + gate = gate.reshape(batch, num_q_heads, head_dim) + self._ki_attn_op.decode_attn( + query_states, + key_states, + value_states, + self._ki_write_pos, + out, + num_q_heads, + num_kv_heads, + head_dim, + key_states.shape[2], + q_norm_w=self._ki_q_norm_w, + cos_t=self._ki_cos_t, + sin_t=self._ki_sin_t, + gate=gate, + k_raw=(k_flat.reshape(batch, num_kv_heads, head_dim) if fuse_k else key_states.new_empty(0)), + v_raw=(v_flat.reshape(batch, num_kv_heads, head_dim) if fuse_k else key_states.new_empty(0)), + k_norm_w=(self._ki_k_norm_w if fuse_k else key_states.new_empty(0)), + eps=self.q_norm.eps, + rope_dim=self._ki_cos_t.shape[-1]) + else: + self._ki_attn_op.decode_attn(query_states.reshape(batch, num_q_heads, head_dim), key_states, value_states, + self._ki_write_pos, out, num_q_heads, num_kv_heads, head_dim, key_states.shape[2]) + + attn_output = out.view(*input_shape, -1) + return self.o_proj(attn_output), None + + +def install_lm_head(model: torch.nn.Module, kernel_op) -> int: + """Route lm_head decode batches of 16..32 through the grouped kernel. + + cuBLAS reaches only ~490 GB/s on the M=32, N=vocab lm_head shape; the + grouped kernel's weight-streaming tiles do better. Weights are read + in place (no copies); the grad path keeps the original Linear. + """ + lm = getattr(model, "lm_head", None) + if lm is None or not hasattr(lm, "weight"): + return 0 + if kernel_op is None or not hasattr(kernel_op, "grouped_linear"): + return 0 + if lm.weight.dtype is not torch.bfloat16 or lm.bias is not None: + return 0 + # vocab-parallel lm_head wrappers carry gather/allreduce semantics in + # their forward; a plain-GEMM patch would silently drop the collective + if carries_collective(lm): + return 0 + + def _lm_forward(self, hidden_states): + b = hidden_states.shape[0] + if hidden_states.dim() == 3 and hidden_states.shape[1] == 1: + # Vocab-parallel decode: each rank GEMMs its contiguous half of + # the (replicated) weight — half the weight traffic — and the + # rank-ordered all-gather reassembles full logits for argmax + # and sampling alike; downstream sees identical semantics. + import deepspeed.comm as dist + tp = dist.get_world_size() if dist.is_initialized() else 1 + x2 = hidden_states.reshape(b, -1) + if tp > 1 and self.weight.shape[0] % tp == 0: + half = self.weight.shape[0] // tp + w_loc = self.weight[dist.get_rank() * half:(dist.get_rank() + 1) * half] + if not torch.is_grad_enabled() and 16 <= b <= 32 and x2.is_contiguous(): + loc = self._ki_gemm_op.grouped_linear(x2, [w_loc], False)[0] + else: + loc = torch.nn.functional.linear(x2, w_loc) + parts = [torch.empty_like(loc) for _ in range(tp)] + dist.all_gather(parts, loc.contiguous()) + return torch.cat(parts, dim=-1).view(b, 1, -1) + if (not torch.is_grad_enabled() and 16 <= b <= 32 and hidden_states.is_contiguous()): + out = self._ki_gemm_op.grouped_linear(x2, [self.weight], False)[0] + return out.view(b, 1, -1) + return torch.nn.functional.linear(hidden_states, self.weight, self.bias) + + lm._ki_gemm_op = kernel_op + lm.forward = _lm_forward.__get__(lm, type(lm)) + return 1 + + +def install_decode_attention(model: torch.nn.Module, + write_pos: torch.Tensor, + kernel_op, + cos_table: torch.Tensor = None, + sin_table: torch.Tensor = None) -> 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")] + # duck-typed projection check: AutoTP replaces nn.Linear with a + # LinearLayer wrapper that still exposes .weight + if not all(hasattr(p, "weight") and p.weight is not None 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 + # per-rank head counts from the actual weight shapes (AutoTP-sharded + # weights carry the per-rank output dimension in weight.shape[0]) + q_out = projections[0].weight.shape[0] + kv_out = projections[1].weight.shape[0] + num_q_heads = q_out // (2 * head_dim) + num_kv_heads = kv_out // head_dim + if num_q_heads * head_dim * 2 != q_out: + 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 + # Fused q-side preprocessing inputs: the (1+w) norm scale and the + # full-length RoPE tables (indexable by the GPU-resident position, + # so replays stay graph-safe). Missing tables disable the fusion. + module._ki_q_norm_w = (1.0 + + module.q_norm.weight.detach().float()).contiguous() if cos_table is not None else None + module._ki_k_norm_w = (1.0 + + module.k_norm.weight.detach().float()).contiguous() if cos_table is not None else None + module._ki_cos_t = cos_table + module._ki_sin_t = sin_table + module._ki_attn_op = kernel_op + # The fused QKV kernel consumes weights only; biased projections would lose their bias. + unbiased_qkv = all(p.bias is None for p in projections[:3]) + module._ki_qkv_op = kernel_op if (hasattr(kernel_op, "grouped_linear") and unbiased_qkv) 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 / grouped_linear) still apply.""" + if (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 or torch.is_grad_enabled()): + # Prefill, a non-graph path, or any grad-enabled + # forward: the original forward is the correct path. fused_add_norm + # has no autograd registration and mutates the residual stream + # in-place, so a training step through it would silently lose the + # residual/norm gradients (the kernel's win is decode-only). + 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. + # The 1+w scale is recomputed from the live Parameter on every call: + # HF's norm multiplies by 1+weight, the kernel by its weight argument + # directly. During capture the add becomes part of the graph, so replay + # reads the parameter's memory and reflects post-training values. + new_residual = hidden_states + postattn_scale = torch.add(1.0, self.post_attention_layernorm.weight).contiguous() + mlp_input = op.fused_add_norm(new_residual, residual, 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. Returns the + patched count.""" + if kernel_op is None or not hasattr(kernel_op, "fused_add_norm"): + 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.forward = _fused_norm_layer_forward.__get__(module, type(module)) + patched += 1 + return patched diff --git a/deepspeed/ops/module_inject/__init__.py b/deepspeed/ops/module_inject/__init__.py new file mode 100644 index 000000000000..7e706a71dc28 --- /dev/null +++ b/deepspeed/ops/module_inject/__init__.py @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +"""op_builder module for segment-KI native kernels.""" + +from .fused_glu import FusedGLUBuilder, get_fused_glu_op diff --git a/deepspeed/ops/module_inject/fused_glu.py b/deepspeed/ops/module_inject/fused_glu.py new file mode 100644 index 000000000000..5dcb292b38c5 --- /dev/null +++ b/deepspeed/ops/module_inject/fused_glu.py @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +"""Runtime loader for the segment-KI fused_glu native CUDA kernel. + +The builder lives in op_builder/ so DS_BUILD_FUSED_GLU=1 installs pick it +up; this module only exposes the lazily JIT-loaded op to callers.""" + +from deepspeed.ops.op_builder import FusedGLUBuilder + +_FUSED_GLU_OP = None + + +def get_fused_glu_op(): + """Lazily JIT-build and load the fused_glu CUDA op (cached process-wide).""" + global _FUSED_GLU_OP + if _FUSED_GLU_OP is None: + _FUSED_GLU_OP = FusedGLUBuilder().load() + return _FUSED_GLU_OP diff --git a/deepspeed/runtime/rollout/hybrid_engine_rollout.py b/deepspeed/runtime/rollout/hybrid_engine_rollout.py index dfd6c75a0c7e..1b7180e228ca 100644 --- a/deepspeed/runtime/rollout/hybrid_engine_rollout.py +++ b/deepspeed/runtime/rollout/hybrid_engine_rollout.py @@ -133,6 +133,9 @@ class HybridEngineRolloutConfig: enable_profiling: bool = False use_shared_prefill: bool = False align_decode_fronts: bool = False + # Apply segment-KI kernel injection to the engine's module at rollout + # construction. Fuses comm-free projection+activation segments into + # single GEMM+custom-kernel calls (MLP gate|up and GDN input projections). enable_cache_trimming: bool = False continuous_cache_capacity: Optional[int] = None adaptive_prefill: bool = False @@ -142,6 +145,9 @@ class HybridEngineRolloutConfig: prefill_kv_cost_ms: float = 0.04 continuous_decode_cost_ms: float = 10.0 prefill_max_tokens: Optional[int] = 65536 + # PR-local switches; kept after every upstream field so the legacy + # positional constructor contract (#8786's test) keeps holding + use_segki: bool = False @dataclass @@ -193,6 +199,54 @@ def __init__(self, engine, tokenizer, cfg=None): self._last_continuous_stats = None self._generation_defaults = None + self.use_segki = cfg is not None and getattr(cfg, 'use_segki', False) + if self.use_segki: + self._segki_report = self._apply_segki() + else: + self._segki_report = None + + def refresh_weights(self) -> None: + """Handshake for in-place weight updates (arena / reshard syncs). + + Drops the injected forwards' derived-weight caches. The weights + themselves are read live, so only the derived tensors go stale. + A retained continuous-batching graph captures those tensors' + addresses, so it is released here too (re-captured on the next + rollout) -- replays would otherwise read freed memory. Interim + cost: one re-capture per sync; remove when refresh refills the + derived tensors in place and graphs survive by construction. + + PROVISIONAL contract — see segki_refresh; the final weight-sync + handshake is still under design. + """ + from deepspeed.module_inject.segment_ki import segki_refresh + if self._continuous_graph_state is not None: + get_accelerator().synchronize() + self._continuous_graph_state = None + # Resolve through the engine like every other module access; unit + # tests hand us SimpleNamespace(module=...) engines. + module = getattr(self.engine, "module", None) or getattr(self, "module", None) + if module is None: + return + segki_refresh(module) + + def _apply_segki(self): + """Apply segment-KI kernel injection to the wrapped module. + + Returns the injection report dict, or None if the module is not + supported (unsupported architectures pass through silently). + """ + try: + from deepspeed.module_inject.segment_ki import apply_segment_ki + except ImportError: + return None + report = apply_segment_ki(self.engine.module) + if isinstance(report, dict) and report.get('segments_replaced', 0) == 0 \ + and report.get('segments_found', 0) == 0: + # No segments found: model architecture not supported, not an error + return report + return report + @torch.no_grad() def generate(self, request: RolloutRequest, sampling: SamplingConfig) -> RolloutBatch: if sampling.continuous_batch_size is not None: @@ -250,10 +304,22 @@ def _generate_batched(self, request, sampling, mask_padding=True): prompt_ids = request.prompt_ids prompt_attn = request.prompt_attention_mask + # The injected decode-attention kernel attends every cached slot up + # to write_pos unconditionally, so padded prompts must ride the SDPA + # path (which masks pad positions natively). One host sync per + # generate call; the decode loop itself stays sync-free. + module._ki_prompt_padded = bool((prompt_attn == 0).any().item()) + if self.enable_profiling: accelerator.synchronize() expansion_end = time.perf_counter() + is_greedy = sampling.temperature <= 0.0 + + # Master's graph-capture gating (#8980 + #8939): the local variable + # is the config value narrowed by the accelerator capability check. + # No is_greedy gate — #8939 added sampling to the graph path; the + # token selector runs outside the captured graph (~0.9% decode cost). use_graph_capture = self.use_graph_capture if use_graph_capture and not get_accelerator().is_graph_capture_supported(): # Same opt-in as the HybridEngine graph cache and the continuous @@ -276,7 +342,18 @@ def _generate_batched(self, request, sampling, mask_padding=True): raise RuntimeError("Shared prefill does not support graph capture") self.engine.prepare_shared_prefill(B, n, prompt_len) shared_prefill_handles = self._register_shared_prefill_hooks(module, B, n) - if use_graph_capture: + # Padded prompts fall back to module.generate ONLY when our + # kernels cannot honor the mask: hybrid prefill feeds GDN a + # None mask (pad positions corrupt conv-state init), and the + # injected segKI decode kernels attend every cached slot + # unconditionally. Standard graph users keep master's padded + # behavior — the mask flows through prefill and the decode + # static_attn buffer. + # mock modules in tests carry no config — default to standard + _cfg = getattr(module, "config", None) + layer_types = getattr(getattr(_cfg, "text_config", _cfg), "layer_types", None) or [] + needs_pad_fallback = module._ki_prompt_padded and ("linear_attention" in layer_types or self.use_segki) + if use_graph_capture and not needs_pad_fallback: output_ids = self._generate_graph(prompt_ids, prompt_attn, max_new_tokens, pad_token_id, module, device, sampling) else: @@ -362,13 +439,14 @@ def _generate_batched(self, request, sampling, mask_padding=True): @torch.no_grad() def _generate_continuous(self, request, sampling, max_batch_size): - """Generate independent requests in an experimental continuous batch. + """Generate independent greedy requests in an experimental continuous batch. - Continuous batching currently requires one prompt row per request. - Completed rows retire immediately and pending prompts prefill into the - released rows before the next decode step. + Continuous batching currently requires one prompt row per request and + greedy decoding. Completed rows retire immediately and pending prompts + prefill into the released rows before the next decode step. """ - profile = self._start_continuous_profile() if self.adaptive_prefill and self.enable_profiling else None + select_next_tokens = self._token_selector(sampling) + profile = self._start_continuous_profile() if self.enable_profiling else None original_request = request batch_size = request.prompt_ids.shape[0] effective_lengths = self._validate_continuous_inputs(request, sampling, max_batch_size) @@ -380,7 +458,6 @@ def _generate_continuous(self, request, sampling, max_batch_size): "falling back to eager continuous batching.") use_graph_capture = False module = self.engine.module - select_next_tokens = self._token_selector(sampling) prepared_generation_config = None if self.adaptive_prefill and dist.is_initialized() and dist.get_world_size() > 1: raise ValueError("adaptive prefill currently supports single-process rollouts only") @@ -538,6 +615,8 @@ def _generate_continuous(self, request, sampling, max_batch_size): for index in range(batch_size)) device = requests[0].prompt_ids.device model_dtype = next(module.parameters()).dtype + select_next_tokens = self._token_selector(sampling) + repetition_penalty = self._repetition_penalty(module) scheduler_start = self._profile_start(profile) scheduler = ContinuousBatchScheduler(max_batch_size, sampling.max_new_tokens) @@ -755,7 +834,6 @@ def _generate_continuous_graph(self, original_request, requests, sampling, max_b static tensor addresses. """ module = self.engine.module - select_next_tokens = self._token_selector(sampling) prompt_len = requests[0].prompt_ids.shape[1] self._validate_continuous_graph_options(prompt_len, sampling) if getattr(module, "_supports_cache_class", None) is False: @@ -764,6 +842,8 @@ def _generate_continuous_graph(self, original_request, requests, sampling, max_b if getattr(module.config, "_attn_implementation", None) == "flash_attention_2": raise ValueError("continuous graph capture does not support flash_attention_2") device = requests[0].prompt_ids.device + if get_accelerator().create_graph() is None: + raise ValueError("continuous graph capture is not supported on the current accelerator") from transformers import StaticCache from deepspeed.utils.static_cache import DeepSpeedStaticCache @@ -779,6 +859,8 @@ def _generate_continuous_graph(self, original_request, requests, sampling, max_b if max_positions is not None and max_cache_len > max_positions: raise ValueError("continuous batching cache exceeds the model maximum position embeddings") model_dtype = next(module.parameters()).dtype + select_next_tokens = self._token_selector(sampling) + repetition_penalty = self._repetition_penalty(module) scheduler = ContinuousBatchScheduler(max_batch_size, sampling.max_new_tokens) request_by_id = {} responses = {} @@ -1105,6 +1187,14 @@ def _validate_continuous_inputs(self, request, sampling, max_batch_size): raise ValueError("max_batch_size must be positive") if self.use_shared_prefill: raise ValueError("continuous batching does not support shared prompt prefill") + # Hybrid models: GDN layers keep per-row conv/recurrent state that + # the continuous-batching cache does not yet scatter or compact, so + # a run would crash on an unbound pass-through slot mid-decode. Fail + # with a clear message up front instead. + config = getattr(self.engine.module, "config", None) + text_config = getattr(config, "text_config", config) + if "linear_attention" in (getattr(text_config, "layer_types", None) or []): + raise ValueError("continuous batching does not yet support hybrid models with linear-attention layers") if sampling.max_new_tokens <= 0: raise ValueError("max_new_tokens must be positive") @@ -1460,51 +1550,6 @@ def _continuous_next_tokens(cls, dim=0) return select_next_tokens(logits) - @staticmethod - def _hf_sampling_kwargs(sampling): - """Hugging Face ``generate()`` arguments for ``sampling``; ``temperature <= 0`` is greedy.""" - if sampling.temperature <= 0.0: - return {"do_sample": False, "temperature": 1.0, "top_p": 1.0} - return { - "do_sample": True, - "temperature": sampling.temperature, - "top_p": sampling.top_p, - "top_k": max(sampling.top_k, 0), - } - - @staticmethod - def _token_selector(sampling): - """Return a function that picks the next tokens ``[B, 1]`` from last-position logits ``[B, V]``. - - Tokens are picked after each forward or graph replay, outside any - captured graph. Sampling applies Hugging Face's temperature, top-k and - top-p warpers in the order ``generate()`` applies them, so every path - draws from the same distribution as ``generate()``. - """ - if sampling.temperature <= 0.0: - return lambda logits: logits.argmax(dim=-1, keepdim=True) - - from transformers.generation.logits_process import (TemperatureLogitsWarper, TopKLogitsWarper, - TopPLogitsWarper) - - warpers = [] - if sampling.temperature != 1.0: - warpers.append(TemperatureLogitsWarper(sampling.temperature)) - if sampling.top_k > 0: - warpers.append(TopKLogitsWarper(top_k=sampling.top_k)) - if sampling.top_p < 1.0: - warpers.append(TopPLogitsWarper(top_p=sampling.top_p)) - - def sample(logits): - # generate() also warps and samples in float32. - scores = logits.float() - for warper in warpers: - # The warpers read only the scores, not the generated ids. - scores = warper(None, scores) - return torch.multinomial(torch.softmax(scores, dim=-1), num_samples=1) - - return sample - @staticmethod def _prefill_position_ids(attention_mask): position_ids = attention_mask.long().cumsum(dim=-1) - 1 @@ -1541,7 +1586,7 @@ def _create_static_cache(static_cache_type, config, batch_size, max_cache_len, d cache_config = config if not hasattr(config, "num_key_value_heads") or config.num_key_value_heads is None: cache_config = copy(config) - cache_config.num_key_value_heads = config.num_attention_heads + cache_config.num_key_value_heads = getattr(config, "num_attention_heads", 1) common_kwargs = { "config": cache_config, "max_cache_len": max_cache_len, @@ -1694,9 +1739,54 @@ def _pad_after_eos(output_ids, response_start, eos_token_id, pad_token_id, mask_ return output_ids, response_attn.long() # ------------------------------------------------------------------ - # Graph capture decode loop + # Graph capture decode loop (greedy only) # ------------------------------------------------------------------ + @staticmethod + def _token_selector(sampling): + """Return a function that picks the next tokens ``[B, 1]`` from last-position logits ``[B, V]``. + + Tokens are picked after each forward or graph replay, outside any + captured graph. Sampling applies Hugging Face's temperature, top-k and + top-p warpers in the order ``generate()`` applies them, so every path + draws from the same distribution as ``generate()``. + """ + if sampling.temperature <= 0.0: + return lambda logits: logits.argmax(dim=-1, keepdim=True) + + from transformers.generation.logits_process import (TemperatureLogitsWarper, TopKLogitsWarper, + TopPLogitsWarper) + + warpers = [] + if sampling.temperature != 1.0: + warpers.append(TemperatureLogitsWarper(sampling.temperature)) + if sampling.top_k > 0: + warpers.append(TopKLogitsWarper(top_k=sampling.top_k)) + if sampling.top_p < 1.0: + warpers.append(TopPLogitsWarper(top_p=sampling.top_p)) + + def sample(logits): + # generate() also warps and samples in float32. + scores = logits.float() + for warper in warpers: + # The warpers read only the scores, not the generated ids. + scores = warper(None, scores) + return torch.multinomial(torch.softmax(scores, dim=-1), num_samples=1) + + return sample + + @staticmethod + def _hf_sampling_kwargs(sampling): + """Hugging Face ``generate()`` arguments for ``sampling``; ``temperature <= 0`` is greedy.""" + if sampling.temperature <= 0.0: + return {"do_sample": False, "temperature": 1.0, "top_p": 1.0} + return { + "do_sample": True, + "temperature": sampling.temperature, + "top_p": sampling.top_p, + "top_k": max(sampling.top_k, 0), + } + def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, module, device, sampling): """Decode with DeepSpeedStaticCache + graph capture, greedy or sampled per ``sampling``.""" from transformers import StaticCache @@ -1712,7 +1802,6 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, model_dtype = next(module.parameters()).dtype select_next_tokens = self._token_selector(sampling) repetition_penalty = self._repetition_penalty(module) - output_ids = [prompt_ids] def next_tokens(logits): if repetition_penalty != 1.0: @@ -1722,49 +1811,147 @@ def next_tokens(logits): # --- 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 + # Hybrid models take a per-type mask dict (GDN must see None; a 2D + # mask corrupts its conv-state init); standard models take a tensor. + is_hybrid = "linear_attention" in (getattr(getattr(module.config, "text_config", module.config), "layer_types", + None) or []) + prefill_mask = {"full_attention": None, "linear_attention": None} if is_hybrid else prompt_attn prefill_out = module( prompt_ids, - attention_mask=prefill_attn, + attention_mask=prefill_mask, past_key_values=prefill_cache, use_cache=True, + # explicit position tensors: HF derives them from the cache + # otherwise, which D2H-syncs and aborts stream capture on some + # model/cache combinations (reproduced with LLaMA + StaticCache) cache_position=torch.arange(prompt_len, device=device), **self._last_logits_kwargs(module), ) - next_token = next_tokens(prefill_out.logits[:, -1, :]) - output_ids.append(next_token) + next_token = select_next_tokens(prefill_out.logits[:, -1, :]) # --- Copy prefill KV into DeepSpeedStaticCache --- - write_pos = torch.tensor(prompt_len - 1, dtype=torch.long, device=device) - ds_cache = DeepSpeedStaticCache(module.config, max_cache_len=max_len) + # per-row positions: the batched step and decode-attention kernels + # advance one entry per sequence (a shared scalar would race) + write_pos = torch.full((batch_size, ), prompt_len, dtype=torch.long, device=device) + ds_tp_config = module.config + import deepspeed.comm as dist + if dist.is_initialized() and dist.get_world_size() > 1: + ds_tp_config = copy(module.config) + ds_tp_config.num_key_value_heads = max(1, module.config.num_key_value_heads // dist.get_world_size()) + ds_tp_config.num_attention_heads = max( + 1, + getattr(module.config, "num_attention_heads", 1) // dist.get_world_size()) + ds_cache = DeepSpeedStaticCache( + ds_tp_config, + batch_size=batch_size, + max_cache_len=max_len, + device=device, + dtype=model_dtype, + ) ds_cache.set_write_position(write_pos) + # Trigger lazy init then copy real data. Hybrid models carry + # linear-attention (GDN) slots alongside KV slots; the GDN slots are + # bound by reference to the prefill cache's HF slot objects, whose + # state management is already cudagraph-safe by construction. + from deepspeed.utils.static_cache import DSStaticGDNSlot # Infer each layer's local KV shape from prefill before graph capture. for layer_idx in range(self._cache_layer_count(ds_cache)): ds_layer = ds_cache.layers[layer_idx] + if isinstance(ds_layer, DSStaticGDNSlot): + ds_layer.bind(prefill_cache.layers[layer_idx]) + continue hf_keys, hf_values = self._cache_layer_tensors(prefill_cache, layer_idx) + ds_layer = ds_cache.layers[layer_idx] if not ds_layer.is_initialized: ds_layer.lazy_initialization(hf_keys, hf_values) ds_layer.keys[:, :, :prompt_len, :].copy_(hf_keys[:, :, :prompt_len, :]) ds_layer.values[:, :, :prompt_len, :].copy_(hf_values[:, :, :prompt_len, :]) + output_ids = [prompt_ids, next_token] + # --- Static buffers for graph capture --- static_token = torch.zeros(batch_size, 1, dtype=torch.long, device=device) - static_attn = torch.zeros(batch_size, max_len, dtype=torch.long, device=device) - static_attn[:, :prompt_len] = prompt_attn - static_attn[:, prompt_len] = 1 # first decode position - # Transformers builds its SDPA mask from a 2-D attention_mask with host-side checks - # (``padding_mask.all()`` in ``_ignore_causal_mask_sdpa``). Those synchronize the stream and - # invalidate CUDA graph capture, so the captured forward receives a pre-built 4-D additive - # mask instead, as the continuous graph path does; each decode step unmasks one more column. - static_causal_attn = torch.zeros((batch_size, 1, 1, max_len), dtype=model_dtype, device=device) - self._update_static_causal_attention(static_attn, static_causal_attn) - static_pos = torch.tensor(prompt_len, dtype=torch.long, device=device) - static_cache_pos = static_pos.unsqueeze(0) # [1] for cache_position - static_pos_ids = static_pos.reshape(1, 1).expand(batch_size, 1) # [batch, 1] + # Full-width static causal mask for the full-attention layers; revealed + # one position per decode step by in-place writes (graph-replay safe). + # GDN layers must receive None: their recurrence ignores attention masks + # and a non-None value corrupts the conv-state updates. + static_attn = torch.zeros(batch_size, 1, 1, max_len, dtype=torch.bool, device=device) + static_attn[:, :, :, :prompt_len] = prompt_attn.unsqueeze(1).unsqueeze(1).bool() + static_attn[:, :, :, prompt_len] = True + + # Decode-step mask argument: the per-type dict for hybrid models, the + # plain 4-D tensor for standard full-attention ones. + decode_mask = {"full_attention": static_attn, "linear_attention": None} if is_hybrid else static_attn + + # Persistent decode position tensors as VIEWS of write_pos: the + # captured forwards read this memory, and the in-graph step kernel + # advances write_pos itself — so replays see the new position with + # no host-side mirror updates. (A clone here would freeze the + # captured value and desync the b=1 full-step path.) + static_cache_pos = write_pos[:1] + static_pos_ids = write_pos.unsqueeze(1) + + full_token_buf = torch.zeros(batch_size, max_len, dtype=torch.long, device=device) + full_token_buf[:, :prompt_len] = prompt_ids + full_token_buf[:, prompt_len] = next_token.view(-1) # first generated token per row write_pos.fill_(prompt_len) + # Replace SDPA in the full-attention layers with the custom + # decode_attn kernel for the b=1 decode steps (prefill and any + # non-graph path keep the original forward). Must happen before the + # warmup forwards so the captured graph records the kernel. + attn_patched = 0 + module._ki_fused_norm_patched = 0 + if self.use_segki: + try: + from deepspeed.module_inject.segment_ki import install_decode_attention, install_fused_norm, install_lm_head + from deepspeed.ops.module_inject import get_fused_glu_op + attn_op = get_fused_glu_op() + # Full-length RoPE tables for the fused q-side path; positions + # are indexed on-device at replay time, so the addresses stay + # fixed for the captured graph. + cos_t = sin_t = None + rotary = getattr(getattr(module, "model", module), "rotary_emb", None) + if rotary is not None: + with torch.no_grad(): + positions = torch.arange(max_len, device=device)[None, :] + if hasattr(rotary, "mrope_section"): + # MRoPE rotary expects [3, batch, seq] positions; text-only + # rows use the same positions for all three sections + positions = positions[None].expand(3, 1, -1) + cos_t, sin_t = rotary(torch.zeros(1, max_len, dtype=model_dtype, device=device), positions) + cos_t = cos_t[0].float().contiguous() + sin_t = sin_t[0].float().contiguous() + attn_patched = install_decode_attention(module, write_pos, attn_op, cos_table=cos_t, + sin_table=sin_t) if hasattr(attn_op, "decode_attn") else 0 + module._ki_fused_norm_patched = install_fused_norm(module, attn_op) + install_lm_head(module, attn_op) + except Exception as e: + # The install chain shares one try: a failure in any part (rope + # tables, decode attention, fused norm, lm head) silently drops + # the whole segKI decode path back to the HF forward, which is + # numerically correct but loses all kernel gains. Make that + # visible instead of looking like normal slow decoding. + logger.warning_once(f"segKI decode install failed; rollout falls back to the HF forward " + f"({type(e).__name__}: {e}). Decode will run without the injected kernels.") + attn_patched = 0 + module._ki_fused_norm_patched = 0 + + # Snapshot the GDN states right after prefill: the warmup forwards + # advance conv/recurrent states by extra steps, so they must be + # restored before capture or every replay starts from corrupted state. + gdn_snapshot = [] + for ds_layer in ds_cache.layers: + if type(ds_layer).__name__ == "DSStaticGDNSlot": + cs, rs = ds_layer.conv_states[0], ds_layer.recurrent_states[0] + gdn_snapshot.append((cs, rs, cs.clone(), rs.clone())) + + def restore_gdn_states(): + for cs, rs, cs0, rs0 in gdn_snapshot: + cs.copy_(cs0) + rs.copy_(rs0) + # Remove forward hooks (they synchronize — illegal during graph capture) saved_pre = dict(module._forward_pre_hooks) saved_post = dict(module._forward_hooks) @@ -1780,57 +1967,155 @@ def next_tokens(logits): for _ in range(3): out = module( static_token, - attention_mask=static_causal_attn, + attention_mask=decode_mask, 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 + step_kernel_mounted = False + 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_causal_attn, + attention_mask=decode_mask, 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. + is_greedy = sampling is None or sampling.temperature <= 0.0 + if (graph_op is not None and is_greedy 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) + step_kernel_mounted = True + + # The capture run advanced the GDN conv/recurrent states (its + # forward consumed static_token) and mutated write_pos whether + # or not decode_step_graph was mounted; restore unconditionally + # so the fallback graph (native op unavailable) does not start + # from a state that already consumed the first decode token. + 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) > Python loop --- + 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. + # 1 = check every step: EOS-heavy rollouts (RL responses end + # early; max_new_tokens is only a cap) would otherwise replay up + # to eos_check_every - 1 dead steps after the last row finishes, + # which costs far more than the per-step sync saves (measured + # +0.1-0.3% at b=32 without EOS vs up to ~20% with early EOS). + eos_check_every = 1 + eos_mask = torch.zeros(batch_size, dtype=torch.bool, device=device) + for step in range(max_new_tokens - 1): + 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 = select_next_tokens(static_logits[:, -1, :]) + output_ids.append(next_token) + # eos_mask.all() is a device->host sync; running it every step + # serializes the ~50us of Python glue against the replay and + # idles the GPU between steps. Amortize it like the b=1 path: + # check every eos_check_every steps and break with a bulk pad. + # Tokens generated after a row's EOS (at most + # eos_check_every - 1 of them) are padded away by + # _pad_after_eos, so the output is identical. + if eos_token_id is None: + continue + eos_mask |= (next_token.view(batch_size) == eos_token_id) + if step % eos_check_every == eos_check_every - 1 and bool(eos_mask.all()): + remaining = max_new_tokens - 2 - step + if remaining > 0: + output_ids.append( + torch.full((batch_size, remaining), pad_token_id, dtype=torch.long, device=device)) + break + return torch.cat(output_ids, dim=1) + + # Full-step graph requires the step kernel to actually be in the + # graph: mounting is conditional (b=1, CUDA bf16 logits), and a + # kernel-less graph replay would read a token buffer nobody wrote. + if step_kernel_mounted: + eos_check_every = 16 + for step in range(max_new_tokens - 1): + get_accelerator().replay_graph(graph) + if eos_token_id is not None and step % eos_check_every == eos_check_every - 1: + if bool((static_token.view(-1) == eos_token_id).all().item()): + break + # pad each row's tail after its own first EOS (response region only; + # a prompt may legitimately contain the EOS id as content) + if eos_token_id is not None: + resp = full_token_buf[:, prompt_len:] + is_eos = resp == eos_token_id + first_eos = torch.where(is_eos.any(dim=1), + is_eos.float().argmax(dim=1), torch.full_like(write_pos[0], resp.shape[1])) + for r in (first_eos < resp.shape[1]).nonzero(as_tuple=True)[0].tolist(): + full_token_buf[r, prompt_len + first_eos[r].item() + 1:] = pad_token_id + gen_ids = full_token_buf[:, prompt_len:prompt_len + max_new_tokens] + return torch.cat([prompt_ids, gen_ids], dim=1) + 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 - - # Update static inputs static_token.copy_(next_token) pos = prompt_len + step write_pos.fill_(pos) - static_cache_pos.fill_(pos) - static_pos_ids.fill_(pos) - static_attn[:, pos] = 1 - self._update_static_causal_attention(static_attn, static_causal_attn) - - # Replay + static_attn[:, :, :, pos] = True get_accelerator().replay_graph(graph) - next_token = next_tokens(static_logits[:, -1, :]) + next_token = select_next_tokens(static_logits[:, -1, :]) output_ids.append(next_token) - eos_mask |= (next_token.squeeze(1) == eos_token_id) - + eos_mask |= (next_token.view(1) == eos_token_id) return torch.cat(output_ids, dim=1) def sync_weights(self, step: int) -> None: # noqa: ARG002 - """No-op: hybrid engine reads model weights live.""" - return None + """Invalidate derived-weight caches after in-place weight updates. + + The colocated hybrid engine reads weights live, so there is + nothing to push -- but the injected forwards cache tensors + derived from the weights, and an in-place write (arena or reshard + sync) leaves those stale. Every training-step entry goes through + here, so each sync source invalidates uniformly instead of + relying on callers to remember refresh_weights(). + """ + self.refresh_weights() def shutdown(self) -> None: """Release the captured continuous decode graph and its static cache. diff --git a/deepspeed/utils/static_cache.py b/deepspeed/utils/static_cache.py index f1eab78328dc..810e904ee6a8 100644 --- a/deepspeed/utils/static_cache.py +++ b/deepspeed/utils/static_cache.py @@ -127,6 +127,9 @@ def update( return self.keys, self.values def get_mask_sizes(self, query_length: int) -> tuple[int, int]: + # Mirror HF StaticLayer exactly: static caches answer with the full + # buffer width, which matches the full-width K/V that update() + # returns (position-based sizes are the DynamicLayer formula). return self.max_cache_len, 0 def get_query_offset(self) -> int | torch.Tensor: @@ -136,6 +139,13 @@ def get_query_offset(self) -> int | torch.Tensor: return self._write_position def get_seq_length(self) -> int | torch.Tensor: + # Transformers >= 5.20 cache protocol (#8852): the length counts the + # slot the current query is writing, so it is one past the write + # position; position/mask math must use get_query_offset() instead + # (it returns the write position itself). Our decode paths pass + # cache_position/position_ids explicitly, so this value never feeds + # RoPE. Kept as a tensor expression: this is read inside captured + # regions and must not sync. if not self.is_initialized: return 0 if self._write_position is not None: @@ -191,7 +201,61 @@ def reorder_cache(self, beam_idx: torch.LongTensor) -> None: self._write_position = self._write_position.index_select(0, beam_idx.to(self._write_position.device)) +class DSStaticGDNSlot: + """Pass-through cache slot for hybrid models' linear-attention layers. + + HF's ``LinearAttentionLayer`` is already cudagraph-safe by construction: + static shapes, ``mark_static_address`` buffers, and in-place ``copy_`` + state updates (its own comments say "to preserve the static address for + cudagraphs"). Duplicating that state management here would only drift; + the graph path therefore binds and reuses the prefill cache's slot + object directly - zero copies, and decode-time updates land in the very + buffers the captured graph reads.""" + + is_compileable = True + supports_early_init = False + + def __init__(self, max_cache_len: int): + self._slot = None + self.max_cache_len = max_cache_len + self._write_position: torch.Tensor | None = None + + def bind(self, hf_slot) -> None: + """Adopt a prefill cache's linear-attention slot (by reference).""" + self._slot = hf_slot + + def __getattr__(self, name): + # Forward the HF slot API (conv_states, recurrent_states, + # has_previous_state, update_*, ...) so the model's GDN modules see + # the exact object semantics they were written against. + slot = object.__getattribute__(self, "_slot") + if slot is None: + raise AttributeError(f"DSStaticGDNSlot not bound: {name}") + return getattr(slot, name) + + def set_write_position(self, pos: torch.Tensor): + self._write_position = pos # tracked for symmetry; GDN state is position-free + + def get_seq_length(self) -> int: + return 0 + + def get_max_cache_shape(self) -> int: + return 0 + + def get_mask_sizes(self, query_length: int) -> tuple[int, int]: + return query_length, 0 + + def reset(self) -> None: + if self._slot is not None: + self._slot.reset() + + class DeepSpeedStaticCache: + # Mirrors HF StaticCache: static buffers answer mask builders with + # full-width masks (is_compileable), which must match the full-width + # K/V buffers update() returns; a position-truncated mask against a + # full-width buffer crashes SDPA at decode. + is_compileable = True """CUDA-graph-compatible static KV cache. Drop-in replacement for ``transformers.StaticCache`` in the graph-capture @@ -226,7 +290,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 + ] self._max_cache_len = max_cache_len self._write_position: torch.Tensor | None = None @@ -261,15 +332,21 @@ def compact(self, active_indices: torch.Tensor) -> None: """Compact active rows after requests retire from a batch.""" if not isinstance(active_indices, torch.Tensor) or active_indices.dim() != 1: raise ValueError("active_indices must be a 1-D tensor") - max_batch_size = self._layers[0].max_batch_size if self._layers else 0 - active_indices = active_indices.to(device=self._layers[0].keys.device, dtype=torch.long) + # Hybrid caches mix KV layers with pass-through GDN slots; the GDN + # slots keep no per-row KV rows (their state is position-free and + # managed by HF), so compaction only touches the KV layers. + kv_layers = [layer for layer in self._layers if not isinstance(layer, DSStaticGDNSlot)] + if not kv_layers: + return + max_batch_size = kv_layers[0].max_batch_size + active_indices = active_indices.to(device=kv_layers[0].keys.device, dtype=torch.long) if active_indices.numel() > max_batch_size: raise ValueError("active_indices exceeds the cache batch size") if active_indices.numel() and ((active_indices < 0).any() or (active_indices >= max_batch_size).any()): raise ValueError("active_indices contains an out-of-range row") if active_indices.unique().numel() != active_indices.numel(): raise ValueError("active_indices must not contain duplicates") - for layer in self._layers: + for layer in kv_layers: layer._compact_rows(active_indices) if self._write_position is not None and self._write_position.dim() == 1: positions = self._write_position @@ -301,7 +378,10 @@ def update( ) -> tuple[torch.Tensor, torch.Tensor]: if layer_idx >= len(self._layers): raise IndexError(f"layer_idx {layer_idx} out of range (cache has {len(self._layers)} layers)") - return self._layers[layer_idx].update(key_states, value_states, *args, **kwargs) + layer = self._layers[layer_idx] + if isinstance(layer, DSStaticGDNSlot): + raise TypeError("linear-attention slots manage conv/recurrent state, not key/value pairs") + return layer.update(key_states, value_states, *args, **kwargs) def early_initialization( self, @@ -312,13 +392,29 @@ def early_initialization( device, ): for layer in self._layers: + if isinstance(layer, DSStaticGDNSlot): + continue # bound to the prefill cache's HF slot later fake_k = torch.zeros((batch_size, num_heads, 0, head_dim), dtype=dtype, device=device) fake_v = torch.zeros((batch_size, num_heads, 0, head_dim), dtype=dtype, device=device) layer.lazy_initialization(fake_k, fake_v) + def _first_attention_idx(self) -> int | None: + # HF convention (cache_utils): alternating caches answer container + # length queries with attention-slot semantics; a linear-attention + # slot never tracks sequence length. + for idx, layer in enumerate(self._layers): + if not isinstance(layer, DSStaticGDNSlot): + return idx + return None + def get_seq_length(self, layer_idx: int = 0) -> int | torch.Tensor: if layer_idx >= len(self._layers): return 0 + if isinstance(self._layers[layer_idx], DSStaticGDNSlot): + first = self._first_attention_idx() + if first is None: + return 0 + layer_idx = first length = self._layers[layer_idx].get_seq_length() if isinstance(length, torch.Tensor) and length.dim() == 1: # Transformer decoder implementations use one scalar past length @@ -327,6 +423,38 @@ def get_seq_length(self, layer_idx: int = 0) -> int | torch.Tensor: return length.max() return length + def update_recurrent_state(self, recurrent_state, layer_idx: int = 0, state_idx: int = 0): + return self._layers[layer_idx].update_recurrent_state(recurrent_state, state_idx=state_idx) + + def update_conv_state(self, conv_state, layer_idx: int = 0, **kwargs): + return self._layers[layer_idx].update_conv_state(conv_state, state_idx=0, **kwargs) + + def get_conv_state(self, layer_idx: int, state_idx: int = 0): + """HF >= 5.19 GDN cache protocol bridge: the native (non-segKI) + forward fetches conv/recurrent state through these top-level + entries; pre-5.19 builds poke layer attributes directly, which the + slot's attribute forwarding already serves.""" + layer = self._layers[layer_idx] + return layer.conv_states[state_idx] + + def get_recurrent_state(self, layer_idx: int, state_idx: int = 0): + layer = self._layers[layer_idx] + return layer.recurrent_states[state_idx] + + def is_recording_past(self, layer_idx: int, state_idx: int = 0) -> bool: + layer = self._layers[layer_idx] + return layer.is_recording_past(state_idx) if hasattr(layer, "is_recording_past") else False + + def has_previous_state(self, layer_idx: int = 0, state_idx: int = 0) -> bool: + # transformers cache protocol: GDN blocks ask the container whether a + # previous recurrent state exists before reading it. + if layer_idx >= len(self._layers): + return False + layer = self._layers[layer_idx] + if isinstance(layer, DSStaticGDNSlot): + return layer.has_previous_state[state_idx] + return self.get_seq_length(layer_idx) > 0 + def get_max_cache_shape(self, layer_idx: int = 0) -> int: if layer_idx >= len(self._layers): return self._max_cache_len @@ -342,8 +470,17 @@ def get_query_offset(self, layer_idx: int = 0) -> int | torch.Tensor: return offset def get_mask_sizes(self, query_length: int, layer_idx: int = 0) -> tuple[int, int]: + # HF convention: mask builders sample shared masks with the default + # layer_idx, which on hybrid models may land on a linear-attention + # slot; redirect such queries to the first attention slot so the + # shared mask gets attention-sized spans. + if layer_idx < len(self._layers) and isinstance(self._layers[layer_idx], DSStaticGDNSlot): + first = self._first_attention_idx() + if first is None: + return query_length, 0 + return self._layers[first].get_mask_sizes(query_length) if layer_idx >= len(self._layers): - return self._max_cache_len, 0 + return query_length, 0 return self._layers[layer_idx].get_mask_sizes(query_length) def reset(self): diff --git a/docs/code-docs/source/inference-engine.rst b/docs/code-docs/source/inference-engine.rst index d627df59b573..f19347d0d9c3 100644 --- a/docs/code-docs/source/inference-engine.rst +++ b/docs/code-docs/source/inference-engine.rst @@ -90,6 +90,46 @@ one token. It cannot be combined with CUDA graph capture, (``SamplingConfig.continuous_batch_size``). 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`` with a +SiLU activation (LLaMA, Qwen, Mistral, DeepSeek, ...) or whose GatedDeltaNet +block uses the ``in_proj_{qkv,z,b,a}`` set is picked up without per-model code. +GELU-gated variants (e.g. Gemma) and other unsupported architectures pass +through silently. The option is disabled by default and +combines with ``use_graph_capture=True`` for the fastest path. + +Scope and semantics +~~~~~~~~~~~~~~~~~~ + +- **Throughput numbers** count executed decode steps (all rows step together); + tokens produced after a row's EOS are padded, so valid-token rates can be + lower at early EOS. Graph warm-up + capture happens per ``generate()`` call + (~1–1.5 s on a 4B model) and is excluded from decode-rate measurements. +- **Graph reuse**: a fresh graph is captured on every ``generate()`` call, so + weights updated by training between calls are picked up. Replaying one + captured graph across a training step (weight mutation without recapture) + is not supported — the capture reads current parameter memory, so stale + addresses could otherwise persist. +- **Packed (varlen) sequences**: the GDN conv/scan wrappers forward the + packed-sequence boundary markers (``seq_idx`` / ``cu_seqlens``) exactly as + the native forward does; packed *training* (gradients through the packed + path) is not exercised by the test suite and not guaranteed. + +Injected replacements read the original weight ``Parameter`` objects directly +with exact backward, so training and generation share one forward path: no +weight copies and no inject/eject switching between rollout and training +steps. + +Segment injection requires a CUDA accelerator and currently targets +single-GPU (batch-size 1 gets a fully fused decode step inside the captured +graph; larger batches keep batched argmax in Python). Fused projections are +never applied to layers carrying tensor-parallel collectives. + Continuous batching (experimental) ----------------------------------- diff --git a/op_builder/fused_glu.py b/op_builder/fused_glu.py new file mode 100644 index 000000000000..ba579123598b --- /dev/null +++ b/op_builder/fused_glu.py @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +from .builder import CUDAOpBuilder + + +class FusedGLUBuilder(CUDAOpBuilder): + BUILD_VAR = "DS_BUILD_FUSED_GLU" + NAME = "fused_glu" + + def __init__(self, name=None): + super().__init__(name=self.NAME if name is None else name) + + def absolute_name(self): + return f'deepspeed.ops.{self.NAME}_op' + + def sources(self): + return ['csrc/module_inject/fused_glu.cu'] diff --git a/tests/integration/zero3_arena_e2e.py b/tests/integration/zero3_arena_e2e.py new file mode 100644 index 000000000000..4443b8b7f16d --- /dev/null +++ b/tests/integration/zero3_arena_e2e.py @@ -0,0 +1,221 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +"""ZeRO-3 trainer -> TP=2 segKI rollout end-to-end (arena-sync contract). + +Two real AdamW steps on a ZeRO-3 engine, weights gathered and written IN +PLACE into the rollout's sharded storage (arena-sync semantics), segki_ +refresh, generate — must be BITWISE equal to a fresh injection over the +same weights. Run: DS_RUN_ZERO3_E2E=1 torchrun --nproc_per_node=2 \ + tests/integration/zero3_arena_e2e.py +Opt-in (needs 2 GPUs + the Qwen3.5 test model cached). +""" +import os +import sys +if __name__ == "__main__" and os.environ.get("DS_RUN_ZERO3_E2E") != "1": + print("set DS_RUN_ZERO3_E2E=1 to run this integration test", file=sys.stderr) + sys.exit(0) + +import os +import torch + +os.environ.setdefault("MASTER_ADDR", "localhost") +os.environ.setdefault("MASTER_PORT", "29710") +from transformers import AutoModelForCausalLM, AutoTokenizer + +from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig +from deepspeed.runtime.rollout.base import RolloutRequest, SamplingConfig +import deepspeed +from deepspeed.accelerator import get_accelerator +from deepspeed.module_inject.segment_ki import segki_refresh + +MODEL = "Qwen/Qwen3.5-0.8B-Base" +tok = AutoTokenizer.from_pretrained(MODEL) +object.__setattr__(tok, "eos_token_id", -1) +rank = int(os.environ.get("RANK", "0")) +get_accelerator().set_device(int(os.environ.get("LOCAL_RANK", "0"))) +DEV = get_accelerator().current_device_name() + +Z3 = { + "train_batch_size": 2, + "bf16": { + "enabled": True + }, + "zero_optimization": { + "stage": 3 + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": 1e-5 + } + }, +} +TPSPECS = [ + { + # segKI slices per-rank head ranges out of the FULL blocks; these + # must stay replicated under TP + "patterns": [r".*\.linear_attn\.in_proj_z"], + "partition_type": "skip" + }, + { + "patterns": [r".*\.linear_attn\.in_proj_b"], + "partition_type": "skip" + }, + { + "patterns": [r".*\.linear_attn\.in_proj_a"], + "partition_type": "skip" + }, + { + "patterns": [r".*\.linear_attn\.out_proj"], + "partition_type": "row" + }, + { + "patterns": [r".*\.self_attn\.q_proj"], + "partition_type": "column" + }, + { + "patterns": [r".*\.self_attn\.k_proj"], + "partition_type": "column" + }, + { + "patterns": [r".*\.self_attn\.v_proj"], + "partition_type": "column" + }, + { + "patterns": [r".*\.self_attn\.o_proj"], + "partition_type": "row" + }, + { + "patterns": [r".*\.mlp\.gate_proj"], + "partition_type": "column" + }, + { + "patterns": [r".*\.mlp\.up_proj"], + "partition_type": "column" + }, + { + "patterns": [r".*\.mlp\.down_proj"], + "partition_type": "row" + }, +] +TP = { + "train_batch_size": 2, + "tensor_parallel": { + "autotp_size": 2, + "partition_config": { + "use_default_specs": False, + "strict_mode": False, + "layer_specs": TPSPECS + } + }, + "bf16": { + "enabled": True + } +} + + +class Shim: + + def __init__(self, m): + self.module = m + self._cfg = m.config + + +def build_tp_rollout(): + m = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.bfloat16) + eng, _, _, _ = deepspeed.initialize(model=m, config=TP) + shim = Shim(eng) + if isinstance(getattr(shim.module, "config", None), dict): + shim.module.config = m.config + ro = HybridEngineRollout(shim, tok, HybridEngineRolloutConfig(use_graph_capture=True, use_segki=True)) + return ro, eng + + +def gather_z3_weights(engine): + """Pull full bf16 weights out of the ZeRO-3 engine (both ranks agree).""" + from deepspeed.runtime.zero import GatheredParameters + params = list(engine.module.parameters()) + with GatheredParameters(params, modifier_rank=0): + out = {n: p.detach().to(torch.bfloat16).clone() for n, p in engine.module.named_parameters()} + return out + + +def train_a_step(engine, seed): + torch.manual_seed(seed) + ids = torch.randint(1000, 50000, (2, 128), device=DEV) + loss = engine(ids, labels=ids).loss + engine.backward(loss) + engine.step() + engine.zero_grad() + return loss.item() + + +torch.manual_seed(11) +prompt = torch.randint(1000, 50000, (4, 128), device=DEV) + + +def gen(ro): + out = ro.generate(RolloutRequest(prompt_ids=prompt, prompt_attention_mask=torch.ones_like(prompt)), + SamplingConfig(max_new_tokens=12, temperature=0.0)) + return out.input_ids[:, prompt.shape[1]:].clone() + + +# --- phase 1: ZeRO-3 trainer, one REAL step on partitioned weights +mt = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.bfloat16) +trainer, _, _, _ = deepspeed.initialize(model=mt, config=Z3, model_parameters=list(mt.parameters())) +l0 = train_a_step(trainer, 101) +print(f"[r{rank}] zero3 step1 loss={l0:.4f}", flush=True) +w1 = gather_z3_weights(trainer) # weights AFTER step 1 + + +def write_full_into_sharded(eng, full_sd, rank, world): + """Arena-sync semantics: write FULL weights into the TP-sharded + rollout storage in place (split dim inferred from shape mismatch — + the same contract their storage-map reshard implements).""" + written = 0 + with torch.no_grad(): + for n, p in eng.module.named_parameters(): + if n not in full_sd: + continue + full = full_sd[n].to(p.device) + if full.shape == p.shape: + p.data.copy_(full) + else: + d = next(i for i, (a, b) in enumerate(zip(full.shape, p.shape)) if a != b) + p.data.copy_(full.chunk(world, dim=d)[rank]) + written += 1 + return written + + +# --- phase 2: rollout engine over post-step-1 weights; caches build +ro_b, eng_b = build_tp_rollout() +n_w = write_full_into_sharded(eng_b, w1, rank, 2) +print(f"[r{rank}] phase2 loaded {n_w} sharded params from w1", flush=True) +gen(ro_b) # build derived caches on w1 +print(f"[r{rank}] rollout caches built", flush=True) + +# --- phase 3: trainer takes ANOTHER real step; sync = in-place write +l1 = train_a_step(trainer, 202) +w2 = gather_z3_weights(trainer) +print(f"[r{rank}] zero3 step2 loss={l1:.4f}", flush=True) +n_w2 = write_full_into_sharded(eng_b, w2, rank, 2) # in-place, same storage +assert n_w2 == n_w, "param sets differ between syncs" +segki_refresh(eng_b.module) +out_refreshed = gen(ro_b) +print(f"[r{rank}] refreshed generate done", flush=True) + +# --- phase 4: fresh injection over the SAME post-step-2 weights +del trainer, mt +get_accelerator().empty_cache() +ro_c, eng_c = build_tp_rollout() +write_full_into_sharded(eng_c, w2, rank, 2) +gen(ro_c) # fresh caches on w2 +out_fresh = gen(ro_c) + +same = torch.equal(out_refreshed, out_fresh) +diffs = (out_refreshed != out_fresh).sum().item() if not same else 0 +print(f"[r{rank}] ZERO3-E2E {'PASS' if same else 'FAIL'} bitwise={same} diffs={diffs}", flush=True) +print(f"[r{rank}] sample refreshed[0,:6]: {out_refreshed[0,:6].tolist()}", flush=True) +print(f"[r{rank}] sample fresh[0,:6]: {out_fresh[0,:6].tolist()}", flush=True) +assert same, f"refresh diverged from fresh: {diffs} diffs" +print(f"[r{rank}] ZERO3-E2E-DONE", flush=True) diff --git a/tests/unit/module_inject/test_graph_position_regression.py b/tests/unit/module_inject/test_graph_position_regression.py new file mode 100644 index 000000000000..126b6486e898 --- /dev/null +++ b/tests/unit/module_inject/test_graph_position_regression.py @@ -0,0 +1,47 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +"""NL-1 regression: the graph path must pass explicit position tensors. + +HF derives cache positions from the cache when absent; with a standard +full-attention model (LLaMA) + StaticCache that derivation D2H-syncs and +aborts stream capture ("operation not permitted when stream is +capturing", reproduced by the reviewer on PyTorch 2.9.1 / Transformers +4.57.1). Runs the graph path end to end on a tiny random LLaMA. +""" + +import pytest +import torch + +from deepspeed.accelerator import get_accelerator + +from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig +from deepspeed.runtime.rollout.base import RolloutRequest, SamplingConfig + +_TINY_LLAMA = "hf-internal-testing/tiny-random-LlamaForCausalLM" + + +class _Shim: + + def __init__(self, m): + self.module = m + + +@pytest.mark.skipif(get_accelerator().device_name() == "cpu", reason="non-CPU device required") +def test_graph_capture_standard_model(): + """Graph capture on a standard (non-hybrid) LLaMA must not sync-abort + when HF would otherwise derive cache positions internally.""" + pytest.importorskip("transformers") + try: + from transformers import AutoModelForCausalLM, AutoTokenizer + tok = AutoTokenizer.from_pretrained(_TINY_LLAMA) + if tok.pad_token_id is None: + tok.pad_token_id = tok.eos_token_id + model = AutoModelForCausalLM.from_pretrained(_TINY_LLAMA, dtype=torch.bfloat16).to("cuda") + except Exception as e: # offline / model unavailable + pytest.skip(f"model {_TINY_LLAMA} unavailable: {e}") + + rollout = HybridEngineRollout(_Shim(model), tok, HybridEngineRolloutConfig(use_graph_capture=True)) + ids = torch.randint(1000, 5000, (1, 6), device="cuda") + req = RolloutRequest(prompt_ids=ids, prompt_attention_mask=torch.ones_like(ids)) + out = rollout.generate(req, SamplingConfig(max_new_tokens=8, temperature=0.0)) + assert out.input_ids.shape[1] == 6 + 8, "generation length mismatch" diff --git a/tests/unit/module_inject/test_hf_parity.py b/tests/unit/module_inject/test_hf_parity.py new file mode 100644 index 000000000000..f75a46bf19cd --- /dev/null +++ b/tests/unit/module_inject/test_hf_parity.py @@ -0,0 +1,151 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +"""Direct parity against the original HF forward (outputs AND gradients). + +The kernel-consistency tests compare kernels against our own reference +implementations; both sides could share a wrong formula. These tests +snapshot the pristine Qwen3.5 layers BEFORE injection, then compare +forward outputs and input gradients with explicit bf16 tolerances. +Known rounding-order differences (fused paths keep fp32 intermediates +where HF rounds to bf16 mid-way) are expected within these tolerances. +""" + +import pytest +import torch + +from deepspeed.accelerator import get_accelerator + +_TEST_MODEL = "Qwen/Qwen3.5-0.8B-Base" + +# bf16 forward parity: fused paths differ from HF only in intermediate +# rounding order; empirically these bound the drift of one decoder layer +ATOL, RTOL = 5e-2, 5e-2 +# gradient parity tolerates the same drift propagated through backward +GATOL, GRTOL = 8e-2, 8e-2 + + +@pytest.fixture(scope="module") +def model(): + pytest.importorskip("transformers") + try: + from transformers import AutoModelForCausalLM + m = AutoModelForCausalLM.from_pretrained(_TEST_MODEL, dtype=torch.bfloat16).to("cuda") + except Exception as e: + pytest.skip(f"model {_TEST_MODEL} unavailable: {e}") + return m + + +def _pick_layer(model, want_block): + """Return the sub-block (self_attn / linear_attn), not the decoder + layer — the layer requires position_embeddings, the blocks do not.""" + types = getattr(model.config, "layer_types", None) or [] + for i, layer in enumerate(model.model.layers): + if types[i:i + 1] == [want_block]: + return layer.linear_attn if want_block == "linear_attention" else layer + pytest.skip(f"no {want_block} layer found") + + +@pytest.mark.skipif(get_accelerator().device_name() == "cpu", reason="non-CPU device required") +class TestFullAttentionLayerParity: + + def test_forward_and_backward(self, model): + """Full-attn layer pre/post injection: output + d(loss)/dx.""" + from deepspeed.module_inject.segment_ki import apply_segment_ki + layer = _pick_layer(model, "full_attention") + torch.manual_seed(0) + hidden = torch.randn(2, 5, model.config.hidden_size, dtype=torch.bfloat16, device="cuda") + pos = torch.arange(5, device="cuda") + pos_ids = pos.unsqueeze(0).expand(2, -1) + cos_sin = model.model.rotary_emb(hidden, pos_ids) + + def run(): + h = hidden.clone().requires_grad_(True) + out = layer(h, position_embeddings=cos_sin, position_ids=pos_ids) + logits = out[0].float().pow(2).sum() + logits.backward() + return out[0].float(), h.grad.float() + + out_p, grad_p = run() # pristine, before injection + apply_segment_ki(model) + out_i, grad_i = run() # same module object, injected forward + torch.testing.assert_close(out_i, out_p, atol=ATOL, rtol=RTOL) + torch.testing.assert_close(grad_i, grad_p, atol=GATOL, rtol=GRTOL) + + +@pytest.mark.skipif(get_accelerator().device_name() == "cpu", reason="non-CPU device required") +class TestGDNLayerParity: + + def test_forward_and_backward(self, model): + """GDN layer pre/post injection: output + input gradient.""" + from deepspeed.module_inject.segment_ki import apply_segment_ki + layer = _pick_layer(model, "linear_attention") + torch.manual_seed(0) + hidden = torch.randn(2, 5, model.config.hidden_size, dtype=torch.bfloat16, device="cuda") + + def run(): + h = hidden.clone().requires_grad_(True) + out = layer(h) # GDN block: no position/rotary inputs + loss = out.float().pow(2).sum() + loss.backward() + return out.float(), h.grad.float() + + out_p, grad_p = run() + apply_segment_ki(model) + out_i, grad_i = run() + torch.testing.assert_close(out_i, out_p, atol=ATOL, rtol=RTOL) + torch.testing.assert_close(grad_i, grad_p, atol=GATOL, rtol=GRTOL) + + +@pytest.mark.skipif(get_accelerator().device_name() == "cpu", reason="non-CPU device required") +class TestMLPParity: + """Injected GLU replacement vs the HF formula on the same weights.""" + + def test_forward_and_weight_grads(self, model): + from deepspeed.module_inject.segment_ki import apply_segment_ki + apply_segment_ki(model) + mlp = next(m for n, m in model.named_modules() if n.endswith("mlp")) + torch.manual_seed(0) + x = torch.randn(2, 5, mlp.gate_proj.in_features, dtype=torch.bfloat16, device="cuda") + + x1 = x.clone().requires_grad_(True) + out1 = mlp(x1) # injected forward (composite path, grad-enabled) + out1.float().pow(2).sum().backward() + + x2 = x.clone().requires_grad_(True) + ref = mlp.down_proj(torch.nn.functional.silu(mlp.gate_proj(x2)) * mlp.up_proj(x2)) + ref.float().pow(2).sum().backward() + + torch.testing.assert_close(out1.float(), ref.float(), atol=ATOL, rtol=RTOL) + torch.testing.assert_close(x1.grad.float(), x2.grad.float(), atol=GATOL, rtol=GRTOL) + + +@pytest.mark.skipif(get_accelerator().device_name() == "cpu", reason="non-CPU device required") +class TestFusedAddNormVsHFFormula: + """The reviewer's rounding-order case: HF materializes the residual sum + in bf16 before the norm; the kernel keeps the fp32 sum for the output + and rounds only the residual write-back. Pin both sides' magnitude.""" + + def test_output_and_residual_vs_hf(self, model): + from deepspeed.ops.module_inject import get_fused_glu_op + torch.manual_seed(0) + dim = 256 + h = (torch.randn(4, dim, device="cuda") * 0.5).bfloat16() + r = (torch.randn(4, dim, device="cuda") * 0.5).bfloat16() + w = (torch.randn(dim, device="cuda") * 0.1).bfloat16() + eps = 1e-6 + + h_kernel = h.clone() + # hold the scaled weight in a variable: the kernel launch is async, + # and an unreferenced temporary's memory can be handed to the next + # allocation (the ref below) before the kernel reads it + w_scaled = (1.0 + w.float()).bfloat16() + out_kernel = get_fused_glu_op().fused_add_norm(h_kernel, r, w_scaled, eps) + + # HF formula verbatim: bf16 sum materialized, fp32 norm, (1+w) scale + combined_bf16 = h + r # bf16 rounding happens here in HF + xf = combined_bf16.float() + ref = (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps) * (1.0 + w.float())).bfloat16() + + torch.testing.assert_close(out_kernel.float(), ref.float(), atol=ATOL, rtol=RTOL) + # the residual stream the kernel writes back is the bf16 sum, as in HF + torch.testing.assert_close(h_kernel.float(), combined_bf16.float(), atol=ATOL, rtol=RTOL) diff --git a/tests/unit/module_inject/test_segment_ki_kernels.py b/tests/unit/module_inject/test_segment_ki_kernels.py new file mode 100644 index 000000000000..b2966cf06f51 --- /dev/null +++ b/tests/unit/module_inject/test_segment_ki_kernels.py @@ -0,0 +1,780 @@ +# 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 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 gated_norm as ref_gated_norm +from deepspeed.module_inject.kernel_reference import grouped_linear as ref_grouped_linear + +DEV = get_accelerator().device_name() + + +def _kernel_op_available() -> bool: + """True when this accelerator registers the segment-KI op builder. + + The kernels are CUDA source today; other backends (XPU/HPU/NPU/MPS) do + not register the builder, so their CI must skip rather than fail while + JIT-loading CUDA sources. A backend that implements the op later gets + these tests automatically.""" + try: + builder = get_accelerator().get_op_builder("FusedGLUBuilder") + except Exception: + return False + # backends without the op answer with the NotImplemented placeholder + return builder is not None and builder.__name__ != "NotImplementedBuilder" + + +GPU_AVAILABLE = _kernel_op_available() + + +def _as_concat(parts): + """Normalize grouped_linear output: some routing paths return + concatenated (list of 1), others separate (list of n).""" + return torch.cat(parts, dim=-1) if len(parts) > 1 else parts[0] + + +def _op(): + from deepspeed.ops.module_inject import get_fused_glu_op + return get_fused_glu_op() + + +def _rand_bf16(*shape, device=DEV): + return torch.randn(*shape, dtype=torch.float32, device=device).bfloat16() + + +# --------------------------------------------------------------------------- +# 1. Kernel vs reference consistency (GPU) +# --------------------------------------------------------------------------- + + +@pytest.mark.skipif(not GPU_AVAILABLE, reason="non-CPU device required") +class TestKernelReferenceConsistency: + + def test_gated_norm(self): + """GDN z-gated norm kernel vs reference: (w * rms(x)) * silu(z).""" + torch.manual_seed(0) + b, dim = 4, 256 + x = _rand_bf16(b, dim) + z = _rand_bf16(b, dim) + w = _rand_bf16(dim) + out = torch.empty_like(x) + _op().gated_norm(x, z, w, out, 1e-6) + expected = ref_gated_norm(x.float(), z.float(), w.float()) + torch.testing.assert_close(out.float(), expected, atol=5e-2, rtol=5e-2) + + def test_decode_attn_fused_q(self): + """Fused q-side path: the kernel applies per-head RMSNorm (1+w), + rotate-half RoPE at the row position, and the sigmoid output gate + in-register; against the same math in torch plus the plain + reference attention.""" + torch.manual_seed(0) + nq, nkv, hd, maxlen, b = 8, 2, 128, 40, 4 + q_raw = torch.randn(b, nq, hd, dtype=torch.float32, device=DEV).bfloat16() + K = torch.randn(b, nkv, maxlen, hd, dtype=torch.float32, device=DEV).bfloat16() + V = torch.randn(b, nkv, maxlen, hd, dtype=torch.float32, device=DEV).bfloat16() + gate = torch.randn(b, nq, hd, dtype=torch.float32, device=DEV).bfloat16() + nw = torch.randn(hd, dtype=torch.float32, device=DEV) + pos = torch.tensor([5, 11, 0, 39], dtype=torch.long, device=DEV) + cos_t = torch.randn(maxlen, hd, dtype=torch.float32, device=DEV) + sin_t = torch.randn(maxlen, hd, dtype=torch.float32, device=DEV) + + out = torch.empty(b, nq, hd, dtype=torch.bfloat16, device=DEV) + _op().decode_attn(q_raw, + K, + V, + pos, + out, + nq, + nkv, + hd, + maxlen, + q_norm_w=1.0 + nw, + cos_t=cos_t, + sin_t=sin_t, + gate=gate, + k_raw=torch.empty(0, device=DEV), + v_raw=torch.empty(0, device=DEV), + k_norm_w=torch.empty(0, device=DEV), + eps=1e-6, + rope_dim=hd) + + # reference: norm -> rope -> attention -> gate + qf = q_raw.float() + qf = qf * torch.rsqrt(qf.pow(2).mean(-1, keepdim=True) + 1e-6) * (1.0 + nw) + half = hd // 2 + rot = torch.cat((-qf[..., half:], qf[..., :half]), dim=-1) + cs = cos_t[pos].unsqueeze(1) # [b, 1, hd] + sn = sin_t[pos].unsqueeze(1) + qf = qf * cs + rot * sn + attn = ref_decode_attn(qf.bfloat16().float(), K.float(), V.float(), pos) + expected = attn * torch.sigmoid(gate.float()).view(b, nq, hd) + torch.testing.assert_close(out.float(), expected, atol=5e-2, rtol=5e-2) + + def test_decode_attn_fused_q_partial_rope(self): + """Partial RoPE (Qwen3.5 convention): rotation over [0, rope_dim) + only, remaining head dims pass through.""" + torch.manual_seed(1) + nq, nkv, hd, rope_dim, maxlen, b = 16, 4, 256, 64, 40, 2 + q_raw = torch.randn(b, nq, hd, dtype=torch.float32, device=DEV).bfloat16() + K = torch.randn(b, nkv, maxlen, hd, dtype=torch.float32, device=DEV).bfloat16() + V = torch.randn(b, nkv, maxlen, hd, dtype=torch.float32, device=DEV).bfloat16() + gate = torch.randn(b, nq, hd, dtype=torch.float32, device=DEV).bfloat16() + nw = torch.randn(hd, dtype=torch.float32, device=DEV) + pos = torch.tensor([7, 21], dtype=torch.long, device=DEV) + cos_t = torch.randn(maxlen, rope_dim, dtype=torch.float32, device=DEV) + sin_t = torch.randn(maxlen, rope_dim, dtype=torch.float32, device=DEV) + out = torch.empty(b, nq, hd, dtype=torch.bfloat16, device=DEV) + _op().decode_attn(q_raw, + K, + V, + pos, + out, + nq, + nkv, + hd, + maxlen, + q_norm_w=1.0 + nw, + cos_t=cos_t, + sin_t=sin_t, + gate=gate, + k_raw=torch.empty(0, device=DEV), + v_raw=torch.empty(0, device=DEV), + k_norm_w=torch.empty(0, device=DEV), + eps=1e-6, + rope_dim=rope_dim) + qf = q_raw.float() + qf = qf * torch.rsqrt(qf.pow(2).mean(-1, keepdim=True) + 1e-6) * (1.0 + nw) + q_rot, q_pass = qf[..., :rope_dim], qf[..., rope_dim:] + half = rope_dim // 2 + rot = torch.cat((-q_rot[..., half:], q_rot[..., :half]), dim=-1) + cs = cos_t[pos].unsqueeze(1) + sn = sin_t[pos].unsqueeze(1) + qf = torch.cat((q_rot * cs + rot * sn, q_pass), dim=-1) + attn = ref_decode_attn(qf.bfloat16().float(), K.float(), V.float(), pos) + expected = attn * torch.sigmoid(gate.float()).view(b, nq, hd) + torch.testing.assert_close(out.float(), expected, atol=5e-2, rtol=5e-2) + + def test_decode_step_graph_contract(self): + """The full-step graph kernel must reproduce torch.argmax (first + index on ties), advance write_pos, reveal exactly the next slot, + and record the token in the buffer across repeated calls.""" + vocab, max_len = 2048, 16 + logits = torch.full((1, vocab), -3.0, dtype=torch.bfloat16, device=DEV) + logits[0, 10] = 2.0 + logits[0, 1500] = 2.0 # exact bf16 tie: torch.argmax keeps index 10 + token_out = torch.zeros(1, 1, dtype=torch.long, device=DEV) + write_pos = torch.tensor([5], dtype=torch.long, device=DEV) + mask = torch.zeros(1, 1, 1, max_len, dtype=torch.bool, device=DEV) + out_buf = torch.zeros(1, max_len, dtype=torch.long, device=DEV) + + expected = torch.argmax(logits[0].float()) + assert expected.item() == 10 # torch.argmax first-index rule + + _op().decode_step_graph(logits, token_out, write_pos, mask, out_buf) + assert token_out.view(-1)[0].item() == 10 + assert write_pos.item() == 6 + assert bool(mask[0, 0, 0, 6]) and not bool(mask[0, 0, 0, 7]) + assert out_buf[0, 6].item() == 10 + + # a second call advances from the updated write_pos and reveals slot 7 + _op().decode_step_graph(logits, token_out, write_pos, mask, out_buf) + assert write_pos.item() == 7 + assert bool(mask[0, 0, 0, 7]) and not bool(mask[0, 0, 0, 8]) + assert out_buf[0, 7].item() == 10 + + def test_decode_step_graph_batched(self): + """b=4 rows with per-row positions: each row argmaxes its own logits + slice, advances only its own write_pos entry, reveals its own mask + row, and stores into its own buffer row.""" + vocab, max_len, b = 512, 8, 4 + logits = torch.full((b, vocab), -3.0, dtype=torch.bfloat16, device=DEV) + wants = [5, 400, 100, 0] + for r, w in enumerate(wants): + logits[r, w] = 2.0 + token_out = torch.zeros(b, 1, dtype=torch.long, device=DEV) + write_pos = torch.tensor([3, 5, 1, 6], dtype=torch.long, device=DEV) + mask = torch.zeros(b, 1, 1, max_len, dtype=torch.bool, device=DEV) + out_buf = torch.zeros(b, max_len, dtype=torch.long, device=DEV) + _op().decode_step_graph(logits, token_out, write_pos, mask, out_buf) + assert token_out.view(-1).tolist() == wants + assert write_pos.tolist() == [4, 6, 2, 7] + for r, w in enumerate(wants): + assert bool(mask[r, 0, 0, r + 4 - 1]) or True # positions differ per row; check below + for r in range(b): + assert out_buf[r, [4, 6, 2, 7][r]].item() == wants[r] + assert bool(mask[r, 0, 0, [4, 6, 2, 7][r]]) + + def test_dual_gemv_silu_mul(self): + h = _rand_bf16(256) + gw = _rand_bf16(384, 256) + uw = _rand_bf16(384, 256) + out = torch.empty(384, dtype=torch.bfloat16, device=DEV) + out = _op().grouped_linear(h, [gw, uw], True)[0] + expected = ref_grouped_linear(h.float(), [gw.float(), uw.float()], True)[0] + torch.testing.assert_close(out.float(), expected, atol=5e-2, rtol=5e-2) + + def test_quad_gemv(self): + h = _rand_bf16(128) + ws = [_rand_bf16(rows, 128) for rows in (96, 48, 6, 6)] + cat = _as_concat(_op().grouped_linear(h, list(ws), False)) + expected = torch.cat(ref_grouped_linear(h.float(), [w.float() for w in ws], False), dim=-1) + torch.testing.assert_close(cat.float(), expected, atol=5e-2, rtol=5e-2) + + def test_gdn_gates(self): + # a/b are [batch, seq, heads]; a_log/dt are per-head [heads] (real usage shapes) + a = _rand_bf16(1, 4, 8) + b = _rand_bf16(1, 4, 8) + a_log = torch.randn(8, device=DEV) # fp32, matching real usage + dt = torch.randn(8, device=DEV) + beta, g = _op().gdn_gates(a, b, a_log, dt) + ref_beta, ref_g = ref_gdn_gates(a, b, a_log, dt) + torch.testing.assert_close(beta.float(), ref_beta.float(), atol=1e-2, rtol=1e-2) + torch.testing.assert_close(g.float(), ref_g.float(), atol=5e-2, rtol=5e-2) + + def test_triple_gemv(self): + h = _rand_bf16(128) + qw, kw, vw = (_rand_bf16(64, 128) for _ in range(3)) + q, k, v = _op().grouped_linear(h, [qw, kw, vw], False) + ref_q, ref_k, ref_v = ref_grouped_linear(h.float(), [qw.float(), kw.float(), vw.float()], False) + for got, exp in ((q, ref_q), (k, ref_k), (v, ref_v)): + torch.testing.assert_close(got.float(), exp, atol=5e-2, rtol=5e-2) + + def test_fused_add_norm(self): + for rows in (1, 4): # the kernel is one-block-per-row + h = _rand_bf16(rows, 128) + r = _rand_bf16(rows, 128) + w = _rand_bf16(128) + h_kernel = h.clone() # the kernel updates hidden in place + out = _op().fused_add_norm(h_kernel, r, w, 1e-5) + ref_out = ref_add_norm(h, r, w, eps=1e-5) + torch.testing.assert_close(out.float(), ref_out.float(), atol=5e-2, rtol=5e-2) + # hidden is updated in place to the pre-norm sum, every row + torch.testing.assert_close(h_kernel.float(), (h.float() + r.float()), atol=5e-2, rtol=5e-2) + + def test_decode_attn(self): + """Batched decode attention vs reference: uniform b=1, b=4 with a + shared position, and b=4 with per-row positions.""" + torch.manual_seed(0) + nq, nkv, hd, maxlen = 8, 2, 64, 33 + for b, per_row in [(1, False), (4, False), (4, True)]: + q = torch.randn(b, nq, hd, dtype=torch.float32, device=DEV).bfloat16() + K = torch.randn(b, nkv, maxlen, hd, dtype=torch.float32, device=DEV).bfloat16() + V = torch.randn(b, nkv, maxlen, hd, dtype=torch.float32, device=DEV).bfloat16() + if per_row: + pos = torch.randint(0, maxlen - 1, (b, ), dtype=torch.long, device=DEV) + else: + pos = torch.tensor([17], dtype=torch.long, device=DEV) + out = torch.empty(b, nq, hd, dtype=torch.bfloat16, device=DEV) + _op().decode_attn(q, K, V, pos, out, nq, nkv, hd, maxlen) + ref_pos = pos if per_row else int(pos[0]) + expected = ref_decode_attn(q.float(), K.float(), V.float(), ref_pos) + torch.testing.assert_close(out.float(), expected, atol=5e-2, rtol=5e-2) + + +# --------------------------------------------------------------------------- +# 2. Composite paths and injection invariants (CPU) +# --------------------------------------------------------------------------- + + +class _MiniGLU(torch.nn.Module): + + def __init__(self, hidden=32, inter=48): + super().__init__() + self.gate_proj = torch.nn.Linear(hidden, inter, bias=False, dtype=torch.bfloat16) + self.up_proj = torch.nn.Linear(hidden, inter, bias=False, dtype=torch.bfloat16) + self.down_proj = torch.nn.Linear(inter, hidden, bias=False, dtype=torch.bfloat16) + self.act_fn = torch.nn.SiLU() + + def forward(self, x): + return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + + +class _MiniGeluGated(torch.nn.Module): + """GELU-gated MLP (Gemma-style): same projection names, different act.""" + + def __init__(self, hidden=32, inter=48): + super().__init__() + self.gate_proj = torch.nn.Linear(hidden, inter, bias=False, dtype=torch.bfloat16) + self.up_proj = torch.nn.Linear(hidden, inter, bias=False, dtype=torch.bfloat16) + self.down_proj = torch.nn.Linear(inter, hidden, bias=False, dtype=torch.bfloat16) + self.act_fn = torch.nn.GELU() + + def forward(self, x): + return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + + +class TestInjectionInvariants: + + def test_apply_and_forward_equivalence(self): + """apply_segment_ki on CPU installs composite replacements whose + output matches the un-injected forward bit-for-bit.""" + from deepspeed.module_inject.segment_ki import apply_segment_ki + torch.manual_seed(0) + model = _MiniGLU().eval() + x = torch.randn(1, 4, 32, dtype=torch.bfloat16) + with torch.no_grad(): + expected = model(x) + report = apply_segment_ki(model) + assert report["fused_glu"]["segments_replaced"] == 1 + with torch.no_grad(): + got = model(x) + torch.testing.assert_close(got.float(), expected.float(), atol=1e-2, rtol=1e-2) + + def test_gelu_gated_mlp_not_fused(self): + """A GELU-gated MLP satisfies the projection-name selector but must + not be fused: the replacement hardcodes SiLU and would silently + change its logits.""" + from deepspeed.module_inject.segment_ki import apply_segment_ki + model = _MiniGeluGated().eval() + report = apply_segment_ki(model) + assert report["fused_glu"]["segments_replaced"] == 0 + + def test_no_weight_copies_installed(self): + """Injection must not materialize fused weight buffers.""" + from deepspeed.module_inject.segment_ki import apply_segment_ki + model = _MiniGLU() + apply_segment_ki(model) + for name, attr in model.named_modules(): + if name: + assert not isinstance(getattr(attr, "_ki_dual_op", None), torch.Tensor), name + assert not hasattr(attr, "_ki_gdn_fused_weight"), name + + def test_composite_forward_cpu(self): + """The autograd.Function fallbacks run on CPU tensors.""" + from deepspeed.module_inject.segment_ki import GDNInputProj + h = torch.randn(1, 4, 32, dtype=torch.bfloat16) + ws = [torch.randn(r, 32, dtype=torch.bfloat16) for r in (40, 16, 4, 4)] + got = GDNInputProj.apply(h, *ws, None) + expected = torch.cat(ref_grouped_linear(h.float(), [w.float() for w in ws], False), dim=-1) + torch.testing.assert_close(got.float(), expected.float(), atol=1e-2, rtol=1e-2) + + def test_composite_backward_scatters_to_original_weights(self): + """Backward through the composite path lands on the original + weight Parameters — the co-location gradient contract.""" + from deepspeed.module_inject.segment_ki import GDNInputProj + h = torch.randn(4, 32, dtype=torch.float32) + ws = [torch.randn(r, 32, dtype=torch.float32, requires_grad=True) for r in (40, 16, 4, 4)] + GDNInputProj.apply(h, *ws, None).pow(2).sum().backward() + for i, w in enumerate(ws): + assert w.grad is not None, f"weight {i} got no gradient" + + +# --------------------------------------------------------------------------- +# 3. Rollout -> train -> rollout integration (GPU + real model) +# --------------------------------------------------------------------------- + +_TEST_MODEL = os.environ.get("DS_SEGMENT_KI_TEST_MODEL", "Qwen/Qwen3.5-0.8B") + + +@pytest.mark.skipif(not GPU_AVAILABLE, reason="non-CPU device required") +class TestGraphPathWithoutSegki: + """The graph-capture path with use_segki=False drives the *native* HF + GDN forward, which reads conv/recurrent state through the cache's + top-level protocol entries. A missing delegation crashes (and silently + untested halves of the path rot); the outputs must also stay + token-identical to plain generate.""" + + def test_graph_decode_without_segki_matches_hf(self): + pytest.importorskip("transformers") + try: + from transformers import AutoModelForCausalLM, AutoTokenizer + tokenizer = AutoTokenizer.from_pretrained(_TEST_MODEL) + model = AutoModelForCausalLM.from_pretrained(_TEST_MODEL, + dtype=torch.bfloat16).to(get_accelerator().device_name()) + except Exception as e: + pytest.skip(f"model {_TEST_MODEL} unavailable: {e}") + + object.__setattr__(tokenizer, "eos_token_id", -1) + from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig + from deepspeed.runtime.rollout.base import RolloutRequest, SamplingConfig + + class Shim: + + def __init__(self, m): + self.module = m + + rollout = HybridEngineRollout(Shim(model), tokenizer, + HybridEngineRolloutConfig(use_graph_capture=True, use_segki=False)) + ids = torch.randint(1000, 50000, (1, 128), device=get_accelerator().device_name()) + attn = torch.ones_like(ids) + greedy = SamplingConfig(max_new_tokens=16, temperature=0.0) + + got = rollout.generate(RolloutRequest(prompt_ids=ids, prompt_attention_mask=attn), greedy) + with torch.no_grad(): + ref = model.generate(ids, + attention_mask=attn, + max_new_tokens=16, + do_sample=False, + pad_token_id=tokenizer.eos_token_id) + assert got.input_ids[0].tolist() == ref[0].tolist(), \ + "graph path without segKI diverged from plain generate" + + +@pytest.mark.skipif(not GPU_AVAILABLE, reason="non-CPU device required") +class TestRolloutTrainRollout: + + def test_rl_loop_needs_no_switch_or_sync(self): + """The co-location contract end-to-end: generate with full + segKI + graph capture, train one step through the same injected + model, generate again — output must change (fresh weights), with + no inject/eject/sync call anywhere in between.""" + pytest.importorskip("transformers") + try: + from transformers import AutoModelForCausalLM, AutoTokenizer + tokenizer = AutoTokenizer.from_pretrained(_TEST_MODEL) + model = AutoModelForCausalLM.from_pretrained(_TEST_MODEL, + dtype=torch.bfloat16).to(get_accelerator().device_name()) + except Exception as e: # offline / model not cached + pytest.skip(f"model {_TEST_MODEL} unavailable: {e}") + + from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig + + class _EngineShim: + + def __init__(self, m): + self.module = m + + rollout = HybridEngineRollout(_EngineShim(model), tokenizer, + HybridEngineRolloutConfig(use_graph_capture=True, use_segki=True)) + assert rollout._segki_report["fused_glu"]["segments_replaced"] > 0 + + prompt_ids = tokenizer("The capital of France is", + return_tensors="pt").input_ids.to(get_accelerator().device_name()) + attn = torch.ones_like(prompt_ids) + from deepspeed.runtime.rollout.base import RolloutRequest, SamplingConfig + req = RolloutRequest(prompt_ids=prompt_ids, prompt_attention_mask=attn) + greedy = SamplingConfig(max_new_tokens=24, temperature=0.0) + + batch1 = rollout.generate(req, greedy) + + # one training step through the SAME injected model + first_glu = next(m for n, m in model.named_modules() if n.endswith("mlp")) + gate_w_before = first_glu.gate_proj.weight.detach().clone() + out = model(batch1.input_ids) + loss = out.logits.float().pow(2).mean() + loss.backward() + assert first_glu.gate_proj.weight.grad is not None, "gradient did not reach gate_proj" + torch.optim.SGD(model.parameters(), lr=0.5).step() + model.zero_grad() + + # Live-weight contract, deterministically: the injected projection + # must read the Parameter's current values, so its output changes + # once the optimizer updated the weights. + from deepspeed.module_inject.segment_ki import DualWeightGluGEMV + probe = torch.randn_like(gate_w_before[0]).bfloat16() + w_now = first_glu.gate_proj.weight.detach() + before = DualWeightGluGEMV.apply(probe, gate_w_before, first_glu.up_proj.weight.detach(), None) + after = DualWeightGluGEMV.apply(probe, w_now, first_glu.up_proj.weight.detach(), None) + assert not torch.equal(before, after), "injected projection still reads pre-step weights" + + # still exercise the post-training generate path end-to-end + rollout.generate(req, greedy) + + def test_grouped_gemm_small_batch(self): + """Grouped GEMM vs reference: the multi-matrix single-launch kernels + for decode batches 2..32 (concat and GLU-paired variants).""" + from deepspeed.module_inject import kernel_reference as ref + for M in (2, 8, 32): + K, fq, fk, fv = 128, 64, 32, 32 + x = _rand_bf16(M, K) + qw, kw, vw = _rand_bf16(fq, K), _rand_bf16(fk, K), _rand_bf16(fv, K) + rq, rk, rv = ref.grouped_linear(x.float(), [qw.float(), kw.float(), vw.float()], False) + q_out, k_out, v_out = _op().grouped_linear(x, [qw, kw, vw], False) + torch.testing.assert_close(q_out.float(), rq, atol=5e-2, rtol=5e-2) + torch.testing.assert_close(k_out.float(), rk, atol=5e-2, rtol=5e-2) + torch.testing.assert_close(v_out.float(), rv, atol=5e-2, rtol=5e-2) + + gz_w, b_w, a_w = _rand_bf16(48, K), _rand_bf16(16, K), _rand_bf16(16, K) + w4 = [qw, gz_w, b_w, a_w] + parts = _op().grouped_linear(x, w4, False) + cat = torch.cat(parts, dim=-1) if len(parts) > 1 else parts[0] + ref_parts = ref.grouped_linear(x.float(), [w.float() for w in w4], False) + ref_cat = torch.cat(ref_parts, dim=-1) + torch.testing.assert_close(cat.float(), ref_cat, atol=5e-2, rtol=5e-2) + + gw, uw = _rand_bf16(fq, K), _rand_bf16(fq, K) + glu = _op().grouped_linear(x, [gw, uw], True)[0] + ref_glu = ref.grouped_linear(x.float(), [gw.float(), uw.float()], True)[0] + torch.testing.assert_close(glu.float(), ref_glu, atol=5e-2, rtol=5e-2) + + def test_grouped_gemm_rejects_out_of_range(self): + import pytest as _pytest + x = _rand_bf16(32, 64) + w = _rand_bf16(32, 64) + with _pytest.raises(RuntimeError): + # 7 weights exceeds the dispatcher's supported range (1..6) + _op().grouped_linear(x, [w] * 7, False) + + def test_grouped_linear_dispatcher(self): + """The portable interface entry: weight count x batch routing vs the + reference for every combination (gemv / grouped / aten composite).""" + from deepspeed.module_inject import kernel_reference as ref + op = _op() + K = 128 + for M in (1, 8, 32, 64): + x = _rand_bf16(M, K) if M > 1 else _rand_bf16(K) + w1 = _rand_bf16(64, K) + out = op.grouped_linear(x, [w1], False) + assert len(out) >= 1, f"grouped_linear returned empty for M={M}, n=1" + if M > op.capabilities()["max_grouped_batch"]: + # composite route: bf16 matmul (same rounding as the route) + exp = torch.matmul(x.reshape(-1, K) if M > 1 else x, w1.t()) + else: + exp = torch.matmul(x.float().reshape(-1, K), w1.float().t()) + torch.testing.assert_close(out[0].float(), exp.float().reshape(out[0].shape), atol=5e-2, rtol=5e-2) + + gw, uw = _rand_bf16(64, K), _rand_bf16(64, K) + out = op.grouped_linear(x, [gw, uw], True) + # batches above the grouped range route to the composite, whose + # matmul output rounds to bf16 before the epilogue (matching HF + # eager semantics); the fp32 reference skips that rounding, so + # anchor large batches on the same-dtype reference instead + if M > op.capabilities()["max_grouped_batch"]: + ref_glu = ref.grouped_linear(x, [gw, uw], True)[0] + torch.testing.assert_close(out[0].float(), ref_glu.float().reshape(out[0].shape), atol=5e-2, rtol=5e-2) + else: + ref_glu = ref.grouped_linear(x.float().reshape(-1, K) if M > 1 else x.float(), + [gw.float(), uw.float()], True)[0] + torch.testing.assert_close(out[0].float(), ref_glu.reshape(out[0].shape), atol=5e-2, rtol=5e-2) + + kw, vw = _rand_bf16(32, K), _rand_bf16(32, K) + q, k, v = op.grouped_linear(x, [w1, kw, vw], False) + if M > op.capabilities()["max_grouped_batch"]: + rq = torch.matmul(x.reshape(-1, K) if M > 1 else x, w1.t()) # composite: bf16 matmul + else: + rq = torch.matmul(x.float().reshape(-1, K), w1.float().t()) + torch.testing.assert_close(q.float(), rq.float().reshape(q.shape), atol=5e-2, rtol=5e-2) + + z, b, a = _rand_bf16(48, K), _rand_bf16(16, K), _rand_bf16(16, K) + q_parts = op.grouped_linear(x, [w1, z, b, a], False) + assert len(q_parts) >= 1, f"grouped_linear returned empty for M={M}, n=4" + cat = _as_concat(q_parts) + xq = x.reshape(-1, K) if M > 1 else x + if M > op.capabilities()["max_grouped_batch"]: + rc = torch.cat(ref.grouped_linear(xq, [w1, z, b, a], False), dim=-1).float() + torch.testing.assert_close(cat.float(), rc.reshape(cat.shape), atol=5e-2, rtol=5e-2) + else: + rc = torch.cat(ref.grouped_linear( + xq.float(), [w1.float(), z.float(), b.float(), a.float()], False), + dim=-1) + torch.testing.assert_close(cat.float(), rc.reshape(cat.shape), atol=5e-2, rtol=5e-2) + caps = op.capabilities() + assert caps["max_grouped_batch"] >= 32 and "bf16" in list(caps["dtypes"]) + + +class TestArenaWeightViews: + """Contract for arena/reshard syncs: weights updated IN PLACE (same + addresses, new values) with segki_refresh() called afterwards must + produce exactly what a fresh injection over the same weights produces + — bitwise. Without the refresh, derived caches serve stale copies + mixed with fresh direct reads.""" + + def _make_rollout(self, tok): + from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig + from transformers import AutoModelForCausalLM + m = AutoModelForCausalLM.from_pretrained(_TEST_MODEL, dtype=torch.bfloat16).to(get_accelerator().device_name()) + + class Shim: + + def __init__(self, m): + self.module = m + self._cfg = m.config + + shim = Shim(m) + if isinstance(getattr(shim.module, "config", None), dict): + shim.module.config = m.config + # graph capture needs a real accelerator: CPU stubs return None streams + # and no-op graph replays, so the eager path exercises the same + # weight-view contract there + graphs_ok = get_accelerator().device_name() != "cpu" + rollout = HybridEngineRollout(shim, tok, HybridEngineRolloutConfig(use_graph_capture=graphs_ok, + use_segki=True)) + return rollout, m + + def _gen(self, rollout, ids): + from deepspeed.runtime.rollout.base import RolloutRequest, SamplingConfig + out = rollout.generate(RolloutRequest(prompt_ids=ids, prompt_attention_mask=torch.ones_like(ids)), + SamplingConfig(max_new_tokens=16, temperature=0.0)) + return out.input_ids[:, ids.shape[1]:] + + def test_inplace_update_refresh_matches_fresh_injection(self): + pytest.importorskip("transformers") + try: + from transformers import AutoTokenizer + tok = AutoTokenizer.from_pretrained(_TEST_MODEL) + except Exception as e: + pytest.skip(f"model {_TEST_MODEL} unavailable: {e}") + object.__setattr__(tok, "eos_token_id", -1) + torch.manual_seed(11) + ids = torch.randint(1000, 50000, (2, 128), device=get_accelerator().device_name()) + + # baseline rollout — its first generate builds the derived caches + rollout, m = self._make_rollout(tok) + self._gen(rollout, ids) + + # in-place weight update (arena sync semantics: same storage) + with torch.no_grad(): + for p in m.parameters(): + p.mul_(1.5) + + # the handshake + from deepspeed.module_inject.segment_ki import segki_refresh + segki_refresh(m) + out_refreshed = self._gen(rollout, ids) + + # ground truth: a fresh injection over the SAME updated weights + rollout2, m2 = self._make_rollout(tok) + with torch.no_grad(): + for p2, p in zip(m2.parameters(), m.parameters()): + p2.copy_(p) + self._gen(rollout2, ids) # builds fresh caches on the right values + out_fresh = self._gen(rollout2, ids) + + assert torch.equal( + out_refreshed, + out_fresh), (f"refresh path diverged from fresh injection: " + f"{(out_refreshed != out_fresh).sum().item()} of {out_fresh.numel()} tokens differ") + + def test_glu_only_model_refresh_clears_backend_cat_cache(self): + """GLU-only (dense) models carry the backend handle on _ki_dual_op; + segki_refresh must still reach the process-wide g_glu_cat_cache + after an in-place sync (review finding: the lookup only read + _ki_gdn_op, leaving the gate|up concat stale on dense models).""" + pytest.importorskip("transformers") + glu_model = os.environ.get("DS_SEGMENT_KI_GLU_TEST_MODEL", "Qwen/Qwen3-0.6B") + try: + from transformers import AutoTokenizer + tok = AutoTokenizer.from_pretrained(glu_model) + except Exception as e: + pytest.skip(f"model {glu_model} unavailable: {e}") + object.__setattr__(tok, "eos_token_id", -1) + + from transformers import AutoModelForCausalLM + torch.manual_seed(13) + ids = torch.randint(1000, 50000, (2, 128), device=get_accelerator().device_name()) + m = AutoModelForCausalLM.from_pretrained(glu_model, dtype=torch.bfloat16).to(get_accelerator().device_name()) + layer_types = getattr(getattr(m.config, "text_config", m.config), "layer_types", None) or [] + if any("linear" in lt for lt in layer_types): + pytest.skip(f"{glu_model} has linear-attention layers; need a dense GLU-only model") + + class Shim: + + def __init__(self, m): + self.module = m + self._cfg = m.config + + from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig + graphs_ok = get_accelerator().device_name() != "cpu" + rollout = HybridEngineRollout(Shim(m), tok, HybridEngineRolloutConfig(use_graph_capture=graphs_ok, + use_segki=True)) + self._gen(rollout, ids) # builds every derived cache (incl. the C++ concat) + + # the injection on a dense model carries the handle on _ki_dual_op only + duals = [mod for mod in m.modules() if getattr(mod, "_ki_dual_op", None) is not None] + gdns = [mod for mod in m.modules() if getattr(mod, "_ki_gdn_op", None) is not None] + assert duals and not gdns, "dense model must be injected GLU-only" + + with torch.no_grad(): + for p in m.parameters(): + p.mul_(1.5) # arena-sync semantics: same storage + from deepspeed.module_inject.segment_ki import segki_refresh + segki_refresh(m) + out_refreshed = self._gen(rollout, ids) + + m2 = AutoModelForCausalLM.from_pretrained(glu_model, dtype=torch.bfloat16).to(get_accelerator().device_name()) + rollout2 = HybridEngineRollout(Shim(m2), tok, HybridEngineRolloutConfig(use_graph_capture=graphs_ok, + use_segki=True)) + with torch.no_grad(): + for p2, p in zip(m2.parameters(), m.parameters()): + p2.copy_(p) + self._gen(rollout2, ids) + out_fresh = self._gen(rollout2, ids) + + assert torch.equal(out_refreshed, out_fresh), ("dense-model refresh diverged from fresh injection: " + f"{(out_refreshed != out_fresh).sum().item()} tokens differ") + + def test_arena_view_binding_survives_inplace_writes(self): + pytest.importorskip("transformers") + try: + from transformers import AutoTokenizer + tok = AutoTokenizer.from_pretrained(_TEST_MODEL) + except Exception as e: + pytest.skip(f"model {_TEST_MODEL} unavailable: {e}") + object.__setattr__(tok, "eos_token_id", -1) + torch.manual_seed(23) + ids = torch.randint(1000, 50000, (2, 128), device=get_accelerator().device_name()) + + # bind parameter storage to external arena tensors, then update + # the ARENA in place — parameters must see the new values without + # any rebinding (fixed-address contract) + rollout, m = self._make_rollout(tok) + arena = {n: p.detach().clone() for n, p in m.named_parameters()} + with torch.no_grad(): + for n, p in m.named_parameters(): + p.data = arena[n] + self._gen(rollout, ids) # caches built against arena storage + + with torch.no_grad(): + for t in arena.values(): + t.mul_(0.75) # reshard writes NEW values into the SAME arena + + from deepspeed.module_inject.segment_ki import segki_refresh + segki_refresh(m) + out_after = self._gen(rollout, ids) + + rollout2, m2 = self._make_rollout(tok) + with torch.no_grad(): + for n, p2 in m2.named_parameters(): + p2.copy_(arena[n]) + self._gen(rollout2, ids) + out_fresh = self._gen(rollout2, ids) + + assert torch.equal(out_after, out_fresh), "arena in-place write + refresh diverged from fresh injection" + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="native kernels are CUDA-only") #ignore-cuda +class TestAmpereGlueReferences: + """Direct reference anchors for the glue kernels that entered after the + original ten: the Ampere GLU epilogue and the scan head-repeat.""" + + def test_silu_mul_matches_reference(self): + from deepspeed.module_inject.kernel_reference import silu_mul as ref_silu_mul + for M, n in ((32, 4608), (1, 2304), (64, 128)): + gu = _rand_bf16(M, 2 * n) + out = _op().silu_mul(gu, n) + r = ref_silu_mul(gu.float(), n) + torch.testing.assert_close(out.float(), r, atol=5e-2, rtol=5e-2) + + def test_repeat_qk_matches_reference(self): + from deepspeed.module_inject.kernel_reference import repeat_qk as ref_repeat_qk + for B, Hk, dk, ratio in ((32, 8, 128, 2), (4, 16, 128, 2), (64, 4, 64, 4)): + q = _rand_bf16(B, 1, Hk, dk) + k = _rand_bf16(B, 1, Hk, dk) + qo, ko = _op().repeat_qk(q, k, ratio) + qr, kr = ref_repeat_qk(q, k, ratio) + torch.testing.assert_close(qo.float(), qr.float(), atol=0, rtol=0) + torch.testing.assert_close(ko.float(), kr.float(), atol=0, rtol=0) diff --git a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py index 215b1898adcf..39b8f8cbea8c 100644 --- a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py +++ b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py @@ -1610,12 +1610,106 @@ def test_engine_pairs_shared_prefill_cache_tensors(): workspace.repeat_kv_cache.assert_called_once_with(2, 2) -# -- sync_weights is no-op --------------------------------------------- +# -- sync_weights invalidates derived caches --------------------------- -def test_sync_weights_is_noop(): - rollout = HybridEngineRollout(_make_engine(), _make_tokenizer()) - assert rollout.sync_weights(step=0) is None +def test_sync_weights_drops_derived_caches(): + # refresh_weights resolves the module through engine.module; the mock + # engine only has to expose it. A fake derived cache on the module + # must vanish after the training-step hook fires. + engine = _make_engine() + # a real module, not the mock's auto-attribute: segki_refresh walks + # .modules() and delattr must actually remove + engine.module = torch.nn.Identity() + engine.module._ki_tp_cat_w = object() # a derived-weight cache stand-in + rollout = HybridEngineRollout(engine, _make_tokenizer()) + rollout.sync_weights(step=0) + assert not hasattr(engine.module, "_ki_tp_cat_w") + + +def test_sync_weights_continuous_graph_safe(): + """Continuous graph + weight sync must not replay freed derived tensors. + + The retained continuous graph captures the derived tensors' addresses + (GLU concat cache, attention cat weights); a refresh that drops them + while the graph survives leaves replays reading freed memory. The + graph must be released across a sync (interim contract) until refresh + refills derived tensors in place.""" + pytest.importorskip("transformers") + from deepspeed.accelerator import get_accelerator + if get_accelerator().device_name() == "cpu": + pytest.skip("segKI injection needs an accelerator") + + model = _make_small_qwen() + device = next(model.parameters()).device + + def make_rollout(): + return HybridEngineRollout(SimpleNamespace(module=model), SimpleNamespace(pad_token_id=0, eos_token_id=None), + HybridEngineRolloutConfig(use_segki=True, use_graph_capture=True)) + + prompt = torch.randint(3, 28, (2, 8), device=device) + sampling = SamplingConfig(max_new_tokens=8, temperature=0, continuous_batch_size=2) + + rollout = make_rollout() + rollout.generate(RolloutRequest(prompt, torch.ones_like(prompt)), sampling) # capture + rollout.generate(RolloutRequest(prompt, torch.ones_like(prompt)), sampling) # reuse -> retained + # the hazard only exists when the graph actually survives across calls + assert rollout._continuous_graph_state is not None, "expected the continuous graph to be retained" + + with torch.no_grad(): + for p in model.parameters(): + p.mul_(3.0) + rollout.sync_weights(step=0) + # interim contract: the sync must release the retained graph. It captures + # the derived tensors' addresses wherever they exist (TP>1 cat weights, + # Ampere/Hopper GLU concat cache, GDN gates); refresh drops those tensors, + # so a surviving graph would replay freed memory. On configs without any + # derived tensor the replay would stay correct by luck -- pin the release + # so every config is safe by construction. + assert rollout._continuous_graph_state is None, "sync must release the retained continuous graph" + synced = rollout.generate(RolloutRequest(prompt, torch.ones_like(prompt)), sampling) + + fresh = make_rollout().generate(RolloutRequest(prompt, torch.ones_like(prompt)), sampling) + assert torch.equal(synced.input_ids, fresh.input_ids), \ + "post-sync continuous generate must match a fresh injection" + + +def test_sync_weights_generate_matches_fresh_injection(): + """Rollout-path weight sync: inject -> generate -> in-place write -> + sync_weights -> generate must equal a fresh injection of the same + weights (derived caches rebuilt, live reads see the new values).""" + pytest.importorskip("transformers") + from deepspeed.accelerator import get_accelerator + from transformers import AutoModelForCausalLM + if get_accelerator().device_name() == "cpu": + pytest.skip("segKI injection needs an accelerator") + + torch.manual_seed(0) + device = torch.device(get_accelerator().device_name()) + try: + model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3.5-0.8B-Base", dtype=torch.bfloat16).to(device).eval() + except Exception as e: + pytest.skip(f"model unavailable: {e}") + + def make_rollout(): + return HybridEngineRollout(SimpleNamespace(module=model), SimpleNamespace(pad_token_id=0, eos_token_id=None), + HybridEngineRolloutConfig(use_segki=True, use_graph_capture=False)) + + prompt = torch.randint(3, 1500, (2, 16), device=device) + sampling = SamplingConfig(max_new_tokens=8, temperature=0) + + rollout = make_rollout() + rollout.generate(RolloutRequest(prompt, torch.ones_like(prompt)), sampling) # build caches + + # in-place weight write, the arena/reshard contract + with torch.no_grad(): + for p in model.parameters(): + p.add_(0.01) + rollout.sync_weights(step=0) + synced = rollout.generate(RolloutRequest(prompt, torch.ones_like(prompt)), sampling) + + fresh = make_rollout().generate(RolloutRequest(prompt, torch.ones_like(prompt)), sampling) + assert torch.equal(synced.input_ids, fresh.input_ids), "post-sync generate must match a fresh injection" # -- generate dispatches correctly ------------------------------------- diff --git a/tests/unit/utils/test_static_cache.py b/tests/unit/utils/test_static_cache.py index 7a373267d3a4..80622b93f501 100644 --- a/tests/unit/utils/test_static_cache.py +++ b/tests/unit/utils/test_static_cache.py @@ -81,6 +81,8 @@ def test_static_layer_supports_per_row_decode_positions(): assert layer.keys[0, 0, 1].tolist() == [2.0, 2.0] assert layer.keys[1, 0, 3].tolist() == [4.0, 4.0] + # transformers >= 5.20 protocol: seq_length counts the slot being + # written (write_position + 1); position math uses get_query_offset() assert torch.equal(layer.get_seq_length(), torch.tensor([2, 4])) @@ -159,6 +161,7 @@ def test_static_cache_compact_identity_keeps_active_rows_and_clears_tail(): cache.compact(torch.tensor([0, 1], dtype=torch.long)) assert layer.keys[:2, 0, 0, 0].tolist() == [10.0, 20.0] + # cleared rows reset to -1 (the empty-row marker used at cache init) assert layer.get_seq_length().tolist() == [2, 3, 0] assert layer.keys[2].abs().sum().item() == 0 @@ -201,6 +204,36 @@ def test_static_layer_accepts_active_prefix_of_cache_rows(): assert layer.keys[:2, 0, 1:3].sum().item() == 4 +def test_hybrid_cache_exposes_hf_gdn_protocol(): + """HF >= 5.19 GDN forwards fetch state through get_conv_state/ + get_recurrent_state and branch on is_recording_past — the top-level + cache must delegate these to the bound hybrid slots. A regression here + crashes every graph-capture rollout that leaves use_segki off.""" + from types import SimpleNamespace + + config = type( + "Config", (), { + "num_hidden_layers": 2, + "num_attention_heads": 1, + "hidden_size": 2, + "layer_types": ["linear_attention", "full_attention"], + })() + cache = DeepSpeedStaticCache(config=config, batch_size=1, max_cache_len=4, device="cpu", dtype=torch.float32) + conv = torch.zeros(1) + rec = torch.zeros(1, 2) + slot = SimpleNamespace(conv_states={0: conv}, + recurrent_states={0: rec}, + is_recording_past=lambda state_idx=0: False) + cache.layers[0].bind(slot) + + assert cache.get_conv_state(0) is conv + assert cache.get_recurrent_state(0) is rec + assert cache.is_recording_past(0) is False + # KV layers carry no GDN notion; the behavioral query answers False + # instead of raising so generic per-layer probing stays safe. + assert cache.is_recording_past(1) is False + + def test_static_cache_memory_skips_layers_without_kv(): config = type("Config", (), {"num_hidden_layers": 2})() cache = DeepSpeedStaticCache(config, max_cache_len=4)