Inkling-2-Mini DGX Spark recipe + t5a DFlash2 drafter (package 1741ea3c) (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- recipe/stack/cands/n361-s3b-p/recipe/patch/n80_cuda.pyAdded+171
- recipe/stack/cands/n361-s3b-p/recipe/patch/n80_draft.pyAdded+147
- recipe/stack/cands/n361-s3b-p/recipe/patch/n86_riders.pyAdded+448
- recipe/stack/cands/n361-s3b-p/recipe/serve/inkling2_mtp.pyAdded+667
- recipe/stack/cands/n361-s3b-p/recipe/serve/serve.shAdded+167
- recipe/stack/cands/n361-s3b-p/recipe/serve/sl.jsonAdded
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n320s/__init__.pyAdded+66
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/__init__.pyAdded+58
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows.pyAdded+31
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows_ctl.pyAdded+31
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n351/__init__.pyAdded+68
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n355/__init__.pyAdded+69
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n381/__init__.pyAdded+98
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/CREDITS.knapcio-v2.9.3.mdAdded+94
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/LICENSE.knapcio-v2.9.3Added+21
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.knapcio-v2.9.3Added+54
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.n389Added+3
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/__init__.pyAdded+307
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/n389_fold.pyAdded+93
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/n351_quant.cuhAdded+175
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/n355_quant.cuhAdded+216
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/n381c_band.cuhAdded
- recipe/stack/cands/n362j-e35d7419/overlay_n362j/sitecustomize.pyAdded+116
- recipe/stack/cands/n419ab-6d18f8eb/df-r1b2.jsonAdded+1
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n320s/__init__.pyAdded+66
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/__init__.pyAdded+58
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows.pyAdded+31
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows_ctl.pyAdded+31
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n351/__init__.pyAdded+68
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n355/__init__.pyAdded+69
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n381/__init__.pyAdded+98
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/CREDITS.knapcio-v2.9.3.mdAdded+94
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/LICENSE.knapcio-v2.9.3Added+21
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.knapcio-v2.9.3Added+54
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.n389Added+3
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/__init__.pyAdded+307
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/n389_fold.pyAdded+93
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/CREDITS.n395.mdAdded+6
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/LICENSE.sglangAdded+201
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/NOTICE.n395Added+7
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/__init__.pyAdded+482
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n395_fold.pyAdded+354
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n438_fold.pyAdded+396
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n437/__init__.pyAdded+96
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n351_quant.cuhAdded+175
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n355_quant.cuhAdded+216
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n381c_band.cuhAdded
- recipe/stack/cands/n419c-8f01ac06/overlay_n419c/sitecustomize.pyAdded+129
- recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/__init__.pyAdded+134
- recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/_hook.pyAdded+83
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""n80_cuda.py (inkling2-spark decode seat, tree n80, 2026-11-24): K-chunked variant of n75 build 2 for drafter linears whose K istoo large for build 2's one shared x stage (DSpark drafter down_proj: K 9216 needs 147 KB at M <= 8). Same 12-bit fragment stream(n75_cuda.pack_frag of an n75_c12.pack_c12 "row" pack), same decode / escape / store code (copied verbatim from c12m_kernel),same per-element FP32 order (one in-order mma.sync chain over K per output tile) -> bit-identical to c12m and to the servedsm12x_bf16_gemv. x is restaged per chunk of CH k16 steps between CTA barriers; every warp walks the same rounds and chunks.Generated (inline script, decode seat) from work_stack/n137/b2/n75_cuda.py 0ab557d0 (the packed seat's build 2 + the stack seat's n137)."""import osimport torch
SMEM_MAX = 101376CUDA_SRC = r'''#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <cuda_bf16.h>#include <stdint.h>
__device__ __forceinline__ void mma16816(float (&c)[4], uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t b0, uint32_t b1) { asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n" : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));}
// n80 c12mk: n75 build 2's c12m_kernel with x staged in K chunks of CH k16 steps (CH % 8 == 0) instead of whole, for K too large for// one shared x stage (the drafter's down_proj, K 9216). Every warp walks the same rounds (one tile per warp per round) and chunks// between CTA barriers; per tile the accumulator runs ONE in-order mma.sync chain over K exactly as c12m_kernel (and the served// Triton _gemv_kernel), so outputs are bit-identical. Decode / escape / store code is c12m_kernel's, copied by gen. BF16 out only.template <int NW, int MT>__global__ void __launch_bounds__(NW * 32) c12mk_kernel(const uint4* __restrict__ wp, const uint8_t* __restrict__ basep, const uint16_t* __restrict__ W, const uint16_t* __restrict__ x, __nv_bfloat16* __restrict__ o, int M, int N, int K, int SX, int SW, int SY, int CH) { extern __shared__ uint4 xs[]; uint2* xs2 = reinterpret_cast<uint2*>(xs); const int steps = K >> 4, NU = steps / 8, ntiles = N >> 3; const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, stride = gridDim.x * NW; const int rounds = (ntiles + stride - 1) / stride; for (int rd = 0; rd < rounds; ++rd) { const int t = blockIdx.x * NW + warp + rd * stride; const bool valid = t < ntiles; float acc[4] = {0.f, 0.f, 0.f, 0.f}; const int n = valid ? t * 8 + (lane >> 2) : 0; const uint32_t base4 = valid ? (uint32_t)basep[n] * 0x01010101u : 0u; const uint16_t* wrow = W + (size_t)n * SW; for (int s0 = 0; s0 < steps; s0 += CH) { const int s1 = min(steps, s0 + CH); __syncthreads(); // every warp finished reading the previous chunk for (int i = threadIdx.x; i < (s1 - s0) * 32; i += NW * 32) { const int s = s0 + (i >> 5), l = i & 31, r = l >> 2, kq = s * 16 + (l & 3) * 2; uint32_t a0 = 0, a1 = 0, a2 = 0, a3 = 0; if (r < M) { a0 = *reinterpret_cast<const uint32_t*>(x + (size_t)r * SX + kq); a2 = *reinterpret_cast<const uint32_t*>(x + (size_t)r * SX + kq + 8); } if (MT == 2 && r + 8 < M) { a1 = *reinterpret_cast<const uint32_t*>(x + (size_t)(r + 8) * SX + kq); a3 = *reinterpret_cast<const uint32_t*>(x + (size_t)(r + 8) * SX + kq + 8); } if (MT == 1) xs2[i] = make_uint2(a0, a2); else xs[i] = make_uint4(a0, a1, a2, a3); } __syncthreads(); if (valid) { const int u0 = s0 >> 3, u1 = s1 >> 3; const uint4* p = wp + ((size_t)t * NU + u0) * 96 + lane; uint4 c0 = __ldg(p), c1 = __ldg(p + 32), c2 = __ldg(p + 64); for (int u = u0; u < u1; ++u) { uint4 d0, d1, d2; const bool more = u + 1 < u1; if (more) { const uint4* q = wp + ((size_t)t * NU + u + 1) * 96 + lane; d0 = __ldg(q); d1 = __ldg(q + 32); d2 = __ldg(q + 64); } const uint32_t L[8] = {c0.x, c0.y, c0.z, c0.w, c1.x, c1.y, c1.z, c1.w}; const uint32_t Cw[4] = {c2.x, c2.y, c2.z, c2.w}; #pragma unroll for (int j = 0; j < 8; ++j) { const uint32_t c4 = (j & 1) ? ((Cw[j >> 1] >> 4) & 0x0F0F0F0Fu) : (Cw[j >> 1] & 0x0F0F0F0Fu); const uint32_t hi = ((c4 & 0x07070707u) + base4) | ((c4 << 4) & 0x80808080u); uint32_t b0 = __byte_perm(L[j], hi, 0x5140), b1 = __byte_perm(L[j], hi, 0x7362); const uint32_t e7 = c4 & 0x07070707u, f = e7 & (e7 >> 1) & (e7 >> 2) & 0x01010101u; const int s = u * 8 + j, sl = s - s0; if (f) { // escape: the element comes from the resident BF16 original const int kb = s * 16 + (lane & 3) * 2; #pragma unroll for (int i = 0; i < 4; ++i) { if ((f >> (8 * i)) & 1u) { const uint32_t v = wrow[kb + (i >= 2 ? 8 : 0) + (i & 1)]; if (i == 0) b0 = (b0 & 0xFFFF0000u) | v; else if (i == 1) b0 = (b0 & 0x0000FFFFu) | (v << 16); else if (i == 2) b1 = (b1 & 0xFFFF0000u) | v; else b1 = (b1 & 0x0000FFFFu) | (v << 16); } } } if (MT == 1) { const uint2 a = xs2[sl * 32 + lane]; mma16816(acc, a.x, 0u, a.y, 0u, b0, b1); } else { const uint4 a = xs[sl * 32 + lane]; mma16816(acc, a.x, a.y, a.z, a.w, b0, b1); } } if (more) { c0 = d0; c1 = d1; c2 = d2; } } } } if (valid) { // c12m_kernel's BF16 store: D[r][c] with r = lane / 4 (+ 8), c = 8 t + 2 (lane % 4) + {0, 1} const int r = lane >> 2, col = t * 8 + (lane & 3) * 2; if (r < M) *reinterpret_cast<__nv_bfloat162*>(o + (size_t)r * SY + col) = __floats2bfloat162_rn(acc[0], acc[1]); if (MT == 2 && r + 8 < M) *reinterpret_cast<__nv_bfloat162*>(o + (size_t)(r + 8) * SY + col) = __floats2bfloat162_rn(acc[2], acc[3]); } }}
template <int NW, int MT>static void launchk(const at::Tensor& wp, const at::Tensor& base, const at::Tensor& W, const at::Tensor& x, at::Tensor& out, int64_t M, int64_t N, int64_t K, int64_t SX, int64_t SY, int64_t CH, int64_t grid) { const int smem = (int)CH * 32 * (MT == 1 ? 8 : 16); auto kern = c12mk_kernel<NW, MT>; static int set = 0; if (set < smem) { C10_CUDA_CHECK(cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem)); set = smem; } if (grid <= 0) { int occ = 0, dev = 0, sms = 0; C10_CUDA_CHECK(cudaGetDevice(&dev)); C10_CUDA_CHECK(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev)); C10_CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, kern, NW * 32, smem)); const int64_t need = (N / 8 + NW - 1) / NW; grid = std::min<int64_t>(need, (int64_t)std::max(occ, 1) * sms); } kern<<<(int)grid, NW * 32, smem, at::cuda::getCurrentCUDAStream()>>>( reinterpret_cast<const uint4*>(wp.data_ptr()), base.data_ptr<uint8_t>(), reinterpret_cast<const uint16_t*>(W.data_ptr()), reinterpret_cast<const uint16_t*>(x.data_ptr()), reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), (int)M, (int)N, (int)K, (int)SX, (int)W.stride(0), (int)SY, (int)CH); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void c12mk(at::Tensor wp, at::Tensor base, at::Tensor W, at::Tensor x, at::Tensor out, int64_t M, int64_t SX, int64_t SY, int64_t nw, int64_t ch, int64_t grid) { const int64_t N = W.size(0), K = W.size(1); TORCH_CHECK(out.scalar_type() == at::kBFloat16, "c12mk: BF16 out only"); TORCH_CHECK(ch > 0 && ch % 8 == 0 && K % 128 == 0 && N % 8 == 0 && M >= 1 && M <= 16, "c12mk: bad shape / chunk"); const int mt = M <= 8 ? 1 : 2;#define C12MK_CASE(NWV, MTV) if (nw == NWV && mt == MTV) return launchk<NWV, MTV>(wp, base, W, x, out, M, N, K, SX, SY, ch, grid); C12MK_CASE(4, 1) C12MK_CASE(4, 2) C12MK_CASE(8, 1) C12MK_CASE(8, 2) C12MK_CASE(16, 1) C12MK_CASE(16, 2) TORCH_CHECK(false, "c12mk: unsupported nw ", nw);}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("c12mk", &c12mk); }'''_EXT = None
def build(verbose=False, build_dir=None): global _EXT if _EXT is None: from torch.utils.cpp_extension import load_inline arch = os.environ.get("N75_CUDA_ARCH", "121a") kw = {"build_directory": build_dir} if build_dir else {} if build_dir: os.makedirs(build_dir, exist_ok=True) _EXT = load_inline("n80_c12mk", cpp_sources="", cuda_sources=CUDA_SRC, verbose=verbose, with_cuda=True, extra_cuda_cflags=["-O3", f"-gencode=arch=compute_{arch},code=sm_{arch}", "-Xptxas=-v"], **kw) return _EXT
def max_ch(m): """Largest chunk (k16 steps, multiple of 8) whose x stage fits one block.""" per = 32 * (8 if m <= 8 else 16) return (SMEM_MAX // per) // 8 * 8
def c12mk_gemv(x, w, pk, frag, out=None, nw=8, ch=0, grid=0): """x[..., K] @ w[N, K]^T (BF16 out) from the fragment stream, x staged in chunks of ch k16 steps (0 = the largest that fits).""" n, k = pk["shape"] lead = x.shape[:-1] x2 = x.reshape(-1, k) m = x2.shape[0] if not (1 <= m <= 16 and x2.dtype == torch.bfloat16 and x2.stride(1) == 1 and x2.stride(0) % 2 == 0 and x2.data_ptr() % 4 == 0): raise ValueError(f"c12mk_gemv: unsupported operands (m {m}, k {k}, x stride {x2.stride()})") ch = ch or max_ch(m) ch = min(ch, (k // 16 + 7) // 8 * 8) if out is None: out = torch.empty((m, n), device=x.device, dtype=torch.bfloat16) elif not (out.dtype == torch.bfloat16 and out.stride(-1) == 1 and (out.dim() < 2 or out.stride(0) % 2 == 0) and out.data_ptr() % 4 == 0): raise ValueError("c12mk_gemv: unsupported out") build().c12mk(frag, pk["base"], w, x2, out, m, x2.stride(0), out.stride(0) if out.dim() > 1 else n, nw, ch, grid) return out.view(*lead, n)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""n80 rider (inkling2-spark decode seat, 2026-11-24; DRAFT, not run on the image): exact 12-bit packed DSpark drafter linears onn75's packed registry (S6: n75_install.py df7cb3e4, n75_cuda.py 0ab557d0, n75_c12.py bb969a78) and the served <= 16-rowsm12x_bf16_gemv route. Bitwise to the served drafter GEMV, so draft tokens, acceptance and outputs are unchanged.
Knobs (env): N80_DRAFT ('' or unset = off, nothing patched; A = n75 build 2 on the drafter linears whose K fits its one shared xstage; B = A + n80_cuda.c12mk on the others, i.e. down_proj K 9216), N80_NW (c12m warps for drafter classes, default 16),N80_MK_NW (c12mk warps, default 8), N80_SKIP (comma list of linears left served, default kv_proj_ctx: mb1 read it +2 pctslower packed, N 2,048 being launch-bound). Needs n75 on (N75_C12 non-empty); otherwise logs and stays off.What it patches: * n75_install._prepare (n75's own one-time hook at the first target DECODE / TARGET-VERIFY forward outside capture, after the KV pool, before the draft model's graphs are captured): after the original, every DFlashDraftModel instance's BF16 linears on the route (2-D, no bias, N >= 2048, K % 256 == 0) are packed: - K that fits build 2 at 16 rows -> n75's registry as class 'draft <leaf>' with KERN 'cuda' (n75's build 2). An entry that would fall back to build 1 (Triton: NOT bitwise, n75 mb1) is removed again, so that weight stays on the served path. - (B) other K -> this module's registry, served by c12mk through one more wrapper around unquant._sm12x_bf16_gemv (the function n75 installed). Everything else falls through to it. The BF16 originals stay (escapes and > 16-row calls read them): about +297 MB (A) / +393 MB (B) device memory after the KV pool.Log prefix '[n80 pid=...]'."""import gc, logging, os
import torch
logger = logging.getLogger(__name__)FORM = os.environ.get("N80_DRAFT", "").strip().upper()NW = int(os.environ.get("N80_NW", "16"))MK_NW = int(os.environ.get("N80_MK_NW", "8"))LEAVES = ("qkv_proj", "kv_proj_ctx", "o_proj", "gate_up_proj", "down_proj")SKIP = {v.strip() for v in os.environ.get("N80_SKIP", "kv_proj_ctx").split(",") if v.strip()}_S = {"installed": False, "done": False, "mk": {}, "mk_calls": 0, "mk_miss": 0, "n75": 0, "bytes": 0}
def _log(msg, *a): logger.warning(f"[n80 pid={os.getpid()}] " + msg, *a)
def _mods(): from sglang.srt.models.inkling_common import n75_c12 as C, n75_cuda as G, n75_install as N try: from sglang.srt.models.inkling_common import n80_cuda as K except ImportError: import n80_cuda as K return C, G, N, K
def _find_drafters(cls): """Every instance of cls alive in this process, also when SGLang's graph-capture setup has run gc.freeze() (base_cuda_graph_runner): frozen objects leave the normal generations, so gc.get_objects() alone returns none of them (stack seat, 2026-11-24: the first composed boot of form B packed 0 drafters for this reason). unfreeze moves them back to the oldest generation, freeze restores the state afterwards; no collection runs (gc stays as it was). type(o).__mro__ is used instead of isinstance: no __class__ lookups on weakref proxies or other objects with hooked __class__.""" frozen = gc.get_freeze_count() > 0 if frozen: gc.unfreeze() try: return [o for o in gc.get_objects() if cls in type(o).__mro__] finally: if frozen: gc.freeze()
def _register_drafter(): C, G, N, K = _mods() if N.S.get("orig") is None: _log("n75's wrapper is not installed (n75 prepared off): n80 off") return from sglang.srt.layers.linear import LinearBase from sglang.srt.models.dflash import DFlashDraftModel drafts = _find_drafters(DFlashDraftModel) if not drafts: _log("no DFlashDraftModel instance found (freeze count %d): n80 packs nothing, served path", gc.get_freeze_count()) N.KERN["draft"] = "cuda" for d in drafts: for name, m in d.named_modules(): leaf = name.split(".")[-1] w, b = getattr(m, "weight", None), getattr(m, "bias", None) if (not isinstance(m, LinearBase) or leaf not in LEAVES or leaf in SKIP or b is not None or not isinstance(w, torch.Tensor) or w.dtype != torch.bfloat16 or w.dim() != 2 or w.shape[0] < 2048 or w.shape[1] % 256 or w.stride(1) != 1): continue if G.fits(w.shape[1], 16): nb = N._register("draft " + leaf, w.data) e = N.S["reg"].get(w.data_ptr()) if e is None or e.get("frag") is None: # build 1 is not bitwise: keep the served path for this weight N.S["reg"].pop(w.data_ptr(), None) _log("%s %s: no build 2 entry, served path", name, tuple(w.shape)) continue N.CUDA_NW["draft " + leaf] = NW _S["n75"] += 1; _S["bytes"] += nb elif FORM == "B": pk = C.pack_c12(w.data, "row") if pk is None: _log("%s %s FAILED the bitwise round trip: served path", name, tuple(w.shape)) continue frag = G.pack_frag(pk) pk["lo"] = pk["cd"] = None # c12mk reads the fragment stream, the base and (escapes) the original _S["mk"][w.data_ptr()] = (pk, frag, tuple(w.shape), tuple(w.stride())) _S["bytes"] += frag.numel() + pk["base"].numel() if _S["mk"]: K.build() from sglang.srt.layers.quantization import unquant as U prev = U._sm12x_bf16_gemv
def wrapped(x, weight, bias=None, out_dtype=None, out=None): e = _S["mk"].get(weight.data_ptr()) if (e is not None and bias is None and out_dtype in (None, torch.bfloat16) and x.dtype == torch.bfloat16 and e[2] == tuple(weight.shape) and e[3] == tuple(weight.stride()) and x.numel() // max(1, x.shape[-1]) <= 16): try: y = K.c12mk_gemv(x, weight, e[0], e[1], out=out, nw=MK_NW) _S["mk_calls"] += 1 return y except ValueError: _S["mk_miss"] += 1 return prev(x, weight, bias, out_dtype, out)
U._sm12x_bf16_gemv = wrapped torch.cuda.synchronize() _log("drafter linears packed: %d DFlashDraftModel, %d on n75 build 2 (nw %d), %d on c12mk (nw %d), %.1f MB, form %s", len(drafts), _S["n75"], NW, len(_S["mk"]), MK_NW, _S["bytes"] / 1e6, FORM)
def install(): if _S["installed"]: return _S["installed"] = True if FORM not in ("A", "B"): _log("N80_DRAFT %r: off, nothing patched", FORM) return from sglang.srt.models.inkling_common import n75_install as N if not N.SEL: _log("n75 is off (N75_C12 empty): n80 off") return orig_prepare = N._prepare
def _prepare(): orig_prepare() if not _S["done"]: _S["done"] = True try: _register_drafter() except Exception as e: # never kill the server: remove drafter entries, served path for k_, e_ in list(N.S["reg"].items()): if str(e_.get("cls", "")).startswith("draft "): N.S["reg"].pop(k_, None) _S["mk"].clear() _log("drafter packing failed (%r): n80 off, served path", e)
N._prepare = _prepare _log("installed: form %s (packing at n75's first-decode prepare)", FORM)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448"""n86 S1 riders (inkling2-spark stack seat, 2026-11-23): n54 + G1 + G2 (n71 riders, KEEP in mb2a-d) + the n75 build-2 rider gate.
Mounted beside the image modules at srt/models/inkling_common/n86_riders.py; install() is called from the bottom of the mountedinkling2_attn.py (after n75's install). Every knob off = the n54 code path (nothing patched).
G1 (N86_G1=1): the MLP short conv of an EXTEND batch of >= 2048 rows (the served tiled-kernel range, PREFILL_MIN_ROWS) writes the layer's residual update directly (n71_sconvres.sconv_residual 09d3d221 = the image _sconv_prefill_kernel text + residual_add's FP32 order / the block-boundary BF16 add); the sconv cache prepare and update stay the served calls, in the served order around the conv. Gates (else the served path, counted): static weights, BF16 contiguous x / attention / partial of one shape, the served cache shape.G2 (N86_G2=1): attn_res(normalize_values=True) + the RMSNorm it feeds in one kernel (n71_resnorm.resnorm d1054a4c) on the NON-LOOP visits (messages is None) of EXTEND batches of >= N86_MIN_ROWS rows: attention side (local: attn_norm; global: the q / k / v input norms into one [3, T, W] BF16 buffer) and MLP side (mlp_norm). Only the (side, sources, addend, queries) shapes in N86_G2_SHAPES run fused (default: mb2d's 16 walk shapes minus ('mlp', 5, 1, 1), which mb2d measured slower, 1.694 -> 2.574 ms); other shapes, BF16 / contiguity / pre_weight / output-dtype misses and blocks-empty visits take the served calls.n75 gate (N75_C12 set): wraps n75_install._wrapped (n75_install.py 088711f7 unchanged) before its _prepare installs it, so the packed GEMV runs only where RULE n86 S1 (i)-(ii) show coverage: build 2 (registered entry has a CUDA fragment stream), M in N86_N75_MS (default 8,16: bitwise in mb1 BITC and timed in TIMEC), weight shape in {qkvr 8600x2304, wo_ud 2304x3072, LM head 201024x2304} and class in N86_N75_CLASSES; every other call takes S['orig'] (the served kernel), counted.
FAIL CLOSED: install() checks the md5 of the nine image files the patch derives from (inkling2.py, inkling2_attn_res.py,inkling2_sconv.py, sconv.py, inkling2_norm.py and the AttnRes / sconv / RMSNorm / residual_add kernel files) and that each of thethree text edits of the served Inkling2DecoderLayer._forward matches exactly once; on any miss G1 and G2 stay off (logged).The patched _forward is the image's source with three guarded insertions, exec'd in inkling2's module globals.Reach: Python counters per path (graph capture + eager calls) printed as 'N86REACH ...' lines; graph replays are not countedhere (the check boot's profiler census counts kernels)."""import hashlib, logging, os, sys, textwrap, threading, time
import torch
logger = logging.getLogger(__name__)
G1 = os.environ.get("N86_G1", "0") == "1"G2 = os.environ.get("N86_G2", "0") == "1"MIN_ROWS = int(os.environ.get("N86_MIN_ROWS", "2048") or 2048)G1_MIN_ROWS = 2048 # the image short_convolution's PREFILL_MIN_ROWS (asserted at install against the module)_DEFAULT_G2 = ("attn:2:0:1,attn:2:0:3,attn:3:0:1,attn:3:0:3,attn:4:0:1,attn:4:0:3,attn:5:0:1,attn:5:0:3," "mlp:2:0:1,mlp:2:1:1,mlp:3:0:1,mlp:3:1:1,mlp:4:0:1,mlp:4:1:1,mlp:5:0:1")
def _shapes(raw): out = set() for part in filter(None, (p.strip() for p in raw.split(","))): side, n, ad, q = part.split(":") out.add((side, int(n), int(ad), int(q))) return out
G2_SHAPES = _shapes(os.environ.get("N86_G2_SHAPES") or _DEFAULT_G2) # empty / unset = the default listN75_MS = {int(v) for v in (os.environ.get("N86_N75_MS") or "8,16").split(",") if v.strip()}N75_CLASSES = {v.strip() for v in (os.environ.get("N86_N75_CLASSES") or "qkvr,wo_ud,lm_head").split(",") if v.strip()}N75_SHAPES = {"qkvr": (8600, 2304), "wo_ud": (2304, 3072), "lm_head": (201024, 2304)}
# md5 of the image files the patch derives from (image lmsysorg/sglang@sha256:efac853b..., checked 11-23 on the Spark)IMAGE_MD5 = { "sglang.srt.models.inkling2": "5db5443befb09e9a846d2fad560bb7cb", "sglang.srt.models.inkling_common.inkling2_attn_res": "803b43bfe76e190f0bf92c61269c2ae2", "sglang.srt.models.inkling_common.inkling2_sconv": "8ca39087d78cfacc0d580144a39c726e", "sglang.srt.models.inkling_common.sconv": "f2d226bdb97182a70b76f24bee3a9ff5", "sglang.srt.models.inkling_common.inkling2_norm": "a1aa0ab904b384f7ab6e61e1af7a3a0f", "sglang.kernels.ops.attention.inkling2_attn_res": "4da6f04bca81772dcc6109bc67fc1730", "sglang.kernels.ops.mamba.inkling2_sconv": "f65e89067b7fa7d76b9b7c3e4bacea26", "sglang.kernels.ops.layernorm.inkling2_rms_norm": "e1be9289e74eb22350b0206f4244f941", "sglang.kernels.ops.elementwise.inkling2_residual_add": "c42560e64d3629b070582e0d7c09525e",}FORWARD_MD5 = "466a152cc7f66083a999dbf15f926fb8" # dedented source of the image Inkling2DecoderLayer._forward
# ---- the three guarded insertions into the served _forward (each anchor must match exactly once) ----EDITS = ( (" attn_input = self._attention_input(\n" " state.attention_input(self.layer_id), messages\n" " )\n", " attn_input = _n86_g2_attention(self, state, forward_batch, messages)\n" " if attn_input is None:\n" " attn_input = self._attention_input(\n" " state.attention_input(self.layer_id), messages\n" " )\n"), (" mlp_input = state.mlp_input(self.layer_id, attention)\n" " if messages is not None:\n" " mlp_input = messages.mix(\n" " self.layer_id - self.config.loop_core_layers.start,\n" " (mlp_input,),\n" " self.controller_weights,\n" " \"mlp\",\n" " )[0]\n" " mlp_input = self.mlp_norm(mlp_input)\n", " mlp_input = _n86_g2_mlp(self, state, attention, forward_batch, messages)\n" " if mlp_input is None:\n" " mlp_input = state.mlp_input(self.layer_id, attention)\n" " if messages is not None:\n" " mlp_input = messages.mix(\n" " self.layer_id - self.config.loop_core_layers.start,\n" " (mlp_input,),\n" " self.controller_weights,\n" " \"mlp\",\n" " )[0]\n" " mlp_input = self.mlp_norm(mlp_input)\n"), (" mlp = self.mlp_sconv(mlp, positions, forward_batch)\n" " state.finalize_layer(self.layer_id, attention, mlp)\n", " if _n86_g1(self, state, attention, mlp, forward_batch):\n" " return\n" " mlp = self.mlp_sconv(mlp, positions, forward_batch)\n" " state.finalize_layer(self.layer_id, attention, mlp)\n"),)
R = {"g1": {}, "g2": {}, "served": {}, "n75": {}, "modes": {}}K = {"sconv_residual": None, "resnorm": None, "pdl": None, "AttentionSources": None}_NW_CACHE = {}_STATE = {"installed": False, "patched": False, "why": "not installed"}
def _bump(d, k): d[k] = d.get(k, 0) + 1
def _served(reason): _bump(R["served"], reason) return None
def _md5_file(path): with open(path, "rb") as f: return hashlib.md5(f.read()).hexdigest()
def served_forward_source(path): """The dedented source of Inkling2DecoderLayer._forward from the image file (ast segment).""" import ast src = open(path).read() for node in ast.walk(ast.parse(src)): if isinstance(node, ast.ClassDef) and node.name == "Inkling2DecoderLayer": for f in node.body: if isinstance(f, ast.FunctionDef) and f.name == "_forward": return textwrap.dedent(ast.get_source_segment(src, f, padded=True)) return None
def patched_forward_source(served): out = served if served.endswith("\n") else served + "\n" # the ast segment ends without one for old, new in EDITS: if out.count(old) != 1: raise ValueError(f"n86: edit anchor found {out.count(old)} times: {old.splitlines()[0].strip()!r}") out = out.replace(old, new) return out
def _mode_ok(forward_batch): """EXTEND batches only (the served ShortConvolution.forward's extend = not decode and not verify); draft modes excluded.""" m = forward_batch.forward_mode _bump(R["modes"], getattr(m, "name", str(m))) if m.is_decode() or m.is_target_verify() or not m.is_extend(): return False for attr in ("is_draft_extend", "is_draft_extend_v2"): f = getattr(m, attr, None) if f is not None and f(): return False return True
DEVICE_OK = lambda x: x.is_cuda # noqa: E731 (the CPU pre-flight replaces it; served kernels need CUDA tensors)
def _bf16_rows(xs, shape): return all(x.dtype == torch.bfloat16 and x.is_contiguous() and tuple(x.shape) == shape and DEVICE_OK(x) for x in xs)
def _queries(attn_res, kind, layer_idx, queries): """block_attn_res's effective queries, exactly: unsqueeze a 1-D query, the cached scaled query (view) or q.float() * W**-0.5.""" if queries.ndim == 1: queries = queries.unsqueeze(0) scaled = attn_res.scaled_query(kind, layer_idx) eff = scaled.view(queries.shape) if scaled is not None else queries.float() * (queries.shape[-1] ** -0.5) return eff.contiguous()
def _norms_ok(norms): n0 = norms[0] return all(n.pre_weight is None and n.weight is not None and n.output_dtype == torch.bfloat16 and n.eps == n0.eps and n.weight.dtype == n0.weight.dtype and n.weight.is_contiguous() and n.weight.dim() == 1 for n in norms)
def _stacked_norm_weight(norms): """[3, W] q / k / v norm weights. Cached only when built outside graph capture (a persistent allocation); inside a capture the stack is recorded into the graph (a 27 KB copy per replay).""" key = tuple((n.weight.data_ptr(), n.weight._version) for n in norms) w = _NW_CACHE.get(key) if w is not None: return w w = torch.stack([n.weight for n in norms]).contiguous() if not torch.cuda.is_current_stream_capturing(): _NW_CACHE[key] = w else: _bump(R["g2"], "nw stacked in capture") return w
def _n86_g2_attention(layer, state, forward_batch, messages): if not G2: return None if messages is not None: return _served("g2 attn: loop pass (messages)") if not state.blocks: return _served("g2 attn: blocks empty (no attn_res)") partial = state.partial if not _mode_ok(forward_batch): return _served("g2 attn: not extend") T, W = partial.shape if T < MIN_ROWS: return _served("g2 attn: rows < min") ar = state.attn_res if not ar.normalize_values: return _served("g2 attn: normalize_values False") sources = [*state.blocks, partial] local = layer.is_local Q = 1 if local else 3 key = ("attn", len(sources), 0, Q) if key not in G2_SHAPES: return _served(f"g2 shape {key} served") if not _bf16_rows(sources, (T, W)): return _served("g2 attn: dtype / layout") norms = (layer.attn_norm,) if local else (layer.q_input_norm, layer.k_input_norm, layer.v_input_norm) if not _norms_ok(norms): return _served("g2 attn: norm config") q = _queries(ar, "attn", layer.layer_id, ar.attn_query(layer.layer_id)) if tuple(q.shape) != (Q, W) or q.dtype != torch.float32: return _served("g2 attn: query shape") nw = norms[0].weight if local else _stacked_norm_weight(norms) y = partial.new_empty((Q, T, W), dtype=torch.bfloat16) K["resnorm"](sources, None, q, nw, y, 1e-6, norms[0].eps) _bump(R["g2"], key) if local: return y[0] return K["AttentionSources"](y[0], y[1], y[2])
def _n86_g2_mlp(layer, state, attention, forward_batch, messages): if not G2: return None if messages is not None: return _served("g2 mlp: loop pass (messages)") if not _mode_ok(forward_batch): return _served("g2 mlp: not extend") T, W = state.partial.shape if T < MIN_ROWS: return _served("g2 mlp: rows < min") ar = state.attn_res if not ar.normalize_values: return _served("g2 mlp: normalize_values False") if ar.is_block_boundary(layer.layer_id): # mlp_input: blocks + [partial], partial block = attention sources, addend = [*state.blocks, state.partial, attention], None else: # mlp_input: blocks, (partial, attention) = last source + addend sources, addend = [*state.blocks, state.partial], attention key = ("mlp", len(sources), int(addend is not None), 1) if key not in G2_SHAPES: return _served(f"g2 shape {key} served") if not _bf16_rows(sources + ([addend] if addend is not None else []), (T, W)): return _served("g2 mlp: dtype / layout") norm = layer.mlp_norm if not _norms_ok((norm,)): return _served("g2 mlp: norm config") q = _queries(ar, "mlp", layer.layer_id, ar.mlp_queries[layer.layer_id]) if tuple(q.shape) != (1, W) or q.dtype != torch.float32: return _served("g2 mlp: query shape") y = state.partial.new_empty((1, T, W), dtype=torch.bfloat16) K["resnorm"](sources, addend, q, norm.weight, y, 1e-6, norm.eps) _bump(R["g2"], key) return y[0]
def _n86_g1(layer, state, attention, mlp, forward_batch): if not G1: return False if not isinstance(mlp, torch.Tensor): _served("g1: routed output") return False if not _mode_ok(forward_batch): _served("g1: not extend") return False sc = layer.mlp_sconv if getattr(sc, "is_dynamic", True): _served("g1: dynamic sconv") return False T = mlp.shape[0] if T < G1_MIN_ROWS or mlp.dim() != 2: _served("g1: rows < 2048") return False boundary = state.attn_res.is_block_boundary(layer.layer_id) xs = [mlp, attention] + ([] if boundary else [state.partial]) if not _bf16_rows(xs, tuple(mlp.shape)): _served("g1: dtype / layout") return False weight = sc._weight_2d() cache = sc._sconv_cache() width = weight.shape[1] if cache.ndim != 3 or tuple(cache.shape[1:]) != (width - 1, mlp.shape[1]) or weight.dim() != 2: _served("g1: cache shape") return False meta = sc._conv_state(forward_batch) sc._prepare_extend_sconv_cache(forward_batch, cache, mlp, meta.track_conv_indices) # served order: prepare, conv, update holder = []
def update(partial): out = K["sconv_residual"](mlp, weight, cache, meta.precomputed, attention, partial, use_pdl=K["pdl"]) holder.append(out) return out
from sglang.srt.models.inkling_common.kernels.sconv import update_sconv_cache # finalize_layer_with: boundary -> blocks.append(partial), partial = update(None); else partial = update(partial) state.finalize_layer_with(layer.layer_id, update) update_sconv_cache( x=mlp, sconv_cache=cache, cache_indices=meta.cache_indices, has_initial_state=meta.has_initial_state, query_start_loc=meta.query_start_loc, ) _bump(R["g1"], "boundary" if boundary else "residual") return True
def build_forward(served_src, module_globals): """Exec the patched _forward in the inkling2 module globals (helpers injected under _n86_* names).""" module_globals["_n86_g2_attention"] = _n86_g2_attention module_globals["_n86_g2_mlp"] = _n86_g2_mlp module_globals["_n86_g1"] = _n86_g1 ns = {} exec(compile(patched_forward_source(served_src), "<n86 Inkling2DecoderLayer._forward>", "exec"), module_globals, ns) return ns["_forward"]
def _check_files(): bad = [] for mod, want in IMAGE_MD5.items(): m = sys.modules.get(mod) if m is None: __import__(mod) m = sys.modules[mod] got = _md5_file(m.__file__) if got != want: bad.append(f"{mod} {got[:8]} != {want[:8]}") return bad
def _patch_layer(): """Runs at the first Inkling2Attention construction (inkling2.py has finished importing by then).""" if _STATE["patched"] or not (G1 or G2): return _STATE["patched"] = True try: bad = _check_files() if bad: _STATE["why"] = f"image files differ: {bad}" logger.warning("n86: G1 / G2 OFF (served path): %s", _STATE["why"]) return I = sys.modules["sglang.srt.models.inkling2"] src = served_forward_source(I.__file__) if src is None or hashlib.md5(src.encode()).hexdigest() != FORWARD_MD5: _STATE["why"] = "served _forward source differs" logger.warning("n86: G1 / G2 OFF (served path): %s", _STATE["why"]) return from sglang.kernels.ops.mamba import inkling2_sconv as KS if KS.PREFILL_MIN_ROWS != G1_MIN_ROWS: _STATE["why"] = f"PREFILL_MIN_ROWS {KS.PREFILL_MIN_ROWS}" logger.warning("n86: G1 / G2 OFF: %s", _STATE["why"]) return from sglang.kernels.jit.utils import is_arch_support_pdl from sglang.srt.models.inkling_common.n71_resnorm import resnorm from sglang.srt.models.inkling_common.n71_sconvres import sconv_residual K.update(sconv_residual=sconv_residual, resnorm=resnorm, pdl=bool(is_arch_support_pdl()), AttentionSources=I.AttentionSources) I.Inkling2DecoderLayer._forward = build_forward(src, I.__dict__) _STATE["why"] = "patched" logger.warning("n86: Inkling2DecoderLayer._forward patched (G1 %s, G2 %s, min rows %d, G2 shapes %d, pdl %s)", G1, G2, MIN_ROWS, len(G2_SHAPES), K["pdl"]) except Exception as ex: # fail closed _STATE["why"] = f"{type(ex).__name__}: {str(ex)[:300]}" logger.warning("n86: G1 / G2 OFF (served path) after an install error: %s", _STATE["why"])
def _n75_gate(): """Restrict n75's wrapper (installed into unquant by n75's own _prepare) to the covered (class, shape, M) on build 2.""" from sglang.srt.models.inkling_common import n75_install as X if not X.SEL: return orig = X._wrapped
def gated(x, weight, bias=None, out_dtype=None, out=None): e = X.S["reg"].get(weight.data_ptr()) if e is not None: m = x.numel() // max(1, x.shape[-1]) cls = e["cls"] why = None if e.get("frag") is None: why = "not build 2" elif cls.startswith("draft "): # S7 (n151): n80's drafter linears ('draft <leaf>', build 2 at <= 16 rows): no class / shape / M gate; if m <= 16: # > 16 rows falls to n75's own wrapper, which returns the served kernel. Packed calls counted below. _bump(R["n75"], f"{cls} M{m} packed") return orig(x, weight, bias, out_dtype, out) elif cls not in N75_CLASSES: why = "class off" elif tuple(weight.shape) != N75_SHAPES.get(cls): why = "shape off" elif m not in N75_MS: why = f"M {m} off" if m <= 16 else None # > 16 rows: n75's own wrapper returns the served kernel if why is not None: _bump(R["n75"], f"{cls} {why}") return X.S["orig"](x, weight, bias, out_dtype, out) if m in N75_MS: _bump(R["n75"], f"{cls} M{m} packed") return orig(x, weight, bias, out_dtype, out)
X._wrapped = gated logger.warning("n86: n75 gate installed: classes %s, M %s, build 2 only", sorted(N75_CLASSES), sorted(N75_MS))
def _reporter(): def run(): last = None while True: time.sleep(15) c = repr((R["g1"], R["g2"], R["n75"], R["served"])) if c != last: print(f"N86REACH g1 {R['g1']} g2 {R['g2']} n75 {R['n75']} served {R['served']} modes {R['modes']} " f"state {_STATE['why']!r} t={time.strftime('%H:%M:%S', time.gmtime())}", file=sys.stderr, flush=True) last = c
threading.Thread(target=run, daemon=True, name="n86reach").start()
def install(): if _STATE["installed"]: return _STATE["installed"] = True if G1 or G2: from sglang.srt.models.inkling_common import inkling2_attn as A cls = A.Inkling2Attention orig_init = cls.__init__
def init(self, *a, **kw): _patch_layer() orig_init(self, *a, **kw)
cls.__init__ = init if os.environ.get("N75_C12", "").strip(): _n75_gate() if G1 or G2 or os.environ.get("N75_C12", "").strip(): _reporter() logger.warning("n86 installed: G1 %s G2 %s N75_C12 %r", G1, G2, os.environ.get("N75_C12", ""))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667import jsonimport loggingimport osfrom collections.abc import Iterable
import torchfrom torch import nn
from sglang.kernels.ops.speculative.inkling2_mtp import ( mix_rmsnorm, rnn_gates, rnn_inputs,)from sglang.srt.distributed.device_communicators.vocab_gather import ( make_vocab_gather,)from sglang.srt.layers.layernorm import RMSNormfrom sglang.srt.layers.linear import QKVParallelLinearfrom sglang.srt.layers.logits_processor import should_apply_lm_head_quant_methodfrom sglang.srt.mem_cache.memory_pool import KVWriteLoc, layer_window_locsfrom sglang.srt.mem_cache.swa_memory_pool import SWAKVPoolfrom sglang.srt.model_loader.weight_utils import default_weight_loaderfrom sglang.srt.models.dflash import DFlashDraftModelfrom sglang.srt.models.dspark import ( BaseDSparkMarkovHead, DSparkDraftModel, VocabShard, gather_and_crop_vocab, project_through_lm_head,)from sglang.srt.runtime_context import get_parallel, get_platform
logger = logging.getLogger(__name__)# n3 ds-sl (inkling2-spark dspark seat, 2026-11-20): shortlist-vocab draft head. When set, the draft's base logits and its# markov step bias are computed only over the token ids listed in this JSON file and written into full-width rows whose# other columns hold _SL_FILL (base) / 0 (bias), so every consumer downstream sees the usual [.., vocab] shapes and real# token ids. Draft-only: the target verify, and so the greedy output, is untouched; off-list tokens can only be rejected._SL_PATH = os.environ.get("SGLANG_INKLING2_DRAFT_SHORTLIST") or None_SL_FILL = -1.0e4
class Inkling2MTPHead(BaseDSparkMarkovHead): def __init__(self, vocab_size, markov_rank, hidden_size, rms_norm_eps): super().__init__() self.vocab_size = vocab_size self.hidden_size = hidden_size self.markov_rank = markov_rank self.markov_w1 = nn.Embedding(vocab_size, markov_rank) self.rnn_proj = nn.Linear(2 * markov_rank + 2 * hidden_size, 3 * markov_rank) self.hidden_out = nn.Linear(markov_rank, hidden_size) self.dflare_norm = RMSNorm(hidden_size, eps=rms_norm_eps) self._fold_weight = None self._fold_bias = None self._gather_logits = None self._get_staged_f = None self._sl_ids = None
@torch.no_grad() def attach_fold(self, weight, multiplier): assert weight.ndim == 2 and weight.shape[1] == self.hidden_size self._fold_weight = weight.new_empty((weight.shape[0], self.markov_rank)) self._fold_bias = weight.new_empty((weight.shape[0],)) self.refresh_fold(weight, multiplier)
@torch.no_grad() def refresh_fold(self, weight, multiplier): assert self._fold_weight is not None and self._fold_bias is not None assert weight.shape == (self._fold_weight.shape[0], self.hidden_size) projection = self.hidden_out.weight.double() bias = self.hidden_out.bias.double() for start in range(0, weight.shape[0], 4096): rows = slice(start, min(start + 4096, weight.shape[0])) head = weight[rows].double() folded_weight, folded_bias = head @ projection, head @ bias if multiplier: folded_weight /= multiplier folded_bias /= multiplier self._fold_weight[rows].copy_(folded_weight) self._fold_bias[rows].copy_(folded_bias) if self._sl_ids is not None: self.attach_shortlist(self._sl_ids, self._sl_width)
@torch.no_grad() def attach_shortlist(self, ids, width): self._sl_ids, self._sl_width = ids, int(width) self._sl_fw = self._fold_weight.index_select(0, ids).contiguous() self._sl_fb = self._fold_bias.index_select(0, ids).contiguous()
def get_prev_embeddings(self, token_ids): return self.markov_w1(token_ids.long())
def _rnn_step(self, state, prev_tokens, hidden, f_rnn): inputs = rnn_inputs(state, prev_tokens, self.markov_w1.weight, hidden, f_rnn) return rnn_gates(self.rnn_proj(inputs), state)
def init_state(self, hidden_states): batch_size = hidden_states.shape[0] assert self._get_staged_f is not None f_rnn = self._get_staged_f() assert f_rnn is not None and f_rnn.shape[0] >= batch_size assert f_rnn.shape[1] == self.hidden_size return ( hidden_states.new_zeros(batch_size, self.markov_rank), f_rnn[:batch_size].to(hidden_states.dtype), )
def step_bias(self, prev_tokens, *, hidden_states, state): state, f_rnn = state state, latent = self._rnn_step(state, prev_tokens, hidden_states, f_rnn) if self._sl_ids is not None: part = torch.addmm(self._sl_fb, latent.to(self._sl_fw.dtype), self._sl_fw.T) bias = part.new_zeros((part.shape[0], self._sl_width)) bias.index_copy_(1, self._sl_ids, part) return bias, (state, f_rnn) assert self._fold_weight is not None and self._fold_bias is not None assert self._gather_logits is not None bias = torch.addmm( self._fold_bias, latent.to(self._fold_weight.dtype), self._fold_weight.T ) if self.vocab_shard is None: bias = self._gather_logits(bias) return bias, (state, f_rnn)
def step_logits_dtype(self, base_dtype): return torch.promote_types(base_dtype, self._fold_weight.dtype)
class Inkling2ForConditionalGenerationMTP(DSparkDraftModel): fall_back_to_pt_during_load = False allow_patterns_overrides = ["mtp.safetensors"] safetensors_index_file = None supports_pre_gather_target_hidden_projection = False supports_fused_context_kv = False folds_static_verify_commit = True
def __init__(self, config, quant_config=None, prefix=""): if quant_config is not None: raise ValueError("Inkling2 MTP requires BF16 checkpoint weights") if config.q_bias or config.o_bias: raise ValueError( "Inkling2 MTP does not support attention projection biases" ) DFlashDraftModel.__init__( self, config, quant_config=quant_config, prefix=prefix ) hidden, eps = config.hidden_size, config.rms_norm_eps self.block_size = config.block_size self.gamma = self.block_size - 1 self.sample_from_anchor = False self.num_stages = config.num_hidden_layers self.num_context_features = len(config.target_layer_ids) self.logits_mup_width_multiplier = None self.fc = self.hidden_norm = None self.lm_head = None self.confidence_head = None self.markov_head = Inkling2MTPHead( config.padded_vocab_size, config.markov_rank, hidden, eps ) self.markov_head.step_softcap = config.final_logit_softcapping or None self.markov_head.step_vocab_limit = config.unpadded_vocab_size self.fuse_weight = nn.Parameter( torch.zeros(self.num_stages + 1, self.num_context_features), requires_grad=False, ) self.mask_embed = nn.Parameter(torch.zeros(hidden), requires_grad=False) self._fuse_alpha = None self._f_rnn_rows = None self._f_rnn_buf = None self._sl_ids = None for layer_id, layer in enumerate(self.layers): attn = layer.self_attn attn.attn.window_anchor_at_start = layer_id in config.local_layer_ids attn.attn.num_splits = ( 0 if get_platform().is_sm90 or layer_id not in config.local_layer_ids else 1 ) attn.attn.pack_gqa = True attn.kv_proj_ctx = QKVParallelLinear( hidden_size=hidden, head_size=attn.head_dim, total_num_heads=0, total_num_kv_heads=attn.total_num_kv_heads, bias=False, ) attn.k_norm_ctx = RMSNorm(attn.head_dim, eps=eps) layer.dflare_norm = RMSNorm(hidden, eps=eps)
def set_block_size(self, block_size): if block_size != self.block_size: raise ValueError("Inkling2 MTP requires the checkpoint's block size")
def attach_shared_modules(self, *, embed_tokens, lm_head): if should_apply_lm_head_quant_method(lm_head, lm_head.quant_method): raise ValueError("Inkling2 MTP requires an unquantized target LM head") self.embed_tokens, self.lm_head = embed_tokens, lm_head self.markov_head.attach_fold(lm_head.weight, self.logits_mup_width_multiplier) self.markov_head._gather_logits = self._gather_logits self.markov_head._get_staged_f = lambda: self._f_rnn_rows if _SL_PATH: self._attach_shortlist(_SL_PATH) if lm_head.tp_size > 1: group = ( get_parallel().attn_tp_group if lm_head.use_attn_tp_group else get_parallel().tp_group ) assert group.world_size == lm_head.tp_size assert ( lm_head.num_embeddings_per_partition * lm_head.tp_size == lm_head.num_embeddings_padded ) self.markov_head.vocab_size = int(lm_head.org_vocab_size) shard = lm_head.shard_indices self.markov_head.vocab_shard = VocabShard( start=int(shard.org_vocab_start_index), width=int(shard.org_vocab_end_index - shard.org_vocab_start_index), gather=make_vocab_gather( group, local_width=int(lm_head.num_embeddings_per_partition), dtype=lm_head.weight.dtype, ), )
@torch.no_grad() def _attach_shortlist(self, path): if self.lm_head.tp_size > 1: raise ValueError("SGLANG_INKLING2_DRAFT_SHORTLIST supports TP1 only") with open(path) as f: ids = sorted({int(i) for i in json.load(f)}) width = int(self.lm_head.org_vocab_size) limit = self.markov_head.step_vocab_limit or width if not ids or ids[0] < 0 or ids[-1] >= min(width, limit): raise ValueError(f"shortlist ids must lie in [0, {min(width, limit)})") weight = self.lm_head.weight sl = torch.tensor(ids, dtype=torch.long, device=weight.device) self._sl_ids, self._sl_width = sl, width self._sl_w = weight.index_select(0, sl).contiguous() self.markov_head.attach_shortlist(sl, width) logger.info( "Inkling2 MTP shortlist draft head: %d of %d tokens (%s).", len(ids), width, path )
def _gather_logits(self, logits): return gather_and_crop_vocab(logits, self.lm_head)
def compute_base_logits(self, hidden): assert self.lm_head is not None if self.logits_mup_width_multiplier: hidden = hidden / self.logits_mup_width_multiplier if self._sl_ids is not None: part = torch.matmul(hidden.to(self._sl_w.dtype), self._sl_w.T) logits = part.new_full((part.shape[0], self._sl_width), _SL_FILL) logits.index_copy_(1, self._sl_ids, part) return logits, None logits = project_through_lm_head(hidden, self.lm_head) if self.markov_head.vocab_shard is None: logits = self._gather_logits(logits) return logits, None
def forward_embed(self, input_ids): assert self.embed_tokens is not None ids = input_ids.view(-1, self.block_size) hidden = ( self.mask_embed.to(self.embed_tokens.weight.dtype) .expand(ids.shape[0], self.block_size, -1) .clone() ) hidden[:, 0, :] = self.embed_tokens(ids[:, 0]).to(hidden.dtype) return hidden.view(-1, hidden.shape[-1])
def ensure_propose_staging(self, req_pool_size): if self._f_rnn_buf is None: self._f_rnn_buf = self.mask_embed.new_zeros( req_pool_size + 1, self.config.hidden_size ) elif self._f_rnn_buf.shape[0] != req_pool_size + 1: raise ValueError( "MTP request pool changed after recurrent state allocation" )
def _mix_norm(self, targets, row, norm): assert self._fuse_alpha is not None alpha = self._fuse_alpha[row].to(targets.dtype) return mix_rmsnorm(targets, alpha, norm.weight, norm.variance_epsilon)
def compute_f_rnn(self, target_hidden_last): targets = target_hidden_last.view( target_hidden_last.shape[0], self.num_context_features, self.config.hidden_size, ) return self._mix_norm(targets, -1, self.markov_head.dflare_norm)
def store_f_rnn(self, req_pool_indices, target_hidden_rows): assert self._f_rnn_buf is not None features = self.compute_f_rnn(target_hidden_rows) self._f_rnn_buf.index_copy_( 0, req_pool_indices.view(-1).long(), features.to(self._f_rnn_buf.dtype) )
def store_verify_commit( self, *, req_pool_indices, verify_hidden, commit_lens, stride, valid=None ): bs = commit_lens.shape[0] rows = torch.arange(bs, device=verify_hidden.device) last_hidden = verify_hidden.view(bs, stride, -1)[rows, commit_lens.long() - 1] indices = req_pool_indices[:bs].view(-1).long() if valid is not None: indices = torch.where(valid, indices, self._f_rnn_buf.shape[0] - 1) self.store_f_rnn(indices, last_hidden)
@torch.no_grad() def forward(self, input_ids, positions, forward_batch, input_embeds=None, **kwargs): batch_size, remainder = divmod(input_ids.numel(), self.block_size) assert remainder == 0 assert self._f_rnn_buf is not None self._f_rnn_rows = self._f_rnn_buf.index_select( 0, forward_batch.req_pool_indices.view(-1)[:batch_size].long() ) input_embeds = self.forward_embed(input_ids) return DFlashDraftModel.forward( self, input_ids, positions, forward_batch, input_embeds=input_embeds, **kwargs, )
def project_target_hidden(self, target_hidden): raise RuntimeError( "Inkling2 MTP requires a separate target mixture for every layer" )
def write_target_hidden_kv( self, *, target_hidden, pool, positions, cache_loc, cache_loc_2d=None, commit_lens=None, target_hidden_is_projected=False, swa_loc=None, ): if target_hidden_is_projected: raise ValueError("Inkling2 MTP requires unprojected target hidden states") targets = target_hidden.view( target_hidden.shape[0], self.num_context_features, self.config.hidden_size ) if swa_loc is None and isinstance(pool, SWAKVPool): # Static verify capture can supply only full-space locations. swa_loc = pool.translate_loc_from_full_to_swa(cache_loc) for i, layer in enumerate(self.layers): attn = layer.self_attn context = self._mix_norm(targets, i, layer.dflare_norm) kv, _ = attn.kv_proj_ctx(context.to(attn.kv_proj_ctx.weight.dtype)) k, v = kv.split([attn.kv_size, attn.kv_size], dim=-1) k = attn.k_norm_ctx(k.reshape(-1, attn.head_dim)).view_as(k) k = attn.apply_k_rope(positions, k) k = k.view(-1, attn.num_kv_heads, attn.head_dim) v = v.view(-1, attn.num_kv_heads, attn.head_dim) if cache_loc_2d is not None and commit_lens is not None: pool.layer_router.layer(attn.attn.layer_id).store_prefix( attn.attn, KVWriteLoc( cache_loc_2d, window_locs=layer_window_locs( pool, attn.attn.layer_id, None if swa_loc is None else swa_loc.view_as(cache_loc_2d), ), physical=True, ), commit_lens, k, v, attn.attn.k_scale, attn.attn.v_scale, ) else: pool.layer_router.layer(attn.attn.layer_id).store( attn.attn, KVWriteLoc( cache_loc, window_locs=layer_window_locs( pool, attn.attn.layer_id, swa_loc ), physical=True, ), k, v, attn.attn.k_scale, attn.attn.v_scale, )
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: params = { name: param for name, param in self.named_parameters() if not name.startswith(("embed_tokens.", "lm_head.")) } mapping = ( (".q_proj.", ".qkv_proj.", "q"), (".k_proj.", ".qkv_proj.", "k"), (".v_proj.", ".qkv_proj.", "v"), (".k_proj_ctx.", ".kv_proj_ctx.", "k"), (".v_proj_ctx.", ".kv_proj_ctx.", "v"), (".gate_proj.", ".gate_up_proj.", 0), (".up_proj.", ".gate_up_proj.", 1), ) loaded, shards = set(), {} for checkpoint_name, weight in weights: name, shard = checkpoint_name, None for source, destination, shard_id in mapping: if source in name: name, shard = name.replace(source, destination), shard_id break if name not in params: raise ValueError( f"Unrecognized MTP checkpoint tensor: {checkpoint_name}" ) param = params[name] if weight.dtype != torch.bfloat16 or param.dtype != weight.dtype: raise ValueError( f"{checkpoint_name}: MTP requires BF16 parameters and checkpoint weights" ) loader = getattr(param, "weight_loader", default_weight_loader) if shard is None: if name in loaded: raise ValueError( f"Duplicate MTP checkpoint tensor: {checkpoint_name}" ) loader(param, weight) else: if name in loaded and name not in shards: raise ValueError( f"MTP checkpoint mixes packed and unpacked tensors: {checkpoint_name}" ) pieces = shards.setdefault(name, set()) if shard in pieces: raise ValueError( f"Duplicate MTP checkpoint tensor: {checkpoint_name}" ) loader(param, weight, shard) pieces.add(shard) loaded.add(name) missing = set(params) - loaded for name, pieces in shards.items(): expected = ( {"q", "k", "v"} if ".qkv_proj." in name else {"k", "v"} if ".kv_proj_ctx." in name else {0, 1} ) if pieces != expected: missing.add(f"{name} shards {sorted(expected - pieces)}") if missing: raise ValueError(f"Missing MTP checkpoint tensors: {sorted(missing)}") fuse_alpha = torch.softmax(self.fuse_weight.float(), dim=-1).to( self.fuse_weight.dtype ) if self._fuse_alpha is None: self._fuse_alpha = fuse_alpha else: self._fuse_alpha.copy_(fuse_alpha) return loaded
EntryClass = Inkling2ForConditionalGenerationMTP
# n38 (inkling2-spark decode seat, 2026-11-21): MXFP8 W8A16 drafter dense layers (draft-only numerics: the target verifies# every draft, so outputs stay the target's greedy tokens; acceptance may move). With N38_DRAFT_W8=1, after load_weights every# BF16 linear of this draft model (qkv_proj, kv_proj_ctx, o_proj, gate_up_proj, down_proj; K % 256 == 0, no bias) gets an# e4m3 copy with power-of-2 scales per 32 K-elements (n35_w8gemv.quantize_mx8), and UnquantizedLinearMethod.apply sends calls# of <= 128 rows on such layers to n35_w8gemv.w8_gemv (n33 microbench: drafter mlp up 185 -> 100 us, down 186 -> 106 us).# Larger calls (prompt-chunk context projections) keep the BF16 path. Off when N38_DRAFT_W8 != 1: this file = 822cddb7 then.if os.environ.get("N38_DRAFT_W8") == "1": from sglang.srt.layers.linear import LinearBase as _N38LinearBase from sglang.srt.layers.quantization import unquant as _n38_unquant
_n38_orig_load = Inkling2ForConditionalGenerationMTP.load_weights _n38_orig_apply = _n38_unquant.UnquantizedLinearMethod.apply
def _n38_load_weights(self, weights): out = _n38_orig_load(self, weights) from sglang.srt.models.inkling_common.n35_w8gemv import quantize_mx8 n = tot = 0 for _, m in self.named_modules(): w = getattr(m, "weight", None) b = getattr(m, "bias", None) if (isinstance(m, _N38LinearBase) and isinstance(w, torch.Tensor) and w.dim() == 2 and w.dtype == torch.bfloat16 and w.shape[1] % 256 == 0 and (b is None or not bool(b.abs().max() > 0))): m._n38_w8 = quantize_mx8(w.data) n += 1; tot += w.numel() logger.warning("n38: drafter W8 copies for %d linears, %.0f MB FP8", n, tot / 1e6) return out
def _n38_apply(self, layer, x, bias=None, *a, **kw): q = getattr(layer, "_n38_w8", None) if (q is not None and not a and not kw and bias is None and x.dtype == torch.bfloat16 # no device sync here (graph capture) and 0 < x.numel() // x.shape[-1] <= 128): from sglang.srt.models.inkling_common.n35_w8gemv import w8_gemv return w8_gemv(x, *q) return _n38_orig_apply(self, layer, x, bias, *a, **kw)
Inkling2ForConditionalGenerationMTP.load_weights = _n38_load_weights _n38_unquant.UnquantizedLinearMethod.apply = _n38_apply logger.warning("n38: drafter W8 dispatch installed")
# n41 (inkling2-spark decode seat, 2026-11-21): context-augmented shortlist draft head (draft-only numerics; off unless# N41_CTX_SL > 0 and the shortlist is on). Per request the prompt's own off-shortlist token ids (the N41_CTX_SL most recent# distinct ones, computed once per request on CPU from req.origin_input_ids when DSparkWorkerV2.forward_batch_generation first# sees the request in its pool slot; last 128K prompt tokens) are written to a [req_pool + 1, X] table (pinned, non_blocking); the draft forward gathers the table rows of its# requests by forward_batch.req_pool_indices (inside the draft graph), compute_base_logits adds hidden @ lm_head[E]^T for those# columns and step_bias adds the folded Markov bias for them (scatter into the full-width rows the shortlist head already builds).# Empty table slots hold the first shortlist id (its column is rewritten with a value of the same dot product). n33 probe4:# 13.9 pct of sessions-eval rejections are off-shortlist targets (5.5 pct with the full-vocab head)._N41_X = int(os.environ.get("N41_CTX_SL", "0"))if _N41_X > 0 and _SL_PATH: import numpy as _n41_np
_N41 = {"model": None, "slot_rid": {}, "mask": None, "pad": None, "n": 0, "sizes": [], "patched": False} _n41_orig_staging = Inkling2ForConditionalGenerationMTP.ensure_propose_staging _n41_orig_forward = Inkling2ForConditionalGenerationMTP.forward _n41_orig_base = Inkling2ForConditionalGenerationMTP.compute_base_logits _n41_orig_bias = Inkling2MTPHead.step_bias
def _n41_staging(self, req_pool_size): _n41_orig_staging(self, req_pool_size) if getattr(self, "_n41_tab", None) is None and self._sl_ids is not None: pad = int(self._sl_ids[0]) self._n41_tab = torch.full((req_pool_size + 1, _N41_X), pad, dtype=torch.long, device=self._sl_ids.device) # pinned staging rows, one per pool slot: the H2D copy is non_blocking (a pageable copy would stall the host until # the stream drains, up to a step per new request); a slot is refilled only after its request has finished. try: self._n41_pin = torch.full((req_pool_size + 1, _N41_X), pad, dtype=torch.long).pin_memory() if torch.cuda.is_available() else None except Exception as e: # never fail the boot: fall back to a pageable copy logger.warning("n41: pinned staging unavailable (%r): pageable copies", e); self._n41_pin = None mask = _n41_np.zeros(self._sl_width, dtype=bool); mask[self._sl_ids.cpu().numpy()] = True _N41.update(model=self, mask=mask, pad=pad) _n41_patch_worker() logger.warning("n41: context shortlist table %s (X %d)", tuple(self._n41_tab.shape), _N41_X)
def _n41_forward(self, input_ids, positions, forward_batch, input_embeds=None, **kwargs): out = _n41_orig_forward(self, input_ids, positions, forward_batch, input_embeds=input_embeds, **kwargs) tab = getattr(self, "_n41_tab", None) if tab is not None and self._f_rnn_rows is not None: bs = self._f_rnn_rows.shape[0] self._n41_rows = tab.index_select(0, forward_batch.req_pool_indices.view(-1)[:bs].long()) return out
def _n41_base(self, hidden): logits, extra = _n41_orig_base(self, hidden) rows = getattr(self, "_n41_rows", None) self.markov_head._n41_ctx = None if rows is None or self._sl_ids is None or hidden.shape[0] % rows.shape[0]: return logits, extra bs, x = rows.shape; g = hidden.shape[0] // bs h = hidden / self.logits_mup_width_multiplier if self.logits_mup_width_multiplier else hidden w = self.lm_head.weight.index_select(0, rows.view(-1)).view(bs, x, -1) part = torch.bmm(h.view(bs, g, -1).to(w.dtype), w.transpose(1, 2)) logits.view(bs, g, -1).scatter_(2, rows[:, None, :].expand(bs, g, x), part.to(logits.dtype)) mh = self.markov_head mh._n41_ctx = (rows, mh._fold_weight.index_select(0, rows.view(-1)).view(bs, x, -1), mh._fold_bias.index_select(0, rows.view(-1)).view(bs, x)) return logits, extra
def _n41_bias(self, prev_tokens, *, hidden_states, state): bias, state2 = _n41_orig_bias(self, prev_tokens, hidden_states=hidden_states, state=state) ctx = getattr(self, "_n41_ctx", None) if ctx is None or self._sl_ids is None: return bias, state2 rows, fw, fb = ctx latent = self._n41_latent if latent.shape[0] != rows.shape[0]: return bias, state2 part = torch.baddbmm(fb.unsqueeze(1), latent.to(fw.dtype).unsqueeze(1), fw.transpose(1, 2)).squeeze(1) bias.scatter_(1, rows, part.to(bias.dtype)) return bias, state2
_n41_orig_rnn = Inkling2MTPHead._rnn_step
def _n41_rnn(self, state, prev_tokens, hidden, f_rnn): state, latent = _n41_orig_rnn(self, state, prev_tokens, hidden, f_rnn) self._n41_latent = latent return state, latent
def _n41_fill(reqs): m = _N41["model"] if m is None: return import time as _n41_time _t0 = _n41_time.perf_counter(); _n0 = _N41["n"] try: _n41_fill_rows(m, reqs) finally: if _N41["n"] > _n0: _N41.setdefault("host_s", 0.0); _N41["host_s"] += _n41_time.perf_counter() - _t0
def _n41_fill_rows(m, reqs): for req in reqs: kv = getattr(req, "kv", None) slot = getattr(kv, "req_pool_idx", None) if kv is not None else getattr(req, "req_pool_idx", None) if slot is None or _N41["slot_rid"].get(slot) == req.rid: continue ids = _n41_np.asarray(req.origin_input_ids[-131072:], dtype=_n41_np.int64) # bound host work per request ids = ids[(ids >= 0) & (ids < len(_N41["mask"]))] off = ids[~_N41["mask"][ids]][::-1] uniq, first = _n41_np.unique(off, return_index=True) recent = uniq[_n41_np.argsort(first)][:_N41_X] row = _n41_np.full(_N41_X, _N41["pad"], dtype=_n41_np.int64); row[: len(recent)] = recent if m._n41_pin is not None: m._n41_pin[slot].copy_(torch.from_numpy(row)) m._n41_tab[slot].copy_(m._n41_pin[slot], non_blocking=True) else: m._n41_tab[slot].copy_(torch.from_numpy(row)) _N41["slot_rid"][slot] = req.rid; _N41["n"] += 1; _N41["sizes"].append(len(uniq)) if _N41["n"] in (1, 10, 32, 50) or _N41["n"] % 64 == 0: s = sorted(_N41["sizes"]) logger.warning("n41: %d requests filled; distinct off-shortlist context ids median %d p90 %d max %d (X %d); host fill %.1f ms per request", _N41["n"], s[len(s) // 2], s[int(0.9 * (len(s) - 1))], s[-1], _N41_X, 1000 * _N41.get("host_s", 0.0) / max(1, _N41["n"] - 1))
def _n41_patch_worker(): if _N41["patched"]: return import sys as _sys mod = _sys.modules.get("sglang.srt.speculative.dspark_components.dspark_worker_v2") cls = getattr(mod, "DSparkWorkerV2", None) if mod is not None else None if cls is None: logger.warning("n41: DSparkWorkerV2 not loaded: context table stays empty") return orig = cls.forward_batch_generation
def forward_batch_generation(self, batch, *a, **kw): try: _n41_fill(getattr(batch, "reqs", ()) or ()) except Exception as e: # never break serving: the table just stays as it is logger.warning("n41: fill failed: %r", e) return orig(self, batch, *a, **kw)
cls.forward_batch_generation = forward_batch_generation _N41["patched"] = True logger.warning("n41: DSparkWorkerV2.forward_batch_generation hook installed")
Inkling2ForConditionalGenerationMTP.ensure_propose_staging = _n41_staging Inkling2ForConditionalGenerationMTP.forward = _n41_forward Inkling2ForConditionalGenerationMTP.compute_base_logits = _n41_base Inkling2MTPHead.step_bias = _n41_bias Inkling2MTPHead._rnn_step = _n41_rnn logger.warning("n41: context-augmented shortlist installed (X %d)", _N41_X)
# n105 (inkling2-spark rnnhoist seat, 2026-11-23): exact bitwise hoisted Markov RNN projection on bs=1 draft walk# (CERT90: precompute W_f + W_h once in init_state with TwoSum-FP32 + Higham/Rump interval certificate, read only W_s# per step with inline exact stride-16 fixup on ~7 pct tripped rows; bs != 1 keeps served _rnn_step). Off unless# N105_RNNHOIST=1 (off = S3 ff39c84d verbatim). Pointer-offset walk-step recovery adapts MIT code from# knapcio/Inkling-2-Mini-1x-DGX-Spark (Copyright (c) 2026 Zbigniew Majewski, MIT License).if os.environ.get("N105_RNNHOIST") == "1": import sys as _n105_sys from sglang.srt.models.inkling_common import n105_rnnhoist as _n105_mod _n105_mod.install(_n105_sys.modules[__name__])
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167#!/bin/bash# inkling2-spark: SGLang day-0 stack for thinkingmachines/Inkling-2-Mini on the DGX Spark (GB10, sm_121).# Source: the SGLang cookbook, DGX Spark + DSpark entry (sgl-project/sglang#51927, python/sglang/cli/_commands/# thinkingmachines--Inkling-2-Mini.json, hw=dgx-spark mode=dspark, "verified"); model support = PR #51926 (open), shipped in# the image lmsysorg/sglang:inkling-2-mini. Flags and env exactly as the cookbook, except:# --context-length 262144 (ours: the cookbook sets none; the same cap as the vLLM Spark recipe, so both engines serve the# same context) and --served-model-name / --api-key / port.# Knobs (env): NAME PORT API_KEY IMAGE (required); MODEL_DIR MEM CTX SPEC NUM_DRAFT CACHE_DIR SERVED EXTRA_ARGS.# n2-proj1 (inkling2-spark prefill seat, 2026-11-20): the champion + per-source qkvr projection on 3-source attention visits (loop# passes 2-3 and the global layers) at >= 512 tokens. The image stacks the three sources (3T rows) through the full 8,600-column# qkvr weight and keeps a third of each output; here each source multiplies only the weight rows it uses (q/r/gate/sinks from# q's source, k from k's, v from v's), F.linear on row slices of the same weight, the same cuBLAS path. Bitwise identical# outputs (n2-probe1: logprobs and KLD equal to the digit). One file mounted over the image: ../patch/inkling2_attn.py (image# file md5 b6d57038 + a guarded branch in _project_sources, switch SGLANG_INKLING_SPLIT_PROJ). Knob added: INK_PROJ_SPLIT# (default 1; 0 = the patched file with the branch off).# n21-bs1 (inkling2-spark attn-global seat, 2026-11-21): n17-slp1 + n13-bs1's global-layer band-split FA4 SM120 prefill kernel# (FlashAttentionForwardSm120BandSplit, bitwise equal to the image kernel). Adds the same two mounted files as n13-bs1# (../patch/n13_fwd.py at fa4_sm120/n13_fwd.py, ../patch/n13_attn_global.py) and n13-bs1's patch/inkling2_attn.py# (n17-slp1's = n2-proj1's file + 2 lines installing the hook). Replaces only FlashAttentionForwardSm120.mma for# has_bias, not is_local, not pack_gqa kernels; the draft head files (serve/inkling2_mtp.py, sl.json) are n17-slp1's.# n32-ikb2 (inkling2-spark attn-bias seat, 2026-11-21): n32-ikb1 + the same in-kernel bias producer on the GLOBAL layers too:# n13's band-split kernel (its consumer mma and unswizzled bias tile, n13_fwd.py unchanged) is built as# FlashAttentionForwardSm120BandSplitRelProd (n32_fwd.py generated with N32_GLOBAL = 1), so the global einsum + ShearingBias# are not run either. This touches n13's global path (supervisor ruling 2026-11-21: n13 unseated, attn-bias owns the change).# Knob added: INK_N32_GLOBAL (default 1; 0 = sliding-only, = n32-ikb1's behaviour under this recipe's kernel file).# n32-ikb1 (inkling2-spark attn-bias seat, 2026-11-21): n21-bs1 + the sliding-layer prefill rel bias computed inside the FA4 SM120# kernel (FlashAttentionForwardSm120RelProd: the DMA warp builds each sheared bias tile with mma.sync m16n8k16 + RTNE, bitwise# equal to the served einsum + ShearingBias + FA4 path in work_attnbias mb1). Adds ../patch/n32_fwd.py at fa4_sm120/n32_fwd.py# (its own FA4 AOT fingerprint) and ../patch/n32_attn_local.py, and ../patch/inkling2_attn.py = n21's file + the guarded rel_bias# line + the hook install. Knobs added: INK_N32 (default 1; 0 = served bias path, same mounted files), ADMIN=1# (--admin-api-key API_KEY, for /start_profile), EXTRA_DOCKER (extra docker run options, e.g. -v .../prof:/prof).# n14x37 (inkling2-spark moe seat, 2026-11-22; composition owned by the moe seat per the supervisor's ruling): decode's# cands/n41-k2 recipe (n48's ikb2 attention files untouched + n35 / n37 / n38 / n41 decode files) + n14's exact SM120 MoE prefill# visit (../patch/n14_moe.py f9435cd7 + ../patch/n14_quant.cuh afdcb38b, calls >= 512 tokens; n37 only touches <= 128-token# tiles, so the two never meet). ../patch/inkling2_attn.py = n41-k2's 1579708b + the n14 install block. Knob N14_MOE (default qc;# empty = the image MoE path). Manifests: work_moe/n14x37.py (x37 knobs) and work_moe/n14n37.py (exact: n14 + n37 only).# n54 (inkling2-spark stack seat, 2026-11-22): n51's recipe (cands/n14x37 = n48 + n14 qc + n37, run with the n14n37 ENV) + n50's# exact fused loop controller: ../patch/inkling2_loop.py (image kernels/ops/elementwise/inkling2_loop.py caaaefb4 + the n50# dispatch) and ../patch/n15_fused.py (the fused kernel, build 4 380adeee), both mounted over / beside the image module.# Knobs N50 (default 1 = prefill-size calls run the fused kernel; 0 = the served kernels with the same files; check = served +# fused + a failing control, returns the fused output, mismatch counter in pinned host memory printed as N50CHECK lines) and# N50_MIN (default 1000 tokens; decode / verify sizes always take the served kernels).# n75 (inkling2-spark packed seat, 2026-11-22): n54 + exact 12-bit packed BF16 weights on the served small-M GEMV route:# ../patch/n75_install.py + ../patch/n75_c12.py mounted beside the image modules; ../patch/inkling2_attn.py = n54's 1e3a8cae + the# n75 install block. Knobs N75_C12 (attn = qkvr + wo_ud, lm = LM head; default empty = off, the n54 code path), N75_C12_CHECK# (1 = served + packed + a failing control per call, returns the packed output, N75CHECK lines), N75_C12_CFG (BN,warps,stages),# N75_C12_KERNEL (triton | cuda | per class 'qkvr=cuda,...': build 1 / build 2 (../patch/n75_cuda.py), same output bits),# N75_C12_CUDA_NW (warps per CTA of build 2, one value or per class).# n86 S1 (inkling2-spark stack seat, 2026-11-23): n54 + n71 riders G1 / G2 + the n75 build-2 rider (RULE n86 S1): ../patch/n86_riders.py,# ../patch/n71_sconvres.py (09d3d221) and ../patch/n71_resnorm.py (d1054a4c) mounted beside the image modules; ../patch/inkling2_attn.py# = n75's 8771c89c + the n86 install block. Knobs N86_G1 / N86_G2 (1 = on; default 0 = the n54 code path), N86_MIN_ROWS (G2 rows# gate, default 2048), N86_G2_SHAPES (fused G2 shapes), N86_N75_MS (packed GEMV rows, default 8,16), N86_N75_CLASSES.# n64-p1 (inkling2-spark attn seat, 2026-11-22): n54 + n64's exact two-kernel global-layer prefill attention: kernel A# (../patch/n64a_fwd.py at fa4_sm120/n64a_fwd.py: n54's band part, state store) + kernel B (../patch/n64b_fwd.py: 8 consumer# warps under setmaxnreg on the far blocks, n54's far math, served finalize) via ../patch/n64_attn_global.py (installed# after n32's hook in ../patch/inkling2_attn.py). Knobs N64 (default 1; 0 = n54's path with the same files), N64_MIN_K# (KV span bound below which a call keeps n54's path; default 0), N64_PREALLOC (heads of the install-time workspace, 24).# n78 certified greedy LM head, S8 (inkling2-spark packed seat, 2026-11-23; recipe cands/<name> = cp -a cands/n54 + these files):# n54 + ../patch/n78_head.py + ../patch/n78_kern.py mounted beside the image modules; ../patch/inkling2_attn.py = n54's 1e3a8cae# + the n78 install block. Knobs N78_CERT (1 = bs-1 / bs-2 target-verify LM-head calls on all-greedy plain steps run the INT8# screen + bound + served-body exact tiles, +474 MB; every other step and call runs the full served head; default empty = off,# n54's path exactly) and N78_CHECK (1 = CHECK BOOT ONLY: the served head also runs in-graph and N78CHECK counters are printed).# n126 S4 (inkling2-spark stack seat, 2026-11-24): S3 (cands/n86-s3) + three exact riders, each off by its knob except a4 (a file):# n115 a4 = ../patch/n32_fwd.py 7e0b8ca9 (S3's 115d2333 + the full-block consumer-built sliding bias; smaller blocks keep the served# DMA producer); n124 F2b = ../patch/n52_moe.py c614ad75 + ../patch/n52_band.cuh e855abc8 (chunked NVFP4 gate_up GEMM, TB 16 bands,# + the lean L2 swiglu-NVFP4 pass on NVFP4 MoE prefill calls >= 3,073 tokens; installed after n14 by ../patch/inkling2_attn.py =# S3's c8bd1ccc + the n52 install block) with knobs N52_BAND (2 = on, default 0 = S3's MoE path), N52_FORM (f2), N52_TB (16),# N52_LEAN (1), N52_RASTER (0; the f2 path forces AlongM); n105 build 3 = ../patch/n105_rnnhoist.py 4f3d50fa + serve/inkling2_mtp.py# f68b1967 (S3's ff39c84d + the env-gated install) with knobs N105_RNNHOIST (1 = on, default empty = S3's drafter verbatim),# N105_MODE, N105_PRE_NW, N105_STEP_NW, N105_CHECK (1 = CHECK BOOT ONLY: served RNN step + a failing control beside each hoisted step).set -eu# n41-k2 (inkling2-spark decode seat, 2026-11-21): n39-k2 (ikb2-rebased) + n41: serve/inkling2_mtp.py = the n41 file (n17 822cddb7 + the n38 block# + the env-gated n41 context-augmented shortlist: the most recent N41_CTX_SL distinct off-shortlist prompt token ids per request# join the 32K draft shortlist; draft-only). Knob N41_CTX_SL (default 4096; 0 = n39-dec's drafter exactly).# n39-k2 (inkling2-spark decode seat, 2026-11-21): n32-ikb2 + the n39-dec decode stack, rebased for the case that ikb2 ships:# n35 (patch/n35_w8.py + patch/n35_w8gemv.py: MXFP8 W8A16 qkvr / wo_ud on decode / verify only, knob N35_W8 attn | empty),# n37 (patch/n37_tiles.py: NVFP4 grouped-GEMM decode tile_k N37_TILE_K, default 256, bitwise equal to the image config),# n38 (serve/inkling2_mtp.py = the n17 file 822cddb7 + an env-gated block: W8 drafter linears when N38_DRAFT_W8=1, default 1).# patch/inkling2_attn.py = ikb2's c1889915 + the n35 and n37 install blocks appended. Empty / 128 / 0 = ikb2 exactly.INK_N32=${INK_N32:-1}INK_N32_GLOBAL=${INK_N32_GLOBAL:-1}EXTRA_DOCKER=${EXTRA_DOCKER:-}ADMIN=${ADMIN:-0}; ADMIN_ARGS=(); [ "$ADMIN" = 1 ] && ADMIN_ARGS=(--admin-api-key "$API_KEY")# n17 (dspark seat, 2026-11-21, staged): n2-proj1 + ds-sl32. Adds the ds-sl32 shortlist-vocab DSpark draft head: serve/inkling2_mtp.py# (image md5 35e23e4a + env-gated shortlist, md5 822cddb7) and serve/sl.json (32,768 ids, md5 389d362c), mounted only with SPEC=1.HERE=$(cd "$(dirname "$0")/.." && pwd)SDIR=$(cd "$(dirname "$0")" && pwd)INK_PROJ_SPLIT=${INK_PROJ_SPLIT:-1}N14_MOE=${N14_MOE-qc}KJ=/sgl-workspace/sglang/python/sglang/kernels/jit/csrc/inkling2N75_C12=${N75_C12:-}; N75_C12_CHECK=${N75_C12_CHECK:-0}; N75_C12_CFG=${N75_C12_CFG:-}N75_C12_KERNEL=${N75_C12_KERNEL:-}; N75_C12_CUDA_NW=${N75_C12_CUDA_NW:-}N86_G1=${N86_G1:-0}; N86_G2=${N86_G2:-0}; N86_MIN_ROWS=${N86_MIN_ROWS:-2048}; N86_G2_SHAPES=${N86_G2_SHAPES:-}N86_N75_MS=${N86_N75_MS:-8,16}; N86_N75_CLASSES=${N86_N75_CLASSES:-qkvr,wo_ud,lm_head}N78_CERT=${N78_CERT:-}; N78_CHECK=${N78_CHECK:-}N35_W8=${N35_W8-attn}N37_TILE_K=${N37_TILE_K:-256}N38_DRAFT_W8=${N38_DRAFT_W8:-1}N41_CTX_SL=${N41_CTX_SL:-4096}N50=${N50:-1}; N50_MIN=${N50_MIN:-1000}N64=${N64:-1}; N64_MIN_K=${N64_MIN_K:-0}; N64_PREALLOC=${N64_PREALLOC:-24}N52_BAND=${N52_BAND:-0}; N52_FORM=${N52_FORM:-f2}; N52_TB=${N52_TB:-16}; N52_LEAN=${N52_LEAN:-1}; N52_RASTER=${N52_RASTER:-0}N105_RNNHOIST=${N105_RNNHOIST:-}; N105_MODE=${N105_MODE:-}; N105_PRE_NW=${N105_PRE_NW:-}; N105_STEP_NW=${N105_STEP_NW:-}; N105_CHECK=${N105_CHECK:-}KO=/sgl-workspace/sglang/python/sglang/kernels/ops/elementwiseMDL=/sgl-workspace/sglang/python/sglang/srt/models/inkling_common: "${NAME:?}" "${PORT:?}" "${API_KEY:?}" "${IMAGE:?}"MODEL_DIR=${MODEL_DIR:-/workspace/models/Inkling-2-Mini}; MEM=${MEM:-0.45}; CTX=${CTX:-262144}SPEC=${SPEC:-1}; NUM_DRAFT=${NUM_DRAFT:-8}; CACHE_DIR=${CACHE_DIR:-/workspace/eat-inkling/cache/sglang}; SERVED=${SERVED:-inkling-2-mini}EXTRA_ARGS=${EXTRA_ARGS:-}FA=/sgl-workspace/sglang/python/sglang/kernels/ops/attention/fa4_sm120mkdir -p "$CACHE_DIR"[ "$SPEC" = dflash2 ] || { echo "n292 requires SPEC=dflash2" >&2; exit 2; }DRAFT_DIR=${DRAFT_DIR:-/workspace/eat-inkling/drafters/dflash2-4f9088ea}[ -f "$DRAFT_DIR/model.safetensors" ] && [ "$(cat "$DRAFT_DIR/.revision" 2>/dev/null)" = 4f9088ea66c21f2b99ed657d1941c306b03e84d2 ] || { echo "no DFlash2 drafter at $DRAFT_DIR" >&2; exit 1; }extra=$(cd "$DRAFT_DIR" && ls -A | grep -vxE 'config\.json|model\.safetensors|sglang_inkling_dflash2\.py|README\.md|\.revision' || true)[ -z "$extra" ] || { echo "unexpected files in $DRAFT_DIR: $extra" >&2; exit 1; }DFLASH2_SHA256="14223ae2f3aa1d661da67cf0143ec33070d952a6e28a119e6cec64fcc0bebe50 sglang_inkling_dflash2.pyd094e435eb939e01fca6297f637c5af35e3da4b552f8e1ab0a181cd278a1cefa config.json217980ab00d116693fa5946df7bbfd967caf5fac1f529afd541fbd470ddb54ee model.safetensors"docker rm -f "$NAME" > /dev/null 2>&1 || true# shellcheck disable=SC2086exec docker run --pull=never -d --name "$NAME" --gpus all --ipc=host --shm-size 32g \ -p 127.0.0.1:$PORT:30000 \ -e MAX_JOBS=4 -e HF_HUB_OFFLINE=1 -e DO_NOT_TRACK=1 -e SGLANG_DISABLE_USAGE_STATS=1 \ -v "$MODEL_DIR":/model:ro -v "$CACHE_DIR":/root/.cache \ -v "$HERE/patch/inkling2_attn.py":$MDL/inkling2_attn.py:ro -e SGLANG_INKLING_SPLIT_PROJ="$INK_PROJ_SPLIT" \ -v "$HERE/patch/n13_attn_global.py":$MDL/n13_attn_global.py:ro -v "$HERE/patch/n13_fwd.py":$FA/n13_fwd.py:ro \ -v "$HERE/patch/n75_install.py":$MDL/n75_install.py:ro -v "$HERE/patch/n75_c12.py":$MDL/n75_c12.py:ro \ -v "$HERE/patch/n75_cuda.py":$MDL/n75_cuda.py:ro -e N75_C12_KERNEL="$N75_C12_KERNEL" -e N75_C12_CUDA_NW="$N75_C12_CUDA_NW" \ -e N75_C12="$N75_C12" -e N75_C12_CHECK="$N75_C12_CHECK" -e N75_C12_CFG="$N75_C12_CFG" \ -v "$HERE/patch/n86_riders.py":$MDL/n86_riders.py:ro -v "$HERE/patch/n71_sconvres.py":$MDL/n71_sconvres.py:ro \ -v "$HERE/patch/n71_resnorm.py":$MDL/n71_resnorm.py:ro -e N86_G1="$N86_G1" -e N86_G2="$N86_G2" -e N86_MIN_ROWS="$N86_MIN_ROWS" \ -e N86_G2_SHAPES="$N86_G2_SHAPES" -e N86_N75_MS="$N86_N75_MS" -e N86_N75_CLASSES="$N86_N75_CLASSES" \ -v "$HERE/patch/n78_head.py":$MDL/n78_head.py:ro -v "$HERE/patch/n78_kern.py":$MDL/n78_kern.py:ro -e N78_CERT="$N78_CERT" -e N78_CHECK="$N78_CHECK" \ -v "$HERE/patch/n35_w8.py":$MDL/n35_w8.py:ro -v "$HERE/patch/n35_w8gemv.py":$MDL/n35_w8gemv.py:ro -e N35_W8="$N35_W8" \ -v "$HERE/patch/n14_moe.py":$MDL/n14_moe.py:ro -v "$HERE/patch/n14_quant.cuh":$KJ/n14_quant.cuh:ro -e N14_MOE="$N14_MOE" \ -v "$HERE/patch/n52_moe.py":$MDL/n52_moe.py:ro -v "$HERE/patch/n52_band.cuh":$KJ/n52_band.cuh:ro \ -e N52_BAND="$N52_BAND" -e N52_FORM="$N52_FORM" -e N52_TB="$N52_TB" -e N52_LEAN="$N52_LEAN" -e N52_RASTER="$N52_RASTER" \ -v "$HERE/patch/n105_rnnhoist.py":$MDL/n105_rnnhoist.py:ro -e N105_RNNHOIST="$N105_RNNHOIST" -e N105_MODE="$N105_MODE" \ -e N105_PRE_NW="$N105_PRE_NW" -e N105_STEP_NW="$N105_STEP_NW" -e N105_CHECK="$N105_CHECK" \ -v "$HERE/patch/n37_tiles.py":$MDL/n37_tiles.py:ro -e N37_TILE_K="$N37_TILE_K" -e N38_DRAFT_W8="$N38_DRAFT_W8" -e N41_CTX_SL="$N41_CTX_SL" \ -v "$HERE/patch/n32_attn_local.py":$MDL/n32_attn_local.py:ro -v "$HERE/patch/n32_fwd.py":$FA/n32_fwd.py:ro \ -v "$HERE/patch/inkling2_loop.py":$KO/inkling2_loop.py:ro -v "$HERE/patch/n15_fused.py":$KO/n15_fused.py:ro \ -e SGLANG_INKLING_N50="$N50" -e SGLANG_INKLING_N50_MIN_TOKENS="$N50_MIN" \ -e SGLANG_INKLING_N32="$INK_N32" -e SGLANG_INKLING_N32_GLOBAL="$INK_N32_GLOBAL" \ -v "$HERE/patch/n64a_fwd.py":$FA/n64a_fwd.py:ro -v "$HERE/patch/n64b_fwd.py":$FA/n64b_fwd.py:ro \ -v "$HERE/patch/n64_attn_global.py":$MDL/n64_attn_global.py:ro -e SGLANG_INKLING_N64="$N64" \ -e SGLANG_INKLING_N64_MIN_K="$N64_MIN_K" -e SGLANG_INKLING_N64_PREALLOC_HEADS="$N64_PREALLOC" $EXTRA_DOCKER \ -e SGLANG_OPT_INKLING2_VERIFY_REL_BIAS_KERNEL=1 \ -e SGLANG_OPT_DSV41_DSPARK_MID_FOLD=1 \ -e SGLANG_OPT_DSV41_DSPARK_PREPARE_INPUTS_ONCE=1 \ -e SGLANG_OPT_DSV41_DSPARK_SKIP_PREFILLED_INPUTS=1 \ -e MALLOC_MMAP_THRESHOLD_=1048576 \ -e SGLANG_ENABLE_DFLASH_DRAFT_KV_RING=1 -e DFLASH2_SHA256="$DFLASH2_SHA256" -v "$DRAFT_DIR":/draft:ro \ --entrypoint bash "$IMAGE" \ -c 'mkdir -p /root/.cache/dflash2-logs; exec > >(tee -a /root/.cache/dflash2-logs/server-$(date -u +%Y%m%dT%H%M%SZ).log) 2>&1 (cd /draft && printf "%s\n" "$DFLASH2_SHA256" | sed "s/ / /" | sha256sum -c --quiet -) || { echo "DFlash2 drafter files do not match the pinned sha256" >&2; exit 1; } python3 -I /draft/sglang_inkling_dflash2.py && exec python3 "$@"' dflash2 \ -m sglang.launch_server --model-path /model --served-model-name "$SERVED" \ --tp 1 --ep 1 --attention-backend fa4 --dtype bfloat16 --page-size 128 \ --speculative-algorithm DFLASH --speculative-draft-model-path /draft --speculative-num-draft-tokens 8 --speculative-draft-attention-backend fa4 --speculative-use-block-verification \ --max-running-requests 48 --cuda-graph-max-bs-decode=48 \ --mem-fraction-static "$MEM" --context-length "$CTX" \ --grammar-backend xgrammar --reasoning-parser inkling --tool-call-parser inkling2 \ --enable-metrics --host 0.0.0.0 --port 30000 --api-key "$API_KEY" --weight-loader-disable-mmap --swa-full-tokens-ratio 0.037 \ --max-mamba-cache-size 512 --max-prefill-tokens 8192 $EXTRA_ARGS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""inkling_n320s: pfuse's sconvres launch at another exact tile (prefill seat, tree n320; enters the package only on an n320-1 KEEP).
INKLING_N320_SCONV=BM,BN,WARPS (needs INKLING_PFUSE with sconvres): inkling_pfuse.mix.sconv_residual is replaced by the same function (served mix.py 1e93144f lines 203-222, checks and arguments unchanged) launching _triton_sconv._sconv_residual_kernel at (BM, BN, WARPS) instead of (16, 128, 4). The kernel is per-element, so every tile is bitwise (n320-1 measures and checks it).Reach: STATE["calls"]; one log line at the first call."""import loggingimport os
import torch
STATE = {"installed": False, "calls": 0, "tile": None}_log = logging.getLogger(__name__)
def _tile(): bm, bn, warps = (int(x) for x in os.environ["INKLING_N320_SCONV"].split(",")) assert bm in (8, 16, 32, 64, 128) and bn in (32, 64, 128, 256, 512) and warps in (1, 2, 4, 8, 16), (bm, bn, warps) return bm, bn, warps
def _patch(mix): import inspect
import triton
served = mix.sconv_residual if getattr(served, "_n320s", False): return src = inspect.getsource(served) assert "(triton.cdiv(rows, 16), triton.cdiv(width, 128))" in src and "partial is not None, 16, 128," in src, "served launch changed" bm, bn, warps = _tile()
def sconv_residual(x, weight, cache, metadata, attention, partial): from inkling_pfuse import _triton_sconv
rows, width = x.shape kernel_width = weight.shape[1] assert rows >= mix.sconv_min_rows() and x.stride(-1) == 1 and x.dtype == torch.bfloat16 assert cache.ndim == 3 and cache.shape[1:] == (kernel_width - 1, width) for t in (attention, partial): assert t is None or (t.shape == x.shape and t.dtype == torch.bfloat16 and t.is_contiguous()) out = torch.empty_like(attention) _triton_sconv._sconv_residual_kernel[(triton.cdiv(rows, bm), triton.cdiv(width, bn))]( x, weight, cache, metadata["safe_idx"], metadata["cache_mask"], metadata["cu"], metadata["si"], attention, partial if partial is not None else attention, out, rows, x.stride(0), *weight.stride(), *cache.stride(), width, kernel_width, (kernel_width + 1) ** -0.5, partial is not None, bm, bn, num_warps=warps, enable_fp_fusion=False, ) STATE["calls"] += 1 if STATE["calls"] == 1: _log.warning("n320s: sconv_residual at tile (%d, %d, %d warps)", bm, bn, warps) return out
sconv_residual._n320s = True mix.sconv_residual = sconv_residual STATE.update(installed=True, tile=(bm, bn, warps))
def install(): from inkling_pfuse import _hook
_tile() # fail at start-up on a malformed switch _hook.when_imported("inkling_pfuse.mix", _patch)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""inkling_n329: phoist.prepare's _bank_stats_kernel launched per row (prefill seat, tree n329; n329-1 KEEP, kit 849ac214).
INKLING_N329=1 (needs INKLING_PFUSE_HOIST): inkling_phoist.phoist_triton._bank_stats_kernel is wrapped so that a launch on grid (T, 12) runs n329_rows._bank_stats_rows_kernel on grid (T,) with the same arguments (the 12 layer-sides looped inside the program, the served body unchanged); any other grid goes to the served kernel. Bitwise vs served (n329-1: BP / BI / MR word-equal, eager + graph, 1-bit control found); -4.73 / -3.98 ms per attention / mlp call at 12,288 rows (17.4 ms per 12K forward).Reach: STATE counts launches routed each way; the first routed launch logs one line ('n329: per-row _bank_stats').CUDA graphs: the wrapper only picks the kernel object at launch time (host side); a captured graph holds the per-row launch."""import loggingimport os
STATE = {"installed": False, "rows": 0, "served": 0}_log = logging.getLogger(__name__)
class _RowsGrid: """Stands in for the served JITFunction at `kernel[grid](...)` call sites."""
def __init__(self, served, rows): self.served = served self.rows = rows
def __getitem__(self, grid): if isinstance(grid, tuple) and len(grid) == 2 and grid[1] == 12: STATE["rows"] += 1 if STATE["rows"] == 1: _log.warning("n329: per-row _bank_stats (grid (%s, 12) -> (%s,))", grid[0], grid[0]) return self.rows[(grid[0],)] STATE["served"] += 1 return self.served[grid]
def __getattr__(self, name): return getattr(self.served, name)
def _patch(kt): if os.environ.get("N329_CONTROL", "").strip() == "1": # failing control for check boots: mrstd x (1 + 2^-18) from . import n329_rows_ctl as n329_rows _log.warning("n329: CONTROL kernel (mrstd x (1 + 2^-18)), outputs must differ") else: from . import n329_rows
kernel = kt._bank_stats_kernel if isinstance(kernel, _RowsGrid): return rows = n329_rows._bank_stats_rows_kernel if list(kernel.arg_names) != list(rows.arg_names): raise RuntimeError(f"n329: served _bank_stats_kernel arguments changed: {kernel.arg_names} vs {rows.arg_names}") kt._bank_stats_kernel = _RowsGrid(kernel, rows) STATE["installed"] = True
def install(): from inkling_phoist import _hook
_hook.when_imported("inkling_phoist.phoist_triton", _patch)12345678910111213141516171819202122232425262728293031"""n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with thelayer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers."""import tritonimport triton.language as tlfrom triton.language.extra import libdevice # noqa: F401from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401
@triton.jitdef _bank_stats_rows_kernel( B, QM, BP, BI, MR, T, eps_res, eps_ctrl, LS_Q_STRIDE, Q_OFF, NM: tl.constexpr, QP: tl.constexpr, QPM: tl.constexpr, NBP: tl.constexpr, D: tl.constexpr, CH: tl.constexpr,): """Program (row, ls): bank weights of the NM queries of layer-side ls (queries at QM + ls * LS_Q_STRIDE + Q_OFF) and the message rstd, exactly as _loop_stats_kernel computes them. BP [NLS, T, NBP, QP], BI [NLS, T, QP], MR [NLS, T, QPM].""" row = tl.program_id(0).to(tl.int64) for ls32 in tl.range(0, 12): # n329: the 12 layer-sides of the served grid's second axis, in one program ls = ls32.to(tl.int64) qm = tl.arange(0, QPM) Q = QM + ls * LS_Q_STRIDE + Q_OFF bprob, binv = _row_weights(B, B[0], Q, row, eps_res, NM, QPM, NBP, False, True, D, CH) tl.store(BP + (ls * T + row) * (NBP * QP) + tl.arange(0, NBP)[:, None] * QP + qm[None, :], bprob) tl.store(BI + (ls * T + row) * QP + qm, binv) mss = tl.zeros([QPM, CH], tl.float32) for c in tl.static_range(D // CH): m = _row_combine(B, B[0], bprob, binv, row, c, QPM, NBP, False, D, CH) mss = mss + m * m mrstd = libdevice.rsqrt(tl.div_rn(tl.sum(mss, 1), tl.full([QPM], D, tl.float32)) + eps_ctrl) tl.store(MR + (ls * T + row) * QPM + qm, mrstd)
12345678910111213141516171819202122232425262728293031"""n329 FAILING-CONTROL copy (N329_CONTROL=1, check boots only): mrstd x (1 + 2^-18). n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with thelayer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers."""import tritonimport triton.language as tlfrom triton.language.extra import libdevice # noqa: F401from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401
@triton.jitdef _bank_stats_rows_kernel( B, QM, BP, BI, MR, T, eps_res, eps_ctrl, LS_Q_STRIDE, Q_OFF, NM: tl.constexpr, QP: tl.constexpr, QPM: tl.constexpr, NBP: tl.constexpr, D: tl.constexpr, CH: tl.constexpr,): """Program (row, ls): bank weights of the NM queries of layer-side ls (queries at QM + ls * LS_Q_STRIDE + Q_OFF) and the message rstd, exactly as _loop_stats_kernel computes them. BP [NLS, T, NBP, QP], BI [NLS, T, QP], MR [NLS, T, QPM].""" row = tl.program_id(0).to(tl.int64) for ls32 in tl.range(0, 12): # n329: the 12 layer-sides of the served grid's second axis, in one program ls = ls32.to(tl.int64) qm = tl.arange(0, QPM) Q = QM + ls * LS_Q_STRIDE + Q_OFF bprob, binv = _row_weights(B, B[0], Q, row, eps_res, NM, QPM, NBP, False, True, D, CH) tl.store(BP + (ls * T + row) * (NBP * QP) + tl.arange(0, NBP)[:, None] * QP + qm[None, :], bprob) tl.store(BI + (ls * T + row) * QP + qm, binv) mss = tl.zeros([QPM, CH], tl.float32) for c in tl.static_range(D // CH): m = _row_combine(B, B[0], bprob, binv, row, c, QPM, NBP, False, D, CH) mss = mss + m * m mrstd = libdevice.rsqrt(tl.div_rn(tl.sum(mss, 1), tl.full([QPM], D, tl.float32)) + eps_ctrl) tl.store(MR + (ls * T + row) * QPM + qm, mrstd * 1.000003814697265625) # N329_CONTROL: x (1 + 2^-18), wrong by design
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""inkling_n351: the MoE NVFP4 token quantize through an exact n351 variant (prefill seat, tree n351; enters the n320 package onlyon an n351-1 KEEP).
INKLING_N351=V[,GRID] V in 1 / 3 / 5 / 7 (n351_quant.cuh variant bits), GRID optional (0 = the served 4 x SMs rule): sglang.srt.models.inkling_common.n14_moe.nvfp4_token_quantize is wrapped so that width-2304 calls run n351_quant::nvfp4_quantize_tokens<2304, V>; any other width falls through to n14's served kernel. Every written word comes from the same image helpers (n351-1 checks it bitwise vs served). Needs n351_quant.cuh mounted at the JIT csrc path inkling2/n351_quant.cuh (manifest EXTRA_DOCKER).Reach: STATE counts routed / fallen-through calls; one log line at the first routed call."""import loggingimport os
STATE = {"installed": False, "routed": 0, "served": 0, "variant": None, "grid": None}_log = logging.getLogger(__name__)
def _cfg(): parts = [int(x) for x in os.environ["INKLING_N351"].split(",")] v, g = parts[0], (parts[1] if len(parts) > 1 else 0) assert v in (1, 3, 5, 7) and 0 <= g <= 4096 and len(parts) <= 2, parts return v, g
def _module(v): from sglang.kernels.jit.utils import cache_once, load_jit # noqa: F401
key = f"q{v}" if key not in _MODS: _MODS[key] = load_jit("n351_quant", f"2304_{v}", cuda_files=["inkling2/n351_quant.cuh"], cuda_wrappers=[(key, f"n351_quant::nvfp4_quantize_tokens<2304, {v}>")]) return getattr(_MODS[key], key)
_MODS = {}
def _patch(n14): served = n14.nvfp4_token_quantize if getattr(served, "_n351", False): return import inspect assert list(inspect.signature(served).parameters) == ["x", "src2dst", "top_k", "offsets", "grid"], "served signature changed" v, g = _cfg()
def nvfp4_token_quantize(x, src2dst, top_k, offsets, grid=None): if x.shape[1] != 2304: STATE["served"] += 1 return served(x, src2dst, top_k, offsets, grid=grid) from sglang.kernels.ops.moe import inkling2_experts_sm120 as ex
values, scales, amax = ex._nvfp4_outputs(rows=src2dst.numel(), width=2304, experts=offsets.numel() - 1, device=x.device) if src2dst.numel(): _module(v)(x, src2dst, values, scales, amax, offsets, top_k, n14._sm_count(x.device), g) STATE["routed"] += 1 if STATE["routed"] == 1: _log.warning("n351: NVFP4 token quantize through variant %d (grid %s)", v, g or "4 x SMs") return values, scales, amax
nvfp4_token_quantize._n351 = True n14.nvfp4_token_quantize = nvfp4_token_quantize STATE.update(installed=True, variant=v, grid=g)
def install(): from inkling_pfuse import _hook
_cfg() # fail at start-up on a malformed switch _hook.when_imported("sglang.srt.models.inkling_common.n14_moe", _patch)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""inkling_n355: the MXFP8 swiglu-quant (layers 20-23) through an exact n355 variant (prefill seat, tree n355; enters a packageonly on an n355-1 KEEP).
INKLING_N355=V V in 1 / 4 / 5 / 8 / 9 / 13 / 15 (n355_quant.cuh variant bits): the image's sglang.kernels.ops.moe.inkling2_experts_sm120.mxfp8_routed_swiglu_quantize is wrapped so that width-1152 calls with >= MIN_ROWS routed rows (prefill chunks) run n355_quant::mxfp8_swiglu_quantize<1152, V>; smaller calls (decode / verify) and other widths fall through to the served kernel. Every written word comes from the image's own helpers (n355-1 checks it bitwise vs served). Callers (n14_moe.forward_sm120 and inkling2_moe's own forward) look the function up on the module at call time. Needs n355_quant.cuh mounted at the JIT csrc path inkling2/n355_quant.cuh (manifest EXTRA_DOCKER).Reach: STATE counts routed / fallen-through calls; one log line at the first routed call."""import loggingimport os
STATE = {"installed": False, "routed": 0, "served": 0, "variant": None}MIN_ROWS = 4096 # routed rows = tokens x top_k: 512 tokens, the n14 prefill thresholdVARIANTS = (1, 4, 5, 8, 9, 13, 15)_log = logging.getLogger(__name__)_MODS = {}
def _cfg(): v = int(os.environ["INKLING_N355"]) assert v in VARIANTS, v return v
def _module(v): from sglang.kernels.jit.utils import load_jit
key = f"q{v}" if key not in _MODS: _MODS[key] = load_jit("n355_quant", f"1152_{v}", cuda_files=["inkling2/n355_quant.cuh"], cuda_wrappers=[(key, f"n355_quant::mxfp8_swiglu_quantize<1152, {v}>")]) return getattr(_MODS[key], key)
def _patch(ex): served = ex.mxfp8_routed_swiglu_quantize if getattr(served, "_n355", False): return import inspect assert list(inspect.signature(served).parameters) == ["acc", "gammas", "offsets", "gate_cap", "up_cap"], "served signature changed" v = _cfg()
def mxfp8_routed_swiglu_quantize(acc, gammas, offsets, gate_cap, up_cap): rows, width = acc.shape[0], acc.shape[1] // 2 if width != 1152 or rows < MIN_ROWS: STATE["served"] += 1 return served(acc=acc, gammas=gammas, offsets=offsets, gate_cap=gate_cap, up_cap=up_cap) import torch
values, scales, m_padded = ex._mxfp8_outputs(rows=rows, width=width, experts=offsets.numel() - 1, device=acc.device) _module(v)(acc, gammas, values.view(torch.uint8), scales, offsets, m_padded, gate_cap, up_cap, ex._sm_count(acc.device)) STATE["routed"] += 1 if STATE["routed"] == 1: _log.warning("n355: MXFP8 swiglu quantize through variant %d", v) return values, scales.t()
mxfp8_routed_swiglu_quantize._n355 = True ex.mxfp8_routed_swiglu_quantize = mxfp8_routed_swiglu_quantize STATE.update(installed=True, variant=v)
def install(): from inkling_pfuse import _hook
_cfg() # fail at start-up on a malformed switch _hook.when_imported("sglang.kernels.ops.moe.inkling2_experts_sm120", _patch)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""inkling_n381: F2b gate_up through the exact n381 schedule (prefill seat, tree n381; enters a package only under its RULE rows).
INKLING_N381=pv=P,tb=T,raster=R sglang.srt.models.inkling_common.n52_moe.gate_up_chunks is wrapped so that every call runs n381c_band::gate_up_chunks(..., pv) from the unit n381c_band_k128_pp1 (n381c_band.cuh = n360-1's pass-variant source + n381-2's ping-pong / tile_k-128 edits): the F2 chunk GEMM on the stock CUTLASS ptr-array ping-pong schedule at tile_k 128 (n381-2 KEEP: word-exact), the chunk pass through n360 variant P (0 = the served pass), T bands per chunk and raster R (0 AlongM, 1 AlongN). Omitted keys keep the served values (pv 0, n52's TB, the call's raster). Same allocations and arguments as served (n360 rider pattern); n52's forward_sm120 looks gate_up_chunks up as a module global at call time. Needs n381c_band.cuh mounted at the JIT csrc path inkling2/n381c_band.cuh (manifest EXTRA_DOCKER).Replaces inkling_n360 in a package (one unit carries both); install() refuses to run if inkling_n360 already wrapped the function.Reach: STATE counts calls; one log line at the first call."""import loggingimport os
STATE = {"installed": False, "routed": 0, "cfg": None}_log = logging.getLogger(__name__)_MODS = {}TILE_K, PP = 128, 1
def _cfg(): cfg = {"pv": 0, "tb": None, "raster": None} raw = os.environ["INKLING_N381"].strip() for item in filter(None, (x.strip() for x in raw.split(","))): key, _, val = item.partition("=") assert key in cfg and val, f"INKLING_N381 item {item!r}" cfg[key] = int(val) assert cfg["pv"] in (0, 1, 2, 3, 4), cfg assert cfg["tb"] is None or 1 <= cfg["tb"] <= 64, cfg assert cfg["raster"] in (None, 0, 1), cfg return cfg
def _module(lean): import flashinfer from sglang.kernels.jit.utils import load_jit
if lean not in _MODS: data = os.path.join(os.path.dirname(flashinfer.__file__), "data") _MODS[lean] = load_jit( f"n381c_band_k{TILE_K}_pp{PP}", str(int(lean)), cuda_files=["inkling2/n381c_band.cuh"], cuda_wrappers=[("gate_up_chunks", "n381c_band::gate_up_chunks")], extra_include_paths=[f"{data}/cutlass/include", f"{data}/cutlass/tools/util/include"], extra_cuda_cflags=["-DCUTLASS_ENABLE_GDC_FOR_SM100=1", "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED", f"-DN52_LEAN={int(lean)}", f"-DN381_TILE_K={TILE_K}", f"-DN381_PP={PP}"]) return _MODS[lean]
def _patch(n52): served = n52.gate_up_chunks if getattr(served, "_n381", False): return if getattr(served, "_n360", False): raise RuntimeError("inkling_n381: inkling_n360 already wraps gate_up_chunks; the n381 unit carries n360's pass variants (use one)") import inspect want = ["layer", "values", "scales", "amax", "gammas", "offsets", "mode", "raster", "tb", "lean"] assert list(inspect.signature(served).parameters) == want, "served signature changed" cfg = _cfg()
def gate_up_chunks(layer, values, scales, amax, gammas, offsets, mode=2, raster=0, tb=None, lean=None): """= n52_moe.gate_up_chunks on the n381 schedule (same allocations, same arguments; tb / raster / pv from INKLING_N381).""" import torch from sglang.kernels.ops.moe import inkling2_experts_sm120 as ex
w = layer.w13_weight experts, n, kp = w.shape rows = values.shape[0] lean = n52.LEAN if lean is None else int(lean) n52._lean_ok(layer, lean) qv, qs, qa = ex._nvfp4_outputs(rows=rows, width=n // 2, experts=experts, device=values.device) if rows: dev = values.device d = torch.empty((rows, n), dtype=torch.bfloat16, device=dev) iw = torch.empty(8 << 20, dtype=torch.uint8, device=dev) fw = torch.empty(4 << 20, dtype=torch.uint8, device=dev) r = int(raster) if cfg["raster"] is None else cfg["raster"] t = int(n52.TB if tb is None else tb) if cfg["tb"] is None else cfg["tb"] _module(lean).gate_up_chunks( values, w, scales, layer.w13_scale.view(torch.uint8).view(experts, n, kp // 8), offsets, amax, layer.w13_amax, layer.w13_outer_scale_denominator, gammas, d, qv, qs, qa, iw, fw, float(layer.gate_cap), float(layer.up_cap), int(mode), r, t, n52._sm_count(dev), int(cfg["pv"])) STATE["routed"] += 1 if STATE["routed"] == 1: _log.warning("n381: F2b gate_up on the ping-pong tile_k-%d schedule, pass variant %d, tb %s, raster %s", TILE_K, cfg["pv"], cfg["tb"], cfg["raster"]) return qv, qs, qa
gate_up_chunks._n381 = True n52.gate_up_chunks = gate_up_chunks STATE.update(installed=True, cfg=cfg)
def install(): from inkling_pfuse import _hook
_cfg() # fail at start-up on a malformed switch _hook.when_imported("sglang.srt.models.inkling_common.n52_moe", _patch)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Credits
- **Thinking Machines Lab** for Inkling-2-Mini, its NVFP4 / MXFP8 checkpoint and the bundled DSpark draft model (`mtp.safetensors`) ([model card](https://huggingface.co/thinkingmachines/Inkling-2-Mini), [announcement](https://thinkingmachines.ai/news/inkling-2-mini/), Apache-2.0).- **incoai**, [Inkling-2-Mini-DFlash2](https://huggingface.co/incoai/Inkling-2-Mini-DFlash2) (Apache-2.0): the DFlash2 draft model that is this recipe's default drafter, and its SGLang compatibility patch (`sglang_inkling_dflash2.py`), both used as published at revision `4f9088ea`, fetched by `scripts/download.sh` and not distributed here. The drafter byte cuts, the DFLASH verify-width cap, the certified head on DFLASH steps and the selector fix are ours, on top of it.- **The DFlash authors** ([z-lab/dflash](https://github.com/z-lab/dflash)): block-diffusion drafting for speculative decoding, the method behind the DFlash2 drafter, and SGLang's DFLASH worker that serves it.- **SGLang** project for the Inkling-2-Mini support, the `lmsysorg/sglang:inkling-2-mini` image and the [Inkling-2-Mini cookbook](https://docs.sglang.io/cookbook/autoregressive/ThinkingMachines/Inkling-2-Mini), whose DGX Spark DSpark cell (TP1/EP1, FA4, page 128, 8 draft tokens, the four `SGLANG_OPT_*` switches, `MAX_JOBS=4`, the `inkling` / `inkling2` parsers) is the base of the default profile.- **vLLM** project for the Inkling-2-Mini support (vllm-project/vllm #69027, #69028, #69039 by Woosuk Kwon and contributors), the `vllm/vllm-openai:inkling-2-mini` image and the [vLLM recipe](https://recipes.vllm.ai/thinkingmachines/Inkling-2-Mini) behind the alternative profile.- **Tech2Wild (tonyd2wild)**, [Inkling-2-Mini-NVFP4-DGX-Spark](https://github.com/tonyd2wild/Inkling-2-Mini-NVFP4-DGX-Spark): the first single-Spark vLLM recipe for this model. Reused here: the vLLM tier settings (`--gpu-memory-utilization 0.80` at 262K context with tool calling on), the hybrid KV-pool block model and the FP8-KV long-context tier with its memory budget (74 GiB of FP8 KV at 1M), the GB10 page-cache trap, and the advice to keep MemAvailable above ~6 GiB.- **thefullctx**, [inkling-2-mini-sglang-dgx-spark](https://github.com/thefullctx/inkling-2-mini-sglang-dgx-spark) and [inkling-2-mini-vllm-dgx-spark](https://github.com/thefullctx/inkling-2-mini-vllm-dgx-spark): the first published SGLang vs vLLM head-to-head on one Spark (vLLM slightly ahead on short c1 decode, SGLang ~2x on long prefill, faster long-context decode and much lower memory use), which set the arms of our comparison.- **Thien Tran (gau-nernst)**, vLLM PR #69168 (small-M GEMMs for Inkling's looped core): the split-K router / conv-projection and controller re-tiling we screened (not adopted, flat in serving).- **sxuff**, [inkling-2-mini-spark](https://github.com/sxuff/inkling-2-mini-spark) (Apache-2.0): the vLLM + DSpark + INT8 draft recipe and benchmark used for the same-harness comparison, and the `--safetensors-load-strategy eager` result (127 -> 45 s) that prompted our one-pass checkpoint load with SGLang's own flag.- **0xSero**, [inference-optimisation skill](https://github.com/sybil-solutions/inference-optimisation-skill) (MIT): the method behind sxuff's eager-load finding.- **tie-pilot-qxw**, [dspark-markov-walk](https://github.com/tie-pilot-qxw/dspark-markov-walk) (MIT), and [vLLM PR #62958](https://github.com/vllm-project/vllm/pull/62958): the one-kernel DSpark Markov walk that inspired `rnnhoist`. Our projection split is an independent implementation.- **nick398** on the [NVIDIA developer forum thread](https://forums.developer.nvidia.com/t/inkling-2-mini/389745): the first FP8-KV serving notes for this model (vLLM `--kv-cache-dtype fp8` on an RTX 5090: about half the KV memory per token, described there as a quality trade-off).- **Andy Shu (@blaesus)**, [dsgb10](https://github.com/blaesus/dsgb10) (formerly dsgx10, MIT), as carried in [Picom-code/pico-dgx-ds4](https://github.com/Picom-code/pico-dgx-ds4) ("pico"): the exactly coded 12-bit BF16 GEMV (`bf16x` format and kernel) that `overlay/inkling_pico12/` builds and calls for the dense projections and the LM head; the sources are vendored unmodified in `overlay/inkling_pico12/third_party/pico/` with their licence.- **Andy Shu's `bf16x` reader** is also copied (MIT, with its notice) into `overlay/inkling_wide/csrc/bf16x_format.cuh`, which reads pico12's coded weights in the 17-256-row GEMM, and `overlay/inkling_cert/` compiles pico's head GEMV body from the vendored copy for the exact pass of the certified LM head.- **Tri Dao et al., FlashAttention-2** (algorithm): the online-softmax tiling of the fused relative-bias prefill attention in `overlay/inkling_attn/`.- **SGLang Inkling2 kernels**: the split-KV relative-bias verify kernel that `overlay/inkling_vattn/` routes every batch size to (and copies, with the bias computed per key tile, above 32 rows), the split-KV decode kernel that `overlay/inkling_kv12/` follows with its K / V tile loads replaced, the split softmax kernels that `VCAP_FASTPROBS` calls, the block-verification accept kernel behind `--speculative-use-block-verification`, and the fused loop-controller kernels of sgl-project/sglang PR #51926, already in the image.- **SGLang PR #51681** (DSpark Markov sampler: Philox words that rounded to u == 1) and **SGLang PR #51692** (blockwise rejection precision): their fixes are carried verbatim in `overlay/inkling_rsfix/` (`RSFIX`) until the image has them. The reject-sampler CDF fix and the DFLASH selector no-match fix in the same package are ours.- **Sun et al.**, "Block Verification Accelerates Speculative Decoding" (ICLR 2025): the block-verification algorithm that sampled requests use (`VCAP_BV`, `DFLASH_BV`). Running it under the verify cap (dead drafts as a stopped draft) and its logits-only form in the fused accept are ours.- **Xiao et al.**, StreamingLLM (2023): the attention sink kept by the optional drafter global-attention window (`dwin`, 128 sink tokens by default).- **Lossless float compression by exponent coding** (ZipNN, Hershcovitch et al., 2024; SplitZip) and **Andy Shu's exactly coded 12-bit `bf16x` format**: the inspiration for the packed 12-bit global-layer KV in `overlay/inkling_kv12/` (sign + mantissa byte, 4-bit exponent code, escapes). The KV format, packer and attention kernel are our own code; nothing is copied from these projects.- **Alexey Fateev / Project Maya**, [maya-inkling-mini](https://github.com/alesha-pro/maya-inkling-mini) (MIT): launch and "bytes in flight" notes on Inkling's small per-visit kernels that framed our L2-warming screen (not adopted, see docs/experiments.md).- **FR-Spec** (Zhao et al., ACL 2025, frequency-ranked draft vocabulary) and SGLang's EAGLE `--speculative-token-map`: the idea behind the hot-vocabulary draft. The prompt corpus that ranks the shipped list comes from allenai/WildChat-1M (ODC-BY), OpenAssistant/oasst2 (Apache-2.0), NousResearch/hermes-function-calling-v1 (Apache-2.0), bigcode/self-oss-instruct-sc2-exec-filter-50k (ODC-BY), HuggingFaceH4/ultrachat_200k (MIT), ise-uiuc/Magicoder-OSS-Instruct-75K (MIT), openai/gsm8k (MIT), databricks/databricks-dolly-15k (CC-BY-SA-3.0), EleutherAI/hendrycks_math (MIT), abisee/cnn_dailymail (Apache-2.0), CohereLabs/aya_dataset (Apache-2.0), wikimedia/wikipedia (CC-BY-SA-4.0), juletxara/mgsm (CC-BY-SA-4.0) and llm-jp/oasst2-33k-ja (Apache-2.0); only token frequencies of the model's own outputs are shipped, no prompt text.- **thefullctx**: the KV page-size 16 measurement we screened (not adopted here).- **Christopher Owen** and B12X (MXFP4-CSF): the scale-code format idea behind `overlay/inkling_scodes/` (our implementation, in a modified FlashInfer / CUTLASS mainloop).- **Christopher Owen, spark-ds41f** (Apache-2.0): the packed-BF16 vocabulary projection (b12x patch 0012) whose format we ported to Triton in a screen (not adopted, see docs/experiments.md).- **FlashInfer** (CUTLASS / CuTe DSL grouped GEMMs, the GEMVs) and **CUTLASS**: the kernels the MoE tile choice and the GPU checks run on; since v2.8.4 also the b12x MXFP8 GEMM and quantiser (`mm_mxfp8`, `mxfp8_quantize`) that run the drafter's eligible linears (mx8w), used as shipped.- **NVIDIA** for the DGX Spark platform.- **speedbench** ([knapcio/speedbench](https://github.com/knapcio/speedbench)), our own benchmark, for the headline numbers and the long-context table; its frozen prompt set also feeds the decode table.
Our own earlier recipes contributed ideas reused here: the verify cap with dead-row expert remap (DeepSeek-V4.1recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bitdraft heads (DeepSeek-V4.1), and our spark-tools and speedbench for measurement.
Every lever adopted from someone else's work gets a line here and an entry in the Credit column of the README.123456789101112131415161718192021MIT License
Copyright (c) 2026 Zbigniew Majewski
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354Inkling-2-Mini on one NVIDIA DGX Spark
Repository-authored launch scripts, benchmark scripts and documentation: MIT, see LICENSE.
Third-party code vendored in this repository:- overlay/inkling_pico12/third_party/pico/: kernels/gemv16.cu, kernels/common.cuh, kernels/dsk.h, common/check.h by Andy Shu (github.com/blaesus/dsgb10, formerly dsgx10, `ds41f-4xgx10-switchless/engine/` at commit f2117916, as carried in github.com/Picom-code/pico-dgx-ds4), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_pico12/third_party/pico/LICENSE. Unmodified except a two-line header naming the origin.- overlay/inkling_wide/csrc/bf16x_format.cuh: the `bf16x` reader (layout description, bf16x_raw_off, mad_imm, bf16x_dec, ldg_bf16x) copied from the same pico gemv16.cu (commit f2117916), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_wide/third_party/pico/LICENSE.- overlay/inkling_cert/csrc/cert_ext.cu compiles kernels/gemv16.cu from overlay/inkling_pico12/third_party/pico/ (above) into its own extension; no further copy.
- overlay/inkling_scodes/csrc/scodes_sm120_mma_array.hpp: derived from CUTLASS's SM120 block-scaled grouped-GEMM collective mainloop (NVIDIA CORPORATION & AFFILIATES, BSD-3-Clause, licence text kept in the file header), modified to expand coded scale factors; scodes_group_gemm.cuh reduces FlashInfer 0.7.4's include/flashinfer/gemm/group_gemm_nvfp4_groupwise_sm120.cuh (Apache-2.0, Copyright (c) 2026 FlashInfer team) to the configuration SGLang uses and swaps in that mainloop.- overlay/inkling_kv12/ops.py: the decode / verify attention kernels (`_kv12_partials_np`, `_kv12_partials`) follow SGLang's Inkling2 split-KV decode kernel (`_decode_partials` in sglang.kernels.ops.attention.inkling2_decode_attention_sm90, sgl-project/sglang, Apache-2.0) with the same grid, tile order and online softmax, modified to read packed 12-bit K / V tiles from a side pool.- overlay/inkling_vattn/ops.py: `_inkernel_bias_partials` is the same SGLang `_decode_partials` kernel body (sgl-project/sglang, Apache-2.0), modified to compute the relative-position bias per key tile in-kernel.- overlay/inkling_rsfix/markov.py and overlay/inkling_rsfix/blockwise.py: the changes of sgl-project/sglang pull requests #51681 (dspark markov_sample) and #51692 (dspark blockwise_rejection), applied verbatim to copies of the image's functions (sgl-project/sglang, Apache-2.0). overlay/inkling_rsfix/reject.py and selector.py are copies of SGLang's reject_sampling kernels and DFLASH selector walk (Apache-2.0), modified as described in overlay/inkling_rsfix/README.md.
Third-party model files fetched at run time, not distributed in this repository:- Inkling-2-Mini-DFlash2 (huggingface.co/incoai/Inkling-2-Mini-DFlash2) by incoai, revision 4f9088ea66c21f2b99ed657d1941c306b03e84d2: the draft model (config.json, model.safetensors) and its SGLang compatibility patch (sglang_inkling_dflash2.py). Licensed under the Apache License, Version 2.0; you may not use these files except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. scripts/download.sh fetches them unmodified at that revision; scripts/launch.sh checks their sha256 and runs the patch, unmodified, inside the serving container only. The draft method builds on DFlash (github.com/z-lab/dflash).
The serving engines run from their published container images, pinned by digest in scripts/launch.sh:- SGLang (sgl-project/sglang), lmsysorg/sglang:inkling-2-mini, Apache-2.0.- vLLM (vllm-project/vllm), vllm/vllm-openai:inkling-2-mini, Apache-2.0.bench/decode_table.py reads the prompt file of speedbench (knapcio/speedbench, MIT) from a separate checkout; theprompts themselves are not copied here.
No model weights or container images are distributed. The Inkling-2-Mini weights (thinkingmachines/Inkling-2-Mini)are Apache-2.0 from Thinking Machines Lab; read the model card for the terms that apply to anything you serve.123inkling_n389/n389_fold.py contains a verbatim copy of _sconv_post_kernel from inkling_prologue/_triton.py (knapcio's inkling-2-miniv2.9.3 overlay, MIT; see LICENSE.knapcio-v2.9.3, NOTICE.knapcio-v2.9.3, CREDITS.knapcio-v2.9.3.md, copied unchanged from the S3b-precipe overlay) with an added store branch (FOLD) by the inkling2-spark prefill seat.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307"""inkling_n389: the KV-cache store folded into INKLING_PROLOGUE's SWA K / V kernel (prefill seat, tree n389; enters a package onlyunder n362's RULE rows).
INKLING_N389=1 needs INKLING_PROLOGUE installed first (sitecustomize: after the INKLING_ATTN block)
On a visit the prologue fuses (inkling_prologue._eligible: plain EXTEND, sliding-window layer, >= 2048 rows, ...), K (conv + L2 clip)and V (conv + value norm) are written by n389_fold._sconv_post_kernel FOLD=1 straight into the layer's KV-cache rows, and thebackend's store for that visit is skipped (FlashAttentionBackend.forward_extend gets save_kv_cache=False). Everything else is theserved code. Where the rows go is taken from the served objects, not re-derived: a zero-row probe runs the backend's own write(kv_layers.layer(id).store with the KVWriteLoc forward_extend builds) with memory_pool._set_kv_buffer_impl swapped for a recorder,which captures the K / V buffers and write ids the store_cache JIT would get. The fold copies store_kvcache_kernel's write: row i ->buffer[ids[i]] unless ids[i] == 0 (store_cache's reserved_skip_index). The prologue's value arithmetic is untouched (n389-1:FOLD=0 PTX = served; cache words = served + store, word-checked with failing controls).
Hooks (post-import, inkling_prologue's _hook): Inkling2Attention._forward (outermost: carries the visit's per-pass RadixAttention),Inkling2Attention._prologue (over inkling_prologue's), FlashAttentionBackend.forward_extend. Fail-closed: a folded visit whosestore was not skipped raises N389Fatal (at capture, i.e. at boot, under prefill CUDA graphs). Breakable graphs, CP, MLA,fa_skip_kv_cache, image masks, MXFP8 KV, no sliding-window pool, an unrecognised write route: the stock prologue runs.Reach: STATE folded / skipped / stock / probe_refused counts; one log line at the first fold.v2 (rider2, after the n362h check boot read 'first folded' 0 with the prologue's own fused line 1 / 1): every stock-path decision on avisit the prologue would fuse logs its reason ONCE per distinct reason ('[inkling_n389] stock path: ...', with the values behind it), andthe backend is taken from the forward context, or from forward_batch.attn_backend when the context's object lacks the FA attributes.v3 (rider3, after the n362i check boot logged 'stock path: no FA backend object (context InklingShortConvHybridAttnBackend,forward_batch NoneType)'): Inkling's context backend is the full-attention + short-conv hybrid wrapper; its full-attention child(`full_attn_backend`, the FlashAttentionBackend whose forward_extend runs) is unwrapped and used."""
import contextvarsimport osimport sys
STATE = {"installed": False, "applied": [], "folded": 0, "skipped": 0, "stock": 0, "probe_refused": {}}_VISIT = contextvars.ContextVar("inkling_n389_visit", default=None)_FOLD = contextvars.ContextVar("inkling_n389_fold", default=None)HEAD, KV_HEADS, ROW = 128, 8, 1024BREAKABLE_MODULE = "sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.context"
# sha256[:16] of each function / class source (inkling_pfuse.source_digest) the rider relies on; a changed image or prologue# refuses to install._TARGETS = ( ("srt/layers/attention/flashattention_backend.py", "FlashAttentionBackend.forward_extend", "6238fb0ae1711d3e"), ("srt/mem_cache/memory_pool.py", "KVWriteLoc", "ef256dbc5dfceec7"), ("srt/mem_cache/memory_pool.py", "window_write_locs", "43b941981b5948bd"), ("srt/mem_cache/memory_pool.py", "_set_kv_buffer_impl", "a661c337aeb8fe96"), ("srt/mem_cache/memory_pool.py", "MHATokenToKVPool.set_kv_buffer", "a86c3004aa1a8468"), ("srt/mem_cache/memory_pool.py", "MHATokenToKVPool._store_kv_layer", "fa6c0e1501fdd0cf"), ("srt/mem_cache/swa_memory_pool.py", "SWAKVPool.set_kv_buffer", "3aba049258719cc9"), ("srt/mem_cache/kv/router.py", "KVLayer.store", "9ddade9026ec0874"), ("srt/mem_cache/kv/router.py", "KVLayer._write_loc", "edfd1a0fccac6954"), ("kernels/ops/kvcache/kvcache.py", "store_cache", "3adea6bd9ce54b66"), ("srt/layers/radix_attention.py", "RadixAttention.forward", "71f4956f88f633c6"), ("srt/layers/attention/base_attn_backend.py", "AttentionBackend.forward", "72ff2bff1f7dec26"),)_PROLOGUE = (("conv_post", "c08dc93ba13b051a"), ("_conv_post", "e95c0067cdbc3f85"), ("_eligible", "223f71a04ad16828"), ("make_prologue", "acb9d7690ed6e038"))
class N389Fatal(BaseException): pass
def _log(msg): print(f"[inkling_n389] {msg}", file=sys.stderr, flush=True)
def check_sources(root=None): import inspect
import inkling_prologue from inkling_pfuse import sglang_root, source_digest
root = root or sglang_root() texts = {} for rel, qualname, digest in _TARGETS: path = os.path.join(root, rel) if path not in texts: with open(path, encoding="utf-8") as f: texts[path] = f.read() got = source_digest(texts[path], qualname) if got != digest: raise N389Fatal(f"inkling_n389: {rel}:{qualname} changed (sha {got} != {digest}); refusing to patch") text = inspect.getsource(inkling_prologue) for qualname, digest in _PROLOGUE: got = source_digest(text, qualname) if got != digest: raise N389Fatal(f"inkling_n389: inkling_prologue.{qualname} changed (sha {got} != {digest}); refusing to patch")
def _why(reason, detail=""): """Log a stock-path reason once (the first 12 distinct reasons).""" n = STATE["probe_refused"].get(reason, 0) STATE["probe_refused"][reason] = n + 1 if n == 0 and len(STATE["probe_refused"]) <= 12: _log(f"stock path: {reason}{(' (' + detail + ')') if detail else ''}")
def _refuse(reason, detail=""): _why(reason, detail) return None
def _fa_backend(forward_batch): from sglang.srt.model_executor.forward_context import get_attn_backend
seen = [] for top in (get_attn_backend(), getattr(forward_batch, "attn_backend", None)): # Inkling's InklingShortConvHybridAttnBackend wraps the FA backend as full_attn_backend (every Inkling layer is full attention) for b in (top, getattr(top, "full_attn_backend", None)): if b is not None and hasattr(b, "forward_metadata") and hasattr(b, "use_sliding_window_kv_pool") and hasattr(b, "kv_layers"): return b, type(b).__name__ + ("" if b is top else f" (full_attn_backend of {type(top).__name__})") seen.append(type(b).__name__) return None, "candidates " + " / ".join(seen)
def _route(attn, forward_batch, k, in_breakable): """(k_rows, v_rows, ids, backend) the store_cache JIT would get for this visit, or None (the stock prologue runs).""" import torch from sglang.kernels.ops.kvcache.kvcache import can_use_store_cache from sglang.srt.layers.cp.utils import is_cp_active from sglang.srt.mem_cache import memory_pool as mp
if in_breakable(): return _refuse("breakable graph") backend, bname = _fa_backend(forward_batch) if backend is None: return _refuse("no FA backend object", bname) meta = getattr(backend, "forward_metadata", None) flags = (getattr(backend, "fa_skip_kv_cache", False), getattr(backend, "use_mla", False), getattr(backend, "kv_cache_is_mxfp8", False), meta is None, getattr(meta, "image_token_ranges", None) is not None, is_cp_active(forward_batch)) if any(flags): return _refuse("backend mode", f"{bname}: skip_kv / mla / mxfp8 / no meta / image / cp = {flags}") if not getattr(backend, "use_sliding_window_kv_pool", False) or getattr(meta, "swa_out_cache_loc", None) is None: return _refuse("no sliding-window write ids", f"{bname}: sliding pool {getattr(backend, 'use_sliding_window_kv_pool', None)}, " f"meta {type(meta).__name__}, swa_out_cache_loc {getattr(meta, 'swa_out_cache_loc', None) is not None}") loc_info = mp.KVWriteLoc.for_layer(forward_batch, attn, window_locs=mp.window_write_locs(backend.runner_ids, meta.swa_out_cache_loc)) rec = []
def recorder(kk, vv, k_cache, v_cache, indices, row_dim, store_dtype, device_module, size_limit, alt_stream=None, v_row_dim=None): rec.append((k_cache, v_cache, indices, row_dim, store_dtype, size_limit, v_row_dim))
stub = k.new_empty((0, KV_HEADS, HEAD)) # zero rows: any other write path writes nothing (or raises) orig = mp._set_kv_buffer_impl mp._set_kv_buffer_impl = recorder try: backend.kv_layers.layer(attn.layer_id).store(attn, loc_info, stub, stub, attn.k_scale, attn.v_scale) except Exception as exc: # noqa: BLE001 return _refuse(f"probe raised {type(exc).__name__}", str(exc)[:200]) finally: mp._set_kv_buffer_impl = orig if len(rec) != 1: kvl = backend.kv_layers.layer(attn.layer_id) return _refuse(f"probe reached _set_kv_buffer_impl {len(rec)} times", f"KVLayer plain {kvl.plain}, view {type(kvl.view).__name__}, sub_pool {kvl.route.sub_pool}") kc, vc, ids, row_dim, store_dtype, size_limit, v_row_dim = rec[0] ok = (row_dim == ROW and v_row_dim in (None, ROW) and store_dtype == torch.bfloat16 and can_use_store_cache(2 * ROW, 2 * ROW) and all(t.dtype == torch.bfloat16 and t.dim() == 3 and tuple(t.shape[1:]) == (KV_HEADS, HEAD) and t.stride() == (ROW, HEAD, 1) and t.device == k.device and t.shape[0] == size_limit for t in (kc, vc)) and ids.dim() == 1 and ids.dtype in (torch.int64, torch.int32) and ids.is_contiguous() and ids.shape[0] == k.shape[0] and ids.device == k.device) if not ok: return _refuse("write route not the BF16 NHD store_cache form", f"row {row_dim} / {v_row_dim}, store {store_dtype}, jit {can_use_store_cache(2 * ROW, 2 * ROW)}, k {kc.dtype} {tuple(kc.shape)} " f"{kc.stride()} vs size_limit {size_limit}, ids {ids.dtype} {tuple(ids.shape)} contiguous {ids.is_contiguous()} vs k rows " f"{k.shape[0]}, devices {kc.device} / {ids.device} / {k.device}") return kc.view(-1, ROW), vc.view(-1, ROW), ids, backend
def _conv_post_fold(sconv, x, forward_batch, post, thr, eps, dst, ids, update_sconv_cache, conv_post_fold): """= inkling_prologue._conv_post with the kernel writing the cache rows (same conv-state prepare / update calls).""" meta = sconv._conv_state(forward_batch) cache = sconv._sconv_cache() sconv._prepare_extend_sconv_cache(forward_batch, cache, x, meta.track_conv_indices) conv_post_fold(x, sconv._weight_2d(), cache, meta.precomputed, post, thr, eps, dst, ids) update_sconv_cache(x=x, sconv_cache=cache, cache_indices=meta.cache_indices, has_initial_state=meta.has_initial_state, query_start_loc=meta.query_start_loc)
def make_forward(prev): def _forward(self, hidden_states, positions, forward_batch, *, attn, attn_padded): vt = _VISIT.set((self, attn, forward_batch)) ft = _FOLD.set(None) try: out = prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) fold = _FOLD.get() finally: _FOLD.reset(ft) _VISIT.reset(vt) if fold is not None and not fold["consumed"]: raise N389Fatal("inkling_n389: a folded visit's KV store was not skipped (it would overwrite the folded cache rows)") return out
_forward.__wrapped__ = prev _forward._inkling_n389 = True return _forward
def make_prologue(prev, eligible, update_sconv_cache, conv_post_fold, in_breakable): import torch
def _prologue(self, q, k, v, r, sources, positions, forward_batch): visit = _VISIT.get() if not eligible(self, q, k, v, forward_batch): STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) if visit is None or visit[0] is not self or visit[2] is not forward_batch: _why("no matching visit context", "none" if visit is None else f"self {visit[0] is self}, forward_batch {visit[2] is forward_batch}") STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) dest = _route(visit[1], forward_batch, k, in_breakable) if dest is None: STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) k_rows, v_rows, ids, backend = dest tokens = q.shape[0] kc = self.k_l2_clip _conv_post_fold(self.k_sconv, k, forward_batch, 1, kc.threshold, kc.eps, k_rows, ids, update_sconv_cache, conv_post_fold) _conv_post_fold(self.v_sconv, v, forward_batch, 2, 0.0, self.v_norm.eps, v_rows, ids, update_sconv_cache, conv_post_fold) q = self.q_l2_clip(q.reshape(tokens, self.num_tp_heads, self.head_dim), output_scale=None) r = self.rel_l2_clip(r.reshape(tokens, self.num_tp_heads, self.d_rel), output_scale=None) # K / V for the attention call: never written, never read (attention reads the paged cache; the store is skipped) k_out = torch.empty((tokens, self.num_tp_kv_heads, self.head_dim), dtype=k.dtype, device=k.device) v_out = torch.empty_like(k_out) _FOLD.set({"layer": visit[1], "k": k_out.data_ptr(), "v": v_out.data_ptr(), "backend": backend, "consumed": False}) STATE["folded"] += 1 if STATE["folded"] == 1: _log(f"first folded SWA prologue ({tokens} rows, cache layer {visit[1].layer_id}, ids {ids.dtype})") return q, k_out, v_out, r
_prologue.__wrapped__ = prev _prologue._inkling_n389 = True return _prologue
def make_forward_extend(orig): def forward_extend(self, q, k, v, layer, forward_batch, *args, **kwargs): fold = _FOLD.get() if (fold is not None and not fold["consumed"] and layer is fold["layer"] and k is not None and v is not None and k.data_ptr() == fold["k"] and v.data_ptr() == fold["v"]): if self is not fold["backend"]: raise N389Fatal("inkling_n389: the folded visit's attention runs on another backend than the probed one") if args: args = (False,) + tuple(args[1:]) else: kwargs["save_kv_cache"] = False fold["consumed"] = True STATE["skipped"] += 1 return orig(self, q, k, v, layer, forward_batch, *args, **kwargs)
forward_extend.__wrapped__ = orig forward_extend._inkling_n389 = True return forward_extend
def _patch_attn(mod): import importlib import inspect
import inkling_prologue from sglang.srt.models.inkling_common.kernels.sconv import update_sconv_cache
from .n389_fold import conv_post_fold
cls = getattr(mod, "Inkling2Attention", None) if cls is None or not getattr(cls._prologue, "_inkling_prologue", False): raise N389Fatal("inkling_n389: Inkling2Attention._prologue is not inkling_prologue's (install INKLING_PROLOGUE first)") if getattr(cls._prologue, "_inkling_n389", False): return params = list(inspect.signature(cls._forward).parameters) if params != ["self", "hidden_states", "positions", "forward_batch", "attn", "attn_padded"]: raise N389Fatal(f"inkling_n389: Inkling2Attention._forward signature changed ({params})") in_breakable = getattr(importlib.import_module(BREAKABLE_MODULE), "is_in_breakable_cuda_graph") cls._forward = make_forward(cls._forward) cls._prologue = make_prologue(cls._prologue, inkling_prologue._eligible, update_sconv_cache, conv_post_fold, in_breakable) STATE["applied"] += ["Inkling2Attention._forward", "Inkling2Attention._prologue"]
def _patch_backend(mod): import inspect
cls = getattr(mod, "FlashAttentionBackend", None) if cls is None: raise N389Fatal("inkling_n389: FlashAttentionBackend is missing") if getattr(cls.forward_extend, "_inkling_n389", False): return params = list(inspect.signature(cls.forward_extend).parameters) if params[:7] != ["self", "q", "k", "v", "layer", "forward_batch", "save_kv_cache"]: raise N389Fatal(f"inkling_n389: forward_extend signature changed ({params[:7]})") cls.forward_extend = make_forward_extend(cls.forward_extend) STATE["applied"].append("FlashAttentionBackend.forward_extend")
def install(env=None): if STATE["installed"]: return bool(STATE["applied"]) or None STATE["installed"] = True env = os.environ if env is None else env if env.get("INKLING_N389", "").strip().lower() in ("", "0", "off", "false", "no"): return False import inkling_prologue from inkling_prologue import _hook
if not (inkling_prologue.STATE["installed"] and env.get("INKLING_PROLOGUE", "").strip().lower() not in ("", "0", "off", "false", "no")): raise N389Fatal("inkling_n389: needs INKLING_PROLOGUE installed first") check_sources() _hook.when_imported("sglang.srt.layers.attention.flashattention_backend", _patch_backend) _hook.when_imported("sglang.srt.models.inkling_common.inkling2_attn", _patch_attn) _log("enabled: SWA prefill K / V written into the KV cache by the fused prologue kernel; the visit's store is skipped") return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""n389 (prefill seat): INKLING_PROLOGUE's fused K / V prologue kernel with the KV-cache store folded in.
_sconv_post_kernel below is a verbatim copy of inkling_prologue._triton._sconv_post_kernel (knapcio v2.9.3, MIT; servedfile 24d2e3d9 in the S3b-p recipe overlay) plus five trailing parameters. With FOLD=False (the default) it is the servedkernel: the CPU check requires its PTX to equal the served kernel's for POST 1 and 2 (debug sections stripped). WithFOLD=True only the final store changes: row i of the BF16 result goes to Dst[Loc[i], :] instead of Y[i, :], and rows whoseslot is SKIP (store_cache's reserved_skip_index, the CUDA-graph padding slot 0) are not written. That is the servedstore_kvcache_kernel's write (k_cache[loc[i]] = k[i] unless loc[i] == 0), so the cache words are the same by construction;the value arithmetic is untouched. The helpers (_row_sumsq, rsqrt_approx_f32) are the served module's own functions."""
import torchimport tritonimport triton.language as tl
from inkling_prologue import HEAD, SUM_ORDERfrom inkling_prologue._triton import _row_sumsq, rsqrt_approx_f32
@triton.jitdef _sconv_post_kernel( X, Weight, Cache, Indices, Mask, Cu, Seq, Y, n_rows, SX: tl.constexpr, SW0: tl.constexpr, SW1: tl.constexpr, SC0: tl.constexpr, SC1: tl.constexpr, SC2: tl.constexpr, D: tl.constexpr, W: tl.constexpr, SCALE: tl.constexpr, POST: tl.constexpr, THR, EPS, BM: tl.constexpr, BN: tl.constexpr, PER: tl.constexpr = 1, XOR: tl.constexpr = 0, ORDER: tl.constexpr = 1, SS=None, WRITE_SS: tl.constexpr = False, Loc=None, Dst=None, SD: tl.constexpr = 0, SKIP: tl.constexpr = 0, FOLD: tl.constexpr = False,): rows = tl.program_id(0) * BM + tl.arange(0, BM) col = tl.program_id(1) * BN + tl.arange(0, BN) valid = (rows < n_rows)[:, None] & (col < D)[None, :] rows = tl.minimum(rows, n_rows - 1) seq = tl.load(Seq + rows) bos = tl.load(Cu + seq) slot = tl.load(Indices + seq).to(tl.int64) has_cache = (tl.load(Mask + seq) != 0) & (slot > 0) current = tl.load(X + rows[:, None] * SX + col[None, :], valid, other=0).to(tl.float32) acc = tl.full((BM, BN), 0, tl.float32) for tap in tl.static_range(W): lag = W - 1 - tap src = rows - lag from_x = (src >= bos)[:, None] value = tl.load(X + src[:, None] * SX + col[None, :], valid & from_x, other=0).to(tl.float32) prefix = tl.load( Cache + slot[:, None] * SC0 + (src - bos + W - 1)[:, None] * SC1 + col[None, :] * SC2, valid & ~from_x & has_cache[:, None], other=0, ).to(tl.float32) value = tl.where(from_x, value, prefix) weight = ( tl.load(Weight + col * SW0 + tap * SW1, col < D, other=0).to(X.dtype.element_ty).to(tl.float32) )[None, :] acc = tl.fma(value, weight, acc) acc = acc + current acc = acc * SCALE y = acc.to(tl.bfloat16).to(tl.float32) # the stock conv output (BF16) if ORDER: ss = _row_sumsq(y, BM, POST, PER, XOR) # bit-exact: the CuTe kernels' reduction tree else: ss = tl.sum(y * y, 1) if WRITE_SS: # check only: the FP32 row sum of squares, [n_rows, D // BN] tl.store(SS + rows * (D // BN) + tl.program_id(1), ss, (tl.program_id(0) * BM + tl.arange(0, BM)) < n_rows) if POST == 1: norm = tl.where(ss > 0.0, ss * rsqrt_approx_f32(ss), 0.0) coeff = tl.minimum(1.0, tl.div_rn(tl.full(norm.shape, THR, tl.float32), norm + EPS), propagate_nan=tl.PropagateNan.ALL) # stock minimumf propagates NaN else: coeff = rsqrt_approx_f32(tl.div_rn(ss, tl.full(ss.shape, BN, tl.float32)) + EPS) out = y * coeff[:, None] if FOLD: # n389: the KV-cache row write of store_kvcache_kernel (slot SKIP is the reserved padding slot: not written) dest = tl.load(Loc + rows).to(tl.int64) offs = dest[:, None] * SD + col[None, :] tl.store(Dst + offs, out.to(tl.bfloat16), valid & (dest != SKIP)[:, None]) else: offs = rows[:, None].to(tl.int64) * D + col[None, :] tl.store(Y + offs, out.to(tl.bfloat16), valid)
def conv_post_fold(x, weight, cache, md, post, thr, eps, dst, loc, order=None, skip=0): """inkling_prologue.conv_post with the result written to the KV-cache rows dst[loc[i]] (dst [slots, H*128] BF16, the layer's K or V buffer viewed as rows; loc [T] int64 / int32, the layer's write ids) instead of a fresh [T, H*128] tensor. Same launch as conv_post (grid, BM 16, BN 128, enable_fp_fusion False). Returns None (nothing else is produced). skip = -1 disables the reserved-slot skip (check-only control).""" width = weight.shape[1] per, xor = SUM_ORDER[post] if order is None else order rows, d = x.shape assert dst.dtype == torch.bfloat16 and dst.dim() == 2 and dst.shape[1] == d and dst.stride() == (d, 1), dst.shape assert loc.dim() == 1 and loc.shape[0] == rows and loc.stride(0) == 1 and loc.dtype in (torch.int32, torch.int64) _sconv_post_kernel[(triton.cdiv(rows, 16), triton.cdiv(d, HEAD))]( x, weight, cache, md["safe_idx"], md["cache_mask"], md["cu"], md["si"], dst, rows, x.stride(0), *weight.stride(), *cache.stride(), d, width, (width + 1) ** -0.5, post, float(thr), float(eps), 16, HEAD, per, xor, int(per >= 0), None, False, loc, dst, d, int(skip), True, enable_fp_fusion=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175// SPDX-License-Identifier: Apache-2.0// n351 (inkling2-spark prefill seat, 2026-11-27): exact restructures of n14's nvfp4_quantize_tokens_kernel<2304> (n14_quant.cuh// afdcb38b, served on S2 79d139b0). Every written word is computed by the same image helpers (part_max, block_max_reduce,// quantize_part, store_part, zero_expert_tail, row_expert); only the schedule changes. Variant bits V:// 1 hoist: per token, threads 0..top_k-1 compute (row, expert) of the token's destinations into shared memory before the// amax reduction (whose __syncthreads publishes them); every thread then reads them instead of running its own binary// search per destination (double-buffered by the reduction's parity, as red[] is)// 2 prefetch: the next token's BF16 row is loaded into registers before the current token's quantize + stores// 4 split 2: E = 8 values per thread, 288 threads per token (the image's split for this width is 4: E = 4, 576 threads).// quantize_part keeps the block's pairwise error-sum order for any E (its own comment), part_max / amax are maxima.// V = 0 is a copy of the served kernel (the copy null).#include <sgl_kernel/tensor.h>
#include <sgl_kernel/utils.cuh>
#include "routed_quant_sm120.cuh"#include <cstdint>
namespace sglang::n351_quant {
using namespace sglang::inkling2_routed_quant;using sglang::inkling2_routed_quant_sm120::verify_offsets;using sglang::inkling2_routed_quant_sm120::verify_rows;using sglang::inkling2_routed_quant_sm120::zero_expert_tail;
template <int K, int V>struct Cfg { static constexpr int kSplit = (V & 4) ? 2 : split(K); static constexpr int E = 16 / kSplit; static constexpr int kThreads = (K / 16 * kSplit + 31) / 32 * 32;};
template <int E>__device__ __forceinline__ void load_part(__nv_bfloat16 const* src, float (&v)[E]) { if constexpr (E == 8) { uint4 raw = *reinterpret_cast<uint4 const*>(src); __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(&raw);#pragma unroll for (int i = 0; i < E; ++i) v[i] = __bfloat162float(h[i]); } else { uint2 raw = *reinterpret_cast<uint2 const*>(src); __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(&raw);#pragma unroll for (int i = 0; i < E; ++i) v[i] = __bfloat162float(h[i]); }}
constexpr int kMaxTopK = 16;
template <int K, int V>__global__ void __launch_bounds__(Cfg<K, V>::kThreads) nvfp4_quantize_tokens_kernel( __nv_bfloat16 const* __restrict__ x, int32_t const* __restrict__ src2dst, uint8_t* values, uint8_t* x_scales, float* amax_out, int32_t const* __restrict__ offsets, int32_t tokens, int32_t top_k, int32_t experts) { constexpr int kThreads = Cfg<K, V>::kThreads, kSplit = Cfg<K, V>::kSplit, E = Cfg<K, V>::E; constexpr bool kHoist = V & 1, kPrefetch = V & 2; static_assert(K % 64 == 0 && kSplit > 1); __shared__ int32_t s_offsets[kMaxExperts + 1]; __shared__ float red[2][kThreads / 32]; __shared__ int32_t s_row[2][kMaxTopK]; __shared__ int32_t s_exp[2][kMaxTopK]; device::PDLWaitPrimary<true>(); device::PDLTriggerSecondary<true>(); load_offsets(offsets, experts, s_offsets); int32_t const block = threadIdx.x / kSplit, part = threadIdx.x % kSplit; bool const active = block < K / 16; int32_t const lo = s_offsets[0], hi = s_offsets[experts]; int32_t parity = 0; float nxt[E]; if constexpr (kPrefetch) {#pragma unroll for (int i = 0; i < E; ++i) nxt[i] = 0.0f; if (active && blockIdx.x < tokens) load_part<E>(x + int64_t(blockIdx.x) * K + block * 16 + part * E, nxt); } for (int32_t token = blockIdx.x; token < tokens; token += gridDim.x, parity ^= 1) { float v[E]; if constexpr (kPrefetch) {#pragma unroll for (int i = 0; i < E; ++i) v[i] = nxt[i]; int32_t const t2 = token + gridDim.x; if (active && t2 < tokens) load_part<E>(x + int64_t(t2) * K + block * 16 + part * E, nxt); } else {#pragma unroll for (int i = 0; i < E; ++i) v[i] = 0.0f; if (active) load_part<E>(x + int64_t(token) * K + block * 16 + part * E, v); } if constexpr (kHoist) { if (threadIdx.x < top_k) { int32_t const row = src2dst[int64_t(token) * top_k + threadIdx.x]; bool const live = row >= lo && row < hi; s_row[parity][threadIdx.x] = live ? row : -1; s_exp[parity][threadIdx.x] = live ? row_expert(s_offsets, experts, row) : -1; } } float block_max = part_max<E>(v); float amax = block_max_reduce<kThreads>(block_max, red[parity]); // its __syncthreads also publishes s_row / s_exp uint32_t packed; uint8_t scale; quantize_part<E>(v, amax, block_max, packed, scale); for (int32_t k = 0; k < top_k; ++k) { int32_t row, expert; if constexpr (kHoist) { row = s_row[parity][k]; if (row < 0) continue; expert = s_exp[parity][k]; } else { row = src2dst[int64_t(token) * top_k + k]; if (row < lo || row >= hi) continue; expert = row_expert(s_offsets, experts, row); } if (active) { if (threadIdx.x == 0) amax_out[row] = amax; store_part<E>(values, x_scales, s_offsets, expert, row, block, part, K, packed, scale); } if (row == s_offsets[expert + 1] - 1) zero_expert_tail(s_offsets, expert, x_scales, (K + 63) / 64 * 4); } }}
inline int32_t grid_for(int32_t tokens, int64_t sm_count, int64_t grid) { int64_t const g = grid > 0 ? grid : 4 * sm_count; return static_cast<int32_t>(std::max<int64_t>(1, std::min<int64_t>(tokens, g)));}
// = n14_quant::nvfp4_quantize_tokens<K> (same checks, grid rule and PDL launch) with the variant kernel<K, V>.template <int K, int V>void nvfp4_quantize_tokens( tvm::ffi::TensorView x, tvm::ffi::TensorView src2dst, tvm::ffi::TensorView values, tvm::ffi::TensorView x_scales, tvm::ffi::TensorView amax, tvm::ffi::TensorView offsets, int64_t top_k, int64_t sm_count, int64_t grid) { constexpr int64_t kPart = 16 / Cfg<K, V>::kSplit; auto tokens = host::SymbolicSize{"tokens"}; auto rows = host::SymbolicSize{"routed rows"}; auto scale_rows = host::SymbolicSize{"scale rows"}; auto device = host::SymbolicDevice{}; device.set_options<kDLCUDA>(); int32_t const experts = verify_offsets(offsets, device); host::TensorMatcher({tokens, K}).with_dtype<bf16_t>().with_device(device).ensure_alignment(kPart * 2).verify(x); host::TensorMatcher({rows}).with_dtype<int32_t>().with_device(device).verify(src2dst); host::TensorMatcher({rows, K / 2}).with_dtype<uint8_t>().with_device(device).ensure_alignment(kPart / 2).verify(values); host::TensorMatcher({scale_rows, K / 16}).with_dtype<uint8_t>().with_device(device).verify(x_scales); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(amax); CHECK_HOST(top_k > 0 && top_k <= kMaxTopK) << "top_k must be in 1.." << kMaxTopK << ", got " << top_k; int32_t const num_rows = verify_rows(rows); int32_t const num_tokens = verify_rows(tokens); CHECK_HOST(int64_t{num_tokens} * top_k == num_rows) << "src2dst must hold tokens x top_k rows"; CHECK_HOST(scale_rows.unwrap() >= host::div_ceil(num_rows + 127 * int64_t{experts}, 128) * 128) << "NVFP4 scales need 128-row blocks per expert, got " << scale_rows.unwrap() << " rows"; host::LaunchKernel(grid_for(num_tokens, sm_count, grid), Cfg<K, V>::kThreads, device.unwrap()) .enable_pdl(true)( nvfp4_quantize_tokens_kernel<K, V>, static_cast<__nv_bfloat16 const*>(x.data_ptr()), static_cast<int32_t const*>(src2dst.data_ptr()), static_cast<uint8_t*>(values.data_ptr()), static_cast<uint8_t*>(x_scales.data_ptr()), static_cast<float*>(amax.data_ptr()), static_cast<int32_t const*>(offsets.data_ptr()), num_tokens, static_cast<int32_t>(top_k), experts);}
} // namespace sglang::n351_quant123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216// SPDX-License-Identifier: Apache-2.0// n355-1 (inkling2-spark prefill seat, 2026-11-27): exact restructures of the image's mxfp8_swiglu_quantize_routed<1152>// (routed_quant_sm120.cuh, served on S2 79d139b0 for the MXFP8 layers 20-23). Every written word is computed by the image's// own helpers (capped_swiglu, the BF16 round, mxfp8_half_block) in the same order per element; only the schedule changes.// Variant bits V:// 1 hoist: each thread keeps the expert of its previous row and walks forward (rows only increase), instead of the// 7-step binary search of cute_exponent_offset per row; the result equals row_expert's (largest e with offsets[e] <= row)// 2 prefetch: the next row's 64 B per lane and its gamma are loaded before the current row's arithmetic + stores// 4 pack 4: 288 threads = 4 rows x 72 lanes (9 full warps) per CTA iteration instead of 1 row on 96 threads (72 active);// lane pairs (2i, 2i + 1) stay inside one row (72 is even), so mxfp8_half_block's shfl_xor 1 pairs the same lanes// 8 grid 16 x SMs instead of the image's 4 x SMs (capped by the iteration count)// V = 0 runs mxfp8_swiglu_quantize_copy: the served kernel body verbatim at the served launch (the copy null; SASS-checked). No variant calls launch_dependents (as served: the CuTe SM120 GEMM// reading the outputs does not wait on its predecessor).#include <sgl_kernel/tensor.h>
#include <sgl_kernel/utils.cuh>
#include "routed_quant_sm120.cuh"#include <cstdint>
namespace sglang::n355_quant {
using namespace sglang::inkling2_routed_quant;using sglang::inkling2_routed_quant_sm120::verify_offsets;using sglang::inkling2_routed_quant_sm120::verify_rows;
template <int N, int V>struct Cfg { static constexpr int kLanes = N / 16; static constexpr int kRows = (V & 4) ? 4 : 1; static constexpr int kThreads = (V & 4) ? kLanes * 4 : threads(N); static constexpr int kGridMul = (V & 8) ? 16 : 4; static_assert((V & 4) == 0 || (kLanes % 2 == 0 && kThreads % 32 == 0 && kThreads <= 1024));};
// = cute_exponent_offset with the expert given (scale row of `row` in expert e's 4-row aligned block, MN-major groups of 4).__device__ __forceinline__ int64_t exponent_offset(int32_t row, int32_t group, int32_t const* offsets, int32_t e, int32_t m_padded) { int32_t const scale_row = (offsets[e] + 3 * e) / 4 * 4 + row - offsets[e]; return (int64_t(group / 4) * m_padded + scale_row) * 4 + group % 4;}
// V = 0: the image's kernel body verbatim (copied from routed_quant_sm120.cuh by the kit's generator step; SASS = served).template <int N>__global__ void __launch_bounds__(threads(N)) mxfp8_swiglu_quantize_copy( __nv_bfloat16 const* __restrict__ x, float const* __restrict__ gammas, uint8_t* values, uint8_t* exponents, int32_t const* __restrict__ offsets, int32_t experts, float gate_cap, float up_cap, int32_t m_padded) { static_assert(N % 128 == 0 && N / 16 <= 1024); device::PDLWaitPrimary<true>(); int32_t const block = threadIdx.x; bool const active = block < N / 16; int32_t const lo = offsets[0], hi = offsets[experts]; for (int32_t row = lo + blockIdx.x; row < hi; row += gridDim.x) { float v[16]; if (active) { uint4 const* src = reinterpret_cast<uint4 const*>(x + int64_t(row) * 2 * N + block * 32); uint4 raw[4] = {src[0], src[1], src[2], src[3]}; __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(raw); float gamma = gammas[row];#pragma unroll for (int i = 0; i < 16; ++i) v[i] = __bfloat162float(__float2bfloat16_rn( capped_swiglu(__bfloat162float(h[2 * i]), __bfloat162float(h[2 * i + 1]), gamma, gate_cap, up_cap))); } else {#pragma unroll for (int i = 0; i < 16; ++i) v[i] = 0.0f; } uint4 packed; uint8_t exponent; mxfp8_half_block(v, packed, exponent); if (active) { *reinterpret_cast<uint4*>(values + int64_t(row) * N + block * 16) = packed; if (block % 2 == 0) exponents[sglang::inkling2_routed_quant_sm120::cute_exponent_offset(row, block / 2, offsets, experts, m_padded)] = exponent; } }}
template <int N, int V>__global__ void __launch_bounds__(Cfg<N, V>::kThreads) mxfp8_swiglu_quantize_v( __nv_bfloat16 const* __restrict__ x, float const* __restrict__ gammas, uint8_t* values, uint8_t* exponents, int32_t const* __restrict__ offsets, int32_t experts, float gate_cap, float up_cap, int32_t m_padded) { using C = Cfg<N, V>; static_assert(N % 128 == 0 && N / 16 <= 1024); constexpr bool kHoist = V & 1, kPrefetch = V & 2; device::PDLWaitPrimary<true>(); int32_t const sub = threadIdx.x / C::kLanes; // row slot inside the CTA iteration (0 unless pack) int32_t const block = threadIdx.x - sub * C::kLanes; // lane inside the row: 0..71 (>= 72 only for the 96-thread form) bool const lane_ok = block < N / 16 && sub < C::kRows; int32_t const lo = offsets[0], hi = offsets[experts]; int32_t const step = gridDim.x * C::kRows; int32_t e = 0; bool have_e = false; uint4 raw[4]; float gamma = 0.0f; int32_t row = lo + blockIdx.x * C::kRows + sub; auto load = [&](int32_t r, uint4 (&dst)[4], float& gm) -> bool { // true iff the lane loaded row r (the active predicate) bool const ok = lane_ok && r < hi; if (ok) { uint4 const* src = reinterpret_cast<uint4 const*>(x + int64_t(r) * 2 * N + block * 32); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; gm = gammas[r]; } return ok; }; if constexpr (kPrefetch) load(row, raw, gamma); for (int32_t base = lo + blockIdx.x * C::kRows; base < hi; base += step, row += step) { bool const active = lane_ok && row < hi; uint4 nraw[4]; float ngamma = 0.0f; bool nok = false; // V & 2: whether this lane loaded the next row (= the next iteration's active predicate) if constexpr (kPrefetch) nok = load(row + step, nraw, ngamma); else load(row, raw, gamma); float v[16]; if (active) { __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(raw);#pragma unroll for (int i = 0; i < 16; ++i) v[i] = __bfloat162float(__float2bfloat16_rn( capped_swiglu(__bfloat162float(h[2 * i]), __bfloat162float(h[2 * i + 1]), gamma, gate_cap, up_cap))); } else {#pragma unroll for (int i = 0; i < 16; ++i) v[i] = 0.0f; } uint4 packed; uint8_t exponent; mxfp8_half_block(v, packed, exponent); if (active) { *reinterpret_cast<uint4*>(values + int64_t(row) * N + block * 16) = packed; if (block % 2 == 0) { if constexpr (kHoist) { if (!have_e) { e = row_expert(offsets, experts, row); have_e = true; } while (e + 1 < experts && offsets[e + 1] <= row) ++e; exponents[exponent_offset(row, block / 2, offsets, e, m_padded)] = exponent; } else { exponents[sglang::inkling2_routed_quant_sm120::cute_exponent_offset(row, block / 2, offsets, experts, m_padded)] = exponent; } } } if constexpr (kPrefetch) { if (nok) { // n355-1 re-pin (verify HOLD 16:4x): copy only what this lane loaded; an inactive lane never reads raw / gamma#pragma unroll for (int i = 0; i < 4; ++i) raw[i] = nraw[i]; gamma = ngamma; } } }}
template <int N, int V>void mxfp8_swiglu_quantize( tvm::ffi::TensorView x, tvm::ffi::TensorView gammas, tvm::ffi::TensorView values, tvm::ffi::TensorView exponents, tvm::ffi::TensorView offsets, int64_t m_padded, double gate_cap, double up_cap, int64_t sm_count) { using C = Cfg<N, V>; auto rows = host::SymbolicSize{"routed rows"}; auto device = host::SymbolicDevice{}; device.set_options<kDLCUDA>(); int32_t const experts = verify_offsets(offsets, device); host::TensorMatcher({rows, 2 * N}) // .with_dtype<bf16_t>() .with_device(device) .ensure_alignment(16) .verify(x); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(gammas); host::TensorMatcher({rows, N}) // .with_dtype<uint8_t>() .with_device(device) .ensure_alignment(16) .verify(values); host::TensorMatcher({N / 128, m_padded}).with_dtype<int32_t>().with_device(device).verify(exponents); int32_t const num_rows = verify_rows(rows); CHECK_HOST(m_padded >= (num_rows + 3 * int64_t{experts}) / 4 * 4 && m_padded < std::numeric_limits<int32_t>::max()) << "MXFP8 scales need 4-row aligned experts, got m_padded " << m_padded; int32_t const iters = (num_rows + C::kRows - 1) / C::kRows; int32_t const grid = V == 0 ? grid_size(num_rows, static_cast<int32_t>(sm_count)) // the image's launch for the copy : std::max(1, std::min(iters, C::kGridMul * static_cast<int32_t>(sm_count))); auto* kernel = V == 0 ? mxfp8_swiglu_quantize_copy<N> : mxfp8_swiglu_quantize_v<N, V>; host::LaunchKernel(grid, V == 0 ? threads(N) : C::kThreads, device.unwrap()) .enable_pdl(true)( kernel, static_cast<__nv_bfloat16 const*>(x.data_ptr()), static_cast<float const*>(gammas.data_ptr()), static_cast<uint8_t*>(values.data_ptr()), static_cast<uint8_t*>(exponents.data_ptr()), static_cast<int32_t const*>(offsets.data_ptr()), experts, static_cast<float>(gate_cap), static_cast<float>(up_cap), static_cast<int32_t>(m_padded));}
} // namespace sglang::n355_quant123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Combined loader for the Inkling-2-Mini SGLang overlays (verify cap, draft bytes, kernels, pico12, prefill).Each overlay activates only when its environment switch is set; with none set nothing is imported.A failing overlay stops the process (site.py would otherwise only print a warning and run the stock path)."""import osimport sys
def _on(name): return os.environ.get(name, "").strip().lower() not in ("", "0", "off", "none", "false", "no")
try: if _on("INKLING_KV12") and _on("INKLING_KV12S"): raise RuntimeError("INKLING_KV12S and INKLING_KV12 are mutually exclusive") if _on("INKLING_VERIFY_CAP"): from inkling_vcap import activate activate() if _on("INKLING_DRAFT_BYTES"): import inkling_draftbytes inkling_draftbytes.install() if _on("INKLING_KERNELS"): import inkling_kernels inkling_kernels.install() if _on("INKLING_MOE2"): # after inkling_kernels: per-token tile tables over moe_tiles' _tiles wrapper import inkling_moe2 inkling_moe2.install() if _on("INKLING_SCODES"): # NVFP4 expert scale codes (exact; wraps nvfp4_expert_matmul) import inkling_scodes inkling_scodes.install() if _on("INKLING_PICO12"): # after inkling_kernels: its _project_sources wrapper goes outside qkvr_gemv's import inkling_pico12 inkling_pico12.install() if _on("INKLING_PREFILL"): # last: its _project_sources wrapper (large M only) goes outermost import inkling_prefill inkling_prefill.install() if _on("INKLING_PFUSE"): # prefill glue fusion: Inkling2DecoderLayer._forward, extend only import inkling_pfuse inkling_pfuse.install() if _on("INKLING_PROLOGUE"): # SWA prefill: K conv + L2 clip, V conv + value norm fused (FP32-order class) import inkling_prologue inkling_prologue.install() if _on("INKLING_PFUSE_HOIST"): # prefill loop-bank hoist over pfuse's loop_mix (FP32-order class; needs PFUSE) import inkling_phoist inkling_phoist.install() if _on("INKLING_N329"): # n329: phoist _bank_stats per row (bitwise; wraps the kernel phoist launches; needs PFUSE_HOIST) import inkling_n329 inkling_n329.install() if _on("INKLING_N320_SCONV"): # n320: pfuse sconvres at another exact tile (per-element kernel; needs PFUSE sconvres) import inkling_n320s inkling_n320s.install() if _on("INKLING_N351"): # n351: MoE NVFP4 token quantize through an exact variant (bitwise; n351_quant.cuh mounted at the JIT path) import inkling_n351 inkling_n351.install() if _on("INKLING_N355"): # n355: MXFP8 swiglu quantize through an exact variant (bitwise; n355_quant.cuh mounted at the JIT path) import inkling_n355 inkling_n355.install() if _on("INKLING_N381"): # n381: F2b gate_up on the exact ping-pong tile_k-128 schedule + n360 pass variant (bitwise; unit mounted at the JIT path) import inkling_n381 inkling_n381.install() if _on("INKLING_WIDE"): # after pico12 (reads its packs) and prefill: outermost _project_sources for 17..256 rows import inkling_wide inkling_wide.install() if _on("INKLING_CERT_HEAD"): # after pico12 and wide: outermost lm-head wrapper (<= 16 rows), reads pico's coded head import inkling_cert inkling_cert.install() if _on("INKLING_ATTN") and not _on("INKLING_KV12S"): # fused relative-bias prefill attention (falls back to the stock FA4 path per call) import inkling_attn inkling_attn.install() if _on("INKLING_N389"): # n389: SWA prefill K / V written into the KV cache by the prologue kernel, store skipped (bitwise words; after ATTN) import inkling_n389 inkling_n389.install() if _on("INKLING_KV12S_VATTN_TRACE"): # diagnostic: log compact verify attention arguments from inkling_kv12s.patch import register_vattn_trace register_vattn_trace() if _on("INKLING_VATTN"): # target-verify attention: split-KV relative-bias kernel for all batch sizes import inkling_vattn inkling_vattn.install() if _on("INKLING_KV12"): # after vattn: global-layer KV read from a packed 12-bit side pool (exact) import inkling_kv12 inkling_kv12.install() if _on("INKLING_KV12S"): import inkling_kv12s inkling_kv12s.install() elif _on("INKLING_DSPARK_EAGER_COMMIT"): # diagnostic: KV12S's eager draft commit on stock pools from inkling_kv12s.patch import register_eager_commit_only register_eager_commit_only() if _on("INKLING_NOEXP"): # dead verify rows get no experts (exact for live rows; needs INKLING_VERIFY_CAP) import inkling_noexp inkling_noexp.install() if _on("INKLING_PADX"): # after noexp: CUDA-graph padding rows route to the phantom expert (exact for live rows) import inkling_padx inkling_padx.install() if _on("INKLING_DFLASH_BYTES") or _on("INKLING_DFLASH_CTX8"): # DFlash2 drafter byte cuts / MXFP8 context projections (draft-only; SPEC=dflash2) import inkling_dfbytes inkling_dfbytes.install() if _on("INKLING_DFLASH_FUSED_ACCEPT"): # DFLASH sampled accept from the logits with sparse q (same law) import inkling_dfaccept inkling_dfaccept.install() if _on("INKLING_DFLASH_PCOPY"): # DFLASH: prompt-copy forced drafts (draft proposals only; after the verify cap) import inkling_pcopy inkling_pcopy.install() if _on("INKLING_DFLASH_PREFIX_TAIL") or _on("INKLING_DFLASH_TAIL_SNAPSHOTS"): # DFLASH draft ring on prefix hits: (A) re-prefill the last N input tokens, (B) restore a prompt-end draft window snapshot import inkling_dftail inkling_dftail.install() if _on("INKLING_PROMPT_TOUCH"): # cache LRU order only: refresh a finished request's prompt-end checkpoint import inkling_ptouch inkling_ptouch.install() if _on("INKLING_RSFIX"): # exact residual / bonus lane rule (+ SGLang PR #51681 / #51692 fixes) import inkling_rsfix inkling_rsfix.install() import inkling_mixdraft inkling_mixdraft.install()except BaseException as exc: # noqa: BLE001 sys.stderr.write("[inkling-overlay pid=%d] FATAL at startup: %r\n" % (os.getpid(), exc)) sys.stderr.flush() os._exit(78)1{"format": "inkling-vcap-policy/df1+features", "stride": 8, "bands": [1, 2, 4, 8, 16, 24, 48], "features": ["slot", "m"], "band_calib": true, "edges": {"m": [0.3, 0.5, 0.7, 0.8, 0.9, 0.95, 0.98, 0.995], "gap": [0.05, 0.2, 0.5, 0.8], "tail": [0.02, 0.05, 0.1, 0.2, 0.35, 0.5], "mt": [0.3, 0.5, 0.7, 0.8, 0.9, 0.95, 0.98, 0.995], "prev": [0, 1, 2, 3, 5]}, "calib": [0.22088353413654618, 0.42931547619047616, 0.5957719410634209, 0.7105911330049262, 0.8072033898305084, 0.8927097661623109, 0.9281767955801105, 0.9748237663645518, 0.9914183937823834, 0.20374707259953162, 0.35695067264573993, 0.5987558320373251, 0.7172774869109948, 0.849493487698987, 0.9152854511970534, 0.9483333333333334, 0.9796893667861409, 0.9907634307257305, 0.25510204081632654, 0.3706521739130435, 0.5776135163674763, 0.7540229885057471, 0.8003597122302158, 0.8963133640552995, 0.9285714285714286, 0.9541547277936963, 0.9937175043327556, 0.23893805309734514, 0.3590504451038576, 0.604225352112676, 0.7002652519893899, 0.8445378151260504, 0.9169054441260746, 0.9634703196347032, 0.9759229534510433, 0.9949773982923155, 0.2919254658385093, 0.4781021897810219, 0.617741935483871, 0.7413793103448276, 0.8442622950819673, 0.9003436426116839, 0.9461756373937678, 0.9594813614262561, 0.9913444893248702, 0.2949640287769784, 0.48283261802575106, 0.5744274809160306, 0.756198347107438, 0.832258064516129, 0.8847583643122676, 0.9173553719008265, 0.9738219895287958, 0.9919001012487344, 0.3202614379084967, 0.5054347826086957, 0.6256038647342995, 0.7551867219917012, 0.8707482993197279, 0.9148148148148149, 0.9696969696969697, 0.9781312127236581, 0.9932324840764332, 0.23809523809523808, 0.40709459459459457, 0.5735694822888283, 0.7096774193548387, 0.8013856812933026, 0.8816568047337278, 0.9347181008902077, 0.9728601252609603, 0.9902029391182645, 0.22527472527472528, 0.35283018867924526, 0.5811258278145696, 0.7030075187969925, 0.8431952662721893, 0.8947368421052632, 0.9456521739130435, 0.9761904761904762, 0.9918099918099919, 0.2835820895522388, 0.3805104408352668, 0.5648148148148148, 0.755868544600939, 0.7795918367346939, 0.9, 0.9298245614035088, 0.9546827794561934, 0.993361782835467, 0.27102803738317754, 0.3624161073825503, 0.5847953216374269, 0.7027027027027027, 0.8552036199095022, 0.9202127659574468, 0.9605911330049262, 0.9686411149825784, 0.9955257270693513, 0.3291139240506329, 0.468, 0.61, 0.736, 0.8242424242424242, 0.8904109589041096, 0.9451219512195121, 0.9490909090909091, 0.9905482041587902, 0.34782608695652173, 0.48214285714285715, 0.6, 0.7181818181818181, 0.8111888111888111, 0.9186991869918699, 0.9096774193548387, 0.98, 0.988905325443787, 0.33766233766233766, 0.48066298342541436, 0.6032608695652174, 0.7946428571428571, 0.837037037037037, 0.9111111111111111, 0.9802631578947368, 0.9726027397260274, 0.9920353982300885, 0.23809523809523808, 0.40709459459459457, 0.5735694822888283, 0.7096774193548387, 0.8013856812933026, 0.8816568047337278, 0.9347181008902077, 0.9728601252609603, 0.9902029391182645, 0.22527472527472528, 0.35283018867924526, 0.5811258278145696, 0.7030075187969925, 0.8431952662721893, 0.8947368421052632, 0.9456521739130435, 0.9761904761904762, 0.9918099918099919, 0.2835820895522388, 0.3805104408352668, 0.5648148148148148, 0.755868544600939, 0.7795918367346939, 0.9, 0.9298245614035088, 0.9546827794561934, 0.993361782835467, 0.27102803738317754, 0.3624161073825503, 0.5847953216374269, 0.7027027027027027, 0.8552036199095022, 0.9202127659574468, 0.9605911330049262, 0.9686411149825784, 0.9955257270693513, 0.3291139240506329, 0.468, 0.61, 0.736, 0.8242424242424242, 0.8904109589041096, 0.9451219512195121, 0.9490909090909091, 0.9905482041587902, 0.34782608695652173, 0.48214285714285715, 0.6, 0.7181818181818181, 0.8111888111888111, 0.9186991869918699, 0.9096774193548387, 0.98, 0.988905325443787, 0.33766233766233766, 0.48066298342541436, 0.6032608695652174, 0.7946428571428571, 0.837037037037037, 0.9111111111111111, 0.9802631578947368, 0.9726027397260274, 0.9920353982300885, 0.23809523809523808, 0.40709459459459457, 0.5735694822888283, 0.7096774193548387, 0.8013856812933026, 0.8816568047337278, 0.9347181008902077, 0.9728601252609603, 0.9902029391182645, 0.22527472527472528, 0.35283018867924526, 0.5811258278145696, 0.7030075187969925, 0.8431952662721893, 0.8947368421052632, 0.9456521739130435, 0.9761904761904762, 0.9918099918099919, 0.2835820895522388, 0.3805104408352668, 0.5648148148148148, 0.755868544600939, 0.7795918367346939, 0.9, 0.9298245614035088, 0.9546827794561934, 0.993361782835467, 0.27102803738317754, 0.3624161073825503, 0.5847953216374269, 0.7027027027027027, 0.8552036199095022, 0.9202127659574468, 0.9605911330049262, 0.9686411149825784, 0.9955257270693513, 0.3291139240506329, 0.468, 0.61, 0.736, 0.8242424242424242, 0.8904109589041096, 0.9451219512195121, 0.9490909090909091, 0.9905482041587902, 0.34782608695652173, 0.48214285714285715, 0.6, 0.7181818181818181, 0.8111888111888111, 0.9186991869918699, 0.9096774193548387, 0.98, 0.988905325443787, 0.33766233766233766, 0.48066298342541436, 0.6032608695652174, 0.7946428571428571, 0.837037037037037, 0.9111111111111111, 0.9802631578947368, 0.9726027397260274, 0.9920353982300885, 0.23809523809523808, 0.40709459459459457, 0.5735694822888283, 0.7096774193548387, 0.8013856812933026, 0.8816568047337278, 0.9347181008902077, 0.9728601252609603, 0.9902029391182645, 0.22527472527472528, 0.35283018867924526, 0.5811258278145696, 0.7030075187969925, 0.8431952662721893, 0.8947368421052632, 0.9456521739130435, 0.9761904761904762, 0.9918099918099919, 0.2835820895522388, 0.3805104408352668, 0.5648148148148148, 0.755868544600939, 0.7795918367346939, 0.9, 0.9298245614035088, 0.9546827794561934, 0.993361782835467, 0.27102803738317754, 0.3624161073825503, 0.5847953216374269, 0.7027027027027027, 0.8552036199095022, 0.9202127659574468, 0.9605911330049262, 0.9686411149825784, 0.9955257270693513, 0.3291139240506329, 0.468, 0.61, 0.736, 0.8242424242424242, 0.8904109589041096, 0.9451219512195121, 0.9490909090909091, 0.9905482041587902, 0.34782608695652173, 0.48214285714285715, 0.6, 0.7181818181818181, 0.8111888111888111, 0.9186991869918699, 0.9096774193548387, 0.98, 0.988905325443787, 0.33766233766233766, 0.48066298342541436, 0.6032608695652174, 0.7946428571428571, 0.837037037037037, 0.9111111111111111, 0.9802631578947368, 0.9726027397260274, 0.9920353982300885, 0.23809523809523808, 0.40709459459459457, 0.5735694822888283, 0.7096774193548387, 0.8013856812933026, 0.8816568047337278, 0.9347181008902077, 0.9728601252609603, 0.9902029391182645, 0.22527472527472528, 0.35283018867924526, 0.5811258278145696, 0.7030075187969925, 0.8431952662721893, 0.8947368421052632, 0.9456521739130435, 0.9761904761904762, 0.9918099918099919, 0.2835820895522388, 0.3805104408352668, 0.5648148148148148, 0.755868544600939, 0.7795918367346939, 0.9, 0.9298245614035088, 0.9546827794561934, 0.993361782835467, 0.27102803738317754, 0.3624161073825503, 0.5847953216374269, 0.7027027027027027, 0.8552036199095022, 0.9202127659574468, 0.9605911330049262, 0.9686411149825784, 0.9955257270693513, 0.3291139240506329, 0.468, 0.61, 0.736, 0.8242424242424242, 0.8904109589041096, 0.9451219512195121, 0.9490909090909091, 0.9905482041587902, 0.34782608695652173, 0.48214285714285715, 0.6, 0.7181818181818181, 0.8111888111888111, 0.9186991869918699, 0.9096774193548387, 0.98, 0.988905325443787, 0.33766233766233766, 0.48066298342541436, 0.6032608695652174, 0.7946428571428571, 0.837037037037037, 0.9111111111111111, 0.9802631578947368, 0.9726027397260274, 0.9920353982300885, 0.23809523809523808, 0.40709459459459457, 0.5735694822888283, 0.7096774193548387, 0.8013856812933026, 0.8816568047337278, 0.9347181008902077, 0.9728601252609603, 0.9902029391182645, 0.22527472527472528, 0.35283018867924526, 0.5811258278145696, 0.7030075187969925, 0.8431952662721893, 0.8947368421052632, 0.9456521739130435, 0.9761904761904762, 0.9918099918099919, 0.2835820895522388, 0.3805104408352668, 0.5648148148148148, 0.755868544600939, 0.7795918367346939, 0.9, 0.9298245614035088, 0.9546827794561934, 0.993361782835467, 0.27102803738317754, 0.3624161073825503, 0.5847953216374269, 0.7027027027027027, 0.8552036199095022, 0.9202127659574468, 0.9605911330049262, 0.9686411149825784, 0.9955257270693513, 0.3291139240506329, 0.468, 0.61, 0.736, 0.8242424242424242, 0.8904109589041096, 0.9451219512195121, 0.9490909090909091, 0.9905482041587902, 0.34782608695652173, 0.48214285714285715, 0.6, 0.7181818181818181, 0.8111888111888111, 0.9186991869918699, 0.9096774193548387, 0.98, 0.988905325443787, 0.33766233766233766, 0.48066298342541436, 0.6032608695652174, 0.7946428571428571, 0.837037037037037, 0.9111111111111111, 0.9802631578947368, 0.9726027397260274, 0.9920353982300885, 0.4802258190803872, 0.5855907123491184, 0.6627248473213047, 0.7083394867859051, 0.7673981416442389, 0.8291139840096211, 0.885485104850898, 0.9243624690413745, 0.9879811143203554, 0.45093440219601766, 0.5232786570593904, 0.607661289343705, 0.6495342773306009, 0.6972758904005532, 0.7581497742447533, 0.8183736473546686, 0.8742642510818929, 0.9715999540068807, 0.4468339149356967, 0.5106912505705081, 0.5865187385189676, 0.6187025032498809, 0.6708171091256463, 0.725044097639737, 0.7810773454034404, 0.8401251891054751, 0.9592186927034748, 0.3832007668601319, 0.481234373180555, 0.5653071051282903, 0.6039427573327721, 0.6463318489728858, 0.672144879963235, 0.750107696016955, 0.823007609969873, 0.9485102833774601, 0.42676439655465437, 0.46911897602089153, 0.5501329869431223, 0.5863151729651664, 0.6483662488514973, 0.664490478845993, 0.7181766749600573, 0.8267821261527637, 0.9489415092270292, 0.40414712126007857, 0.4300521328591911, 0.518659013411751, 0.553188201248941, 0.5783525965248669, 0.6401514581503208, 0.7059024303873664, 0.7851663741753302, 0.9451390765560068, 0.42797128096454135, 0.4384533013767665, 0.5086661694741602, 0.5402954165966664, 0.570955867235186, 0.6387332604166541, 0.6950615640970516, 0.7935046489563086, 0.941899443504606, 0.4802258190803872, 0.5855907123491184, 0.6627248473213047, 0.7083394867859051, 0.7673981416442389, 0.8291139840096211, 0.885485104850898, 0.9243624690413745, 0.9879811143203554, 0.45093440219601766, 0.5232786570593904, 0.607661289343705, 0.6495342773306009, 0.6972758904005532, 0.7581497742447533, 0.8183736473546686, 0.8742642510818929, 0.9715999540068807, 0.4468339149356967, 0.5106912505705081, 0.5865187385189676, 0.6187025032498809, 0.6708171091256463, 0.725044097639737, 0.7810773454034404, 0.8401251891054751, 0.9592186927034748, 0.3832007668601319, 0.481234373180555, 0.5653071051282903, 0.6039427573327721, 0.6463318489728858, 0.672144879963235, 0.750107696016955, 0.823007609969873, 0.9485102833774601, 0.42676439655465437, 0.46911897602089153, 0.5501329869431223, 0.5863151729651664, 0.6483662488514973, 0.664490478845993, 0.7181766749600573, 0.8267821261527637, 0.9489415092270292, 0.40414712126007857, 0.4300521328591911, 0.518659013411751, 0.553188201248941, 0.5783525965248669, 0.6401514581503208, 0.7059024303873664, 0.7851663741753302, 0.9451390765560068, 0.42797128096454135, 0.4384533013767665, 0.5086661694741602, 0.5402954165966664, 0.570955867235186, 0.6387332604166541, 0.6950615640970516, 0.7935046489563086, 0.941899443504606, 0.4802258190803872, 0.5855907123491184, 0.6627248473213047, 0.7083394867859051, 0.7673981416442389, 0.8291139840096211, 0.885485104850898, 0.9243624690413745, 0.9879811143203554, 0.45093440219601766, 0.5232786570593904, 0.607661289343705, 0.6495342773306009, 0.6972758904005532, 0.7581497742447533, 0.8183736473546686, 0.8742642510818929, 0.9715999540068807, 0.4468339149356967, 0.5106912505705081, 0.5865187385189676, 0.6187025032498809, 0.6708171091256463, 0.725044097639737, 0.7810773454034404, 0.8401251891054751, 0.9592186927034748, 0.3832007668601319, 0.481234373180555, 0.5653071051282903, 0.6039427573327721, 0.6463318489728858, 0.672144879963235, 0.750107696016955, 0.823007609969873, 0.9485102833774601, 0.42676439655465437, 0.46911897602089153, 0.5501329869431223, 0.5863151729651664, 0.6483662488514973, 0.664490478845993, 0.7181766749600573, 0.8267821261527637, 0.9489415092270292, 0.40414712126007857, 0.4300521328591911, 0.518659013411751, 0.553188201248941, 0.5783525965248669, 0.6401514581503208, 0.7059024303873664, 0.7851663741753302, 0.9451390765560068, 0.42797128096454135, 0.4384533013767665, 0.5086661694741602, 0.5402954165966664, 0.570955867235186, 0.6387332604166541, 0.6950615640970516, 0.7935046489563086, 0.941899443504606, 0.4802258190803872, 0.5855907123491184, 0.6627248473213047, 0.7083394867859051, 0.7673981416442389, 0.8291139840096211, 0.885485104850898, 0.9243624690413745, 0.9879811143203554, 0.45093440219601766, 0.5232786570593904, 0.607661289343705, 0.6495342773306009, 0.6972758904005532, 0.7581497742447533, 0.8183736473546686, 0.8742642510818929, 0.9715999540068807, 0.4468339149356967, 0.5106912505705081, 0.5865187385189676, 0.6187025032498809, 0.6708171091256463, 0.725044097639737, 0.7810773454034404, 0.8401251891054751, 0.9592186927034748, 0.3832007668601319, 0.481234373180555, 0.5653071051282903, 0.6039427573327721, 0.6463318489728858, 0.672144879963235, 0.750107696016955, 0.823007609969873, 0.9485102833774601, 0.42676439655465437, 0.46911897602089153, 0.5501329869431223, 0.5863151729651664, 0.6483662488514973, 0.664490478845993, 0.7181766749600573, 0.8267821261527637, 0.9489415092270292, 0.40414712126007857, 0.4300521328591911, 0.518659013411751, 0.553188201248941, 0.5783525965248669, 0.6401514581503208, 0.7059024303873664, 0.7851663741753302, 0.9451390765560068, 0.42797128096454135, 0.4384533013767665, 0.5086661694741602, 0.5402954165966664, 0.570955867235186, 0.6387332604166541, 0.6950615640970516, 0.7935046489563086, 0.941899443504606, 0.4802258190803872, 0.5855907123491184, 0.6627248473213047, 0.7083394867859051, 0.7673981416442389, 0.8291139840096211, 0.885485104850898, 0.9243624690413745, 0.9879811143203554, 0.45093440219601766, 0.5232786570593904, 0.607661289343705, 0.6495342773306009, 0.6972758904005532, 0.7581497742447533, 0.8183736473546686, 0.8742642510818929, 0.9715999540068807, 0.4468339149356967, 0.5106912505705081, 0.5865187385189676, 0.6187025032498809, 0.6708171091256463, 0.725044097639737, 0.7810773454034404, 0.8401251891054751, 0.9592186927034748, 0.3832007668601319, 0.481234373180555, 0.5653071051282903, 0.6039427573327721, 0.6463318489728858, 0.672144879963235, 0.750107696016955, 0.823007609969873, 0.9485102833774601, 0.42676439655465437, 0.46911897602089153, 0.5501329869431223, 0.5863151729651664, 0.6483662488514973, 0.664490478845993, 0.7181766749600573, 0.8267821261527637, 0.9489415092270292, 0.40414712126007857, 0.4300521328591911, 0.518659013411751, 0.553188201248941, 0.5783525965248669, 0.6401514581503208, 0.7059024303873664, 0.7851663741753302, 0.9451390765560068, 0.42797128096454135, 0.4384533013767665, 0.5086661694741602, 0.5402954165966664, 0.570955867235186, 0.6387332604166541, 0.6950615640970516, 0.7935046489563086, 0.941899443504606, 0.4802258190803872, 0.5855907123491184, 0.6627248473213047, 0.7083394867859051, 0.7673981416442389, 0.8291139840096211, 0.885485104850898, 0.9243624690413745, 0.9879811143203554, 0.45093440219601766, 0.5232786570593904, 0.607661289343705, 0.6495342773306009, 0.6972758904005532, 0.7581497742447533, 0.8183736473546686, 0.8742642510818929, 0.9715999540068807, 0.4468339149356967, 0.5106912505705081, 0.5865187385189676, 0.6187025032498809, 0.6708171091256463, 0.725044097639737, 0.7810773454034404, 0.8401251891054751, 0.9592186927034748, 0.3832007668601319, 0.481234373180555, 0.5653071051282903, 0.6039427573327721, 0.6463318489728858, 0.672144879963235, 0.750107696016955, 0.823007609969873, 0.9485102833774601, 0.42676439655465437, 0.46911897602089153, 0.5501329869431223, 0.5863151729651664, 0.6483662488514973, 0.664490478845993, 0.7181766749600573, 0.8267821261527637, 0.9489415092270292, 0.40414712126007857, 0.4300521328591911, 0.518659013411751, 0.553188201248941, 0.5783525965248669, 0.6401514581503208, 0.7059024303873664, 0.7851663741753302, 0.9451390765560068, 0.42797128096454135, 0.4384533013767665, 0.5086661694741602, 0.5402954165966664, 0.570955867235186, 0.6387332604166541, 0.6950615640970516, 0.7935046489563086, 0.941899443504606, 0.4802258190803872, 0.5855907123491184, 0.6627248473213047, 0.7083394867859051, 0.7673981416442389, 0.8291139840096211, 0.885485104850898, 0.9243624690413745, 0.9879811143203554, 0.45093440219601766, 0.5232786570593904, 0.607661289343705, 0.6495342773306009, 0.6972758904005532, 0.7581497742447533, 0.8183736473546686, 0.8742642510818929, 0.9715999540068807, 0.4468339149356967, 0.5106912505705081, 0.5865187385189676, 0.6187025032498809, 0.6708171091256463, 0.725044097639737, 0.7810773454034404, 0.8401251891054751, 0.9592186927034748, 0.3832007668601319, 0.481234373180555, 0.5653071051282903, 0.6039427573327721, 0.6463318489728858, 0.672144879963235, 0.750107696016955, 0.823007609969873, 0.9485102833774601, 0.42676439655465437, 0.46911897602089153, 0.5501329869431223, 0.5863151729651664, 0.6483662488514973, 0.664490478845993, 0.7181766749600573, 0.8267821261527637, 0.9489415092270292, 0.40414712126007857, 0.4300521328591911, 0.518659013411751, 0.553188201248941, 0.5783525965248669, 0.6401514581503208, 0.7059024303873664, 0.7851663741753302, 0.9451390765560068, 0.42797128096454135, 0.4384533013767665, 0.5086661694741602, 0.5402954165966664, 0.570955867235186, 0.6387332604166541, 0.6950615640970516, 0.7935046489563086, 0.941899443504606], "theta": [[1, 0.09498087165248209], [2, 0.12243877370748137], [4, 0.20346261035667612], [8, 0.2622813633311557], [16, 0.5618441892859829], [24, 0.7242670271814892]], "theta_x": [[1, 0, 0, 0.09498087165248209], [1, 0, 2, 0.0572], [1, 1, 0, 0.09498087165248209], [2, 0, 0, 0.09498087165248209], [2, 1, 0, 0.12243877370748137], [4, 0, 0, 0.20346261035667612], [4, 1, 0, 0.20346261035667612], [8, 0, 0, 0.2622813633311557], [8, 1, 0, 0.0], [16, 0, 0, 0.5618441892859829], [16, 1, 0, 0.0], [24, 1, 0, 0.0], [48, 1, 0, 0.0]], "ctx_edges": [16384, 65536], "rowcost": {"1": [4.097364292888137, 3.21575018970647, 2.7293579086908677, 2.376344459589287, 2.0953389052689944, 1.8685887360159914, 1.6779982542840293], "2": [2.904315362678283, 2.033107729678425, 1.612193160013325, 1.3805476030193526, 1.1412675032625421, 0.9746121995345051, 0.8149632799875539], "4": [1.5811469098423414, 1.0437488202771443, 0.8174825015848364, 0.6610072559926901, 0.5455456003849378, 0.4605102228876234, 0.3925326758752063], "8": [1.1272158884151946, 0.6851266855294836, 0.508302117389736, 0.40050183017505747, 0.3256106075418518, 0.2621108193533909, 0.22124713031122684], "16": [0.4123823206085167, 0.2395650534916857, 0.17030613966631086, 0.13024499348454693, 0.10229840607620427, 0.08330105003823787, 0.06755254781669796], "24": [0.37076008364142793, 0.19955072641017174, 0.13996915772539473, 0.10892169684615309, 0.08722777171101082, 0.06935845663473332, 0.05700626799869273]}, "bsmax": 48, "source": {"dirs": ["../../data/steplog/SLDF2-s06-1124T1318"], "draft_ms": {}, "beta": {"1": {"beta": 0.018856679261243202, "intercept": 18.666400224085095, "r2": 0.8997860559867149, "n": 10110}, "2": {"beta": 0.0180716391981113, "intercept": 25.45274691979146, "r2": 0.8653132453372483, "n": 187}, "4": {"beta": 0.013988786336405294, "intercept": 40.21355214554565, "r2": 0.03643342356997337, "n": 1571}, "8": {"beta": 0.016626417380724363, "intercept": 43.63445941322922, "r2": 0.8749980574554489, "n": 2397}, "16": {"beta": 0.009723945437442275, "intercept": 89.42130334700101, "r2": 0.45049132293543603, "n": 451}, "24": {"beta": 0.015397694685328943, "intercept": 86.92289775972661, "r2": 0.17274131652250835, "n": 2116}}, "beta_scale": 1.0, "row_ms": 0.0, "derivation": "per-mode fit on the full-width capture: greedy and sampled requests priced separately per batch band; sampled requests verify full width from band 8 up; greedy bs1 at >= 64K tokens of context priced 0.0572 (from a long-context capture, draft step 3.33 ms)", "n387": "R1: band 1 re-fit on folded.npz (13761 kept request-steps, 7395 at bs 1): survival table (replay346 refit_calib), shipped theta / theta_x; bands >= 2 from df-b2.json"}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""inkling_n320s: pfuse's sconvres launch at another exact tile (prefill seat, tree n320; enters the package only on an n320-1 KEEP).
INKLING_N320_SCONV=BM,BN,WARPS (needs INKLING_PFUSE with sconvres): inkling_pfuse.mix.sconv_residual is replaced by the same function (served mix.py 1e93144f lines 203-222, checks and arguments unchanged) launching _triton_sconv._sconv_residual_kernel at (BM, BN, WARPS) instead of (16, 128, 4). The kernel is per-element, so every tile is bitwise (n320-1 measures and checks it).Reach: STATE["calls"]; one log line at the first call."""import loggingimport os
import torch
STATE = {"installed": False, "calls": 0, "tile": None}_log = logging.getLogger(__name__)
def _tile(): bm, bn, warps = (int(x) for x in os.environ["INKLING_N320_SCONV"].split(",")) assert bm in (8, 16, 32, 64, 128) and bn in (32, 64, 128, 256, 512) and warps in (1, 2, 4, 8, 16), (bm, bn, warps) return bm, bn, warps
def _patch(mix): import inspect
import triton
served = mix.sconv_residual if getattr(served, "_n320s", False): return src = inspect.getsource(served) assert "(triton.cdiv(rows, 16), triton.cdiv(width, 128))" in src and "partial is not None, 16, 128," in src, "served launch changed" bm, bn, warps = _tile()
def sconv_residual(x, weight, cache, metadata, attention, partial): from inkling_pfuse import _triton_sconv
rows, width = x.shape kernel_width = weight.shape[1] assert rows >= mix.sconv_min_rows() and x.stride(-1) == 1 and x.dtype == torch.bfloat16 assert cache.ndim == 3 and cache.shape[1:] == (kernel_width - 1, width) for t in (attention, partial): assert t is None or (t.shape == x.shape and t.dtype == torch.bfloat16 and t.is_contiguous()) out = torch.empty_like(attention) _triton_sconv._sconv_residual_kernel[(triton.cdiv(rows, bm), triton.cdiv(width, bn))]( x, weight, cache, metadata["safe_idx"], metadata["cache_mask"], metadata["cu"], metadata["si"], attention, partial if partial is not None else attention, out, rows, x.stride(0), *weight.stride(), *cache.stride(), width, kernel_width, (kernel_width + 1) ** -0.5, partial is not None, bm, bn, num_warps=warps, enable_fp_fusion=False, ) STATE["calls"] += 1 if STATE["calls"] == 1: _log.warning("n320s: sconv_residual at tile (%d, %d, %d warps)", bm, bn, warps) return out
sconv_residual._n320s = True mix.sconv_residual = sconv_residual STATE.update(installed=True, tile=(bm, bn, warps))
def install(): from inkling_pfuse import _hook
_tile() # fail at start-up on a malformed switch _hook.when_imported("inkling_pfuse.mix", _patch)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""inkling_n329: phoist.prepare's _bank_stats_kernel launched per row (prefill seat, tree n329; n329-1 KEEP, kit 849ac214).
INKLING_N329=1 (needs INKLING_PFUSE_HOIST): inkling_phoist.phoist_triton._bank_stats_kernel is wrapped so that a launch on grid (T, 12) runs n329_rows._bank_stats_rows_kernel on grid (T,) with the same arguments (the 12 layer-sides looped inside the program, the served body unchanged); any other grid goes to the served kernel. Bitwise vs served (n329-1: BP / BI / MR word-equal, eager + graph, 1-bit control found); -4.73 / -3.98 ms per attention / mlp call at 12,288 rows (17.4 ms per 12K forward).Reach: STATE counts launches routed each way; the first routed launch logs one line ('n329: per-row _bank_stats').CUDA graphs: the wrapper only picks the kernel object at launch time (host side); a captured graph holds the per-row launch."""import loggingimport os
STATE = {"installed": False, "rows": 0, "served": 0}_log = logging.getLogger(__name__)
class _RowsGrid: """Stands in for the served JITFunction at `kernel[grid](...)` call sites."""
def __init__(self, served, rows): self.served = served self.rows = rows
def __getitem__(self, grid): if isinstance(grid, tuple) and len(grid) == 2 and grid[1] == 12: STATE["rows"] += 1 if STATE["rows"] == 1: _log.warning("n329: per-row _bank_stats (grid (%s, 12) -> (%s,))", grid[0], grid[0]) return self.rows[(grid[0],)] STATE["served"] += 1 return self.served[grid]
def __getattr__(self, name): return getattr(self.served, name)
def _patch(kt): if os.environ.get("N329_CONTROL", "").strip() == "1": # failing control for check boots: mrstd x (1 + 2^-18) from . import n329_rows_ctl as n329_rows _log.warning("n329: CONTROL kernel (mrstd x (1 + 2^-18)), outputs must differ") else: from . import n329_rows
kernel = kt._bank_stats_kernel if isinstance(kernel, _RowsGrid): return rows = n329_rows._bank_stats_rows_kernel if list(kernel.arg_names) != list(rows.arg_names): raise RuntimeError(f"n329: served _bank_stats_kernel arguments changed: {kernel.arg_names} vs {rows.arg_names}") kt._bank_stats_kernel = _RowsGrid(kernel, rows) STATE["installed"] = True
def install(): from inkling_phoist import _hook
_hook.when_imported("inkling_phoist.phoist_triton", _patch)12345678910111213141516171819202122232425262728293031"""n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with thelayer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers."""import tritonimport triton.language as tlfrom triton.language.extra import libdevice # noqa: F401from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401
@triton.jitdef _bank_stats_rows_kernel( B, QM, BP, BI, MR, T, eps_res, eps_ctrl, LS_Q_STRIDE, Q_OFF, NM: tl.constexpr, QP: tl.constexpr, QPM: tl.constexpr, NBP: tl.constexpr, D: tl.constexpr, CH: tl.constexpr,): """Program (row, ls): bank weights of the NM queries of layer-side ls (queries at QM + ls * LS_Q_STRIDE + Q_OFF) and the message rstd, exactly as _loop_stats_kernel computes them. BP [NLS, T, NBP, QP], BI [NLS, T, QP], MR [NLS, T, QPM].""" row = tl.program_id(0).to(tl.int64) for ls32 in tl.range(0, 12): # n329: the 12 layer-sides of the served grid's second axis, in one program ls = ls32.to(tl.int64) qm = tl.arange(0, QPM) Q = QM + ls * LS_Q_STRIDE + Q_OFF bprob, binv = _row_weights(B, B[0], Q, row, eps_res, NM, QPM, NBP, False, True, D, CH) tl.store(BP + (ls * T + row) * (NBP * QP) + tl.arange(0, NBP)[:, None] * QP + qm[None, :], bprob) tl.store(BI + (ls * T + row) * QP + qm, binv) mss = tl.zeros([QPM, CH], tl.float32) for c in tl.static_range(D // CH): m = _row_combine(B, B[0], bprob, binv, row, c, QPM, NBP, False, D, CH) mss = mss + m * m mrstd = libdevice.rsqrt(tl.div_rn(tl.sum(mss, 1), tl.full([QPM], D, tl.float32)) + eps_ctrl) tl.store(MR + (ls * T + row) * QPM + qm, mrstd)
12345678910111213141516171819202122232425262728293031"""n329 FAILING-CONTROL copy (N329_CONTROL=1, check boots only): mrstd x (1 + 2^-18). n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with thelayer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers."""import tritonimport triton.language as tlfrom triton.language.extra import libdevice # noqa: F401from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401
@triton.jitdef _bank_stats_rows_kernel( B, QM, BP, BI, MR, T, eps_res, eps_ctrl, LS_Q_STRIDE, Q_OFF, NM: tl.constexpr, QP: tl.constexpr, QPM: tl.constexpr, NBP: tl.constexpr, D: tl.constexpr, CH: tl.constexpr,): """Program (row, ls): bank weights of the NM queries of layer-side ls (queries at QM + ls * LS_Q_STRIDE + Q_OFF) and the message rstd, exactly as _loop_stats_kernel computes them. BP [NLS, T, NBP, QP], BI [NLS, T, QP], MR [NLS, T, QPM].""" row = tl.program_id(0).to(tl.int64) for ls32 in tl.range(0, 12): # n329: the 12 layer-sides of the served grid's second axis, in one program ls = ls32.to(tl.int64) qm = tl.arange(0, QPM) Q = QM + ls * LS_Q_STRIDE + Q_OFF bprob, binv = _row_weights(B, B[0], Q, row, eps_res, NM, QPM, NBP, False, True, D, CH) tl.store(BP + (ls * T + row) * (NBP * QP) + tl.arange(0, NBP)[:, None] * QP + qm[None, :], bprob) tl.store(BI + (ls * T + row) * QP + qm, binv) mss = tl.zeros([QPM, CH], tl.float32) for c in tl.static_range(D // CH): m = _row_combine(B, B[0], bprob, binv, row, c, QPM, NBP, False, D, CH) mss = mss + m * m mrstd = libdevice.rsqrt(tl.div_rn(tl.sum(mss, 1), tl.full([QPM], D, tl.float32)) + eps_ctrl) tl.store(MR + (ls * T + row) * QPM + qm, mrstd * 1.000003814697265625) # N329_CONTROL: x (1 + 2^-18), wrong by design
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""inkling_n351: the MoE NVFP4 token quantize through an exact n351 variant (prefill seat, tree n351; enters the n320 package onlyon an n351-1 KEEP).
INKLING_N351=V[,GRID] V in 1 / 3 / 5 / 7 (n351_quant.cuh variant bits), GRID optional (0 = the served 4 x SMs rule): sglang.srt.models.inkling_common.n14_moe.nvfp4_token_quantize is wrapped so that width-2304 calls run n351_quant::nvfp4_quantize_tokens<2304, V>; any other width falls through to n14's served kernel. Every written word comes from the same image helpers (n351-1 checks it bitwise vs served). Needs n351_quant.cuh mounted at the JIT csrc path inkling2/n351_quant.cuh (manifest EXTRA_DOCKER).Reach: STATE counts routed / fallen-through calls; one log line at the first routed call."""import loggingimport os
STATE = {"installed": False, "routed": 0, "served": 0, "variant": None, "grid": None}_log = logging.getLogger(__name__)
def _cfg(): parts = [int(x) for x in os.environ["INKLING_N351"].split(",")] v, g = parts[0], (parts[1] if len(parts) > 1 else 0) assert v in (1, 3, 5, 7) and 0 <= g <= 4096 and len(parts) <= 2, parts return v, g
def _module(v): from sglang.kernels.jit.utils import cache_once, load_jit # noqa: F401
key = f"q{v}" if key not in _MODS: _MODS[key] = load_jit("n351_quant", f"2304_{v}", cuda_files=["inkling2/n351_quant.cuh"], cuda_wrappers=[(key, f"n351_quant::nvfp4_quantize_tokens<2304, {v}>")]) return getattr(_MODS[key], key)
_MODS = {}
def _patch(n14): served = n14.nvfp4_token_quantize if getattr(served, "_n351", False): return import inspect assert list(inspect.signature(served).parameters) == ["x", "src2dst", "top_k", "offsets", "grid"], "served signature changed" v, g = _cfg()
def nvfp4_token_quantize(x, src2dst, top_k, offsets, grid=None): if x.shape[1] != 2304: STATE["served"] += 1 return served(x, src2dst, top_k, offsets, grid=grid) from sglang.kernels.ops.moe import inkling2_experts_sm120 as ex
values, scales, amax = ex._nvfp4_outputs(rows=src2dst.numel(), width=2304, experts=offsets.numel() - 1, device=x.device) if src2dst.numel(): _module(v)(x, src2dst, values, scales, amax, offsets, top_k, n14._sm_count(x.device), g) STATE["routed"] += 1 if STATE["routed"] == 1: _log.warning("n351: NVFP4 token quantize through variant %d (grid %s)", v, g or "4 x SMs") return values, scales, amax
nvfp4_token_quantize._n351 = True n14.nvfp4_token_quantize = nvfp4_token_quantize STATE.update(installed=True, variant=v, grid=g)
def install(): from inkling_pfuse import _hook
_cfg() # fail at start-up on a malformed switch _hook.when_imported("sglang.srt.models.inkling_common.n14_moe", _patch)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""inkling_n355: the MXFP8 swiglu-quant (layers 20-23) through an exact n355 variant (prefill seat, tree n355; enters a packageonly on an n355-1 KEEP).
INKLING_N355=V V in 1 / 4 / 5 / 8 / 9 / 13 / 15 (n355_quant.cuh variant bits): the image's sglang.kernels.ops.moe.inkling2_experts_sm120.mxfp8_routed_swiglu_quantize is wrapped so that width-1152 calls with >= MIN_ROWS routed rows (prefill chunks) run n355_quant::mxfp8_swiglu_quantize<1152, V>; smaller calls (decode / verify) and other widths fall through to the served kernel. Every written word comes from the image's own helpers (n355-1 checks it bitwise vs served). Callers (n14_moe.forward_sm120 and inkling2_moe's own forward) look the function up on the module at call time. Needs n355_quant.cuh mounted at the JIT csrc path inkling2/n355_quant.cuh (manifest EXTRA_DOCKER).Reach: STATE counts routed / fallen-through calls; one log line at the first routed call."""import loggingimport os
STATE = {"installed": False, "routed": 0, "served": 0, "variant": None}MIN_ROWS = 4096 # routed rows = tokens x top_k: 512 tokens, the n14 prefill thresholdVARIANTS = (1, 4, 5, 8, 9, 13, 15)_log = logging.getLogger(__name__)_MODS = {}
def _cfg(): v = int(os.environ["INKLING_N355"]) assert v in VARIANTS, v return v
def _module(v): from sglang.kernels.jit.utils import load_jit
key = f"q{v}" if key not in _MODS: _MODS[key] = load_jit("n355_quant", f"1152_{v}", cuda_files=["inkling2/n355_quant.cuh"], cuda_wrappers=[(key, f"n355_quant::mxfp8_swiglu_quantize<1152, {v}>")]) return getattr(_MODS[key], key)
def _patch(ex): served = ex.mxfp8_routed_swiglu_quantize if getattr(served, "_n355", False): return import inspect assert list(inspect.signature(served).parameters) == ["acc", "gammas", "offsets", "gate_cap", "up_cap"], "served signature changed" v = _cfg()
def mxfp8_routed_swiglu_quantize(acc, gammas, offsets, gate_cap, up_cap): rows, width = acc.shape[0], acc.shape[1] // 2 if width != 1152 or rows < MIN_ROWS: STATE["served"] += 1 return served(acc=acc, gammas=gammas, offsets=offsets, gate_cap=gate_cap, up_cap=up_cap) import torch
values, scales, m_padded = ex._mxfp8_outputs(rows=rows, width=width, experts=offsets.numel() - 1, device=acc.device) _module(v)(acc, gammas, values.view(torch.uint8), scales, offsets, m_padded, gate_cap, up_cap, ex._sm_count(acc.device)) STATE["routed"] += 1 if STATE["routed"] == 1: _log.warning("n355: MXFP8 swiglu quantize through variant %d", v) return values, scales.t()
mxfp8_routed_swiglu_quantize._n355 = True ex.mxfp8_routed_swiglu_quantize = mxfp8_routed_swiglu_quantize STATE.update(installed=True, variant=v)
def install(): from inkling_pfuse import _hook
_cfg() # fail at start-up on a malformed switch _hook.when_imported("sglang.kernels.ops.moe.inkling2_experts_sm120", _patch)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""inkling_n381: F2b gate_up through the exact n381 schedule (prefill seat, tree n381; enters a package only under its RULE rows).
INKLING_N381=pv=P,tb=T,raster=R sglang.srt.models.inkling_common.n52_moe.gate_up_chunks is wrapped so that every call runs n381c_band::gate_up_chunks(..., pv) from the unit n381c_band_k128_pp1 (n381c_band.cuh = n360-1's pass-variant source + n381-2's ping-pong / tile_k-128 edits): the F2 chunk GEMM on the stock CUTLASS ptr-array ping-pong schedule at tile_k 128 (n381-2 KEEP: word-exact), the chunk pass through n360 variant P (0 = the served pass), T bands per chunk and raster R (0 AlongM, 1 AlongN). Omitted keys keep the served values (pv 0, n52's TB, the call's raster). Same allocations and arguments as served (n360 rider pattern); n52's forward_sm120 looks gate_up_chunks up as a module global at call time. Needs n381c_band.cuh mounted at the JIT csrc path inkling2/n381c_band.cuh (manifest EXTRA_DOCKER).Replaces inkling_n360 in a package (one unit carries both); install() refuses to run if inkling_n360 already wrapped the function.Reach: STATE counts calls; one log line at the first call."""import loggingimport os
STATE = {"installed": False, "routed": 0, "cfg": None}_log = logging.getLogger(__name__)_MODS = {}TILE_K, PP = 128, 1
def _cfg(): cfg = {"pv": 0, "tb": None, "raster": None} raw = os.environ["INKLING_N381"].strip() for item in filter(None, (x.strip() for x in raw.split(","))): key, _, val = item.partition("=") assert key in cfg and val, f"INKLING_N381 item {item!r}" cfg[key] = int(val) assert cfg["pv"] in (0, 1, 2, 3, 4), cfg assert cfg["tb"] is None or 1 <= cfg["tb"] <= 64, cfg assert cfg["raster"] in (None, 0, 1), cfg return cfg
def _module(lean): import flashinfer from sglang.kernels.jit.utils import load_jit
if lean not in _MODS: data = os.path.join(os.path.dirname(flashinfer.__file__), "data") _MODS[lean] = load_jit( f"n381c_band_k{TILE_K}_pp{PP}", str(int(lean)), cuda_files=["inkling2/n381c_band.cuh"], cuda_wrappers=[("gate_up_chunks", "n381c_band::gate_up_chunks")], extra_include_paths=[f"{data}/cutlass/include", f"{data}/cutlass/tools/util/include"], extra_cuda_cflags=["-DCUTLASS_ENABLE_GDC_FOR_SM100=1", "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED", f"-DN52_LEAN={int(lean)}", f"-DN381_TILE_K={TILE_K}", f"-DN381_PP={PP}"]) return _MODS[lean]
def _patch(n52): served = n52.gate_up_chunks if getattr(served, "_n381", False): return if getattr(served, "_n360", False): raise RuntimeError("inkling_n381: inkling_n360 already wraps gate_up_chunks; the n381 unit carries n360's pass variants (use one)") import inspect want = ["layer", "values", "scales", "amax", "gammas", "offsets", "mode", "raster", "tb", "lean"] assert list(inspect.signature(served).parameters) == want, "served signature changed" cfg = _cfg()
def gate_up_chunks(layer, values, scales, amax, gammas, offsets, mode=2, raster=0, tb=None, lean=None): """= n52_moe.gate_up_chunks on the n381 schedule (same allocations, same arguments; tb / raster / pv from INKLING_N381).""" import torch from sglang.kernels.ops.moe import inkling2_experts_sm120 as ex
w = layer.w13_weight experts, n, kp = w.shape rows = values.shape[0] lean = n52.LEAN if lean is None else int(lean) n52._lean_ok(layer, lean) qv, qs, qa = ex._nvfp4_outputs(rows=rows, width=n // 2, experts=experts, device=values.device) if rows: dev = values.device d = torch.empty((rows, n), dtype=torch.bfloat16, device=dev) iw = torch.empty(8 << 20, dtype=torch.uint8, device=dev) fw = torch.empty(4 << 20, dtype=torch.uint8, device=dev) r = int(raster) if cfg["raster"] is None else cfg["raster"] t = int(n52.TB if tb is None else tb) if cfg["tb"] is None else cfg["tb"] _module(lean).gate_up_chunks( values, w, scales, layer.w13_scale.view(torch.uint8).view(experts, n, kp // 8), offsets, amax, layer.w13_amax, layer.w13_outer_scale_denominator, gammas, d, qv, qs, qa, iw, fw, float(layer.gate_cap), float(layer.up_cap), int(mode), r, t, n52._sm_count(dev), int(cfg["pv"])) STATE["routed"] += 1 if STATE["routed"] == 1: _log.warning("n381: F2b gate_up on the ping-pong tile_k-%d schedule, pass variant %d, tb %s, raster %s", TILE_K, cfg["pv"], cfg["tb"], cfg["raster"]) return qv, qs, qa
gate_up_chunks._n381 = True n52.gate_up_chunks = gate_up_chunks STATE.update(installed=True, cfg=cfg)
def install(): from inkling_pfuse import _hook
_cfg() # fail at start-up on a malformed switch _hook.when_imported("sglang.srt.models.inkling_common.n52_moe", _patch)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Credits
- **Thinking Machines Lab** for Inkling-2-Mini, its NVFP4 / MXFP8 checkpoint and the bundled DSpark draft model (`mtp.safetensors`) ([model card](https://huggingface.co/thinkingmachines/Inkling-2-Mini), [announcement](https://thinkingmachines.ai/news/inkling-2-mini/), Apache-2.0).- **incoai**, [Inkling-2-Mini-DFlash2](https://huggingface.co/incoai/Inkling-2-Mini-DFlash2) (Apache-2.0): the DFlash2 draft model that is this recipe's default drafter, and its SGLang compatibility patch (`sglang_inkling_dflash2.py`), both used as published at revision `4f9088ea`, fetched by `scripts/download.sh` and not distributed here. The drafter byte cuts, the DFLASH verify-width cap, the certified head on DFLASH steps and the selector fix are ours, on top of it.- **The DFlash authors** ([z-lab/dflash](https://github.com/z-lab/dflash)): block-diffusion drafting for speculative decoding, the method behind the DFlash2 drafter, and SGLang's DFLASH worker that serves it.- **SGLang** project for the Inkling-2-Mini support, the `lmsysorg/sglang:inkling-2-mini` image and the [Inkling-2-Mini cookbook](https://docs.sglang.io/cookbook/autoregressive/ThinkingMachines/Inkling-2-Mini), whose DGX Spark DSpark cell (TP1/EP1, FA4, page 128, 8 draft tokens, the four `SGLANG_OPT_*` switches, `MAX_JOBS=4`, the `inkling` / `inkling2` parsers) is the base of the default profile.- **vLLM** project for the Inkling-2-Mini support (vllm-project/vllm #69027, #69028, #69039 by Woosuk Kwon and contributors), the `vllm/vllm-openai:inkling-2-mini` image and the [vLLM recipe](https://recipes.vllm.ai/thinkingmachines/Inkling-2-Mini) behind the alternative profile.- **Tech2Wild (tonyd2wild)**, [Inkling-2-Mini-NVFP4-DGX-Spark](https://github.com/tonyd2wild/Inkling-2-Mini-NVFP4-DGX-Spark): the first single-Spark vLLM recipe for this model. Reused here: the vLLM tier settings (`--gpu-memory-utilization 0.80` at 262K context with tool calling on), the hybrid KV-pool block model and the FP8-KV long-context tier with its memory budget (74 GiB of FP8 KV at 1M), the GB10 page-cache trap, and the advice to keep MemAvailable above ~6 GiB.- **thefullctx**, [inkling-2-mini-sglang-dgx-spark](https://github.com/thefullctx/inkling-2-mini-sglang-dgx-spark) and [inkling-2-mini-vllm-dgx-spark](https://github.com/thefullctx/inkling-2-mini-vllm-dgx-spark): the first published SGLang vs vLLM head-to-head on one Spark (vLLM slightly ahead on short c1 decode, SGLang ~2x on long prefill, faster long-context decode and much lower memory use), which set the arms of our comparison.- **Thien Tran (gau-nernst)**, vLLM PR #69168 (small-M GEMMs for Inkling's looped core): the split-K router / conv-projection and controller re-tiling we screened (not adopted, flat in serving).- **sxuff**, [inkling-2-mini-spark](https://github.com/sxuff/inkling-2-mini-spark) (Apache-2.0): the vLLM + DSpark + INT8 draft recipe and benchmark used for the same-harness comparison, and the `--safetensors-load-strategy eager` result (127 -> 45 s) that prompted our one-pass checkpoint load with SGLang's own flag.- **0xSero**, [inference-optimisation skill](https://github.com/sybil-solutions/inference-optimisation-skill) (MIT): the method behind sxuff's eager-load finding.- **tie-pilot-qxw**, [dspark-markov-walk](https://github.com/tie-pilot-qxw/dspark-markov-walk) (MIT), and [vLLM PR #62958](https://github.com/vllm-project/vllm/pull/62958): the one-kernel DSpark Markov walk that inspired `rnnhoist`. Our projection split is an independent implementation.- **nick398** on the [NVIDIA developer forum thread](https://forums.developer.nvidia.com/t/inkling-2-mini/389745): the first FP8-KV serving notes for this model (vLLM `--kv-cache-dtype fp8` on an RTX 5090: about half the KV memory per token, described there as a quality trade-off).- **Andy Shu (@blaesus)**, [dsgb10](https://github.com/blaesus/dsgb10) (formerly dsgx10, MIT), as carried in [Picom-code/pico-dgx-ds4](https://github.com/Picom-code/pico-dgx-ds4) ("pico"): the exactly coded 12-bit BF16 GEMV (`bf16x` format and kernel) that `overlay/inkling_pico12/` builds and calls for the dense projections and the LM head; the sources are vendored unmodified in `overlay/inkling_pico12/third_party/pico/` with their licence.- **Andy Shu's `bf16x` reader** is also copied (MIT, with its notice) into `overlay/inkling_wide/csrc/bf16x_format.cuh`, which reads pico12's coded weights in the 17-256-row GEMM, and `overlay/inkling_cert/` compiles pico's head GEMV body from the vendored copy for the exact pass of the certified LM head.- **Tri Dao et al., FlashAttention-2** (algorithm): the online-softmax tiling of the fused relative-bias prefill attention in `overlay/inkling_attn/`.- **SGLang Inkling2 kernels**: the split-KV relative-bias verify kernel that `overlay/inkling_vattn/` routes every batch size to (and copies, with the bias computed per key tile, above 32 rows), the split-KV decode kernel that `overlay/inkling_kv12/` follows with its K / V tile loads replaced, the split softmax kernels that `VCAP_FASTPROBS` calls, the block-verification accept kernel behind `--speculative-use-block-verification`, and the fused loop-controller kernels of sgl-project/sglang PR #51926, already in the image.- **SGLang PR #51681** (DSpark Markov sampler: Philox words that rounded to u == 1) and **SGLang PR #51692** (blockwise rejection precision): their fixes are carried verbatim in `overlay/inkling_rsfix/` (`RSFIX`) until the image has them. The reject-sampler CDF fix and the DFLASH selector no-match fix in the same package are ours.- **Sun et al.**, "Block Verification Accelerates Speculative Decoding" (ICLR 2025): the block-verification algorithm that sampled requests use (`VCAP_BV`, `DFLASH_BV`). Running it under the verify cap (dead drafts as a stopped draft) and its logits-only form in the fused accept are ours.- **Xiao et al.**, StreamingLLM (2023): the attention sink kept by the optional drafter global-attention window (`dwin`, 128 sink tokens by default).- **Lossless float compression by exponent coding** (ZipNN, Hershcovitch et al., 2024; SplitZip) and **Andy Shu's exactly coded 12-bit `bf16x` format**: the inspiration for the packed 12-bit global-layer KV in `overlay/inkling_kv12/` (sign + mantissa byte, 4-bit exponent code, escapes). The KV format, packer and attention kernel are our own code; nothing is copied from these projects.- **Alexey Fateev / Project Maya**, [maya-inkling-mini](https://github.com/alesha-pro/maya-inkling-mini) (MIT): launch and "bytes in flight" notes on Inkling's small per-visit kernels that framed our L2-warming screen (not adopted, see docs/experiments.md).- **FR-Spec** (Zhao et al., ACL 2025, frequency-ranked draft vocabulary) and SGLang's EAGLE `--speculative-token-map`: the idea behind the hot-vocabulary draft. The prompt corpus that ranks the shipped list comes from allenai/WildChat-1M (ODC-BY), OpenAssistant/oasst2 (Apache-2.0), NousResearch/hermes-function-calling-v1 (Apache-2.0), bigcode/self-oss-instruct-sc2-exec-filter-50k (ODC-BY), HuggingFaceH4/ultrachat_200k (MIT), ise-uiuc/Magicoder-OSS-Instruct-75K (MIT), openai/gsm8k (MIT), databricks/databricks-dolly-15k (CC-BY-SA-3.0), EleutherAI/hendrycks_math (MIT), abisee/cnn_dailymail (Apache-2.0), CohereLabs/aya_dataset (Apache-2.0), wikimedia/wikipedia (CC-BY-SA-4.0), juletxara/mgsm (CC-BY-SA-4.0) and llm-jp/oasst2-33k-ja (Apache-2.0); only token frequencies of the model's own outputs are shipped, no prompt text.- **thefullctx**: the KV page-size 16 measurement we screened (not adopted here).- **Christopher Owen** and B12X (MXFP4-CSF): the scale-code format idea behind `overlay/inkling_scodes/` (our implementation, in a modified FlashInfer / CUTLASS mainloop).- **Christopher Owen, spark-ds41f** (Apache-2.0): the packed-BF16 vocabulary projection (b12x patch 0012) whose format we ported to Triton in a screen (not adopted, see docs/experiments.md).- **FlashInfer** (CUTLASS / CuTe DSL grouped GEMMs, the GEMVs) and **CUTLASS**: the kernels the MoE tile choice and the GPU checks run on; since v2.8.4 also the b12x MXFP8 GEMM and quantiser (`mm_mxfp8`, `mxfp8_quantize`) that run the drafter's eligible linears (mx8w), used as shipped.- **NVIDIA** for the DGX Spark platform.- **speedbench** ([knapcio/speedbench](https://github.com/knapcio/speedbench)), our own benchmark, for the headline numbers and the long-context table; its frozen prompt set also feeds the decode table.
Our own earlier recipes contributed ideas reused here: the verify cap with dead-row expert remap (DeepSeek-V4.1recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bitdraft heads (DeepSeek-V4.1), and our spark-tools and speedbench for measurement.
Every lever adopted from someone else's work gets a line here and an entry in the Credit column of the README.123456789101112131415161718192021MIT License
Copyright (c) 2026 Zbigniew Majewski
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354Inkling-2-Mini on one NVIDIA DGX Spark
Repository-authored launch scripts, benchmark scripts and documentation: MIT, see LICENSE.
Third-party code vendored in this repository:- overlay/inkling_pico12/third_party/pico/: kernels/gemv16.cu, kernels/common.cuh, kernels/dsk.h, common/check.h by Andy Shu (github.com/blaesus/dsgb10, formerly dsgx10, `ds41f-4xgx10-switchless/engine/` at commit f2117916, as carried in github.com/Picom-code/pico-dgx-ds4), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_pico12/third_party/pico/LICENSE. Unmodified except a two-line header naming the origin.- overlay/inkling_wide/csrc/bf16x_format.cuh: the `bf16x` reader (layout description, bf16x_raw_off, mad_imm, bf16x_dec, ldg_bf16x) copied from the same pico gemv16.cu (commit f2117916), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_wide/third_party/pico/LICENSE.- overlay/inkling_cert/csrc/cert_ext.cu compiles kernels/gemv16.cu from overlay/inkling_pico12/third_party/pico/ (above) into its own extension; no further copy.
- overlay/inkling_scodes/csrc/scodes_sm120_mma_array.hpp: derived from CUTLASS's SM120 block-scaled grouped-GEMM collective mainloop (NVIDIA CORPORATION & AFFILIATES, BSD-3-Clause, licence text kept in the file header), modified to expand coded scale factors; scodes_group_gemm.cuh reduces FlashInfer 0.7.4's include/flashinfer/gemm/group_gemm_nvfp4_groupwise_sm120.cuh (Apache-2.0, Copyright (c) 2026 FlashInfer team) to the configuration SGLang uses and swaps in that mainloop.- overlay/inkling_kv12/ops.py: the decode / verify attention kernels (`_kv12_partials_np`, `_kv12_partials`) follow SGLang's Inkling2 split-KV decode kernel (`_decode_partials` in sglang.kernels.ops.attention.inkling2_decode_attention_sm90, sgl-project/sglang, Apache-2.0) with the same grid, tile order and online softmax, modified to read packed 12-bit K / V tiles from a side pool.- overlay/inkling_vattn/ops.py: `_inkernel_bias_partials` is the same SGLang `_decode_partials` kernel body (sgl-project/sglang, Apache-2.0), modified to compute the relative-position bias per key tile in-kernel.- overlay/inkling_rsfix/markov.py and overlay/inkling_rsfix/blockwise.py: the changes of sgl-project/sglang pull requests #51681 (dspark markov_sample) and #51692 (dspark blockwise_rejection), applied verbatim to copies of the image's functions (sgl-project/sglang, Apache-2.0). overlay/inkling_rsfix/reject.py and selector.py are copies of SGLang's reject_sampling kernels and DFLASH selector walk (Apache-2.0), modified as described in overlay/inkling_rsfix/README.md.
Third-party model files fetched at run time, not distributed in this repository:- Inkling-2-Mini-DFlash2 (huggingface.co/incoai/Inkling-2-Mini-DFlash2) by incoai, revision 4f9088ea66c21f2b99ed657d1941c306b03e84d2: the draft model (config.json, model.safetensors) and its SGLang compatibility patch (sglang_inkling_dflash2.py). Licensed under the Apache License, Version 2.0; you may not use these files except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. scripts/download.sh fetches them unmodified at that revision; scripts/launch.sh checks their sha256 and runs the patch, unmodified, inside the serving container only. The draft method builds on DFlash (github.com/z-lab/dflash).
The serving engines run from their published container images, pinned by digest in scripts/launch.sh:- SGLang (sgl-project/sglang), lmsysorg/sglang:inkling-2-mini, Apache-2.0.- vLLM (vllm-project/vllm), vllm/vllm-openai:inkling-2-mini, Apache-2.0.bench/decode_table.py reads the prompt file of speedbench (knapcio/speedbench, MIT) from a separate checkout; theprompts themselves are not copied here.
No model weights or container images are distributed. The Inkling-2-Mini weights (thinkingmachines/Inkling-2-Mini)are Apache-2.0 from Thinking Machines Lab; read the model card for the terms that apply to anything you serve.123inkling_n389/n389_fold.py contains a verbatim copy of _sconv_post_kernel from inkling_prologue/_triton.py (knapcio's inkling-2-miniv2.9.3 overlay, MIT; see LICENSE.knapcio-v2.9.3, NOTICE.knapcio-v2.9.3, CREDITS.knapcio-v2.9.3.md, copied unchanged from the S3b-precipe overlay) with an added store branch (FOLD) by the inkling2-spark prefill seat.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307"""inkling_n389: the KV-cache store folded into INKLING_PROLOGUE's SWA K / V kernel (prefill seat, tree n389; enters a package onlyunder n362's RULE rows).
INKLING_N389=1 needs INKLING_PROLOGUE installed first (sitecustomize: after the INKLING_ATTN block)
On a visit the prologue fuses (inkling_prologue._eligible: plain EXTEND, sliding-window layer, >= 2048 rows, ...), K (conv + L2 clip)and V (conv + value norm) are written by n389_fold._sconv_post_kernel FOLD=1 straight into the layer's KV-cache rows, and thebackend's store for that visit is skipped (FlashAttentionBackend.forward_extend gets save_kv_cache=False). Everything else is theserved code. Where the rows go is taken from the served objects, not re-derived: a zero-row probe runs the backend's own write(kv_layers.layer(id).store with the KVWriteLoc forward_extend builds) with memory_pool._set_kv_buffer_impl swapped for a recorder,which captures the K / V buffers and write ids the store_cache JIT would get. The fold copies store_kvcache_kernel's write: row i ->buffer[ids[i]] unless ids[i] == 0 (store_cache's reserved_skip_index). The prologue's value arithmetic is untouched (n389-1:FOLD=0 PTX = served; cache words = served + store, word-checked with failing controls).
Hooks (post-import, inkling_prologue's _hook): Inkling2Attention._forward (outermost: carries the visit's per-pass RadixAttention),Inkling2Attention._prologue (over inkling_prologue's), FlashAttentionBackend.forward_extend. Fail-closed: a folded visit whosestore was not skipped raises N389Fatal (at capture, i.e. at boot, under prefill CUDA graphs). Breakable graphs, CP, MLA,fa_skip_kv_cache, image masks, MXFP8 KV, no sliding-window pool, an unrecognised write route: the stock prologue runs.Reach: STATE folded / skipped / stock / probe_refused counts; one log line at the first fold.v2 (rider2, after the n362h check boot read 'first folded' 0 with the prologue's own fused line 1 / 1): every stock-path decision on avisit the prologue would fuse logs its reason ONCE per distinct reason ('[inkling_n389] stock path: ...', with the values behind it), andthe backend is taken from the forward context, or from forward_batch.attn_backend when the context's object lacks the FA attributes.v3 (rider3, after the n362i check boot logged 'stock path: no FA backend object (context InklingShortConvHybridAttnBackend,forward_batch NoneType)'): Inkling's context backend is the full-attention + short-conv hybrid wrapper; its full-attention child(`full_attn_backend`, the FlashAttentionBackend whose forward_extend runs) is unwrapped and used."""
import contextvarsimport osimport sys
STATE = {"installed": False, "applied": [], "folded": 0, "skipped": 0, "stock": 0, "probe_refused": {}}_VISIT = contextvars.ContextVar("inkling_n389_visit", default=None)_FOLD = contextvars.ContextVar("inkling_n389_fold", default=None)HEAD, KV_HEADS, ROW = 128, 8, 1024BREAKABLE_MODULE = "sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.context"
# sha256[:16] of each function / class source (inkling_pfuse.source_digest) the rider relies on; a changed image or prologue# refuses to install._TARGETS = ( ("srt/layers/attention/flashattention_backend.py", "FlashAttentionBackend.forward_extend", "6238fb0ae1711d3e"), ("srt/mem_cache/memory_pool.py", "KVWriteLoc", "ef256dbc5dfceec7"), ("srt/mem_cache/memory_pool.py", "window_write_locs", "43b941981b5948bd"), ("srt/mem_cache/memory_pool.py", "_set_kv_buffer_impl", "a661c337aeb8fe96"), ("srt/mem_cache/memory_pool.py", "MHATokenToKVPool.set_kv_buffer", "a86c3004aa1a8468"), ("srt/mem_cache/memory_pool.py", "MHATokenToKVPool._store_kv_layer", "fa6c0e1501fdd0cf"), ("srt/mem_cache/swa_memory_pool.py", "SWAKVPool.set_kv_buffer", "3aba049258719cc9"), ("srt/mem_cache/kv/router.py", "KVLayer.store", "9ddade9026ec0874"), ("srt/mem_cache/kv/router.py", "KVLayer._write_loc", "edfd1a0fccac6954"), ("kernels/ops/kvcache/kvcache.py", "store_cache", "3adea6bd9ce54b66"), ("srt/layers/radix_attention.py", "RadixAttention.forward", "71f4956f88f633c6"), ("srt/layers/attention/base_attn_backend.py", "AttentionBackend.forward", "72ff2bff1f7dec26"),)_PROLOGUE = (("conv_post", "c08dc93ba13b051a"), ("_conv_post", "e95c0067cdbc3f85"), ("_eligible", "223f71a04ad16828"), ("make_prologue", "acb9d7690ed6e038"))
class N389Fatal(BaseException): pass
def _log(msg): print(f"[inkling_n389] {msg}", file=sys.stderr, flush=True)
def check_sources(root=None): import inspect
import inkling_prologue from inkling_pfuse import sglang_root, source_digest
root = root or sglang_root() texts = {} for rel, qualname, digest in _TARGETS: path = os.path.join(root, rel) if path not in texts: with open(path, encoding="utf-8") as f: texts[path] = f.read() got = source_digest(texts[path], qualname) if got != digest: raise N389Fatal(f"inkling_n389: {rel}:{qualname} changed (sha {got} != {digest}); refusing to patch") text = inspect.getsource(inkling_prologue) for qualname, digest in _PROLOGUE: got = source_digest(text, qualname) if got != digest: raise N389Fatal(f"inkling_n389: inkling_prologue.{qualname} changed (sha {got} != {digest}); refusing to patch")
def _why(reason, detail=""): """Log a stock-path reason once (the first 12 distinct reasons).""" n = STATE["probe_refused"].get(reason, 0) STATE["probe_refused"][reason] = n + 1 if n == 0 and len(STATE["probe_refused"]) <= 12: _log(f"stock path: {reason}{(' (' + detail + ')') if detail else ''}")
def _refuse(reason, detail=""): _why(reason, detail) return None
def _fa_backend(forward_batch): from sglang.srt.model_executor.forward_context import get_attn_backend
seen = [] for top in (get_attn_backend(), getattr(forward_batch, "attn_backend", None)): # Inkling's InklingShortConvHybridAttnBackend wraps the FA backend as full_attn_backend (every Inkling layer is full attention) for b in (top, getattr(top, "full_attn_backend", None)): if b is not None and hasattr(b, "forward_metadata") and hasattr(b, "use_sliding_window_kv_pool") and hasattr(b, "kv_layers"): return b, type(b).__name__ + ("" if b is top else f" (full_attn_backend of {type(top).__name__})") seen.append(type(b).__name__) return None, "candidates " + " / ".join(seen)
def _route(attn, forward_batch, k, in_breakable): """(k_rows, v_rows, ids, backend) the store_cache JIT would get for this visit, or None (the stock prologue runs).""" import torch from sglang.kernels.ops.kvcache.kvcache import can_use_store_cache from sglang.srt.layers.cp.utils import is_cp_active from sglang.srt.mem_cache import memory_pool as mp
if in_breakable(): return _refuse("breakable graph") backend, bname = _fa_backend(forward_batch) if backend is None: return _refuse("no FA backend object", bname) meta = getattr(backend, "forward_metadata", None) flags = (getattr(backend, "fa_skip_kv_cache", False), getattr(backend, "use_mla", False), getattr(backend, "kv_cache_is_mxfp8", False), meta is None, getattr(meta, "image_token_ranges", None) is not None, is_cp_active(forward_batch)) if any(flags): return _refuse("backend mode", f"{bname}: skip_kv / mla / mxfp8 / no meta / image / cp = {flags}") if not getattr(backend, "use_sliding_window_kv_pool", False) or getattr(meta, "swa_out_cache_loc", None) is None: return _refuse("no sliding-window write ids", f"{bname}: sliding pool {getattr(backend, 'use_sliding_window_kv_pool', None)}, " f"meta {type(meta).__name__}, swa_out_cache_loc {getattr(meta, 'swa_out_cache_loc', None) is not None}") loc_info = mp.KVWriteLoc.for_layer(forward_batch, attn, window_locs=mp.window_write_locs(backend.runner_ids, meta.swa_out_cache_loc)) rec = []
def recorder(kk, vv, k_cache, v_cache, indices, row_dim, store_dtype, device_module, size_limit, alt_stream=None, v_row_dim=None): rec.append((k_cache, v_cache, indices, row_dim, store_dtype, size_limit, v_row_dim))
stub = k.new_empty((0, KV_HEADS, HEAD)) # zero rows: any other write path writes nothing (or raises) orig = mp._set_kv_buffer_impl mp._set_kv_buffer_impl = recorder try: backend.kv_layers.layer(attn.layer_id).store(attn, loc_info, stub, stub, attn.k_scale, attn.v_scale) except Exception as exc: # noqa: BLE001 return _refuse(f"probe raised {type(exc).__name__}", str(exc)[:200]) finally: mp._set_kv_buffer_impl = orig if len(rec) != 1: kvl = backend.kv_layers.layer(attn.layer_id) return _refuse(f"probe reached _set_kv_buffer_impl {len(rec)} times", f"KVLayer plain {kvl.plain}, view {type(kvl.view).__name__}, sub_pool {kvl.route.sub_pool}") kc, vc, ids, row_dim, store_dtype, size_limit, v_row_dim = rec[0] ok = (row_dim == ROW and v_row_dim in (None, ROW) and store_dtype == torch.bfloat16 and can_use_store_cache(2 * ROW, 2 * ROW) and all(t.dtype == torch.bfloat16 and t.dim() == 3 and tuple(t.shape[1:]) == (KV_HEADS, HEAD) and t.stride() == (ROW, HEAD, 1) and t.device == k.device and t.shape[0] == size_limit for t in (kc, vc)) and ids.dim() == 1 and ids.dtype in (torch.int64, torch.int32) and ids.is_contiguous() and ids.shape[0] == k.shape[0] and ids.device == k.device) if not ok: return _refuse("write route not the BF16 NHD store_cache form", f"row {row_dim} / {v_row_dim}, store {store_dtype}, jit {can_use_store_cache(2 * ROW, 2 * ROW)}, k {kc.dtype} {tuple(kc.shape)} " f"{kc.stride()} vs size_limit {size_limit}, ids {ids.dtype} {tuple(ids.shape)} contiguous {ids.is_contiguous()} vs k rows " f"{k.shape[0]}, devices {kc.device} / {ids.device} / {k.device}") return kc.view(-1, ROW), vc.view(-1, ROW), ids, backend
def _conv_post_fold(sconv, x, forward_batch, post, thr, eps, dst, ids, update_sconv_cache, conv_post_fold): """= inkling_prologue._conv_post with the kernel writing the cache rows (same conv-state prepare / update calls).""" meta = sconv._conv_state(forward_batch) cache = sconv._sconv_cache() sconv._prepare_extend_sconv_cache(forward_batch, cache, x, meta.track_conv_indices) conv_post_fold(x, sconv._weight_2d(), cache, meta.precomputed, post, thr, eps, dst, ids) update_sconv_cache(x=x, sconv_cache=cache, cache_indices=meta.cache_indices, has_initial_state=meta.has_initial_state, query_start_loc=meta.query_start_loc)
def make_forward(prev): def _forward(self, hidden_states, positions, forward_batch, *, attn, attn_padded): vt = _VISIT.set((self, attn, forward_batch)) ft = _FOLD.set(None) try: out = prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) fold = _FOLD.get() finally: _FOLD.reset(ft) _VISIT.reset(vt) if fold is not None and not fold["consumed"]: raise N389Fatal("inkling_n389: a folded visit's KV store was not skipped (it would overwrite the folded cache rows)") return out
_forward.__wrapped__ = prev _forward._inkling_n389 = True return _forward
def make_prologue(prev, eligible, update_sconv_cache, conv_post_fold, in_breakable): import torch
def _prologue(self, q, k, v, r, sources, positions, forward_batch): visit = _VISIT.get() if not eligible(self, q, k, v, forward_batch): STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) if visit is None or visit[0] is not self or visit[2] is not forward_batch: _why("no matching visit context", "none" if visit is None else f"self {visit[0] is self}, forward_batch {visit[2] is forward_batch}") STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) dest = _route(visit[1], forward_batch, k, in_breakable) if dest is None: STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) k_rows, v_rows, ids, backend = dest tokens = q.shape[0] kc = self.k_l2_clip _conv_post_fold(self.k_sconv, k, forward_batch, 1, kc.threshold, kc.eps, k_rows, ids, update_sconv_cache, conv_post_fold) _conv_post_fold(self.v_sconv, v, forward_batch, 2, 0.0, self.v_norm.eps, v_rows, ids, update_sconv_cache, conv_post_fold) q = self.q_l2_clip(q.reshape(tokens, self.num_tp_heads, self.head_dim), output_scale=None) r = self.rel_l2_clip(r.reshape(tokens, self.num_tp_heads, self.d_rel), output_scale=None) # K / V for the attention call: never written, never read (attention reads the paged cache; the store is skipped) k_out = torch.empty((tokens, self.num_tp_kv_heads, self.head_dim), dtype=k.dtype, device=k.device) v_out = torch.empty_like(k_out) _FOLD.set({"layer": visit[1], "k": k_out.data_ptr(), "v": v_out.data_ptr(), "backend": backend, "consumed": False}) STATE["folded"] += 1 if STATE["folded"] == 1: _log(f"first folded SWA prologue ({tokens} rows, cache layer {visit[1].layer_id}, ids {ids.dtype})") return q, k_out, v_out, r
_prologue.__wrapped__ = prev _prologue._inkling_n389 = True return _prologue
def make_forward_extend(orig): def forward_extend(self, q, k, v, layer, forward_batch, *args, **kwargs): fold = _FOLD.get() if (fold is not None and not fold["consumed"] and layer is fold["layer"] and k is not None and v is not None and k.data_ptr() == fold["k"] and v.data_ptr() == fold["v"]): if self is not fold["backend"]: raise N389Fatal("inkling_n389: the folded visit's attention runs on another backend than the probed one") if args: args = (False,) + tuple(args[1:]) else: kwargs["save_kv_cache"] = False fold["consumed"] = True STATE["skipped"] += 1 return orig(self, q, k, v, layer, forward_batch, *args, **kwargs)
forward_extend.__wrapped__ = orig forward_extend._inkling_n389 = True return forward_extend
def _patch_attn(mod): import importlib import inspect
import inkling_prologue from sglang.srt.models.inkling_common.kernels.sconv import update_sconv_cache
from .n389_fold import conv_post_fold
cls = getattr(mod, "Inkling2Attention", None) if cls is None or not getattr(cls._prologue, "_inkling_prologue", False): raise N389Fatal("inkling_n389: Inkling2Attention._prologue is not inkling_prologue's (install INKLING_PROLOGUE first)") if getattr(cls._prologue, "_inkling_n389", False): return params = list(inspect.signature(cls._forward).parameters) if params != ["self", "hidden_states", "positions", "forward_batch", "attn", "attn_padded"]: raise N389Fatal(f"inkling_n389: Inkling2Attention._forward signature changed ({params})") in_breakable = getattr(importlib.import_module(BREAKABLE_MODULE), "is_in_breakable_cuda_graph") cls._forward = make_forward(cls._forward) cls._prologue = make_prologue(cls._prologue, inkling_prologue._eligible, update_sconv_cache, conv_post_fold, in_breakable) STATE["applied"] += ["Inkling2Attention._forward", "Inkling2Attention._prologue"]
def _patch_backend(mod): import inspect
cls = getattr(mod, "FlashAttentionBackend", None) if cls is None: raise N389Fatal("inkling_n389: FlashAttentionBackend is missing") if getattr(cls.forward_extend, "_inkling_n389", False): return params = list(inspect.signature(cls.forward_extend).parameters) if params[:7] != ["self", "q", "k", "v", "layer", "forward_batch", "save_kv_cache"]: raise N389Fatal(f"inkling_n389: forward_extend signature changed ({params[:7]})") cls.forward_extend = make_forward_extend(cls.forward_extend) STATE["applied"].append("FlashAttentionBackend.forward_extend")
def install(env=None): if STATE["installed"]: return bool(STATE["applied"]) or None STATE["installed"] = True env = os.environ if env is None else env if env.get("INKLING_N389", "").strip().lower() in ("", "0", "off", "false", "no"): return False import inkling_prologue from inkling_prologue import _hook
if not (inkling_prologue.STATE["installed"] and env.get("INKLING_PROLOGUE", "").strip().lower() not in ("", "0", "off", "false", "no")): raise N389Fatal("inkling_n389: needs INKLING_PROLOGUE installed first") check_sources() _hook.when_imported("sglang.srt.layers.attention.flashattention_backend", _patch_backend) _hook.when_imported("sglang.srt.models.inkling_common.inkling2_attn", _patch_attn) _log("enabled: SWA prefill K / V written into the KV cache by the fused prologue kernel; the visit's store is skipped") return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""n389 (prefill seat): INKLING_PROLOGUE's fused K / V prologue kernel with the KV-cache store folded in.
_sconv_post_kernel below is a verbatim copy of inkling_prologue._triton._sconv_post_kernel (knapcio v2.9.3, MIT; servedfile 24d2e3d9 in the S3b-p recipe overlay) plus five trailing parameters. With FOLD=False (the default) it is the servedkernel: the CPU check requires its PTX to equal the served kernel's for POST 1 and 2 (debug sections stripped). WithFOLD=True only the final store changes: row i of the BF16 result goes to Dst[Loc[i], :] instead of Y[i, :], and rows whoseslot is SKIP (store_cache's reserved_skip_index, the CUDA-graph padding slot 0) are not written. That is the servedstore_kvcache_kernel's write (k_cache[loc[i]] = k[i] unless loc[i] == 0), so the cache words are the same by construction;the value arithmetic is untouched. The helpers (_row_sumsq, rsqrt_approx_f32) are the served module's own functions."""
import torchimport tritonimport triton.language as tl
from inkling_prologue import HEAD, SUM_ORDERfrom inkling_prologue._triton import _row_sumsq, rsqrt_approx_f32
@triton.jitdef _sconv_post_kernel( X, Weight, Cache, Indices, Mask, Cu, Seq, Y, n_rows, SX: tl.constexpr, SW0: tl.constexpr, SW1: tl.constexpr, SC0: tl.constexpr, SC1: tl.constexpr, SC2: tl.constexpr, D: tl.constexpr, W: tl.constexpr, SCALE: tl.constexpr, POST: tl.constexpr, THR, EPS, BM: tl.constexpr, BN: tl.constexpr, PER: tl.constexpr = 1, XOR: tl.constexpr = 0, ORDER: tl.constexpr = 1, SS=None, WRITE_SS: tl.constexpr = False, Loc=None, Dst=None, SD: tl.constexpr = 0, SKIP: tl.constexpr = 0, FOLD: tl.constexpr = False,): rows = tl.program_id(0) * BM + tl.arange(0, BM) col = tl.program_id(1) * BN + tl.arange(0, BN) valid = (rows < n_rows)[:, None] & (col < D)[None, :] rows = tl.minimum(rows, n_rows - 1) seq = tl.load(Seq + rows) bos = tl.load(Cu + seq) slot = tl.load(Indices + seq).to(tl.int64) has_cache = (tl.load(Mask + seq) != 0) & (slot > 0) current = tl.load(X + rows[:, None] * SX + col[None, :], valid, other=0).to(tl.float32) acc = tl.full((BM, BN), 0, tl.float32) for tap in tl.static_range(W): lag = W - 1 - tap src = rows - lag from_x = (src >= bos)[:, None] value = tl.load(X + src[:, None] * SX + col[None, :], valid & from_x, other=0).to(tl.float32) prefix = tl.load( Cache + slot[:, None] * SC0 + (src - bos + W - 1)[:, None] * SC1 + col[None, :] * SC2, valid & ~from_x & has_cache[:, None], other=0, ).to(tl.float32) value = tl.where(from_x, value, prefix) weight = ( tl.load(Weight + col * SW0 + tap * SW1, col < D, other=0).to(X.dtype.element_ty).to(tl.float32) )[None, :] acc = tl.fma(value, weight, acc) acc = acc + current acc = acc * SCALE y = acc.to(tl.bfloat16).to(tl.float32) # the stock conv output (BF16) if ORDER: ss = _row_sumsq(y, BM, POST, PER, XOR) # bit-exact: the CuTe kernels' reduction tree else: ss = tl.sum(y * y, 1) if WRITE_SS: # check only: the FP32 row sum of squares, [n_rows, D // BN] tl.store(SS + rows * (D // BN) + tl.program_id(1), ss, (tl.program_id(0) * BM + tl.arange(0, BM)) < n_rows) if POST == 1: norm = tl.where(ss > 0.0, ss * rsqrt_approx_f32(ss), 0.0) coeff = tl.minimum(1.0, tl.div_rn(tl.full(norm.shape, THR, tl.float32), norm + EPS), propagate_nan=tl.PropagateNan.ALL) # stock minimumf propagates NaN else: coeff = rsqrt_approx_f32(tl.div_rn(ss, tl.full(ss.shape, BN, tl.float32)) + EPS) out = y * coeff[:, None] if FOLD: # n389: the KV-cache row write of store_kvcache_kernel (slot SKIP is the reserved padding slot: not written) dest = tl.load(Loc + rows).to(tl.int64) offs = dest[:, None] * SD + col[None, :] tl.store(Dst + offs, out.to(tl.bfloat16), valid & (dest != SKIP)[:, None]) else: offs = rows[:, None].to(tl.int64) * D + col[None, :] tl.store(Y + offs, out.to(tl.bfloat16), valid)
def conv_post_fold(x, weight, cache, md, post, thr, eps, dst, loc, order=None, skip=0): """inkling_prologue.conv_post with the result written to the KV-cache rows dst[loc[i]] (dst [slots, H*128] BF16, the layer's K or V buffer viewed as rows; loc [T] int64 / int32, the layer's write ids) instead of a fresh [T, H*128] tensor. Same launch as conv_post (grid, BM 16, BN 128, enable_fp_fusion False). Returns None (nothing else is produced). skip = -1 disables the reserved-slot skip (check-only control).""" width = weight.shape[1] per, xor = SUM_ORDER[post] if order is None else order rows, d = x.shape assert dst.dtype == torch.bfloat16 and dst.dim() == 2 and dst.shape[1] == d and dst.stride() == (d, 1), dst.shape assert loc.dim() == 1 and loc.shape[0] == rows and loc.stride(0) == 1 and loc.dtype in (torch.int32, torch.int64) _sconv_post_kernel[(triton.cdiv(rows, 16), triton.cdiv(d, HEAD))]( x, weight, cache, md["safe_idx"], md["cache_mask"], md["cu"], md["si"], dst, rows, x.stride(0), *weight.stride(), *cache.stride(), d, width, (width + 1) ** -0.5, post, float(thr), float(eps), 16, HEAD, per, xor, int(per >= 0), None, False, loc, dst, d, int(skip), True, enable_fp_fusion=False)123456# Credits
- **Thinking Machines Lab** for Inkling-2-Mini and its NVFP4 / MXFP8 checkpoint ([model card](https://huggingface.co/thinkingmachines/Inkling-2-Mini), Apache-2.0).- **SGLang** (sgl-project/sglang, Apache-2.0) for the Inkling 2 model code and the CuTe DSL K clip / RMSNorm kernels whose bodies `n395_fold.py` copies and modifies (see NOTICE.n395, LICENSE.sglang).- **NVIDIA CUTLASS / CuTe DSL** (BSD-3-Clause), used through the image's `cutlass` package (not copied here).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2023-2024 SGLang Team
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567inkling_n395/n395_fold.py contains copies of the kernel bodies of QKL2ClipFwd.kernel (sglang/kernels/ops/layernorm/inkling2_qk_l2_clip.py)and RMSNormFwd.kernel (sglang/kernels/ops/layernorm/inkling2_rms_norm.py) from SGLang (sgl-project/sglang, as shipped in the imagelmsysorg/sglang@sha256:efac853b46811ccb760545b7b29e7119bdf907537ccf6e863fac3011fe8b98de; Apache License 2.0, see LICENSE.sglang copiedunchanged from /sgl-workspace/sglang/LICENSE in that image), modified by the inkling2-spark prefill seat (2026-11-28): one-token CTAs forthe K clip, the output tile placed at KV-cache rows loc[token] with slot 0 skipped, and the constexpr-dead branches of these two callsremoved. Every modified line is marked 'n395' in the file. The rest of inkling_n395 is the prefill seat's own code, in the form ofinkling_n389 (work_prefill2/n389/rider3).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482"""inkling_n395: the KV-cache store folded into the producers of the 8 GLOBAL attention visits (prefill seat, tree n395; n395-1 KEEP:[v3 = v2 + INKLING_N438=1 (prefill seat, tree n438): on a folded visit each of K / V may take n438's fused conv + clip / norm (see _fused_side).]exact, 3.5 ms per 12K forward; enters a package only under its RULE rows).
INKLING_N395=1 after INKLING_N389 when that is on (sitecustomize: the block right after INKLING_N389's); refuses with INKLING_KV12 / INKLING_KV12S (they own the global layers' KV)
On a global (non-local) plain EXTEND visit with >= 2048 rows the served _prologue runs as written (patch/inkling2_attn.pyInkling2Attention._prologue, digest-pinned): the stock dynamic k_sconv / v_sconv, tau, the stock q clip, then K and V go throughn395_fold.k_clip_fold / v_norm_fold (the n395-1 measured kernels: the image's QKL2ClipFwd / RMSNormFwd bodies with one-token CTAs and theoutput tile at the cache rows) straight into the owner route's K / V layer buffers at out_cache_loc (slot 0 skipped = store_cache'sreserved_skip_index), then the stock rel clip; the backend's store for that visit is skipped (FlashAttentionBackend.forward_extend getssave_kv_cache=False). Where the rows go is taken from the served objects (rider3's zero-row probe of the backend's own store withmemory_pool._set_kv_buffer_impl swapped for a recorder), and the probe's ids must BE forward_batch.out_cache_loc (the owner route; thepointer-stable buffer under prefill CUDA graphs). SWA visits, decode / verify / MIXED / draft extends, < 2048 rows, a learnable K scale, aweighted / missing value norm, breakable graphs, CP, MLA, MXFP8 KV, skip-KV, image masks, an unrecognised write route, int32 ids: thechain below runs (inkling_n389 / inkling_prologue / the served code); each stock reason on a global EXTEND >= 2048-row visit is logged once.If the conv outputs are not in the fold form (BF16 [T, 8, 128], unit last stride), the visit finishes with the stock K clip / V norm onthose outputs and the store runs (the conv never runs twice). Fail-closed: a folded visit whose store was not skipped, or whose attentionruns on another backend than the probed one, raises N395Fatal (at capture, i.e. at boot, under prefill CUDA graphs).Hooks (post-import, inkling_prologue's _hook, registered after inkling_n389's): Inkling2Attention._forward (outermost: carries thevisit's per-pass RadixAttention), Inkling2Attention._prologue (over inkling_n389's when INKLING_N389 is on), FlashAttentionBackend.forward_extend. Reach: STATE folded / skipped / stock / stock_after_conv / probe_refused; one log line at the first fold."""
import contextvarsimport osimport sys
STATE = {"installed": False, "applied": [], "folded": 0, "skipped": 0, "stock": 0, "stock_after_conv": 0, "probe_refused": {}}_VISIT = contextvars.ContextVar("inkling_n395_visit", default=None)_FOLD = contextvars.ContextVar("inkling_n395_fold", default=None)HEAD, KV_HEADS, ROW, MIN_ROWS = 128, 8, 1024, 2048BREAKABLE_MODULE = "sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.context"_ON = lambda env, name: env.get(name, "").strip().lower() not in ("", "0", "off", "false", "no") # noqa: E731_IS_DEVICE = lambda t: t.is_cuda # noqa: E731 (the CPU check swaps it)
# sha256[:16] of each function / class source (inkling_pfuse.source_digest) the rider relies on; a changed image refuses to install.# = inkling_n389 rider3's store-path set + n395-1's 9 kernel / module pins (work_prefill2/n395/kit/mb395.py PINS) + the served _prologue# this rider mirrors (the digest inkling_prologue also pins)._TARGETS = ( ("srt/layers/attention/flashattention_backend.py", "FlashAttentionBackend.forward_extend", "6238fb0ae1711d3e"), ("srt/mem_cache/memory_pool.py", "KVWriteLoc", "ef256dbc5dfceec7"), ("srt/mem_cache/memory_pool.py", "window_write_locs", "43b941981b5948bd"), ("srt/mem_cache/memory_pool.py", "_set_kv_buffer_impl", "a661c337aeb8fe96"), ("srt/mem_cache/memory_pool.py", "MHATokenToKVPool.set_kv_buffer", "a86c3004aa1a8468"), ("srt/mem_cache/memory_pool.py", "MHATokenToKVPool._store_kv_layer", "fa6c0e1501fdd0cf"), ("srt/mem_cache/swa_memory_pool.py", "SWAKVPool.set_kv_buffer", "3aba049258719cc9"), ("srt/mem_cache/kv/router.py", "KVLayer.store", "9ddade9026ec0874"), ("srt/mem_cache/kv/router.py", "KVLayer._write_loc", "edfd1a0fccac6954"), ("kernels/ops/kvcache/kvcache.py", "store_cache", "3adea6bd9ce54b66"), ("srt/layers/radix_attention.py", "RadixAttention.forward", "71f4956f88f633c6"), ("srt/layers/attention/base_attn_backend.py", "AttentionBackend.forward", "72ff2bff1f7dec26"), ("kernels/ops/layernorm/inkling2_qk_l2_clip.py", "qk_l2_clip_fwd_cutedsl", "70d55d47c05648fc"), ("kernels/ops/layernorm/inkling2_qk_l2_clip.py", "QKL2ClipFwd", "b0be913c00270b77"), ("kernels/ops/layernorm/inkling2_cute_utils.py", "qk_l2_clip_row_stats", "a43c63be8515eb1c"), ("kernels/ops/layernorm/inkling2_cute_utils.py", "rmsnorm_row_rstd", "0e862090ca9b2e32"), ("kernels/ops/layernorm/inkling2_cute_utils.py", "min_f32", "382f3ee5dc9c5396"), ("kernels/ops/layernorm/inkling2_rms_norm.py", "rms_norm", "23afb3d646391ccb"), ("kernels/ops/layernorm/inkling2_rms_norm.py", "RMSNormFwd", "a8e486ef1d67daf3"), ("srt/models/inkling_common/inkling2_norm.py", "RMSNorm", "a95658ccfd18f291"), ("srt/models/inkling_common/inkling2_attn.py", "QKL2Clip", "ab220241fb563e1e"), ("srt/models/inkling_common/inkling2_attn.py", "Inkling2Attention._prologue", "bee4e4209010ba08"),)FOLD_MD5 = "c1064c8a6e17eed4115cfb93829f44e4" # n395_fold.py = the n395-1 kit file (work_prefill2/n395/kit/n395_fold.py)
class N395Fatal(BaseException): pass
def _log(msg): print(f"[inkling_n395] {msg}", file=sys.stderr, flush=True)
def check_sources(root=None): import hashlib
from inkling_pfuse import sglang_root, source_digest
root = root or sglang_root() texts = {} for rel, qualname, digest in _TARGETS: path = os.path.join(root, rel) if path not in texts: with open(path, encoding="utf-8") as f: texts[path] = f.read() got = source_digest(texts[path], qualname) if got != digest: raise N395Fatal(f"inkling_n395: {rel}:{qualname} changed (sha {got} != {digest}); refusing to patch") here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "n395_fold.py") with open(here, "rb") as f: got = hashlib.md5(f.read()).hexdigest() if got != FOLD_MD5: raise N395Fatal(f"inkling_n395: n395_fold.py md5 {got[:8]} != the measured kit file {FOLD_MD5[:8]}; refusing to patch")
def _why(reason, detail=""): """Log a stock-path reason once (the first 12 distinct reasons).""" n = STATE["probe_refused"].get(reason, 0) STATE["probe_refused"][reason] = n + 1 if n == 0 and len(STATE["probe_refused"]) <= 12: _log(f"stock path: {reason}{(' (' + detail + ')') if detail else ''}")
def _refuse(reason, detail=""): _why(reason, detail) return None
def _global_extend(self, k, forward_batch): """A global plain EXTEND visit with >= MIN_ROWS rows: the visits this rider is about (others pass through silently).""" import torch
mode = forward_batch.forward_mode if getattr(self, "is_local", True) or getattr(mode, "name", None) != "EXTEND": # plain EXTEND only (not MIXED / DLLM / verify) return False for name in ("is_draft_extend", "is_draft_extend_v2"): fn = getattr(mode, name, None) if fn is not None and fn(): return False return not torch.compiler.is_compiling() and k.shape[0] >= MIN_ROWS
def _form_why(self, k, v): """None if the visit's served objects are the fold's form, else the reason (the chain below runs).""" import torch
kc, vn = self.k_l2_clip, self.v_norm if self.head_dim != HEAD or self.num_tp_kv_heads != KV_HEADS: return f"head shape {self.num_tp_kv_heads} x {self.head_dim}" if getattr(kc, "scale", None) is not None: return "learnable K clip scale" if vn is None or getattr(vn, "weight", None) is not None or getattr(vn, "pre_weight", None) is not None: return "value norm missing or weighted" if getattr(vn, "output_dtype", None) not in (None, torch.bfloat16): return f"value norm output dtype {vn.output_dtype}" if not all(t.dtype == torch.bfloat16 and t.dim() == 2 and t.stride(-1) == 1 and _IS_DEVICE(t) for t in (k, v)): return "K / V inputs not BF16 2-D unit-stride device tensors" return None
def _fold_form(x): import torch
return x.dtype == torch.bfloat16 and x.dim() == 3 and tuple(x.shape[1:]) == (KV_HEADS, HEAD) and x.stride(-1) == 1 and _IS_DEVICE(x)
def _fa_backend(forward_batch): from sglang.srt.model_executor.forward_context import get_attn_backend
seen = [] for top in (get_attn_backend(), getattr(forward_batch, "attn_backend", None)): # Inkling's InklingShortConvHybridAttnBackend wraps the FA backend as full_attn_backend (rider3's lesson) for b in (top, getattr(top, "full_attn_backend", None)): # v2 (n409 check VOID check-1129-014537): the wrapper itself has forward_metadata (a property delegating to its child) and the # base class's kv_layers, so the v1 test accepted the WRAPPER and forward_extend (run on the child) failed the identity check. # = rider3's test: an FA backend also carries use_sliding_window_kv_pool, which the wrapper lacks. if (b is not None and hasattr(b, "forward_metadata") and hasattr(b, "use_sliding_window_kv_pool") and hasattr(b, "kv_layers")): return b, type(b).__name__ + ("" if b is top else f" (full_attn_backend of {type(top).__name__})") seen.append(type(b).__name__) return None, "candidates " + " / ".join(seen)
def _route(attn, forward_batch, k, in_breakable): """(k_rows [slots * 8, 128], v_rows, ids, backend) the store_cache JIT would get for this global visit, or None (stock).""" import torch from sglang.kernels.ops.kvcache.kvcache import can_use_store_cache from sglang.srt.layers.cp.utils import is_cp_active from sglang.srt.mem_cache import memory_pool as mp
if in_breakable(): return _refuse("breakable graph") backend, bname = _fa_backend(forward_batch) if backend is None: return _refuse("no FA backend object", bname) meta = getattr(backend, "forward_metadata", None) flags = (getattr(backend, "fa_skip_kv_cache", False), getattr(backend, "use_mla", False), getattr(backend, "kv_cache_is_mxfp8", False), meta is None, getattr(meta, "image_token_ranges", None) is not None, is_cp_active(forward_batch)) if any(flags): return _refuse("backend mode", f"{bname}: skip_kv / mla / mxfp8 / no meta / image / cp = {flags}") # = forward_extend's own store call (flashattention_backend.py, the plain MHA branch): the same KVWriteLoc for every layer loc_info = mp.KVWriteLoc.for_layer(forward_batch, attn, window_locs=mp.window_write_locs(getattr(backend, "runner_ids", None), getattr(meta, "swa_out_cache_loc", None))) rec = []
def recorder(kk, vv, k_cache, v_cache, indices, row_dim, store_dtype, device_module, size_limit, alt_stream=None, v_row_dim=None): rec.append((k_cache, v_cache, indices, row_dim, store_dtype, size_limit, v_row_dim))
stub = k.new_empty((0, KV_HEADS, HEAD)) # zero rows: any other write path writes nothing (or raises) orig = mp._set_kv_buffer_impl mp._set_kv_buffer_impl = recorder try: backend.kv_layers.layer(attn.layer_id).store(attn, loc_info, stub, stub, attn.k_scale, attn.v_scale) except Exception as exc: # noqa: BLE001 return _refuse(f"probe raised {type(exc).__name__}", str(exc)[:200]) finally: mp._set_kv_buffer_impl = orig if len(rec) != 1: return _refuse(f"probe reached _set_kv_buffer_impl {len(rec)} times") kc, vc, ids, row_dim, store_dtype, size_limit, v_row_dim = rec[0] out = getattr(forward_batch, "out_cache_loc", None) ok = (row_dim == ROW and v_row_dim in (None, ROW) and store_dtype == torch.bfloat16 and can_use_store_cache(2 * ROW, 2 * ROW) and all(t.dtype == torch.bfloat16 and t.dim() == 3 and tuple(t.shape[1:]) == (KV_HEADS, HEAD) and t.stride() == (ROW, HEAD, 1) and t.device == k.device and t.shape[0] == size_limit for t in (kc, vc)) and ids.dim() == 1 and ids.is_contiguous() and ids.shape[0] == k.shape[0] and ids.device == k.device) if not ok: return _refuse("write route not the BF16 NHD store_cache form", f"row {row_dim} / {v_row_dim}, store {store_dtype}, jit {can_use_store_cache(2 * ROW, 2 * ROW)}, k {kc.dtype} {tuple(kc.shape)} " f"{kc.stride()} vs size_limit {size_limit}, ids {ids.dtype} {tuple(ids.shape)} vs k rows {k.shape[0]}") if out is None or ids.data_ptr() != out.data_ptr() or ids.shape != out.shape: return _refuse("write ids are not forward_batch.out_cache_loc (not the owner route)") if ids.dtype != torch.int64: return _refuse("write ids not int64", str(ids.dtype)) return kc.view(-1, HEAD), vc.view(-1, HEAD), ids, backend
def make_forward(prev): def _forward(self, hidden_states, positions, forward_batch, *, attn, attn_padded): vt = _VISIT.set((self, attn, forward_batch)) ft = _FOLD.set(None) try: out = prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) fold = _FOLD.get() finally: _FOLD.reset(ft) _VISIT.reset(vt) if fold is not None and not fold["consumed"]: raise N395Fatal("inkling_n395: a folded global visit's KV store was not skipped (it would overwrite the folded cache rows)") return out
_forward.__wrapped__ = prev _forward._inkling_n395 = True return _forward
def make_prologue(prev, k_fold, v_fold, in_breakable, tau_fn, global_extend=_global_extend, form_why=_form_why): import torch
def _prologue(self, q, k, v, r, sources, positions, forward_batch): if not global_extend(self, k, forward_batch): STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) why = form_why(self, k, v) if why is not None: _why(why) STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) visit = _VISIT.get() if visit is None or visit[0] is not self or visit[2] is not forward_batch: _why("no matching visit context", "none" if visit is None else f"self {visit[0] is self}, forward_batch {visit[2] is forward_batch}") STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) dest = _route(visit[1], forward_batch, k, in_breakable) if dest is None: STATE["stock"] += 1 return prev(self, q, k, v, r, sources, positions, forward_batch) k_rows, v_rows, ids, backend = dest # = the served Inkling2Attention._prologue (digest bee4e420), global branch, with the K clip / V norm writing the cache rows tokens = q.shape[0] kz = vz = "INKLING_N438 off" if N438["on"]: # v3: n438's fused conv + clip / norm per side, at the conv's position (the served order of conv, cache update) kz = _fused_side(self.k_sconv, k, positions, forward_batch, sources.k, "k", k_rows, ids, self.k_l2_clip.eps, self.k_l2_clip.threshold) if kz is not None: _why438(f"K: {kz}") vz = _fused_side(self.v_sconv, v, positions, forward_batch, sources.v, "v", v_rows, ids, self.v_norm.eps) if vz is not None: _why438(f"V: {vz}") if kz is not None: k = self.k_sconv(k, positions, forward_batch, dynamic_input=sources.k) if vz is not None: v = self.v_sconv(v, positions, forward_batch, dynamic_input=sources.v) tau = tau_fn(positions, self.log_scaling_n_floor, self.log_scaling_alpha) if self.log_scaling_n_floor is not None else None q = self.q_l2_clip(q.reshape(tokens, self.num_tp_heads, self.head_dim), output_scale=tau) if kz is None or vz is None: # v3: a fused side already wrote its cache rows; the other side takes v2's fold if kz is not None: kx = k.reshape(tokens, self.num_tp_kv_heads, self.head_dim) if not _fold_form(kx): raise N395Fatal("inkling_n395: n438: V fused but the K conv output is not in the fold form") kc = self.k_l2_clip k_fold(kx, kc.threshold, kc.eps, k_rows, ids) if vz is not None: vx = v.reshape(tokens, self.num_tp_kv_heads, self.head_dim) if not _fold_form(vx): raise N395Fatal("inkling_n395: n438: K fused but the V conv output is not in the fold form") v_fold(vx, self.v_norm.eps, v_rows, ids) r = self.rel_l2_clip(r.reshape(tokens, self.num_tp_heads, self.d_rel), output_scale=tau) k_out = torch.empty((tokens, self.num_tp_kv_heads, self.head_dim), dtype=k.dtype, device=k.device) v_out = torch.empty_like(k_out) _FOLD.set({"layer": visit[1], "k": k_out.data_ptr(), "v": v_out.data_ptr(), "backend": backend, "consumed": False}) STATE["folded"] += 1 if STATE["folded"] == 1: _log(f"first folded global prologue ({tokens} rows, cache layer {visit[1].layer_id}, ids {ids.dtype})") return q, k_out, v_out, r kx = k.reshape(tokens, self.num_tp_kv_heads, self.head_dim) vx = v.reshape(tokens, self.num_tp_kv_heads, self.head_dim) if not (_fold_form(kx) and _fold_form(vx)): _why("conv outputs not in the fold form", f"k {kx.dtype} {tuple(kx.shape)} {kx.stride()}, v {vx.dtype} {tuple(vx.shape)} {vx.stride()}") STATE["stock_after_conv"] += 1 k = self.k_l2_clip(kx) v = self.v_norm(vx) r = self.rel_l2_clip(r.reshape(tokens, self.num_tp_heads, self.d_rel), output_scale=tau) return q, k, v, r kc = self.k_l2_clip k_fold(kx, kc.threshold, kc.eps, k_rows, ids) v_fold(vx, self.v_norm.eps, v_rows, ids) r = self.rel_l2_clip(r.reshape(tokens, self.num_tp_heads, self.d_rel), output_scale=tau) # K / V for the attention call: never written, never read (attention reads the paged cache; the store is skipped) k_out = torch.empty((tokens, self.num_tp_kv_heads, self.head_dim), dtype=kx.dtype, device=kx.device) v_out = torch.empty_like(k_out) _FOLD.set({"layer": visit[1], "k": k_out.data_ptr(), "v": v_out.data_ptr(), "backend": backend, "consumed": False}) STATE["folded"] += 1 if STATE["folded"] == 1: _log(f"first folded global prologue ({tokens} rows, cache layer {visit[1].layer_id}, ids {ids.dtype})") return q, k_out, v_out, r
_prologue.__wrapped__ = prev _prologue._inkling_n395 = True return _prologue
def make_forward_extend(orig): def forward_extend(self, q, k, v, layer, forward_batch, *args, **kwargs): fold = _FOLD.get() if (fold is not None and not fold["consumed"] and layer is fold["layer"] and k is not None and v is not None and k.data_ptr() == fold["k"] and v.data_ptr() == fold["v"]): if self is not fold["backend"]: raise N395Fatal("inkling_n395: the folded visit's attention runs on another backend than the probed one") if args: args = (False,) + tuple(args[1:]) else: kwargs["save_kv_cache"] = False fold["consumed"] = True STATE["skipped"] += 1 return orig(self, q, k, v, layer, forward_batch, *args, **kwargs)
forward_extend.__wrapped__ = orig forward_extend._inkling_n395 = True return forward_extend
def prewarm(fold): """Compile both fold kernels now (fake tensors only: no device work), under the exact functools.cache keys the calls use (k_clip_fold: BF16 x rank 3, 16-byte rows, skip; v_norm_fold: BF16 rows rank 2, 16-byte rows, skip), so no DSL compile runs inside a prefill CUDA-graph capture; a compile failure fails the boot here.""" import cutlass.cute as cute
fold.compile_k_clip_fold(cute.BFloat16, cute.BFloat16, HEAD, (3, 16), True) fold.compile_v_norm_fold(cute.BFloat16, cute.BFloat16, HEAD, (2, 16), True) STATE["prewarmed"] = (fold.compile_k_clip_fold.cache_info().currsize, fold.compile_v_norm_fold.cache_info().currsize)
def _patch_attn(mod, need_n389): import importlib import inspect
from . import n395_fold from .n395_fold import k_clip_fold, v_norm_fold
cls = getattr(mod, "Inkling2Attention", None) if cls is None: raise N395Fatal("inkling_n395: Inkling2Attention is missing") if getattr(cls._prologue, "_inkling_n395", False): return if need_n389 and not getattr(cls._prologue, "_inkling_n389", False): raise N395Fatal("inkling_n395: INKLING_N389 is on but its _prologue wrapper is not in place (install INKLING_N389 first)") params = list(inspect.signature(cls._forward).parameters) if params != ["self", "hidden_states", "positions", "forward_batch", "attn", "attn_padded"]: raise N395Fatal(f"inkling_n395: Inkling2Attention._forward signature changed ({params})") tau_fn = getattr(mod, "compute_log_scaling_tau", None) if tau_fn is None: raise N395Fatal("inkling_n395: compute_log_scaling_tau is missing from inkling2_attn") in_breakable = getattr(importlib.import_module(BREAKABLE_MODULE), "is_in_breakable_cuda_graph") prewarm(n395_fold) cls._forward = make_forward(cls._forward) cls._prologue = make_prologue(cls._prologue, k_clip_fold, v_norm_fold, in_breakable, tau_fn) STATE["applied"] += ["Inkling2Attention._forward", "Inkling2Attention._prologue"]
def _patch_backend(mod): import inspect
cls = getattr(mod, "FlashAttentionBackend", None) if cls is None: raise N395Fatal("inkling_n395: FlashAttentionBackend is missing") if getattr(cls.forward_extend, "_inkling_n395", False): return params = list(inspect.signature(cls.forward_extend).parameters) if params[:7] != ["self", "q", "k", "v", "layer", "forward_batch", "save_kv_cache"]: raise N395Fatal(f"inkling_n395: forward_extend signature changed ({params[:7]})") cls.forward_extend = make_forward_extend(cls.forward_extend) STATE["applied"].append("FlashAttentionBackend.forward_extend")
N438_TARGET = ("srt/models/inkling_common/inkling2_sconv.py", "ShortConvolution.forward", "e0818ad6a45c4763") # the extend body _fused_side mirrors
def check_n438_source(): import os from inkling_pfuse import sglang_root, source_digest rel, qualname, digest = N438_TARGET got = source_digest(open(os.path.join(sglang_root(), rel)).read(), qualname) if got != digest: raise N395Fatal(f"inkling_n395: n438: {rel}:{qualname} changed (sha {got} != {digest}); refusing INKLING_N438")
N438 = {"on": False}STOCK438 = {}
def _why438(reason): STOCK438[reason] = STOCK438.get(reason, 0) + 1 if STOCK438[reason] == 1: _log(f"n438 stock path: {reason}")
def _fused_side(sconv, x, positions, forward_batch, dynamic_input, kind, rows_buf, ids, eps, threshold=None): """ShortConvolution.forward's extend body (digest e0818ad6) with the short_convolution call AND the later fold replaced by n438's fused kernel: _conv_state, _sconv_cache, the dyn projection (the module's own `linear`), _prepare_extend_sconv_cache, the fused call, update_sconv_cache (the module's own). Returns None when done, else the refusal reason (no side effect has run then).""" import sys from . import n438_fold from sglang.kernels.ops.mamba.inkling2_sconv import PREFILL_MIN_ROWS mode = forward_batch.forward_mode if not mode.is_extend() or mode.is_decode() or mode.is_target_verify(): return "not a plain extend" if not getattr(sconv, "is_dynamic", False) or dynamic_input is None: return "static sconv" if x.shape[0] < PREFILL_MIN_ROWS: return "rows < PREFILL_MIN_ROWS" mod = sys.modules[type(sconv).__module__] meta = sconv._conv_state(forward_batch) cache = sconv._sconv_cache() weight = sconv.static_w dyn = mod.linear(dynamic_input.to(x.dtype), sconv.weight_proj.to(x.dtype)).view(x.shape[0], sconv.n_heads, sconv.kernel_size[0]) try: n438_fold._views(x, weight, dyn, cache, meta.precomputed, rows_buf, ids) except ValueError as exc: return str(exc) sconv._prepare_extend_sconv_cache(forward_batch, cache, x, meta.track_conv_indices) if kind == "k": n438_fold.k_conv_clip_fold(x, weight, dyn, cache, meta.precomputed, threshold, eps, rows_buf, ids) else: n438_fold.v_conv_norm_fold(x, weight, dyn, cache, meta.precomputed, eps, rows_buf, ids) mod.update_sconv_cache(x=x, sconv_cache=cache, cache_indices=meta.cache_indices, has_initial_state=meta.has_initial_state, query_start_loc=meta.query_start_loc) STATE["fused_" + kind] = STATE.get("fused_" + kind, 0) + 1 if STATE["fused_" + kind] == 1: _log(f"n438: first fused global conv + {'clip' if kind == 'k' else 'norm'} ({kind.upper()}, {x.shape[0]} rows)") return None
def install(env=None): if STATE["installed"]: return bool(STATE["applied"]) or None env = os.environ if env is None else env if not _ON(env, "INKLING_N395"): STATE["installed"] = True return False if _ON(env, "INKLING_KV12") or _ON(env, "INKLING_KV12S"): raise N395Fatal("inkling_n395: incompatible with INKLING_KV12 / INKLING_KV12S (they own the global layers' KV)") need_n389 = _ON(env, "INKLING_N389") if need_n389: import inkling_n389
if not inkling_n389.STATE["installed"]: raise N395Fatal("inkling_n395: INKLING_N389 is on: install it first (sitecustomize: the n395 block after n389's)") check_sources() if _ON(env, "INKLING_N438"): # v3 check_n438_source() from . import n438_fold n438_fold.compile_k_conv_fold() n438_fold.compile_v_conv_fold() N438["on"] = True _log("n438: enabled: the global K / V short conv fused into the clip / norm folds (prewarmed)") from inkling_prologue import _hook
STATE["installed"] = True _hook.when_imported("sglang.srt.layers.attention.flashattention_backend", _patch_backend) _hook.when_imported("sglang.srt.models.inkling_common.inkling2_attn", lambda mod: _patch_attn(mod, need_n389)) _log("enabled: global prefill K / V written into the KV cache by the K clip / V norm kernels; the visit's store is skipped") return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354# type: ignore"""n395 (prefill seat, tree n395 implementation 1): the KV-cache store folded into the producers of the 8 GLOBAL attention visits(work_prefill2/n395/CALLSITE.md). Subclasses of the image's CuTe kernels (sglang.kernels.ops.layernorm.inkling2_qk_l2_clip.QKL2ClipFwd,inkling2_rms_norm.RMSNormFwd); the kernel bodies are the served ones VERBATIM except the lines marked 'n395': K QKL2ClipFold: NUM_THREADS 64 (served 128) -> the CTA tile is ONE token's 8 KV-head rows (8 x 128; served 16 x 128 = 2 tokens). threads_per_row (8), vecsize (8), the thread -> (row, column) map and the per-row 8-lane reduction are unchanged. V RMSNormFold (weightless): the served CTA tile is already 8 x 128 (16 threads per row, vecsize 4, 128 threads): unchanged. Both: the output tile is `local_tile(mY, tile_mn, (loc[bid_m], 0))` over the layer's cache buffer viewed as [slots * 8, 128] (served: `(bid_m, 0)` over a fresh [T * 8, 128]); the store is skipped when loc == 0 (store_cache's reserved_skip_index).Branches that are constexpr-dead in the served calls are left out (K: scale_rank 0 kept, the output_scale branch dropped: the K clipgets output_scale=None; V: no weight, no pre-affine, no preload). So the cache words equal (served producer + store_cache) by construction; the microbench checks it word for word with a failing control.Wrappers: k_clip_fold(x, threshold, eps, k_rows, loc), v_norm_fold(x, eps, v_rows, loc); x = the visit's [T, 8, 128] BF16 producerinput (the served call's argument), k_rows / v_rows = the layer's K / V buffer viewed [rows * 8, 128], loc = int64 [T] write ids."""
import mathfrom functools import cache, partial
import cutlassimport torchfrom cutlass import Float32, const_expr, cute, range_constexpr
from sglang.kernels.ops.attention.flash_attn.cute.utils import predicate_kfrom sglang.kernels.ops.layernorm.inkling2_cute_utils import ( BASE_ALIGN, as_norm_rows, copy_partition, load_norm_rows, make_fake_2d_row_major, make_fake_norm_rows, norm_num_rows, norm_row_alignment, qk_l2_clip_fwd_layout, qk_l2_clip_row_stats, reduction_buffer_layout, rmsnorm_fwd_layout, rmsnorm_row_rstd, torch_to_cute_dtype,)from sglang.kernels.ops.layernorm.inkling2_qk_l2_clip import QKL2ClipFwdfrom sglang.kernels.ops.layernorm.inkling2_rms_norm import RMSNormFwd
HEADS, HEAD_DIM = 8, 128
class QKL2ClipFold(QKL2ClipFwd): NUM_THREADS = 64 # n395: one token (8 head rows) per CTA SKIP = True # n395: skip loc 0 (store_cache's reserved_skip_index); False = the kit's failing no-skip control only
@cute.jit def __call__( self, mX: cute.Tensor, mScale: cute.Tensor, mY: cute.Tensor, mLoc: cute.Tensor, threshold: Float32, eps: Float32, stream, ) -> None: widest_dtype_bits = const_expr( max(mX.element_type.width, mY.element_type.width) ) threads_per_row, vecsize = qk_l2_clip_fwd_layout(self.N, widest_dtype_bits) tiled_copy, tile_mn, threads_per_row = self._make_tiled_copy( mX.element_type, vecsize, threads_per_row ) assert tile_mn[0] == HEADS and tile_mn[1] == self.N, tile_mn # n395: CTA = one token self.kernel( mX, mScale, mY, mLoc, threshold, eps, tile_mn, tiled_copy, threads_per_row, ).launch( grid=[cute.ceil_div(norm_num_rows(mX), tile_mn[0]), 1, 1], block=[cute.size(tiled_copy), 1, 1], stream=stream, )
@cute.kernel def kernel( self, mX: cute.Tensor, mScale: cute.Tensor, mY: cute.Tensor, mLoc: cute.Tensor, threshold: Float32, eps: Float32, tile_mn: cute.Shape, tiled_copy: cute.TiledCopy, threads_per_row: cutlass.Constexpr[int], ) -> None: tidx, _, _ = cute.arch.thread_idx() bid_m, _, _ = cute.arch.block_idx() tv_layout = tiled_copy.layout_tv_tiled
smem = cutlass.utils.SmemAllocator() reduction_buffer = smem.allocate_tensor( cute.Float32, reduction_buffer_layout(tv_layout), byte_alignment=8, )
shape = (norm_num_rows(mX), self.N) cX_full = cute.make_identity_tensor(shape) loc = mLoc[bid_m] # n395: this token's cache slot gY = cute.local_tile(mY, tile_mn, (loc, 0)) # n395: the cache rows (served: (bid_m, 0) of a fresh output) cX = cute.local_tile(cX_full, tile_mn, (bid_m, 0))
thr_copy = tiled_copy.get_slice(tidx) tXgY = thr_copy.partition_D(gY) tXcX_full = thr_copy.partition_S(cX) tXcX = tXcX_full[(0, None), None, None]
tXrX = cute.make_rmem_tensor(tXgY.layout, mX.element_type) tXrY = cute.make_rmem_tensor_like(tXgY)
is_even_n = const_expr(shape[1] == tile_mn[1]) pred_n = ( None if is_even_n else predicate_k(thr_copy.partition_S(cX), limit=shape[1]) ) copy_n = partial(copy_partition, pred=pred_n)
row = tXcX[0][0] tXrX.fill(0.0) if row < shape[0]: if const_expr(cute.rank(mX) == 2 and self.x_alignment == 16): gX = cute.local_tile(mX, tile_mn, (bid_m, 0)) copy_n(thr_copy.partition_S(gX), tXrX) else: load_norm_rows(mX, tXrX, tXcX_full, self.x_alignment)
x = tXrX.load().to(cute.Float32) if const_expr(self.scale_rank != 0): tXrScale = cute.make_rmem_tensor(tXrX.layout, mScale.element_type) tXrScale.fill(0.0) scale_head = ( row % cutlass.Int32(mScale.shape[0]) if const_expr(self.scale_rank == 2) else 0 ) for rest_v in range_constexpr(cute.size(tXrScale.shape[0])): for rest_m in range_constexpr(cute.size(tXrScale, mode=[1])): for rest_n in range_constexpr(cute.size(tXrScale, mode=[2])): row_i = tXcX_full[(rest_v, 0), rest_m, rest_n][0] col_i = tXcX_full[(rest_v, 0), rest_m, rest_n][1] if row_i < shape[0] and col_i < shape[1]: if const_expr(self.scale_rank == 1): tXrScale[(rest_v, 0), rest_m, rest_n] = mScale[col_i] else: tXrScale[(rest_v, 0), rest_m, rest_n] = mScale[ scale_head, col_i ] x = x * tXrScale.load().to(cute.Float32)
coeff = qk_l2_clip_row_stats( x, threshold, eps, threads_per_row, reduction_buffer )
y = x * coeff tXrY.store(y.to(tXrY.element_type)) if const_expr(self.SKIP): if loc != 0: # n395: store_cache's reserved_skip_index if row < shape[0]: copy_n(tXrY, tXgY) else: if row < shape[0]: copy_n(tXrY, tXgY)
class RMSNormFold(RMSNormFwd): SKIP = True # n395: as QKL2ClipFold.SKIP @cute.jit def __call__( self, mX: cute.Tensor, mW: cute.Tensor | None, mY: cute.Tensor, mLoc: cute.Tensor, eps: Float32, stream, ) -> None: assert mW is None and not self.has_pre_affine # n395: the weightless value norm only weight_bits = const_expr(32) widest_dtype_bits = const_expr( max(mX.element_type.width, weight_bits, mY.element_type.width) ) num_threads = self._num_threads(mX.element_type) threads_per_row, vecsize = rmsnorm_fwd_layout( self.N, widest_dtype_bits, num_threads ) tiled_copy, tile_mn, threads_per_row = self._make_tiled_copy( mX.element_type, vecsize, num_threads, threads_per_row ) assert tile_mn[0] == HEADS and tile_mn[1] == self.N, tile_mn # n395: CTA = one token (as served) self.kernel( mX, mY, mLoc, eps, tile_mn, tiled_copy, threads_per_row, ).launch( grid=[cute.ceil_div(norm_num_rows(mX), tile_mn[0]), 1, 1], block=[cute.size(tiled_copy), 1, 1], stream=stream, use_pdl=True, )
@cute.kernel def kernel( self, mX: cute.Tensor, mY: cute.Tensor, mLoc: cute.Tensor, eps: Float32, tile_mn: cute.Shape, tiled_copy: cute.TiledCopy, threads_per_row: cutlass.Constexpr[int], ) -> None: tidx, _, _ = cute.arch.thread_idx() bid_m, _, _ = cute.arch.block_idx() cute.arch.griddepcontrol_wait() cute.arch.griddepcontrol_launch_dependents() tv_layout = tiled_copy.layout_tv_tiled smem = cutlass.utils.SmemAllocator() sX = smem.allocate_tensor( mX.element_type, cute.make_ordered_layout(tile_mn, order=(1, 0)), byte_alignment=BASE_ALIGN, ) reduction_buffer = smem.allocate_tensor( cute.Float32, reduction_buffer_layout(tv_layout), byte_alignment=8 ) shape = (norm_num_rows(mX), self.N) cX_full = cute.make_identity_tensor(shape) if const_expr(cute.rank(mX) == 2): gX = cute.local_tile(mX, tile_mn, (bid_m, 0)) loc = mLoc[bid_m] # n395: this token's cache slot gY = cute.local_tile(mY, tile_mn, (loc, 0)) # n395: the cache rows (served: (bid_m, 0) of a fresh output) cX = cute.local_tile(cX_full, tile_mn, (bid_m, 0)) thr_copy = tiled_copy.get_slice(tidx) if const_expr(cute.rank(mX) == 2): tXgX = thr_copy.partition_S(gX) tXsX = thr_copy.partition_D(sX) tXgY = thr_copy.partition_D(gY) tXcX = thr_copy.partition_S(cX)[(0, None), None, None] tXrX = cute.make_rmem_tensor_like(tXsX) tXrY = cute.make_rmem_tensor_like(tXgY) is_even_n = const_expr(shape[1] == tile_mn[1]) pred_n = ( None if is_even_n else predicate_k(thr_copy.partition_S(cX), limit=shape[1]) ) copy_n = partial(copy_partition, pred=pred_n) row = tXcX[0][0] if const_expr(self.use_x_g2r_load): tXrX.fill(0.0) if row < shape[0]: if const_expr(cute.rank(mX) == 2 and self.x_alignment == 16): copy_n(tXgX, tXrX) else: load_norm_rows(mX, tXrX, thr_copy.partition_S(cX), self.x_alignment) else: if row < shape[0]: if const_expr(cute.rank(mX) == 2 and self.x_alignment == 16): copy_n(tXgX, tXsX, is_async=True) else: load_norm_rows( mX, tXsX, thr_copy.partition_S(cX), self.x_alignment, is_async=True, ) cute.arch.cp_async_commit_group() cute.arch.cp_async_wait_group(0) cute.autovec_copy(tXsX, tXrX) x = tXrX.load().to(cute.Float32) rstd = rmsnorm_row_rstd(x, self.N, eps, threads_per_row, reduction_buffer) if const_expr(self.reload_x_from_smem): cute.autovec_copy(tXsX, tXrX) x = tXrX.load().to(cute.Float32) y = x * rstd y = y.to(tXrY.element_type) tXrY.store(y) if const_expr(self.SKIP): if loc != 0: # n395: store_cache's reserved_skip_index if row < shape[0]: copy_n(tXrY, tXgY) else: if row < shape[0]: copy_n(tXrY, tXgY)
class QKL2ClipFoldNoSkip(QKL2ClipFold): SKIP = False # the kit's failing control: writes slot 0 too (must differ from served in row 0 only)
class RMSNormFoldNoSkip(RMSNormFold): SKIP = False
def _fake_loc(): return cute.runtime.make_fake_tensor(cutlass.Int64, (cute.sym_int64(),), stride=(1,), assumed_align=8)
@cachedef compile_k_clip_fold(x_dtype, output_dtype, N, x_layout, skip=True): kernel = (QKL2ClipFold if skip else QKL2ClipFoldNoSkip)(N, 0, 0, x_layout[1]) mX = make_fake_norm_rows(x_dtype, N, *x_layout) mY = make_fake_2d_row_major(output_dtype, (cute.sym_int64(), N), align=BASE_ALIGN, stride_divisibility=math.gcd(N, BASE_ALIGN // (output_dtype.width // 8))) stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) return cute.compile(kernel, mX, mX, mY, _fake_loc(), Float32(0.0), Float32(0.0), stream, options="--enable-tvm-ffi")
@cachedef compile_v_norm_fold(x_dtype, output_dtype, width, x_layout, skip=True): kernel = (RMSNormFold if skip else RMSNormFoldNoSkip)(width, has_pre_affine=False, preload_weight=False, x_alignment=x_layout[1]) x = make_fake_norm_rows(x_dtype, width, *x_layout) y = make_fake_2d_row_major(output_dtype, (cute.sym_int64(), width), 16, math.gcd(width, 16 // (output_dtype.width // 8))) stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) return cute.compile(kernel, x, None, y, _fake_loc(), Float32(0.0), stream, options="--enable-tvm-ffi")
def _check(x, rows, loc): assert x.is_cuda and x.dtype == torch.bfloat16 and x.ndim == 3 and tuple(x.shape[1:]) == (HEADS, HEAD_DIM), (x.shape, x.dtype) assert rows.dtype == torch.bfloat16 and rows.ndim == 2 and rows.shape[1] == HEAD_DIM and rows.is_contiguous(), (rows.shape, rows.stride()) assert rows.shape[0] % HEADS == 0 and rows.device == x.device assert loc.dtype == torch.int64 and loc.ndim == 1 and loc.is_contiguous() and loc.numel() == x.shape[0] and loc.device == x.device
def k_clip_fold(x, threshold, eps, k_rows, loc, skip=True): """= qk_l2_clip_fwd_cutedsl(x, threshold, eps) (scale None, output_scale None) written at k_rows[loc[t] * 8 + h] (loc 0 skipped).""" _check(x, k_rows, loc) if x.shape[0] == 0: return compiled = compile_k_clip_fold(torch_to_cute_dtype[x.dtype], torch_to_cute_dtype[k_rows.dtype], HEAD_DIM, (x.ndim, norm_row_alignment(x)), skip) compiled(x, x, k_rows, loc, float(threshold), float(eps))
def v_norm_fold(x, eps, v_rows, loc, skip=True): """= rms_norm(x, None, eps) (weightless value norm) written at v_rows[loc[t] * 8 + h] (loc 0 skipped).""" _check(x, v_rows, loc) if x.shape[0] == 0: return rows = as_norm_rows(x) compiled = compile_v_norm_fold(torch_to_cute_dtype[rows.dtype], torch_to_cute_dtype[v_rows.dtype], HEAD_DIM, (rows.ndim, norm_row_alignment(x)), skip) compiled(rows, None, v_rows, loc, float(eps))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396# type: ignore"""n438 (prefill seat, tree n438 = the n404 fused form; work_prefill2/n404/fuse/DESIGN.md): the image's short_convolution (Triton_sconv_prefill_kernel: dynamic, residual, W 4) computed IN REGISTERS ahead of n395's K clip / V norm folds, so the conv outputs arenever written or re-read. Subclasses of n395_fold.py's QKL2ClipFold / RMSNormFold (c1064c8a, the n395-1 measured file); the kernel bodiesare n395's VERBATIM except the input load, replaced by conv_prologue() (lines marked 'n438'): per element (row = token * 8 + head, col): for lag 0..3, src = token - lag: value = x[src] if src >= bos(seq), else cache[slot][src - bos + 3] if has_cache (mask != 0 and slot > 0), else 0; weight = add.rn(w[lag], dyn[row, lag]); acc = mul.rn(value, weight) at lag 0, else fma.rn(value, weight, acc); then acc = add.rn(acc, x[token]); acc = mul.rn(acc, f32(9 ** -0.5)); y = BF16(acc) (RNE); then the fold. The f32 ops are inline PTX with explicit .rn (n438-1 census: = the served Triton kernel's op set per element; plain operators contract).The sequence-start branch is CTA-uniform (one token per CTA)."""import mathfrom functools import cache, partial
import cutlassimport torchfrom cutlass import Float32, const_expr, cute, range_constexprfrom cutlass._mlir.dialects import llvmfrom cutlass.cutlass_dsl import T, dsl_user_op
from sglang.kernels.ops.attention.flash_attn.cute.utils import predicate_kfrom sglang.kernels.ops.layernorm.inkling2_cute_utils import ( BASE_ALIGN, copy_partition, make_fake_2d_row_major, norm_num_rows, qk_l2_clip_fwd_layout, qk_l2_clip_row_stats, reduction_buffer_layout, rmsnorm_fwd_layout, rmsnorm_row_rstd, torch_to_cute_dtype)from .n395_fold import HEADS, HEAD_DIM, QKL2ClipFold, RMSNormFold, _fake_loc # (package-relative in the rider)
W_TAPS = 4SCALE = (W_TAPS * 2 + 1) ** -0.5 # short_convolution's scale: (width * 2 (dynamic) + 1 (residual)) ** -0.5
def _asm(fmt, *xs): return Float32(llvm.inline_asm(T.f32(), [Float32(x).ir_value() for x in xs], fmt, ",".join(["=f"] + ["f"] * len(xs)), has_side_effects=False, is_align_stack=False, asm_dialect=llvm.AsmDialect.AD_ATT))
@dsl_user_opdef fma_rn(a, b, c, *, loc=None, ip=None): return _asm("fma.rn.f32 $0, $1, $2, $3;", a, b, c)
@dsl_user_opdef mul_rn(a, b, *, loc=None, ip=None): return _asm("mul.rn.f32 $0, $1, $2;", a, b)
@dsl_user_opdef add_rn(a, b, *, loc=None, ip=None): return _asm("add.rn.f32 $0, $1, $2;", a, b)
def _conv_prologue_text(mX, mW, mDyn, mCache, mSi, mCu, mSlot, mMask, tXrX, tXc, thr_copy, tile_mn, copy_n, token): """y = short_convolution(x)[token] for this thread's fragment, written into tXrX (BF16). mX = x [T * 8, 128]; mW = w [4 * 8, 128]; mDyn = dyn [T * 8, 4]; mCache = cache [slots * 3 * 8, 128]; mSi / mCu / mSlot / mMask = the served metadata (si, cu, safe_idx, cache_mask as uint8).""" seq = mSi[token] bos = mCu[seq] slot = mSlot[seq] has_cache = (mMask[seq] != 0) & (slot > 0) acc = cute.make_rmem_tensor(tXrX.layout, Float32) cur = cute.make_rmem_tensor(tXrX.layout, Float32) for lag in range_constexpr(W_TAPS): tV = cute.make_rmem_tensor(tXrX.layout, mX.element_type) tV.fill(0.0) src = token - lag if src >= bos: copy_n(thr_copy.partition_S(cute.local_tile(mX, tile_mn, (src, 0))), tV) else: if has_cache: copy_n(thr_copy.partition_S(cute.local_tile(mCache, tile_mn, (slot * (W_TAPS - 1) + (src - bos + W_TAPS - 1), 0))), tV) tW = cute.make_rmem_tensor(tXrX.layout, mW.element_type) copy_n(thr_copy.partition_S(cute.local_tile(mW, tile_mn, (lag, 0))), tW) for i in range_constexpr(cute.size(tV)): v = Float32(tV[i]) w = add_rn(Float32(tW[i]), Float32(mDyn[tXc[i][0], lag])) if const_expr(lag == 0): cur[i] = v acc[i] = mul_rn(v, w) else: acc[i] = fma_rn(v, w, acc[i]) for i in range_constexpr(cute.size(acc)): tXrX[i] = mul_rn(add_rn(acc[i], cur[i]), Float32(SCALE)).to(tXrX.element_type)
class QKL2ClipConvFold(QKL2ClipFold): """n395's QKL2ClipFold with the conv computed in registers (n438)."""
@cute.jit def __call__(self, mX, mW, mDyn, mCache, mSi, mCu, mSlot, mMask, mScale, mY, mLoc, threshold: Float32, eps: Float32, stream) -> None: widest_dtype_bits = const_expr(max(mX.element_type.width, mY.element_type.width)) threads_per_row, vecsize = qk_l2_clip_fwd_layout(self.N, widest_dtype_bits) tiled_copy, tile_mn, threads_per_row = self._make_tiled_copy(mX.element_type, vecsize, threads_per_row) assert tile_mn[0] == HEADS and tile_mn[1] == self.N, tile_mn self.kernel(mX, mW, mDyn, mCache, mSi, mCu, mSlot, mMask, mScale, mY, mLoc, threshold, eps, tile_mn, tiled_copy, threads_per_row).launch( grid=[cute.ceil_div(norm_num_rows(mX), tile_mn[0]), 1, 1], block=[cute.size(tiled_copy), 1, 1], stream=stream)
@cute.kernel def kernel( self, mX: cute.Tensor, mW: cute.Tensor, mDyn: cute.Tensor, mCache: cute.Tensor, mSi: cute.Tensor, mCu: cute.Tensor, mSlot: cute.Tensor, mMask: cute.Tensor, mScale: cute.Tensor, mY: cute.Tensor, mLoc: cute.Tensor, threshold: Float32, eps: Float32, tile_mn: cute.Shape, tiled_copy: cute.TiledCopy, threads_per_row: cutlass.Constexpr[int], ) -> None: tidx, _, _ = cute.arch.thread_idx() bid_m, _, _ = cute.arch.block_idx() tv_layout = tiled_copy.layout_tv_tiled
smem = cutlass.utils.SmemAllocator() reduction_buffer = smem.allocate_tensor( cute.Float32, reduction_buffer_layout(tv_layout), byte_alignment=8, )
shape = (norm_num_rows(mX), self.N) cX_full = cute.make_identity_tensor(shape) loc = mLoc[bid_m] # n395: this token's cache slot gY = cute.local_tile(mY, tile_mn, (loc, 0)) # n395: the cache rows (served: (bid_m, 0) of a fresh output) cX = cute.local_tile(cX_full, tile_mn, (bid_m, 0))
thr_copy = tiled_copy.get_slice(tidx) tXgY = thr_copy.partition_D(gY) tXcX_full = thr_copy.partition_S(cX) tXcX = tXcX_full[(0, None), None, None]
tXrX = cute.make_rmem_tensor(tXgY.layout, mX.element_type) tXrY = cute.make_rmem_tensor_like(tXgY)
is_even_n = const_expr(shape[1] == tile_mn[1]) pred_n = ( None if is_even_n else predicate_k(thr_copy.partition_S(cX), limit=shape[1]) ) copy_n = partial(copy_partition, pred=pred_n)
row = tXcX[0][0] # n438: the conv prologue (y = short_convolution(x)[token] into tXrX), inlined: conv_prologue's text seq = mSi[bid_m] bos = mCu[seq] slot = mSlot[seq] has_cache = (mMask[seq] != 0) & (slot > 0) acc = cute.make_rmem_tensor(tXrX.layout, Float32) cur = cute.make_rmem_tensor(tXrX.layout, Float32) for lag in range_constexpr(W_TAPS): tV = cute.make_rmem_tensor(tXrX.layout, mX.element_type) tV.fill(0.0) src = bid_m - lag if src >= bos: copy_n(thr_copy.partition_S(cute.local_tile(mX, tile_mn, (src, 0))), tV) else: if has_cache: copy_n(thr_copy.partition_S(cute.local_tile(mCache, tile_mn, (slot * (W_TAPS - 1) + (src - bos + W_TAPS - 1), 0))), tV) tW = cute.make_rmem_tensor(tXrX.layout, mW.element_type) copy_n(thr_copy.partition_S(cute.local_tile(mW, tile_mn, (lag, 0))), tW) for i in range_constexpr(cute.size(tV)): v = Float32(tV[i]) w = add_rn(Float32(tW[i]), Float32(mDyn[tXcX_full[i][0], lag])) if const_expr(lag == 0): cur[i] = v acc[i] = mul_rn(v, w) else: acc[i] = fma_rn(v, w, acc[i]) for i in range_constexpr(cute.size(acc)): tXrX[i] = mul_rn(add_rn(acc[i], cur[i]), Float32(SCALE)).to(tXrX.element_type)
x = tXrX.load().to(cute.Float32) if const_expr(self.scale_rank != 0): tXrScale = cute.make_rmem_tensor(tXrX.layout, mScale.element_type) tXrScale.fill(0.0) scale_head = ( row % cutlass.Int32(mScale.shape[0]) if const_expr(self.scale_rank == 2) else 0 ) for rest_v in range_constexpr(cute.size(tXrScale.shape[0])): for rest_m in range_constexpr(cute.size(tXrScale, mode=[1])): for rest_n in range_constexpr(cute.size(tXrScale, mode=[2])): row_i = tXcX_full[(rest_v, 0), rest_m, rest_n][0] col_i = tXcX_full[(rest_v, 0), rest_m, rest_n][1] if row_i < shape[0] and col_i < shape[1]: if const_expr(self.scale_rank == 1): tXrScale[(rest_v, 0), rest_m, rest_n] = mScale[col_i] else: tXrScale[(rest_v, 0), rest_m, rest_n] = mScale[ scale_head, col_i ] x = x * tXrScale.load().to(cute.Float32)
coeff = qk_l2_clip_row_stats( x, threshold, eps, threads_per_row, reduction_buffer )
y = x * coeff tXrY.store(y.to(tXrY.element_type)) if const_expr(self.SKIP): if loc != 0: # n395: store_cache's reserved_skip_index if row < shape[0]: copy_n(tXrY, tXgY) else: if row < shape[0]: copy_n(tXrY, tXgY)
class RMSNormConvFold(RMSNormFold): """n395's RMSNormFold with the conv computed in registers (n438)."""
@cute.jit def __call__(self, mX, mW, mDyn, mCache, mSi, mCu, mSlot, mMask, mNoW, mY, mLoc, eps: Float32, stream) -> None: assert mNoW is None and not self.has_pre_affine widest_dtype_bits = const_expr(max(mX.element_type.width, 32, mY.element_type.width)) num_threads = self._num_threads(mX.element_type) threads_per_row, vecsize = rmsnorm_fwd_layout(self.N, widest_dtype_bits, num_threads) tiled_copy, tile_mn, threads_per_row = self._make_tiled_copy(mX.element_type, vecsize, num_threads, threads_per_row) assert tile_mn[0] == HEADS and tile_mn[1] == self.N, tile_mn self.kernel(mX, mW, mDyn, mCache, mSi, mCu, mSlot, mMask, mY, mLoc, eps, tile_mn, tiled_copy, threads_per_row).launch( grid=[cute.ceil_div(norm_num_rows(mX), tile_mn[0]), 1, 1], block=[cute.size(tiled_copy), 1, 1], stream=stream, use_pdl=True)
@cute.kernel def kernel( self, mX: cute.Tensor, mW: cute.Tensor, mDyn: cute.Tensor, mCache: cute.Tensor, mSi: cute.Tensor, mCu: cute.Tensor, mSlot: cute.Tensor, mMask: cute.Tensor, mY: cute.Tensor, mLoc: cute.Tensor, eps: Float32, tile_mn: cute.Shape, tiled_copy: cute.TiledCopy, threads_per_row: cutlass.Constexpr[int], ) -> None: tidx, _, _ = cute.arch.thread_idx() bid_m, _, _ = cute.arch.block_idx() cute.arch.griddepcontrol_wait() cute.arch.griddepcontrol_launch_dependents() tv_layout = tiled_copy.layout_tv_tiled smem = cutlass.utils.SmemAllocator() sX = smem.allocate_tensor( mX.element_type, cute.make_ordered_layout(tile_mn, order=(1, 0)), byte_alignment=BASE_ALIGN, ) reduction_buffer = smem.allocate_tensor( cute.Float32, reduction_buffer_layout(tv_layout), byte_alignment=8 ) shape = (norm_num_rows(mX), self.N) cX_full = cute.make_identity_tensor(shape) if const_expr(cute.rank(mX) == 2): gX = cute.local_tile(mX, tile_mn, (bid_m, 0)) loc = mLoc[bid_m] # n395: this token's cache slot gY = cute.local_tile(mY, tile_mn, (loc, 0)) # n395: the cache rows (served: (bid_m, 0) of a fresh output) cX = cute.local_tile(cX_full, tile_mn, (bid_m, 0)) thr_copy = tiled_copy.get_slice(tidx) if const_expr(cute.rank(mX) == 2): tXgX = thr_copy.partition_S(gX) tXsX = thr_copy.partition_D(sX) tXgY = thr_copy.partition_D(gY) tXcX = thr_copy.partition_S(cX)[(0, None), None, None] tXrX = cute.make_rmem_tensor_like(tXsX) tXrY = cute.make_rmem_tensor_like(tXgY) is_even_n = const_expr(shape[1] == tile_mn[1]) pred_n = ( None if is_even_n else predicate_k(thr_copy.partition_S(cX), limit=shape[1]) ) copy_n = partial(copy_partition, pred=pred_n) row = tXcX[0][0] # n438: the conv prologue, inlined (as in QKL2ClipConvFold) tXc438 = thr_copy.partition_S(cX) seq = mSi[bid_m] bos = mCu[seq] slot = mSlot[seq] has_cache = (mMask[seq] != 0) & (slot > 0) acc = cute.make_rmem_tensor(tXrX.layout, Float32) cur = cute.make_rmem_tensor(tXrX.layout, Float32) for lag in range_constexpr(W_TAPS): tV = cute.make_rmem_tensor(tXrX.layout, mX.element_type) tV.fill(0.0) src = bid_m - lag if src >= bos: copy_n(thr_copy.partition_S(cute.local_tile(mX, tile_mn, (src, 0))), tV) else: if has_cache: copy_n(thr_copy.partition_S(cute.local_tile(mCache, tile_mn, (slot * (W_TAPS - 1) + (src - bos + W_TAPS - 1), 0))), tV) tW = cute.make_rmem_tensor(tXrX.layout, mW.element_type) copy_n(thr_copy.partition_S(cute.local_tile(mW, tile_mn, (lag, 0))), tW) for i in range_constexpr(cute.size(tV)): v = Float32(tV[i]) w = add_rn(Float32(tW[i]), Float32(mDyn[tXc438[i][0], lag])) if const_expr(lag == 0): cur[i] = v acc[i] = mul_rn(v, w) else: acc[i] = fma_rn(v, w, acc[i]) for i in range_constexpr(cute.size(acc)): tXrX[i] = mul_rn(add_rn(acc[i], cur[i]), Float32(SCALE)).to(tXrX.element_type) if const_expr(self.reload_x_from_smem): cute.autovec_copy(tXrX, tXsX) # n438: the reload below reads y back from shared memory x = tXrX.load().to(cute.Float32) rstd = rmsnorm_row_rstd(x, self.N, eps, threads_per_row, reduction_buffer) if const_expr(self.reload_x_from_smem): cute.autovec_copy(tXsX, tXrX) x = tXrX.load().to(cute.Float32) y = x * rstd y = y.to(tXrY.element_type) tXrY.store(y) if const_expr(self.SKIP): if loc != 0: # n395: store_cache's reserved_skip_index if row < shape[0]: copy_n(tXrY, tXgY) else: if row < shape[0]: copy_n(tXrY, tXgY)
# ---- wrappers (n438): the fused forms of (short_convolution -> n395's k_clip_fold / v_norm_fold) on one global visitdef _fake_1d(dtype): return cute.runtime.make_fake_tensor(dtype, (cute.sym_int64(),), stride=(1,), assumed_align=max(1, dtype.width // 8))
def _fakes(): bf = cutlass.BFloat16 rows = lambda: make_fake_2d_row_major(bf, (cute.sym_int64(), HEAD_DIM), align=16, stride_divisibility=8) # noqa: E731 w = make_fake_2d_row_major(bf, (W_TAPS * HEADS, HEAD_DIM), align=16, stride_divisibility=8) dyn = make_fake_2d_row_major(bf, (cute.sym_int64(), W_TAPS), align=8, stride_divisibility=W_TAPS) meta = (_fake_1d(cutlass.Int32), _fake_1d(cutlass.Int64), _fake_1d(cutlass.Int64), _fake_1d(cutlass.Uint8)) return rows, w, dyn, meta
@cachedef compile_k_conv_fold(): rows, w, dyn, meta = _fakes() stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) return cute.compile(QKL2ClipConvFold(HEAD_DIM, 0, 0, 16), rows(), w, dyn, rows(), *meta, rows(), rows(), _fake_loc(), Float32(0.0), Float32(0.0), stream, options="--enable-tvm-ffi")
@cachedef compile_v_conv_fold(): rows, w, dyn, meta = _fakes() stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) kernel = RMSNormConvFold(HEAD_DIM, has_pre_affine=False, preload_weight=False, x_alignment=16) return cute.compile(kernel, rows(), w, dyn, rows(), *meta, None, rows(), _fake_loc(), Float32(0.0), stream, options="--enable-tvm-ffi")
def _views(x, weight, dyn, cache_t, meta, rows_buf, loc): """-> the kernel views, or raise ValueError (the caller keeps the served chain). Only the Triton prefill path is reproduced.""" from sglang.kernels.ops.mamba.inkling2_sconv import PREFILL_MIN_ROWS T = x.shape[0] D = HEADS * HEAD_DIM checks = [ (x.is_cuda and x.dtype == torch.bfloat16 and x.ndim == 2 and x.shape[1] == D and x.is_contiguous(), "x [T, 1024] BF16 contiguous"), (T >= PREFILL_MIN_ROWS, f"rows {T} < PREFILL_MIN_ROWS {PREFILL_MIN_ROWS} (served path is the CUDA sconv)"), (weight.dtype == torch.bfloat16 and tuple(weight.shape) == (W_TAPS, D) and weight.is_contiguous(), "weight [4, 1024] BF16 contiguous"), (dyn.dtype == torch.bfloat16 and tuple(dyn.shape) == (T, HEADS, W_TAPS) and dyn.is_contiguous(), "dynamic [T, 8, 4] BF16 contiguous"), (cache_t.dtype == torch.bfloat16 and cache_t.ndim == 3 and tuple(cache_t.shape[1:]) == (W_TAPS - 1, D) and cache_t.is_contiguous(), "cache [S, 3, 1024] BF16 contiguous"), (meta["si"].dtype == torch.int32 and meta["si"].numel() == T and meta["si"].is_contiguous(), "si int32 [T]"), (meta["cu"].dtype == torch.int64 and meta["cu"].is_contiguous(), "cu int64"), (meta["safe_idx"].dtype == torch.int64 and meta["safe_idx"].is_contiguous(), "safe_idx int64"), (meta["cache_mask"].dtype == torch.bool and meta["cache_mask"].is_contiguous(), "cache_mask bool"), (rows_buf.dtype == torch.bfloat16 and rows_buf.ndim == 2 and rows_buf.shape[1] == HEAD_DIM and rows_buf.is_contiguous() and rows_buf.shape[0] % HEADS == 0, "rows buffer [slots * 8, 128] BF16"), (loc.dtype == torch.int64 and loc.ndim == 1 and loc.numel() == T and loc.is_contiguous(), "loc int64 [T]"), ] bad = [m for ok, m in checks if not ok] if bad: raise ValueError("n438: " + "; ".join(bad)) return (x.view(-1, HEAD_DIM), weight.view(-1, HEAD_DIM), dyn.view(-1, W_TAPS), cache_t.view(-1, HEAD_DIM), meta["si"], meta["cu"], meta["safe_idx"], meta["cache_mask"].reshape(-1).view(torch.uint8))
def k_conv_clip_fold(x, weight, dyn, cache_t, meta, threshold, eps, k_rows, loc): """= k_clip_fold(short_convolution(x, weight, cache_t, meta, dynamic_weights=dyn).view(-1, 8, 128), threshold, eps, k_rows, loc).""" v = _views(x, weight, dyn, cache_t, meta, k_rows, loc) compile_k_conv_fold()(*v, v[0], k_rows, loc, float(threshold), float(eps))
def v_conv_norm_fold(x, weight, dyn, cache_t, meta, eps, v_rows, loc): """= v_norm_fold(short_convolution(x, weight, cache_t, meta, dynamic_weights=dyn).view(-1, 8, 128), eps, v_rows, loc).""" v = _views(x, weight, dyn, cache_t, meta, v_rows, loc) compile_v_conv_fold()(*v, None, v_rows, loc, float(eps))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""inkling_n437 v3: phoist's attention-side _mix1_hoist_kernel launched at BM 16, SHARED True AND SHARED False (prefill seat, trees n437 + n439).v3 = v2 (RIDER.md5 967b2f07, CHECK PASS in n409c / n409d) + ONE change: the SHARED constexpr is no longer pinned to True. The attention-sidelaunch at SHARED False (loop_mix_hoisted on the global core layers 11 / 17: their attention query is (3, 2304), nqs = 3) is routed to BM 16too. n439 measured it (kit 2ecac3fc, run_20261129T135949Z, KEEP): BM 16 word-equal to BM 32 at SHARED False on 8 configs (GV 1 and GV 3,eager + graph), +0.356 ms per call = +1.42 ms per 12K forward. SHARED False classes log 'n437: routed gv<G>_add<A>_shf' (first per class).Below: v2's docstring (its SHARED-True-only routing rule is the part v3 changes).inkling_n437: phoist's attention-side _mix1_hoist_kernel launched at BM 16 (prefill seat, tree n437; n437 KEEP, kit 5177dd7b).
INKLING_N437=1 (needs INKLING_PFUSE_HOIST): inkling_phoist.phoist_triton._mix1_hoist_kernel is wrapped so that a launch with NM 3, SHARED, NORM at BM 32 / BN 64 / STAGES 2 / num_warps 8 on grid (3, cdiv(T, 32)) (= loop_mix_hoisted's attention side, n437's measured launch) runs the SAME served kernel with BM 16 on grid (3, cdiv(T, 16)); every other launch (the mlp side, any other shape) goes to the served kernel unchanged. pfuse's non-hoisted mix1 is another kernel object (_triton_mix._loop_mix1_kernel) and mix.MIX is not touched: both keep BM 32. n437 measured BM 16 word-equal to BM 32 at T 12,288 / 12,275, HAS_ADD False, GV 1, 3 / 6 sources (eager + graph) and +7.86 ms per 12K forward. Other T / GV / HAS_ADD values are routed too; the package check boot's KLD and fixed seeds cover them.Reach: STATE counts routed launches (by GV / HAS_ADD), launches passed through, and NORM launches left at BM 32. v2 (verify f412af06note): the first routed launch of EACH (GV, HAS_ADD) class logs one line ('n437: routed gv<G>_add<A> ...'), so a check boot can show BM 16reach on the GV 3 and HAS_ADD branches n437 did not measure; the first NORM launch left at BM 32 logs one line ('n437: NORM launch left ...').CUDA graphs: the wrapper only rewrites the grid and the BM argument at launch time (host side); a captured graph holds the BM 16 launch."""import logging
STATE = {"installed": False, "routed": 0, "served": 0, "norm_served": 0, "routed_by": {}}_log = logging.getLogger(__name__)NAMES = ("T", "NM", "HAS_ADD", "SHARED", "NORM", "GV", "BM", "BN", "STAGES")WANT = {"NM": 3, "NORM": True, "BM": 32, "BN": 64, "STAGES": 2} # v3: SHARED is not pinned (True: n437; False: n439); it must be a boolWARPS, BM_NEW = 8, 16KW = {"num_warps", "enable_fp_fusion"}
def _cdiv(a, b): return -(-a // b)
class _BM16Grid: """Stands in for the served JITFunction at `kernel[grid](...)` call sites."""
def __init__(self, served): names = list(served.arg_names) missing = [n for n in NAMES if n not in names] if missing: raise RuntimeError(f"n437: served _mix1_hoist_kernel lacks arguments {missing}: {names}") self.served = served self.nargs = len(names) self.idx = {n: names.index(n) for n in NAMES}
def _route(self, grid, args, kw): i = self.idx if len(args) != self.nargs or set(kw) - KW or kw.get("num_warps") != WARPS: return False if not all(type(args[i[k]]) is type(v) and args[i[k]] == v for k, v in WANT.items()): return False if type(args[i["SHARED"]]) is not bool: # v3 return False t = args[i["T"]] return isinstance(t, int) and t > 0 and isinstance(grid, tuple) and len(grid) == 2 and grid == (3, _cdiv(t, 32))
def __getitem__(self, grid): def launch(*args, **kw): if self._route(grid, args, kw): i = self.idx t = args[i["T"]] new = list(args) new[i["BM"]] = BM_NEW STATE["routed"] += 1 key = f"gv{args[i['GV']]}_add{int(bool(args[i['HAS_ADD']]))}" + ("" if args[i["SHARED"]] else "_shf") # v3: SHARED False classes STATE["routed_by"][key] = STATE["routed_by"].get(key, 0) + 1 if STATE["routed_by"][key] == 1: _log.warning("n437: routed %s: attention-side _mix1_hoist at BM 16 (grid %s -> (3, %s), T %s)", key, grid, _cdiv(t, BM_NEW), t) return self.served[(3, _cdiv(t, BM_NEW))](*new, **kw) STATE["served"] += 1 if len(args) == self.nargs and args[self.idx["NORM"]] is True: STATE["norm_served"] += 1 if STATE["norm_served"] == 1: _log.warning("n437: NORM launch left at the served BM (grid %s, NM %s, SHARED %s, BM %s)", grid, args[self.idx["NM"]], args[self.idx["SHARED"]], args[self.idx["BM"]]) return self.served[grid](*args, **kw) return launch
def __getattr__(self, name): return getattr(self.served, name)
def _patch(kt): kernel = kt._mix1_hoist_kernel if isinstance(kernel, _BM16Grid): return kt._mix1_hoist_kernel = _BM16Grid(kernel) STATE["installed"] = True
def install(): from inkling_phoist import _hook
_hook.when_imported("inkling_phoist.phoist_triton", _patch)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175// SPDX-License-Identifier: Apache-2.0// n351 (inkling2-spark prefill seat, 2026-11-27): exact restructures of n14's nvfp4_quantize_tokens_kernel<2304> (n14_quant.cuh// afdcb38b, served on S2 79d139b0). Every written word is computed by the same image helpers (part_max, block_max_reduce,// quantize_part, store_part, zero_expert_tail, row_expert); only the schedule changes. Variant bits V:// 1 hoist: per token, threads 0..top_k-1 compute (row, expert) of the token's destinations into shared memory before the// amax reduction (whose __syncthreads publishes them); every thread then reads them instead of running its own binary// search per destination (double-buffered by the reduction's parity, as red[] is)// 2 prefetch: the next token's BF16 row is loaded into registers before the current token's quantize + stores// 4 split 2: E = 8 values per thread, 288 threads per token (the image's split for this width is 4: E = 4, 576 threads).// quantize_part keeps the block's pairwise error-sum order for any E (its own comment), part_max / amax are maxima.// V = 0 is a copy of the served kernel (the copy null).#include <sgl_kernel/tensor.h>
#include <sgl_kernel/utils.cuh>
#include "routed_quant_sm120.cuh"#include <cstdint>
namespace sglang::n351_quant {
using namespace sglang::inkling2_routed_quant;using sglang::inkling2_routed_quant_sm120::verify_offsets;using sglang::inkling2_routed_quant_sm120::verify_rows;using sglang::inkling2_routed_quant_sm120::zero_expert_tail;
template <int K, int V>struct Cfg { static constexpr int kSplit = (V & 4) ? 2 : split(K); static constexpr int E = 16 / kSplit; static constexpr int kThreads = (K / 16 * kSplit + 31) / 32 * 32;};
template <int E>__device__ __forceinline__ void load_part(__nv_bfloat16 const* src, float (&v)[E]) { if constexpr (E == 8) { uint4 raw = *reinterpret_cast<uint4 const*>(src); __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(&raw);#pragma unroll for (int i = 0; i < E; ++i) v[i] = __bfloat162float(h[i]); } else { uint2 raw = *reinterpret_cast<uint2 const*>(src); __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(&raw);#pragma unroll for (int i = 0; i < E; ++i) v[i] = __bfloat162float(h[i]); }}
constexpr int kMaxTopK = 16;
template <int K, int V>__global__ void __launch_bounds__(Cfg<K, V>::kThreads) nvfp4_quantize_tokens_kernel( __nv_bfloat16 const* __restrict__ x, int32_t const* __restrict__ src2dst, uint8_t* values, uint8_t* x_scales, float* amax_out, int32_t const* __restrict__ offsets, int32_t tokens, int32_t top_k, int32_t experts) { constexpr int kThreads = Cfg<K, V>::kThreads, kSplit = Cfg<K, V>::kSplit, E = Cfg<K, V>::E; constexpr bool kHoist = V & 1, kPrefetch = V & 2; static_assert(K % 64 == 0 && kSplit > 1); __shared__ int32_t s_offsets[kMaxExperts + 1]; __shared__ float red[2][kThreads / 32]; __shared__ int32_t s_row[2][kMaxTopK]; __shared__ int32_t s_exp[2][kMaxTopK]; device::PDLWaitPrimary<true>(); device::PDLTriggerSecondary<true>(); load_offsets(offsets, experts, s_offsets); int32_t const block = threadIdx.x / kSplit, part = threadIdx.x % kSplit; bool const active = block < K / 16; int32_t const lo = s_offsets[0], hi = s_offsets[experts]; int32_t parity = 0; float nxt[E]; if constexpr (kPrefetch) {#pragma unroll for (int i = 0; i < E; ++i) nxt[i] = 0.0f; if (active && blockIdx.x < tokens) load_part<E>(x + int64_t(blockIdx.x) * K + block * 16 + part * E, nxt); } for (int32_t token = blockIdx.x; token < tokens; token += gridDim.x, parity ^= 1) { float v[E]; if constexpr (kPrefetch) {#pragma unroll for (int i = 0; i < E; ++i) v[i] = nxt[i]; int32_t const t2 = token + gridDim.x; if (active && t2 < tokens) load_part<E>(x + int64_t(t2) * K + block * 16 + part * E, nxt); } else {#pragma unroll for (int i = 0; i < E; ++i) v[i] = 0.0f; if (active) load_part<E>(x + int64_t(token) * K + block * 16 + part * E, v); } if constexpr (kHoist) { if (threadIdx.x < top_k) { int32_t const row = src2dst[int64_t(token) * top_k + threadIdx.x]; bool const live = row >= lo && row < hi; s_row[parity][threadIdx.x] = live ? row : -1; s_exp[parity][threadIdx.x] = live ? row_expert(s_offsets, experts, row) : -1; } } float block_max = part_max<E>(v); float amax = block_max_reduce<kThreads>(block_max, red[parity]); // its __syncthreads also publishes s_row / s_exp uint32_t packed; uint8_t scale; quantize_part<E>(v, amax, block_max, packed, scale); for (int32_t k = 0; k < top_k; ++k) { int32_t row, expert; if constexpr (kHoist) { row = s_row[parity][k]; if (row < 0) continue; expert = s_exp[parity][k]; } else { row = src2dst[int64_t(token) * top_k + k]; if (row < lo || row >= hi) continue; expert = row_expert(s_offsets, experts, row); } if (active) { if (threadIdx.x == 0) amax_out[row] = amax; store_part<E>(values, x_scales, s_offsets, expert, row, block, part, K, packed, scale); } if (row == s_offsets[expert + 1] - 1) zero_expert_tail(s_offsets, expert, x_scales, (K + 63) / 64 * 4); } }}
inline int32_t grid_for(int32_t tokens, int64_t sm_count, int64_t grid) { int64_t const g = grid > 0 ? grid : 4 * sm_count; return static_cast<int32_t>(std::max<int64_t>(1, std::min<int64_t>(tokens, g)));}
// = n14_quant::nvfp4_quantize_tokens<K> (same checks, grid rule and PDL launch) with the variant kernel<K, V>.template <int K, int V>void nvfp4_quantize_tokens( tvm::ffi::TensorView x, tvm::ffi::TensorView src2dst, tvm::ffi::TensorView values, tvm::ffi::TensorView x_scales, tvm::ffi::TensorView amax, tvm::ffi::TensorView offsets, int64_t top_k, int64_t sm_count, int64_t grid) { constexpr int64_t kPart = 16 / Cfg<K, V>::kSplit; auto tokens = host::SymbolicSize{"tokens"}; auto rows = host::SymbolicSize{"routed rows"}; auto scale_rows = host::SymbolicSize{"scale rows"}; auto device = host::SymbolicDevice{}; device.set_options<kDLCUDA>(); int32_t const experts = verify_offsets(offsets, device); host::TensorMatcher({tokens, K}).with_dtype<bf16_t>().with_device(device).ensure_alignment(kPart * 2).verify(x); host::TensorMatcher({rows}).with_dtype<int32_t>().with_device(device).verify(src2dst); host::TensorMatcher({rows, K / 2}).with_dtype<uint8_t>().with_device(device).ensure_alignment(kPart / 2).verify(values); host::TensorMatcher({scale_rows, K / 16}).with_dtype<uint8_t>().with_device(device).verify(x_scales); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(amax); CHECK_HOST(top_k > 0 && top_k <= kMaxTopK) << "top_k must be in 1.." << kMaxTopK << ", got " << top_k; int32_t const num_rows = verify_rows(rows); int32_t const num_tokens = verify_rows(tokens); CHECK_HOST(int64_t{num_tokens} * top_k == num_rows) << "src2dst must hold tokens x top_k rows"; CHECK_HOST(scale_rows.unwrap() >= host::div_ceil(num_rows + 127 * int64_t{experts}, 128) * 128) << "NVFP4 scales need 128-row blocks per expert, got " << scale_rows.unwrap() << " rows"; host::LaunchKernel(grid_for(num_tokens, sm_count, grid), Cfg<K, V>::kThreads, device.unwrap()) .enable_pdl(true)( nvfp4_quantize_tokens_kernel<K, V>, static_cast<__nv_bfloat16 const*>(x.data_ptr()), static_cast<int32_t const*>(src2dst.data_ptr()), static_cast<uint8_t*>(values.data_ptr()), static_cast<uint8_t*>(x_scales.data_ptr()), static_cast<float*>(amax.data_ptr()), static_cast<int32_t const*>(offsets.data_ptr()), num_tokens, static_cast<int32_t>(top_k), experts);}
} // namespace sglang::n351_quant123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216// SPDX-License-Identifier: Apache-2.0// n355-1 (inkling2-spark prefill seat, 2026-11-27): exact restructures of the image's mxfp8_swiglu_quantize_routed<1152>// (routed_quant_sm120.cuh, served on S2 79d139b0 for the MXFP8 layers 20-23). Every written word is computed by the image's// own helpers (capped_swiglu, the BF16 round, mxfp8_half_block) in the same order per element; only the schedule changes.// Variant bits V:// 1 hoist: each thread keeps the expert of its previous row and walks forward (rows only increase), instead of the// 7-step binary search of cute_exponent_offset per row; the result equals row_expert's (largest e with offsets[e] <= row)// 2 prefetch: the next row's 64 B per lane and its gamma are loaded before the current row's arithmetic + stores// 4 pack 4: 288 threads = 4 rows x 72 lanes (9 full warps) per CTA iteration instead of 1 row on 96 threads (72 active);// lane pairs (2i, 2i + 1) stay inside one row (72 is even), so mxfp8_half_block's shfl_xor 1 pairs the same lanes// 8 grid 16 x SMs instead of the image's 4 x SMs (capped by the iteration count)// V = 0 runs mxfp8_swiglu_quantize_copy: the served kernel body verbatim at the served launch (the copy null; SASS-checked). No variant calls launch_dependents (as served: the CuTe SM120 GEMM// reading the outputs does not wait on its predecessor).#include <sgl_kernel/tensor.h>
#include <sgl_kernel/utils.cuh>
#include "routed_quant_sm120.cuh"#include <cstdint>
namespace sglang::n355_quant {
using namespace sglang::inkling2_routed_quant;using sglang::inkling2_routed_quant_sm120::verify_offsets;using sglang::inkling2_routed_quant_sm120::verify_rows;
template <int N, int V>struct Cfg { static constexpr int kLanes = N / 16; static constexpr int kRows = (V & 4) ? 4 : 1; static constexpr int kThreads = (V & 4) ? kLanes * 4 : threads(N); static constexpr int kGridMul = (V & 8) ? 16 : 4; static_assert((V & 4) == 0 || (kLanes % 2 == 0 && kThreads % 32 == 0 && kThreads <= 1024));};
// = cute_exponent_offset with the expert given (scale row of `row` in expert e's 4-row aligned block, MN-major groups of 4).__device__ __forceinline__ int64_t exponent_offset(int32_t row, int32_t group, int32_t const* offsets, int32_t e, int32_t m_padded) { int32_t const scale_row = (offsets[e] + 3 * e) / 4 * 4 + row - offsets[e]; return (int64_t(group / 4) * m_padded + scale_row) * 4 + group % 4;}
// V = 0: the image's kernel body verbatim (copied from routed_quant_sm120.cuh by the kit's generator step; SASS = served).template <int N>__global__ void __launch_bounds__(threads(N)) mxfp8_swiglu_quantize_copy( __nv_bfloat16 const* __restrict__ x, float const* __restrict__ gammas, uint8_t* values, uint8_t* exponents, int32_t const* __restrict__ offsets, int32_t experts, float gate_cap, float up_cap, int32_t m_padded) { static_assert(N % 128 == 0 && N / 16 <= 1024); device::PDLWaitPrimary<true>(); int32_t const block = threadIdx.x; bool const active = block < N / 16; int32_t const lo = offsets[0], hi = offsets[experts]; for (int32_t row = lo + blockIdx.x; row < hi; row += gridDim.x) { float v[16]; if (active) { uint4 const* src = reinterpret_cast<uint4 const*>(x + int64_t(row) * 2 * N + block * 32); uint4 raw[4] = {src[0], src[1], src[2], src[3]}; __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(raw); float gamma = gammas[row];#pragma unroll for (int i = 0; i < 16; ++i) v[i] = __bfloat162float(__float2bfloat16_rn( capped_swiglu(__bfloat162float(h[2 * i]), __bfloat162float(h[2 * i + 1]), gamma, gate_cap, up_cap))); } else {#pragma unroll for (int i = 0; i < 16; ++i) v[i] = 0.0f; } uint4 packed; uint8_t exponent; mxfp8_half_block(v, packed, exponent); if (active) { *reinterpret_cast<uint4*>(values + int64_t(row) * N + block * 16) = packed; if (block % 2 == 0) exponents[sglang::inkling2_routed_quant_sm120::cute_exponent_offset(row, block / 2, offsets, experts, m_padded)] = exponent; } }}
template <int N, int V>__global__ void __launch_bounds__(Cfg<N, V>::kThreads) mxfp8_swiglu_quantize_v( __nv_bfloat16 const* __restrict__ x, float const* __restrict__ gammas, uint8_t* values, uint8_t* exponents, int32_t const* __restrict__ offsets, int32_t experts, float gate_cap, float up_cap, int32_t m_padded) { using C = Cfg<N, V>; static_assert(N % 128 == 0 && N / 16 <= 1024); constexpr bool kHoist = V & 1, kPrefetch = V & 2; device::PDLWaitPrimary<true>(); int32_t const sub = threadIdx.x / C::kLanes; // row slot inside the CTA iteration (0 unless pack) int32_t const block = threadIdx.x - sub * C::kLanes; // lane inside the row: 0..71 (>= 72 only for the 96-thread form) bool const lane_ok = block < N / 16 && sub < C::kRows; int32_t const lo = offsets[0], hi = offsets[experts]; int32_t const step = gridDim.x * C::kRows; int32_t e = 0; bool have_e = false; uint4 raw[4]; float gamma = 0.0f; int32_t row = lo + blockIdx.x * C::kRows + sub; auto load = [&](int32_t r, uint4 (&dst)[4], float& gm) -> bool { // true iff the lane loaded row r (the active predicate) bool const ok = lane_ok && r < hi; if (ok) { uint4 const* src = reinterpret_cast<uint4 const*>(x + int64_t(r) * 2 * N + block * 32); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; gm = gammas[r]; } return ok; }; if constexpr (kPrefetch) load(row, raw, gamma); for (int32_t base = lo + blockIdx.x * C::kRows; base < hi; base += step, row += step) { bool const active = lane_ok && row < hi; uint4 nraw[4]; float ngamma = 0.0f; bool nok = false; // V & 2: whether this lane loaded the next row (= the next iteration's active predicate) if constexpr (kPrefetch) nok = load(row + step, nraw, ngamma); else load(row, raw, gamma); float v[16]; if (active) { __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(raw);#pragma unroll for (int i = 0; i < 16; ++i) v[i] = __bfloat162float(__float2bfloat16_rn( capped_swiglu(__bfloat162float(h[2 * i]), __bfloat162float(h[2 * i + 1]), gamma, gate_cap, up_cap))); } else {#pragma unroll for (int i = 0; i < 16; ++i) v[i] = 0.0f; } uint4 packed; uint8_t exponent; mxfp8_half_block(v, packed, exponent); if (active) { *reinterpret_cast<uint4*>(values + int64_t(row) * N + block * 16) = packed; if (block % 2 == 0) { if constexpr (kHoist) { if (!have_e) { e = row_expert(offsets, experts, row); have_e = true; } while (e + 1 < experts && offsets[e + 1] <= row) ++e; exponents[exponent_offset(row, block / 2, offsets, e, m_padded)] = exponent; } else { exponents[sglang::inkling2_routed_quant_sm120::cute_exponent_offset(row, block / 2, offsets, experts, m_padded)] = exponent; } } } if constexpr (kPrefetch) { if (nok) { // n355-1 re-pin (verify HOLD 16:4x): copy only what this lane loaded; an inactive lane never reads raw / gamma#pragma unroll for (int i = 0; i < 4; ++i) raw[i] = nraw[i]; gamma = ngamma; } } }}
template <int N, int V>void mxfp8_swiglu_quantize( tvm::ffi::TensorView x, tvm::ffi::TensorView gammas, tvm::ffi::TensorView values, tvm::ffi::TensorView exponents, tvm::ffi::TensorView offsets, int64_t m_padded, double gate_cap, double up_cap, int64_t sm_count) { using C = Cfg<N, V>; auto rows = host::SymbolicSize{"routed rows"}; auto device = host::SymbolicDevice{}; device.set_options<kDLCUDA>(); int32_t const experts = verify_offsets(offsets, device); host::TensorMatcher({rows, 2 * N}) // .with_dtype<bf16_t>() .with_device(device) .ensure_alignment(16) .verify(x); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(gammas); host::TensorMatcher({rows, N}) // .with_dtype<uint8_t>() .with_device(device) .ensure_alignment(16) .verify(values); host::TensorMatcher({N / 128, m_padded}).with_dtype<int32_t>().with_device(device).verify(exponents); int32_t const num_rows = verify_rows(rows); CHECK_HOST(m_padded >= (num_rows + 3 * int64_t{experts}) / 4 * 4 && m_padded < std::numeric_limits<int32_t>::max()) << "MXFP8 scales need 4-row aligned experts, got m_padded " << m_padded; int32_t const iters = (num_rows + C::kRows - 1) / C::kRows; int32_t const grid = V == 0 ? grid_size(num_rows, static_cast<int32_t>(sm_count)) // the image's launch for the copy : std::max(1, std::min(iters, C::kGridMul * static_cast<int32_t>(sm_count))); auto* kernel = V == 0 ? mxfp8_swiglu_quantize_copy<N> : mxfp8_swiglu_quantize_v<N, V>; host::LaunchKernel(grid, V == 0 ? threads(N) : C::kThreads, device.unwrap()) .enable_pdl(true)( kernel, static_cast<__nv_bfloat16 const*>(x.data_ptr()), static_cast<float const*>(gammas.data_ptr()), static_cast<uint8_t*>(values.data_ptr()), static_cast<uint8_t*>(exponents.data_ptr()), static_cast<int32_t const*>(offsets.data_ptr()), experts, static_cast<float>(gate_cap), static_cast<float>(up_cap), static_cast<int32_t>(m_padded));}
} // namespace sglang::n355_quant123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""Combined loader for the Inkling-2-Mini SGLang overlays (verify cap, draft bytes, kernels, pico12, prefill).Each overlay activates only when its environment switch is set; with none set nothing is imported.A failing overlay stops the process (site.py would otherwise only print a warning and run the stock path)."""import osimport sys
def _on(name): return os.environ.get(name, "").strip().lower() not in ("", "0", "off", "none", "false", "no")
try: if _on("INKLING_KV12") and _on("INKLING_KV12S"): raise RuntimeError("INKLING_KV12S and INKLING_KV12 are mutually exclusive") if _on("INKLING_VERIFY_CAP"): from inkling_vcap import activate activate() if _on("INKLING_DRAFT_BYTES"): import inkling_draftbytes inkling_draftbytes.install() if _on("INKLING_KERNELS"): import inkling_kernels inkling_kernels.install() if _on("INKLING_MOE2"): # after inkling_kernels: per-token tile tables over moe_tiles' _tiles wrapper import inkling_moe2 inkling_moe2.install() if _on("INKLING_SCODES"): # NVFP4 expert scale codes (exact; wraps nvfp4_expert_matmul) import inkling_scodes inkling_scodes.install() if _on("INKLING_PICO12"): # after inkling_kernels: its _project_sources wrapper goes outside qkvr_gemv's import inkling_pico12 inkling_pico12.install() if _on("INKLING_PREFILL"): # last: its _project_sources wrapper (large M only) goes outermost import inkling_prefill inkling_prefill.install() if _on("INKLING_PFUSE"): # prefill glue fusion: Inkling2DecoderLayer._forward, extend only import inkling_pfuse inkling_pfuse.install() if _on("INKLING_PROLOGUE"): # SWA prefill: K conv + L2 clip, V conv + value norm fused (FP32-order class) import inkling_prologue inkling_prologue.install() if _on("INKLING_PFUSE_HOIST"): # prefill loop-bank hoist over pfuse's loop_mix (FP32-order class; needs PFUSE) import inkling_phoist inkling_phoist.install() if _on("INKLING_N329"): # n329: phoist _bank_stats per row (bitwise; wraps the kernel phoist launches; needs PFUSE_HOIST) import inkling_n329 inkling_n329.install() if _on("INKLING_N437"): # n437: phoist's attention-side _mix1_hoist at BM 16 (bitwise words; wraps the kernel phoist launches; needs PFUSE_HOIST) import inkling_n437 inkling_n437.install() if _on("INKLING_N320_SCONV"): # n320: pfuse sconvres at another exact tile (per-element kernel; needs PFUSE sconvres) import inkling_n320s inkling_n320s.install() if _on("INKLING_N351"): # n351: MoE NVFP4 token quantize through an exact variant (bitwise; n351_quant.cuh mounted at the JIT path) import inkling_n351 inkling_n351.install() if _on("INKLING_N355"): # n355: MXFP8 swiglu quantize through an exact variant (bitwise; n355_quant.cuh mounted at the JIT path) import inkling_n355 inkling_n355.install() if _on("INKLING_N381"): # n381: F2b gate_up on the exact ping-pong tile_k-128 schedule + n360 pass variant (bitwise; unit mounted at the JIT path) import inkling_n381 inkling_n381.install() if _on("INKLING_WIDE"): # after pico12 (reads its packs) and prefill: outermost _project_sources for 17..256 rows import inkling_wide inkling_wide.install() if _on("INKLING_CERT_HEAD"): # after pico12 and wide: outermost lm-head wrapper (<= 16 rows), reads pico's coded head import inkling_cert inkling_cert.install() if _on("INKLING_ATTN") and not _on("INKLING_KV12S"): # fused relative-bias prefill attention (falls back to the stock FA4 path per call) import inkling_attn inkling_attn.install() if _on("INKLING_N389"): # n389: SWA prefill K / V written into the KV cache by the prologue kernel, store skipped (bitwise words; after ATTN) import inkling_n389 inkling_n389.install() if _on("INKLING_N395"): # n395: global prefill K / V written into the KV cache by the K clip / V norm kernels, store skipped (bitwise words; after N389) import inkling_n395 inkling_n395.install() if _on("INKLING_KV12S_VATTN_TRACE"): # diagnostic: log compact verify attention arguments from inkling_kv12s.patch import register_vattn_trace register_vattn_trace() if _on("INKLING_VATTN"): # target-verify attention: split-KV relative-bias kernel for all batch sizes import inkling_vattn inkling_vattn.install() if _on("INKLING_KV12"): # after vattn: global-layer KV read from a packed 12-bit side pool (exact) import inkling_kv12 inkling_kv12.install() if _on("INKLING_KV12S"): import inkling_kv12s inkling_kv12s.install() elif _on("INKLING_DSPARK_EAGER_COMMIT"): # diagnostic: KV12S's eager draft commit on stock pools from inkling_kv12s.patch import register_eager_commit_only register_eager_commit_only() if _on("INKLING_NOEXP"): # dead verify rows get no experts (exact for live rows; needs INKLING_VERIFY_CAP) import inkling_noexp inkling_noexp.install() if _on("INKLING_PADX"): # after noexp: CUDA-graph padding rows route to the phantom expert (exact for live rows) import inkling_padx inkling_padx.install() if _on("INKLING_DFLASH_BYTES") or _on("INKLING_DFLASH_CTX8"): # DFlash2 drafter byte cuts / MXFP8 context projections (draft-only; SPEC=dflash2) import inkling_dfbytes inkling_dfbytes.install() if _on("INKLING_DFLASH_FUSED_ACCEPT"): # DFLASH sampled accept from the logits with sparse q (same law) import inkling_dfaccept inkling_dfaccept.install() if _on("INKLING_DFLASH_PCOPY"): # DFLASH: prompt-copy forced drafts (draft proposals only; after the verify cap) import inkling_pcopy inkling_pcopy.install() if _on("INKLING_DFLASH_PCOPY_RINGOFF"): # n405: inkling_pcopy on a ring-off DFLASH drafter (after inkling_pcopy; its own pins) import inkling_pcopyro inkling_pcopyro.install() if _on("INKLING_DFLASH_PREFIX_TAIL") or _on("INKLING_DFLASH_TAIL_SNAPSHOTS"): # DFLASH draft ring on prefix hits: (A) re-prefill the last N input tokens, (B) restore a prompt-end draft window snapshot import inkling_dftail inkling_dftail.install() if _on("INKLING_PROMPT_TOUCH"): # cache LRU order only: refresh a finished request's prompt-end checkpoint import inkling_ptouch inkling_ptouch.install() if _on("INKLING_RSFIX"): # exact residual / bonus lane rule (+ SGLang PR #51681 / #51692 fixes) import inkling_rsfix inkling_rsfix.install() if os.environ.get("INKLING_DFLASH_MIX_PATH", "").strip(): # n391: the Strata mix only when a mix is named (it pins no base drafter) import inkling_mixdraft inkling_mixdraft.install() if _on("INKLING_DFLASH_GLOBAL"): # n391: per-layer rope base for global-attention DFlash2 drafter layers (config layer_types) import inkling_dfglobal inkling_dfglobal.install()except BaseException as exc: # noqa: BLE001 sys.stderr.write("[inkling-overlay pid=%d] FATAL at startup: %r\n" % (os.getpid(), exc)) sys.stderr.flush() os._exit(78)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""inkling_dfglobal (n391, dflash): per-layer RoPE base for DFlash2-family drafters with global-attention layers.
INKLING_DFLASH_GLOBAL=1 (default: unset -> install() does nothing)
Stock SGLang (models/dflash.py) already reads the drafter's per-layer attention type from config.layer_types(full_attention -> no window, sliding_attention -> config.sliding_window). What it lacks is a per-layer RoPE base:every layer's rotary_emb is built from one get_rope_config(config). DFlash2-Global configs (e.g.cambash23/Inkling-2-Mini-DFlash2-Global-L13) train their full_attention layers with global_rope_theta (top-level, ordflash_global_config.global_rope_theta) and their sliding layers with rope_parameters.rope_theta.
This wraps DFlashAttention.__init__: for layer_id with layer_types[layer_id] == "full_attention" AND a configured globaltheta, the stock __init__ runs with the module's get_rope_config returning (global theta, the stock rope_scaling); everyother line of the stock layer is unchanged, and every other layer is built exactly as stock. No layer index ishard-coded: the layer map comes from config.json. After construction the layer's rotary_emb.base must equal theintended base (else the process stops). A non-null global_yarn_scale refuses (not supported). An MLA drafter with afull_attention layer and a global theta refuses (only the MHA DFlashAttention path is patched).Stock gap 2 (worker _init_fused_kv_helper, dflash_worker_v2.py:1614-1690): the fused context-K/V writer rotates every layer'scontext K with layer 0's rotary_emb (one cos_sin_cache). With per-layer bases that would rotate the global layers' context K withthe sliding base. So DFlashDraftModel.__init__ is wrapped too: when its layers' rotary bases differ, the instance'ssupports_fused_context_kv is set False (the stock opt-out, dflash_worker_v2.py:1622), and context K/V take the stock sequentialpath (per layer: kv_proj_only, k_norm, the layer's own apply_k_rope). A drafter with one base keeps the fused path.Logged (fixed grammar): '[inkling_dfglobal pid=N] armed' '[inkling_dfglobal pid=N] layer L TYPE rope base B' TYPE in full_attention / sliding_attention / untyped '[inkling_dfglobal pid=N] fused context KV off: rope bases B1,B2' (only when the layers' bases differ)"""import osimport sys
from . import _hook
ENV = "INKLING_DFLASH_GLOBAL"DFLASH_MODULE = "sglang.srt.models.dflash"MARK = "_inkling_dfglobal"STATE = {"installed": False, "layers": {}}
def _log(msg): sys.stderr.write(f"[inkling_dfglobal pid={os.getpid()}] {msg}\n") sys.stderr.flush()
def _get(cfg, key, default=None): if isinstance(cfg, dict): return cfg.get(key, default) return getattr(cfg, key, default)
def global_theta(config): """(theta or None, yarn scale or None) from a DFlash2-Global config: top-level global_rope_theta wins over dflash_global_config.global_rope_theta; both present and different refuses.""" top = _get(config, "global_rope_theta") gc = _get(config, "dflash_global_config") or {} inner = _get(gc, "global_rope_theta") if top is not None and inner is not None and float(top) != float(inner): raise ValueError(f"inkling_dfglobal: global_rope_theta {top} != dflash_global_config.global_rope_theta {inner}") theta = top if top is not None else inner return (None if theta is None else float(theta)), _get(gc, "global_yarn_scale")
def patch_dflash(mod): from sglang.srt.speculative.dflash_utils import get_dflash_layer_types
cls = mod.DFlashAttention if getattr(cls.__init__, MARK, False): return orig_init = cls.__init__ stock_rope_config = mod.get_rope_config
def __init__(self, config, layer_id, *args, **kwargs): types = get_dflash_layer_types(config) ltype = types[layer_id] if types is not None and layer_id < len(types) else None theta, yarn = global_theta(config) if ltype == "full_attention" and theta is not None: if yarn is not None: raise ValueError(f"inkling_dfglobal: global_yarn_scale {yarn!r} is not supported") _, scaling = stock_rope_config(config) mod.get_rope_config = lambda _cfg, _s=scaling: (theta, _s) try: orig_init(self, config, layer_id, *args, **kwargs) finally: mod.get_rope_config = stock_rope_config want = theta else: orig_init(self, config, layer_id, *args, **kwargs) want = float(stock_rope_config(config)[0]) base = float(getattr(self.rotary_emb, "base", float("nan"))) if base != want: raise RuntimeError(f"inkling_dfglobal: layer {layer_id} rotary base {base} != intended {want}") STATE["layers"][int(layer_id)] = (ltype or "untyped", base) _log(f"layer {int(layer_id)} {ltype or 'untyped'} rope base {base:g}")
__init__.__wrapped__ = orig_init setattr(__init__, MARK, True) cls.__init__ = __init__ model = mod.DFlashDraftModel if not getattr(model.__init__, MARK, False): model_init = model.__init__
def model_init_wrap(self, *args, **kwargs): model_init(self, *args, **kwargs) bases = sorted({float(layer.self_attn.rotary_emb.base) for layer in self.layers if hasattr(getattr(layer, "self_attn", None), "rotary_emb")}) if len(bases) > 1: self.supports_fused_context_kv = False STATE["fused_off"] = bases _log("fused context KV off: rope bases " + ",".join(f"{b:g}" for b in bases))
model_init_wrap.__wrapped__ = model_init setattr(model_init_wrap, MARK, True) model.__init__ = model_init_wrap mla = getattr(mod, "DFlashMLAAttention", None) if mla is not None and not getattr(mla.__init__, MARK, False): mla_init = mla.__init__
def mla_guard(self, config, layer_id, *args, **kwargs): types = get_dflash_layer_types(config) if types is not None and layer_id < len(types) and types[layer_id] == "full_attention" and global_theta(config)[0] is not None: raise ValueError("inkling_dfglobal: an MLA drafter with a global rope theta is not supported") mla_init(self, config, layer_id, *args, **kwargs)
mla_guard.__wrapped__ = mla_init setattr(mla_guard, MARK, True) mla.__init__ = mla_guard _log("armed")
def install(env=None): env = os.environ if env is None else env if STATE["installed"] or env.get(ENV, "").strip() in ("", "0"): return False STATE["installed"] = True _hook.when_imported(DFLASH_MODULE, patch_dflash) return True1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Post-import hooks: run a callback right after a module finishes executing.
Patches attach lazily so that processes which never import the model pay nothingand never import sglang or torch. If the target module is already imported, thecallback runs at once. A callback that raises makes the import of its target fail.Several overlays may each install a finder of this kind; they nest (each wraps theloader the next one returned), so every package's callbacks run."""
import importlib.abcimport sysimport threading
_lock = threading.RLock()_callbacks: dict = {}_finder = None
class _Loader(importlib.abc.Loader): def __init__(self, inner, name): self._inner = inner self._name = name
def create_module(self, spec): create = getattr(self._inner, "create_module", None) return create(spec) if create is not None else None
def exec_module(self, module): self._inner.exec_module(module) _run(self._name, module)
def __getattr__(self, attr): return getattr(self._inner, attr)
class _Finder(importlib.abc.MetaPathFinder): def __init__(self): self._busy = set()
def find_spec(self, fullname, path, target=None): if fullname not in _callbacks or fullname in self._busy: return None self._busy.add(fullname) try: spec = None for finder in sys.meta_path: if finder is self or not hasattr(finder, "find_spec"): continue spec = finder.find_spec(fullname, path, target) if spec is not None: break finally: self._busy.discard(fullname) if spec is None or spec.loader is None: return None spec.loader = _Loader(spec.loader, fullname) return spec
def _run(name, module): with _lock: callbacks = _callbacks.pop(name, []) for callback in callbacks: callback(module)
def when_imported(name, callback): """Call callback(module) once module `name` has been imported.""" global _finder with _lock: module = sys.modules.get(name) if module is None: _callbacks.setdefault(name, []).append(callback) if _finder is None: _finder = _Finder() sys.meta_path.insert(0, _finder) return callback(module)
def pending(): with _lock: return sorted(_callbacks)recipe/stack/cands/n361-s3b-p/recipe/patch/n80_cuda.pyAdded+171
recipe/stack/cands/n361-s3b-p/recipe/patch/n80_draft.pyAdded+147
recipe/stack/cands/n361-s3b-p/recipe/patch/n86_riders.pyAdded+448
recipe/stack/cands/n361-s3b-p/recipe/serve/inkling2_mtp.pyAdded+667
recipe/stack/cands/n361-s3b-p/recipe/serve/serve.shAdded+167
recipe/stack/cands/n361-s3b-p/recipe/serve/sl.jsonAdded
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n320s/__init__.pyAdded+66
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/__init__.pyAdded+58
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows.pyAdded+31
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows_ctl.pyAdded+31
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n351/__init__.pyAdded+68
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n355/__init__.pyAdded+69
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n381/__init__.pyAdded+98
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/CREDITS.knapcio-v2.9.3.mdAdded+94
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/LICENSE.knapcio-v2.9.3Added+21
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.knapcio-v2.9.3Added+54
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.n389Added+3
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/__init__.pyAdded+307
recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/n389_fold.pyAdded+93
recipe/stack/cands/n362j-e35d7419/overlay_n362j/n351_quant.cuhAdded+175
recipe/stack/cands/n362j-e35d7419/overlay_n362j/n355_quant.cuhAdded+216
recipe/stack/cands/n362j-e35d7419/overlay_n362j/n381c_band.cuhAdded
recipe/stack/cands/n362j-e35d7419/overlay_n362j/sitecustomize.pyAdded+116
recipe/stack/cands/n419ab-6d18f8eb/df-r1b2.jsonAdded+1
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n320s/__init__.pyAdded+66
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/__init__.pyAdded+58
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows.pyAdded+31
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows_ctl.pyAdded+31
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n351/__init__.pyAdded+68
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n355/__init__.pyAdded+69
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n381/__init__.pyAdded+98
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/CREDITS.knapcio-v2.9.3.mdAdded+94
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/LICENSE.knapcio-v2.9.3Added+21
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.knapcio-v2.9.3Added+54
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.n389Added+3
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/__init__.pyAdded+307
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/n389_fold.pyAdded+93
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/CREDITS.n395.mdAdded+6
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/LICENSE.sglangAdded+201
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/NOTICE.n395Added+7
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/__init__.pyAdded+482
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n395_fold.pyAdded+354
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n438_fold.pyAdded+396
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n437/__init__.pyAdded+96
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n351_quant.cuhAdded+175
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n355_quant.cuhAdded+216
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n381c_band.cuhAdded
recipe/stack/cands/n419c-8f01ac06/overlay_n419c/sitecustomize.pyAdded+129
recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/__init__.pyAdded+134
recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/_hook.pyAdded+83