diff --git a/recipe/stack/cands/n361-s3b-p/recipe/patch/n80_cuda.py b/recipe/stack/cands/n361-s3b-p/recipe/patch/n80_cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..136c1b7df454c5cb691b87d908e7d022bad7d355 --- /dev/null +++ b/recipe/stack/cands/n361-s3b-p/recipe/patch/n80_cuda.py @@ -0,0 +1,171 @@ +"""n80_cuda.py (inkling2-spark decode seat, tree n80, 2026-11-24): K-chunked variant of n75 build 2 for drafter linears whose K is +too 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 served +sm12x_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 os +import torch + +SMEM_MAX = 101376 +CUDA_SRC = r''' +#include +#include +#include +#include + +__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 +__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(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(x + (size_t)r * SX + kq); a2 = *reinterpret_cast(x + (size_t)r * SX + kq + 8); } + if (MT == 2 && r + 8 < M) { a1 = *reinterpret_cast(x + (size_t)(r + 8) * SX + kq); a3 = *reinterpret_cast(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 +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; + 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(need, (int64_t)std::max(occ, 1) * sms); + } + kern<<<(int)grid, NW * 32, smem, at::cuda::getCurrentCUDAStream()>>>( + reinterpret_cast(wp.data_ptr()), base.data_ptr(), reinterpret_cast(W.data_ptr()), + reinterpret_cast(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(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) diff --git a/recipe/stack/cands/n361-s3b-p/recipe/patch/n80_draft.py b/recipe/stack/cands/n361-s3b-p/recipe/patch/n80_draft.py new file mode 100644 index 0000000000000000000000000000000000000000..a937eb2e29c4dd8d0ab7a4a259b59bc484c64739 --- /dev/null +++ b/recipe/stack/cands/n361-s3b-p/recipe/patch/n80_draft.py @@ -0,0 +1,147 @@ +"""n80 rider (inkling2-spark decode seat, 2026-11-24; DRAFT, not run on the image): exact 12-bit packed DSpark drafter linears on +n75's packed registry (S6: n75_install.py df7cb3e4, n75_cuda.py 0ab557d0, n75_c12.py bb969a78) and the served <= 16-row +sm12x_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 x +stage; 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 pct +slower 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 ' 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) diff --git a/recipe/stack/cands/n361-s3b-p/recipe/patch/n86_riders.py b/recipe/stack/cands/n361-s3b-p/recipe/patch/n86_riders.py new file mode 100644 index 0000000000000000000000000000000000000000..87677861d1256adb329bce2fcb2a21667c3372e5 --- /dev/null +++ b/recipe/stack/cands/n361-s3b-p/recipe/patch/n86_riders.py @@ -0,0 +1,448 @@ +"""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 mounted +inkling2_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 the +three 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 counted +here (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 list +N75_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), "", "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 ', 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", "")) diff --git a/recipe/stack/cands/n361-s3b-p/recipe/serve/inkling2_mtp.py b/recipe/stack/cands/n361-s3b-p/recipe/serve/inkling2_mtp.py new file mode 100644 index 0000000000000000000000000000000000000000..8c77a6e549d5321263d97523c0a9a1aa615a4a20 --- /dev/null +++ b/recipe/stack/cands/n361-s3b-p/recipe/serve/inkling2_mtp.py @@ -0,0 +1,667 @@ +import json +import logging +import os +from collections.abc import Iterable + +import torch +from 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 RMSNorm +from sglang.srt.layers.linear import QKVParallelLinear +from sglang.srt.layers.logits_processor import should_apply_lm_head_quant_method +from sglang.srt.mem_cache.memory_pool import KVWriteLoc, layer_window_locs +from sglang.srt.mem_cache.swa_memory_pool import SWAKVPool +from sglang.srt.model_loader.weight_utils import default_weight_loader +from sglang.srt.models.dflash import DFlashDraftModel +from 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__]) + diff --git a/recipe/stack/cands/n361-s3b-p/recipe/serve/serve.sh b/recipe/stack/cands/n361-s3b-p/recipe/serve/serve.sh new file mode 100644 index 0000000000000000000000000000000000000000..419c7a0e0a643f916865616af59dd41cad169ec6 --- /dev/null +++ b/recipe/stack/cands/n361-s3b-p/recipe/serve/serve.sh @@ -0,0 +1,167 @@ +#!/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/ = 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/inkling2 +N75_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/elementwise +MDL=/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_sm120 +mkdir -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.py +d094e435eb939e01fca6297f637c5af35e3da4b552f8e1ab0a181cd278a1cefa config.json +217980ab00d116693fa5946df7bbfd967caf5fac1f529afd541fbd470ddb54ee model.safetensors" +docker rm -f "$NAME" > /dev/null 2>&1 || true +# shellcheck disable=SC2086 +exec 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_ARGS diff --git a/recipe/stack/cands/n361-s3b-p/recipe/serve/sl.json b/recipe/stack/cands/n361-s3b-p/recipe/serve/sl.json new file mode 100644 index 0000000000000000000000000000000000000000..000d388661eb28dd6d0f261cd3fcba25a766f223 --- /dev/null +++ b/recipe/stack/cands/n361-s3b-p/recipe/serve/sl.json @@ -0,0 +1 @@ +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 95, 99, 100, 103, 105, 106, 107, 112, 114, 116, 120, 121, 126, 135, 138, 140, 147, 148, 153, 155, 158, 170, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 243, 246, 247, 248, 249, 252, 253, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 286, 289, 290, 291, 292, 293, 295, 296, 297, 300, 301, 302, 304, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 316, 317, 318, 319, 320, 322, 323, 324, 325, 326, 327, 329, 330, 331, 332, 334, 335, 336, 337, 338, 339, 340, 341, 344, 345, 346, 347, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 384, 385, 386, 391, 392, 393, 397, 406, 407, 427, 452, 482, 483, 508, 542, 543, 544, 547, 551, 587, 588, 589, 590, 601, 623, 626, 627, 628, 635, 648, 661, 664, 665, 666, 667, 673, 675, 693, 694, 696, 713, 714, 715, 716, 729, 730, 731, 745, 746, 747, 755, 761, 762, 764, 767, 768, 778, 779, 780, 781, 782, 784, 785, 786, 787, 788, 789, 791, 792, 793, 794, 796, 797, 798, 799, 800, 801, 802, 804, 805, 806, 807, 808, 809, 813, 814, 815, 816, 818, 819, 820, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 834, 835, 837, 838, 839, 840, 842, 845, 846, 848, 849, 850, 852, 853, 854, 855, 856, 861, 862, 863, 864, 865, 866, 867, 868, 869, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 887, 888, 889, 890, 891, 895, 896, 897, 898, 899, 900, 902, 903, 904, 905, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 927, 928, 929, 930, 931, 932, 933, 941, 942, 943, 944, 945, 946, 947, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 970, 971, 976, 977, 978, 979, 981, 982, 983, 984, 985, 986, 987, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1008, 1009, 1010, 1011, 1012, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1082, 1083, 1085, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1118, 1119, 1121, 1122, 1123, 1124, 1125, 1126, 1141, 1142, 1143, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1167, 1168, 1169, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1196, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1223, 1224, 1225, 1226, 1227, 1228, 1229, 1230, 1232, 1233, 1234, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1264, 1265, 1267, 1268, 1269, 1270, 1271, 1272, 1274, 1276, 1277, 1278, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1293, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1339, 1341, 1342, 1343, 1345, 1346, 1347, 1349, 1350, 1353, 1354, 1355, 1356, 1357, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1373, 1374, 1375, 1376, 1377, 1404, 1406, 1407, 1408, 1410, 1411, 1412, 1413, 1414, 1415, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1476, 1477, 1478, 1479, 1481, 1482, 1484, 1485, 1486, 1487, 1488, 1489, 1491, 1492, 1494, 1495, 1496, 1498, 1499, 1500, 1502, 1503, 1504, 1506, 1507, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1539, 1540, 1541, 1542, 1543, 1545, 1546, 1547, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1603, 1604, 1605, 1606, 1607, 1609, 1610, 1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1623, 1624, 1625, 1626, 1628, 1629, 1630, 1631, 1632, 1633, 1635, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1644, 1645, 1647, 1648, 1649, 1651, 1653, 1654, 1655, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1695, 1696, 1697, 1698, 1699, 1700, 1701, 1702, 1703, 1704, 1705, 1707, 1708, 1709, 1711, 1712, 1714, 1715, 1716, 1717, 1719, 1720, 1721, 1725, 1726, 1727, 1728, 1729, 1730, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1744, 1745, 1746, 1747, 1748, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1758, 1759, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1769, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1780, 1781, 1782, 1783, 1784, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1795, 1796, 1798, 1800, 1801, 1802, 1804, 1805, 1807, 1808, 1809, 1810, 1860, 1861, 1862, 1864, 1865, 1866, 1867, 1868, 1869, 1870, 1871, 1872, 1874, 1877, 1879, 1880, 1881, 1884, 1885, 1886, 1887, 1889, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1900, 1901, 1902, 1905, 1906, 1908, 1909, 1910, 1911, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1944, 1945, 1947, 1948, 1950, 1951, 1952, 1953, 1954, 1955, 1957, 1958, 1959, 1961, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1979, 1980, 1982, 1983, 1984, 1986, 1987, 1988, 1989, 1992, 1994, 1995, 1996, 1997, 1998, 2000, 2001, 2003, 2004, 2005, 2006, 2007, 2008, 2083, 2084, 2085, 2086, 2087, 2089, 2090, 2092, 2093, 2095, 2096, 2097, 2098, 2099, 2101, 2103, 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2112, 2113, 2115, 2117, 2118, 2119, 2120, 2121, 2122, 2125, 2126, 2127, 2128, 2129, 2131, 2133, 2134, 2135, 2137, 2138, 2140, 2141, 2143, 2144, 2145, 2146, 2147, 2148, 2149, 2150, 2151, 2152, 2153, 2154, 2156, 2157, 2158, 2160, 2161, 2164, 2165, 2168, 2169, 2170, 2171, 2172, 2174, 2175, 2176, 2177, 2178, 2179, 2181, 2183, 2184, 2186, 2187, 2188, 2191, 2192, 2193, 2194, 2195, 2196, 2197, 2198, 2199, 2200, 2202, 2203, 2204, 2205, 2206, 2207, 2208, 2209, 2210, 2211, 2212, 2213, 2214, 2215, 2217, 2218, 2220, 2221, 2222, 2225, 2226, 2227, 2228, 2229, 2232, 2233, 2234, 2235, 2236, 2237, 2238, 2240, 2241, 2242, 2244, 2247, 2248, 2250, 2251, 2253, 2254, 2255, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2267, 2268, 2269, 2270, 2272, 2273, 2274, 2275, 2276, 2277, 2278, 2280, 2281, 2285, 2286, 2287, 2288, 2289, 2290, 2386, 2387, 2388, 2389, 2390, 2392, 2393, 2394, 2397, 2398, 2399, 2400, 2401, 2402, 2404, 2405, 2407, 2409, 2410, 2411, 2412, 2414, 2419, 2420, 2421, 2423, 2424, 2425, 2426, 2427, 2428, 2429, 2430, 2431, 2432, 2434, 2435, 2436, 2437, 2438, 2439, 2440, 2441, 2443, 2444, 2445, 2446, 2447, 2449, 2450, 2451, 2452, 2453, 2456, 2457, 2458, 2459, 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2469, 2470, 2471, 2472, 2475, 2476, 2477, 2478, 2479, 2480, 2481, 2482, 2484, 2485, 2488, 2489, 2490, 2491, 2492, 2494, 2495, 2496, 2497, 2499, 2502, 2503, 2504, 2505, 2507, 2511, 2512, 2514, 2515, 2516, 2517, 2519, 2520, 2521, 2523, 2525, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2534, 2536, 2537, 2538, 2539, 2540, 2541, 2545, 2546, 2547, 2549, 2550, 2551, 2552, 2553, 2554, 2556, 2557, 2558, 2559, 2560, 2564, 2566, 2567, 2568, 2569, 2571, 2573, 2574, 2577, 2578, 2579, 2582, 2583, 2584, 2585, 2586, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2596, 2598, 2599, 2600, 2601, 2602, 2603, 2604, 2605, 2606, 2608, 2613, 2615, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2623, 2624, 2625, 2627, 2628, 2629, 2633, 2634, 2635, 2636, 2637, 2639, 2641, 2642, 2643, 2644, 2645, 2646, 2647, 2648, 2649, 2650, 2651, 2653, 2655, 2657, 2658, 2660, 2662, 2663, 2664, 2666, 2667, 2668, 2669, 2671, 2673, 2677, 2678, 2681, 2682, 2685, 2686, 2687, 2689, 2690, 2691, 2693, 2697, 2698, 2701, 2702, 2704, 2705, 2706, 2707, 2708, 2709, 2710, 2711, 2713, 2714, 2715, 2716, 2717, 2718, 2720, 2721, 2722, 2723, 2724, 2725, 2727, 2728, 2853, 2855, 2856, 2863, 2864, 2865, 2866, 2872, 2874, 2876, 2877, 2878, 2879, 2881, 2882, 2883, 2884, 2885, 2886, 2887, 2888, 2889, 2890, 2892, 2893, 2894, 2895, 2896, 2897, 2898, 2900, 2901, 2902, 2903, 2905, 2906, 2908, 2910, 2911, 2912, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2926, 2927, 2929, 2931, 2932, 2934, 2935, 2936, 2937, 2938, 2939, 2940, 2941, 2945, 2946, 2947, 2948, 2949, 2951, 2952, 2953, 2955, 2956, 2957, 2959, 2960, 2961, 2962, 2963, 2965, 2967, 2968, 2969, 2970, 2971, 2973, 2974, 2976, 2978, 2979, 2980, 2985, 2986, 2988, 2991, 2992, 2993, 2994, 2995, 2997, 2998, 2999, 3000, 3001, 3002, 3003, 3005, 3006, 3011, 3013, 3014, 3016, 3017, 3018, 3020, 3022, 3023, 3024, 3026, 3028, 3029, 3030, 3031, 3034, 3035, 3036, 3037, 3039, 3040, 3041, 3042, 3043, 3044, 3045, 3046, 3047, 3049, 3050, 3051, 3052, 3053, 3054, 3056, 3058, 3059, 3061, 3062, 3063, 3067, 3068, 3070, 3071, 3072, 3074, 3075, 3077, 3078, 3079, 3081, 3083, 3084, 3085, 3086, 3087, 3088, 3089, 3090, 3091, 3092, 3094, 3095, 3097, 3098, 3102, 3103, 3104, 3105, 3107, 3108, 3109, 3111, 3112, 3113, 3115, 3116, 3117, 3118, 3119, 3120, 3121, 3124, 3125, 3126, 3127, 3129, 3131, 3134, 3135, 3136, 3137, 3138, 3139, 3140, 3142, 3143, 3144, 3145, 3146, 3148, 3149, 3150, 3151, 3153, 3154, 3156, 3158, 3159, 3160, 3163, 3164, 3165, 3168, 3169, 3170, 3172, 3173, 3175, 3176, 3178, 3179, 3181, 3182, 3183, 3186, 3190, 3191, 3192, 3193, 3194, 3195, 3196, 3197, 3198, 3199, 3202, 3203, 3205, 3206, 3207, 3208, 3211, 3213, 3214, 3216, 3217, 3218, 3219, 3220, 3223, 3224, 3226, 3227, 3230, 3231, 3233, 3234, 3236, 3237, 3238, 3240, 3241, 3243, 3244, 3246, 3247, 3249, 3250, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3259, 3260, 3261, 3263, 3264, 3265, 3267, 3268, 3269, 3272, 3274, 3277, 3279, 3281, 3284, 3285, 3286, 3288, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3297, 3300, 3301, 3304, 3307, 3309, 3310, 3311, 3312, 3314, 3316, 3317, 3318, 3319, 3320, 3321, 3323, 3324, 3326, 3328, 3329, 3330, 3331, 3333, 3334, 3335, 3336, 3339, 3340, 3341, 3344, 3345, 3346, 3347, 3349, 3350, 3352, 3353, 3354, 3355, 3356, 3357, 3360, 3364, 3365, 3368, 3369, 3371, 3372, 3373, 3374, 3377, 3378, 3379, 3381, 3383, 3385, 3386, 3387, 3388, 3394, 3396, 3397, 3398, 3401, 3402, 3404, 3405, 3406, 3408, 3413, 3414, 3415, 3416, 3417, 3420, 3421, 3422, 3423, 3426, 3427, 3429, 3430, 3431, 3433, 3435, 3437, 3439, 3440, 3441, 3444, 3445, 3446, 3447, 3448, 3590, 3591, 3593, 3594, 3596, 3598, 3601, 3602, 3605, 3607, 3609, 3613, 3616, 3618, 3620, 3621, 3622, 3623, 3624, 3625, 3626, 3628, 3629, 3630, 3631, 3632, 3633, 3636, 3637, 3638, 3639, 3640, 3641, 3642, 3644, 3646, 3647, 3648, 3651, 3653, 3654, 3655, 3657, 3659, 3660, 3661, 3662, 3665, 3666, 3667, 3668, 3669, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3679, 3680, 3683, 3685, 3687, 3688, 3690, 3691, 3693, 3694, 3695, 3697, 3699, 3701, 3702, 3703, 3704, 3705, 3706, 3709, 3710, 3711, 3712, 3713, 3714, 3715, 3717, 3718, 3719, 3720, 3721, 3723, 3724, 3725, 3726, 3727, 3728, 3729, 3730, 3731, 3734, 3737, 3738, 3740, 3741, 3743, 3744, 3745, 3746, 3747, 3748, 3749, 3754, 3757, 3758, 3759, 3761, 3762, 3764, 3765, 3766, 3767, 3768, 3771, 3772, 3774, 3775, 3776, 3777, 3778, 3780, 3782, 3783, 3784, 3785, 3786, 3787, 3790, 3791, 3794, 3795, 3796, 3797, 3800, 3801, 3802, 3808, 3809, 3811, 3812, 3814, 3815, 3818, 3820, 3821, 3826, 3828, 3829, 3830, 3831, 3832, 3833, 3834, 3835, 3836, 3837, 3838, 3840, 3844, 3846, 3848, 3849, 3850, 3851, 3853, 3854, 3856, 3859, 3861, 3862, 3863, 3864, 3865, 3867, 3869, 3875, 3877, 3880, 3882, 3883, 3884, 3885, 3886, 3888, 3890, 3892, 3895, 3898, 3899, 3900, 3901, 3902, 3904, 3905, 3906, 3907, 3908, 3909, 3910, 3911, 3912, 3913, 3914, 3916, 3917, 3921, 3923, 3928, 3931, 3932, 3934, 3936, 3938, 3941, 3942, 3943, 3944, 3946, 3947, 3948, 3951, 3953, 3954, 3955, 3958, 3959, 3960, 3965, 3966, 3970, 3971, 3972, 3973, 3975, 3977, 3978, 3980, 3981, 3983, 3984, 3985, 3986, 3987, 3989, 3996, 3997, 3998, 4000, 4001, 4002, 4003, 4006, 4008, 4009, 4010, 4011, 4013, 4014, 4017, 4018, 4019, 4023, 4024, 4027, 4028, 4030, 4033, 4034, 4035, 4036, 4043, 4044, 4046, 4047, 4049, 4050, 4051, 4055, 4056, 4058, 4060, 4061, 4062, 4063, 4065, 4066, 4067, 4068, 4069, 4071, 4073, 4076, 4077, 4078, 4079, 4081, 4082, 4094, 4096, 4098, 4100, 4102, 4104, 4105, 4109, 4112, 4113, 4114, 4115, 4116, 4117, 4119, 4121, 4122, 4123, 4124, 4125, 4126, 4127, 4128, 4129, 4131, 4133, 4134, 4135, 4136, 4137, 4138, 4139, 4140, 4142, 4144, 4145, 4148, 4150, 4151, 4152, 4153, 4159, 4161, 4162, 4164, 4165, 4166, 4167, 4169, 4170, 4178, 4179, 4181, 4182, 4183, 4184, 4186, 4188, 4189, 4192, 4195, 4198, 4199, 4200, 4202, 4205, 4207, 4208, 4209, 4210, 4211, 4212, 4219, 4221, 4222, 4226, 4227, 4228, 4230, 4231, 4232, 4235, 4237, 4239, 4240, 4242, 4245, 4246, 4247, 4249, 4250, 4251, 4252, 4253, 4255, 4256, 4257, 4258, 4259, 4260, 4261, 4262, 4266, 4267, 4268, 4269, 4270, 4271, 4274, 4275, 4276, 4277, 4280, 4282, 4284, 4290, 4294, 4295, 4297, 4298, 4300, 4302, 4303, 4304, 4306, 4307, 4308, 4309, 4311, 4312, 4313, 4315, 4318, 4321, 4323, 4324, 4326, 4329, 4331, 4332, 4334, 4338, 4339, 4341, 4343, 4344, 4345, 4348, 4350, 4352, 4356, 4357, 4361, 4362, 4364, 4366, 4367, 4373, 4374, 4376, 4377, 4381, 4385, 4387, 4388, 4389, 4390, 4392, 4393, 4395, 4396, 4400, 4401, 4402, 4405, 4406, 4407, 4411, 4412, 4413, 4414, 4415, 4419, 4421, 4424, 4427, 4428, 4429, 4435, 4436, 4437, 4438, 4440, 4444, 4446, 4447, 4452, 4454, 4457, 4458, 4459, 4460, 4462, 4465, 4471, 4473, 4474, 4475, 4476, 4477, 4481, 4486, 4487, 4489, 4491, 4492, 4493, 4495, 4496, 4499, 4501, 4504, 4505, 4506, 4508, 4510, 4512, 4513, 4518, 4519, 4522, 4528, 4529, 4534, 4535, 4539, 4542, 4547, 4548, 4550, 4553, 4554, 4556, 4557, 4559, 4560, 4561, 4562, 4567, 4568, 4570, 4574, 4575, 4576, 4580, 4581, 4582, 4586, 4588, 4589, 4590, 4591, 4592, 4593, 4597, 4598, 4601, 4602, 4603, 4604, 4605, 4607, 4609, 4611, 4616, 4617, 4618, 4621, 4622, 4625, 4627, 4628, 4630, 4631, 4632, 4633, 4637, 4640, 4643, 4646, 4649, 4652, 4655, 4656, 4658, 4660, 4662, 4663, 4665, 4666, 4670, 4673, 4675, 4676, 4679, 4681, 4684, 4685, 4686, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4698, 4700, 4701, 4702, 4704, 4706, 4708, 4709, 4710, 4711, 4713, 4714, 4717, 4718, 4721, 4724, 4725, 4729, 4732, 4735, 4739, 4740, 4741, 4743, 4744, 4745, 4746, 4750, 4752, 4753, 4754, 4756, 4757, 4758, 4759, 4760, 4765, 4766, 4768, 4770, 4773, 4775, 4777, 4780, 4783, 4786, 4787, 4788, 4789, 4792, 4794, 4795, 4799, 4801, 4802, 4803, 4804, 4806, 4808, 4809, 4813, 4814, 4816, 4820, 4822, 4823, 4824, 4826, 4828, 4830, 4831, 4832, 4833, 4835, 4836, 4838, 4840, 4841, 4844, 4845, 4846, 4847, 4848, 4851, 4852, 4854, 4855, 4856, 4861, 4862, 4865, 4867, 4869, 4870, 4871, 4873, 4875, 4877, 4879, 4881, 4882, 4886, 4887, 4890, 4893, 4894, 4896, 4898, 4901, 4902, 4903, 4904, 4905, 4907, 4910, 4912, 4913, 4914, 4915, 4917, 4918, 4920, 4924, 4925, 4927, 4928, 4929, 4930, 4931, 4932, 4935, 4938, 4939, 4940, 4941, 4943, 4944, 4945, 4946, 4947, 4949, 4950, 4953, 4958, 4959, 4960, 4963, 4964, 4967, 4970, 4972, 4973, 4975, 4976, 4982, 4983, 4985, 4987, 4988, 4989, 4992, 4993, 4995, 4996, 5001, 5005, 5006, 5008, 5009, 5010, 5013, 5014, 5017, 5126, 5127, 5128, 5129, 5130, 5131, 5132, 5133, 5134, 5135, 5136, 5137, 5140, 5141, 5142, 5143, 5144, 5145, 5146, 5147, 5149, 5150, 5151, 5152, 5154, 5155, 5156, 5157, 5158, 5159, 5162, 5163, 5164, 5165, 5166, 5167, 5168, 5169, 5170, 5171, 5172, 5173, 5174, 5175, 5176, 5177, 5179, 5180, 5181, 5182, 5184, 5186, 5187, 5188, 5189, 5190, 5191, 5193, 5194, 5195, 5197, 5199, 5201, 5205, 5209, 5210, 5211, 5212, 5213, 5215, 5216, 5218, 5219, 5263, 5266, 5267, 5284, 5306, 5312, 5331, 5332, 5393, 5396, 5397, 5398, 5399, 5400, 5401, 5402, 5406, 5409, 5410, 5411, 5412, 5413, 5414, 5415, 5416, 5417, 5418, 5419, 5420, 5421, 5422, 5423, 5424, 5425, 5426, 5427, 5429, 5430, 5434, 5438, 5439, 5440, 5441, 5442, 5443, 5444, 5445, 5446, 5447, 5449, 5450, 5451, 5452, 5453, 5454, 5455, 5456, 5457, 5458, 5459, 5460, 5461, 5462, 5463, 5464, 5465, 5466, 5468, 5469, 5470, 5471, 5472, 5473, 5475, 5476, 5477, 5478, 5479, 5485, 5487, 5527, 5621, 5623, 5625, 5626, 5628, 5629, 5630, 5631, 5632, 5633, 5634, 5635, 5636, 5637, 5638, 5639, 5640, 5641, 5642, 5643, 5644, 5645, 5646, 5648, 5650, 5651, 5652, 5653, 5654, 5655, 5656, 5657, 5760, 6276, 6282, 6300, 6303, 6343, 6347, 6352, 6360, 6376, 6378, 6390, 6392, 6393, 6397, 6398, 6448, 6449, 6528, 6586, 6632, 6633, 6647, 6732, 6949, 8625, 8695, 8876, 8879, 9199, 9611, 9889, 9932, 9934, 9935, 10243, 10248, 10400, 10638, 11389, 11874, 12135, 12446, 12599, 12688, 13298, 13474, 13736, 14792, 15088, 15115, 15181, 15515, 15737, 15809, 15815, 16729, 16772, 16794, 17145, 17291, 17619, 17789, 18097, 18128, 18670, 18727, 18807, 18808, 19282, 19433, 19777, 20597, 20598, 20599, 20600, 20742, 21029, 21373, 21409, 22177, 22178, 22718, 23032, 23033, 23037, 23048, 23056, 23058, 23059, 23063, 23064, 23065, 23067, 23068, 23069, 23071, 23107, 23172, 23289, 23678, 23824, 23996, 24293, 24620, 24641, 25173, 25208, 25638, 25650, 25671, 25754, 25758, 25762, 25763, 25764, 25767, 25769, 25770, 25777, 25783, 25846, 25849, 25850, 25852, 25856, 25858, 25860, 25861, 25864, 25867, 25871, 25874, 25876, 25883, 25884, 25886, 25893, 25894, 25898, 25905, 25906, 25914, 25915, 25917, 25922, 25924, 25927, 25960, 25965, 25966, 25968, 25975, 25984, 25994, 25995, 25996, 25998, 26001, 26007, 26012, 26013, 26014, 26017, 26020, 26022, 26024, 26027, 26031, 26032, 26039, 26046, 26047, 26049, 26050, 26053, 26058, 26059, 26060, 26116, 26119, 26124, 26126, 26127, 26134, 26137, 26139, 26140, 26191, 26194, 26195, 26196, 26199, 26200, 26205, 26206, 26209, 26210, 26218, 26221, 26222, 26224, 26225, 26228, 26229, 26232, 26234, 26276, 26283, 26316, 26318, 26322, 26326, 26329, 26333, 26334, 26342, 26343, 26353, 26355, 26356, 26357, 26360, 26364, 26365, 26370, 26378, 26389, 26390, 26393, 26396, 26444, 26460, 26467, 26487, 26488, 26497, 26501, 26510, 26511, 26514, 26516, 26519, 26523, 26524, 26528, 26529, 26530, 26555, 26560, 26564, 26566, 26569, 26570, 26571, 26575, 26578, 26580, 26589, 26594, 26595, 26597, 26601, 26609, 26622, 26629, 26631, 26642, 26656, 26719, 26727, 26729, 26733, 26748, 26750, 26757, 26762, 26764, 26767, 26773, 26790, 26792, 26821, 26833, 26835, 26840, 26842, 26850, 26872, 26879, 26962, 26963, 26965, 26968, 26971, 26972, 26973, 26975, 26979, 26984, 26994, 26996, 27001, 27004, 27019, 27021, 27023, 27040, 27042, 27057, 27061, 27063, 27064, 27065, 27066, 27068, 27071, 27072, 27092, 27096, 27100, 27103, 27104, 27105, 27111, 27114, 27118, 27131, 27132, 27135, 27140, 27142, 27150, 27151, 27153, 27205, 27206, 27210, 27212, 27219, 27221, 27240, 27254, 27255, 27258, 27330, 27332, 27364, 27374, 27377, 27379, 27387, 27390, 27393, 27395, 27405, 27406, 27407, 27410, 27415, 27427, 27429, 27434, 27443, 27447, 27449, 27459, 27463, 27465, 27467, 27470, 27481, 27531, 27535, 27556, 27558, 27559, 27568, 27569, 27571, 27572, 27580, 27581, 27582, 27584, 27587, 27591, 27596, 27597, 27606, 27607, 27612, 27620, 27629, 27630, 27637, 27641, 27644, 27648, 27650, 27655, 27659, 27660, 27662, 27675, 27772, 27776, 27784, 27786, 27789, 27791, 27792, 27796, 27801, 27807, 27816, 27824, 27826, 27834, 27835, 27839, 27843, 27851, 27930, 27931, 27932, 27968, 27984, 27999, 28000, 28002, 28008, 28020, 28042, 28043, 28055, 28057, 28059, 28072, 28076, 28077, 28078, 28079, 28080, 28085, 28087, 28236, 28260, 28273, 28279, 28286, 28290, 28291, 28478, 28493, 28494, 28499, 28500, 28502, 28503, 28505, 28507, 28511, 28516, 28520, 28522, 28526, 28527, 28528, 28530, 28531, 28559, 28562, 28572, 28578, 28580, 28581, 28731, 28733, 28742, 28745, 28747, 28760, 28761, 28767, 28785, 28792, 28795, 28813, 28977, 28978, 28983, 28988, 28996, 28998, 29000, 29176, 29177, 29188, 29191, 29200, 29201, 29205, 29209, 29477, 29806, 29821, 29823, 29824, 29825, 29827, 30148, 30153, 30717, 30718, 30720, 30726, 30730, 30733, 30734, 30735, 30737, 30739, 30740, 30743, 30746, 30751, 30753, 30760, 30761, 30762, 30767, 30769, 30770, 30771, 30773, 30774, 30775, 30776, 30777, 30778, 30780, 30781, 30782, 30789, 30790, 30791, 30793, 30794, 30796, 30797, 30799, 30800, 30801, 30804, 30805, 30806, 30807, 30810, 30811, 30813, 30817, 30818, 30823, 30825, 30826, 30831, 30836, 30837, 30843, 30845, 30848, 30854, 30856, 30864, 30866, 30868, 30870, 30872, 30874, 30880, 30881, 30883, 30886, 30888, 30890, 30892, 30896, 30897, 30898, 30899, 30900, 30904, 30905, 30907, 30911, 30912, 30913, 30920, 30921, 30922, 30924, 30925, 30926, 30927, 30929, 30930, 30931, 30932, 30937, 30938, 30939, 30940, 30941, 30942, 30943, 30944, 30948, 30952, 30953, 30954, 30956, 30958, 30961, 30962, 30964, 30966, 30969, 30970, 30971, 30976, 30977, 30978, 30979, 30983, 30984, 30985, 30986, 30989, 30992, 30993, 30997, 30998, 31000, 31001, 31005, 31007, 31008, 31010, 31013, 31016, 31021, 31022, 31028, 31029, 31031, 31036, 31037, 31038, 31039, 31040, 31042, 31047, 31050, 31051, 31054, 31055, 31058, 31063, 31065, 31070, 31073, 31074, 31077, 31082, 31083, 31085, 31087, 31095, 31096, 31097, 31098, 31100, 31101, 31102, 31103, 31107, 31109, 31110, 31111, 31116, 31118, 31123, 31126, 31130, 31131, 31132, 31136, 31137, 31139, 31140, 31141, 31142, 31144, 31145, 31146, 31147, 31148, 31151, 31152, 31153, 31154, 31156, 31158, 31167, 31169, 31173, 31174, 31175, 31176, 31177, 31182, 31183, 31187, 31188, 31197, 31201, 31206, 31207, 31211, 31214, 31216, 31218, 31220, 31224, 31226, 31229, 31230, 31233, 31235, 31237, 31239, 31240, 31244, 31245, 31246, 31247, 31248, 31252, 31255, 31258, 31260, 31261, 31262, 31264, 31270, 31271, 31272, 31274, 31275, 31277, 31281, 31283, 31285, 31288, 31289, 31290, 31291, 31294, 31303, 31304, 31306, 31310, 31312, 31313, 31316, 31317, 31318, 31319, 31320, 31321, 31324, 31329, 31330, 31332, 31333, 31335, 31337, 31339, 31340, 31341, 31342, 31344, 31346, 31349, 31351, 31354, 31357, 31358, 31361, 31363, 31365, 31366, 31372, 31373, 31376, 31379, 31380, 31382, 31383, 31384, 31385, 31387, 31390, 31398, 31399, 31402, 31405, 31406, 31408, 31409, 31410, 31413, 31417, 31419, 31421, 31422, 31424, 31434, 31436, 31441, 31442, 31446, 31448, 31449, 31450, 31451, 31454, 31455, 31456, 31457, 31461, 31462, 31463, 31466, 31469, 31474, 31478, 31479, 31480, 31483, 31484, 31485, 31491, 31492, 31495, 31496, 31500, 31501, 31502, 31506, 31507, 31508, 31510, 31512, 31514, 31515, 31519, 31520, 31524, 31527, 31529, 31530, 31531, 31532, 31534, 31537, 31538, 31543, 31555, 31559, 31563, 31567, 31576, 31577, 31578, 31579, 31581, 31588, 31589, 31591, 31593, 31594, 31596, 31597, 31598, 31602, 31603, 31609, 31611, 31614, 31616, 31617, 31621, 31628, 31629, 31633, 31635, 31637, 31639, 31640, 31641, 31642, 31643, 31645, 31648, 31651, 31652, 31654, 31655, 31657, 31658, 31662, 31663, 31664, 31665, 31666, 31667, 31669, 31671, 31674, 31675, 31676, 31677, 31678, 31680, 31681, 31685, 31686, 31687, 31693, 31701, 31704, 31707, 31708, 31712, 31713, 31717, 31719, 31720, 31721, 31722, 31723, 31724, 31730, 31731, 31734, 31736, 31743, 31744, 31745, 31746, 31749, 31751, 31752, 31753, 31755, 31757, 31758, 31765, 31766, 31770, 31777, 31779, 31780, 31785, 31789, 31793, 31794, 31795, 31796, 31797, 31800, 31801, 31802, 31803, 31804, 31808, 31816, 31818, 31820, 31823, 31824, 31830, 31832, 31834, 31836, 31839, 31841, 31844, 31847, 31848, 31850, 31852, 31853, 31855, 31856, 31858, 31860, 31862, 31863, 31864, 31865, 31872, 31873, 31876, 31877, 31880, 31883, 31884, 31885, 31887, 31890, 31891, 31894, 31897, 31899, 31900, 31901, 31903, 31904, 31907, 31908, 31909, 31914, 31916, 31917, 31922, 31925, 31926, 31927, 31929, 31930, 31931, 31932, 31933, 31935, 31936, 31937, 31939, 31940, 31941, 31943, 31945, 31946, 31948, 31949, 31952, 31954, 31956, 31958, 31963, 31970, 31973, 31976, 31979, 31980, 31983, 31993, 31995, 31997, 31998, 32002, 32006, 32008, 32009, 32010, 32011, 32013, 32014, 32016, 32020, 32022, 32030, 32031, 32033, 32037, 32038, 32040, 32042, 32044, 32046, 32050, 32054, 32055, 32056, 32059, 32062, 32065, 32069, 32080, 32084, 32086, 32087, 32088, 32089, 32090, 32100, 32103, 32113, 32120, 32124, 32127, 32130, 32132, 32135, 32136, 32140, 32144, 32152, 32153, 32156, 32160, 32165, 32166, 32167, 32168, 32175, 32176, 32178, 32180, 32181, 32183, 32185, 32187, 32188, 32189, 32191, 32195, 32196, 32198, 32199, 32201, 32202, 32203, 32205, 32207, 32212, 32213, 32215, 32217, 32218, 32222, 32223, 32230, 32234, 32235, 32241, 32248, 32251, 32253, 32254, 32257, 32263, 32264, 32267, 32268, 32269, 32271, 32272, 32275, 32277, 32278, 32280, 32281, 32282, 32283, 32285, 32291, 32296, 32297, 32302, 32305, 32307, 32310, 32312, 32314, 32315, 32316, 32317, 32318, 32321, 32323, 32325, 32326, 32327, 32329, 32330, 32334, 32335, 32336, 32337, 32338, 32340, 32341, 32342, 32343, 32346, 32348, 32351, 32352, 32354, 32358, 32359, 32362, 32367, 32375, 32378, 32381, 32385, 32386, 32389, 32390, 32391, 32392, 32393, 32394, 32395, 32400, 32402, 32403, 32406, 32408, 32412, 32413, 32416, 32421, 32422, 32426, 32428, 32431, 32433, 32434, 32438, 32441, 32442, 32443, 32445, 32447, 32449, 32450, 32452, 32456, 32457, 32461, 32462, 32478, 32483, 32487, 32488, 32493, 32494, 32495, 32496, 32497, 32498, 32500, 32505, 32511, 32512, 32519, 32520, 32524, 32526, 32528, 32529, 32530, 32532, 32534, 32536, 32538, 32541, 32543, 32549, 32552, 32553, 32559, 32561, 32563, 32565, 32568, 32571, 32574, 32576, 32578, 32579, 32583, 32584, 32585, 32586, 32587, 32588, 32594, 32602, 32607, 32610, 32611, 32614, 32615, 32617, 32620, 32622, 32629, 32630, 32634, 32637, 32639, 32644, 32647, 32648, 32649, 32651, 32652, 32653, 32654, 32656, 32657, 32660, 32661, 32667, 32668, 32669, 32671, 32673, 32681, 32685, 32690, 32691, 32692, 32693, 32696, 32697, 32699, 32701, 32707, 32714, 32717, 32725, 32726, 32727, 32732, 32736, 32740, 32742, 32743, 32744, 32751, 32752, 32753, 32760, 32765, 32767, 32769, 32771, 32773, 32774, 32783, 32785, 32787, 32789, 32791, 32792, 32793, 32796, 32798, 32799, 32800, 32801, 32802, 32803, 32804, 32805, 32806, 32808, 32810, 32811, 32813, 32825, 32827, 32835, 32838, 32841, 32843, 32846, 32849, 32850, 32852, 32853, 32858, 32863, 32864, 32866, 32875, 32877, 32879, 32886, 32891, 32895, 32896, 32898, 32902, 32907, 32910, 32911, 32912, 32916, 32917, 32920, 32924, 32925, 32929, 32930, 32937, 32942, 32943, 32945, 32946, 32948, 32953, 32954, 32955, 32958, 32959, 32961, 32962, 32965, 32966, 32971, 32975, 32978, 32981, 32984, 32989, 32990, 32993, 32995, 32997, 33001, 33004, 33005, 33013, 33019, 33023, 33024, 33030, 33031, 33032, 33033, 33034, 33036, 33037, 33039, 33042, 33043, 33044, 33045, 33048, 33049, 33050, 33052, 33059, 33062, 33065, 33072, 33074, 33076, 33077, 33078, 33079, 33080, 33082, 33084, 33087, 33090, 33092, 33094, 33096, 33097, 33098, 33099, 33101, 33104, 33110, 33111, 33114, 33117, 33118, 33120, 33122, 33126, 33127, 33129, 33131, 33132, 33133, 33134, 33139, 33142, 33146, 33150, 33151, 33152, 33153, 33155, 33156, 33158, 33161, 33163, 33164, 33167, 33168, 33174, 33178, 33179, 33184, 33185, 33186, 33189, 33194, 33196, 33201, 33205, 33207, 33208, 33209, 33213, 33214, 33216, 33217, 33221, 33225, 33226, 33228, 33230, 33234, 33236, 33237, 33242, 33243, 33245, 33246, 33247, 33251, 33256, 33258, 33259, 33261, 33263, 33265, 33268, 33272, 33274, 33275, 33285, 33287, 33289, 33293, 33295, 33297, 33300, 33301, 33302, 33304, 33305, 33306, 33307, 33310, 33311, 33315, 33316, 33320, 33322, 33324, 33326, 33329, 33330, 33333, 33334, 33335, 33337, 33338, 33339, 33340, 33341, 33342, 33346, 33347, 33348, 33351, 33352, 33353, 33359, 33367, 33370, 33376, 33378, 33380, 33381, 33382, 33385, 33386, 33391, 33394, 33395, 33396, 33398, 33401, 33405, 33408, 33415, 33419, 33420, 33421, 33424, 33427, 33430, 33432, 33437, 33441, 33443, 33444, 33445, 33452, 33460, 33466, 33467, 33469, 33471, 33472, 33484, 33490, 33492, 33497, 33499, 33500, 33501, 33509, 33510, 33512, 33513, 33516, 33517, 33519, 33526, 33528, 33529, 33530, 33537, 33538, 33542, 33544, 33550, 33551, 33555, 33558, 33561, 33562, 33563, 33564, 33567, 33568, 33570, 33572, 33575, 33579, 33580, 33581, 33585, 33588, 33589, 33593, 33594, 33596, 33599, 33603, 33607, 33608, 33609, 33610, 33612, 33614, 33619, 33620, 33622, 33627, 33632, 33634, 33641, 33645, 33646, 33647, 33649, 33652, 33655, 33659, 33661, 33663, 33664, 33668, 33670, 33673, 33676, 33678, 33682, 33683, 33684, 33688, 33695, 33697, 33707, 33709, 33715, 33719, 33721, 33724, 33731, 33733, 33739, 33741, 33742, 33746, 33748, 33749, 33752, 33754, 33756, 33759, 33764, 33765, 33770, 33772, 33773, 33774, 33779, 33780, 33782, 33783, 33784, 33794, 33797, 33800, 33803, 33807, 33808, 33818, 33821, 33825, 33835, 33836, 33838, 33839, 33840, 33841, 33843, 33845, 33846, 33847, 33849, 33851, 33859, 33860, 33872, 33873, 33874, 33875, 33879, 33881, 33883, 33887, 33889, 33897, 33898, 33899, 33902, 33904, 33909, 33911, 33912, 33914, 33921, 33922, 33923, 33925, 33929, 33937, 33938, 33940, 33943, 33948, 33949, 33951, 33952, 33956, 33957, 33966, 33967, 33970, 33974, 33975, 33976, 33979, 33981, 33983, 33985, 33989, 33991, 33992, 33994, 33997, 34002, 34004, 34007, 34008, 34011, 34017, 34018, 34020, 34021, 34023, 34025, 34026, 34029, 34031, 34032, 34034, 34036, 34037, 34038, 34040, 34042, 34045, 34053, 34055, 34056, 34058, 34061, 34062, 34072, 34074, 34075, 34078, 34079, 34081, 34086, 34091, 34092, 34097, 34102, 34105, 34106, 34108, 34110, 34117, 34125, 34127, 34129, 34131, 34132, 34134, 34137, 34138, 34139, 34140, 34143, 34146, 34147, 34149, 34152, 34154, 34156, 34157, 34159, 34160, 34161, 34163, 34168, 34169, 34171, 34172, 34173, 34175, 34180, 34184, 34187, 34188, 34195, 34197, 34203, 34205, 34207, 34210, 34213, 34214, 34219, 34222, 34225, 34227, 34232, 34234, 34235, 34242, 34243, 34245, 34246, 34248, 34250, 34251, 34253, 34258, 34259, 34261, 34265, 34267, 34268, 34277, 34278, 34281, 34282, 34288, 34290, 34293, 34297, 34298, 34301, 34305, 34309, 34310, 34311, 34314, 34315, 34318, 34322, 34324, 34326, 34331, 34332, 34336, 34337, 34338, 34346, 34347, 34348, 34353, 34358, 34361, 34364, 34365, 34367, 34371, 34372, 34373, 34380, 34388, 34389, 34390, 34391, 34392, 34395, 34397, 34398, 34401, 34403, 34405, 34410, 34413, 34417, 34418, 34421, 34431, 34437, 34438, 34441, 34444, 34454, 34458, 34459, 34464, 34469, 34472, 34475, 34476, 34479, 34481, 34484, 34490, 34491, 34496, 34498, 34499, 34504, 34512, 34516, 34519, 34521, 34524, 34525, 34526, 34529, 34532, 34534, 34538, 34539, 34540, 34545, 34549, 34551, 34555, 34557, 34558, 34560, 34563, 34565, 34569, 34572, 34579, 34580, 34584, 34588, 34594, 34604, 34609, 34612, 34613, 34618, 34619, 34621, 34624, 34632, 34638, 34643, 34644, 34645, 34647, 34656, 34657, 34658, 34659, 34669, 34672, 34673, 34676, 34677, 34679, 34680, 34681, 34687, 34691, 34692, 34694, 34703, 34704, 34706, 34707, 34716, 34720, 34721, 34722, 34724, 34731, 34733, 34737, 34743, 34745, 34746, 34747, 34749, 34750, 34751, 34752, 34759, 34761, 34765, 34766, 34769, 34771, 34772, 34775, 34777, 34780, 34784, 34785, 34786, 34787, 34789, 34795, 34798, 34799, 34802, 34805, 34807, 34809, 34816, 34817, 34827, 34829, 34836, 34838, 34840, 34842, 34843, 34844, 34847, 34851, 34852, 34856, 34859, 34860, 34861, 34872, 34875, 34878, 34885, 34886, 34892, 34895, 34896, 34905, 34907, 34913, 34914, 34915, 34919, 34921, 34924, 34930, 34931, 34934, 34937, 34938, 34940, 34946, 34949, 34954, 34955, 34956, 34963, 34964, 34966, 34967, 34968, 34972, 34974, 34981, 34984, 34986, 34987, 34989, 34992, 35001, 35003, 35007, 35013, 35017, 35025, 35028, 35029, 35034, 35037, 35042, 35047, 35051, 35056, 35057, 35060, 35061, 35065, 35066, 35067, 35070, 35074, 35080, 35081, 35087, 35089, 35091, 35094, 35095, 35101, 35104, 35108, 35110, 35111, 35114, 35125, 35126, 35128, 35130, 35131, 35132, 35134, 35138, 35141, 35145, 35147, 35151, 35155, 35156, 35165, 35166, 35167, 35173, 35176, 35177, 35178, 35179, 35187, 35190, 35194, 35196, 35197, 35201, 35204, 35206, 35213, 35218, 35222, 35224, 35230, 35231, 35240, 35241, 35245, 35247, 35250, 35252, 35255, 35258, 35259, 35264, 35269, 35271, 35275, 35276, 35277, 35282, 35286, 35287, 35288, 35290, 35297, 35298, 35299, 35306, 35310, 35312, 35314, 35317, 35320, 35322, 35323, 35328, 35329, 35336, 35338, 35346, 35351, 35353, 35356, 35357, 35359, 35360, 35369, 35370, 35374, 35376, 35381, 35384, 35386, 35391, 35393, 35394, 35397, 35399, 35400, 35402, 35404, 35407, 35414, 35419, 35422, 35426, 35427, 35429, 35430, 35432, 35438, 35444, 35459, 35461, 35472, 35496, 35499, 35505, 35510, 35515, 35517, 35518, 35519, 35521, 35534, 35535, 35542, 35543, 35544, 35549, 35550, 35551, 35560, 35562, 35568, 35570, 35572, 35573, 35575, 35582, 35588, 35589, 35590, 35591, 35596, 35597, 35598, 35599, 35603, 35605, 35606, 35609, 35610, 35612, 35617, 35621, 35630, 35631, 35643, 35646, 35647, 35653, 35661, 35663, 35664, 35665, 35666, 35668, 35678, 35680, 35683, 35684, 35711, 35714, 35721, 35725, 35733, 35736, 35739, 35740, 35745, 35750, 35752, 35755, 35757, 35758, 35759, 35764, 35765, 35767, 35771, 35774, 35775, 35777, 35782, 35789, 35790, 35795, 35800, 35803, 35807, 35808, 35812, 35818, 35820, 35821, 35822, 35823, 35825, 35831, 35832, 35837, 35838, 35841, 35846, 35851, 35861, 35863, 35864, 35866, 35867, 35869, 35873, 35874, 35875, 35877, 35880, 35884, 35892, 35894, 35899, 35900, 35904, 35906, 35908, 35909, 35913, 35917, 35918, 35922, 35924, 35926, 35931, 35933, 35936, 35938, 35947, 35957, 35958, 35960, 35961, 35964, 35967, 35971, 35976, 35978, 35979, 35981, 35986, 35989, 35993, 36002, 36004, 36005, 36008, 36009, 36010, 36018, 36020, 36021, 36024, 36026, 36029, 36031, 36033, 36035, 36036, 36037, 36043, 36044, 36050, 36057, 36061, 36068, 36071, 36074, 36075, 36079, 36080, 36081, 36088, 36096, 36099, 36104, 36105, 36107, 36109, 36111, 36112, 36115, 36121, 36122, 36131, 36138, 36139, 36140, 36142, 36145, 36148, 36149, 36160, 36172, 36174, 36180, 36191, 36198, 36204, 36211, 36217, 36218, 36221, 36228, 36229, 36230, 36235, 36236, 36238, 36248, 36252, 36256, 36260, 36264, 36269, 36274, 36277, 36286, 36289, 36290, 36294, 36299, 36305, 36306, 36309, 36318, 36324, 36325, 36326, 36332, 36337, 36340, 36346, 36351, 36352, 36362, 36365, 36372, 36374, 36382, 36387, 36391, 36398, 36403, 36404, 36405, 36406, 36408, 36409, 36413, 36416, 36417, 36418, 36420, 36421, 36425, 36432, 36435, 36437, 36440, 36444, 36445, 36446, 36448, 36450, 36458, 36460, 36461, 36463, 36466, 36477, 36483, 36488, 36492, 36500, 36504, 36505, 36506, 36507, 36509, 36515, 36519, 36521, 36523, 36529, 36536, 36538, 36542, 36546, 36547, 36552, 36553, 36556, 36557, 36561, 36563, 36567, 36575, 36579, 36586, 36592, 36595, 36602, 36603, 36606, 36608, 36610, 36621, 36622, 36633, 36638, 36639, 36640, 36642, 36643, 36646, 36650, 36651, 36655, 36656, 36660, 36672, 36673, 36680, 36687, 36689, 36690, 36692, 36699, 36705, 36707, 36711, 36716, 36718, 36721, 36723, 36735, 36742, 36749, 36756, 36757, 36760, 36763, 36765, 36766, 36770, 36771, 36778, 36785, 36787, 36788, 36789, 36791, 36794, 36800, 36801, 36802, 36810, 36813, 36818, 36819, 36822, 36830, 36835, 36836, 36842, 36854, 36858, 36860, 36861, 36864, 36865, 36867, 36877, 36879, 36893, 36898, 36901, 36904, 36905, 36909, 36911, 36912, 36919, 36925, 36930, 36931, 36933, 36940, 36950, 36952, 36954, 36958, 36962, 36967, 36970, 36972, 36973, 36974, 36977, 36984, 36988, 36990, 36995, 37005, 37009, 37013, 37020, 37024, 37025, 37032, 37035, 37036, 37039, 37044, 37045, 37049, 37051, 37057, 37065, 37066, 37084, 37087, 37090, 37096, 37101, 37105, 37109, 37114, 37118, 37122, 37141, 37150, 37154, 37159, 37161, 37168, 37169, 37171, 37175, 37182, 37187, 37194, 37197, 37198, 37204, 37212, 37224, 37225, 37237, 37238, 37240, 37241, 37249, 37260, 37265, 37273, 37277, 37278, 37281, 37288, 37289, 37291, 37293, 37303, 37310, 37313, 37315, 37317, 37319, 37326, 37329, 37352, 37364, 37369, 37372, 37373, 37384, 37385, 37389, 37391, 37395, 37397, 37403, 37407, 37409, 37411, 37414, 37415, 37421, 37424, 37431, 37436, 37438, 37441, 37442, 37444, 37451, 37453, 37456, 37458, 37459, 37463, 37469, 37472, 37474, 37475, 37477, 37479, 37482, 37485, 37490, 37495, 37499, 37507, 37508, 37509, 37520, 37524, 37528, 37536, 37538, 37545, 37547, 37548, 37549, 37553, 37560, 37562, 37563, 37567, 37569, 37574, 37575, 37576, 37583, 37586, 37588, 37589, 37597, 37609, 37615, 37616, 37621, 37622, 37626, 37628, 37629, 37631, 37637, 37639, 37640, 37643, 37653, 37657, 37659, 37665, 37666, 37674, 37677, 37679, 37681, 37682, 37688, 37690, 37694, 37700, 37701, 37703, 37705, 37706, 37710, 37711, 37712, 37713, 37719, 37720, 37732, 37739, 37741, 37743, 37749, 37753, 37755, 37756, 37757, 37758, 37761, 37768, 37773, 37780, 37781, 37783, 37785, 37791, 37793, 37800, 37811, 37813, 37822, 37831, 37832, 37833, 37842, 37843, 37851, 37853, 37857, 37858, 37859, 37860, 37866, 37868, 37869, 37872, 37877, 37882, 37890, 37894, 37895, 37899, 37903, 37904, 37909, 37910, 37929, 37930, 37933, 37935, 37936, 37941, 37944, 37950, 37961, 37962, 37963, 37975, 37976, 37980, 37982, 37984, 37987, 37989, 37997, 38002, 38012, 38017, 38019, 38026, 38033, 38035, 38038, 38052, 38053, 38057, 38059, 38068, 38070, 38075, 38083, 38091, 38097, 38100, 38110, 38113, 38114, 38127, 38130, 38140, 38143, 38148, 38154, 38155, 38163, 38175, 38179, 38180, 38181, 38182, 38183, 38184, 38186, 38192, 38194, 38197, 38200, 38204, 38206, 38210, 38219, 38220, 38224, 38225, 38233, 38235, 38240, 38247, 38249, 38250, 38251, 38254, 38256, 38257, 38258, 38260, 38261, 38263, 38265, 38266, 38276, 38279, 38287, 38291, 38293, 38297, 38302, 38307, 38309, 38311, 38313, 38314, 38315, 38316, 38323, 38329, 38332, 38333, 38337, 38338, 38339, 38341, 38352, 38356, 38368, 38369, 38370, 38374, 38375, 38384, 38391, 38392, 38398, 38399, 38401, 38417, 38418, 38426, 38432, 38443, 38445, 38447, 38451, 38454, 38461, 38462, 38467, 38482, 38507, 38512, 38514, 38522, 38525, 38528, 38534, 38536, 38537, 38539, 38540, 38542, 38545, 38547, 38548, 38552, 38554, 38559, 38565, 38566, 38577, 38578, 38592, 38600, 38601, 38604, 38611, 38613, 38622, 38625, 38637, 38639, 38643, 38649, 38653, 38655, 38664, 38666, 38668, 38670, 38674, 38677, 38679, 38681, 38686, 38692, 38696, 38697, 38698, 38705, 38707, 38713, 38715, 38716, 38722, 38724, 38729, 38739, 38740, 38744, 38749, 38759, 38760, 38769, 38772, 38777, 38778, 38796, 38801, 38802, 38807, 38808, 38813, 38828, 38834, 38837, 38838, 38840, 38846, 38853, 38856, 38857, 38858, 38862, 38872, 38874, 38879, 38891, 38892, 38894, 38898, 38902, 38918, 38919, 38922, 38926, 38935, 38937, 38943, 38949, 38953, 38959, 38968, 38970, 38974, 38978, 38983, 38985, 38986, 38993, 38997, 39000, 39002, 39004, 39007, 39009, 39010, 39015, 39018, 39019, 39020, 39026, 39037, 39039, 39044, 39052, 39060, 39067, 39068, 39078, 39081, 39082, 39085, 39086, 39091, 39093, 39098, 39099, 39103, 39107, 39109, 39110, 39114, 39115, 39117, 39118, 39119, 39125, 39130, 39134, 39135, 39155, 39158, 39159, 39161, 39163, 39165, 39166, 39167, 39171, 39176, 39184, 39187, 39192, 39194, 39200, 39203, 39205, 39209, 39214, 39222, 39223, 39227, 39233, 39241, 39242, 39243, 39253, 39255, 39257, 39258, 39263, 39264, 39270, 39271, 39274, 39287, 39296, 39298, 39310, 39315, 39317, 39327, 39328, 39341, 39353, 39354, 39360, 39361, 39368, 39375, 39377, 39379, 39380, 39381, 39382, 39386, 39388, 39389, 39393, 39397, 39408, 39411, 39412, 39414, 39416, 39417, 39419, 39421, 39422, 39435, 39454, 39455, 39459, 39462, 39464, 39469, 39474, 39480, 39499, 39506, 39507, 39512, 39514, 39525, 39533, 39539, 39541, 39565, 39569, 39570, 39571, 39572, 39574, 39579, 39580, 39581, 39588, 39594, 39599, 39601, 39604, 39611, 39613, 39614, 39620, 39623, 39632, 39636, 39640, 39645, 39646, 39651, 39653, 39657, 39660, 39663, 39664, 39669, 39672, 39678, 39682, 39693, 39695, 39697, 39699, 39721, 39722, 39725, 39728, 39732, 39734, 39737, 39742, 39743, 39751, 39758, 39762, 39766, 39770, 39776, 39787, 39788, 39793, 39795, 39797, 39798, 39802, 39804, 39805, 39807, 39808, 39810, 39820, 39833, 39836, 39844, 39854, 39863, 39866, 39870, 39874, 39884, 39886, 39888, 39891, 39897, 39906, 39907, 39919, 39926, 39932, 39937, 39948, 39950, 39952, 39957, 39958, 39964, 39966, 39967, 39968, 39973, 39975, 39979, 39981, 39992, 39994, 39998, 40001, 40003, 40023, 40027, 40031, 40032, 40033, 40036, 40038, 40041, 40043, 40045, 40060, 40073, 40074, 40075, 40090, 40093, 40102, 40103, 40107, 40108, 40112, 40117, 40118, 40119, 40120, 40121, 40125, 40128, 40137, 40146, 40149, 40151, 40156, 40157, 40160, 40165, 40173, 40174, 40175, 40178, 40185, 40187, 40192, 40206, 40210, 40211, 40212, 40221, 40229, 40239, 40243, 40246, 40249, 40250, 40252, 40259, 40260, 40268, 40275, 40277, 40284, 40287, 40296, 40300, 40303, 40304, 40305, 40306, 40307, 40310, 40311, 40313, 40315, 40317, 40321, 40325, 40328, 40330, 40332, 40334, 40360, 40361, 40370, 40373, 40375, 40384, 40397, 40398, 40401, 40403, 40408, 40417, 40418, 40422, 40430, 40438, 40444, 40449, 40452, 40453, 40455, 40457, 40469, 40477, 40489, 40490, 40494, 40495, 40501, 40502, 40503, 40507, 40508, 40521, 40525, 40527, 40530, 40536, 40537, 40540, 40549, 40554, 40561, 40562, 40566, 40575, 40579, 40580, 40592, 40593, 40595, 40596, 40604, 40606, 40608, 40610, 40615, 40617, 40629, 40636, 40643, 40644, 40649, 40651, 40653, 40660, 40662, 40671, 40678, 40688, 40695, 40698, 40702, 40703, 40708, 40712, 40716, 40720, 40723, 40727, 40729, 40730, 40732, 40738, 40739, 40742, 40745, 40750, 40764, 40765, 40769, 40778, 40780, 40787, 40788, 40792, 40800, 40801, 40814, 40820, 40822, 40828, 40829, 40835, 40839, 40843, 40845, 40849, 40851, 40852, 40853, 40876, 40883, 40885, 40886, 40900, 40901, 40902, 40903, 40911, 40913, 40917, 40918, 40930, 40931, 40936, 40937, 40953, 40956, 40958, 40964, 40974, 40979, 40982, 40989, 40990, 40991, 40994, 40998, 41006, 41008, 41014, 41022, 41029, 41038, 41039, 41040, 41043, 41047, 41049, 41050, 41057, 41058, 41059, 41060, 41061, 41068, 41083, 41090, 41093, 41098, 41099, 41114, 41117, 41123, 41126, 41127, 41142, 41146, 41152, 41154, 41157, 41158, 41160, 41161, 41174, 41183, 41190, 41195, 41196, 41203, 41212, 41213, 41216, 41217, 41218, 41219, 41221, 41225, 41227, 41230, 41238, 41239, 41241, 41245, 41247, 41248, 41254, 41260, 41261, 41275, 41277, 41280, 41290, 41292, 41299, 41302, 41303, 41318, 41320, 41321, 41323, 41330, 41335, 41353, 41354, 41363, 41365, 41367, 41371, 41374, 41377, 41392, 41393, 41402, 41411, 41415, 41420, 41423, 41426, 41431, 41436, 41437, 41443, 41446, 41457, 41473, 41474, 41476, 41490, 41491, 41499, 41502, 41504, 41505, 41506, 41515, 41519, 41530, 41532, 41534, 41540, 41546, 41547, 41548, 41552, 41556, 41557, 41562, 41563, 41564, 41567, 41573, 41582, 41590, 41591, 41598, 41607, 41610, 41613, 41619, 41622, 41624, 41629, 41633, 41634, 41640, 41647, 41649, 41660, 41661, 41668, 41673, 41678, 41686, 41687, 41688, 41690, 41691, 41696, 41705, 41706, 41711, 41713, 41714, 41725, 41726, 41734, 41739, 41746, 41747, 41754, 41763, 41772, 41776, 41782, 41783, 41792, 41799, 41804, 41810, 41812, 41816, 41817, 41821, 41823, 41829, 41833, 41838, 41841, 41851, 41878, 41879, 41880, 41896, 41901, 41904, 41905, 41907, 41908, 41909, 41913, 41920, 41926, 41928, 41931, 41937, 41938, 41949, 41969, 41981, 41982, 41983, 41985, 41989, 41990, 41992, 41996, 42000, 42002, 42003, 42010, 42012, 42027, 42028, 42041, 42049, 42053, 42064, 42066, 42067, 42068, 42076, 42081, 42086, 42088, 42104, 42115, 42119, 42128, 42133, 42134, 42136, 42139, 42146, 42164, 42165, 42166, 42169, 42175, 42180, 42182, 42183, 42186, 42188, 42191, 42202, 42203, 42204, 42211, 42212, 42222, 42225, 42226, 42230, 42234, 42237, 42240, 42247, 42248, 42253, 42258, 42261, 42266, 42267, 42268, 42270, 42278, 42279, 42280, 42282, 42283, 42288, 42296, 42303, 42318, 42321, 42324, 42330, 42342, 42349, 42350, 42352, 42355, 42371, 42375, 42379, 42389, 42391, 42401, 42402, 42403, 42404, 42405, 42415, 42417, 42419, 42431, 42436, 42441, 42445, 42456, 42469, 42471, 42473, 42475, 42481, 42484, 42486, 42491, 42493, 42495, 42503, 42507, 42510, 42513, 42517, 42522, 42523, 42524, 42530, 42539, 42541, 42550, 42551, 42552, 42553, 42558, 42561, 42572, 42589, 42594, 42595, 42606, 42608, 42611, 42615, 42624, 42626, 42627, 42628, 42633, 42636, 42637, 42639, 42644, 42651, 42654, 42656, 42669, 42670, 42675, 42693, 42705, 42706, 42707, 42719, 42721, 42729, 42730, 42734, 42737, 42739, 42749, 42754, 42756, 42760, 42764, 42778, 42779, 42795, 42796, 42798, 42808, 42810, 42816, 42818, 42826, 42844, 42849, 42853, 42855, 42860, 42870, 42877, 42878, 42882, 42900, 42916, 42918, 42927, 42928, 42931, 42932, 42937, 42943, 42946, 42949, 42950, 42958, 42971, 42986, 43001, 43002, 43009, 43020, 43021, 43027, 43036, 43046, 43048, 43059, 43069, 43079, 43083, 43090, 43094, 43095, 43108, 43114, 43115, 43127, 43134, 43148, 43153, 43158, 43162, 43164, 43175, 43190, 43198, 43203, 43204, 43205, 43206, 43207, 43212, 43217, 43223, 43238, 43244, 43250, 43253, 43271, 43273, 43282, 43283, 43284, 43290, 43297, 43298, 43301, 43310, 43313, 43314, 43329, 43330, 43338, 43350, 43352, 43354, 43361, 43365, 43370, 43375, 43377, 43378, 43381, 43383, 43384, 43392, 43393, 43394, 43410, 43417, 43420, 43422, 43425, 43431, 43432, 43440, 43446, 43453, 43464, 43478, 43479, 43481, 43510, 43517, 43533, 43535, 43538, 43543, 43562, 43580, 43584, 43594, 43603, 43614, 43634, 43635, 43637, 43638, 43646, 43647, 43650, 43653, 43654, 43656, 43661, 43665, 43669, 43671, 43679, 43683, 43685, 43691, 43693, 43696, 43717, 43722, 43725, 43736, 43744, 43745, 43747, 43748, 43754, 43756, 43760, 43764, 43769, 43778, 43780, 43782, 43784, 43794, 43796, 43798, 43802, 43805, 43808, 43809, 43816, 43817, 43818, 43822, 43826, 43828, 43833, 43835, 43855, 43862, 43871, 43875, 43890, 43893, 43904, 43910, 43911, 43912, 43914, 43917, 43918, 43930, 43932, 43938, 43946, 43963, 43965, 43969, 43972, 43975, 43984, 43985, 43990, 44002, 44004, 44005, 44006, 44008, 44018, 44025, 44031, 44041, 44048, 44049, 44071, 44086, 44088, 44101, 44106, 44124, 44129, 44132, 44133, 44139, 44143, 44150, 44151, 44154, 44155, 44160, 44169, 44181, 44184, 44197, 44204, 44212, 44221, 44229, 44232, 44238, 44246, 44254, 44258, 44261, 44265, 44275, 44278, 44291, 44295, 44298, 44303, 44304, 44310, 44312, 44324, 44325, 44335, 44340, 44342, 44353, 44355, 44364, 44366, 44374, 44380, 44385, 44392, 44396, 44403, 44415, 44416, 44419, 44430, 44433, 44435, 44440, 44443, 44444, 44446, 44451, 44469, 44479, 44482, 44483, 44484, 44485, 44496, 44497, 44500, 44509, 44511, 44512, 44532, 44535, 44537, 44538, 44543, 44550, 44562, 44566, 44569, 44572, 44588, 44596, 44602, 44605, 44606, 44625, 44634, 44636, 44643, 44645, 44651, 44654, 44661, 44664, 44683, 44684, 44687, 44688, 44689, 44699, 44701, 44704, 44710, 44726, 44731, 44750, 44761, 44768, 44769, 44778, 44784, 44785, 44806, 44809, 44815, 44817, 44822, 44828, 44831, 44833, 44841, 44842, 44847, 44855, 44857, 44858, 44859, 44861, 44878, 44885, 44895, 44901, 44905, 44906, 44908, 44917, 44919, 44921, 44937, 44938, 44939, 44956, 44957, 44960, 44966, 44968, 44978, 44983, 45006, 45013, 45023, 45024, 45025, 45030, 45033, 45034, 45042, 45043, 45045, 45053, 45054, 45059, 45063, 45066, 45071, 45076, 45080, 45092, 45094, 45099, 45101, 45124, 45127, 45131, 45155, 45156, 45199, 45200, 45206, 45217, 45221, 45239, 45240, 45243, 45244, 45248, 45254, 45275, 45276, 45277, 45279, 45287, 45297, 45314, 45317, 45319, 45333, 45335, 45348, 45349, 45354, 45360, 45361, 45362, 45372, 45380, 45381, 45386, 45388, 45417, 45422, 45425, 45434, 45439, 45443, 45445, 45460, 45467, 45474, 45488, 45493, 45494, 45502, 45508, 45509, 45511, 45518, 45527, 45531, 45539, 45540, 45545, 45602, 45605, 45609, 45612, 45620, 45631, 45647, 45656, 45660, 45668, 45684, 45688, 45704, 45706, 45711, 45713, 45718, 45735, 45746, 45749, 45755, 45765, 45768, 45773, 45788, 45790, 45796, 45806, 45811, 45829, 45833, 45834, 45836, 45884, 45890, 45892, 45895, 45898, 45915, 45917, 45929, 45930, 45938, 45941, 45961, 45970, 45974, 45975, 45976, 45995, 45996, 45998, 46000, 46005, 46006, 46014, 46015, 46033, 46034, 46036, 46038, 46041, 46055, 46056, 46058, 46060, 46063, 46068, 46071, 46081, 46093, 46100, 46113, 46125, 46137, 46147, 46149, 46150, 46160, 46161, 46162, 46171, 46176, 46179, 46191, 46192, 46193, 46219, 46226, 46230, 46234, 46236, 46247, 46251, 46263, 46268, 46269, 46273, 46284, 46285, 46287, 46290, 46303, 46304, 46314, 46315, 46316, 46317, 46319, 46333, 46334, 46335, 46338, 46340, 46341, 46355, 46387, 46392, 46394, 46411, 46413, 46418, 46434, 46435, 46437, 46441, 46445, 46451, 46452, 46455, 46457, 46458, 46466, 46477, 46486, 46488, 46517, 46518, 46520, 46528, 46530, 46531, 46533, 46538, 46544, 46548, 46568, 46569, 46577, 46590, 46601, 46618, 46619, 46636, 46639, 46649, 46653, 46659, 46664, 46680, 46683, 46691, 46692, 46698, 46705, 46707, 46715, 46716, 46721, 46722, 46726, 46742, 46756, 46758, 46774, 46776, 46777, 46780, 46793, 46797, 46800, 46818, 46839, 46841, 46855, 46858, 46865, 46867, 46868, 46869, 46870, 46892, 46896, 46900, 46902, 46903, 46917, 46919, 46923, 46931, 46932, 46933, 46935, 46936, 46941, 46964, 46969, 46985, 46987, 46988, 46989, 47001, 47013, 47014, 47015, 47022, 47023, 47026, 47034, 47037, 47039, 47040, 47041, 47045, 47046, 47065, 47067, 47068, 47071, 47075, 47080, 47087, 47089, 47090, 47099, 47102, 47116, 47119, 47121, 47122, 47124, 47127, 47128, 47130, 47142, 47143, 47144, 47145, 47146, 47163, 47166, 47169, 47171, 47172, 47173, 47195, 47198, 47218, 47222, 47225, 47233, 47237, 47247, 47248, 47252, 47264, 47271, 47278, 47279, 47282, 47292, 47303, 47311, 47317, 47321, 47328, 47330, 47342, 47343, 47352, 47369, 47372, 47374, 47377, 47388, 47399, 47406, 47417, 47424, 47431, 47442, 47449, 47451, 47454, 47476, 47478, 47483, 47501, 47508, 47509, 47523, 47525, 47528, 47538, 47539, 47541, 47557, 47558, 47560, 47566, 47572, 47585, 47595, 47596, 47610, 47611, 47612, 47613, 47628, 47635, 47637, 47639, 47642, 47653, 47667, 47673, 47687, 47692, 47695, 47699, 47701, 47708, 47710, 47718, 47720, 47721, 47751, 47755, 47760, 47783, 47784, 47785, 47787, 47788, 47814, 47821, 47847, 47848, 47850, 47853, 47865, 47883, 47884, 47888, 47903, 47904, 47907, 47936, 47937, 47958, 47964, 47965, 47967, 47986, 47992, 48000, 48001, 48004, 48007, 48035, 48038, 48040, 48041, 48060, 48071, 48074, 48075, 48082, 48090, 48097, 48098, 48104, 48115, 48117, 48118, 48122, 48124, 48133, 48149, 48155, 48167, 48171, 48172, 48180, 48183, 48188, 48189, 48193, 48206, 48210, 48214, 48227, 48241, 48244, 48266, 48270, 48275, 48277, 48289, 48290, 48324, 48325, 48333, 48338, 48340, 48342, 48345, 48376, 48413, 48431, 48435, 48441, 48443, 48446, 48460, 48464, 48466, 48469, 48487, 48489, 48491, 48497, 48503, 48513, 48515, 48522, 48524, 48530, 48535, 48540, 48551, 48554, 48555, 48558, 48564, 48565, 48566, 48572, 48597, 48600, 48621, 48626, 48635, 48636, 48657, 48658, 48661, 48664, 48672, 48689, 48691, 48708, 48714, 48728, 48731, 48732, 48733, 48760, 48774, 48805, 48809, 48815, 48817, 48831, 48857, 48861, 48878, 48880, 48887, 48889, 48890, 48894, 48921, 48922, 48931, 48935, 48951, 48956, 48973, 48976, 48977, 48982, 48986, 48988, 49004, 49014, 49040, 49041, 49044, 49052, 49063, 49077, 49081, 49084, 49108, 49110, 49111, 49117, 49124, 49126, 49130, 49145, 49146, 49151, 49157, 49162, 49178, 49182, 49184, 49186, 49197, 49216, 49217, 49220, 49228, 49232, 49233, 49246, 49248, 49250, 49252, 49253, 49256, 49264, 49281, 49282, 49288, 49309, 49311, 49316, 49320, 49347, 49349, 49350, 49381, 49385, 49386, 49388, 49390, 49394, 49396, 49418, 49423, 49426, 49440, 49446, 49447, 49453, 49455, 49461, 49463, 49468, 49474, 49482, 49486, 49491, 49492, 49494, 49508, 49509, 49521, 49526, 49544, 49547, 49551, 49553, 49559, 49587, 49589, 49592, 49609, 49623, 49635, 49645, 49646, 49661, 49664, 49666, 49670, 49674, 49694, 49695, 49700, 49710, 49721, 49728, 49730, 49739, 49741, 49743, 49744, 49773, 49778, 49780, 49782, 49786, 49798, 49821, 49822, 49823, 49834, 49851, 49858, 49861, 49864, 49866, 49880, 49882, 49890, 49893, 49894, 49899, 49904, 49928, 49959, 49978, 49980, 49981, 49988, 49999, 50009, 50010, 50028, 50030, 50036, 50039, 50042, 50050, 50056, 50071, 50083, 50085, 50087, 50092, 50095, 50110, 50116, 50119, 50120, 50124, 50129, 50146, 50148, 50154, 50162, 50171, 50179, 50184, 50188, 50213, 50226, 50227, 50230, 50234, 50235, 50239, 50266, 50270, 50301, 50302, 50304, 50315, 50316, 50318, 50350, 50358, 50360, 50370, 50383, 50384, 50387, 50396, 50399, 50421, 50422, 50427, 50432, 50434, 50435, 50437, 50439, 50453, 50458, 50461, 50465, 50480, 50512, 50514, 50515, 50516, 50531, 50546, 50556, 50561, 50579, 50595, 50602, 50619, 50641, 50644, 50647, 50674, 50677, 50679, 50690, 50698, 50711, 50717, 50727, 50745, 50751, 50775, 50777, 50778, 50797, 50800, 50806, 50825, 50847, 50854, 50859, 50868, 50871, 50879, 50880, 50881, 50884, 50891, 50897, 50899, 50907, 50914, 50916, 50919, 50921, 50966, 50978, 50986, 50987, 50992, 51016, 51017, 51023, 51029, 51035, 51063, 51065, 51066, 51067, 51070, 51071, 51079, 51080, 51082, 51103, 51104, 51106, 51117, 51123, 51147, 51149, 51157, 51158, 51174, 51177, 51180, 51196, 51197, 51239, 51250, 51264, 51265, 51266, 51271, 51276, 51281, 51285, 51320, 51321, 51330, 51353, 51356, 51358, 51360, 51398, 51407, 51414, 51417, 51448, 51452, 51460, 51474, 51477, 51495, 51499, 51519, 51525, 51526, 51549, 51551, 51563, 51597, 51605, 51613, 51624, 51630, 51648, 51662, 51706, 51708, 51733, 51734, 51735, 51741, 51770, 51774, 51781, 51786, 51789, 51792, 51804, 51822, 51833, 51854, 51872, 51877, 51878, 51881, 51888, 51892, 51898, 51899, 51900, 51913, 51915, 51919, 51921, 51924, 51931, 51934, 51937, 51945, 51967, 51974, 51975, 51980, 51983, 51991, 51998, 52024, 52028, 52029, 52032, 52037, 52040, 52041, 52049, 52058, 52068, 52076, 52077, 52079, 52083, 52086, 52095, 52106, 52124, 52137, 52148, 52176, 52187, 52198, 52213, 52223, 52224, 52227, 52230, 52236, 52239, 52242, 52244, 52249, 52280, 52282, 52298, 52299, 52309, 52314, 52330, 52331, 52332, 52349, 52359, 52377, 52380, 52397, 52412, 52417, 52441, 52445, 52453, 52454, 52462, 52472, 52473, 52498, 52499, 52518, 52521, 52532, 52550, 52590, 52592, 52599, 52600, 52601, 52628, 52629, 52631, 52637, 52640, 52641, 52647, 52667, 52675, 52677, 52680, 52684, 52685, 52692, 52713, 52721, 52726, 52729, 52737, 52743, 52752, 52783, 52788, 52815, 52828, 52840, 52845, 52858, 52861, 52865, 52866, 52893, 52903, 52907, 52935, 52953, 52963, 52985, 53000, 53002, 53007, 53008, 53009, 53022, 53028, 53043, 53056, 53067, 53068, 53069, 53071, 53077, 53081, 53087, 53089, 53093, 53113, 53116, 53117, 53121, 53124, 53135, 53168, 53173, 53187, 53199, 53200, 53202, 53207, 53230, 53237, 53278, 53291, 53293, 53295, 53297, 53304, 53307, 53316, 53321, 53325, 53338, 53344, 53362, 53369, 53373, 53385, 53394, 53408, 53417, 53426, 53427, 53430, 53441, 53448, 53458, 53476, 53478, 53479, 53495, 53504, 53529, 53566, 53587, 53600, 53603, 53611, 53653, 53656, 53659, 53672, 53673, 53684, 53713, 53715, 53718, 53719, 53722, 53724, 53767, 53774, 53778, 53782, 53800, 53821, 53836, 53844, 53845, 53846, 53852, 53865, 53869, 53879, 53882, 53905, 53909, 53911, 53915, 53917, 53921, 53925, 53940, 53970, 53977, 53978, 53982, 53997, 54009, 54039, 54060, 54061, 54081, 54083, 54084, 54132, 54175, 54176, 54179, 54187, 54188, 54194, 54216, 54219, 54222, 54235, 54244, 54253, 54259, 54270, 54272, 54276, 54307, 54315, 54334, 54340, 54374, 54378, 54379, 54380, 54383, 54399, 54436, 54438, 54439, 54440, 54442, 54443, 54445, 54447, 54449, 54450, 54452, 54459, 54461, 54479, 54486, 54492, 54499, 54509, 54511, 54515, 54517, 54523, 54524, 54531, 54548, 54581, 54584, 54585, 54587, 54593, 54596, 54600, 54601, 54619, 54627, 54658, 54659, 54667, 54669, 54676, 54684, 54692, 54727, 54729, 54731, 54734, 54735, 54746, 54748, 54751, 54756, 54766, 54789, 54796, 54797, 54802, 54806, 54811, 54817, 54824, 54829, 54839, 54863, 54866, 54869, 54872, 54873, 54884, 54885, 54886, 54888, 54894, 54907, 54916, 54948, 54956, 54971, 54983, 55014, 55017, 55022, 55034, 55053, 55060, 55067, 55070, 55084, 55091, 55098, 55107, 55116, 55121, 55155, 55158, 55168, 55175, 55177, 55186, 55196, 55213, 55230, 55231, 55233, 55236, 55237, 55244, 55256, 55263, 55301, 55307, 55309, 55310, 55311, 55331, 55340, 55367, 55370, 55372, 55375, 55380, 55416, 55424, 55455, 55460, 55475, 55478, 55479, 55481, 55482, 55501, 55530, 55539, 55540, 55574, 55580, 55590, 55596, 55603, 55604, 55635, 55640, 55641, 55642, 55648, 55653, 55655, 55657, 55667, 55680, 55682, 55687, 55713, 55715, 55721, 55727, 55740, 55803, 55807, 55810, 55823, 55824, 55830, 55831, 55859, 55884, 55887, 55892, 55894, 55905, 55915, 55922, 55941, 55944, 55981, 56005, 56011, 56016, 56036, 56060, 56063, 56066, 56068, 56071, 56076, 56082, 56094, 56119, 56131, 56138, 56140, 56141, 56150, 56161, 56215, 56221, 56223, 56230, 56231, 56245, 56249, 56256, 56263, 56284, 56301, 56316, 56317, 56325, 56334, 56381, 56391, 56394, 56403, 56407, 56412, 56420, 56421, 56469, 56470, 56471, 56473, 56474, 56479, 56487, 56493, 56497, 56507, 56508, 56511, 56528, 56543, 56563, 56575, 56586, 56596, 56601, 56607, 56622, 56623, 56632, 56640, 56658, 56659, 56665, 56666, 56667, 56669, 56670, 56679, 56680, 56682, 56684, 56702, 56704, 56705, 56712, 56757, 56770, 56777, 56779, 56782, 56787, 56788, 56792, 56803, 56858, 56860, 56863, 56872, 56878, 56884, 56910, 56931, 56938, 56941, 56945, 56951, 56971, 57018, 57024, 57031, 57033, 57034, 57038, 57039, 57044, 57094, 57123, 57126, 57129, 57134, 57154, 57163, 57176, 57188, 57204, 57222, 57226, 57251, 57299, 57303, 57304, 57322, 57323, 57341, 57351, 57372, 57377, 57405, 57418, 57422, 57431, 57435, 57438, 57439, 57452, 57462, 57466, 57477, 57478, 57520, 57523, 57531, 57535, 57543, 57551, 57575, 57580, 57600, 57605, 57618, 57621, 57622, 57627, 57628, 57630, 57633, 57653, 57673, 57674, 57679, 57704, 57705, 57716, 57718, 57724, 57746, 57779, 57806, 57809, 57813, 57816, 57821, 57828, 57841, 57842, 57867, 57883, 57906, 57915, 57916, 57925, 57935, 57940, 57944, 57959, 57982, 57986, 57989, 58010, 58030, 58045, 58046, 58059, 58060, 58065, 58108, 58118, 58121, 58130, 58131, 58144, 58146, 58194, 58212, 58222, 58235, 58239, 58251, 58252, 58269, 58276, 58344, 58348, 58351, 58353, 58367, 58377, 58378, 58395, 58397, 58398, 58403, 58454, 58456, 58465, 58466, 58470, 58476, 58480, 58495, 58557, 58561, 58567, 58570, 58574, 58577, 58580, 58583, 58637, 58671, 58673, 58681, 58682, 58685, 58695, 58699, 58714, 58716, 58723, 58731, 58748, 58755, 58799, 58801, 58809, 58813, 58814, 58821, 58833, 58839, 58845, 58850, 58853, 58856, 58857, 58862, 58872, 58891, 58895, 58902, 58935, 58941, 58947, 58950, 58958, 58971, 58974, 58989, 58999, 59013, 59022, 59030, 59037, 59039, 59041, 59045, 59048, 59049, 59068, 59075, 59108, 59122, 59128, 59174, 59175, 59180, 59183, 59191, 59215, 59220, 59221, 59272, 59297, 59333, 59339, 59353, 59385, 59392, 59396, 59397, 59412, 59416, 59419, 59425, 59441, 59481, 59527, 59529, 59532, 59543, 59549, 59551, 59559, 59561, 59576, 59578, 59630, 59631, 59636, 59644, 59647, 59650, 59651, 59655, 59700, 59716, 59766, 59779, 59784, 59785, 59789, 59790, 59800, 59804, 59805, 59826, 59831, 59843, 59909, 59910, 59912, 59925, 59935, 59937, 59950, 59974, 59982, 60022, 60025, 60034, 60037, 60058, 60095, 60101, 60145, 60146, 60166, 60178, 60182, 60191, 60213, 60221, 60274, 60315, 60322, 60330, 60341, 60343, 60357, 60362, 60422, 60426, 60427, 60438, 60445, 60454, 60457, 60462, 60465, 60470, 60483, 60501, 60515, 60549, 60552, 60561, 60576, 60594, 60598, 60605, 60609, 60610, 60618, 60621, 60638, 60641, 60653, 60655, 60656, 60658, 60662, 60709, 60718, 60719, 60750, 60784, 60803, 60862, 60876, 60880, 60884, 60887, 60894, 60895, 60915, 60927, 60949, 60999, 61007, 61018, 61038, 61042, 61044, 61045, 61056, 61068, 61071, 61072, 61078, 61090, 61133, 61148, 61150, 61165, 61175, 61186, 61198, 61218, 61227, 61234, 61272, 61274, 61330, 61333, 61341, 61344, 61353, 61361, 61366, 61370, 61382, 61414, 61432, 61444, 61493, 61495, 61500, 61501, 61502, 61507, 61543, 61562, 61567, 61585, 61611, 61648, 61658, 61661, 61674, 61678, 61679, 61687, 61689, 61734, 61744, 61748, 61752, 61764, 61791, 61803, 61812, 61817, 61823, 61832, 61842, 61847, 61852, 61857, 61871, 61878, 61914, 61957, 61973, 61990, 61992, 61993, 61994, 61995, 62003, 62005, 62018, 62022, 62027, 62033, 62041, 62045, 62058, 62074, 62079, 62083, 62096, 62125, 62162, 62178, 62182, 62199, 62213, 62336, 62344, 62361, 62387, 62388, 62402, 62435, 62440, 62469, 62482, 62514, 62530, 62536, 62549, 62557, 62558, 62562, 62565, 62597, 62607, 62649, 62674, 62677, 62685, 62690, 62698, 62702, 62703, 62710, 62717, 62737, 62759, 62778, 62857, 62865, 62866, 62876, 62880, 62886, 62889, 62890, 62899, 62909, 62921, 62957, 62965, 62975, 63003, 63048, 63050, 63054, 63055, 63061, 63076, 63090, 63093, 63095, 63097, 63098, 63101, 63105, 63128, 63139, 63141, 63161, 63166, 63186, 63207, 63238, 63262, 63268, 63273, 63281, 63284, 63292, 63304, 63311, 63327, 63333, 63372, 63413, 63462, 63470, 63483, 63504, 63513, 63515, 63540, 63543, 63558, 63572, 63613, 63685, 63693, 63705, 63710, 63715, 63716, 63717, 63747, 63760, 63764, 63769, 63789, 63824, 63846, 63849, 63868, 63874, 63889, 63904, 63906, 63908, 63929, 63951, 63955, 63967, 63994, 64062, 64072, 64074, 64092, 64108, 64111, 64127, 64137, 64170, 64172, 64261, 64273, 64283, 64284, 64295, 64320, 64322, 64328, 64337, 64343, 64352, 64362, 64374, 64408, 64424, 64440, 64444, 64507, 64508, 64521, 64533, 64559, 64580, 64585, 64623, 64670, 64717, 64719, 64734, 64764, 64766, 64829, 64844, 64873, 64881, 64950, 64953, 64963, 64967, 64969, 64970, 64978, 64985, 65012, 65016, 65017, 65019, 65020, 65021, 65022, 65024, 65025, 65026, 65027, 65028, 65029, 65030, 65031, 65033, 65034, 65035, 65036, 65037, 65038, 65039, 65043, 65045, 65046, 65049, 65050, 65051, 65052, 65053, 65055, 65056, 65057, 65058, 65060, 65061, 65062, 65064, 65065, 65067, 65069, 65070, 65071, 65073, 65076, 65077, 65078, 65080, 65081, 65082, 65083, 65084, 65085, 65086, 65088, 65089, 65090, 65092, 65093, 65096, 65097, 65098, 65099, 65100, 65103, 65104, 65105, 65107, 65108, 65109, 65111, 65112, 65116, 65117, 65120, 65121, 65122, 65123, 65124, 65125, 65127, 65128, 65129, 65130, 65131, 65132, 65136, 65138, 65142, 65145, 65146, 65147, 65149, 65153, 65155, 65156, 65157, 65158, 65159, 65160, 65164, 65165, 65166, 65168, 65169, 65173, 65174, 65175, 65177, 65179, 65180, 65184, 65188, 65189, 65190, 65192, 65195, 65196, 65197, 65198, 65199, 65201, 65202, 65203, 65206, 65208, 65210, 65211, 65212, 65213, 65214, 65215, 65216, 65217, 65218, 65219, 65221, 65222, 65225, 65226, 65227, 65228, 65229, 65230, 65235, 65237, 65238, 65241, 65244, 65245, 65252, 65253, 65254, 65255, 65256, 65257, 65260, 65262, 65263, 65264, 65265, 65268, 65269, 65270, 65271, 65272, 65275, 65276, 65279, 65280, 65282, 65284, 65286, 65287, 65288, 65289, 65290, 65291, 65294, 65295, 65296, 65299, 65300, 65301, 65302, 65304, 65306, 65307, 65308, 65310, 65315, 65317, 65318, 65319, 65321, 65322, 65327, 65329, 65332, 65334, 65335, 65336, 65337, 65340, 65341, 65344, 65346, 65348, 65352, 65353, 65356, 65360, 65362, 65364, 65366, 65371, 65372, 65374, 65376, 65382, 65385, 65388, 65389, 65391, 65392, 65393, 65397, 65401, 65403, 65405, 65407, 65408, 65409, 65415, 65417, 65418, 65421, 65422, 65425, 65429, 65431, 65433, 65434, 65435, 65438, 65439, 65440, 65441, 65445, 65447, 65449, 65453, 65461, 65463, 65464, 65466, 65467, 65468, 65470, 65471, 65472, 65473, 65475, 65478, 65482, 65485, 65487, 65488, 65490, 65491, 65492, 65493, 65494, 65495, 65498, 65499, 65500, 65501, 65502, 65506, 65507, 65508, 65510, 65511, 65515, 65517, 65518, 65521, 65523, 65524, 65528, 65530, 65531, 65532, 65533, 65537, 65539, 65543, 65549, 65553, 65579, 65580, 65581, 65582, 65583, 65584, 65586, 65587, 65588, 65590, 65591, 65593, 65594, 65596, 65597, 65605, 65607, 65609, 65610, 65611, 65612, 65615, 65617, 65618, 65619, 65621, 65622, 65624, 65625, 65633, 65634, 65645, 65646, 65648, 65649, 65652, 65653, 65656, 65657, 65658, 65659, 65660, 65661, 65663, 65664, 65665, 65667, 65668, 65669, 65670, 65672, 65673, 65675, 65676, 65678, 65680, 65685, 65692, 65702, 65703, 65710, 65712, 65713, 65714, 65719, 65721, 65722, 65723, 65724, 65728, 65731, 65732, 65734, 65740, 65741, 65744, 65745, 65747, 65750, 65751, 65752, 65755, 65758, 65760, 65764, 65766, 65773, 65778, 65779, 65780, 65781, 65783, 65785, 65786, 65787, 65789, 65792, 65793, 65795, 65796, 65798, 65801, 65803, 65804, 65812, 65816, 65817, 65818, 65822, 65825, 65830, 65832, 65834, 65835, 65836, 65837, 65840, 65844, 65845, 65847, 65848, 65849, 65855, 65857, 65859, 65863, 65864, 65867, 65868, 65874, 65877, 65879, 65882, 65884, 65887, 65888, 65889, 65891, 65895, 65898, 65899, 65902, 65907, 65909, 65910, 65911, 65915, 65917, 65920, 65921, 65922, 65924, 65925, 65926, 65937, 65940, 65942, 65943, 65945, 65959, 65965, 65968, 65977, 65979, 65981, 65984, 65985, 65990, 65992, 65995, 65996, 66006, 66007, 66008, 66010, 66011, 66013, 66015, 66016, 66017, 66019, 66020, 66022, 66024, 66028, 66034, 66037, 66040, 66044, 66046, 66047, 66049, 66051, 66055, 66061, 66063, 66068, 66070, 66071, 66076, 66078, 66079, 66081, 66082, 66085, 66087, 66091, 66095, 66097, 66099, 66102, 66103, 66109, 66112, 66113, 66117, 66119, 66120, 66122, 66127, 66130, 66132, 66133, 66140, 66144, 66148, 66149, 66151, 66153, 66154, 66155, 66157, 66159, 66160, 66161, 66164, 66166, 66169, 66172, 66174, 66175, 66176, 66177, 66184, 66195, 66196, 66198, 66200, 66201, 66203, 66206, 66211, 66214, 66215, 66219, 66226, 66231, 66233, 66235, 66236, 66237, 66238, 66240, 66243, 66246, 66253, 66254, 66258, 66262, 66275, 66279, 66282, 66283, 66287, 66288, 66290, 66292, 66294, 66295, 66296, 66297, 66298, 66301, 66306, 66311, 66315, 66324, 66325, 66329, 66331, 66334, 66335, 66337, 66346, 66347, 66354, 66362, 66365, 66369, 66373, 66374, 66375, 66380, 66381, 66382, 66387, 66388, 66389, 66396, 66397, 66398, 66399, 66418, 66420, 66422, 66425, 66427, 66428, 66429, 66430, 66432, 66433, 66434, 66435, 66436, 66437, 66438, 66440, 66442, 66445, 66446, 66448, 66450, 66456, 66457, 66471, 66478, 66480, 66482, 66483, 66484, 66487, 66490, 66492, 66495, 66498, 66501, 66504, 66505, 66506, 66508, 66509, 66513, 66517, 66519, 66520, 66522, 66524, 66526, 66528, 66529, 66533, 66534, 66535, 66536, 66537, 66540, 66543, 66545, 66547, 66549, 66550, 66552, 66556, 66557, 66559, 66562, 66563, 66567, 66573, 66576, 66578, 66580, 66581, 66587, 66590, 66591, 66592, 66596, 66597, 66600, 66601, 66603, 66604, 66606, 66612, 66615, 66617, 66625, 66626, 66627, 66631, 66632, 66636, 66639, 66645, 66647, 66652, 66654, 66656, 66657, 66658, 66662, 66663, 66664, 66667, 66669, 66670, 66671, 66672, 66675, 66677, 66687, 66689, 66693, 66700, 66701, 66702, 66705, 66706, 66707, 66708, 66711, 66713, 66717, 66721, 66723, 66724, 66725, 66726, 66730, 66733, 66739, 66742, 66745, 66748, 66754, 66755, 66758, 66761, 66764, 66770, 66771, 66774, 66775, 66776, 66777, 66782, 66783, 66788, 66795, 66796, 66805, 66809, 66813, 66815, 66817, 66818, 66819, 66820, 66823, 66824, 66828, 66833, 66835, 66836, 66837, 66838, 66839, 66850, 66852, 66854, 66857, 66860, 66861, 66863, 66867, 66871, 66872, 66873, 66874, 66877, 66879, 66880, 66883, 66885, 66888, 66890, 66891, 66892, 66897, 66899, 66900, 66901, 66906, 66908, 66912, 66915, 66916, 66920, 66923, 66924, 66925, 66931, 66933, 66935, 66937, 66938, 66941, 66945, 66950, 66952, 66953, 66961, 66963, 66965, 66971, 66973, 66977, 66981, 66982, 66990, 66991, 66992, 66993, 66997, 66998, 66999, 67007, 67014, 67015, 67019, 67024, 67041, 67044, 67051, 67061, 67062, 67064, 67067, 67073, 67075, 67077, 67081, 67089, 67101, 67108, 67109, 67110, 67115, 67120, 67121, 67129, 67130, 67135, 67136, 67141, 67144, 67147, 67148, 67149, 67150, 67151, 67153, 67154, 67156, 67159, 67165, 67169, 67175, 67176, 67178, 67181, 67182, 67185, 67188, 67190, 67191, 67192, 67194, 67196, 67209, 67216, 67218, 67219, 67228, 67229, 67235, 67237, 67238, 67239, 67241, 67244, 67245, 67246, 67248, 67249, 67256, 67260, 67262, 67266, 67268, 67274, 67276, 67277, 67279, 67284, 67285, 67288, 67289, 67290, 67297, 67300, 67305, 67306, 67308, 67324, 67325, 67331, 67334, 67335, 67336, 67344, 67347, 67348, 67355, 67356, 67361, 67362, 67366, 67379, 67384, 67385, 67388, 67392, 67393, 67397, 67398, 67401, 67405, 67419, 67420, 67424, 67427, 67433, 67436, 67441, 67444, 67450, 67455, 67456, 67457, 67460, 67465, 67471, 67473, 67477, 67489, 67492, 67503, 67504, 67505, 67508, 67511, 67512, 67520, 67524, 67527, 67535, 67542, 67548, 67552, 67554, 67558, 67561, 67562, 67563, 67565, 67571, 67573, 67574, 67575, 67577, 67580, 67581, 67586, 67588, 67590, 67592, 67598, 67599, 67602, 67604, 67605, 67606, 67609, 67612, 67619, 67625, 67630, 67632, 67633, 67634, 67640, 67641, 67643, 67646, 67649, 67653, 67654, 67662, 67663, 67664, 67667, 67672, 67673, 67677, 67679, 67681, 67682, 67683, 67684, 67685, 67686, 67687, 67689, 67692, 67696, 67697, 67715, 67721, 67731, 67732, 67735, 67741, 67748, 67749, 67759, 67761, 67762, 67768, 67769, 67777, 67783, 67785, 67787, 67790, 67791, 67792, 67796, 67798, 67803, 67805, 67806, 67808, 67815, 67816, 67820, 67829, 67832, 67834, 67841, 67842, 67844, 67851, 67856, 67860, 67865, 67867, 67868, 67875, 67881, 67884, 67892, 67900, 67901, 67902, 67911, 67915, 67920, 67930, 67946, 67949, 67954, 67964, 67965, 67967, 67968, 67969, 67970, 67971, 67972, 67973, 67975, 67976, 67979, 67985, 67986, 67989, 67997, 67998, 68010, 68011, 68013, 68014, 68015, 68016, 68018, 68019, 68020, 68021, 68022, 68023, 68024, 68025, 68026, 68027, 68028, 68030, 68033, 68034, 68035, 68036, 68038, 68040, 68042, 68044, 68045, 68046, 68047, 68048, 68049, 68050, 68052, 68053, 68054, 68056, 68058, 68061, 68063, 68066, 68067, 68068, 68069, 68070, 68073, 68074, 68075, 68078, 68079, 68080, 68082, 68084, 68085, 68095, 68098, 68103, 68105, 68107, 68108, 68109, 68111, 68112, 68115, 68119, 68120, 68121, 68122, 68123, 68124, 68125, 68128, 68129, 68130, 68131, 68132, 68133, 68136, 68137, 68138, 68139, 68142, 68144, 68145, 68146, 68151, 68152, 68154, 68155, 68158, 68160, 68162, 68165, 68167, 68168, 68169, 68171, 68176, 68180, 68181, 68183, 68188, 68189, 68197, 68199, 68201, 68202, 68205, 68206, 68209, 68214, 68216, 68217, 68219, 68221, 68222, 68223, 68227, 68230, 68233, 68235, 68236, 68237, 68239, 68243, 68244, 68247, 68248, 68249, 68251, 68253, 68256, 68257, 68258, 68260, 68261, 68264, 68267, 68268, 68269, 68271, 68273, 68275, 68277, 68278, 68286, 68288, 68289, 68291, 68293, 68299, 68303, 68306, 68307, 68308, 68314, 68315, 68317, 68319, 68322, 68323, 68324, 68326, 68333, 68336, 68337, 68338, 68340, 68341, 68344, 68345, 68346, 68347, 68349, 68353, 68354, 68356, 68358, 68361, 68363, 68364, 68366, 68369, 68381, 68383, 68384, 68385, 68386, 68388, 68389, 68390, 68391, 68399, 68402, 68403, 68410, 68411, 68413, 68414, 68415, 68417, 68420, 68426, 68427, 68429, 68432, 68435, 68436, 68437, 68440, 68445, 68447, 68451, 68453, 68457, 68458, 68460, 68463, 68465, 68468, 68472, 68474, 68475, 68476, 68481, 68486, 68487, 68488, 68493, 68500, 68507, 68516, 68517, 68519, 68521, 68522, 68523, 68524, 68525, 68527, 68528, 68529, 68533, 68534, 68535, 68536, 68539, 68544, 68549, 68550, 68551, 68552, 68554, 68555, 68559, 68563, 68565, 68566, 68567, 68569, 68572, 68573, 68574, 68576, 68580, 68582, 68583, 68585, 68586, 68587, 68592, 68596, 68597, 68599, 68602, 68603, 68604, 68605, 68607, 68609, 68610, 68613, 68617, 68620, 68623, 68625, 68627, 68631, 68641, 68645, 68648, 68651, 68652, 68659, 68661, 68665, 68667, 68669, 68672, 68674, 68678, 68681, 68684, 68685, 68686, 68696, 68698, 68706, 68709, 68710, 68713, 68714, 68715, 68722, 68723, 68727, 68730, 68732, 68735, 68741, 68742, 68749, 68750, 68754, 68757, 68761, 68766, 68767, 68772, 68775, 68778, 68785, 68786, 68787, 68789, 68790, 68791, 68792, 68796, 68798, 68799, 68800, 68804, 68811, 68813, 68814, 68815, 68816, 68820, 68824, 68825, 68828, 68830, 68831, 68832, 68835, 68838, 68842, 68844, 68845, 68846, 68847, 68850, 68852, 68856, 68861, 68868, 68870, 68872, 68875, 68882, 68883, 68884, 68887, 68889, 68893, 68898, 68903, 68905, 68906, 68907, 68910, 68914, 68916, 68918, 68919, 68920, 68923, 68925, 68937, 68938, 68940, 68941, 68952, 68963, 68967, 68971, 68976, 68993, 68995, 68998, 69007, 69013, 69015, 69016, 69017, 69022, 69023, 69026, 69030, 69032, 69034, 69037, 69038, 69042, 69043, 69047, 69048, 69049, 69051, 69057, 69059, 69068, 69073, 69074, 69077, 69082, 69089, 69093, 69095, 69100, 69102, 69103, 69104, 69107, 69113, 69116, 69118, 69123, 69126, 69127, 69130, 69131, 69135, 69137, 69139, 69144, 69146, 69148, 69150, 69151, 69154, 69155, 69159, 69162, 69165, 69169, 69171, 69178, 69180, 69190, 69193, 69198, 69201, 69202, 69207, 69210, 69215, 69226, 69231, 69236, 69238, 69239, 69242, 69243, 69258, 69263, 69270, 69273, 69279, 69280, 69281, 69284, 69287, 69306, 69307, 69312, 69313, 69333, 69334, 69349, 69353, 69361, 69364, 69367, 69368, 69371, 69377, 69386, 69387, 69390, 69392, 69395, 69421, 69423, 69427, 69432, 69436, 69439, 69444, 69447, 69451, 69457, 69461, 69462, 69463, 69464, 69469, 69471, 69472, 69474, 69476, 69478, 69485, 69486, 69487, 69490, 69491, 69492, 69493, 69499, 69503, 69505, 69506, 69512, 69518, 69520, 69524, 69526, 69529, 69530, 69535, 69536, 69546, 69547, 69550, 69552, 69553, 69556, 69561, 69563, 69566, 69577, 69580, 69584, 69586, 69588, 69591, 69592, 69595, 69596, 69597, 69598, 69603, 69606, 69608, 69610, 69614, 69617, 69620, 69627, 69628, 69638, 69645, 69647, 69651, 69657, 69659, 69660, 69663, 69682, 69683, 69692, 69697, 69703, 69707, 69708, 69710, 69714, 69717, 69728, 69730, 69733, 69734, 69739, 69741, 69742, 69746, 69747, 69752, 69753, 69754, 69755, 69758, 69759, 69760, 69770, 69779, 69781, 69783, 69784, 69791, 69802, 69805, 69806, 69808, 69809, 69812, 69816, 69838, 69839, 69848, 69851, 69857, 69861, 69869, 69871, 69874, 69884, 69885, 69888, 69893, 69894, 69895, 69899, 69903, 69907, 69909, 69910, 69912, 69913, 69914, 69924, 69925, 69930, 69935, 69942, 69944, 69950, 69957, 69964, 69976, 69980, 69981, 69984, 69985, 69986, 69989, 69990, 69992, 69995, 70001, 70004, 70006, 70010, 70011, 70015, 70017, 70024, 70027, 70031, 70032, 70034, 70037, 70040, 70041, 70042, 70044, 70050, 70052, 70053, 70061, 70062, 70063, 70067, 70070, 70072, 70077, 70078, 70080, 70082, 70084, 70088, 70089, 70091, 70095, 70096, 70099, 70102, 70104, 70117, 70119, 70121, 70123, 70140, 70146, 70148, 70149, 70156, 70159, 70162, 70167, 70172, 70174, 70175, 70177, 70178, 70183, 70185, 70186, 70196, 70198, 70201, 70202, 70207, 70219, 70221, 70222, 70225, 70228, 70235, 70241, 70244, 70246, 70251, 70260, 70261, 70263, 70264, 70266, 70272, 70275, 70277, 70280, 70281, 70283, 70287, 70289, 70293, 70298, 70310, 70316, 70323, 70339, 70362, 70363, 70368, 70371, 70376, 70382, 70383, 70385, 70391, 70392, 70393, 70398, 70405, 70407, 70425, 70429, 70434, 70435, 70449, 70451, 70452, 70460, 70461, 70466, 70469, 70474, 70476, 70479, 70497, 70498, 70501, 70504, 70506, 70510, 70518, 70519, 70520, 70526, 70535, 70546, 70553, 70554, 70559, 70561, 70563, 70564, 70565, 70569, 70571, 70573, 70580, 70592, 70594, 70607, 70610, 70618, 70624, 70625, 70630, 70631, 70633, 70635, 70642, 70646, 70648, 70653, 70659, 70664, 70669, 70678, 70681, 70689, 70690, 70699, 70701, 70710, 70715, 70722, 70725, 70730, 70736, 70737, 70747, 70755, 70758, 70760, 70766, 70771, 70774, 70775, 70784, 70786, 70790, 70794, 70795, 70799, 70801, 70806, 70808, 70809, 70818, 70821, 70826, 70827, 70836, 70838, 70843, 70845, 70846, 70849, 70851, 70858, 70863, 70865, 70867, 70869, 70879, 70886, 70889, 70893, 70894, 70896, 70901, 70904, 70905, 70907, 70914, 70915, 70918, 70919, 70921, 70924, 70929, 70930, 70935, 70937, 70939, 70940, 70945, 70947, 70951, 70953, 70956, 70965, 70966, 70969, 70973, 70976, 70978, 70982, 70990, 70991, 70994, 71003, 71008, 71011, 71018, 71020, 71027, 71029, 71033, 71035, 71036, 71037, 71039, 71048, 71052, 71057, 71059, 71060, 71062, 71066, 71067, 71069, 71070, 71072, 71077, 71079, 71085, 71086, 71087, 71091, 71092, 71096, 71103, 71104, 71105, 71108, 71114, 71115, 71124, 71128, 71130, 71134, 71138, 71152, 71153, 71154, 71155, 71157, 71158, 71167, 71168, 71169, 71171, 71174, 71175, 71176, 71181, 71184, 71186, 71187, 71188, 71189, 71191, 71193, 71194, 71195, 71200, 71214, 71215, 71226, 71236, 71243, 71248, 71259, 71260, 71261, 71263, 71267, 71268, 71269, 71276, 71280, 71283, 71288, 71291, 71292, 71295, 71300, 71303, 71311, 71317, 71325, 71327, 71339, 71347, 71350, 71351, 71353, 71358, 71360, 71370, 71372, 71376, 71380, 71384, 71388, 71394, 71399, 71417, 71420, 71423, 71425, 71427, 71432, 71437, 71442, 71448, 71462, 71466, 71467, 71468, 71486, 71492, 71495, 71497, 71499, 71501, 71509, 71518, 71532, 71534, 71535, 71542, 71544, 71547, 71554, 71559, 71565, 71567, 71568, 71571, 71573, 71584, 71585, 71587, 71590, 71601, 71607, 71611, 71612, 71613, 71615, 71619, 71624, 71628, 71636, 71646, 71648, 71651, 71653, 71654, 71656, 71659, 71663, 71665, 71676, 71683, 71685, 71697, 71709, 71710, 71711, 71715, 71718, 71719, 71725, 71732, 71734, 71743, 71747, 71752, 71754, 71755, 71764, 71766, 71772, 71783, 71786, 71792, 71805, 71806, 71808, 71811, 71812, 71819, 71822, 71823, 71825, 71831, 71849, 71850, 71856, 71862, 71864, 71867, 71869, 71870, 71871, 71884, 71887, 71890, 71898, 71905, 71908, 71909, 71917, 71921, 71923, 71926, 71930, 71931, 71932, 71934, 71935, 71936, 71937, 71939, 71940, 71942, 71944, 71950, 71951, 71952, 71954, 71961, 71964, 71968, 71971, 71972, 71978, 71979, 71981, 71986, 71989, 71990, 71994, 71995, 72000, 72020, 72023, 72025, 72032, 72037, 72038, 72048, 72056, 72060, 72065, 72068, 72069, 72073, 72074, 72075, 72078, 72084, 72087, 72088, 72099, 72103, 72107, 72108, 72110, 72111, 72125, 72129, 72138, 72139, 72143, 72146, 72148, 72151, 72157, 72161, 72169, 72171, 72184, 72186, 72187, 72198, 72203, 72205, 72206, 72210, 72212, 72215, 72219, 72233, 72249, 72262, 72277, 72285, 72291, 72298, 72301, 72313, 72321, 72327, 72329, 72331, 72336, 72340, 72341, 72350, 72351, 72358, 72359, 72364, 72376, 72392, 72396, 72398, 72402, 72403, 72405, 72426, 72427, 72428, 72433, 72448, 72452, 72453, 72457, 72458, 72460, 72463, 72467, 72472, 72475, 72476, 72482, 72490, 72494, 72500, 72504, 72505, 72509, 72515, 72516, 72520, 72525, 72528, 72535, 72537, 72543, 72544, 72552, 72553, 72563, 72570, 72571, 72589, 72590, 72591, 72596, 72600, 72606, 72607, 72608, 72611, 72619, 72621, 72629, 72648, 72657, 72660, 72664, 72665, 72669, 72673, 72687, 72693, 72696, 72704, 72705, 72707, 72713, 72722, 72727, 72728, 72729, 72744, 72747, 72750, 72751, 72759, 72767, 72769, 72778, 72784, 72797, 72801, 72809, 72823, 72831, 72833, 72842, 72848, 72852, 72853, 72854, 72855, 72858, 72860, 72864, 72868, 72870, 72872, 72873, 72882, 72887, 72891, 72892, 72901, 72903, 72909, 72910, 72916, 72919, 72926, 72929, 72938, 72942, 72950, 72954, 72962, 72964, 72965, 72968, 72973, 72977, 72980, 72987, 72990, 72998, 72999, 73003, 73004, 73005, 73006, 73009, 73010, 73024, 73025, 73027, 73031, 73032, 73033, 73035, 73044, 73066, 73081, 73091, 73093, 73094, 73105, 73111, 73113, 73121, 73129, 73132, 73141, 73143, 73149, 73156, 73157, 73162, 73163, 73165, 73166, 73168, 73169, 73173, 73174, 73181, 73185, 73191, 73197, 73200, 73203, 73208, 73211, 73214, 73216, 73218, 73223, 73234, 73239, 73240, 73273, 73278, 73279, 73280, 73286, 73296, 73303, 73305, 73313, 73329, 73336, 73340, 73368, 73369, 73370, 73374, 73388, 73393, 73397, 73411, 73413, 73420, 73433, 73435, 73436, 73438, 73444, 73450, 73458, 73469, 73476, 73483, 73485, 73486, 73495, 73499, 73500, 73508, 73517, 73522, 73540, 73548, 73550, 73551, 73555, 73558, 73559, 73571, 73574, 73579, 73582, 73585, 73588, 73590, 73593, 73594, 73595, 73599, 73604, 73605, 73609, 73613, 73614, 73617, 73627, 73628, 73630, 73636, 73637, 73639, 73642, 73646, 73648, 73649, 73653, 73683, 73685, 73686, 73698, 73699, 73708, 73709, 73712, 73717, 73718, 73719, 73742, 73757, 73767, 73769, 73771, 73779, 73787, 73792, 73800, 73810, 73812, 73815, 73817, 73820, 73822, 73824, 73830, 73832, 73833, 73841, 73857, 73858, 73860, 73867, 73870, 73872, 73873, 73876, 73879, 73880, 73886, 73891, 73893, 73898, 73911, 73913, 73919, 73926, 73927, 73931, 73942, 73946, 73948, 73952, 73953, 73955, 73960, 73962, 73963, 73976, 73987, 73992, 73999, 74001, 74008, 74010, 74013, 74014, 74023, 74027, 74032, 74047, 74050, 74061, 74064, 74068, 74074, 74080, 74083, 74086, 74091, 74092, 74097, 74098, 74104, 74112, 74114, 74116, 74121, 74125, 74141, 74143, 74159, 74162, 74166, 74170, 74171, 74178, 74187, 74191, 74207, 74208, 74209, 74213, 74215, 74219, 74240, 74241, 74242, 74245, 74249, 74251, 74253, 74259, 74261, 74263, 74264, 74278, 74282, 74283, 74289, 74292, 74293, 74299, 74308, 74309, 74310, 74322, 74331, 74340, 74343, 74357, 74358, 74360, 74361, 74366, 74370, 74377, 74386, 74387, 74391, 74393, 74394, 74395, 74397, 74399, 74405, 74412, 74413, 74416, 74418, 74421, 74423, 74425, 74426, 74428, 74441, 74448, 74452, 74453, 74459, 74467, 74468, 74475, 74477, 74478, 74483, 74484, 74485, 74495, 74496, 74498, 74500, 74503, 74505, 74515, 74519, 74529, 74531, 74532, 74537, 74541, 74571, 74578, 74582, 74583, 74601, 74602, 74606, 74610, 74628, 74636, 74649, 74651, 74652, 74656, 74659, 74661, 74665, 74676, 74677, 74679, 74682, 74695, 74696, 74702, 74711, 74722, 74723, 74726, 74728, 74729, 74738, 74740, 74741, 74745, 74748, 74756, 74757, 74760, 74770, 74772, 74773, 74780, 74785, 74788, 74790, 74796, 74797, 74798, 74802, 74805, 74810, 74827, 74831, 74841, 74847, 74848, 74854, 74856, 74860, 74863, 74864, 74870, 74874, 74883, 74888, 74897, 74904, 74908, 74917, 74926, 74946, 74962, 74963, 74974, 74977, 74978, 74986, 74999, 75006, 75008, 75010, 75011, 75022, 75023, 75028, 75032, 75034, 75036, 75038, 75044, 75047, 75050, 75055, 75056, 75067, 75083, 75084, 75094, 75096, 75099, 75103, 75104, 75110, 75115, 75122, 75135, 75138, 75150, 75152, 75157, 75159, 75160, 75161, 75162, 75163, 75177, 75180, 75181, 75185, 75188, 75192, 75194, 75196, 75200, 75208, 75214, 75215, 75219, 75236, 75250, 75251, 75255, 75268, 75271, 75283, 75295, 75297, 75309, 75311, 75324, 75337, 75344, 75348, 75359, 75366, 75377, 75383, 75391, 75393, 75397, 75401, 75405, 75407, 75409, 75410, 75413, 75416, 75419, 75443, 75463, 75475, 75479, 75480, 75487, 75509, 75512, 75519, 75520, 75522, 75524, 75525, 75527, 75533, 75540, 75543, 75550, 75555, 75561, 75572, 75573, 75584, 75586, 75587, 75590, 75593, 75604, 75605, 75607, 75617, 75620, 75623, 75636, 75638, 75643, 75650, 75675, 75680, 75687, 75689, 75700, 75703, 75709, 75710, 75715, 75719, 75720, 75726, 75730, 75731, 75742, 75745, 75749, 75755, 75758, 75768, 75796, 75801, 75803, 75804, 75811, 75817, 75819, 75821, 75830, 75836, 75854, 75856, 75861, 75864, 75898, 75901, 75905, 75908, 75915, 75922, 75929, 75932, 75941, 75942, 75947, 75966, 75975, 75977, 75978, 75980, 75988, 76006, 76010, 76017, 76024, 76027, 76028, 76032, 76045, 76068, 76080, 76096, 76108, 76109, 76111, 76120, 76124, 76129, 76130, 76132, 76176, 76183, 76184, 76188, 76193, 76195, 76198, 76211, 76212, 76224, 76228, 76230, 76237, 76240, 76249, 76252, 76253, 76269, 76287, 76295, 76298, 76301, 76306, 76307, 76316, 76323, 76333, 76356, 76360, 76372, 76386, 76389, 76398, 76399, 76406, 76417, 76418, 76419, 76440, 76448, 76450, 76451, 76453, 76461, 76480, 76481, 76485, 76487, 76498, 76500, 76501, 76513, 76514, 76529, 76538, 76547, 76553, 76554, 76558, 76565, 76566, 76570, 76576, 76581, 76594, 76596, 76598, 76608, 76619, 76622, 76623, 76626, 76632, 76636, 76643, 76654, 76656, 76657, 76658, 76663, 76665, 76669, 76678, 76700, 76706, 76707, 76735, 76747, 76750, 76754, 76762, 76764, 76768, 76780, 76791, 76793, 76800, 76803, 76804, 76806, 76813, 76815, 76819, 76822, 76829, 76834, 76836, 76842, 76857, 76869, 76872, 76890, 76895, 76900, 76914, 76942, 76955, 76962, 76971, 76982, 76988, 76993, 77001, 77002, 77006, 77015, 77016, 77017, 77020, 77026, 77043, 77066, 77072, 77093, 77099, 77102, 77105, 77115, 77121, 77125, 77135, 77136, 77139, 77142, 77146, 77151, 77155, 77187, 77199, 77206, 77211, 77215, 77230, 77239, 77243, 77250, 77259, 77260, 77267, 77273, 77281, 77295, 77301, 77304, 77307, 77325, 77326, 77337, 77347, 77359, 77361, 77375, 77380, 77385, 77392, 77393, 77400, 77401, 77405, 77417, 77434, 77441, 77447, 77451, 77452, 77473, 77474, 77486, 77490, 77503, 77517, 77525, 77528, 77543, 77545, 77547, 77553, 77556, 77567, 77575, 77576, 77577, 77586, 77600, 77606, 77630, 77632, 77634, 77640, 77644, 77650, 77653, 77655, 77657, 77659, 77668, 77671, 77681, 77682, 77683, 77691, 77693, 77702, 77703, 77707, 77718, 77720, 77735, 77736, 77739, 77751, 77761, 77765, 77766, 77767, 77770, 77779, 77793, 77799, 77800, 77804, 77811, 77818, 77824, 77829, 77845, 77850, 77862, 77863, 77869, 77873, 77878, 77892, 77903, 77904, 77907, 77913, 77924, 77928, 77943, 77973, 77978, 77995, 78005, 78014, 78016, 78022, 78035, 78038, 78040, 78053, 78057, 78071, 78072, 78078, 78080, 78085, 78086, 78092, 78114, 78131, 78146, 78150, 78160, 78168, 78170, 78171, 78179, 78197, 78203, 78215, 78220, 78224, 78225, 78228, 78233, 78239, 78244, 78251, 78253, 78257, 78261, 78262, 78265, 78281, 78283, 78289, 78293, 78294, 78299, 78301, 78305, 78308, 78319, 78320, 78326, 78327, 78335, 78336, 78346, 78355, 78360, 78364, 78380, 78385, 78389, 78402, 78409, 78429, 78431, 78433, 78438, 78449, 78454, 78473, 78476, 78483, 78489, 78497, 78525, 78536, 78544, 78545, 78557, 78558, 78593, 78602, 78619, 78629, 78632, 78636, 78640, 78648, 78662, 78666, 78668, 78679, 78702, 78703, 78721, 78723, 78726, 78734, 78740, 78742, 78758, 78773, 78774, 78788, 78790, 78793, 78801, 78802, 78812, 78817, 78830, 78832, 78843, 78848, 78859, 78865, 78875, 78877, 78878, 78882, 78883, 78884, 78889, 78894, 78895, 78911, 78914, 78916, 78926, 78927, 78929, 78936, 78951, 78958, 78967, 78970, 78974, 78976, 78988, 78989, 78993, 78997, 79006, 79009, 79010, 79011, 79016, 79018, 79022, 79023, 79031, 79033, 79040, 79048, 79061, 79064, 79066, 79074, 79088, 79097, 79098, 79117, 79125, 79128, 79130, 79138, 79143, 79144, 79145, 79151, 79160, 79161, 79162, 79164, 79165, 79172, 79177, 79180, 79181, 79185, 79188, 79195, 79198, 79212, 79224, 79231, 79239, 79244, 79245, 79255, 79271, 79277, 79281, 79295, 79327, 79328, 79332, 79342, 79361, 79365, 79368, 79378, 79381, 79408, 79413, 79416, 79422, 79429, 79435, 79447, 79451, 79452, 79457, 79463, 79464, 79471, 79472, 79482, 79483, 79484, 79492, 79493, 79499, 79503, 79509, 79511, 79515, 79523, 79529, 79534, 79536, 79547, 79552, 79564, 79565, 79567, 79577, 79578, 79582, 79583, 79584, 79599, 79612, 79613, 79630, 79636, 79644, 79668, 79671, 79674, 79681, 79686, 79690, 79693, 79695, 79705, 79713, 79716, 79720, 79725, 79726, 79728, 79730, 79740, 79742, 79743, 79752, 79753, 79770, 79776, 79788, 79791, 79792, 79795, 79799, 79813, 79816, 79817, 79818, 79829, 79834, 79836, 79837, 79844, 79846, 79849, 79852, 79855, 79857, 79865, 79866, 79871, 79879, 79883, 79892, 79898, 79905, 79907, 79919, 79926, 79928, 79931, 79943, 79945, 79949, 79956, 79991, 80005, 80009, 80011, 80012, 80018, 80025, 80033, 80036, 80042, 80046, 80048, 80052, 80062, 80064, 80069, 80081, 80084, 80086, 80096, 80099, 80117, 80122, 80123, 80124, 80127, 80130, 80136, 80148, 80155, 80167, 80175, 80185, 80186, 80189, 80194, 80197, 80198, 80205, 80209, 80218, 80223, 80230, 80239, 80253, 80259, 80262, 80263, 80270, 80294, 80303, 80304, 80305, 80316, 80318, 80345, 80346, 80356, 80363, 80364, 80371, 80374, 80378, 80380, 80388, 80393, 80400, 80404, 80405, 80406, 80425, 80426, 80433, 80440, 80455, 80457, 80458, 80465, 80473, 80484, 80486, 80492, 80496, 80504, 80506, 80507, 80511, 80514, 80515, 80518, 80523, 80535, 80536, 80549, 80556, 80569, 80577, 80592, 80599, 80616, 80627, 80630, 80632, 80640, 80660, 80662, 80667, 80668, 80675, 80688, 80689, 80692, 80704, 80710, 80713, 80716, 80719, 80726, 80730, 80740, 80745, 80748, 80774, 80778, 80779, 80788, 80799, 80810, 80814, 80822, 80834, 80840, 80844, 80860, 80866, 80867, 80881, 80888, 80894, 80910, 80913, 80923, 80939, 80940, 80944, 80948, 80964, 80978, 80979, 80980, 80981, 81007, 81056, 81064, 81069, 81075, 81082, 81106, 81111, 81115, 81116, 81117, 81138, 81154, 81159, 81163, 81170, 81172, 81192, 81199, 81204, 81217, 81219, 81226, 81227, 81231, 81238, 81241, 81247, 81254, 81256, 81271, 81279, 81284, 81299, 81300, 81310, 81316, 81318, 81323, 81333, 81341, 81355, 81359, 81362, 81371, 81374, 81375, 81378, 81385, 81388, 81400, 81405, 81410, 81437, 81439, 81444, 81448, 81458, 81461, 81467, 81470, 81473, 81480, 81482, 81497, 81507, 81526, 81532, 81538, 81543, 81552, 81554, 81565, 81569, 81573, 81577, 81588, 81600, 81617, 81622, 81626, 81631, 81638, 81654, 81671, 81686, 81688, 81694, 81699, 81701, 81709, 81720, 81731, 81732, 81735, 81740, 81742, 81752, 81753, 81764, 81770, 81773, 81783, 81787, 81795, 81796, 81818, 81825, 81826, 81840, 81842, 81850, 81852, 81853, 81862, 81868, 81869, 81872, 81873, 81877, 81881, 81894, 81917, 81920, 81923, 81927, 81928, 81929, 81934, 81958, 81962, 81979, 81984, 81985, 81999, 82000, 82005, 82011, 82029, 82030, 82034, 82045, 82046, 82049, 82059, 82060, 82061, 82069, 82071, 82072, 82073, 82075, 82080, 82091, 82103, 82107, 82136, 82138, 82139, 82140, 82159, 82164, 82203, 82215, 82226, 82228, 82229, 82240, 82241, 82266, 82272, 82274, 82278, 82280, 82289, 82293, 82294, 82305, 82307, 82310, 82313, 82321, 82323, 82325, 82330, 82331, 82349, 82359, 82370, 82372, 82381, 82385, 82386, 82388, 82396, 82397, 82401, 82410, 82418, 82421, 82424, 82433, 82440, 82444, 82449, 82453, 82455, 82465, 82468, 82474, 82491, 82503, 82506, 82509, 82510, 82513, 82514, 82518, 82519, 82526, 82534, 82541, 82548, 82553, 82564, 82583, 82591, 82592, 82595, 82609, 82611, 82615, 82616, 82624, 82627, 82630, 82653, 82654, 82671, 82674, 82675, 82676, 82678, 82687, 82700, 82707, 82708, 82710, 82711, 82718, 82734, 82746, 82782, 82785, 82804, 82814, 82832, 82838, 82839, 82859, 82860, 82865, 82885, 82891, 82895, 82897, 82903, 82924, 82930, 82934, 82959, 82961, 82967, 82974, 82977, 82991, 82992, 82997, 83008, 83011, 83020, 83035, 83051, 83059, 83064, 83072, 83078, 83079, 83091, 83094, 83100, 83118, 83121, 83140, 83153, 83161, 83172, 83173, 83176, 83178, 83185, 83198, 83205, 83215, 83218, 83224, 83227, 83239, 83247, 83282, 83293, 83294, 83319, 83329, 83334, 83348, 83357, 83364, 83371, 83375, 83384, 83387, 83408, 83412, 83427, 83447, 83457, 83488, 83493, 83512, 83517, 83528, 83529, 83538, 83540, 83546, 83548, 83549, 83558, 83562, 83575, 83577, 83586, 83587, 83594, 83607, 83647, 83656, 83657, 83658, 83662, 83673, 83674, 83679, 83685, 83691, 83711, 83716, 83726, 83729, 83734, 83739, 83743, 83763, 83770, 83774, 83781, 83786, 83790, 83794, 83795, 83805, 83811, 83812, 83819, 83823, 83825, 83828, 83839, 83855, 83856, 83872, 83874, 83876, 83877, 83878, 83896, 83903, 83904, 83921, 83936, 83938, 83940, 83949, 83954, 83959, 83971, 83979, 83999, 84015, 84022, 84025, 84032, 84039, 84042, 84053, 84062, 84063, 84067, 84068, 84076, 84078, 84096, 84098, 84105, 84106, 84108, 84131, 84133, 84139, 84149, 84166, 84167, 84168, 84183, 84189, 84193, 84198, 84204, 84230, 84250, 84255, 84258, 84276, 84280, 84296, 84297, 84298, 84299, 84330, 84342, 84347, 84349, 84352, 84360, 84369, 84377, 84378, 84382, 84403, 84406, 84407, 84411, 84416, 84434, 84450, 84453, 84464, 84467, 84474, 84483, 84511, 84516, 84535, 84539, 84548, 84550, 84554, 84566, 84601, 84606, 84613, 84614, 84623, 84625, 84627, 84639, 84642, 84650, 84689, 84709, 84712, 84720, 84730, 84740, 84743, 84751, 84773, 84779, 84790, 84800, 84804, 84806, 84812, 84832, 84836, 84848, 84857, 84871, 84879, 84892, 84893, 84908, 84913, 84926, 84943, 84950, 84957, 84983, 84984, 84990, 84992, 85041, 85053, 85062, 85076, 85077, 85088, 85094, 85111, 85121, 85124, 85132, 85135, 85138, 85147, 85174, 85176, 85178, 85191, 85206, 85228, 85242, 85265, 85277, 85278, 85283, 85285, 85290, 85305, 85308, 85325, 85346, 85347, 85349, 85351, 85354, 85359, 85360, 85362, 85387, 85389, 85408, 85415, 85432, 85434, 85435, 85440, 85453, 85456, 85463, 85465, 85466, 85469, 85479, 85480, 85493, 85500, 85505, 85510, 85532, 85542, 85550, 85563, 85564, 85573, 85600, 85608, 85609, 85617, 85637, 85640, 85647, 85654, 85667, 85674, 85688, 85690, 85696, 85708, 85717, 85720, 85736, 85738, 85744, 85753, 85762, 85794, 85812, 85833, 85836, 85852, 85860, 85863, 85867, 85869, 85871, 85874, 85877, 85883, 85885, 85887, 85902, 85903, 85924, 85925, 85927, 85938, 85945, 85954, 85958, 85960, 85966, 85971, 85977, 85980, 85995, 85997, 85999, 86001, 86009, 86012, 86022, 86029, 86049, 86050, 86063, 86087, 86099, 86118, 86123, 86138, 86148, 86159, 86179, 86192, 86199, 86219, 86220, 86221, 86226, 86228, 86229, 86244, 86245, 86247, 86260, 86271, 86294, 86315, 86322, 86333, 86334, 86335, 86355, 86358, 86363, 86374, 86391, 86399, 86414, 86424, 86428, 86437, 86443, 86444, 86475, 86480, 86485, 86493, 86501, 86515, 86517, 86521, 86530, 86551, 86560, 86566, 86567, 86575, 86583, 86592, 86596, 86602, 86605, 86610, 86640, 86645, 86649, 86655, 86656, 86667, 86675, 86676, 86679, 86683, 86710, 86717, 86721, 86723, 86730, 86747, 86756, 86761, 86773, 86789, 86801, 86802, 86810, 86818, 86820, 86827, 86840, 86843, 86867, 86872, 86880, 86881, 86894, 86908, 86910, 86938, 86948, 86960, 86963, 86994, 86997, 87007, 87016, 87026, 87039, 87061, 87067, 87069, 87079, 87092, 87115, 87123, 87124, 87126, 87136, 87170, 87178, 87182, 87202, 87203, 87206, 87207, 87209, 87212, 87219, 87248, 87269, 87271, 87280, 87297, 87304, 87314, 87330, 87339, 87347, 87360, 87364, 87368, 87373, 87374, 87377, 87390, 87392, 87401, 87405, 87413, 87421, 87426, 87429, 87445, 87449, 87465, 87471, 87477, 87485, 87488, 87491, 87507, 87509, 87512, 87518, 87521, 87522, 87527, 87543, 87547, 87550, 87567, 87568, 87581, 87592, 87597, 87598, 87604, 87617, 87637, 87640, 87646, 87655, 87675, 87678, 87691, 87706, 87710, 87714, 87715, 87716, 87719, 87724, 87727, 87732, 87740, 87750, 87753, 87758, 87761, 87782, 87792, 87796, 87810, 87814, 87839, 87847, 87867, 87871, 87876, 87877, 87878, 87884, 87885, 87902, 87919, 87934, 87944, 87947, 87952, 87968, 87988, 87994, 87995, 88001, 88009, 88010, 88031, 88042, 88051, 88068, 88076, 88077, 88079, 88085, 88091, 88123, 88134, 88137, 88150, 88167, 88175, 88177, 88203, 88226, 88230, 88242, 88250, 88259, 88277, 88310, 88312, 88330, 88346, 88347, 88349, 88356, 88361, 88365, 88367, 88395, 88397, 88400, 88403, 88404, 88409, 88414, 88416, 88434, 88457, 88460, 88491, 88501, 88510, 88513, 88516, 88523, 88529, 88532, 88552, 88561, 88570, 88571, 88588, 88590, 88593, 88621, 88630, 88632, 88642, 88644, 88652, 88659, 88704, 88705, 88717, 88720, 88726, 88729, 88732, 88747, 88748, 88753, 88761, 88763, 88765, 88775, 88784, 88789, 88792, 88812, 88819, 88826, 88832, 88839, 88845, 88850, 88870, 88873, 88874, 88891, 88893, 88906, 88923, 88927, 88928, 88933, 88936, 88942, 88949, 88954, 88974, 88996, 89016, 89023, 89034, 89065, 89068, 89087, 89098, 89109, 89126, 89150, 89186, 89202, 89203, 89222, 89228, 89230, 89235, 89240, 89243, 89246, 89249, 89253, 89260, 89275, 89288, 89297, 89301, 89315, 89336, 89357, 89362, 89369, 89377, 89380, 89403, 89416, 89424, 89430, 89431, 89439, 89449, 89456, 89459, 89467, 89474, 89479, 89482, 89485, 89493, 89500, 89505, 89507, 89523, 89529, 89548, 89554, 89564, 89567, 89589, 89595, 89599, 89600, 89608, 89637, 89643, 89666, 89676, 89690, 89692, 89707, 89730, 89745, 89753, 89756, 89758, 89759, 89765, 89766, 89772, 89820, 89835, 89838, 89847, 89855, 89878, 89885, 89900, 89904, 89909, 89913, 89922, 89935, 89945, 89951, 89952, 89955, 89961, 89962, 89963, 89977, 89978, 89988, 89995, 90004, 90034, 90046, 90047, 90048, 90055, 90057, 90064, 90068, 90074, 90076, 90083, 90088, 90105, 90117, 90145, 90160, 90165, 90173, 90180, 90186, 90197, 90211, 90213, 90232, 90266, 90269, 90272, 90278, 90301, 90317, 90318, 90329, 90333, 90335, 90346, 90353, 90356, 90384, 90391, 90396, 90400, 90402, 90410, 90413, 90430, 90434, 90439, 90464, 90475, 90483, 90489, 90495, 90507, 90517, 90538, 90567, 90577, 90585, 90589, 90593, 90601, 90604, 90610, 90624, 90629, 90632, 90638, 90676, 90690, 90698, 90704, 90713, 90729, 90735, 90738, 90741, 90752, 90755, 90756, 90757, 90762, 90787, 90789, 90792, 90808, 90815, 90839, 90840, 90851, 90866, 90891, 90893, 90895, 90898, 90913, 90939, 90949, 90961, 90989, 90990, 90991, 90996, 91007, 91030, 91033, 91038, 91050, 91051, 91054, 91066, 91071, 91078, 91093, 91102, 91106, 91107, 91122, 91151, 91152, 91156, 91157, 91163, 91164, 91169, 91181, 91198, 91199, 91203, 91225, 91227, 91243, 91252, 91261, 91266, 91268, 91279, 91284, 91315, 91322, 91325, 91335, 91342, 91351, 91354, 91365, 91368, 91380, 91388, 91397, 91405, 91406, 91411, 91417, 91418, 91422, 91426, 91430, 91435, 91449, 91466, 91485, 91492, 91505, 91508, 91525, 91527, 91534, 91540, 91550, 91560, 91567, 91572, 91578, 91579, 91597, 91602, 91609, 91627, 91628, 91629, 91640, 91666, 91685, 91687, 91694, 91708, 91711, 91715, 91723, 91759, 91761, 91795, 91816, 91848, 91851, 91853, 91868, 91877, 91878, 91879, 91884, 91889, 91898, 91902, 91918, 91922, 91923, 91925, 91927, 91928, 91930, 91933, 91940, 91942, 91957, 91959, 91967, 91971, 92001, 92010, 92014, 92015, 92089, 92090, 92099, 92103, 92120, 92126, 92134, 92152, 92156, 92166, 92209, 92215, 92226, 92237, 92239, 92251, 92279, 92304, 92320, 92329, 92355, 92360, 92377, 92381, 92391, 92398, 92425, 92432, 92439, 92453, 92454, 92476, 92477, 92482, 92502, 92513, 92550, 92556, 92560, 92581, 92590, 92605, 92607, 92616, 92631, 92641, 92642, 92643, 92660, 92661, 92668, 92678, 92680, 92700, 92711, 92724, 92733, 92740, 92749, 92757, 92759, 92764, 92770, 92776, 92793, 92795, 92798, 92802, 92814, 92818, 92831, 92840, 92850, 92865, 92870, 92871, 92884, 92897, 92899, 92914, 92915, 92924, 92931, 92945, 92951, 92957, 92976, 92998, 93007, 93011, 93018, 93031, 93042, 93044, 93055, 93062, 93068, 93074, 93084, 93103, 93108, 93114, 93124, 93127, 93129, 93132, 93137, 93142, 93150, 93162, 93174, 93193, 93221, 93230, 93238, 93246, 93254, 93265, 93270, 93272, 93275, 93293, 93296, 93297, 93298, 93300, 93318, 93319, 93323, 93343, 93360, 93364, 93371, 93382, 93383, 93387, 93388, 93392, 93397, 93400, 93401, 93406, 93417, 93437, 93448, 93452, 93477, 93478, 93482, 93494, 93497, 93504, 93513, 93516, 93521, 93528, 93540, 93542, 93554, 93555, 93565, 93569, 93570, 93583, 93594, 93595, 93619, 93624, 93642, 93648, 93660, 93661, 93677, 93679, 93697, 93699, 93705, 93716, 93719, 93720, 93732, 93737, 93746, 93752, 93773, 93778, 93784, 93803, 93807, 93817, 93823, 93830, 93834, 93844, 93852, 93858, 93862, 93863, 93889, 93893, 93895, 93898, 93905, 93919, 93921, 93922, 93930, 93931, 93938, 93946, 93961, 93964, 93971, 93978, 93984, 93986, 94007, 94011, 94012, 94021, 94025, 94037, 94039, 94043, 94063, 94076, 94077, 94079, 94082, 94116, 94118, 94122, 94126, 94141, 94142, 94159, 94172, 94177, 94191, 94194, 94198, 94203, 94208, 94210, 94234, 94240, 94251, 94253, 94258, 94272, 94289, 94293, 94295, 94316, 94320, 94327, 94361, 94364, 94366, 94367, 94396, 94401, 94420, 94446, 94459, 94462, 94469, 94483, 94486, 94499, 94504, 94508, 94511, 94527, 94532, 94558, 94565, 94568, 94571, 94579, 94584, 94586, 94587, 94592, 94593, 94614, 94644, 94654, 94663, 94683, 94686, 94699, 94725, 94737, 94738, 94742, 94746, 94753, 94767, 94774, 94789, 94794, 94797, 94809, 94815, 94819, 94837, 94842, 94843, 94845, 94847, 94857, 94862, 94868, 94885, 94888, 94890, 94894, 94904, 94915, 94948, 94954, 94968, 94969, 94981, 94982, 94984, 94987, 94994, 95006, 95009, 95035, 95036, 95047, 95051, 95062, 95072, 95099, 95115, 95138, 95166, 95174, 95182, 95197, 95225, 95242, 95245, 95248, 95266, 95269, 95280, 95283, 95284, 95325, 95331, 95337, 95361, 95364, 95366, 95375, 95383, 95394, 95396, 95401, 95402, 95415, 95430, 95436, 95450, 95466, 95470, 95480, 95488, 95507, 95509, 95512, 95513, 95515, 95521, 95523, 95527, 95529, 95532, 95550, 95581, 95589, 95595, 95611, 95622, 95625, 95629, 95631, 95671, 95675, 95691, 95697, 95699, 95720, 95746, 95747, 95748, 95761, 95777, 95788, 95813, 95818, 95845, 95859, 95871, 95897, 95917, 95918, 95921, 95942, 95947, 95949, 95952, 95953, 95963, 95967, 95968, 95990, 96002, 96009, 96022, 96026, 96063, 96072, 96083, 96086, 96087, 96094, 96099, 96112, 96117, 96126, 96167, 96176, 96182, 96191, 96200, 96205, 96206, 96264, 96275, 96282, 96296, 96306, 96329, 96333, 96353, 96354, 96367, 96381, 96385, 96390, 96393, 96396, 96404, 96410, 96435, 96445, 96446, 96465, 96482, 96484, 96497, 96501, 96504, 96514, 96529, 96567, 96574, 96586, 96589, 96591, 96592, 96593, 96594, 96614, 96616, 96624, 96627, 96646, 96651, 96657, 96661, 96662, 96671, 96682, 96687, 96689, 96690, 96693, 96703, 96705, 96715, 96716, 96726, 96745, 96747, 96755, 96756, 96759, 96773, 96774, 96775, 96787, 96807, 96820, 96823, 96824, 96839, 96840, 96847, 96848, 96854, 96860, 96865, 96870, 96879, 96885, 96900, 96928, 96961, 96963, 96964, 96970, 96971, 96992, 96993, 96998, 97005, 97019, 97022, 97023, 97044, 97053, 97057, 97061, 97067, 97068, 97069, 97071, 97083, 97106, 97131, 97135, 97144, 97171, 97179, 97183, 97195, 97210, 97217, 97220, 97223, 97234, 97241, 97244, 97246, 97250, 97255, 97258, 97262, 97263, 97265, 97268, 97272, 97293, 97313, 97321, 97339, 97340, 97347, 97365, 97377, 97387, 97390, 97400, 97401, 97414, 97420, 97427, 97430, 97437, 97460, 97477, 97485, 97496, 97503, 97508, 97528, 97535, 97536, 97542, 97550, 97558, 97564, 97600, 97607, 97623, 97634, 97642, 97659, 97664, 97679, 97703, 97752, 97757, 97765, 97767, 97768, 97774, 97785, 97786, 97810, 97811, 97818, 97826, 97829, 97832, 97849, 97864, 97868, 97873, 97877, 97879, 97906, 97910, 97936, 97947, 97948, 97949, 97953, 97959, 97964, 97990, 97994, 98001, 98006, 98009, 98023, 98026, 98042, 98046, 98059, 98060, 98129, 98153, 98160, 98169, 98188, 98196, 98205, 98219, 98222, 98230, 98238, 98243, 98258, 98262, 98263, 98266, 98276, 98283, 98288, 98293, 98315, 98319, 98326, 98330, 98331, 98346, 98349, 98354, 98356, 98385, 98395, 98396, 98398, 98399, 98419, 98422, 98425, 98430, 98457, 98470, 98480, 98487, 98503, 98513, 98526, 98537, 98544, 98561, 98575, 98579, 98600, 98602, 98613, 98614, 98625, 98630, 98631, 98632, 98644, 98647, 98648, 98653, 98657, 98658, 98660, 98676, 98677, 98678, 98693, 98694, 98718, 98724, 98737, 98738, 98740, 98776, 98793, 98797, 98799, 98808, 98812, 98813, 98820, 98824, 98831, 98839, 98842, 98847, 98849, 98850, 98870, 98871, 98872, 98887, 98892, 98893, 98894, 98896, 98912, 98928, 98937, 98942, 98944, 98948, 98955, 98959, 98971, 98998, 98999, 99019, 99023, 99051, 99053, 99054, 99059, 99064, 99073, 99074, 99075, 99077, 99083, 99096, 99097, 99108, 99113, 99128, 99129, 99133, 99139, 99151, 99158, 99171, 99182, 99183, 99205, 99207, 99213, 99228, 99229, 99236, 99247, 99256, 99278, 99303, 99313, 99316, 99325, 99326, 99348, 99354, 99359, 99363, 99364, 99372, 99374, 99376, 99394, 99410, 99417, 99457, 99468, 99470, 99478, 99486, 99498, 99501, 99526, 99530, 99532, 99537, 99548, 99584, 99588, 99593, 99600, 99601, 99619, 99625, 99629, 99648, 99650, 99675, 99704, 99727, 99732, 99739, 99740, 99748, 99751, 99753, 99783, 99790, 99792, 99811, 99812, 99813, 99814, 99822, 99832, 99852, 99876, 99878, 99880, 99897, 99902, 99903, 99914, 99924, 99926, 99928, 99955, 99965, 99970, 99972, 99974, 99989, 99996, 100003, 100008, 100011, 100014, 100025, 100035, 100051, 100052, 100054, 100057, 100067, 100077, 100081, 100089, 100091, 100092, 100107, 100108, 100115, 100130, 100131, 100139, 100142, 100148, 100149, 100151, 100173, 100183, 100212, 100218, 100222, 100252, 100254, 100266, 100268, 100271, 100282, 100286, 100298, 100304, 100308, 100324, 100325, 100328, 100338, 100339, 100345, 100365, 100368, 100391, 100453, 100461, 100476, 100477, 100489, 100490, 100510, 100534, 100535, 100544, 100555, 100556, 100557, 100559, 100583, 100602, 100618, 100619, 100620, 100626, 100641, 100659, 100665, 100671, 100680, 100682, 100696, 100702, 100711, 100720, 100721, 100731, 100751, 100760, 100768, 100770, 100777, 100792, 100798, 100805, 100814, 100822, 100842, 100843, 100861, 100866, 100879, 100887, 100903, 100908, 100909, 100917, 100923, 100938, 100961, 100965, 100973, 100979, 100980, 100982, 100987, 101003, 101006, 101010, 101028, 101037, 101038, 101053, 101058, 101062, 101083, 101102, 101117, 101129, 101132, 101135, 101136, 101144, 101147, 101165, 101189, 101196, 101202, 101211, 101216, 101226, 101228, 101230, 101236, 101238, 101252, 101268, 101270, 101272, 101287, 101296, 101300, 101301, 101302, 101319, 101321, 101327, 101331, 101332, 101336, 101338, 101341, 101342, 101357, 101361, 101388, 101417, 101418, 101422, 101426, 101432, 101435, 101439, 101447, 101453, 101457, 101458, 101464, 101479, 101483, 101490, 101508, 101509, 101514, 101519, 101523, 101530, 101539, 101540, 101553, 101572, 101573, 101585, 101587, 101601, 101606, 101616, 101624, 101625, 101627, 101631, 101632, 101635, 101662, 101665, 101670, 101675, 101679, 101686, 101704, 101706, 101717, 101718, 101727, 101728, 101731, 101735, 101750, 101768, 101773, 101778, 101779, 101781, 101789, 101800, 101824, 101826, 101848, 101855, 101858, 101863, 101864, 101872, 101882, 101888, 101900, 101909, 101918, 101937, 101946, 101978, 101990, 101992, 101993, 102009, 102013, 102021, 102039, 102062, 102063, 102066, 102078, 102087, 102103, 102114, 102119, 102120, 102121, 102138, 102140, 102143, 102151, 102157, 102185, 102190, 102194, 102204, 102216, 102221, 102222, 102225, 102228, 102231, 102234, 102242, 102243, 102252, 102256, 102285, 102288, 102292, 102299, 102302, 102303, 102309, 102311, 102326, 102342, 102364, 102371, 102385, 102401, 102402, 102412, 102435, 102455, 102474, 102478, 102479, 102484, 102493, 102496, 102510, 102523, 102530, 102558, 102569, 102570, 102588, 102604, 102615, 102638, 102650, 102661, 102665, 102678, 102681, 102683, 102687, 102691, 102697, 102701, 102710, 102726, 102727, 102733, 102739, 102740, 102744, 102749, 102756, 102771, 102775, 102793, 102809, 102814, 102823, 102832, 102834, 102848, 102856, 102857, 102871, 102876, 102877, 102881, 102882, 102886, 102895, 102909, 102919, 102926, 102935, 102936, 102940, 102943, 102953, 102956, 102957, 102961, 102972, 102994, 102997, 103000, 103006, 103024, 103026, 103031, 103034, 103040, 103050, 103053, 103057, 103065, 103086, 103095, 103116, 103135, 103137, 103139, 103142, 103143, 103148, 103149, 103152, 103161, 103165, 103174, 103192, 103198, 103213, 103221, 103222, 103227, 103229, 103233, 103237, 103253, 103258, 103271, 103279, 103298, 103309, 103321, 103322, 103331, 103334, 103341, 103342, 103343, 103370, 103374, 103379, 103390, 103396, 103404, 103421, 103451, 103459, 103475, 103484, 103496, 103500, 103505, 103540, 103546, 103550, 103551, 103552, 103560, 103577, 103587, 103588, 103595, 103600, 103601, 103602, 103603, 103610, 103622, 103625, 103638, 103644, 103649, 103664, 103665, 103668, 103671, 103679, 103702, 103714, 103715, 103716, 103728, 103738, 103757, 103762, 103769, 103784, 103786, 103790, 103791, 103796, 103817, 103826, 103835, 103840, 103858, 103859, 103874, 103887, 103893, 103900, 103905, 103912, 103916, 103918, 103919, 103920, 103921, 103934, 103940, 103949, 103962, 103975, 103976, 103979, 103980, 103981, 103985, 103992, 104002, 104003, 104007, 104017, 104024, 104029, 104042, 104055, 104061, 104066, 104070, 104075, 104103, 104118, 104120, 104122, 104154, 104155, 104161, 104162, 104187, 104206, 104236, 104244, 104252, 104259, 104260, 104264, 104279, 104284, 104294, 104297, 104298, 104311, 104319, 104320, 104326, 104327, 104339, 104348, 104360, 104382, 104393, 104395, 104408, 104418, 104424, 104425, 104438, 104453, 104455, 104479, 104486, 104490, 104491, 104495, 104498, 104503, 104506, 104511, 104522, 104524, 104530, 104531, 104538, 104540, 104551, 104577, 104578, 104593, 104594, 104601, 104608, 104616, 104622, 104642, 104658, 104665, 104675, 104680, 104697, 104721, 104722, 104723, 104729, 104736, 104755, 104763, 104773, 104788, 104795, 104810, 104816, 104819, 104831, 104836, 104837, 104838, 104839, 104854, 104857, 104867, 104877, 104887, 104892, 104898, 104902, 104908, 104911, 104912, 104917, 104923, 104928, 104934, 104953, 104964, 104978, 104981, 105011, 105016, 105019, 105034, 105044, 105052, 105054, 105079, 105101, 105117, 105124, 105140, 105144, 105145, 105147, 105149, 105152, 105163, 105164, 105180, 105198, 105214, 105227, 105243, 105253, 105259, 105274, 105278, 105281, 105291, 105297, 105306, 105307, 105311, 105326, 105334, 105340, 105345, 105355, 105391, 105404, 105420, 105425, 105428, 105429, 105434, 105435, 105438, 105453, 105459, 105461, 105466, 105478, 105482, 105503, 105512, 105518, 105519, 105521, 105535, 105539, 105542, 105554, 105564, 105566, 105571, 105598, 105602, 105614, 105616, 105634, 105641, 105649, 105672, 105693, 105694, 105712, 105719, 105727, 105737, 105754, 105766, 105768, 105774, 105775, 105780, 105785, 105787, 105793, 105795, 105799, 105802, 105805, 105813, 105842, 105844, 105852, 105866, 105873, 105876, 105888, 105902, 105906, 105925, 105930, 105934, 105942, 105947, 105962, 105977, 105992, 105996, 106012, 106015, 106021, 106026, 106028, 106037, 106043, 106061, 106063, 106077, 106079, 106086, 106091, 106098, 106099, 106104, 106109, 106116, 106121, 106128, 106131, 106172, 106173, 106174, 106188, 106192, 106194, 106197, 106216, 106221, 106234, 106237, 106249, 106250, 106259, 106268, 106271, 106275, 106294, 106297, 106315, 106333, 106346, 106348, 106355, 106356, 106358, 106359, 106369, 106379, 106411, 106412, 106467, 106468, 106469, 106486, 106488, 106490, 106505, 106518, 106550, 106561, 106580, 106607, 106625, 106626, 106629, 106634, 106636, 106637, 106643, 106649, 106650, 106660, 106687, 106704, 106706, 106743, 106750, 106761, 106777, 106784, 106794, 106802, 106805, 106810, 106811, 106814, 106828, 106836, 106847, 106848, 106871, 106876, 106895, 106899, 106900, 106901, 106907, 106909, 106910, 106917, 106922, 106923, 106928, 106933, 106936, 106937, 106945, 106962, 106978, 106998, 107005, 107010, 107024, 107030, 107032, 107047, 107049, 107058, 107059, 107063, 107076, 107093, 107094, 107103, 107104, 107112, 107118, 107119, 107139, 107150, 107159, 107186, 107200, 107201, 107207, 107210, 107244, 107246, 107253, 107254, 107267, 107269, 107272, 107273, 107290, 107322, 107345, 107350, 107371, 107383, 107390, 107395, 107398, 107399, 107414, 107450, 107467, 107494, 107544, 107557, 107558, 107565, 107566, 107594, 107598, 107610, 107633, 107641, 107655, 107661, 107675, 107689, 107691, 107698, 107705, 107707, 107717, 107719, 107727, 107728, 107729, 107732, 107750, 107762, 107775, 107791, 107792, 107802, 107835, 107870, 107873, 107874, 107885, 107886, 107904, 107911, 107963, 107981, 107988, 107989, 107990, 107999, 108010, 108018, 108056, 108065, 108077, 108085, 108102, 108104, 108112, 108125, 108130, 108135, 108137, 108177, 108181, 108184, 108185, 108188, 108196, 108213, 108214, 108223, 108226, 108232, 108238, 108243, 108255, 108270, 108280, 108285, 108313, 108323, 108329, 108348, 108350, 108367, 108377, 108391, 108401, 108412, 108426, 108433, 108445, 108469, 108496, 108506, 108508, 108525, 108533, 108539, 108545, 108557, 108558, 108572, 108576, 108577, 108586, 108589, 108601, 108602, 108611, 108644, 108649, 108650, 108660, 108673, 108687, 108688, 108689, 108700, 108715, 108727, 108783, 108784, 108789, 108796, 108846, 108858, 108865, 108868, 108873, 108877, 108929, 108938, 108945, 108964, 108969, 108981, 109022, 109029, 109034, 109043, 109048, 109056, 109063, 109065, 109087, 109110, 109111, 109116, 109122, 109131, 109154, 109156, 109157, 109158, 109168, 109180, 109186, 109205, 109206, 109220, 109224, 109238, 109306, 109309, 109374, 109381, 109385, 109392, 109397, 109438, 109496, 109503, 109509, 109512, 109568, 109576, 109582, 109585, 109593, 109595, 109622, 109644, 109645, 109661, 109712, 109727, 109751, 109753, 109760, 109772, 109789, 109793, 109813, 109832, 109837, 109849, 109872, 109893, 109894, 109943, 109957, 109997, 110006, 110021, 110029, 110034, 110047, 110052, 110068, 110075, 110095, 110104, 110111, 110117, 110157, 110160, 110189, 110211, 110230, 110254, 110261, 110286, 110292, 110299, 110318, 110352, 110375, 110416, 110448, 110457, 110459, 110474, 110480, 110497, 110502, 110528, 110535, 110537, 110540, 110546, 110547, 110558, 110560, 110587, 110603, 110620, 110650, 110678, 110683, 110690, 110696, 110711, 110715, 110718, 110729, 110735, 110739, 110764, 110769, 110791, 110797, 110800, 110820, 110844, 110860, 110916, 110940, 110944, 110945, 110946, 110962, 110963, 110966, 110976, 111000, 111051, 111052, 111055, 111057, 111061, 111103, 111113, 111136, 111165, 111169, 111181, 111183, 111218, 111234, 111244, 111251, 111304, 111310, 111351, 111357, 111375, 111388, 111429, 111430, 111444, 111454, 111456, 111472, 111473, 111474, 111481, 111512, 111536, 111539, 111547, 111570, 111589, 111597, 111617, 111686, 111688, 111707, 111720, 111728, 111731, 111744, 111745, 111746, 111754, 111765, 111767, 111781, 111791, 111804, 111808, 111814, 111816, 111818, 111840, 111859, 111860, 111878, 111893, 111897, 111906, 111925, 111943, 111944, 111959, 111986, 112012, 112046, 112059, 112060, 112061, 112075, 112089, 112108, 112135, 112143, 112158, 112244, 112253, 112262, 112273, 112305, 112306, 112319, 112324, 112402, 112435, 112477, 112488, 112538, 112542, 112549, 112552, 112568, 112571, 112588, 112596, 112603, 112620, 112635, 112646, 112656, 112663, 112667, 112691, 112702, 112721, 112746, 112749, 112789, 112820, 112830, 112869, 112891, 112897, 112921, 112932, 112944, 112989, 113016, 113028, 113042, 113055, 113074, 113089, 113092, 113109, 113127, 113172, 113205, 113207, 113218, 113242, 113250, 113256, 113265, 113275, 113299, 113301, 113314, 113317, 113328, 113352, 113357, 113365, 113384, 113388, 113400, 113409, 113421, 113428, 113440, 113494, 113497, 113505, 113522, 113530, 113543, 113560, 113565, 113580, 113605, 113613, 113615, 113629, 113634, 113666, 113671, 113678, 113715, 113735, 113753, 113770, 113788, 113794, 113801, 113809, 113828, 113839, 113841, 113844, 113868, 113905, 113941, 113944, 113950, 113962, 113988, 113989, 113995, 113999, 114005, 114033, 114038, 114045, 114051, 114070, 114071, 114099, 114101, 114102, 114105, 114122, 114135, 114137, 114141, 114152, 114167, 114172, 114194, 114213, 114224, 114229, 114282, 114285, 114289, 114291, 114297, 114306, 114315, 114328, 114329, 114337, 114338, 114357, 114358, 114365, 114377, 114380, 114390, 114401, 114405, 114413, 114427, 114448, 114465, 114467, 114470, 114478, 114489, 114505, 114520, 114540, 114563, 114564, 114569, 114579, 114607, 114634, 114637, 114638, 114655, 114706, 114708, 114722, 114730, 114735, 114752, 114755, 114759, 114771, 114772, 114784, 114786, 114788, 114792, 114794, 114799, 114827, 114833, 114842, 114845, 114864, 114875, 114901, 114912, 114915, 114930, 114962, 114967, 114970, 114997, 115012, 115017, 115030, 115060, 115078, 115096, 115109, 115124, 115151, 115164, 115172, 115177, 115180, 115190, 115192, 115215, 115224, 115235, 115250, 115257, 115301, 115320, 115346, 115361, 115363, 115364, 115366, 115368, 115386, 115393, 115397, 115418, 115420, 115449, 115458, 115465, 115467, 115480, 115486, 115536, 115539, 115561, 115569, 115578, 115583, 115601, 115611, 115622, 115625, 115649, 115672, 115704, 115744, 115762, 115774, 115805, 115813, 115817, 115822, 115830, 115861, 115866, 115876, 115896, 115898, 115904, 115905, 115920, 115934, 115943, 115961, 115970, 115973, 115974, 115982, 116018, 116019, 116032, 116034, 116035, 116052, 116053, 116067, 116075, 116098, 116117, 116145, 116175, 116228, 116278, 116300, 116350, 116351, 116361, 116364, 116438, 116454, 116496, 116505, 116542, 116545, 116553, 116568, 116595, 116605, 116608, 116640, 116677, 116680, 116695, 116720, 116721, 116750, 116769, 116881, 116884, 116897, 116909, 116917, 116937, 116944, 116968, 116994, 117004, 117008, 117011, 117015, 117033, 117047, 117060, 117069, 117086, 117097, 117104, 117119, 117154, 117195, 117196, 117201, 117226, 117233, 117246, 117289, 117295, 117297, 117352, 117379, 117381, 117401, 117407, 117417, 117443, 117444, 117468, 117470, 117483, 117493, 117494, 117514, 117522, 117542, 117551, 117564, 117567, 117617, 117650, 117662, 117671, 117674, 117675, 117699, 117713, 117762, 117787, 117810, 117836, 117837, 117888, 117892, 117901, 117907, 117921, 117969, 117981, 118009, 118021, 118025, 118026, 118100, 118133, 118160, 118163, 118171, 118174, 118183, 118188, 118189, 118208, 118211, 118224, 118230, 118273, 118298, 118316, 118331, 118336, 118345, 118358, 118359, 118369, 118371, 118390, 118392, 118404, 118405, 118455, 118458, 118469, 118488, 118492, 118495, 118500, 118518, 118533, 118549, 118562, 118570, 118576, 118597, 118602, 118651, 118664, 118667, 118708, 118720, 118737, 118742, 118746, 118771, 118785, 118797, 118801, 118830, 118834, 118860, 118947, 118960, 118989, 118994, 119056, 119071, 119112, 119121, 119132, 119163, 119179, 119184, 119204, 119208, 119250, 119267, 119311, 119350, 119416, 119421, 119449, 119478, 119526, 119555, 119565, 119603, 119682, 119700, 119704, 119718, 119743, 119765, 119797, 119799, 119810, 119823, 119831, 119836, 119858, 119864, 119890, 119974, 119984, 119999, 120029, 120048, 120063, 120065, 120081, 120100, 120102, 120113, 120125, 120139, 120157, 120211, 120219, 120229, 120251, 120277, 120293, 120324, 120329, 120352, 120364, 120365, 120400, 120418, 120466, 120482, 120485, 120495, 120503, 120519, 120535, 120569, 120610, 120612, 120684, 120696, 120708, 120716, 120717, 120722, 120739, 120762, 120812, 120846, 120860, 120867, 120874, 120888, 120903, 120946, 120948, 120949, 120954, 120957, 120969, 121002, 121020, 121029, 121042, 121079, 121108, 121116, 121140, 121157, 121171, 121219, 121253, 121254, 121262, 121269, 121279, 121290, 121328, 121342, 121378, 121384, 121393, 121422, 121425, 121469, 121470, 121489, 121535, 121545, 121568, 121624, 121655, 121689, 121721, 121723, 121757, 121770, 121794, 121795, 121811, 121843, 121846, 121852, 121930, 121996, 122010, 122021, 122113, 122114, 122121, 122184, 122210, 122232, 122241, 122256, 122257, 122280, 122286, 122303, 122306, 122358, 122361, 122366, 122372, 122379, 122426, 122457, 122462, 122466, 122482, 122512, 122551, 122577, 122621, 122628, 122634, 122672, 122685, 122726, 122876, 122925, 122936, 122955, 122982, 122986, 122990, 123002, 123061, 123072, 123090, 123146, 123173, 123179, 123284, 123297, 123329, 123331, 123430, 123432, 123435, 123437, 123439, 123538, 123606, 123607, 123673, 123683, 123784, 123816, 123858, 123898, 123935, 123949, 123954, 123981, 123994, 123995, 124010, 124091, 124133, 124135, 124167, 124190, 124191, 124244, 124252, 124269, 124270, 124374, 124379, 124388, 124392, 124395, 124408, 124412, 124417, 124471, 124492, 124535, 124693, 124719, 124727, 124740, 124767, 124768, 124769, 124816, 124825, 124826, 124846, 124870, 124872, 124910, 124916, 124921, 124927, 124945, 124957, 125062, 125103, 125115, 125139, 125141, 125176, 125181, 125221, 125308, 125326, 125352, 125368, 125373, 125398, 125521, 125537, 125567, 125593, 125609, 125611, 125617, 125667, 125707, 125720, 125783, 125797, 125798, 125801, 125952, 126021, 126070, 126089, 126111, 126121, 126127, 126129, 126163, 126229, 126251, 126256, 126280, 126311, 126359, 126360, 126446, 126477, 126549, 126564, 126587, 126640, 126666, 126706, 126719, 126815, 126816, 126844, 126845, 126846, 126912, 126913, 126914, 126943, 126974, 127031, 127057, 127074, 127083, 127087, 127091, 127123, 127139, 127173, 127178, 127189, 127208, 127263, 127273, 127289, 127317, 127333, 127334, 127340, 127349, 127398, 127425, 127431, 127463, 127551, 127606, 127635, 127654, 127656, 127734, 127743, 127752, 127786, 127844, 127971, 127989, 127994, 128018, 128033, 128081, 128120, 128139, 128142, 128153, 128213, 128237, 128249, 128250, 128259, 128274, 128282, 128304, 128367, 128485, 128519, 128595, 128635, 128653, 128657, 128678, 128681, 128683, 128716, 128766, 128778, 128824, 128875, 128877, 128892, 128893, 128923, 128936, 128948, 128968, 128987, 129001, 129002, 129030, 129040, 129071, 129073, 129114, 129132, 129134, 129142, 129147, 129159, 129193, 129209, 129217, 129223, 129226, 129240, 129247, 129261, 129287, 129332, 129375, 129398, 129405, 129487, 129514, 129522, 129553, 129627, 129639, 129643, 129651, 129678, 129689, 129692, 129711, 129715, 129733, 129746, 129766, 129771, 129784, 129878, 129904, 129922, 129923, 129973, 129985, 129988, 130041, 130058, 130086, 130092, 130118, 130126, 130178, 130186, 130236, 130249, 130266, 130280, 130320, 130326, 130377, 130411, 130423, 130427, 130482, 130544, 130576, 130581, 130617, 130628, 130642, 130665, 130695, 130767, 130769, 130770, 130780, 130854, 130875, 130889, 130923, 130924, 130936, 130968, 130998, 131132, 131154, 131199, 131201, 131203, 131228, 131229, 131256, 131281, 131313, 131331, 131352, 131434, 131466, 131505, 131525, 131528, 131533, 131543, 131578, 131588, 131615, 131632, 131643, 131658, 131664, 131682, 131715, 131744, 131788, 131805, 131828, 131869, 131871, 131872, 131874, 131886, 131980, 131983, 131998, 132024, 132030, 132031, 132057, 132064, 132080, 132111, 132130, 132168, 132227, 132238, 132239, 132303, 132305, 132317, 132345, 132379, 132386, 132409, 132436, 132443, 132449, 132459, 132465, 132475, 132477, 132501, 132534, 132548, 132628, 132648, 132679, 132683, 132690, 132702, 132759, 132785, 132786, 132810, 132858, 132892, 132893, 132918, 132928, 132943, 132944, 132955, 132992, 132997, 133010, 133018, 133020, 133034, 133067, 133076, 133083, 133088, 133095, 133154, 133173, 133204, 133233, 133238, 133254, 133263, 133328, 133330, 133340, 133347, 133409, 133487, 133497, 133511, 133523, 133533, 133536, 133570, 133603, 133629, 133638, 133669, 133670, 133687, 133708, 133724, 133731, 133801, 133831, 133839, 133857, 133883, 133914, 133934, 133956, 133981, 134004, 134052, 134086, 134092, 134094, 134101, 134102, 134125, 134157, 134172, 134179, 134200, 134217, 134295, 134335, 134368, 134396, 134429, 134453, 134470, 134503, 134548, 134566, 134616, 134662, 134665, 134691, 134695, 134706, 134730, 134789, 134828, 134850, 134897, 134920, 134931, 134944, 134947, 134966, 135054, 135070, 135126, 135145, 135150, 135159, 135173, 135209, 135210, 135228, 135279, 135311, 135316, 135327, 135329, 135337, 135338, 135347, 135419, 135420, 135473, 135495, 135499, 135519, 135550, 135593, 135636, 135654, 135684, 135710, 135739, 135741, 135749, 135782, 135785, 135810, 135817, 135905, 135954, 135980, 136004, 136026, 136050, 136077, 136120, 136131, 136186, 136205, 136209, 136217, 136246, 136248, 136261, 136322, 136345, 136354, 136368, 136401, 136404, 136420, 136440, 136458, 136503, 136555, 136556, 136568, 136583, 136597, 136639, 136650, 136683, 136692, 136709, 136741, 136759, 136795, 136797, 136803, 136832, 136861, 136862, 136881, 136899, 136908, 136917, 136936, 136937, 136969, 136996, 137003, 137005, 137013, 137014, 137031, 137048, 137058, 137060, 137062, 137067, 137115, 137122, 137170, 137171, 137177, 137187, 137206, 137217, 137233, 137283, 137284, 137294, 137295, 137300, 137350, 137425, 137484, 137505, 137510, 137527, 137530, 137544, 137580, 137600, 137606, 137621, 137640, 137644, 137650, 137729, 137740, 137755, 137757, 137845, 137852, 137864, 137916, 137935, 137950, 137982, 137989, 137990, 138010, 138020, 138029, 138030, 138062, 138093, 138100, 138123, 138151, 138172, 138192, 138201, 138211, 138214, 138238, 138251, 138273, 138274, 138332, 138385, 138428, 138454, 138465, 138468, 138529, 138558, 138563, 138574, 138586, 138606, 138684, 138695, 138719, 138737, 138753, 138799, 138823, 138834, 138835, 138843, 138859, 138861, 138869, 138891, 138895, 138906, 138943, 138952, 138958, 138982, 138997, 139001, 139014, 139020, 139051, 139083, 139091, 139136, 139138, 139142, 139169, 139256, 139269, 139280, 139283, 139300, 139330, 139343, 139351, 139364, 139366, 139375, 139377, 139379, 139410, 139415, 139418, 139425, 139426, 139436, 139491, 139501, 139515, 139526, 139544, 139573, 139577, 139579, 139582, 139612, 139622, 139626, 139628, 139677, 139684, 139695, 139730, 139767, 139805, 139818, 139858, 139877, 139888, 139896, 139936, 139984, 140009, 140014, 140065, 140066, 140093, 140121, 140124, 140175, 140213, 140238, 140239, 140267, 140317, 140355, 140360, 140370, 140403, 140439, 140446, 140533, 140537, 140540, 140559, 140567, 140586, 140588, 140632, 140648, 140670, 140698, 140700, 140716, 140719, 140734, 140759, 140763, 140798, 140837, 140857, 140902, 140987, 141024, 141141, 141178, 141201, 141238, 141240, 141271, 141293, 141374, 141400, 141441, 141458, 141462, 141481, 141491, 141515, 141527, 141530, 141547, 141610, 141631, 141657, 141666, 141670, 141674, 141675, 141684, 141685, 141698, 141749, 141756, 141800, 141877, 141905, 141931, 142075, 142081, 142090, 142116, 142119, 142136, 142156, 142167, 142176, 142194, 142207, 142210, 142212, 142223, 142226, 142227, 142231, 142251, 142278, 142286, 142328, 142346, 142354, 142369, 142383, 142398, 142434, 142469, 142485, 142525, 142527, 142560, 142592, 142602, 142624, 142637, 142643, 142685, 142686, 142707, 142765, 142837, 142839, 142840, 142940, 142946, 142948, 142969, 142997, 143043, 143066, 143085, 143098, 143099, 143112, 143131, 143132, 143180, 143194, 143203, 143225, 143227, 143232, 143298, 143301, 143313, 143325, 143330, 143355, 143424, 143425, 143432, 143434, 143442, 143456, 143460, 143513, 143543, 143562, 143632, 143645, 143646, 143673, 143702, 143721, 143740, 143768, 143823, 143826, 143831, 143864, 143900, 143909, 143935, 143936, 143941, 144029, 144038, 144080, 144081, 144084, 144099, 144134, 144150, 144151, 144190, 144285, 144308, 144332, 144408, 144433, 144454, 144468, 144479, 144489, 144490, 144537, 144542, 144568, 144583, 144591, 144603, 144604, 144631, 144637, 144645, 144657, 144665, 144697, 144785, 144828, 144833, 144854, 144858, 144888, 144915, 144967, 144991, 145001, 145026, 145027, 145028, 145029, 145030, 145031, 145032, 145033, 145034, 145035, 145036, 145037, 145038, 145039, 145040, 145041, 145042, 145043, 145044, 145045, 145048, 145051, 145053, 145054, 145055, 145056, 145057, 145058, 145059, 145060, 145061, 145062, 145063, 145068, 145074, 145077, 145080, 145090, 145092, 145096, 145097, 145105, 145106, 145110, 145113, 145115, 145116, 145120, 145122, 145150, 145152, 145169, 145177, 145179, 145198, 145199, 145201, 145207, 145213, 145214, 145226, 145234, 145243, 145283, 145291, 145292, 145294, 145303, 145304, 145306, 145317, 145331, 145367, 145368, 145369, 145375, 145385, 145414, 145443, 145477, 145487, 145498, 145509, 145538, 145541, 145543, 145544, 145563, 145575, 145577, 145587, 145594, 145603, 145606, 145637, 145640, 145662, 145670, 145671, 145685, 145703, 145720, 145734, 145741, 145742, 145759, 145765, 145786, 145787, 145798, 145801, 145803, 145830, 145835, 145849, 145853, 145859, 145860, 145861, 145862, 145863, 145864, 145865, 145866, 145867, 145868, 145869, 145870, 145871, 145872, 145873, 145874, 145875, 145876, 145877, 145878, 145879, 145880, 145881, 145882, 145883, 145884, 145885, 145886, 145887, 145888, 145889, 145890, 145891, 145892, 145893, 145894, 145895, 145896, 145897, 145898, 145899, 145900, 145901, 145902, 145903, 145904, 145905, 145906, 145908, 145909, 145910, 145911, 145912, 145913, 145914, 145915, 145916, 145917, 145918, 145919, 145920, 145921, 145922, 145923, 145924, 145925, 145926, 145927, 145929, 145930, 145931, 145932, 145933, 145934, 145935, 145936, 145937, 145938, 145939, 145940, 145941, 145942, 145943, 145944, 145945, 145946, 145947, 145948, 145949, 145950, 145951, 145952, 145953, 145954, 145955, 145956, 145957, 145958, 145959, 145960, 145961, 145962, 145963, 145964, 145965, 145966, 145967, 145968, 145969, 145970, 145971, 145972, 145973, 145974, 145975, 145976, 145977, 145978, 145979, 145980, 145981, 145982, 145983, 145984, 145985, 145986, 145987, 145988, 145989, 145990, 145991, 145992, 145993, 145994, 145995, 145996, 145997, 145998, 145999, 146000, 146001, 146002, 146003, 146004, 146005, 146006, 146008, 146009, 146010, 146011, 146012, 146013, 146014, 146015, 146016, 146017, 146018, 146019, 146020, 146021, 146022, 146023, 146024, 146025, 146026, 146028, 146029, 146030, 146031, 146032, 146033, 146034, 146035, 146036, 146037, 146038, 146039, 146040, 146041, 146042, 146043, 146044, 146045, 146046, 146047, 146049, 146050, 146051, 146052, 146053, 146054, 146055, 146056, 146057, 146058, 146059, 146061, 146062, 146063, 146064, 146065, 146066, 146067, 146068, 146069, 146070, 146071, 146072, 146073, 146074, 146075, 146076, 146077, 146078, 146079, 146080, 146081, 146082, 146083, 146084, 146086, 146087, 146088, 146089, 146090, 146091, 146092, 146093, 146094, 146095, 146096, 146097, 146098, 146099, 146100, 146102, 146103, 146104, 146105, 146106, 146107, 146108, 146109, 146110, 146111, 146112, 146113, 146114, 146115, 146116, 146117, 146118, 146119, 146120, 146121, 146122, 146123, 146124, 146126, 146127, 146128, 146129, 146130, 146131, 146132, 146133, 146134, 146135, 146136, 146137, 146138, 146139, 146140, 146141, 146142, 146143, 146144, 146145, 146146, 146147, 146148, 146149, 146150, 146151, 146152, 146153, 146154, 146155, 146156, 146158, 146159, 146160, 146161, 146162, 146163, 146164, 146165, 146167, 146168, 146169, 146170, 146171, 146172, 146173, 146174, 146175, 146176, 146177, 146178, 146179, 146180, 146181, 146182, 146183, 146184, 146185, 146186, 146188, 146189, 146190, 146191, 146192, 146195, 146196, 146197, 146198, 146199, 146200, 146202, 146203, 146204, 146205, 146207, 146208, 146209, 146210, 146211, 146212, 146214, 146215, 146216, 146218, 146219, 146220, 146221, 146222, 146223, 146224, 146225, 146226, 146227, 146228, 146229, 146230, 146231, 146232, 146233, 146234, 146235, 146237, 146238, 146239, 146240, 146241, 146242, 146243, 146244, 146245, 146246, 146247, 146248, 146249, 146250, 146251, 146252, 146253, 146254, 146255, 146256, 146257, 146258, 146260, 146261, 146262, 146263, 146264, 146265, 146268, 146269, 146270, 146271, 146272, 146273, 146274, 146275, 146276, 146278, 146279, 146280, 146281, 146282, 146283, 146286, 146287, 146288, 146289, 146290, 146291, 146292, 146293, 146294, 146295, 146296, 146297, 146298, 146299, 146300, 146301, 146303, 146305, 146306, 146307, 146308, 146309, 146310, 146311, 146312, 146313, 146315, 146316, 146317, 146318, 146319, 146320, 146321, 146322, 146323, 146324, 146325, 146326, 146327, 146328, 146329, 146330, 146331, 146332, 146334, 146335, 146336, 146337, 146338, 146339, 146340, 146341, 146344, 146345, 146346, 146347, 146349, 146350, 146351, 146353, 146354, 146357, 146358, 146359, 146360, 146361, 146362, 146363, 146364, 146365, 146366, 146367, 146368, 146370, 146372, 146373, 146374, 146375, 146376, 146379, 146380, 146381, 146382, 146383, 146384, 146385, 146386, 146387, 146389, 146390, 146391, 146392, 146394, 146395, 146398, 146399, 146400, 146401, 146402, 146403, 146404, 146405, 146406, 146407, 146408, 146410, 146411, 146412, 146413, 146414, 146416, 146417, 146418, 146419, 146420, 146421, 146422, 146423, 146424, 146426, 146427, 146428, 146429, 146432, 146433, 146435, 146436, 146437, 146438, 146439, 146440, 146441, 146444, 146445, 146446, 146447, 146448, 146449, 146450, 146451, 146452, 146453, 146454, 146455, 146456, 146457, 146458, 146459, 146460, 146461, 146463, 146464, 146466, 146468, 146469, 146470, 146471, 146472, 146473, 146475, 146476, 146477, 146479, 146480, 146482, 146483, 146484, 146485, 146486, 146487, 146488, 146489, 146490, 146491, 146492, 146493, 146494, 146496, 146498, 146499, 146500, 146502, 146503, 146504, 146505, 146506, 146507, 146508, 146509, 146510, 146511, 146512, 146513, 146514, 146515, 146516, 146517, 146518, 146519, 146520, 146521, 146522, 146523, 146526, 146527, 146528, 146529, 146530, 146531, 146533, 146534, 146535, 146537, 146539, 146541, 146542, 146546, 146547, 146548, 146549, 146550, 146551, 146553, 146554, 146555, 146556, 146558, 146559, 146560, 146561, 146562, 146563, 146564, 146565, 146567, 146568, 146569, 146570, 146571, 146572, 146573, 146574, 146575, 146576, 146577, 146578, 146580, 146581, 146582, 146583, 146585, 146586, 146588, 146589, 146592, 146594, 146595, 146597, 146598, 146599, 146600, 146602, 146603, 146604, 146605, 146606, 146607, 146610, 146612, 146613, 146614, 146615, 146617, 146618, 146619, 146620, 146621, 146622, 146624, 146626, 146627, 146628, 146631, 146632, 146634, 146638, 146639, 146640, 146642, 146644, 146645, 146646, 146647, 146648, 146649, 146650, 146651, 146652, 146653, 146654, 146655, 146656, 146658, 146659, 146660, 146662, 146664, 146666, 146667, 146668, 146669, 146670, 146671, 146672, 146673, 146674, 146675, 146677, 146678, 146679, 146680, 146682, 146683, 146684, 146685, 146686, 146689, 146690, 146692, 146693, 146694, 146696, 146698, 146699, 146700, 146701, 146702, 146705, 146706, 146709, 146710, 146713, 146715, 146716, 146718, 146719, 146720, 146721, 146722, 146726, 146728, 146729, 146734, 146736, 146737, 146738, 146740, 146743, 146744, 146745, 146746, 146749, 146750, 146751, 146753, 146754, 146756, 146757, 146758, 146759, 146760, 146761, 146762, 146763, 146765, 146767, 146768, 146769, 146771, 146772, 146773, 146774, 146775, 146777, 146778, 146779, 146780, 146781, 146782, 146783, 146785, 146786, 146787, 146788, 146790, 146791, 146792, 146794, 146795, 146796, 146797, 146799, 146800, 146801, 146802, 146804, 146805, 146806, 146807, 146808, 146809, 146810, 146811, 146812, 146814, 146816, 146817, 146819, 146821, 146822, 146823, 146825, 146827, 146828, 146829, 146830, 146831, 146832, 146833, 146835, 146836, 146838, 146839, 146841, 146843, 146844, 146846, 146848, 146849, 146851, 146852, 146856, 146857, 146858, 146859, 146860, 146861, 146862, 146863, 146864, 146865, 146866, 146867, 146869, 146870, 146871, 146872, 146873, 146876, 146877, 146878, 146879, 146882, 146883, 146885, 146886, 146888, 146889, 146890, 146892, 146893, 146895, 146896, 146897, 146898, 146899, 146901, 146903, 146904, 146905, 146906, 146907, 146909, 146911, 146912, 146913, 146914, 146916, 146920, 146924, 146925, 146927, 146930, 146932, 146933, 146934, 146936, 146937, 146938, 146939, 146940, 146942, 146943, 146945, 146946, 146947, 146949, 146950, 146952, 146953, 146956, 146957, 146960, 146961, 146962, 146963, 146964, 146965, 146966, 146968, 146969, 146970, 146971, 146973, 146974, 146976, 146977, 146978, 146979, 146980, 146981, 146982, 146984, 146985, 146987, 146988, 146994, 146996, 146997, 146999, 147001, 147002, 147003, 147004, 147005, 147006, 147007, 147008, 147009, 147010, 147012, 147013, 147014, 147015, 147016, 147020, 147021, 147023, 147024, 147026, 147027, 147028, 147029, 147032, 147033, 147035, 147036, 147037, 147038, 147040, 147041, 147042, 147045, 147047, 147048, 147049, 147050, 147053, 147057, 147058, 147059, 147060, 147061, 147063, 147064, 147065, 147066, 147067, 147070, 147071, 147072, 147073, 147074, 147075, 147077, 147080, 147081, 147084, 147085, 147086, 147087, 147088, 147089, 147091, 147093, 147094, 147095, 147096, 147097, 147098, 147099, 147101, 147103, 147105, 147107, 147108, 147109, 147110, 147111, 147113, 147115, 147116, 147117, 147118, 147119, 147121, 147122, 147125, 147126, 147127, 147129, 147130, 147132, 147134, 147135, 147136, 147141, 147143, 147144, 147149, 147150, 147153, 147154, 147155, 147156, 147157, 147158, 147160, 147162, 147164, 147165, 147167, 147169, 147171, 147173, 147174, 147175, 147176, 147177, 147178, 147181, 147183, 147184, 147186, 147188, 147192, 147193, 147194, 147199, 147200, 147201, 147202, 147204, 147205, 147206, 147208, 147211, 147212, 147216, 147217, 147218, 147219, 147220, 147228, 147229, 147232, 147233, 147236, 147240, 147241, 147242, 147245, 147246, 147247, 147248, 147249, 147252, 147253, 147255, 147256, 147257, 147258, 147259, 147261, 147262, 147263, 147264, 147265, 147266, 147268, 147270, 147271, 147272, 147273, 147275, 147277, 147278, 147279, 147280, 147281, 147282, 147286, 147293, 147294, 147298, 147300, 147301, 147303, 147304, 147307, 147310, 147311, 147312, 147313, 147315, 147318, 147319, 147322, 147324, 147325, 147326, 147327, 147329, 147331, 147334, 147335, 147337, 147339, 147340, 147342, 147343, 147345, 147346, 147351, 147353, 147355, 147356, 147359, 147360, 147363, 147364, 147365, 147367, 147371, 147374, 147378, 147379, 147380, 147381, 147383, 147389, 147393, 147394, 147395, 147396, 147398, 147399, 147401, 147402, 147406, 147408, 147409, 147410, 147411, 147413, 147415, 147417, 147418, 147419, 147421, 147423, 147424, 147426, 147429, 147430, 147433, 147434, 147435, 147436, 147437, 147439, 147445, 147447, 147449, 147450, 147452, 147453, 147454, 147455, 147456, 147459, 147465, 147468, 147469, 147470, 147471, 147473, 147478, 147479, 147480, 147481, 147486, 147487, 147488, 147490, 147492, 147493, 147495, 147500, 147501, 147504, 147505, 147508, 147509, 147510, 147511, 147512, 147515, 147516, 147517, 147520, 147521, 147522, 147528, 147529, 147530, 147532, 147534, 147536, 147538, 147539, 147540, 147546, 147549, 147551, 147552, 147554, 147555, 147556, 147557, 147560, 147563, 147564, 147568, 147569, 147570, 147571, 147572, 147573, 147574, 147575, 147577, 147578, 147580, 147581, 147582, 147583, 147585, 147586, 147587, 147588, 147589, 147590, 147591, 147592, 147593, 147597, 147598, 147599, 147600, 147601, 147602, 147603, 147604, 147606, 147607, 147610, 147611, 147613, 147614, 147615, 147616, 147619, 147621, 147622, 147624, 147627, 147628, 147630, 147631, 147633, 147634, 147635, 147636, 147637, 147638, 147639, 147641, 147642, 147644, 147650, 147651, 147652, 147653, 147654, 147655, 147658, 147659, 147660, 147661, 147662, 147663, 147666, 147668, 147669, 147670, 147672, 147678, 147680, 147681, 147682, 147683, 147686, 147687, 147689, 147691, 147692, 147693, 147695, 147696, 147698, 147701, 147702, 147703, 147704, 147706, 147707, 147708, 147709, 147710, 147711, 147712, 147715, 147716, 147719, 147720, 147721, 147723, 147725, 147728, 147729, 147730, 147732, 147734, 147736, 147737, 147739, 147742, 147743, 147744, 147746, 147749, 147750, 147753, 147754, 147756, 147760, 147761, 147762, 147764, 147766, 147768, 147770, 147771, 147772, 147775, 147776, 147777, 147779, 147780, 147781, 147782, 147784, 147785, 147786, 147789, 147790, 147791, 147792, 147793, 147795, 147796, 147798, 147799, 147800, 147802, 147805, 147806, 147809, 147812, 147813, 147815, 147818, 147820, 147823, 147829, 147831, 147832, 147833, 147834, 147836, 147837, 147838, 147839, 147840, 147841, 147842, 147844, 147848, 147849, 147850, 147851, 147853, 147854, 147856, 147857, 147858, 147862, 147863, 147864, 147865, 147866, 147869, 147870, 147871, 147872, 147873, 147874, 147876, 147877, 147878, 147879, 147881, 147883, 147885, 147886, 147887, 147888, 147889, 147890, 147891, 147895, 147896, 147899, 147900, 147901, 147902, 147903, 147904, 147905, 147908, 147910, 147914, 147916, 147917, 147919, 147922, 147924, 147928, 147931, 147933, 147941, 147943, 147944, 147945, 147948, 147950, 147958, 147960, 147961, 147964, 147967, 147968, 147969, 147971, 147973, 147977, 147978, 147980, 147984, 147985, 147987, 147991, 147994, 147995, 147996, 147998, 148002, 148003, 148005, 148009, 148011, 148015, 148016, 148017, 148018, 148021, 148024, 148026, 148027, 148028, 148029, 148030, 148033, 148034, 148039, 148040, 148041, 148042, 148044, 148045, 148049, 148053, 148054, 148055, 148060, 148068, 148069, 148070, 148073, 148075, 148079, 148080, 148082, 148083, 148084, 148086, 148088, 148092, 148094, 148096, 148098, 148101, 148102, 148103, 148104, 148107, 148108, 148111, 148113, 148114, 148115, 148116, 148118, 148121, 148124, 148126, 148127, 148129, 148130, 148132, 148133, 148135, 148137, 148139, 148141, 148144, 148145, 148147, 148153, 148158, 148164, 148166, 148168, 148170, 148171, 148172, 148176, 148179, 148180, 148182, 148184, 148185, 148187, 148190, 148191, 148193, 148196, 148197, 148199, 148203, 148204, 148205, 148207, 148211, 148214, 148215, 148217, 148218, 148220, 148223, 148229, 148231, 148232, 148233, 148234, 148235, 148237, 148238, 148240, 148242, 148243, 148245, 148248, 148249, 148252, 148253, 148257, 148260, 148261, 148262, 148263, 148268, 148273, 148274, 148280, 148281, 148283, 148284, 148285, 148286, 148287, 148292, 148296, 148300, 148301, 148302, 148304, 148305, 148306, 148308, 148313, 148315, 148317, 148321, 148323, 148324, 148326, 148329, 148330, 148332, 148333, 148335, 148338, 148342, 148345, 148349, 148350, 148352, 148353, 148357, 148362, 148366, 148367, 148369, 148371, 148373, 148375, 148377, 148378, 148382, 148383, 148386, 148387, 148388, 148389, 148390, 148393, 148394, 148399, 148401, 148407, 148410, 148413, 148414, 148415, 148420, 148421, 148422, 148425, 148428, 148430, 148431, 148434, 148437, 148439, 148441, 148442, 148445, 148449, 148452, 148453, 148454, 148456, 148457, 148458, 148459, 148461, 148467, 148471, 148472, 148474, 148477, 148478, 148479, 148482, 148484, 148486, 148488, 148489, 148495, 148496, 148498, 148500, 148501, 148502, 148503, 148504, 148505, 148506, 148510, 148511, 148514, 148515, 148517, 148518, 148521, 148522, 148524, 148525, 148526, 148527, 148531, 148533, 148534, 148535, 148538, 148539, 148540, 148541, 148544, 148549, 148553, 148554, 148556, 148560, 148561, 148562, 148565, 148567, 148568, 148569, 148570, 148571, 148572, 148574, 148575, 148576, 148577, 148578, 148579, 148581, 148583, 148584, 148588, 148592, 148594, 148596, 148598, 148599, 148600, 148601, 148603, 148605, 148610, 148613, 148614, 148615, 148616, 148617, 148619, 148620, 148621, 148622, 148626, 148628, 148631, 148632, 148633, 148634, 148635, 148639, 148648, 148654, 148656, 148660, 148661, 148664, 148665, 148666, 148668, 148669, 148671, 148672, 148674, 148677, 148682, 148683, 148684, 148689, 148690, 148692, 148693, 148694, 148696, 148697, 148698, 148700, 148701, 148702, 148703, 148704, 148705, 148706, 148707, 148709, 148710, 148711, 148712, 148713, 148716, 148719, 148721, 148722, 148726, 148730, 148731, 148733, 148734, 148735, 148736, 148739, 148740, 148743, 148744, 148749, 148750, 148753, 148758, 148763, 148764, 148766, 148768, 148770, 148775, 148776, 148779, 148780, 148783, 148785, 148788, 148789, 148790, 148793, 148794, 148795, 148797, 148802, 148803, 148808, 148812, 148814, 148817, 148821, 148822, 148824, 148830, 148832, 148833, 148834, 148835, 148838, 148846, 148850, 148852, 148853, 148854, 148856, 148861, 148862, 148864, 148868, 148871, 148873, 148874, 148876, 148877, 148879, 148881, 148892, 148899, 148901, 148902, 148933, 148952, 149029, 149112, 149338, 149859, 149860, 149861, 149862, 149863, 149864, 149865, 149866, 149867, 149868, 149869, 149870, 149871, 149873, 149874, 149875, 149876, 149877, 149878, 149879, 149880, 149881, 149882, 149883, 149884, 149885, 149886, 149887, 149888, 149889, 149890, 149891, 149892, 149893, 149894, 149895, 149896, 149897, 149898, 149899, 149900, 149901, 149902, 149904, 149905, 149906, 149907, 149908, 149909, 149910, 149911, 149912, 149913, 149914, 149915, 149916, 149917, 149918, 149919, 149920, 149921, 149922, 149923, 149924, 149925, 149926, 149927, 149928, 149929, 149930, 149931, 149932, 149933, 149934, 149935, 149936, 149937, 149938, 149939, 149940, 149941, 149942, 149943, 149944, 149945, 149946, 149947, 149948, 149949, 149950, 149951, 149952, 149953, 149954, 149955, 149956, 149957, 149958, 149959, 149960, 149961, 149962, 149963, 149964, 149965, 149966, 149967, 149968, 149969, 149970, 149971, 149972, 149973, 149974, 149975, 149976, 149977, 149978, 149979, 149980, 149981, 149982, 149983, 149984, 149985, 149986, 149987, 149988, 149989, 149990, 149991, 149992, 149994, 149995, 149996, 149997, 149998, 149999, 150000, 150001, 150002, 150003, 150004, 150005, 150006, 150007, 150008, 150009, 150010, 150011, 150012, 150013, 150014, 150015, 150016, 150017, 150018, 150019, 150021, 150022, 150023, 150024, 150025, 150026, 150027, 150028, 150029, 150030, 150031, 150032, 150033, 150034, 150035, 150036, 150037, 150038, 150039, 150040, 150041, 150042, 150043, 150044, 150046, 150047, 150048, 150051, 150052, 150053, 150054, 150055, 150056, 150058, 150059, 150060, 150061, 150062, 150063, 150064, 150065, 150066, 150068, 150069, 150070, 150071, 150074, 150075, 150076, 150077, 150078, 150079, 150081, 150082, 150083, 150084, 150086, 150087, 150088, 150089, 150090, 150091, 150092, 150093, 150094, 150095, 150096, 150097, 150098, 150099, 150100, 150102, 150103, 150104, 150105, 150106, 150107, 150109, 150110, 150112, 150113, 150114, 150115, 150116, 150117, 150118, 150120, 150121, 150124, 150125, 150126, 150127, 150128, 150129, 150130, 150131, 150132, 150133, 150134, 150135, 150136, 150137, 150138, 150139, 150140, 150141, 150142, 150144, 150145, 150146, 150147, 150148, 150149, 150150, 150151, 150152, 150153, 150154, 150156, 150157, 150158, 150159, 150161, 150162, 150163, 150164, 150166, 150167, 150168, 150169, 150170, 150171, 150172, 150173, 150175, 150176, 150177, 150178, 150179, 150180, 150182, 150183, 150184, 150185, 150186, 150187, 150188, 150189, 150190, 150191, 150192, 150194, 150195, 150196, 150197, 150198, 150200, 150201, 150202, 150204, 150205, 150206, 150207, 150209, 150210, 150211, 150212, 150214, 150215, 150216, 150218, 150219, 150220, 150221, 150222, 150223, 150225, 150226, 150227, 150229, 150230, 150231, 150232, 150233, 150234, 150235, 150237, 150238, 150239, 150240, 150241, 150242, 150243, 150244, 150245, 150246, 150247, 150248, 150249, 150250, 150252, 150253, 150254, 150255, 150256, 150258, 150259, 150260, 150261, 150262, 150264, 150265, 150266, 150267, 150268, 150269, 150270, 150271, 150272, 150273, 150274, 150278, 150279, 150282, 150283, 150284, 150286, 150287, 150288, 150289, 150291, 150292, 150293, 150294, 150296, 150298, 150299, 150300, 150301, 150302, 150303, 150304, 150305, 150306, 150307, 150308, 150309, 150310, 150311, 150313, 150315, 150316, 150317, 150318, 150320, 150322, 150323, 150325, 150326, 150327, 150329, 150330, 150332, 150333, 150334, 150335, 150337, 150338, 150340, 150344, 150345, 150346, 150347, 150348, 150349, 150350, 150351, 150352, 150353, 150354, 150355, 150357, 150358, 150359, 150360, 150362, 150363, 150365, 150366, 150367, 150368, 150369, 150372, 150373, 150374, 150376, 150377, 150378, 150379, 150380, 150381, 150382, 150383, 150384, 150385, 150386, 150387, 150388, 150389, 150390, 150391, 150392, 150393, 150394, 150395, 150396, 150397, 150398, 150399, 150400, 150401, 150402, 150403, 150404, 150405, 150406, 150407, 150409, 150410, 150411, 150412, 150415, 150416, 150417, 150419, 150420, 150422, 150423, 150424, 150425, 150427, 150429, 150430, 150431, 150432, 150433, 150434, 150435, 150436, 150437, 150438, 150439, 150440, 150441, 150442, 150443, 150444, 150445, 150446, 150447, 150448, 150450, 150452, 150453, 150455, 150457, 150459, 150460, 150462, 150463, 150464, 150465, 150466, 150467, 150468, 150470, 150471, 150473, 150474, 150475, 150476, 150478, 150479, 150480, 150481, 150482, 150485, 150487, 150488, 150489, 150490, 150491, 150492, 150493, 150494, 150495, 150496, 150497, 150498, 150499, 150500, 150501, 150502, 150503, 150504, 150506, 150508, 150509, 150510, 150512, 150513, 150514, 150515, 150517, 150519, 150520, 150522, 150523, 150524, 150525, 150527, 150528, 150529, 150530, 150532, 150535, 150536, 150537, 150538, 150539, 150542, 150543, 150544, 150545, 150546, 150547, 150548, 150550, 150552, 150553, 150554, 150555, 150557, 150558, 150559, 150560, 150561, 150562, 150563, 150564, 150565, 150566, 150567, 150568, 150570, 150572, 150573, 150574, 150575, 150576, 150578, 150579, 150580, 150581, 150582, 150583, 150584, 150585, 150587, 150589, 150590, 150591, 150592, 150594, 150595, 150596, 150597, 150598, 150600, 150602, 150603, 150604, 150608, 150609, 150610, 150611, 150613, 150615, 150617, 150618, 150620, 150622, 150623, 150624, 150625, 150626, 150627, 150628, 150629, 150630, 150631, 150632, 150633, 150634, 150635, 150637, 150638, 150641, 150642, 150643, 150644, 150646, 150648, 150649, 150651, 150653, 150654, 150655, 150657, 150658, 150659, 150660, 150661, 150662, 150664, 150665, 150666, 150667, 150669, 150670, 150671, 150672, 150673, 150674, 150676, 150677, 150678, 150680, 150681, 150682, 150683, 150684, 150687, 150688, 150689, 150690, 150692, 150693, 150694, 150695, 150696, 150697, 150698, 150699, 150700, 150701, 150702, 150703, 150706, 150708, 150709, 150710, 150711, 150712, 150714, 150716, 150717, 150718, 150719, 150720, 150721, 150722, 150723, 150724, 150725, 150726, 150727, 150728, 150729, 150731, 150732, 150733, 150735, 150736, 150737, 150739, 150740, 150741, 150742, 150743, 150744, 150746, 150747, 150748, 150749, 150750, 150751, 150752, 150753, 150754, 150755, 150756, 150757, 150759, 150760, 150761, 150762, 150763, 150764, 150766, 150768, 150769, 150770, 150771, 150772, 150774, 150775, 150776, 150777, 150778, 150779, 150780, 150781, 150782, 150785, 150786, 150787, 150788, 150790, 150791, 150792, 150793, 150795, 150796, 150797, 150799, 150800, 150801, 150802, 150803, 150805, 150806, 150807, 150808, 150809, 150810, 150811, 150812, 150813, 150814, 150815, 150816, 150818, 150819, 150820, 150821, 150822, 150823, 150824, 150825, 150826, 150827, 150828, 150829, 150830, 150832, 150834, 150837, 150838, 150840, 150841, 150842, 150843, 150845, 150846, 150847, 150848, 150852, 150854, 150855, 150856, 150857, 150858, 150859, 150860, 150861, 150862, 150863, 150864, 150865, 150867, 150869, 150870, 150871, 150873, 150874, 150875, 150876, 150877, 150878, 150879, 150881, 150882, 150883, 150884, 150885, 150886, 150887, 150889, 150891, 150893, 150894, 150895, 150896, 150897, 150898, 150899, 150900, 150901, 150902, 150903, 150904, 150908, 150910, 150911, 150914, 150916, 150917, 150918, 150919, 150920, 150921, 150922, 150923, 150925, 150927, 150929, 150931, 150932, 150933, 150934, 150935, 150936, 150937, 150938, 150939, 150941, 150942, 150943, 150944, 150945, 150946, 150948, 150949, 150950, 150953, 150954, 150955, 150956, 150957, 150958, 150959, 150960, 150961, 150962, 150963, 150964, 150965, 150966, 150967, 150968, 150970, 150971, 150972, 150973, 150974, 150976, 150978, 150980, 150981, 150982, 150983, 150984, 150985, 150987, 150988, 150989, 150990, 150991, 150992, 150994, 150995, 150996, 150997, 150998, 150999, 151002, 151003, 151004, 151005, 151007, 151008, 151009, 151010, 151011, 151012, 151013, 151014, 151015, 151016, 151017, 151019, 151022, 151024, 151026, 151027, 151028, 151029, 151030, 151031, 151033, 151035, 151036, 151037, 151038, 151039, 151040, 151041, 151042, 151043, 151044, 151047, 151048, 151049, 151050, 151051, 151052, 151054, 151055, 151056, 151057, 151058, 151059, 151060, 151061, 151062, 151063, 151064, 151065, 151066, 151069, 151071, 151072, 151073, 151075, 151076, 151077, 151080, 151082, 151083, 151084, 151085, 151086, 151087, 151088, 151089, 151090, 151092, 151093, 151094, 151095, 151097, 151098, 151100, 151104, 151105, 151106, 151108, 151109, 151110, 151111, 151113, 151114, 151115, 151116, 151119, 151120, 151121, 151122, 151123, 151124, 151125, 151127, 151128, 151131, 151133, 151135, 151137, 151138, 151139, 151140, 151141, 151142, 151143, 151145, 151146, 151150, 151151, 151154, 151155, 151156, 151157, 151158, 151162, 151163, 151164, 151166, 151167, 151169, 151170, 151171, 151172, 151173, 151174, 151175, 151177, 151178, 151180, 151183, 151184, 151186, 151187, 151188, 151189, 151191, 151192, 151193, 151195, 151197, 151198, 151201, 151202, 151203, 151204, 151205, 151206, 151208, 151209, 151211, 151212, 151214, 151215, 151216, 151217, 151218, 151219, 151220, 151221, 151223, 151224, 151225, 151226, 151228, 151230, 151231, 151234, 151235, 151236, 151238, 151239, 151240, 151241, 151242, 151244, 151245, 151246, 151247, 151248, 151249, 151252, 151253, 151254, 151255, 151256, 151257, 151258, 151259, 151260, 151261, 151262, 151263, 151264, 151265, 151267, 151269, 151270, 151271, 151272, 151273, 151275, 151276, 151277, 151278, 151279, 151280, 151282, 151283, 151284, 151286, 151287, 151288, 151289, 151290, 151291, 151292, 151295, 151297, 151298, 151299, 151301, 151302, 151303, 151304, 151306, 151308, 151309, 151310, 151313, 151315, 151317, 151318, 151319, 151320, 151322, 151323, 151324, 151325, 151326, 151327, 151329, 151330, 151331, 151332, 151333, 151334, 151335, 151336, 151337, 151338, 151339, 151340, 151341, 151344, 151346, 151347, 151348, 151350, 151351, 151352, 151353, 151354, 151357, 151360, 151362, 151363, 151364, 151366, 151367, 151368, 151369, 151370, 151371, 151372, 151373, 151374, 151375, 151377, 151378, 151380, 151381, 151382, 151385, 151386, 151387, 151388, 151389, 151390, 151393, 151394, 151395, 151399, 151400, 151401, 151402, 151403, 151404, 151405, 151406, 151407, 151408, 151409, 151412, 151413, 151414, 151415, 151416, 151418, 151420, 151421, 151422, 151424, 151425, 151426, 151427, 151429, 151431, 151432, 151433, 151434, 151435, 151436, 151437, 151440, 151441, 151443, 151445, 151447, 151450, 151451, 151452, 151454, 151455, 151456, 151457, 151458, 151459, 151461, 151464, 151466, 151467, 151469, 151470, 151471, 151472, 151474, 151475, 151479, 151481, 151483, 151484, 151485, 151486, 151488, 151489, 151490, 151491, 151492, 151493, 151494, 151495, 151498, 151499, 151500, 151501, 151503, 151504, 151505, 151506, 151507, 151510, 151511, 151514, 151515, 151516, 151517, 151518, 151520, 151522, 151524, 151525, 151527, 151528, 151529, 151530, 151531, 151532, 151533, 151534, 151535, 151536, 151537, 151538, 151539, 151540, 151542, 151544, 151545, 151546, 151547, 151548, 151549, 151550, 151551, 151552, 151553, 151554, 151555, 151556, 151560, 151561, 151562, 151563, 151564, 151565, 151566, 151569, 151570, 151572, 151573, 151574, 151577, 151581, 151582, 151583, 151586, 151588, 151589, 151590, 151591, 151592, 151595, 151596, 151597, 151598, 151599, 151600, 151601, 151603, 151604, 151605, 151606, 151607, 151608, 151609, 151610, 151611, 151613, 151614, 151616, 151621, 151624, 151625, 151626, 151627, 151628, 151629, 151630, 151631, 151632, 151633, 151635, 151636, 151637, 151640, 151641, 151642, 151643, 151644, 151646, 151647, 151649, 151651, 151652, 151653, 151654, 151655, 151656, 151659, 151660, 151661, 151662, 151663, 151664, 151665, 151669, 151671, 151673, 151674, 151675, 151676, 151677, 151678, 151679, 151682, 151683, 151685, 151686, 151687, 151689, 151690, 151691, 151692, 151693, 151697, 151698, 151701, 151702, 151703, 151704, 151705, 151707, 151708, 151709, 151711, 151712, 151713, 151715, 151716, 151717, 151718, 151719, 151720, 151721, 151722, 151724, 151726, 151727, 151729, 151731, 151733, 151736, 151737, 151738, 151739, 151740, 151741, 151742, 151743, 151744, 151745, 151747, 151748, 151749, 151750, 151752, 151755, 151756, 151758, 151759, 151760, 151761, 151762, 151763, 151764, 151765, 151766, 151767, 151768, 151769, 151770, 151771, 151774, 151775, 151776, 151780, 151781, 151784, 151785, 151786, 151787, 151788, 151789, 151790, 151791, 151792, 151793, 151794, 151795, 151798, 151799, 151800, 151802, 151804, 151805, 151806, 151807, 151809, 151810, 151811, 151817, 151818, 151820, 151821, 151823, 151824, 151825, 151826, 151827, 151829, 151830, 151831, 151832, 151833, 151834, 151835, 151836, 151837, 151838, 151841, 151842, 151844, 151846, 151848, 151849, 151850, 151851, 151852, 151853, 151855, 151856, 151857, 151858, 151860, 151861, 151862, 151863, 151864, 151865, 151866, 151867, 151868, 151869, 151870, 151872, 151874, 151876, 151878, 151879, 151880, 151881, 151883, 151884, 151886, 151887, 151888, 151889, 151892, 151893, 151894, 151897, 151901, 151906, 151909, 151910, 151911, 151913, 151916, 151917, 151918, 151919, 151920, 151922, 151924, 151927, 151930, 151932, 151933, 151934, 151935, 151937, 151939, 151940, 151942, 151943, 151944, 151945, 151946, 151947, 151950, 151952, 151954, 151955, 151957, 151959, 151961, 151962, 151965, 151966, 151967, 151968, 151970, 151971, 151972, 151974, 151977, 151982, 151983, 151984, 151985, 151986, 151987, 151990, 151992, 151993, 151994, 151998, 151999, 152000, 152001, 152003, 152004, 152007, 152011, 152012, 152013, 152015, 152017, 152018, 152019, 152020, 152021, 152024, 152025, 152026, 152027, 152028, 152029, 152030, 152031, 152032, 152034, 152035, 152036, 152038, 152039, 152041, 152042, 152043, 152044, 152045, 152046, 152047, 152048, 152049, 152050, 152051, 152052, 152053, 152054, 152057, 152058, 152059, 152060, 152061, 152062, 152067, 152068, 152069, 152070, 152071, 152072, 152073, 152074, 152077, 152078, 152079, 152080, 152082, 152083, 152084, 152085, 152086, 152087, 152088, 152089, 152090, 152091, 152092, 152093, 152094, 152095, 152096, 152098, 152103, 152105, 152106, 152107, 152109, 152110, 152111, 152112, 152115, 152116, 152118, 152119, 152120, 152121, 152122, 152124, 152125, 152127, 152131, 152132, 152133, 152134, 152135, 152136, 152137, 152138, 152139, 152140, 152142, 152143, 152144, 152145, 152146, 152147, 152148, 152150, 152151, 152152, 152153, 152157, 152158, 152159, 152160, 152161, 152162, 152163, 152164, 152165, 152166, 152167, 152170, 152171, 152172, 152174, 152175, 152177, 152179, 152180, 152182, 152183, 152186, 152187, 152188, 152191, 152193, 152196, 152197, 152198, 152199, 152202, 152203, 152206, 152210, 152211, 152213, 152214, 152215, 152216, 152217, 152220, 152221, 152223, 152225, 152226, 152227, 152228, 152229, 152230, 152232, 152233, 152235, 152236, 152237, 152238, 152243, 152244, 152246, 152248, 152249, 152250, 152252, 152254, 152255, 152258, 152259, 152261, 152263, 152264, 152265, 152266, 152268, 152269, 152271, 152272, 152273, 152274, 152275, 152276, 152277, 152281, 152282, 152283, 152284, 152285, 152286, 152287, 152288, 152289, 152290, 152291, 152292, 152293, 152294, 152297, 152300, 152301, 152302, 152303, 152304, 152307, 152308, 152310, 152311, 152312, 152313, 152314, 152316, 152317, 152318, 152321, 152322, 152324, 152328, 152330, 152331, 152333, 152334, 152335, 152336, 152337, 152338, 152339, 152340, 152341, 152343, 152344, 152345, 152346, 152347, 152349, 152352, 152353, 152354, 152355, 152356, 152357, 152362, 152364, 152367, 152369, 152371, 152373, 152374, 152376, 152377, 152378, 152379, 152380, 152381, 152383, 152385, 152386, 152387, 152388, 152391, 152392, 152393, 152394, 152396, 152397, 152398, 152401, 152404, 152405, 152406, 152407, 152408, 152409, 152411, 152412, 152413, 152414, 152416, 152417, 152418, 152419, 152425, 152426, 152428, 152429, 152430, 152432, 152433, 152436, 152439, 152442, 152443, 152444, 152445, 152446, 152447, 152449, 152450, 152452, 152453, 152455, 152456, 152457, 152459, 152460, 152461, 152463, 152464, 152465, 152467, 152468, 152469, 152471, 152473, 152475, 152477, 152480, 152481, 152482, 152484, 152486, 152487, 152488, 152489, 152491, 152492, 152496, 152497, 152498, 152501, 152504, 152505, 152506, 152507, 152508, 152509, 152510, 152511, 152514, 152516, 152518, 152519, 152520, 152521, 152524, 152527, 152528, 152529, 152530, 152531, 152532, 152535, 152539, 152540, 152541, 152543, 152548, 152550, 152552, 152553, 152554, 152555, 152556, 152558, 152564, 152565, 152567, 152568, 152570, 152573, 152575, 152576, 152582, 152583, 152587, 152588, 152589, 152590, 152591, 152592, 152593, 152599, 152600, 152601, 152602, 152607, 152609, 152610, 152611, 152613, 152615, 152617, 152618, 152621, 152625, 152626, 152627, 152628, 152629, 152630, 152633, 152634, 152635, 152636, 152640, 152641, 152642, 152643, 152644, 152645, 152646, 152651, 152652, 152655, 152656, 152659, 152661, 152662, 152663, 152664, 152665, 152666, 152667, 152668, 152669, 152670, 152671, 152672, 152673, 152676, 152677, 152678, 152679, 152682, 152683, 152686, 152687, 152689, 152690, 152691, 152692, 152693, 152694, 152696, 152697, 152698, 152699, 152701, 152702, 152703, 152704, 152705, 152706, 152708, 152710, 152711, 152712, 152713, 152715, 152719, 152720, 152721, 152722, 152725, 152727, 152728, 152729, 152730, 152732, 152734, 152736, 152738, 152739, 152741, 152742, 152743, 152744, 152745, 152746, 152748, 152750, 152751, 152752, 152753, 152754, 152755, 152757, 152758, 152762, 152763, 152765, 152767, 152770, 152771, 152773, 152774, 152777, 152778, 152782, 152783, 152787, 152788, 152789, 152790, 152791, 152792, 152793, 152794, 152795, 152800, 152802, 152803, 152804, 152808, 152809, 152811, 152812, 152813, 152815, 152816, 152818, 152821, 152822, 152823, 152825, 152826, 152827, 152831, 152832, 152833, 152834, 152835, 152836, 152837, 152838, 152841, 152842, 152844, 152845, 152849, 152850, 152851, 152853, 152854, 152855, 152856, 152858, 152860, 152862, 152863, 152864, 152866, 152867, 152868, 152869, 152870, 152871, 152872, 152874, 152875, 152877, 152881, 152882, 152887, 152888, 152889, 152893, 152894, 152897, 152898, 152900, 152904, 152905, 152906, 152907, 152908, 152909, 152912, 152913, 152914, 152916, 152918, 152919, 152921, 152922, 152925, 152926, 152930, 152931, 152932, 152935, 152939, 152940, 152941, 152942, 152943, 152945, 152946, 152947, 152948, 152949, 152951, 152953, 152955, 152956, 152959, 152961, 152962, 152963, 152964, 152965, 152966, 152967, 152968, 152971, 152972, 152975, 152976, 152978, 152979, 152980, 152983, 152985, 152989, 152990, 152991, 152992, 152993, 152995, 152996, 152997, 153001, 153002, 153003, 153005, 153006, 153008, 153011, 153012, 153013, 153014, 153015, 153018, 153020, 153021, 153023, 153025, 153030, 153032, 153033, 153035, 153036, 153039, 153041, 153042, 153043, 153046, 153048, 153049, 153051, 153052, 153054, 153055, 153056, 153057, 153060, 153061, 153062, 153063, 153064, 153065, 153066, 153068, 153069, 153072, 153073, 153074, 153075, 153077, 153078, 153081, 153082, 153083, 153085, 153088, 153092, 153093, 153094, 153096, 153097, 153098, 153099, 153101, 153102, 153103, 153105, 153106, 153107, 153108, 153110, 153111, 153113, 153121, 153122, 153123, 153125, 153126, 153128, 153130, 153132, 153133, 153134, 153135, 153140, 153143, 153145, 153150, 153151, 153152, 153154, 153155, 153159, 153160, 153163, 153169, 153170, 153172, 153173, 153174, 153175, 153176, 153177, 153178, 153180, 153182, 153183, 153186, 153187, 153189, 153190, 153191, 153192, 153194, 153195, 153199, 153200, 153201, 153206, 153210, 153212, 153215, 153216, 153218, 153220, 153221, 153222, 153223, 153224, 153225, 153230, 153232, 153233, 153235, 153236, 153238, 153241, 153242, 153243, 153244, 153245, 153247, 153249, 153250, 153251, 153253, 153257, 153258, 153262, 153263, 153266, 153267, 153268, 153269, 153270, 153271, 153276, 153277, 153278, 153279, 153281, 153282, 153284, 153287, 153288, 153289, 153290, 153291, 153297, 153300, 153302, 153303, 153304, 153305, 153306, 153308, 153309, 153310, 153312, 153313, 153314, 153316, 153317, 153318, 153319, 153320, 153322, 153328, 153329, 153334, 153336, 153337, 153339, 153341, 153343, 153345, 153346, 153348, 153349, 153352, 153356, 153357, 153359, 153361, 153362, 153364, 153367, 153371, 153373, 153374, 153375, 153376, 153378, 153379, 153380, 153381, 153383, 153384, 153387, 153388, 153391, 153393, 153394, 153397, 153398, 153399, 153400, 153403, 153405, 153406, 153408, 153409, 153411, 153412, 153413, 153414, 153417, 153420, 153422, 153423, 153424, 153425, 153426, 153427, 153428, 153429, 153431, 153432, 153434, 153435, 153436, 153437, 153440, 153442, 153443, 153444, 153445, 153446, 153449, 153450, 153451, 153453, 153454, 153457, 153458, 153462, 153464, 153470, 153475, 153477, 153479, 153480, 153481, 153483, 153486, 153487, 153488, 153490, 153493, 153494, 153495, 153496, 153498, 153499, 153500, 153501, 153502, 153506, 153507, 153513, 153514, 153515, 153516, 153518, 153521, 153522, 153525, 153527, 153528, 153529, 153533, 153534, 153535, 153536, 153537, 153544, 153545, 153546, 153547, 153549, 153551, 153553, 153555, 153556, 153557, 153558, 153559, 153560, 153562, 153563, 153565, 153566, 153567, 153571, 153572, 153575, 153579, 153580, 153581, 153582, 153584, 153585, 153587, 153590, 153592, 153594, 153595, 153596, 153597, 153599, 153602, 153603, 153605, 153606, 153607, 153608, 153609, 153611, 153612, 153614, 153615, 153618, 153622, 153623, 153624, 153626, 153627, 153628, 153631, 153633, 153634, 153635, 153636, 153637, 153641, 153642, 153643, 153644, 153646, 153647, 153648, 153650, 153651, 153652, 153654, 153655, 153656, 153658, 153660, 153662, 153663, 153665, 153666, 153667, 153670, 153672, 153673, 153677, 153678, 153681, 153685, 153686, 153688, 153689, 153690, 153691, 153694, 153695, 153697, 153700, 153701, 153704, 153705, 153706, 153707, 153708, 153709, 153710, 153713, 153716, 153717, 153718, 153721, 153725, 153726, 153727, 153728, 153729, 153730, 153731, 153733, 153735, 153736, 153739, 153741, 153742, 153744, 153745, 153746, 153747, 153748, 153750, 153751, 153753, 153755, 153758, 153765, 153766, 153767, 153771, 153772, 153777, 153780, 153783, 153784, 153786, 153788, 153791, 153792, 153793, 153794, 153796, 153797, 153799, 153800, 153801, 153802, 153803, 153804, 153806, 153810, 153812, 153813, 153815, 153816, 153819, 153820, 153821, 153822, 153823, 153825, 153827, 153830, 153831, 153833, 153834, 153835, 153836, 153839, 153840, 153841, 153842, 153843, 153845, 153846, 153847, 153850, 153852, 153853, 153855, 153856, 153857, 153858, 153859, 153860, 153861, 153862, 153863, 153864, 153868, 153869, 153873, 153874, 153877, 153878, 153879, 153880, 153881, 153884, 153886, 153887, 153889, 153890, 153891, 153892, 153893, 153898, 153899, 153900, 153902, 153905, 153906, 153908, 153912, 153913, 153914, 153916, 153917, 153918, 153919, 153920, 153922, 153923, 153925, 153928, 153931, 153932, 153933, 153934, 153935, 153937, 153938, 153939, 153942, 153944, 153946, 153947, 153950, 153951, 153953, 153955, 153956, 153958, 153959, 153960, 153961, 153962, 153966, 153968, 153969, 153971, 153972, 153975, 153977, 153980, 153981, 153983, 153985, 153987, 153989, 153991, 153995, 153996, 153998, 154001, 154002, 154004, 154006, 154007, 154010, 154011, 154013, 154014, 154015, 154018, 154019, 154020, 154022, 154023, 154025, 154027, 154028, 154031, 154034, 154036, 154038, 154040, 154043, 154044, 154045, 154047, 154048, 154049, 154050, 154054, 154056, 154057, 154059, 154060, 154064, 154066, 154067, 154070, 154071, 154072, 154073, 154074, 154075, 154076, 154077, 154078, 154080, 154081, 154082, 154083, 154085, 154090, 154091, 154092, 154093, 154097, 154098, 154102, 154104, 154105, 154106, 154107, 154110, 154111, 154112, 154113, 154114, 154115, 154116, 154117, 154118, 154121, 154122, 154124, 154125, 154126, 154127, 154128, 154129, 154131, 154132, 154133, 154134, 154135, 154136, 154141, 154142, 154147, 154149, 154152, 154153, 154154, 154156, 154157, 154158, 154160, 154162, 154163, 154164, 154165, 154168, 154171, 154174, 154175, 154182, 154183, 154185, 154188, 154189, 154193, 154195, 154196, 154199, 154201, 154203, 154204, 154206, 154207, 154209, 154211, 154212, 154213, 154214, 154217, 154218, 154219, 154220, 154223, 154227, 154228, 154231, 154234, 154235, 154238, 154239, 154240, 154241, 154242, 154243, 154244, 154245, 154246, 154247, 154248, 154250, 154251, 154256, 154259, 154264, 154265, 154267, 154269, 154270, 154271, 154272, 154273, 154275, 154276, 154277, 154281, 154282, 154283, 154284, 154289, 154291, 154292, 154295, 154297, 154300, 154302, 154303, 154305, 154306, 154309, 154310, 154311, 154312, 154314, 154315, 154316, 154318, 154319, 154320, 154322, 154323, 154324, 154325, 154326, 154329, 154332, 154336, 154339, 154341, 154342, 154343, 154344, 154345, 154346, 154347, 154348, 154351, 154352, 154356, 154358, 154359, 154360, 154361, 154366, 154370, 154379, 154382, 154383, 154384, 154385, 154388, 154389, 154390, 154391, 154393, 154395, 154396, 154400, 154403, 154404, 154405, 154407, 154408, 154409, 154412, 154413, 154414, 154415, 154420, 154421, 154423, 154425, 154426, 154427, 154429, 154430, 154431, 154432, 154433, 154435, 154436, 154437, 154438, 154441, 154442, 154445, 154449, 154450, 154451, 154452, 154455, 154458, 154460, 154465, 154466, 154467, 154469, 154470, 154473, 154476, 154477, 154478, 154479, 154480, 154481, 154482, 154483, 154486, 154487, 154488, 154489, 154490, 154491, 154493, 154495, 154496, 154497, 154498, 154499, 154503, 154505, 154506, 154507, 154508, 154511, 154512, 154513, 154515, 154516, 154517, 154520, 154522, 154523, 154526, 154527, 154530, 154532, 154536, 154538, 154541, 154542, 154546, 154549, 154551, 154552, 154553, 154554, 154556, 154561, 154565, 154568, 154570, 154572, 154573, 154574, 154575, 154577, 154580, 154585, 154586, 154591, 154592, 154593, 154594, 154595, 154600, 154603, 154605, 154608, 154609, 154610, 154611, 154613, 154614, 154619, 154620, 154621, 154622, 154623, 154624, 154625, 154626, 154627, 154630, 154631, 154633, 154634, 154637, 154638, 154639, 154642, 154643, 154647, 154649, 154650, 154651, 154653, 154654, 154656, 154657, 154660, 154661, 154662, 154664, 154668, 154671, 154675, 154677, 154679, 154681, 154684, 154686, 154687, 154688, 154689, 154691, 154693, 154694, 154695, 154697, 154699, 154700, 154701, 154702, 154704, 154706, 154707, 154709, 154710, 154711, 154714, 154715, 154721, 154723, 154724, 154728, 154729, 154732, 154735, 154736, 154737, 154742, 154745, 154747, 154748, 154749, 154750, 154751, 154753, 154754, 154755, 154757, 154760, 154761, 154762, 154763, 154765, 154766, 154767, 154768, 154769, 154770, 154771, 154773, 154776, 154778, 154787, 154788, 154790, 154793, 154801, 154803, 154805, 154806, 154807, 154810, 154811, 154812, 154815, 154816, 154817, 154818, 154824, 154826, 154828, 154829, 154830, 154831, 154833, 154834, 154835, 154837, 154838, 154839, 154842, 154843, 154844, 154845, 154850, 154853, 154854, 154855, 154856, 154857, 154859, 154861, 154864, 154870, 154871, 154872, 154877, 154878, 154879, 154881, 154885, 154886, 154887, 154889, 154890, 154898, 154899, 154901, 154902, 154904, 154906, 154907, 154910, 154911, 154912, 154914, 154916, 154917, 154918, 154919, 154920, 154921, 154926, 154927, 154930, 154935, 154941, 154942, 154943, 154948, 154950, 154955, 154956, 154957, 154958, 154959, 154962, 154965, 154968, 154969, 154970, 154972, 154973, 154976, 154978, 154981, 154983, 154984, 154985, 154986, 154987, 154989, 154994, 154995, 154999, 155003, 155005, 155006, 155007, 155008, 155009, 155013, 155014, 155015, 155019, 155021, 155022, 155023, 155026, 155028, 155032, 155033, 155035, 155037, 155040, 155041, 155045, 155047, 155049, 155051, 155052, 155055, 155057, 155058, 155060, 155063, 155066, 155067, 155068, 155069, 155071, 155072, 155073, 155075, 155076, 155077, 155078, 155082, 155083, 155086, 155087, 155091, 155093, 155095, 155096, 155100, 155104, 155108, 155110, 155111, 155112, 155113, 155114, 155117, 155119, 155122, 155125, 155126, 155130, 155131, 155134, 155138, 155139, 155140, 155141, 155144, 155147, 155148, 155149, 155151, 155152, 155154, 155156, 155158, 155159, 155160, 155161, 155162, 155163, 155164, 155165, 155167, 155169, 155173, 155175, 155177, 155180, 155181, 155182, 155184, 155185, 155188, 155189, 155190, 155191, 155192, 155193, 155194, 155195, 155196, 155197, 155198, 155199, 155200, 155202, 155204, 155205, 155207, 155210, 155211, 155213, 155214, 155215, 155217, 155218, 155219, 155222, 155224, 155225, 155226, 155230, 155231, 155237, 155241, 155242, 155244, 155248, 155249, 155252, 155253, 155256, 155258, 155262, 155264, 155266, 155267, 155269, 155271, 155274, 155282, 155284, 155289, 155291, 155294, 155296, 155302, 155303, 155304, 155307, 155309, 155310, 155312, 155316, 155317, 155318, 155320, 155323, 155324, 155326, 155327, 155328, 155329, 155333, 155335, 155336, 155337, 155338, 155339, 155341, 155347, 155348, 155350, 155351, 155354, 155355, 155357, 155358, 155360, 155361, 155367, 155369, 155372, 155374, 155379, 155380, 155381, 155382, 155383, 155385, 155389, 155392, 155393, 155397, 155398, 155401, 155404, 155405, 155406, 155407, 155410, 155411, 155414, 155415, 155417, 155420, 155424, 155426, 155428, 155430, 155431, 155434, 155435, 155436, 155438, 155440, 155442, 155443, 155445, 155448, 155449, 155450, 155451, 155452, 155453, 155455, 155456, 155458, 155459, 155462, 155463, 155468, 155470, 155471, 155472, 155474, 155477, 155478, 155482, 155483, 155484, 155485, 155489, 155490, 155492, 155494, 155497, 155498, 155499, 155501, 155503, 155507, 155509, 155510, 155511, 155512, 155513, 155515, 155516, 155531, 155533, 155534, 155535, 155538, 155539, 155543, 155545, 155547, 155548, 155549, 155550, 155552, 155555, 155557, 155558, 155559, 155563, 155564, 155566, 155569, 155571, 155572, 155573, 155575, 155576, 155582, 155584, 155586, 155587, 155588, 155589, 155591, 155593, 155594, 155595, 155599, 155601, 155602, 155604, 155608, 155610, 155612, 155613, 155615, 155617, 155621, 155623, 155625, 155626, 155627, 155633, 155639, 155640, 155641, 155647, 155648, 155650, 155653, 155654, 155655, 155656, 155658, 155659, 155661, 155665, 155668, 155669, 155670, 155671, 155672, 155673, 155674, 155675, 155682, 155685, 155687, 155688, 155692, 155694, 155699, 155700, 155705, 155707, 155711, 155715, 155716, 155720, 155731, 155734, 155735, 155736, 155737, 155741, 155743, 155744, 155745, 155747, 155749, 155750, 155754, 155761, 155762, 155767, 155768, 155770, 155771, 155773, 155774, 155775, 155780, 155781, 155782, 155783, 155784, 155786, 155787, 155788, 155790, 155791, 155798, 155799, 155801, 155803, 155804, 155805, 155806, 155808, 155813, 155814, 155818, 155820, 155824, 155825, 155826, 155827, 155833, 155835, 155838, 155843, 155845, 155846, 155847, 155848, 155849, 155850, 155851, 155854, 155856, 155859, 155861, 155862, 155863, 155864, 155867, 155871, 155872, 155873, 155875, 155878, 155879, 155884, 155885, 155886, 155890, 155893, 155894, 155895, 155896, 155899, 155900, 155904, 155907, 155910, 155911, 155915, 155916, 155919, 155920, 155922, 155925, 155926, 155928, 155930, 155931, 155934, 155937, 155939, 155943, 155949, 155950, 155952, 155953, 155954, 155955, 155958, 155960, 155961, 155964, 155965, 155967, 155971, 155972, 155974, 155975, 155976, 155978, 155982, 155984, 155985, 155988, 155995, 156000, 156003, 156005, 156006, 156007, 156009, 156011, 156013, 156014, 156016, 156017, 156021, 156023, 156027, 156030, 156031, 156033, 156035, 156041, 156046, 156047, 156050, 156051, 156052, 156053, 156055, 156057, 156063, 156064, 156076, 156077, 156078, 156079, 156080, 156082, 156085, 156089, 156090, 156094, 156095, 156096, 156098, 156104, 156105, 156109, 156110, 156112, 156113, 156116, 156117, 156118, 156119, 156121, 156124, 156125, 156126, 156127, 156128, 156132, 156133, 156136, 156138, 156147, 156150, 156151, 156154, 156155, 156156, 156157, 156159, 156163, 156168, 156169, 156170, 156172, 156173, 156174, 156175, 156178, 156180, 156182, 156183, 156186, 156187, 156195, 156197, 156199, 156201, 156203, 156204, 156207, 156210, 156211, 156212, 156213, 156216, 156219, 156220, 156221, 156223, 156224, 156227, 156228, 156232, 156234, 156235, 156236, 156238, 156239, 156241, 156244, 156246, 156249, 156255, 156257, 156258, 156259, 156262, 156263, 156264, 156265, 156266, 156267, 156268, 156269, 156275, 156277, 156278, 156280, 156285, 156286, 156287, 156289, 156291, 156292, 156294, 156295, 156296, 156299, 156300, 156301, 156303, 156307, 156308, 156310, 156312, 156315, 156316, 156319, 156322, 156323, 156325, 156327, 156331, 156333, 156340, 156342, 156344, 156349, 156350, 156355, 156358, 156359, 156360, 156362, 156363, 156364, 156365, 156366, 156367, 156368, 156369, 156372, 156374, 156375, 156377, 156378, 156379, 156385, 156390, 156392, 156395, 156399, 156402, 156405, 156408, 156409, 156410, 156411, 156414, 156418, 156421, 156423, 156424, 156426, 156429, 156430, 156431, 156437, 156438, 156439, 156440, 156441, 156444, 156446, 156447, 156448, 156449, 156453, 156454, 156458, 156464, 156465, 156466, 156469, 156470, 156471, 156476, 156481, 156483, 156488, 156490, 156491, 156493, 156495, 156496, 156500, 156502, 156503, 156507, 156510, 156516, 156517, 156518, 156519, 156521, 156524, 156526, 156530, 156531, 156534, 156535, 156536, 156537, 156538, 156541, 156544, 156545, 156551, 156552, 156554, 156556, 156557, 156559, 156563, 156566, 156567, 156570, 156571, 156572, 156576, 156577, 156580, 156581, 156582, 156584, 156586, 156587, 156590, 156591, 156592, 156593, 156600, 156607, 156612, 156614, 156619, 156620, 156622, 156624, 156627, 156632, 156635, 156637, 156639, 156642, 156644, 156647, 156648, 156650, 156651, 156653, 156654, 156655, 156658, 156659, 156663, 156666, 156667, 156669, 156670, 156672, 156673, 156674, 156677, 156679, 156681, 156682, 156685, 156686, 156687, 156690, 156691, 156693, 156694, 156696, 156701, 156702, 156704, 156706, 156707, 156708, 156718, 156720, 156723, 156724, 156727, 156730, 156732, 156733, 156736, 156740, 156743, 156744, 156747, 156751, 156752, 156757, 156760, 156761, 156762, 156764, 156775, 156777, 156778, 156780, 156781, 156787, 156791, 156793, 156795, 156796, 156797, 156798, 156803, 156804, 156806, 156808, 156812, 156814, 156815, 156822, 156828, 156830, 156832, 156834, 156835, 156836, 156839, 156841, 156845, 156847, 156848, 156850, 156852, 156853, 156860, 156862, 156864, 156865, 156870, 156871, 156872, 156877, 156880, 156881, 156883, 156885, 156887, 156888, 156889, 156890, 156892, 156897, 156898, 156900, 156903, 156911, 156919, 156920, 156922, 156924, 156926, 156929, 156934, 156936, 156938, 156940, 156947, 156948, 156950, 156951, 156953, 156954, 156957, 156958, 156959, 156964, 156966, 156968, 156970, 156971, 156972, 156983, 156984, 156992, 156994, 156996, 156997, 156998, 157000, 157002, 157004, 157009, 157010, 157011, 157012, 157013, 157014, 157016, 157020, 157021, 157025, 157030, 157032, 157034, 157035, 157039, 157040, 157041, 157044, 157047, 157050, 157051, 157053, 157054, 157060, 157061, 157063, 157064, 157067, 157071, 157074, 157075, 157076, 157077, 157078, 157081, 157084, 157089, 157092, 157093, 157094, 157095, 157096, 157099, 157104, 157105, 157106, 157108, 157109, 157112, 157113, 157114, 157115, 157119, 157121, 157124, 157125, 157126, 157132, 157133, 157135, 157141, 157143, 157150, 157151, 157153, 157154, 157155, 157160, 157161, 157162, 157164, 157165, 157166, 157170, 157174, 157175, 157176, 157177, 157180, 157181, 157186, 157190, 157192, 157196, 157200, 157201, 157207, 157208, 157210, 157213, 157215, 157221, 157222, 157223, 157226, 157229, 157233, 157234, 157235, 157242, 157245, 157247, 157249, 157254, 157256, 157257, 157258, 157259, 157261, 157265, 157267, 157276, 157282, 157288, 157290, 157294, 157295, 157296, 157299, 157301, 157307, 157308, 157311, 157314, 157320, 157324, 157325, 157328, 157329, 157330, 157333, 157335, 157338, 157344, 157347, 157348, 157350, 157351, 157353, 157354, 157356, 157358, 157360, 157364, 157368, 157370, 157374, 157375, 157377, 157382, 157385, 157388, 157389, 157392, 157393, 157394, 157396, 157401, 157413, 157414, 157416, 157421, 157423, 157424, 157429, 157433, 157434, 157436, 157437, 157439, 157442, 157443, 157444, 157450, 157452, 157454, 157455, 157456, 157460, 157464, 157470, 157472, 157473, 157474, 157475, 157476, 157477, 157480, 157486, 157489, 157494, 157498, 157500, 157503, 157507, 157514, 157516, 157517, 157518, 157520, 157521, 157525, 157526, 157527, 157528, 157530, 157533, 157535, 157536, 157538, 157543, 157545, 157547, 157550, 157551, 157552, 157553, 157557, 157558, 157560, 157561, 157562, 157567, 157570, 157571, 157572, 157573, 157574, 157579, 157581, 157583, 157584, 157589, 157591, 157592, 157597, 157600, 157604, 157609, 157611, 157613, 157614, 157616, 157619, 157620, 157621, 157626, 157628, 157631, 157633, 157634, 157635, 157638, 157641, 157642, 157643, 157644, 157645, 157646, 157647, 157652, 157654, 157658, 157659, 157661, 157663, 157666, 157675, 157679, 157680, 157682, 157687, 157690, 157694, 157699, 157702, 157707, 157709, 157711, 157712, 157713, 157714, 157715, 157716, 157717, 157718, 157720, 157724, 157730, 157731, 157734, 157735, 157737, 157740, 157742, 157744, 157746, 157750, 157754, 157763, 157764, 157768, 157773, 157779, 157782, 157783, 157786, 157790, 157791, 157794, 157796, 157797, 157801, 157803, 157809, 157810, 157811, 157817, 157819, 157820, 157822, 157823, 157825, 157831, 157833, 157836, 157839, 157840, 157846, 157848, 157850, 157851, 157856, 157857, 157859, 157861, 157864, 157865, 157866, 157869, 157872, 157878, 157882, 157883, 157884, 157885, 157887, 157892, 157900, 157904, 157906, 157911, 157914, 157916, 157917, 157924, 157931, 157934, 157938, 157939, 157940, 157943, 157947, 157953, 157957, 157963, 157970, 157971, 157972, 157973, 157975, 157976, 157977, 157979, 157981, 157984, 157987, 157988, 157991, 157992, 157994, 157995, 158000, 158002, 158003, 158004, 158006, 158010, 158011, 158013, 158015, 158016, 158018, 158019, 158020, 158022, 158023, 158025, 158026, 158027, 158029, 158030, 158031, 158033, 158039, 158040, 158041, 158042, 158050, 158051, 158052, 158053, 158054, 158058, 158059, 158065, 158066, 158068, 158070, 158074, 158078, 158079, 158081, 158082, 158084, 158086, 158089, 158093, 158095, 158099, 158101, 158102, 158103, 158104, 158105, 158108, 158109, 158114, 158116, 158117, 158123, 158127, 158131, 158132, 158133, 158134, 158141, 158142, 158147, 158148, 158152, 158158, 158163, 158164, 158165, 158167, 158171, 158172, 158173, 158176, 158181, 158183, 158185, 158188, 158191, 158192, 158193, 158195, 158197, 158200, 158205, 158212, 158215, 158217, 158221, 158222, 158226, 158227, 158228, 158230, 158235, 158241, 158242, 158243, 158246, 158247, 158248, 158252, 158255, 158257, 158260, 158261, 158268, 158275, 158279, 158282, 158283, 158285, 158286, 158288, 158296, 158307, 158308, 158310, 158311, 158312, 158314, 158320, 158321, 158324, 158327, 158329, 158330, 158331, 158336, 158340, 158341, 158342, 158345, 158346, 158347, 158348, 158354, 158360, 158361, 158362, 158366, 158367, 158370, 158371, 158375, 158380, 158381, 158391, 158393, 158394, 158401, 158403, 158406, 158407, 158408, 158409, 158412, 158414, 158419, 158423, 158431, 158439, 158442, 158451, 158455, 158457, 158462, 158463, 158466, 158467, 158469, 158471, 158472, 158473, 158475, 158478, 158482, 158486, 158487, 158488, 158490, 158491, 158493, 158497, 158502, 158503, 158511, 158515, 158519, 158522, 158529, 158530, 158531, 158535, 158536, 158537, 158540, 158541, 158547, 158548, 158549, 158554, 158555, 158557, 158560, 158564, 158565, 158566, 158567, 158568, 158571, 158572, 158573, 158575, 158577, 158588, 158589, 158596, 158601, 158605, 158606, 158608, 158611, 158612, 158615, 158617, 158618, 158624, 158626, 158628, 158631, 158632, 158636, 158642, 158645, 158646, 158649, 158651, 158657, 158661, 158664, 158669, 158670, 158671, 158676, 158677, 158679, 158680, 158681, 158684, 158688, 158691, 158692, 158694, 158701, 158702, 158706, 158707, 158719, 158722, 158723, 158725, 158728, 158729, 158730, 158733, 158735, 158738, 158739, 158743, 158748, 158750, 158755, 158757, 158758, 158761, 158765, 158767, 158774, 158779, 158783, 158785, 158786, 158788, 158792, 158796, 158804, 158805, 158807, 158810, 158814, 158818, 158823, 158827, 158830, 158832, 158835, 158836, 158837, 158839, 158840, 158841, 158842, 158852, 158854, 158856, 158860, 158861, 158865, 158872, 158876, 158879, 158880, 158884, 158887, 158891, 158893, 158901, 158902, 158904, 158906, 158912, 158913, 158916, 158919, 158920, 158921, 158925, 158928, 158929, 158941, 158943, 158945, 158953, 158954, 158956, 158960, 158961, 158963, 158965, 158967, 158970, 158974, 158975, 158976, 158977, 158982, 158987, 158988, 158991, 158996, 158997, 158999, 159010, 159012, 159014, 159015, 159017, 159018, 159022, 159023, 159026, 159029, 159036, 159039, 159046, 159049, 159052, 159055, 159056, 159057, 159059, 159066, 159071, 159072, 159073, 159077, 159084, 159094, 159097, 159099, 159100, 159103, 159104, 159105, 159106, 159107, 159109, 159111, 159112, 159113, 159116, 159117, 159122, 159124, 159128, 159133, 159134, 159135, 159136, 159137, 159139, 159140, 159141, 159144, 159147, 159152, 159153, 159157, 159158, 159161, 159162, 159164, 159165, 159167, 159168, 159170, 159171, 159172, 159178, 159182, 159185, 159197, 159198, 159201, 159203, 159204, 159206, 159208, 159209, 159210, 159218, 159220, 159223, 159225, 159230, 159232, 159233, 159234, 159241, 159246, 159249, 159250, 159252, 159254, 159257, 159259, 159260, 159261, 159262, 159265, 159266, 159269, 159270, 159272, 159273, 159280, 159283, 159286, 159295, 159297, 159299, 159302, 159303, 159306, 159309, 159312, 159315, 159319, 159322, 159326, 159328, 159330, 159336, 159342, 159344, 159347, 159349, 159357, 159358, 159360, 159364, 159367, 159369, 159370, 159371, 159373, 159375, 159378, 159381, 159382, 159383, 159394, 159400, 159406, 159409, 159413, 159416, 159422, 159428, 159429, 159431, 159434, 159439, 159446, 159450, 159451, 159452, 159453, 159455, 159456, 159459, 159461, 159462, 159463, 159464, 159469, 159471, 159472, 159473, 159475, 159476, 159479, 159489, 159490, 159492, 159493, 159501, 159502, 159512, 159513, 159515, 159519, 159520, 159521, 159524, 159527, 159529, 159530, 159542, 159550, 159552, 159557, 159560, 159563, 159564, 159572, 159573, 159574, 159576, 159578, 159580, 159588, 159595, 159597, 159600, 159606, 159607, 159611, 159613, 159614, 159615, 159616, 159618, 159622, 159629, 159630, 159633, 159639, 159643, 159647, 159648, 159650, 159655, 159659, 159660, 159665, 159675, 159679, 159683, 159687, 159689, 159690, 159694, 159699, 159701, 159702, 159703, 159706, 159710, 159711, 159712, 159714, 159718, 159719, 159720, 159721, 159727, 159729, 159731, 159734, 159737, 159739, 159741, 159743, 159745, 159746, 159747, 159748, 159749, 159753, 159754, 159755, 159756, 159757, 159760, 159766, 159772, 159775, 159776, 159778, 159783, 159792, 159793, 159800, 159801, 159802, 159809, 159811, 159818, 159819, 159821, 159822, 159825, 159829, 159835, 159837, 159838, 159839, 159843, 159845, 159846, 159851, 159855, 159857, 159858, 159868, 159872, 159877, 159889, 159893, 159894, 159895, 159896, 159901, 159902, 159908, 159911, 159913, 159914, 159917, 159922, 159923, 159925, 159926, 159927, 159930, 159932, 159933, 159938, 159942, 159944, 159945, 159946, 159950, 159952, 159953, 159954, 159955, 159966, 159967, 159970, 159972, 159975, 159977, 159978, 159979, 159980, 159983, 159988, 159991, 159994, 159995, 159996, 159997, 160003, 160006, 160008, 160010, 160013, 160014, 160015, 160016, 160022, 160033, 160034, 160036, 160039, 160044, 160045, 160048, 160050, 160056, 160060, 160061, 160064, 160073, 160085, 160090, 160092, 160094, 160097, 160103, 160108, 160109, 160113, 160115, 160116, 160117, 160124, 160127, 160129, 160133, 160137, 160139, 160141, 160143, 160154, 160157, 160160, 160161, 160162, 160166, 160167, 160172, 160174, 160180, 160181, 160188, 160200, 160201, 160202, 160204, 160206, 160207, 160215, 160218, 160219, 160220, 160221, 160222, 160227, 160230, 160235, 160240, 160242, 160243, 160246, 160265, 160269, 160274, 160278, 160285, 160291, 160297, 160302, 160305, 160306, 160316, 160317, 160323, 160324, 160327, 160328, 160329, 160333, 160339, 160340, 160342, 160343, 160345, 160351, 160353, 160355, 160358, 160360, 160371, 160376, 160380, 160384, 160385, 160386, 160393, 160398, 160405, 160410, 160412, 160413, 160415, 160418, 160420, 160427, 160429, 160432, 160433, 160439, 160442, 160444, 160453, 160455, 160465, 160469, 160475, 160477, 160487, 160489, 160492, 160493, 160502, 160505, 160507, 160523, 160526, 160531, 160537, 160541, 160542, 160544, 160545, 160550, 160554, 160556, 160562, 160563, 160565, 160568, 160574, 160578, 160580, 160581, 160589, 160592, 160598, 160602, 160604, 160607, 160608, 160609, 160611, 160613, 160616, 160621, 160628, 160630, 160637, 160638, 160647, 160650, 160653, 160666, 160671, 160678, 160687, 160695, 160701, 160706, 160710, 160711, 160712, 160714, 160717, 160730, 160732, 160737, 160743, 160744, 160753, 160756, 160757, 160761, 160763, 160765, 160769, 160771, 160773, 160780, 160781, 160789, 160798, 160801, 160804, 160807, 160812, 160814, 160816, 160818, 160819, 160821, 160824, 160825, 160826, 160829, 160831, 160832, 160836, 160837, 160841, 160844, 160849, 160850, 160852, 160861, 160864, 160868, 160870, 160872, 160873, 160874, 160879, 160883, 160886, 160888, 160889, 160892, 160893, 160899, 160900, 160902, 160904, 160912, 160925, 160926, 160927, 160930, 160934, 160936, 160937, 160938, 160944, 160947, 160948, 160953, 160960, 160964, 160979, 160982, 160987, 160988, 160995, 160997, 160998, 161002, 161003, 161004, 161005, 161010, 161018, 161025, 161026, 161030, 161035, 161036, 161040, 161041, 161043, 161045, 161047, 161053, 161054, 161055, 161057, 161062, 161065, 161066, 161069, 161071, 161072, 161073, 161080, 161084, 161086, 161093, 161094, 161095, 161112, 161114, 161117, 161118, 161123, 161131, 161138, 161140, 161144, 161146, 161147, 161149, 161158, 161159, 161164, 161165, 161167, 161173, 161175, 161179, 161183, 161186, 161189, 161191, 161201, 161203, 161205, 161206, 161210, 161212, 161218, 161227, 161228, 161230, 161232, 161236, 161238, 161242, 161243, 161246, 161249, 161251, 161252, 161253, 161255, 161257, 161259, 161264, 161265, 161267, 161269, 161272, 161274, 161283, 161284, 161287, 161288, 161291, 161295, 161302, 161309, 161310, 161314, 161315, 161316, 161320, 161327, 161329, 161332, 161338, 161343, 161345, 161349, 161351, 161354, 161357, 161359, 161361, 161365, 161366, 161367, 161369, 161370, 161371, 161372, 161376, 161377, 161380, 161384, 161385, 161389, 161391, 161394, 161395, 161398, 161402, 161407, 161408, 161413, 161414, 161416, 161417, 161419, 161422, 161426, 161427, 161429, 161437, 161443, 161445, 161451, 161457, 161458, 161459, 161460, 161472, 161476, 161487, 161491, 161493, 161497, 161501, 161503, 161505, 161509, 161510, 161512, 161513, 161518, 161520, 161527, 161542, 161543, 161545, 161546, 161548, 161554, 161561, 161563, 161564, 161570, 161573, 161574, 161575, 161579, 161584, 161586, 161598, 161602, 161605, 161609, 161616, 161618, 161625, 161632, 161636, 161640, 161641, 161643, 161644, 161646, 161648, 161655, 161663, 161664, 161665, 161669, 161670, 161671, 161677, 161679, 161682, 161684, 161685, 161692, 161697, 161699, 161703, 161708, 161712, 161716, 161718, 161720, 161721, 161724, 161725, 161726, 161729, 161730, 161738, 161748, 161749, 161750, 161752, 161763, 161764, 161767, 161768, 161779, 161783, 161787, 161789, 161791, 161792, 161794, 161796, 161797, 161798, 161803, 161806, 161807, 161813, 161814, 161819, 161822, 161825, 161827, 161829, 161830, 161833, 161835, 161838, 161845, 161848, 161854, 161856, 161860, 161864, 161868, 161871, 161879, 161882, 161885, 161890, 161898, 161900, 161907, 161913, 161916, 161919, 161922, 161923, 161939, 161940, 161943, 161945, 161946, 161948, 161951, 161952, 161956, 161959, 161969, 161973, 161978, 161980, 161985, 161991, 162009, 162017, 162021, 162023, 162033, 162048, 162051, 162058, 162062, 162065, 162066, 162078, 162084, 162086, 162092, 162094, 162095, 162100, 162108, 162110, 162111, 162127, 162129, 162130, 162132, 162134, 162135, 162137, 162140, 162141, 162144, 162145, 162149, 162151, 162153, 162154, 162158, 162159, 162163, 162164, 162170, 162172, 162174, 162178, 162179, 162185, 162186, 162192, 162193, 162194, 162195, 162200, 162205, 162209, 162211, 162215, 162225, 162226, 162227, 162231, 162241, 162247, 162249, 162252, 162262, 162263, 162270, 162271, 162274, 162278, 162280, 162283, 162285, 162302, 162312, 162313, 162318, 162319, 162321, 162322, 162325, 162329, 162330, 162331, 162334, 162338, 162339, 162344, 162345, 162352, 162355, 162364, 162365, 162366, 162371, 162377, 162379, 162380, 162385, 162395, 162399, 162404, 162405, 162411, 162413, 162418, 162421, 162428, 162429, 162433, 162434, 162437, 162447, 162458, 162467, 162469, 162475, 162480, 162484, 162496, 162497, 162502, 162508, 162516, 162521, 162524, 162526, 162545, 162553, 162559, 162561, 162566, 162574, 162576, 162587, 162591, 162593, 162603, 162610, 162612, 162613, 162621, 162624, 162625, 162631, 162633, 162635, 162639, 162643, 162651, 162654, 162656, 162658, 162672, 162681, 162684, 162687, 162689, 162690, 162693, 162694, 162706, 162712, 162713, 162718, 162719, 162723, 162729, 162731, 162734, 162736, 162738, 162746, 162749, 162753, 162755, 162757, 162760, 162764, 162766, 162767, 162772, 162774, 162776, 162779, 162781, 162782, 162786, 162790, 162795, 162796, 162797, 162798, 162801, 162809, 162815, 162817, 162820, 162821, 162828, 162830, 162834, 162835, 162837, 162843, 162845, 162847, 162849, 162851, 162854, 162855, 162856, 162861, 162863, 162869, 162870, 162871, 162872, 162880, 162882, 162887, 162895, 162896, 162899, 162900, 162904, 162905, 162911, 162912, 162913, 162917, 162926, 162937, 162944, 162947, 162951, 162956, 162961, 162962, 162970, 162980, 162981, 162988, 162996, 163005, 163007, 163008, 163009, 163017, 163019, 163025, 163033, 163039, 163041, 163048, 163050, 163057, 163062, 163066, 163067, 163068, 163081, 163084, 163088, 163092, 163094, 163113, 163114, 163121, 163126, 163128, 163131, 163139, 163142, 163143, 163144, 163146, 163148, 163155, 163157, 163164, 163165, 163178, 163180, 163181, 163182, 163184, 163189, 163190, 163192, 163195, 163198, 163199, 163205, 163214, 163221, 163222, 163224, 163225, 163227, 163232, 163234, 163237, 163240, 163241, 163249, 163253, 163254, 163262, 163263, 163273, 163275, 163276, 163293, 163294, 163297, 163298, 163299, 163301, 163305, 163316, 163322, 163323, 163325, 163329, 163335, 163338, 163340, 163342, 163357, 163358, 163360, 163361, 163363, 163365, 163369, 163371, 163377, 163378, 163379, 163380, 163386, 163393, 163394, 163399, 163407, 163408, 163409, 163419, 163427, 163437, 163443, 163445, 163446, 163447, 163448, 163455, 163457, 163460, 163466, 163467, 163469, 163471, 163475, 163479, 163485, 163489, 163493, 163495, 163496, 163502, 163503, 163506, 163507, 163515, 163520, 163525, 163529, 163531, 163533, 163535, 163536, 163537, 163538, 163542, 163543, 163545, 163551, 163556, 163559, 163567, 163568, 163570, 163575, 163577, 163579, 163584, 163585, 163591, 163594, 163601, 163604, 163606, 163610, 163616, 163619, 163620, 163628, 163632, 163634, 163643, 163645, 163648, 163652, 163653, 163657, 163659, 163660, 163662, 163663, 163665, 163668, 163670, 163673, 163674, 163676, 163677, 163680, 163684, 163688, 163692, 163696, 163697, 163698, 163699, 163706, 163707, 163709, 163714, 163715, 163722, 163726, 163740, 163741, 163743, 163750, 163753, 163754, 163755, 163757, 163762, 163769, 163776, 163785, 163787, 163788, 163791, 163792, 163806, 163809, 163820, 163824, 163827, 163828, 163839, 163841, 163845, 163847, 163852, 163854, 163856, 163859, 163863, 163866, 163867, 163872, 163873, 163877, 163879, 163881, 163882, 163886, 163891, 163896, 163897, 163898, 163904, 163906, 163908, 163909, 163918, 163921, 163925, 163930, 163935, 163937, 163939, 163946, 163961, 163964, 163965, 163978, 163979, 163982, 163983, 163987, 163988, 163989, 163993, 163998, 164002, 164003, 164006, 164010, 164011, 164023, 164024, 164025, 164030, 164032, 164033, 164038, 164039, 164053, 164065, 164069, 164072, 164077, 164078, 164080, 164084, 164085, 164088, 164092, 164098, 164101, 164109, 164110, 164117, 164122, 164128, 164143, 164149, 164154, 164160, 164164, 164166, 164174, 164176, 164178, 164179, 164183, 164193, 164200, 164202, 164208, 164209, 164212, 164215, 164216, 164217, 164225, 164226, 164227, 164229, 164240, 164243, 164244, 164254, 164267, 164275, 164277, 164281, 164295, 164310, 164317, 164320, 164321, 164324, 164327, 164333, 164334, 164335, 164337, 164338, 164340, 164344, 164345, 164348, 164354, 164356, 164359, 164364, 164375, 164380, 164393, 164394, 164399, 164406, 164407, 164408, 164430, 164435, 164439, 164440, 164452, 164458, 164465, 164476, 164480, 164485, 164488, 164492, 164512, 164515, 164516, 164517, 164519, 164521, 164526, 164528, 164531, 164535, 164536, 164541, 164542, 164550, 164553, 164554, 164558, 164560, 164563, 164566, 164568, 164582, 164586, 164617, 164619, 164621, 164626, 164627, 164628, 164629, 164632, 164637, 164642, 164647, 164655, 164662, 164665, 164668, 164677, 164678, 164680, 164685, 164693, 164695, 164708, 164709, 164712, 164715, 164725, 164726, 164729, 164731, 164739, 164744, 164748, 164755, 164762, 164763, 164765, 164770, 164772, 164781, 164787, 164792, 164795, 164797, 164798, 164800, 164804, 164806, 164809, 164811, 164818, 164820, 164831, 164836, 164839, 164845, 164846, 164854, 164860, 164867, 164875, 164877, 164881, 164884, 164885, 164895, 164899, 164909, 164912, 164919, 164924, 164928, 164929, 164930, 164937, 164939, 164951, 164953, 164957, 164962, 164964, 164966, 164967, 164969, 164978, 164980, 164981, 164982, 164985, 164999, 165000, 165008, 165009, 165012, 165016, 165021, 165027, 165030, 165031, 165037, 165039, 165042, 165048, 165052, 165059, 165065, 165066, 165069, 165071, 165080, 165086, 165088, 165095, 165100, 165107, 165118, 165125, 165129, 165135, 165141, 165143, 165149, 165153, 165155, 165157, 165158, 165159, 165163, 165164, 165166, 165168, 165169, 165174, 165176, 165179, 165185, 165190, 165196, 165210, 165211, 165214, 165219, 165220, 165225, 165229, 165233, 165234, 165235, 165237, 165240, 165243, 165245, 165249, 165252, 165258, 165260, 165264, 165271, 165274, 165275, 165283, 165298, 165300, 165302, 165309, 165310, 165317, 165326, 165331, 165332, 165334, 165338, 165341, 165344, 165347, 165348, 165349, 165351, 165356, 165358, 165359, 165365, 165367, 165388, 165393, 165395, 165396, 165403, 165404, 165407, 165417, 165431, 165434, 165436, 165440, 165449, 165459, 165460, 165461, 165464, 165477, 165478, 165483, 165484, 165485, 165486, 165489, 165490, 165492, 165493, 165495, 165496, 165497, 165502, 165503, 165507, 165514, 165521, 165522, 165524, 165536, 165551, 165566, 165576, 165580, 165600, 165601, 165602, 165608, 165621, 165625, 165627, 165632, 165638, 165641, 165643, 165659, 165661, 165665, 165673, 165676, 165683, 165691, 165702, 165703, 165706, 165711, 165713, 165714, 165722, 165723, 165740, 165742, 165766, 165768, 165772, 165774, 165779, 165801, 165804, 165815, 165816, 165824, 165826, 165827, 165829, 165831, 165833, 165839, 165841, 165847, 165859, 165861, 165863, 165867, 165872, 165874, 165876, 165882, 165883, 165887, 165891, 165893, 165897, 165898, 165909, 165912, 165915, 165919, 165923, 165925, 165929, 165932, 165934, 165936, 165939, 165946, 165950, 165951, 165957, 165962, 165964, 165967, 165979, 165991, 165998, 166006, 166008, 166011, 166019, 166020, 166026, 166030, 166031, 166032, 166036, 166046, 166048, 166053, 166062, 166082, 166084, 166086, 166088, 166097, 166101, 166105, 166115, 166119, 166131, 166132, 166139, 166141, 166144, 166147, 166154, 166160, 166169, 166171, 166182, 166183, 166189, 166192, 166195, 166199, 166201, 166205, 166209, 166210, 166215, 166217, 166220, 166223, 166225, 166228, 166231, 166242, 166243, 166253, 166265, 166268, 166284, 166300, 166302, 166305, 166306, 166309, 166315, 166318, 166319, 166320, 166321, 166327, 166328, 166333, 166334, 166357, 166361, 166364, 166370, 166372, 166377, 166384, 166387, 166388, 166390, 166391, 166392, 166397, 166399, 166405, 166406, 166417, 166420, 166426, 166433, 166435, 166437, 166438, 166439, 166450, 166453, 166461, 166467, 166469, 166478, 166479, 166483, 166490, 166493, 166498, 166499, 166507, 166509, 166520, 166521, 166527, 166529, 166537, 166540, 166543, 166552, 166557, 166559, 166565, 166570, 166571, 166574, 166575, 166578, 166586, 166608, 166620, 166622, 166624, 166626, 166627, 166642, 166643, 166645, 166649, 166653, 166658, 166666, 166667, 166669, 166671, 166674, 166675, 166685, 166693, 166695, 166697, 166703, 166704, 166709, 166719, 166722, 166728, 166733, 166734, 166738, 166739, 166752, 166762, 166768, 166775, 166777, 166785, 166787, 166788, 166789, 166790, 166795, 166804, 166831, 166832, 166835, 166840, 166842, 166855, 166863, 166871, 166873, 166876, 166886, 166890, 166896, 166898, 166904, 166910, 166914, 166915, 166917, 166930, 166939, 166944, 166946, 166951, 166952, 166959, 166961, 166962, 166965, 166980, 166984, 166985, 167008, 167010, 167012, 167015, 167019, 167020, 167024, 167029, 167034, 167037, 167041, 167042, 167049, 167053, 167062, 167064, 167066, 167073, 167077, 167090, 167107, 167112, 167114, 167117, 167133, 167139, 167143, 167146, 167152, 167160, 167161, 167165, 167166, 167170, 167172, 167175, 167177, 167182, 167198, 167200, 167207, 167210, 167214, 167227, 167229, 167230, 167231, 167233, 167240, 167247, 167255, 167258, 167261, 167265, 167269, 167270, 167280, 167281, 167288, 167290, 167291, 167297, 167298, 167302, 167305, 167307, 167311, 167313, 167317, 167326, 167333, 167335, 167341, 167350, 167360, 167363, 167366, 167368, 167375, 167378, 167380, 167381, 167389, 167391, 167392, 167399, 167400, 167409, 167411, 167420, 167422, 167424, 167431, 167442, 167443, 167447, 167454, 167455, 167459, 167474, 167479, 167480, 167491, 167492, 167496, 167498, 167499, 167508, 167518, 167520, 167521, 167527, 167529, 167533, 167536, 167543, 167550, 167552, 167554, 167558, 167560, 167561, 167569, 167572, 167574, 167577, 167585, 167599, 167602, 167606, 167608, 167609, 167611, 167617, 167618, 167620, 167623, 167628, 167630, 167647, 167649, 167652, 167669, 167676, 167684, 167688, 167690, 167694, 167699, 167700, 167703, 167705, 167706, 167708, 167710, 167729, 167734, 167739, 167742, 167744, 167746, 167747, 167751, 167759, 167769, 167771, 167772, 167786, 167789, 167791, 167800, 167804, 167810, 167811, 167819, 167825, 167834, 167840, 167843, 167845, 167848, 167851, 167852, 167859, 167862, 167864, 167865, 167869, 167876, 167877, 167885, 167888, 167889, 167891, 167893, 167899, 167911, 167921, 167928, 167932, 167935, 167936, 167938, 167941, 167944, 167960, 167966, 167974, 167986, 167987, 167990, 168005, 168008, 168009, 168013, 168016, 168018, 168021, 168044, 168046, 168047, 168052, 168072, 168076, 168081, 168085, 168094, 168098, 168105, 168112, 168115, 168119, 168121, 168129, 168139, 168140, 168143, 168144, 168146, 168155, 168166, 168168, 168172, 168177, 168178, 168193, 168196, 168214, 168224, 168229, 168231, 168237, 168238, 168241, 168242, 168243, 168247, 168249, 168250, 168257, 168263, 168264, 168267, 168268, 168274, 168282, 168284, 168290, 168294, 168303, 168304, 168310, 168311, 168324, 168329, 168331, 168332, 168340, 168341, 168348, 168350, 168355, 168356, 168357, 168359, 168365, 168366, 168368, 168369, 168370, 168380, 168381, 168385, 168388, 168394, 168402, 168411, 168417, 168425, 168428, 168432, 168433, 168434, 168439, 168443, 168451, 168459, 168463, 168474, 168480, 168487, 168490, 168496, 168497, 168500, 168503, 168515, 168518, 168525, 168529, 168539, 168542, 168545, 168548, 168549, 168550, 168554, 168555, 168558, 168563, 168567, 168577, 168595, 168596, 168597, 168598, 168601, 168604, 168613, 168618, 168620, 168625, 168628, 168636, 168643, 168648, 168651, 168653, 168656, 168657, 168666, 168668, 168675, 168679, 168680, 168681, 168690, 168695, 168702, 168703, 168706, 168709, 168712, 168717, 168722, 168725, 168731, 168732, 168738, 168741, 168744, 168750, 168754, 168755, 168756, 168763, 168766, 168768, 168772, 168778, 168779, 168788, 168798, 168802, 168806, 168807, 168808, 168809, 168814, 168823, 168824, 168829, 168833, 168843, 168852, 168855, 168858, 168862, 168868, 168878, 168880, 168894, 168899, 168914, 168915, 168920, 168921, 168922, 168928, 168942, 168956, 168957, 168964, 168973, 168983, 168985, 168987, 168996, 169014, 169016, 169017, 169021, 169037, 169038, 169042, 169049, 169068, 169082, 169092, 169104, 169114, 169116, 169117, 169118, 169119, 169121, 169125, 169132, 169134, 169135, 169136, 169143, 169145, 169146, 169147, 169149, 169150, 169151, 169160, 169162, 169165, 169167, 169178, 169179, 169180, 169181, 169182, 169190, 169194, 169196, 169202, 169203, 169204, 169206, 169208, 169213, 169215, 169217, 169221, 169227, 169229, 169230, 169238, 169243, 169245, 169247, 169263, 169264, 169266, 169269, 169275, 169278, 169284, 169288, 169292, 169293, 169311, 169313, 169314, 169319, 169331, 169339, 169340, 169341, 169362, 169364, 169371, 169380, 169382, 169384, 169388, 169390, 169400, 169401, 169410, 169411, 169414, 169415, 169418, 169433, 169435, 169441, 169444, 169448, 169450, 169453, 169455, 169457, 169458, 169461, 169471, 169483, 169484, 169488, 169493, 169494, 169496, 169500, 169501, 169503, 169507, 169509, 169511, 169514, 169518, 169520, 169521, 169522, 169524, 169538, 169539, 169540, 169548, 169568, 169579, 169582, 169584, 169590, 169591, 169595, 169602, 169604, 169607, 169611, 169626, 169628, 169629, 169631, 169632, 169639, 169644, 169645, 169648, 169653, 169670, 169672, 169705, 169706, 169711, 169712, 169713, 169720, 169722, 169732, 169752, 169758, 169763, 169765, 169768, 169775, 169777, 169778, 169783, 169784, 169792, 169793, 169794, 169798, 169799, 169809, 169812, 169813, 169825, 169836, 169838, 169840, 169848, 169851, 169857, 169858, 169860, 169869, 169880, 169883, 169898, 169900, 169902, 169906, 169914, 169917, 169937, 169947, 169956, 169967, 169975, 169976, 169981, 169987, 169993, 170008, 170010, 170013, 170016, 170023, 170032, 170033, 170034, 170036, 170043, 170068, 170080, 170084, 170099, 170110, 170118, 170123, 170129, 170130, 170131, 170137, 170139, 170140, 170141, 170142, 170143, 170146, 170151, 170152, 170164, 170172, 170174, 170178, 170192, 170194, 170195, 170200, 170203, 170205, 170222, 170228, 170232, 170234, 170238, 170239, 170247, 170248, 170256, 170266, 170286, 170288, 170289, 170298, 170299, 170303, 170308, 170309, 170313, 170315, 170320, 170322, 170324, 170325, 170329, 170333, 170334, 170337, 170339, 170342, 170347, 170354, 170356, 170358, 170368, 170374, 170376, 170385, 170390, 170392, 170395, 170410, 170418, 170419, 170425, 170429, 170436, 170449, 170455, 170471, 170474, 170477, 170488, 170497, 170498, 170512, 170524, 170532, 170537, 170551, 170554, 170559, 170567, 170569, 170576, 170587, 170590, 170593, 170597, 170599, 170610, 170612, 170613, 170618, 170619, 170628, 170635, 170651, 170658, 170667, 170671, 170675, 170683, 170698, 170699, 170700, 170709, 170714, 170721, 170729, 170730, 170747, 170753, 170762, 170764, 170774, 170775, 170780, 170781, 170782, 170787, 170789, 170793, 170798, 170802, 170803, 170823, 170825, 170837, 170845, 170846, 170856, 170860, 170861, 170867, 170870, 170873, 170879, 170881, 170882, 170883, 170885, 170893, 170896, 170900, 170908, 170915, 170919, 170923, 170937, 170940, 170942, 170944, 170946, 170953, 170956, 170964, 170990, 170992, 170993, 170995, 170996, 170999, 171010, 171013, 171019, 171022, 171023, 171032, 171037, 171040, 171051, 171056, 171061, 171064, 171069, 171071, 171073, 171074, 171076, 171079, 171086, 171089, 171098, 171116, 171119, 171129, 171130, 171131, 171138, 171140, 171141, 171145, 171159, 171168, 171170, 171174, 171175, 171182, 171186, 171199, 171201, 171203, 171209, 171212, 171214, 171216, 171220, 171236, 171237, 171242, 171247, 171255, 171268, 171277, 171278, 171279, 171290, 171292, 171294, 171300, 171302, 171304, 171314, 171335, 171339, 171343, 171345, 171352, 171355, 171356, 171385, 171394, 171395, 171397, 171400, 171405, 171408, 171413, 171420, 171421, 171427, 171430, 171436, 171439, 171441, 171455, 171464, 171469, 171474, 171475, 171477, 171480, 171503, 171504, 171507, 171512, 171520, 171521, 171531, 171541, 171545, 171547, 171552, 171556, 171561, 171562, 171568, 171578, 171581, 171595, 171597, 171607, 171611, 171612, 171613, 171620, 171624, 171632, 171641, 171642, 171647, 171649, 171650, 171656, 171657, 171663, 171679, 171680, 171681, 171683, 171684, 171689, 171692, 171699, 171700, 171701, 171705, 171729, 171755, 171758, 171759, 171765, 171766, 171772, 171773, 171774, 171775, 171777, 171789, 171799, 171806, 171811, 171814, 171827, 171837, 171839, 171846, 171850, 171884, 171892, 171894, 171899, 171900, 171908, 171911, 171920, 171928, 171943, 171948, 171949, 171954, 171955, 171960, 171963, 171966, 171973, 171974, 171981, 171985, 171986, 171990, 171999, 172002, 172004, 172010, 172012, 172013, 172020, 172027, 172029, 172036, 172044, 172048, 172055, 172060, 172064, 172079, 172080, 172088, 172096, 172108, 172109, 172116, 172117, 172126, 172150, 172155, 172160, 172162, 172166, 172167, 172173, 172175, 172185, 172187, 172189, 172194, 172200, 172202, 172203, 172209, 172214, 172217, 172219, 172221, 172222, 172223, 172224, 172226, 172233, 172241, 172250, 172251, 172252, 172261, 172262, 172269, 172278, 172280, 172283, 172284, 172290, 172298, 172302, 172303, 172304, 172307, 172309, 172311, 172320, 172330, 172332, 172334, 172337, 172339, 172352, 172353, 172362, 172366, 172381, 172397, 172401, 172404, 172406, 172411, 172416, 172418, 172421, 172433, 172434, 172435, 172446, 172449, 172453, 172469, 172519, 172521, 172530, 172533, 172537, 172547, 172555, 172562, 172570, 172575, 172577, 172579, 172588, 172589, 172591, 172594, 172596, 172597, 172598, 172600, 172602, 172604, 172605, 172613, 172615, 172616, 172630, 172633, 172634, 172636, 172639, 172642, 172648, 172649, 172651, 172669, 172676, 172680, 172681, 172682, 172684, 172688, 172698, 172701, 172704, 172706, 172709, 172711, 172715, 172717, 172723, 172725, 172726, 172727, 172731, 172745, 172746, 172751, 172753, 172759, 172772, 172782, 172783, 172785, 172786, 172792, 172798, 172800, 172805, 172806, 172810, 172813, 172817, 172821, 172827, 172833, 172843, 172850, 172858, 172859, 172871, 172874, 172883, 172895, 172905, 172914, 172917, 172923, 172924, 172926, 172927, 172934, 172943, 172962, 172963, 172972, 172978, 172981, 172997, 173000, 173001, 173002, 173018, 173029, 173030, 173032, 173055, 173068, 173071, 173072, 173073, 173076, 173079, 173082, 173090, 173091, 173092, 173108, 173110, 173111, 173121, 173123, 173136, 173137, 173141, 173142, 173149, 173152, 173155, 173171, 173173, 173177, 173178, 173185, 173201, 173209, 173213, 173217, 173224, 173233, 173235, 173242, 173244, 173250, 173251, 173255, 173264, 173273, 173281, 173282, 173296, 173305, 173306, 173307, 173310, 173312, 173320, 173321, 173326, 173331, 173334, 173339, 173340, 173341, 173357, 173361, 173363, 173370, 173371, 173387, 173388, 173390, 173395, 173401, 173403, 173406, 173416, 173420, 173425, 173431, 173450, 173453, 173455, 173474, 173482, 173486, 173487, 173489, 173490, 173496, 173501, 173505, 173512, 173513, 173522, 173554, 173561, 173562, 173563, 173565, 173569, 173577, 173579, 173606, 173610, 173613, 173616, 173632, 173635, 173642, 173648, 173656, 173659, 173663, 173670, 173672, 173684, 173686, 173690, 173692, 173699, 173706, 173708, 173715, 173720, 173727, 173728, 173736, 173738, 173739, 173740, 173742, 173743, 173749, 173752, 173762, 173766, 173767, 173779, 173782, 173788, 173802, 173803, 173816, 173821, 173822, 173826, 173828, 173829, 173830, 173847, 173850, 173857, 173859, 173873, 173876, 173879, 173890, 173891, 173894, 173895, 173896, 173897, 173907, 173908, 173909, 173915, 173917, 173920, 173928, 173930, 173951, 173961, 173969, 173974, 173979, 173981, 173982, 173990, 173992, 174003, 174005, 174007, 174013, 174028, 174040, 174041, 174049, 174055, 174058, 174059, 174064, 174067, 174068, 174081, 174082, 174089, 174091, 174093, 174096, 174100, 174103, 174104, 174113, 174115, 174123, 174127, 174132, 174139, 174140, 174142, 174143, 174146, 174152, 174156, 174161, 174165, 174167, 174178, 174181, 174186, 174187, 174191, 174197, 174201, 174211, 174218, 174227, 174231, 174247, 174254, 174255, 174257, 174258, 174260, 174263, 174264, 174269, 174281, 174287, 174288, 174290, 174303, 174310, 174311, 174313, 174323, 174332, 174339, 174348, 174351, 174354, 174356, 174358, 174359, 174364, 174365, 174380, 174384, 174385, 174386, 174388, 174389, 174390, 174391, 174397, 174398, 174410, 174470, 174474, 174475, 174479, 174485, 174490, 174492, 174502, 174506, 174509, 174517, 174541, 174545, 174549, 174553, 174555, 174557, 174562, 174564, 174566, 174577, 174584, 174586, 174598, 174600, 174611, 174617, 174621, 174626, 174630, 174633, 174635, 174651, 174661, 174665, 174667, 174669, 174673, 174676, 174680, 174693, 174696, 174699, 174703, 174706, 174716, 174717, 174718, 174721, 174729, 174732, 174751, 174756, 174757, 174758, 174765, 174772, 174775, 174779, 174781, 174785, 174786, 174787, 174810, 174838, 174839, 174851, 174858, 174860, 174869, 174870, 174871, 174878, 174881, 174884, 174888, 174893, 174899, 174914, 174921, 174931, 174941, 174952, 174955, 174961, 174966, 174968, 174969, 174988, 174991, 175003, 175006, 175008, 175010, 175011, 175017, 175019, 175037, 175041, 175049, 175050, 175051, 175057, 175058, 175063, 175076, 175078, 175090, 175096, 175101, 175104, 175106, 175112, 175113, 175114, 175124, 175126, 175143, 175154, 175159, 175161, 175167, 175173, 175190, 175194, 175201, 175208, 175220, 175228, 175233, 175249, 175253, 175261, 175268, 175269, 175271, 175283, 175288, 175293, 175328, 175331, 175337, 175340, 175341, 175356, 175371, 175374, 175383, 175386, 175394, 175395, 175397, 175399, 175407, 175415, 175419, 175429, 175442, 175444, 175447, 175457, 175461, 175469, 175473, 175474, 175479, 175482, 175492, 175494, 175497, 175502, 175511, 175516, 175520, 175523, 175539, 175541, 175543, 175544, 175551, 175552, 175556, 175559, 175560, 175564, 175569, 175572, 175582, 175583, 175585, 175592, 175594, 175600, 175608, 175610, 175611, 175619, 175622, 175631, 175641, 175642, 175644, 175648, 175650, 175673, 175675, 175678, 175679, 175691, 175710, 175712, 175714, 175715, 175723, 175726, 175732, 175733, 175735, 175749, 175755, 175761, 175773, 175775, 175777, 175783, 175786, 175789, 175796, 175798, 175807, 175809, 175823, 175839, 175849, 175854, 175860, 175878, 175879, 175883, 175888, 175889, 175890, 175895, 175900, 175901, 175914, 175924, 175934, 175949, 175956, 175963, 175964, 175965, 175983, 175984, 175997, 176003, 176006, 176014, 176038, 176039, 176046, 176056, 176060, 176065, 176070, 176096, 176102, 176105, 176108, 176109, 176113, 176116, 176138, 176144, 176149, 176150, 176152, 176162, 176182, 176186, 176187, 176189, 176198, 176202, 176233, 176235, 176254, 176257, 176258, 176261, 176262, 176265, 176272, 176274, 176300, 176328, 176330, 176332, 176343, 176346, 176354, 176358, 176365, 176371, 176372, 176384, 176385, 176391, 176401, 176420, 176425, 176430, 176445, 176456, 176463, 176466, 176468, 176470, 176474, 176479, 176486, 176491, 176492, 176495, 176498, 176502, 176506, 176512, 176516, 176522, 176524, 176531, 176545, 176557, 176558, 176559, 176565, 176567, 176577, 176587, 176588, 176591, 176592, 176593, 176603, 176614, 176615, 176618, 176622, 176643, 176650, 176655, 176662, 176663, 176671, 176680, 176687, 176694, 176700, 176701, 176715, 176727, 176741, 176746, 176751, 176752, 176753, 176754, 176755, 176762, 176767, 176770, 176783, 176784, 176785, 176786, 176806, 176809, 176815, 176822, 176823, 176824, 176828, 176839, 176840, 176841, 176843, 176851, 176852, 176854, 176876, 176877, 176885, 176889, 176891, 176893, 176897, 176902, 176907, 176910, 176911, 176916, 176921, 176923, 176925, 176931, 176935, 176942, 176943, 176962, 176963, 176970, 176981, 176982, 176986, 176988, 176992, 176997, 177008, 177011, 177019, 177026, 177031, 177032, 177036, 177039, 177046, 177052, 177054, 177066, 177067, 177069, 177083, 177090, 177095, 177097, 177105, 177110, 177113, 177122, 177132, 177144, 177148, 177155, 177156, 177157, 177158, 177195, 177196, 177198, 177199, 177218, 177229, 177250, 177251, 177256, 177258, 177259, 177261, 177263, 177264, 177284, 177287, 177290, 177291, 177292, 177293, 177295, 177311, 177315, 177328, 177334, 177346, 177355, 177358, 177364, 177366, 177367, 177370, 177376, 177379, 177380, 177381, 177396, 177403, 177404, 177409, 177416, 177422, 177437, 177438, 177444, 177450, 177475, 177479, 177480, 177490, 177495, 177499, 177505, 177514, 177515, 177522, 177545, 177560, 177561, 177564, 177570, 177571, 177572, 177575, 177580, 177608, 177616, 177628, 177635, 177642, 177649, 177652, 177653, 177656, 177658, 177661, 177671, 177711, 177716, 177718, 177724, 177725, 177726, 177727, 177738, 177740, 177742, 177747, 177751, 177756, 177761, 177764, 177776, 177783, 177787, 177791, 177795, 177796, 177797, 177807, 177809, 177814, 177832, 177836, 177840, 177857, 177861, 177866, 177867, 177869, 177872, 177877, 177881, 177886, 177887, 177888, 177902, 177904, 177915, 177933, 177935, 177937, 177942, 177947, 177948, 177949, 177952, 177959, 177960, 177966, 177986, 177989, 177994, 178009, 178014, 178024, 178025, 178026, 178029, 178031, 178032, 178040, 178055, 178064, 178071, 178073, 178081, 178089, 178091, 178095, 178102, 178105, 178107, 178108, 178115, 178125, 178129, 178136, 178138, 178141, 178145, 178154, 178169, 178178, 178181, 178185, 178186, 178203, 178215, 178219, 178222, 178229, 178234, 178241, 178250, 178258, 178274, 178275, 178278, 178288, 178299, 178305, 178310, 178313, 178314, 178330, 178332, 178333, 178351, 178356, 178363, 178367, 178370, 178381, 178390, 178399, 178407, 178409, 178416, 178428, 178440, 178447, 178475, 178477, 178479, 178480, 178481, 178484, 178487, 178490, 178500, 178502, 178503, 178505, 178521, 178537, 178542, 178559, 178567, 178571, 178573, 178578, 178579, 178581, 178582, 178591, 178592, 178594, 178595, 178598, 178604, 178611, 178619, 178624, 178631, 178634, 178648, 178650, 178658, 178691, 178702, 178708, 178712, 178757, 178761, 178773, 178778, 178779, 178792, 178800, 178804, 178807, 178814, 178815, 178828, 178832, 178849, 178854, 178858, 178866, 178871, 178874, 178890, 178893, 178895, 178906, 178912, 178927, 178973, 178985, 178986, 178993, 178996, 179004, 179013, 179014, 179018, 179026, 179027, 179032, 179038, 179040, 179052, 179054, 179072, 179084, 179099, 179102, 179112, 179119, 179125, 179131, 179133, 179134, 179142, 179148, 179156, 179161, 179163, 179166, 179173, 179180, 179182, 179185, 179193, 179194, 179196, 179204, 179208, 179209, 179212, 179224, 179225, 179231, 179232, 179235, 179239, 179241, 179248, 179249, 179251, 179254, 179255, 179256, 179260, 179263, 179266, 179277, 179279, 179297, 179298, 179302, 179311, 179313, 179317, 179318, 179331, 179348, 179358, 179360, 179363, 179378, 179389, 179391, 179392, 179404, 179413, 179428, 179430, 179433, 179434, 179436, 179439, 179449, 179465, 179471, 179480, 179481, 179489, 179491, 179495, 179499, 179502, 179503, 179505, 179510, 179526, 179527, 179544, 179548, 179551, 179557, 179559, 179571, 179575, 179582, 179589, 179590, 179593, 179611, 179616, 179626, 179627, 179628, 179635, 179636, 179640, 179647, 179657, 179661, 179662, 179682, 179689, 179698, 179705, 179710, 179721, 179723, 179724, 179728, 179737, 179741, 179752, 179757, 179760, 179765, 179775, 179776, 179782, 179788, 179789, 179791, 179795, 179798, 179812, 179816, 179824, 179828, 179835, 179836, 179838, 179845, 179852, 179854, 179860, 179874, 179877, 179883, 179890, 179906, 179917, 179921, 179931, 179941, 179943, 179949, 179951, 179973, 179975, 179976, 179979, 179983, 179985, 179993, 179994, 179998, 180011, 180012, 180019, 180020, 180036, 180039, 180040, 180055, 180058, 180070, 180074, 180078, 180096, 180112, 180121, 180126, 180127, 180128, 180132, 180133, 180141, 180161, 180162, 180172, 180174, 180188, 180193, 180197, 180233, 180241, 180271, 180272, 180285, 180286, 180288, 180293, 180311, 180319, 180320, 180341, 180350, 180351, 180352, 180367, 180371, 180388, 180391, 180401, 180410, 180414, 180429, 180433, 180435, 180436, 180456, 180461, 180463, 180464, 180469, 180476, 180478, 180480, 180485, 180508, 180510, 180511, 180516, 180518, 180528, 180536, 180537, 180546, 180548, 180550, 180552, 180557, 180566, 180578, 180581, 180590, 180592, 180594, 180613, 180616, 180622, 180623, 180629, 180636, 180647, 180651, 180657, 180659, 180664, 180675, 180680, 180681, 180684, 180702, 180706, 180709, 180716, 180722, 180723, 180725, 180726, 180739, 180747, 180763, 180764, 180793, 180808, 180810, 180848, 180849, 180855, 180858, 180864, 180879, 180881, 180882, 180884, 180890, 180896, 180911, 180916, 180927, 180935, 180939, 180941, 180942, 180951, 180952, 180953, 180956, 180972, 180988, 180993, 180996, 181002, 181014, 181020, 181026, 181028, 181049, 181052, 181070, 181078, 181080, 181089, 181093, 181097, 181099, 181105, 181114, 181118, 181120, 181121, 181124, 181130, 181133, 181144, 181149, 181163, 181169, 181173, 181183, 181225, 181226, 181269, 181280, 181281, 181291, 181315, 181317, 181319, 181322, 181323, 181326, 181330, 181339, 181341, 181342, 181343, 181344, 181352, 181356, 181358, 181364, 181377, 181389, 181397, 181400, 181401, 181403, 181404, 181425, 181445, 181447, 181449, 181456, 181478, 181480, 181507, 181511, 181514, 181535, 181539, 181542, 181557, 181579, 181582, 181583, 181614, 181616, 181620, 181622, 181623, 181624, 181632, 181637, 181651, 181655, 181659, 181664, 181671, 181677, 181687, 181692, 181698, 181701, 181708, 181715, 181722, 181726, 181743, 181754, 181757, 181759, 181763, 181766, 181771, 181774, 181775, 181782, 181785, 181789, 181795, 181796, 181801, 181808, 181810, 181820, 181822, 181834, 181835, 181852, 181860, 181878, 181886, 181887, 181891, 181892, 181895, 181919, 181927, 181932, 181938, 181940, 181948, 181953, 181963, 181968, 181969, 181970, 181976, 181977, 181988, 181996, 182011, 182029, 182032, 182035, 182037, 182041, 182044, 182045, 182048, 182051, 182052, 182065, 182074, 182078, 182114, 182135, 182136, 182137, 182156, 182157, 182162, 182174, 182175, 182178, 182186, 182189, 182192, 182200, 182202, 182203, 182212, 182223, 182224, 182229, 182232, 182241, 182250, 182251, 182268, 182270, 182272, 182273, 182277, 182287, 182298, 182314, 182326, 182328, 182331, 182340, 182343, 182345, 182349, 182364, 182367, 182370, 182385, 182386, 182388, 182394, 182396, 182401, 182406, 182408, 182411, 182414, 182417, 182441, 182455, 182460, 182463, 182466, 182470, 182480, 182494, 182496, 182510, 182512, 182533, 182546, 182550, 182552, 182556, 182563, 182564, 182570, 182579, 182596, 182598, 182602, 182604, 182606, 182610, 182611, 182627, 182638, 182652, 182653, 182673, 182675, 182689, 182690, 182733, 182742, 182749, 182752, 182755, 182758, 182759, 182766, 182768, 182769, 182772, 182779, 182784, 182786, 182809, 182811, 182825, 182848, 182851, 182853, 182864, 182868, 182879, 182888, 182890, 182899, 182907, 182911, 182916, 182920, 182926, 182934, 182944, 182949, 182958, 182969, 182975, 182982, 182988, 182998, 183000, 183006, 183025, 183048, 183055, 183060, 183066, 183067, 183074, 183089, 183095, 183106, 183108, 183124, 183125, 183126, 183139, 183148, 183150, 183172, 183200, 183228, 183229, 183230, 183231, 183252, 183254, 183257, 183260, 183262, 183263, 183270, 183276, 183277, 183278, 183280, 183301, 183302, 183316, 183322, 183327, 183337, 183344, 183366, 183374, 183375, 183376, 183394, 183417, 183427, 183428, 183430, 183442, 183443, 183447, 183450, 183457, 183459, 183468, 183471, 183472, 183485, 183494, 183501, 183503, 183511, 183513, 183515, 183522, 183525, 183544, 183549, 183550, 183554, 183557, 183565, 183570, 183575, 183578, 183583, 183590, 183594, 183608, 183635, 183640, 183666, 183673, 183674, 183696, 183704, 183719, 183720, 183726, 183738, 183740, 183747, 183758, 183763, 183782, 183790, 183800, 183806, 183810, 183814, 183822, 183836, 183848, 183850, 183852, 183857, 183860, 183861, 183871, 183872, 183878, 183885, 183900, 183907, 183909, 183911, 183913, 183919, 183927, 183936, 183937, 183943, 183948, 183965, 183969, 183972, 183984, 183994, 184008, 184009, 184012, 184016, 184017, 184031, 184033, 184044, 184046, 184049, 184058, 184065, 184070, 184073, 184074, 184081, 184086, 184087, 184093, 184098, 184103, 184104, 184116, 184117, 184127, 184139, 184142, 184161, 184179, 184180, 184192, 184200, 184220, 184228, 184234, 184246, 184250, 184251, 184263, 184267, 184276, 184294, 184303, 184317, 184321, 184327, 184329, 184343, 184345, 184356, 184365, 184368, 184371, 184380, 184384, 184387, 184401, 184403, 184417, 184428, 184430, 184437, 184440, 184444, 184457, 184470, 184471, 184476, 184489, 184504, 184512, 184513, 184519, 184521, 184534, 184535, 184537, 184538, 184541, 184546, 184550, 184564, 184569, 184591, 184600, 184603, 184611, 184622, 184631, 184641, 184650, 184659, 184671, 184674, 184693, 184700, 184701, 184714, 184728, 184729, 184730, 184741, 184748, 184753, 184756, 184770, 184786, 184797, 184803, 184804, 184824, 184827, 184829, 184841, 184847, 184851, 184852, 184853, 184854, 184856, 184866, 184869, 184880, 184895, 184898, 184902, 184909, 184918, 184923, 184924, 184932, 184941, 184944, 184955, 184960, 184963, 184972, 184981, 184985, 184992, 184994, 185001, 185010, 185020, 185038, 185044, 185057, 185060, 185062, 185069, 185073, 185075, 185081, 185087, 185088, 185089, 185095, 185105, 185115, 185118, 185123, 185136, 185149, 185167, 185173, 185192, 185196, 185211, 185215, 185216, 185221, 185223, 185224, 185225, 185243, 185246, 185261, 185263, 185269, 185273, 185276, 185279, 185283, 185287, 185294, 185297, 185300, 185305, 185306, 185309, 185335, 185342, 185348, 185358, 185362, 185366, 185370, 185382, 185386, 185390, 185392, 185401, 185403, 185408, 185412, 185418, 185421, 185429, 185444, 185459, 185484, 185494, 185505, 185508, 185516, 185519, 185523, 185535, 185537, 185539, 185549, 185578, 185580, 185595, 185596, 185599, 185616, 185619, 185627, 185634, 185635, 185641, 185668, 185670, 185671, 185696, 185706, 185715, 185718, 185723, 185724, 185728, 185749, 185770, 185774, 185778, 185781, 185787, 185793, 185794, 185797, 185798, 185800, 185805, 185820, 185835, 185845, 185853, 185855, 185865, 185868, 185872, 185881, 185904, 185905, 185912, 185914, 185945, 185962, 185963, 185977, 185978, 185979, 185994, 185995, 185998, 185999, 186001, 186016, 186018, 186020, 186022, 186024, 186025, 186028, 186030, 186037, 186038, 186039, 186050, 186055, 186069, 186095, 186097, 186104, 186105, 186125, 186138, 186139, 186140, 186143, 186150, 186155, 186159, 186168, 186188, 186206, 186209, 186215, 186230, 186231, 186247, 186259, 186276, 186285, 186289, 186302, 186303, 186316, 186327, 186338, 186340, 186348, 186351, 186355, 186369, 186375, 186380, 186383, 186384, 186394, 186403, 186418, 186419, 186420, 186421, 186428, 186434, 186436, 186441, 186465, 186466, 186487, 186489, 186495, 186505, 186516, 186519, 186533, 186539, 186549, 186555, 186558, 186565, 186572, 186574, 186576, 186609, 186614, 186624, 186626, 186645, 186646, 186652, 186654, 186659, 186671, 186672, 186677, 186682, 186684, 186695, 186697, 186701, 186710, 186763, 186780, 186789, 186800, 186803, 186812, 186828, 186829, 186838, 186842, 186848, 186849, 186871, 186890, 186896, 186912, 186933, 186938, 186954, 186957, 186961, 186967, 186969, 186970, 186984, 186988, 186992, 187000, 187008, 187021, 187031, 187039, 187057, 187063, 187075, 187083, 187090, 187092, 187095, 187102, 187114, 187116, 187121, 187142, 187149, 187157, 187160, 187161, 187171, 187177, 187178, 187184, 187191, 187195, 187197, 187199, 187200, 187209, 187214, 187215, 187224, 187225, 187227, 187231, 187238, 187268, 187281, 187301, 187311, 187326, 187340, 187342, 187361, 187363, 187369, 187375, 187385, 187386, 187389, 187399, 187417, 187421, 187428, 187433, 187437, 187445, 187449, 187452, 187453, 187461, 187471, 187472, 187473, 187475, 187477, 187484, 187495, 187497, 187509, 187530, 187532, 187539, 187552, 187554, 187564, 187575, 187591, 187592, 187600, 187603, 187608, 187629, 187630, 187631, 187636, 187647, 187648, 187667, 187669, 187672, 187679, 187688, 187689, 187691, 187700, 187706, 187708, 187709, 187736, 187737, 187739, 187747, 187760, 187761, 187765, 187777, 187784, 187785, 187786, 187791, 187819, 187835, 187855, 187860, 187863, 187871, 187886, 187892, 187903, 187928, 187931, 187937, 187940, 187947, 187961, 187966, 187968, 187979, 187981, 187988, 187989, 187998, 188000, 188005, 188013, 188030, 188031, 188032, 188034, 188037, 188053, 188055, 188062, 188072, 188075, 188089, 188098, 188103, 188111, 188118, 188130, 188133, 188137, 188149, 188151, 188155, 188156, 188162, 188163, 188173, 188175, 188176, 188178, 188193, 188199, 188202, 188205, 188215, 188219, 188224, 188228, 188229, 188231, 188253, 188256, 188257, 188269, 188270, 188272, 188297, 188302, 188306, 188325, 188340, 188347, 188354, 188360, 188364, 188367, 188369, 188375, 188385, 188386, 188389, 188394, 188396, 188410, 188412, 188418, 188431, 188434, 188453, 188456, 188460, 188461, 188463, 188465, 188479, 188480, 188485, 188486, 188489, 188495, 188516, 188517, 188553, 188561, 188568, 188578, 188586, 188602, 188606, 188607, 188614, 188615, 188624, 188627, 188632, 188646, 188648, 188650, 188651, 188655, 188663, 188666, 188675, 188704, 188709, 188721, 188726, 188741, 188743, 188758, 188763, 188776, 188791, 188822, 188829, 188834, 188838, 188846, 188852, 188863, 188865, 188872, 188882, 188888, 188894, 188895, 188913, 188920, 188945, 188947, 188949, 188959, 188966, 188970, 188977, 188978, 188987, 188992, 189014, 189016, 189017, 189026, 189029, 189032, 189036, 189040, 189051, 189058, 189070, 189073, 189081, 189091, 189097, 189105, 189113, 189129, 189131, 189132, 189137, 189139, 189153, 189164, 189166, 189174, 189175, 189186, 189187, 189190, 189192, 189204, 189206, 189228, 189230, 189232, 189236, 189241, 189242, 189246, 189249, 189270, 189277, 189281, 189300, 189313, 189322, 189332, 189341, 189345, 189366, 189369, 189371, 189375, 189377, 189381, 189388, 189402, 189408, 189409, 189415, 189416, 189435, 189436, 189449, 189459, 189466, 189470, 189477, 189479, 189480, 189487, 189501, 189516, 189518, 189526, 189528, 189543, 189559, 189566, 189567, 189568, 189574, 189579, 189591, 189593, 189602, 189615, 189617, 189624, 189631, 189643, 189644, 189652, 189659, 189662, 189682, 189692, 189697, 189702, 189705, 189709, 189712, 189715, 189723, 189740, 189743, 189744, 189747, 189748, 189771, 189775, 189796, 189801, 189816, 189824, 189839, 189846, 189847, 189848, 189860, 189874, 189877, 189878, 189881, 189894, 189900, 189909, 189910, 189941, 189942, 189943, 189951, 189952, 189963, 189978, 189985, 189987, 190000, 190021, 190028, 190031, 190032, 190035, 190037, 190040, 190054, 190055, 190076, 190080, 190084, 190085, 190088, 190107, 190114, 190115, 190143, 190148, 190157, 190174, 190182, 190186, 190187, 190195, 190199, 190210, 190211, 190230, 190233, 190242, 190246, 190249, 190250, 190257, 190262, 190264, 190265, 190267, 190269, 190276, 190285, 190293, 190325, 190329, 190352, 190380, 190383, 190392, 190393, 190394, 190395, 190408, 190410, 190411, 190415, 190417, 190423, 190473, 190482, 190484, 190490, 190502, 190521, 190525, 190534, 190537, 190539, 190541, 190557, 190558, 190564, 190568, 190586, 190598, 190618, 190620, 190624, 190628, 190645, 190647, 190648, 190657, 190658, 190673, 190674, 190685, 190687, 190699, 190702, 190730, 190733, 190739, 190757, 190763, 190778, 190793, 190802, 190809, 190810, 190814, 190815, 190827, 190831, 190842, 190843, 190862, 190864, 190866, 190867, 190868, 190874, 190876, 190880, 190885, 190897, 190906, 190911, 190929, 190931, 190934, 190935, 190937, 190942, 190956, 190957, 190973, 190980, 190984, 190992, 190995, 191007, 191022, 191029, 191032, 191043, 191053, 191055, 191062, 191066, 191080, 191081, 191118, 191122, 191128, 191136, 191140, 191150, 191152, 191155, 191156, 191172, 191173, 191183, 191188, 191189, 191197, 191199, 191206, 191213, 191215, 191236, 191243, 191246, 191267, 191273, 191293, 191312, 191320, 191321, 191324, 191331, 191342, 191349, 191353, 191354, 191358, 191360, 191366, 191368, 191371, 191391, 191393, 191394, 191402, 191415, 191416, 191424, 191427, 191430, 191449, 191451, 191457, 191465, 191477, 191487, 191502, 191512, 191513, 191520, 191544, 191554, 191561, 191574, 191582, 191595, 191598, 191609, 191615, 191625, 191633, 191650, 191657, 191665, 191671, 191672, 191674, 191676, 191690, 191708, 191718, 191726, 191727, 191736, 191744, 191759, 191761, 191762, 191764, 191770, 191776, 191781, 191786, 191792, 191797, 191798, 191800, 191811, 191832, 191833, 191834, 191852, 191853, 191855, 191856, 191860, 191862, 191873, 191875, 191908, 191910, 191929, 191950, 191952, 191977, 191986, 191995, 192003, 192015, 192024, 192026, 192029, 192030, 192072, 192073, 192078, 192081, 192089, 192107, 192112, 192113, 192115, 192125, 192143, 192148, 192162, 192183, 192193, 192210, 192211, 192215, 192220, 192234, 192237, 192241, 192253, 192257, 192258, 192259, 192262, 192272, 192275, 192279, 192288, 192291, 192304, 192316, 192320, 192321, 192324, 192328, 192329, 192330, 192338, 192350, 192351, 192357, 192362, 192367, 192397, 192399, 192400, 192402, 192441, 192448, 192456, 192464, 192466, 192474, 192476, 192477, 192478, 192499, 192542, 192556, 192564, 192575, 192579, 192583, 192584, 192588, 192589, 192602, 192606, 192621, 192623, 192641, 192650, 192660, 192670, 192692, 192697, 192705, 192709, 192715, 192732, 192736, 192749, 192764, 192773, 192774, 192775, 192789, 192806, 192810, 192811, 192812, 192815, 192824, 192827, 192836, 192845, 192849, 192852, 192858, 192860, 192863, 192865, 192870, 192897, 192902, 192912, 192913, 192919, 192929, 192930, 192932, 192948, 192950, 192965, 192978, 192980, 192987, 193004, 193006, 193016, 193017, 193026, 193037, 193040, 193057, 193058, 193059, 193062, 193067, 193076, 193083, 193090, 193092, 193123, 193131, 193145, 193156, 193194, 193196, 193203, 193205, 193215, 193224, 193245, 193250, 193255, 193256, 193265, 193276, 193282, 193287, 193298, 193301, 193309, 193315, 193326, 193328, 193338, 193342, 193353, 193365, 193367, 193369, 193377, 193379, 193380, 193388, 193399, 193417, 193423, 193433, 193443, 193449, 193458, 193461, 193467, 193480, 193483, 193485, 193486, 193497, 193509, 193527, 193542, 193547, 193548, 193549, 193551, 193556, 193562, 193568, 193578, 193581, 193594, 193616, 193621, 193626, 193627, 193631, 193647, 193654, 193655, 193672, 193674, 193676, 193677, 193706, 193712, 193723, 193727, 193738, 193742, 193743, 193747, 193753, 193754, 193756, 193761, 193774, 193779, 193784, 193798, 193804, 193828, 193837, 193839, 193844, 193851, 193869, 193875, 193876, 193883, 193885, 193893, 193894, 193899, 193912, 193913, 193925, 193932, 193953, 193966, 193985, 193996, 194007, 194030, 194036, 194037, 194041, 194048, 194063, 194067, 194074, 194087, 194099, 194104, 194113, 194121, 194131, 194132, 194134, 194140, 194148, 194165, 194166, 194174, 194230, 194232, 194240, 194243, 194252, 194253, 194281, 194299, 194310, 194311, 194313, 194314, 194316, 194320, 194335, 194346, 194368, 194381, 194383, 194387, 194390, 194404, 194417, 194425, 194427, 194438, 194444, 194459, 194460, 194464, 194476, 194483, 194491, 194502, 194510, 194530, 194544, 194547, 194556, 194558, 194562, 194566, 194576, 194585, 194586, 194593, 194595, 194598, 194608, 194626, 194634, 194635, 194639, 194644, 194668, 194676, 194690, 194693, 194709, 194725, 194736, 194752, 194757, 194766, 194768, 194770, 194773, 194784, 194789, 194799, 194802, 194804, 194811, 194818, 194830, 194837, 194841, 194842, 194849, 194856, 194858, 194861, 194863, 194865, 194876, 194884, 194885, 194891, 194900, 194901, 194906, 194928, 194934, 194938, 194942, 194958, 194964, 194967, 194974, 194984, 195006, 195009, 195010, 195012, 195023, 195039, 195041, 195042, 195043, 195054, 195056, 195077, 195087, 195091, 195100, 195103, 195107, 195113, 195120, 195142, 195143, 195150, 195167, 195170, 195181, 195182, 195187, 195195, 195203, 195215, 195221, 195223, 195226, 195236, 195239, 195255, 195262, 195271, 195275, 195280, 195283, 195284, 195296, 195310, 195315, 195320, 195336, 195350, 195352, 195353, 195398, 195433, 195436, 195451, 195452, 195472, 195473, 195481, 195482, 195484, 195507, 195508, 195509, 195523, 195530, 195534, 195539, 195543, 195564, 195572, 195579, 195581, 195597, 195601, 195615, 195617, 195624, 195625, 195632, 195633, 195646, 195647, 195651, 195657, 195658, 195660, 195666, 195686, 195709, 195711, 195714, 195749, 195763, 195766, 195768, 195784, 195787, 195791, 195839, 195849, 195854, 195855, 195859, 195863, 195870, 195915, 195919, 195933, 195939, 195943, 195954, 195958, 195972, 195989, 195994, 196009, 196034, 196042, 196067, 196072, 196093, 196128, 196142, 196146, 196149, 196157, 196162, 196165, 196169, 196185, 196211, 196229, 196234, 196235, 196248, 196262, 196291, 196330, 196337, 196345, 196349, 196358, 196362, 196387, 196388, 196393, 196402, 196420, 196422, 196431, 196438, 196449, 196479, 196488, 196489, 196490, 196494, 196495, 196496, 196497, 196498, 196501, 196511, 196517, 196522, 196530, 196532, 196544, 196548, 196554, 196559, 196565, 196566, 196580, 196596, 196599, 196603, 196616, 196619, 196632, 196633, 196644, 196646, 196657, 196660, 196669, 196676, 196677, 196679, 196686, 196698, 196708, 196713, 196717, 196722, 196743, 196760, 196763, 196772, 196782, 196792, 196797, 196807, 196819, 196825, 196829, 196831, 196834, 196839, 196843, 196851, 196864, 196868, 196876, 196878, 196902, 196906, 196919, 196934, 196938, 196952, 196956, 196962, 196965, 196973, 196974, 196975, 196976, 196977, 196978, 196979, 196980, 196981, 196982, 196983, 196984, 196985, 196986, 196987, 196988, 196989, 196990, 196991, 196992, 196993, 196994, 196995, 196996, 196997, 196998, 196999, 197000, 197001, 197002, 197003, 197004, 197005, 197006, 197007, 197008, 197009, 197010, 197011, 197012, 197013, 197014, 197015, 197016, 197017, 197018, 197019, 197020, 197021, 197022, 197023, 197027, 197030, 197032, 197033, 197034, 197035, 197036, 197037, 197038, 197039, 197040, 197042, 197043, 197044, 197045, 197046, 197047, 197048, 197054, 197069, 197135, 197163, 197170, 197236, 197286, 197307, 197320, 197416, 197544, 197626, 197719, 197721, 197889, 198094, 198254, 198255, 198256, 198257, 198258, 198259, 198260, 198261, 198262, 198264, 198265, 198266, 198267, 198268, 198269, 198270, 198271, 198272, 198273, 198274, 198275, 198276, 198277, 198278, 198279, 198280, 198281, 198283, 198284, 198285, 198286, 198287, 198289, 198290, 198291, 198292, 198293, 198294, 198295, 198296, 198297, 198298, 198299, 198301, 198302, 198303, 198304, 198305, 198306, 198307, 198308, 198309, 198310, 198311, 198312, 198316, 198317, 198318, 198319, 198320, 198322, 198323, 198324, 198325, 198326, 198327, 198328, 198329, 198330, 198331, 198332, 198333, 198334, 198336, 198337, 198339, 198340, 198341, 198342, 198343, 198344, 198346, 198347, 198348, 198349, 198350, 198351, 198352, 198354, 198355, 198356, 198357, 198358, 198360, 198362, 198363, 198364, 198366, 198367, 198369, 198370, 198371, 198372, 198373, 198375, 198377, 198378, 198379, 198380, 198381, 198382, 198383, 198384, 198385, 198387, 198389, 198390, 198391, 198392, 198394, 198397, 198398, 198401, 198402, 198403, 198404, 198406, 198407, 198409, 198412, 198414, 198416, 198417, 198418, 198419, 198420, 198421, 198422, 198423, 198424, 198425, 198426, 198428, 198429, 198430, 198431, 198432, 198436, 198437, 198438, 198439, 198440, 198442, 198443, 198444, 198445, 198446, 198447, 198448, 198449, 198450, 198451, 198452, 198453, 198455, 198456, 198457, 198458, 198459, 198460, 198461, 198462, 198466, 198468, 198469, 198470, 198471, 198472, 198473, 198474, 198475, 198476, 198477, 198480, 198483, 198484, 198486, 198487, 198488, 198489, 198490, 198491, 198492, 198494, 198496, 198497, 198498, 198499, 198500, 198501, 198502, 198503, 198504, 198506, 198507, 198508, 198510, 198511, 198512, 198514, 198515, 198517, 198518, 198519, 198520, 198521, 198522, 198523, 198524, 198525, 198526, 198527, 198529, 198530, 198531, 198532, 198533, 198534, 198535, 198536, 198537, 198539, 198541, 198542, 198543, 198544, 198545, 198547, 198550, 198551, 198552, 198556, 198557, 198558, 198560, 198561, 198563, 198568, 198569, 198570, 198573, 198574, 198575, 198576, 198577, 198578, 198580, 198582, 198583, 198584, 198585, 198589, 198590, 198591, 198592, 198593, 198594, 198595, 198596, 198599, 198600, 198601, 198602, 198604, 198607, 198609, 198610, 198612, 198613, 198614, 198616, 198618, 198619, 198620, 198627, 198628, 198630, 198632, 198633, 198634, 198636, 198640, 198641, 198642, 198644, 198646, 198647, 198648, 198649, 198651, 198652, 198653, 198654, 198655, 198656, 198657, 198659, 198661, 198663, 198664, 198665, 198666, 198667, 198670, 198671, 198673, 198674, 198676, 198677, 198678, 198681, 198682, 198683, 198684, 198686, 198687, 198688, 198689, 198690, 198691, 198693, 198694, 198695, 198696, 198697, 198698, 198700, 198702, 198703, 198705, 198706, 198707, 198711, 198712, 198713, 198716, 198719, 198720, 198721, 198724, 198725, 198730, 198731, 198732, 198733, 198735, 198739, 198742, 198743, 198744, 198745, 198746, 198747, 198749, 198754, 198757, 198758, 198759, 198762, 198763, 198764, 198766, 198767, 198770, 198774, 198776, 198777, 198779, 198780, 198782, 198786, 198788, 198791, 198793, 198794, 198795, 198796, 198797, 198799, 198801, 198802, 198805, 198807, 198810, 198812, 198814, 198815, 198820, 198828, 198829, 198830, 198832, 198838, 198840, 198841, 198843, 198846, 198847, 198848, 198850, 198853, 198854, 198857, 198858, 198860, 198861, 198862, 198863, 198864, 198865, 198867, 198869, 198870, 198871, 198874, 198876, 198877, 198881, 198883, 198885, 198886, 198888, 198889, 198890, 198894, 198898, 198902, 198903, 198904, 198905, 198906, 198909, 198911, 198912, 198913, 198917, 198919, 198921, 198922, 198923, 198925, 198929, 198931, 198932, 198936, 198940, 198942, 198943, 198948, 198949, 198951, 198952, 198953, 198955, 198956, 198958, 198960, 198962, 198963, 198964, 198965, 198969, 198972, 198976, 198978, 198984, 198987, 198990, 198991, 198993, 198999, 199000, 199001, 199003, 199004, 199006, 199009, 199012, 199013, 199014, 199015, 199016, 199017, 199019, 199021, 199022, 199024, 199025, 199026, 199031, 199032, 199033, 199035, 199037, 199040, 199045, 199048, 199053, 199056, 199058, 199059, 199061, 199063, 199065, 199067, 199070, 199074, 199075, 199078, 199082, 199085, 199088, 199091, 199097, 199100, 199102, 199103, 199105, 199106, 199108, 199117, 199118, 199121, 199122, 199126, 199128, 199130, 199131, 199133, 199134, 199136, 199137, 199138, 199140, 199141, 199143, 199144, 199148, 199150, 199158, 199159, 199161, 199163, 199164, 199165, 199167, 199168, 199169, 199172, 199175, 199177, 199178, 199181, 199182, 199184, 199186, 199193, 199194, 199195, 199199, 199200, 199201, 199202, 199204, 199205, 199207, 199209, 199210, 199214, 199215, 199217, 199219, 199220, 199221, 199222, 199224, 199229, 199233, 199234, 199235, 199237, 199241, 199242, 199243, 199247, 199248, 199250, 199252, 199254, 199255, 199258, 199259, 199267, 199268, 199269, 199282, 199285, 199286, 199287, 199289, 199290, 199294, 199295, 199297, 199298, 199299, 199300, 199301, 199302, 199306, 199307, 199308, 199311, 199312, 199314, 199315, 199322, 199326, 199328, 199329, 199334, 199340, 199342, 199343, 199344, 199345, 199346, 199347, 199349, 199352, 199355, 199357, 199369, 199372, 199375, 199377, 199380, 199382, 199383, 199389, 199390, 199392, 199394, 199395, 199399, 199401, 199404, 199406, 199407, 199408, 199409, 199411, 199412, 199413, 199418, 199422, 199432, 199433, 199439, 199442, 199445, 199448, 199453, 199456, 199457, 199460, 199464, 199470, 199471, 199476, 199484, 199486, 199489, 199491, 199495, 199497, 199499, 199506, 199507, 199513, 199514, 199516, 199517, 199518, 199523, 199527, 199531, 199534, 199535, 199537, 199544, 199561, 199564, 199565, 199567, 199570, 199571, 199572, 199573, 199575, 199576, 199579, 199580, 199588, 199591, 199595, 199597, 199600, 199604, 199608, 199614, 199625, 199628, 199635, 199638, 199644, 199646, 199648, 199653, 199655, 199657, 199659, 199662, 199665, 199666, 199667, 199668, 199669, 199676, 199677, 199681, 199684, 199686, 199690, 199692, 199693, 199695, 199706, 199710, 199711, 199716, 199720, 199727, 199728, 199729, 199740, 199744, 199746, 199750, 199753, 199755, 199757, 199764, 199766, 199768, 199769, 199772, 199774, 199780, 199781, 199782, 199783, 199791, 199793, 199798, 199800, 199803, 199812, 199820, 199822, 199826, 199828, 199829, 199832, 199840, 199842, 199849, 199850, 199852, 199854, 199855, 199858, 199867, 199871, 199872, 199883, 199887, 199888, 199891, 199893, 199895, 199898, 199899, 199901, 199906, 199908, 199909, 199910, 199917, 199921, 199923, 199928, 199933, 199940, 199942, 199950, 199952, 199961, 199964, 199970, 199971, 199972, 199973, 199978, 199979, 199980, 199981, 199982, 199983, 199984, 199985, 199986, 199987, 199988, 199989, 199990, 199991, 199992, 199993, 199994, 199995, 199996, 199997, 199998, 199999, 200000, 200001, 200002, 200003, 200004, 200005, 200006, 200007, 200008, 200009, 200010, 200011, 200012, 200013, 200014, 200015, 200016, 200017, 200018, 200019, 200020, 200021, 200022, 200023, 200024, 200025, 200026, 200027, 200028, 200029, 200030, 200031, 200032, 200033, 200034, 200035, 200036, 200037, 200038, 200039, 200040, 200041, 200042, 200043, 200044, 200045, 200046, 200047, 200048, 200049, 200050, 200051, 200052, 200053, 200054, 200055, 200056, 200057] \ No newline at end of file diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n320s/__init__.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n320s/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9daec93de1b3c7c2cbefbc0076a6cf4cc3ea08 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n320s/__init__.py @@ -0,0 +1,66 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/__init__.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00f48018d7f45b482883a0603699122ea004b98b --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/__init__.py @@ -0,0 +1,58 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows.py new file mode 100644 index 0000000000000000000000000000000000000000..cd6068f702a78ffe6d70f414e098d4793fcb15ca --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows.py @@ -0,0 +1,31 @@ +"""n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with the +layer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers.""" +import triton +import triton.language as tl +from triton.language.extra import libdevice # noqa: F401 +from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401 + + +@triton.jit +def _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) + diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows_ctl.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows_ctl.py new file mode 100644 index 0000000000000000000000000000000000000000..b36e7bdcb843262ee0a8795d5e001a232ae73f8e --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n329/n329_rows_ctl.py @@ -0,0 +1,31 @@ +"""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 the +layer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers.""" +import triton +import triton.language as tl +from triton.language.extra import libdevice # noqa: F401 +from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401 + + +@triton.jit +def _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 + diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n351/__init__.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n351/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..174048d0855b92121e5da00d2d63798911c84c38 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n351/__init__.py @@ -0,0 +1,68 @@ +"""inkling_n351: the MoE NVFP4 token quantize through an exact n351 variant (prefill seat, tree n351; enters the n320 package only +on 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 logging +import 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) diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n355/__init__.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n355/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c8994d08341841d16b9701c420e0e587a3fe861f --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n355/__init__.py @@ -0,0 +1,69 @@ +"""inkling_n355: the MXFP8 swiglu-quant (layers 20-23) through an exact n355 variant (prefill seat, tree n355; enters a package +only 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 logging +import os + +STATE = {"installed": False, "routed": 0, "served": 0, "variant": None} +MIN_ROWS = 4096 # routed rows = tokens x top_k: 512 tokens, the n14 prefill threshold +VARIANTS = (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) diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n381/__init__.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n381/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1276081848fd3ce2e98df4b6f92d629d7c4d6458 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n381/__init__.py @@ -0,0 +1,98 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/CREDITS.knapcio-v2.9.3.md b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/CREDITS.knapcio-v2.9.3.md new file mode 100644 index 0000000000000000000000000000000000000000..c21f38fd1177e6925575871e8052fa35d99fe663 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/CREDITS.knapcio-v2.9.3.md @@ -0,0 +1,94 @@ +# 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.1 +recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bit +draft 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. diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/LICENSE.knapcio-v2.9.3 b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/LICENSE.knapcio-v2.9.3 new file mode 100644 index 0000000000000000000000000000000000000000..272aceba2ac697cd358e703c7e849e738e9b83c3 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/LICENSE.knapcio-v2.9.3 @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Zbigniew Majewski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.knapcio-v2.9.3 b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.knapcio-v2.9.3 new file mode 100644 index 0000000000000000000000000000000000000000..d1ae19376d8e6f56690206da57d8a30de168440e --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.knapcio-v2.9.3 @@ -0,0 +1,54 @@ +Inkling-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; the +prompts 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. diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.n389 b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.n389 new file mode 100644 index 0000000000000000000000000000000000000000..9f3d6d5834274c2852cab6637ccb03b09267d2cc --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/NOTICE.n389 @@ -0,0 +1,3 @@ +inkling_n389/n389_fold.py contains a verbatim copy of _sconv_post_kernel from inkling_prologue/_triton.py (knapcio's inkling-2-mini +v2.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-p +recipe overlay) with an added store branch (FOLD) by the inkling2-spark prefill seat. diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/__init__.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab8bb1bd4a1a462044410baebacb6c7e532a517 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/__init__.py @@ -0,0 +1,307 @@ +"""inkling_n389: the KV-cache store folded into INKLING_PROLOGUE's SWA K / V kernel (prefill seat, tree n389; enters a package only +under 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 the +backend's store for that visit is skipped (FlashAttentionBackend.forward_extend gets save_kv_cache=False). Everything else is the +served 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 whose +store 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 a +visit the prologue would fuse logs its reason ONCE per distinct reason ('[inkling_n389] stock path: ...', with the values behind it), and +the 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 contextvars +import os +import 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, 1024 +BREAKABLE_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 True diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/n389_fold.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/n389_fold.py new file mode 100644 index 0000000000000000000000000000000000000000..e2205c2b7fe50be2528116486c3e0772373731c5 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/inkling_n389/n389_fold.py @@ -0,0 +1,93 @@ +"""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; served +file 24d2e3d9 in the S3b-p recipe overlay) plus five trailing parameters. With FOLD=False (the default) it is the served +kernel: the CPU check requires its PTX to equal the served kernel's for POST 1 and 2 (debug sections stripped). With +FOLD=True only the final store changes: row i of the BF16 result goes to Dst[Loc[i], :] instead of Y[i, :], and rows whose +slot is SKIP (store_cache's reserved_skip_index, the CUDA-graph padding slot 0) are not written. That is the served +store_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 torch +import triton +import triton.language as tl + +from inkling_prologue import HEAD, SUM_ORDER +from inkling_prologue._triton import _row_sumsq, rsqrt_approx_f32 + + +@triton.jit +def _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) diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n351_quant.cuh b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n351_quant.cuh new file mode 100644 index 0000000000000000000000000000000000000000..f71f8f11e828a889533de670f85efd6061525288 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n351_quant.cuh @@ -0,0 +1,175 @@ +// 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 + +#include + +#include "routed_quant_sm120.cuh" +#include + +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 +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 +__device__ __forceinline__ void load_part(__nv_bfloat16 const* src, float (&v)[E]) { + if constexpr (E == 8) { + uint4 raw = *reinterpret_cast(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(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 +__global__ void __launch_bounds__(Cfg::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::kThreads, kSplit = Cfg::kSplit, E = Cfg::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(); + device::PDLTriggerSecondary(); + 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(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(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(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(v); + float amax = block_max_reduce(block_max, red[parity]); // its __syncthreads also publishes s_row / s_exp + uint32_t packed; + uint8_t scale; + quantize_part(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(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(std::max(1, std::min(tokens, g))); +} + +// = n14_quant::nvfp4_quantize_tokens (same checks, grid rule and PDL launch) with the variant kernel. +template +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::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(); + int32_t const experts = verify_offsets(offsets, device); + host::TensorMatcher({tokens, K}).with_dtype().with_device(device).ensure_alignment(kPart * 2).verify(x); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(src2dst); + host::TensorMatcher({rows, K / 2}).with_dtype().with_device(device).ensure_alignment(kPart / 2).verify(values); + host::TensorMatcher({scale_rows, K / 16}).with_dtype().with_device(device).verify(x_scales); + host::TensorMatcher({rows}).with_dtype().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::kThreads, device.unwrap()) + .enable_pdl(true)( + nvfp4_quantize_tokens_kernel, + static_cast<__nv_bfloat16 const*>(x.data_ptr()), + static_cast(src2dst.data_ptr()), + static_cast(values.data_ptr()), + static_cast(x_scales.data_ptr()), + static_cast(amax.data_ptr()), + static_cast(offsets.data_ptr()), + num_tokens, + static_cast(top_k), + experts); +} + +} // namespace sglang::n351_quant diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n355_quant.cuh b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n355_quant.cuh new file mode 100644 index 0000000000000000000000000000000000000000..3c517a75bd8c6620ad921aba426411f3c9eb9a12 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n355_quant.cuh @@ -0,0 +1,216 @@ +// 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 + +#include + +#include "routed_quant_sm120.cuh" +#include + +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 +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 +__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(); + 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(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(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 +__global__ void __launch_bounds__(Cfg::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; + static_assert(N % 128 == 0 && N / 16 <= 1024); + constexpr bool kHoist = V & 1, kPrefetch = V & 2; + device::PDLWaitPrimary(); + 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(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(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 +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; + auto rows = host::SymbolicSize{"routed rows"}; + auto device = host::SymbolicDevice{}; + device.set_options(); + int32_t const experts = verify_offsets(offsets, device); + host::TensorMatcher({rows, 2 * N}) // + .with_dtype() + .with_device(device) + .ensure_alignment(16) + .verify(x); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(gammas); + host::TensorMatcher({rows, N}) // + .with_dtype() + .with_device(device) + .ensure_alignment(16) + .verify(values); + host::TensorMatcher({N / 128, m_padded}).with_dtype().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::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(sm_count)) // the image's launch for the copy + : std::max(1, std::min(iters, C::kGridMul * static_cast(sm_count))); + auto* kernel = V == 0 ? mxfp8_swiglu_quantize_copy : mxfp8_swiglu_quantize_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(gammas.data_ptr()), + static_cast(values.data_ptr()), + static_cast(exponents.data_ptr()), + static_cast(offsets.data_ptr()), + experts, + static_cast(gate_cap), + static_cast(up_cap), + static_cast(m_padded)); +} + +} // namespace sglang::n355_quant diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n381c_band.cuh b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n381c_band.cuh new file mode 100644 index 0000000000000000000000000000000000000000..ab6b42d35169e84e705a098312e5ab14466f2c99 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/n381c_band.cuh @@ -0,0 +1,2062 @@ +// n381c (prefill seat, n381 implementation 3 + package rider unit): = work_moe/n360/kit/n360_band.cuh (n360-1's reviewed pass-variant source, +// b41a11aa) + n381-2's edits (825eaa0e, KEEP): tile_k = N381_TILE_K; with N381_PP 1 the F2 chunk GEMM is the stock CUTLASS ptr-array PING-PONG +// kernel (F2 runs the hook off), F1's gate_up_band compiled out; namespace sglang::n381c_band, class N381CKernel. Pass variants pv 0..4 as n360 +// (0 = the served chunk_pass). Same tile / K order / mma / epilogue and pass arithmetic: bitwise expected (n381-2 v2 and n360-1 p1 both exact). +// n360 F2b chunk-pass schedules: GENERATED by work_moe/n360/kit/gen_n360.py from n52_band.cuh e855abc8 (asserted edits + added pass kernels). +// SPDX-License-Identifier: Apache-2.0 +// n52 F1 (inkling2-spark moe seat, 2026-11-23): the SM120 MoE prefill visit's NVFP4 gate_up grouped GEMM with the swiglu + +// NVFP4 quantization done per 128-row band from L2 by the CTA that finishes the band's last tile ("band pass"). +// GENERATED by work_moe/n52/gen_n52.py from n52_head.cuh + CUTLASS's ptr-array cooperative kernel + n52_tail.cuh. +// +// - GEMM: FlashInfer 0.7.4's CutlassNVFP4GroupwiseScaledGroupGEMMSM120<128, 128, 256, SwapAB false> types (the served config +// above 3,072 tokens at K 2,304) with the stock BF16 TMA epilogue, so D = the served gate_up output bit for bit. +// - After each tile's epilogue store, the TMA-issuing warp waits for its bulk stores, fences the async proxy and the GPU, and +// thread 0 adds 1 to the band's counter (band = one 128-row M-tile of one expert, numbered like the SFA layout). The CTA +// whose add makes N / 128 (= 18) runs the band pass. +// - Band pass = the image's nvfp4_swiglu_quantize_routed arithmetic (its own device helpers from routed_quant.cuh, E = 4 lanes +// per 16-value block as the image's split for width 1,152) over the band's rows: D read with ld.global.cg (L2), per row +// scale and gamma loaded once, v = bf16(capped_swiglu(bf16(D * scale) pairs)), row amax, quantize_part, store_part, the +// expert's scale tail zeroed on its last band; then discard.global.L2 on the row's D lines (never written back). +// - mode (runtime): -1 stock (no hook), 0 signal only, 1 discard only, 2 pass + discard (the form), 3 pass without discard. +#include + +#include + +#include + +#include "routed_quant_sm120.cuh" + +#include "cute/tensor.hpp" +#include "cutlass/cutlass.h" +#include "cutlass/detail/sm100_blockscaled_layout.hpp" +#include "cutlass/epilogue/collective/collective_builder.hpp" +#include "cutlass/gemm/collective/collective_builder.hpp" +#include "cutlass/gemm/device/gemm_universal_adapter.h" +#include "cutlass/gemm/group_array_problem_shape.hpp" +#include "cutlass/gemm/kernel/gemm_universal.hpp" +#include "cutlass/util/packed_stride.hpp" + +#include + +namespace sglang::n381c_band { + +struct BandParams { + int mode = -1; // -1 stock, 0 signal, 1 discard, 2 pass + discard, 3 pass + int* counters = nullptr; // [bands], zero on entry; the last arriver resets its band to 0 + __nv_bfloat16 const* d = nullptr; // [rows, n] gate_up D (BF16), the GEMM's output + int n = 0; // gate_up width (2 x the swiglu width) + int const* offsets = nullptr; // [experts + 1] expert row offsets (m_indptr) + float const* acc_amax = nullptr; // [rows] amax of the quantized A rows + float const* w_amax = nullptr; // [experts] + float const* w_den = nullptr; // [1] + float const* gammas = nullptr; // [rows] + uint8_t* values = nullptr; // [rows, n / 4] NVFP4 of v + uint8_t* x_scales = nullptr; // SFA layout, 128-row padding per expert + float* amax_out = nullptr; // [rows] + float gate_cap = 0.f; + float up_cap = 0.f; +}; + +constexpr int kBandBarrier = 14; // named barrier id (CUTLASS reserves the low ids) +constexpr int kTileN = 128; + +// bar.red.or over the 256 consumer threads: returns 1 in every thread if any thread passed a nonzero pred. +__device__ __forceinline__ int bar_red_or(int pred) { + int r; + asm volatile( + "{ .reg .pred p, q; setp.ne.s32 p, %1, 0; bar.red.or.pred q, %2, %3, p; selp.s32 %0, 1, 0, q; }" + : "=r"(r) + : "r"(pred), "n"(kBandBarrier), "n"(256) + : "memory"); + return r; +} + +__device__ __forceinline__ void discard_l2(void const* p) { + asm volatile("discard.global.L2 [%0], 128;" ::"l"(p) : "memory"); +} + +#if defined(N52_LEAN) && N52_LEAN +// Build 2 ("lean"), for the checkpoint's caps (gate 4, up 25) only: n52_moe.py refuses lean for other caps. The image's +// capped_swiglu with its two IEEE divides replaced where provably equal on BF16 inputs (work_moe/n52/cpu/div25_proof.py, +// exact rationals over all 65,280 finite BF16 values: PASS): gate / 4 -> gate * 0.25; up / 25 -> q0 = up * RN(1/25), +// rem = fma(-q0, 25, up), fma(rem, RN(1/25), q0); a non-finite up takes the IEEE divide. gate and up are BF16-rounded before +// this call, as in the image kernel; sigmoid, tanh and the multiplies are the image's instructions in the image's order. +__device__ __forceinline__ float capped_swiglu_lean(float gate, float up, float gamma, float, float) { + float sigmoid; + asm("{ .reg .f32 t; mul.rn.f32 t, %1, 0fBFB8AA3B; " + "ex2.approx.ftz.f32 t, t; add.rn.f32 t, t, 0f3F800000; " + "rcp.approx.ftz.f32 %0, t; }" + : "=f"(sigmoid) + : "f"(gate)); + float t; + asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(__fmul_rn(gate, 0.25f))); + gate = __fmul_rn(4.0f, t); + float q = __fmul_rn(up, 0.04f); + q = __fmaf_rn(__fmaf_rn(-q, 25.0f, up), 0.04f, q); + if (!isfinite(up)) q = __fdiv_rn(up, 25.0f); + asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(q)); + up = __fmul_rn(25.0f, t); + return __fmul_rn(__fmul_rn(__fmul_rn(gate, sigmoid), up), gamma); +} +#define N52_SWIGLU capped_swiglu_lean +#else +#define N52_SWIGLU capped_swiglu +#endif + +// One row of expert e by one warp: lane = (block within the 8-block group) * 4 + part, as the image's E = 4 split, 9 groups of +// 8 blocks per 1,152-wide row. Used by the band pass (F1, one warp per row of the band) and the chunk pass (F2). +template +__device__ __forceinline__ void band_row(BandParams const& p, int e, int row, int lane, bool pass, bool discard) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8, LINES = N2 * 2 / 128; + static_assert(NH % 128 == 0 && N2 * 2 % 128 == 0, "whole 8-block groups and whole 128-byte lines per row"); + static_assert(split(NH) == 4, "the image quantizes width NH with E = 4 (4 lanes per block)"); + int const bl = lane / 4, part = lane % 4; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *p.w_den)); + float const wa = p.w_amax[e]; + { + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + if (pass) { + uint4 raw[ITERS]; + uint4 const* src = reinterpret_cast(drow); +#pragma unroll + for (int i = 0; i < ITERS; ++i) + raw[i] = __ldcg(src + (i * 8 + bl) * 4 + part); // block b = 8i + bl: D columns 32b + 8 part .. + 8 + float const scale = __fmul_rn(__fmul_rn(p.acc_amax[row], wa), rcp); + float const gamma = p.gammas[row]; + float v[ITERS][4]; + float bmax[ITERS]; + float m = 0.0f; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(&raw[i]); +#pragma unroll + for (int j = 0; j < 4; ++j) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j + 1]), scale))); + v[i][j] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, p.gate_cap, p.up_cap))); + } + bmax[i] = part_max<4>(v[i]); // max over the block's 16 values (xor 1, 2 within the lane quad) + m = fmaxf(m, bmax[i]); + } +#pragma unroll + for (int s = 4; s < 32; s *= 2) // the other 7 blocks of each group: all 72 block maxima of the row + m = fmaxf(m, __shfl_xor_sync(0xFFFFFFFF, m, s)); + float const amax = m; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + uint32_t packed; + uint8_t sbits; + quantize_part<4>(v[i], amax, bmax[i], packed, sbits); + store_part<4>(p.values, p.x_scales, p.offsets, e, row, i * 8 + bl, part, NH, packed, sbits); + } + if (lane == 0) p.amax_out[row] = amax; + } + if (discard) { + __syncwarp(); // every lane's loads of this row have returned (their values were consumed above) + for (int l = lane; l < LINES; l += 32) + discard_l2(drow + l * 64); + } + } +} + +// One band's rows, one warp per row (rows w, w + 8, ...). +template +__device__ __forceinline__ void band_rows(BandParams const& p, int e, int r0, int r1, int tid, bool pass, bool discard) { + int const warp = tid / 32, lane = tid % 32; + for (int row = r0 + warp; row < r1; row += 8) + band_row(p, e, row, lane, pass, discard); +} + +// zero_expert_tail for the expert's last 128-row tile (the image's bytes), by threads tid = 0 .. nthreads - 1. +template +__device__ __forceinline__ void band_tail(BandParams const& p, int e, int tid, int nthreads = 256) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, SCALE_K = (NH + 63) / 64 * 4, ATOMS = SCALE_K / 4; + int const count = p.offsets[e + 1] - p.offsets[e]; + int const used = count % 128; + if (used == 0) return; + uint8_t* tile = p.x_scales + scale_base(p.offsets, e, SCALE_K) + int64_t(count / 128) * ATOMS * 512; + for (int item = tid; item < ATOMS * 32; item += nthreads) { + int const lane = item % 32; + uint32_t* atom = reinterpret_cast(tile + (item / 32) * 512 + lane * 16); +#pragma unroll + for (int i = 0; i < 4; ++i) + if (lane + 32 * i >= used) atom[i] = 0; + } +} + +// Called by all 256 consumer threads after each tile's epilogue store (tid = mma_thread_idx; warp 0 issued the TMA stores). +template +__device__ __forceinline__ void n52_band_hook(BandParams const& p, int e, int mt, int n, int tid) { + if (tid < 32) { + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); // this tile's D stores are complete (not just read) + asm volatile("fence.proxy.async.global;" ::: "memory"); // async-proxy writes ordered before generic accesses + __syncwarp(); + } + int const base = p.offsets[0]; + int const band = (p.offsets[e] - base + e * 127) / 128 + mt; + int last = 0; + if (tid == 0) { + __threadfence(); + int const old = atomicAdd(p.counters + band, 1); + __threadfence(); + last = old == (n + kTileN - 1) / kTileN - 1; + } + if (!bar_red_or(last)) return; + __threadfence(); + if (p.mode >= 1) { + int const r0 = p.offsets[e] + mt * 128; + int const r1 = min(r0 + 128, p.offsets[e + 1]); + bool const pass = p.mode >= 2, discard = p.mode <= 2; + if (n == N2) { + band_rows(p, e, r0, r1, tid, pass, discard); + if (pass && r1 == p.offsets[e + 1]) band_tail(p, e, tid); + } + } + if (tid == 0) p.counters[band] = 0; +} + +} // namespace sglang::n381c_band + +namespace cutlass::gemm::kernel { + +// ---- N381CKernel: cutlass/gemm/kernel/sm90_gemm_array_tma_warpspecialized_cooperative.hpp (md5 3b39c38d712b5f27af49baea07e8c8b4) with the n52 edits ---- +using sglang::n381c_band::BandParams; +using sglang::n381c_band::n52_band_hook; + +template < + class ProblemShape_, + class CollectiveMainloop_, + class CollectiveEpilogue_, + class TileScheduler_ +> +class N381CKernel +{ + // Get the type of the scheduler response. + template + struct TileSchedulerResponseGetter { + using Type = typename TileScheduler::CLCResponse; + }; + + template + struct TileSchedulerResponseGetter> { + using Type = typename TileScheduler::SchedulerResponse; + }; + +public: + // + // Type Aliases + // + using ProblemShape = ProblemShape_; + static_assert(rank(typename ProblemShape::UnderlyingProblemShape{}) == 3 or rank(typename ProblemShape::UnderlyingProblemShape{}) == 4, + "ProblemShape{} should be or "); + + static_assert(cute::is_base_of_v); + + static constexpr bool IsGdcEnabled = false; + + // Mainloop derived types + using CollectiveMainloop = CollectiveMainloop_; + using TileShape = typename CollectiveMainloop::TileShape; + using TiledMma = typename CollectiveMainloop::TiledMma; + using ArchTag = typename CollectiveMainloop::ArchTag; + using ElementA = typename CollectiveMainloop::ElementA; + using StrideA = typename CollectiveMainloop::StrideA; + using InternalStrideA = typename CollectiveMainloop::InternalStrideA; + using ElementB = typename CollectiveMainloop::ElementB; + using InternalStrideB = typename CollectiveMainloop::InternalStrideB; + using StrideB = typename CollectiveMainloop::StrideB; + using DispatchPolicy = typename CollectiveMainloop::DispatchPolicy; + using Schedule = typename DispatchPolicy::Schedule; + using ElementAccumulator = typename CollectiveMainloop::ElementAccumulator; + using ClusterShape = typename DispatchPolicy::ClusterShape; + using MainloopArguments = typename CollectiveMainloop::Arguments; + using MainloopParams = typename CollectiveMainloop::Params; + + // Epilogue derived types + using CollectiveEpilogue = CollectiveEpilogue_; + using ElementC = typename CollectiveEpilogue::ElementC; + using StrideC = typename CollectiveEpilogue::StrideC; + using InternalStrideC = typename CollectiveEpilogue::InternalStrideC; + using ElementD = typename CollectiveEpilogue::ElementD; + using StrideD = typename CollectiveEpilogue::StrideD; + using InternalStrideD = typename CollectiveEpilogue::InternalStrideD; + using EpilogueArguments = typename CollectiveEpilogue::Arguments; + using EpilogueParams = typename CollectiveEpilogue::Params; + + static_assert(ArchTag::kMinComputeCapability >= 90); + + static constexpr bool IsGroupedGemmKernel = !cute::is_same_v; + static constexpr uint32_t MinTensorMapWorkspaceAlignment = 64; + + static_assert( + cute::is_void_v + or ( + IsGroupedGemmKernel + and cute::is_any_of_v + ), + "Ptr-Array Cooperative and Grouped Gemm Cooperative kernel only supports the default scheduler."); + + using SchedulerTag = cute::conditional_t< + cute::is_void_v, + cute::conditional_t< + IsGroupedGemmKernel, + GroupScheduler, // Special grouped gemm scheduler + void // Default scheduler for non-grouped kernels + >, + TileScheduler_ + >; + + using TileScheduler = typename detail::TileSchedulerSelector< + SchedulerTag, + ArchTag, + TileShape, + ClusterShape, + 8, // SchedulerPipelineStageCount -- Grouped GEMM scheduler will benefit from a larger number of stages. + cute::conditional_t, void, ProblemShape> // Use void for default scheduler. + >::Scheduler; + + using TileSchedulerArguments = typename TileScheduler::Arguments; + using TileSchedulerParams = typename TileScheduler::Params; + using TileSchedulerResponse = typename TileSchedulerResponseGetter::Type; + + static constexpr auto TileSchedulerStages = 8; + + static constexpr uint32_t NumLoadWarpGroups = 1; + static constexpr uint32_t NumMmaThreads = size(TiledMma{}); + static constexpr uint32_t NumMmaWarpGroups = NumMmaThreads / NumThreadsPerWarpGroup; + static constexpr uint32_t MaxThreadsPerBlock = NumMmaThreads + (NumLoadWarpGroups * NumThreadsPerWarpGroup); + static constexpr uint32_t MinBlocksPerMultiprocessor = 1; + static constexpr uint32_t NumProducerThreads = CollectiveMainloop::NumProducerThreadEvents; + static constexpr bool IsMainloopAuxiliaryLoadNeeded = detail::HasAuxiliaryLoad_v; + + /// Register requirement for Load and Math WGs + static constexpr int RegsPerThread = + 2 * size<0>(TileShape{}) * size<1>(TileShape{}) / NumMmaThreads * + sizeof(ElementAccumulator) / sizeof(uint32_t); + + // Detect if this is SM120 blockscaled kernel which hits low register pressure + // on smaller tiles + template + struct IsSm120BlockScaled : cute::false_type {}; + + template + struct IsSm120BlockScaled> + : cute::true_type {}; + + static constexpr bool IsLowRegisterPressure = IsSm120BlockScaled::value && (RegsPerThread <= 64); + + /// Register requirement for Load and Math WGs + static constexpr uint32_t LoadRegisterRequirement = 40; + static constexpr uint32_t MmaRegisterRequirement = 232; + + static constexpr bool IsSm120Family = cute::is_same_v; + + // 1 stage ordered sequence between mainloop and epilogue producer load threads + using LoadWarpOrderBarrier = cutlass::OrderedSequenceBarrier<1,2>; + + // Kernel level shared memory storage + struct SharedStorage { + struct TensorStorage : cute::aligned_struct<128, _1> { + using MainloopTensorStorage = typename CollectiveMainloop::TensorStorage; + using EpilogueTensorStorage = typename CollectiveEpilogue::TensorStorage; + + MainloopTensorStorage mainloop; + EpilogueTensorStorage epilogue; + } tensors; + + struct PipelineStorage : cute::aligned_struct<16, _1> { + using TileSchedulerPipelineStorage = typename TileScheduler::PipelineStorage; + using MainloopPipelineStorage = typename CollectiveMainloop::PipelineStorage; + using EpiLoadPipelineStorage = typename CollectiveEpilogue::PipelineStorage; + + alignas(16) TileSchedulerPipelineStorage scheduler; + alignas(16) MainloopPipelineStorage mainloop; + alignas(16) EpiLoadPipelineStorage epi_load; + alignas(16) typename LoadWarpOrderBarrier::SharedStorage load_order; + } pipelines; + + alignas(16) TileSchedulerResponse scheduler_response[TileSchedulerStages]; + + struct TensorMapStorage : cute::aligned_struct<128, _1> { + using MainloopTensorMapStorage = typename CollectiveMainloop::TensorMapStorage; + using EpilogueTensorMapStorage = typename CollectiveEpilogue::TensorMapStorage; + + alignas(128) MainloopTensorMapStorage mainloop; + alignas(128) EpilogueTensorMapStorage epilogue; + } tensormaps; + }; + + static constexpr int SharedStorageSize = sizeof(SharedStorage); + + // Device side arguments + struct Arguments { + GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopArguments mainloop{}; + EpilogueArguments epilogue{}; + KernelHardwareInfo hw_info{}; + TileSchedulerArguments scheduler{}; + BandParams band{}; // n52 + }; + + // Kernel entry point API + struct Params { + GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopParams mainloop{}; + EpilogueParams epilogue{}; + KernelHardwareInfo hw_info{}; + TileSchedulerParams scheduler{}; + void* workspace{nullptr}; + BandParams band{}; // n52 + }; + + // + // Methods + // + + // Convert to underlying arguments. In this case, a simple copy for the aliased type. + static + Params + to_underlying_arguments(Arguments const& args, void* workspace) { + CUTLASS_TRACE_HOST("to_underlying_arguments():"); + + ProblemShape problem_shapes = args.problem_shape; + + // Get SM count if needed, otherwise use user supplied SM count + int sm_count = args.hw_info.sm_count; + if (sm_count <= 0) { + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid SM count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the SM count."); + sm_count = KernelHardwareInfo::query_device_multiprocessor_count(args.hw_info.device_id); + } + CUTLASS_TRACE_HOST("to_underlying_arguments(): Setting persistent grid SM count to " << sm_count); + + // Get maximum number of clusters that could co-exist on the target device + int max_active_clusters = args.hw_info.max_active_clusters; + if (max_active_clusters <= 0) { + max_active_clusters = 0; + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid max cluster count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the max_active_clusters."); + } + else { + CUTLASS_TRACE_HOST("to_underlying_arguments(): Setting persistent grid cluster count to " << max_active_clusters); + } + + KernelHardwareInfo hw_info{args.hw_info.device_id, sm_count, max_active_clusters}; + + // Calculate workspace pointers + uint8_t* workspace_ptr = reinterpret_cast(workspace); + size_t workspace_offset = 0; + + void* epilogue_workspace = workspace_ptr + workspace_offset; + workspace_offset += CollectiveEpilogue::get_workspace_size(problem_shapes, args.epilogue, sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + void* mainloop_workspace = workspace_ptr + workspace_offset; + workspace_offset += CollectiveMainloop::get_workspace_size(problem_shapes, args.mainloop, sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + void* scheduler_workspace = workspace_ptr + workspace_offset; + workspace_offset += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + TileSchedulerParams scheduler; + if constexpr (IsGroupedGemmKernel) { + scheduler = TileScheduler::to_underlying_arguments( + problem_shapes, TileShape{}, ClusterShape{}, hw_info, args.scheduler, scheduler_workspace); + } + else { + scheduler = TileScheduler::to_underlying_arguments( + problem_shapes.get_host_problem_shape(), TileShape{}, ClusterShape{}, hw_info, args.scheduler, scheduler_workspace); + } + + return { + args.mode, + problem_shapes, + CollectiveMainloop::to_underlying_arguments(problem_shapes, args.mainloop, mainloop_workspace), + CollectiveEpilogue::to_underlying_arguments(problem_shapes, args.epilogue, epilogue_workspace), + hw_info, + scheduler, + workspace, + args.band // n52 + }; + } + + static bool + can_implement(Arguments const& args) { + bool implementable = true; + if constexpr (IsGroupedGemmKernel) { + // Group GEMM currently only supports rank-3 problem shapes + implementable &= (args.mode == GemmUniversalMode::kGrouped && rank(typename ProblemShape::UnderlyingProblemShape{}) == 3); + } + else { + implementable &= (args.mode == GemmUniversalMode::kArray && rank(typename ProblemShape::UnderlyingProblemShape{}) == 4); + } + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Arguments or Problem Shape don't meet the requirements for Ptr Array Gemm or Grouped Gemm.\n"); + return implementable; + } + implementable &= CollectiveMainloop::can_implement(args.problem_shape, args.mainloop); + implementable &= CollectiveEpilogue::can_implement(args.problem_shape, args.epilogue); + implementable &= TileScheduler::can_implement(args.scheduler); + return implementable; + } + + static size_t + get_workspace_size(Arguments const& args) { + size_t workspace_size = 0; + constexpr uint32_t NumEpilogueSubTiles = CollectiveEpilogue::get_store_pipe_increment(TileShape{}); + + // Get SM count if needed, otherwise use user supplied SM count + int sm_count = args.hw_info.sm_count; + if (sm_count <= 0) { + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid SM count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the SM count."); + sm_count = KernelHardwareInfo::query_device_multiprocessor_count(args.hw_info.device_id); + } + + workspace_size += CollectiveEpilogue::get_workspace_size(args.problem_shape, args.epilogue, sm_count); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + workspace_size += CollectiveMainloop::get_workspace_size(args.problem_shape, args.mainloop, sm_count); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + workspace_size += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + return workspace_size; + } + + static cutlass::Status + initialize_workspace(Arguments const& args, void* workspace = nullptr, cudaStream_t stream = nullptr, + CudaHostAdapter* cuda_adapter = nullptr) { + Status status = Status::kSuccess; + uint8_t* workspace_ptr = reinterpret_cast(workspace); + size_t workspace_offset = 0; + constexpr uint32_t NumEpilogueSubTiles = CollectiveEpilogue::get_store_pipe_increment(TileShape{}); + static constexpr uint32_t NumAccumulatorMtxs = 1; + + status = CollectiveEpilogue::initialize_workspace(args.problem_shape, args.epilogue, workspace_ptr + workspace_offset, stream, cuda_adapter); + workspace_offset += CollectiveEpilogue::get_workspace_size(args.problem_shape, args.epilogue, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + status = CollectiveMainloop::initialize_workspace(args.problem_shape, args.mainloop, workspace_ptr + workspace_offset, stream, cuda_adapter); + workspace_offset += CollectiveMainloop::get_workspace_size(args.problem_shape, args.mainloop, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + status = TileScheduler::template initialize_workspace( + args.scheduler, workspace_ptr + workspace_offset, stream, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles, NumAccumulatorMtxs, cuda_adapter); + workspace_offset += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + return status; + } + + // Computes the kernel launch grid shape based on runtime parameters + static dim3 + get_grid_shape(Params const& params) { + // Given device SM count, set grid size s.t. we do not launch more thread blocks than we can run concurrently + TileSchedulerArguments args{}; + args.raster_order = params.scheduler.raster_order_ == TileScheduler::RasterOrder::AlongN ? TileScheduler::RasterOrderOptions::AlongN : TileScheduler::RasterOrderOptions::AlongM; + dim3 grid_shape; + if constexpr (IsGroupedGemmKernel) { + grid_shape = TileScheduler::get_grid_shape(params.scheduler, params.problem_shape, TileShape{}, ClusterShape{}, params.hw_info, args); + } + else { + grid_shape = TileScheduler::get_grid_shape(params.scheduler, params.problem_shape.get_host_problem_shape(), TileShape{}, ClusterShape{}, params.hw_info, args); + } + return grid_shape; + } + + static dim3 + get_block_shape() { + return dim3(MaxThreadsPerBlock, 1, 1); + } + + CUTLASS_DEVICE + void + operator()(Params const& params, char* smem_buf) { + using namespace cute; + using X = Underscore; + +# if (defined(__CUDA_ARCH_FEAT_SM90_ALL) || defined(__CUDA_ARCH_FEAT_SM120_ALL) || defined(__CUDA_ARCH_FEAT_SM121_ALL) ||\ + CUDA_ARCH_CONDITIONAL_OR_FAMILY(1200) || CUDA_ARCH_CONDITIONAL_OR_FAMILY(1210)) +# define ENABLE_SM90_KERNEL_LEVEL 1 +# endif + +// Any Tensor Op MMA Atom in the ISA is arch conditional. +#if ! defined(ENABLE_SM90_KERNEL_LEVEL) + CUTE_INVALID_CONTROL_PATH("ERROR : Arch conditional MMA instruction used without targeting appropriate compute capability. Aborting.\n"); +#else + + // Preconditions + static_assert(size(TiledMma{}) == 256, "Cooperative kernel must have TiledMMA operating using 256 threads."); + static_assert(size<0>(TileShape{}) >= 128, + "Cooperative kernel requires Tile Size to be greater than or equal to 128 along the M-dimension."); + static_assert(NumMmaWarpGroups == 2, "Cooperative kernels currently only support NumMmaWarpGroups == 2"); + + if constexpr (cutlass::epilogue::collective::detail::sm90_is_ptr_array_tma_dispatch_policy_v) { + static_assert(NumMmaWarpGroups == CollectiveEpilogue::NumEpilogueWarpGroups, + "Tiled MmA does not match expected warp groups performing the epilogue"); + } + + static_assert(cute::rank(InternalStrideA{}) == 3, "StrideA must be rank-3: [M, K, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideB{}) == 3, "StrideB must be rank-3: [N, K, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideC{}) == 3, "StrideC must be rank-3: [M, N, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideD{}) == 3, "StrideD must be rank-3: [M, N, L]. If batch mode is not needed, set L stride to Int<0>."); + + /* In the Cooperative kernel, Consumer0 and Consumer1 collaborate on the same tile */ + enum class WarpGroupRole { + Producer = 0, + Consumer0 = 1, + Consumer1 = 2 + }; + enum class ProducerWarpRole { + Mainloop = 0, + MainloopAux = 1, + Epilogue = 2, + Scheduler = 3 + }; + + // Kernel level shared memory storage + SharedStorage& shared_storage = *reinterpret_cast(smem_buf); + + // In a warp specialized kernel, collectives expose data movement and compute operations separately + CollectiveMainloop collective_mainloop; + CollectiveEpilogue collective_epilogue(params.epilogue, shared_storage.tensors.epilogue); + + int thread_idx = int(threadIdx.x); + int lane_idx = canonical_lane_idx(); + int warp_idx = canonical_warp_idx_sync(); + int warp_idx_in_warp_group = warp_idx % NumWarpsPerWarpGroup; + int warp_group_thread_idx = thread_idx % NumThreadsPerWarpGroup; + int mma_thread_idx = thread_idx % size(TiledMma{}); + auto warp_group_idx = canonical_warp_group_idx(); + auto warp_group_role = WarpGroupRole(warp_group_idx); + auto producer_warp_role = ProducerWarpRole(warp_idx_in_warp_group); + int lane_predicate = cute::elect_one_sync(); + uint32_t block_rank_in_cluster = cute::block_rank_in_cluster(); + + // Note: Tma Descriptor Prefetch (from either const or param) is not applicable here + + // TileScheduler pipeline + using TileSchedulerPipeline = typename TileScheduler::Pipeline; + typename TileSchedulerPipeline::Params tile_scheduler_pipeline_params; + if constexpr (cute::is_same_v) { + if (warp_group_role == WarpGroupRole::Producer + && producer_warp_role == ProducerWarpRole::Scheduler) { + tile_scheduler_pipeline_params.role = TileSchedulerPipeline::ThreadCategory::Producer; + } + else { + tile_scheduler_pipeline_params.role = TileSchedulerPipeline::ThreadCategory::Consumer; + } + tile_scheduler_pipeline_params.consumer_arv_count = NumMmaThreads + + NumThreadsPerWarp * ( + 1 // Main DMA warp + + (collective_epilogue.is_producer_load_needed() ? 1 : 0) // Epilog DMA warp + + (IsMainloopAuxiliaryLoadNeeded ? 1 : 0) // Aux DMA warp + ); + tile_scheduler_pipeline_params.producer_arv_count = 1; + } + TileSchedulerPipeline tile_scheduler_pipeline(shared_storage.pipelines.scheduler, tile_scheduler_pipeline_params); + // Mainloop Load pipeline + using MainloopPipeline = typename CollectiveMainloop::MainloopPipeline; + typename MainloopPipeline::Params mainloop_pipeline_params; + if (warp_group_role == WarpGroupRole::Producer + && (producer_warp_role == ProducerWarpRole::Mainloop + || producer_warp_role == ProducerWarpRole::MainloopAux)) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Producer; + } + if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Consumer; + } + mainloop_pipeline_params.is_leader = warp_group_thread_idx == 0; + mainloop_pipeline_params.num_consumers = NumMmaThreads; + mainloop_pipeline_params.num_producers = NumProducerThreads; + mainloop_pipeline_params.transaction_bytes = params.mainloop.tma_transaction_bytes; + MainloopPipeline mainloop_pipeline(shared_storage.pipelines.mainloop, mainloop_pipeline_params, ClusterShape{}); + + // Epilogue Load pipeline + using EpiLoadPipeline = typename CollectiveEpilogue::LoadPipeline; + typename EpiLoadPipeline::Params epi_load_pipeline_params; + if (warp_group_role == WarpGroupRole::Producer && producer_warp_role == ProducerWarpRole::Epilogue) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Producer; + } + if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Consumer; + } + epi_load_pipeline_params.dst_blockid = cute::block_rank_in_cluster(); + epi_load_pipeline_params.producer_arv_count = NumThreadsPerWarp; + epi_load_pipeline_params.consumer_arv_count = size(TiledMma{}); + if constexpr (CollectiveEpilogue::RequiresTransactionBytes) { + epi_load_pipeline_params.transaction_bytes = params.epilogue.tma_transaction_bytes; + } + EpiLoadPipeline epi_load_pipeline(shared_storage.pipelines.epi_load, epi_load_pipeline_params); + + // Epilogue Store pipeline + using EpiStorePipeline = typename CollectiveEpilogue::StorePipeline; + typename EpiStorePipeline::Params epi_store_pipeline_params; + epi_store_pipeline_params.always_wait = true; + EpiStorePipeline epi_store_pipeline(epi_store_pipeline_params); + + typename LoadWarpOrderBarrier::Params params_load_order_barrier; + params_load_order_barrier.group_id = producer_warp_role == ProducerWarpRole::Mainloop ? 0 : 1; + params_load_order_barrier.group_size = NumThreadsPerWarp; + LoadWarpOrderBarrier load_order_barrier(shared_storage.pipelines.load_order, params_load_order_barrier); + + // Initialize starting pipeline states for the collectives + // Epilogue store pipe is producer-only (consumer is TMA unit, waits via scoreboarding) + typename TileSchedulerPipeline::PipelineState tile_scheduler_pipe_consumer_state; + typename CollectiveMainloop::PipelineState mainloop_pipe_consumer_state; + typename CollectiveEpilogue::LoadPipelineState epi_load_pipe_consumer_state; + + // For the DMA Load (producer) we start with an opposite phase + // i.e., we skip all waits since we know that the buffer is indeed empty + PipelineState tile_scheduler_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState mainloop_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState epi_load_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState epi_store_pipe_producer_state = cutlass::make_producer_start_state(); + + auto cluster_wait_fn = [] () { + // We need this to guarantee that the Pipeline init is visible + // To all producers and consumer thread blocks in the Cluster + if constexpr (size(ClusterShape{}) > 1) { + cute::cluster_arrive_relaxed(); + return [] () { cute::cluster_wait(); }; + } + else { + __syncthreads(); + return [] () {}; // do nothing + } + } (); + + // Get the appropriate blocks for this thread block -- potential for thread block locality + TiledMma tiled_mma; + const auto blk_shape = TileShape{}; // (BLK_M,BLK_N,BLK_K) + const auto c_tile_count = CollectiveEpilogue::get_load_pipe_increment(blk_shape); + const auto d_tile_count = CollectiveEpilogue::get_store_pipe_increment(blk_shape); + + // Wait for all thread blocks in the Cluster + cluster_wait_fn(); + + // Ensure memory ops in this kernel are not done prior to completion of dependent grids. + cutlass::arch::wait_on_dependent_grids(); + + auto scheduler = [&] () { + // Group scheduler requires a different constructor that takes a response ptr + if constexpr (cute::is_same_v) { + return TileScheduler{params.scheduler, shared_storage.scheduler_response}; + } + else { + return TileScheduler{params.scheduler}; + } + } (); + + auto work_tile_info = scheduler.initial_work_tile_info(ClusterShape{}); + + if (not work_tile_info.is_valid()) { + // When problem shapes are only on device, the grid launched may be larger than the total number of blocks across groups + return; + } + + // Optionally append 1s until problem shape is rank-4 in case it is only rank-3 (MNK) + auto problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + + // Prepare and partition the input tensors. Expects a tuple of tensors where: + // get<0>(load_inputs) is the tma tensor A after local tiling so that it has shape (BLK_M,BLK_K,m,k,l) + // get<1>(load_inputs) is the tma tensor B after local tiling so that it has shape (BLK_N,BLK_K,n,k,l) + auto load_inputs = collective_mainloop.load_init(problem_shape_MNKL, params.mainloop); + static_assert(cute::tuple_size_v >= 2, "Output of load_init must have at least two elements (A, B)"); + + // Extract out partitioned A and B. + Tensor gA_mkl = get<0>(load_inputs); + Tensor gB_nkl = get<1>(load_inputs); + + // Get pipeline stage increments from tensor shapes + auto k_tile_count = size<3>(gA_mkl); + + if (warp_group_role == WarpGroupRole::Producer) { + if constexpr (!IsLowRegisterPressure) { + cutlass::arch::warpgroup_reg_dealloc(); + } + + if (producer_warp_role == ProducerWarpRole::Scheduler) { + // GroupScheduler requires a producer warp to iterate over the group infos and push + // the work tile infos to the downstream pipelines. + if constexpr (cute::is_same_v) { + do { + auto [next_work_tile_info, increment_pipe] = scheduler.advance_to_next_work(tile_scheduler_pipeline, tile_scheduler_pipe_producer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_producer_state; + } + } while (work_tile_info.is_valid()); + tile_scheduler_pipeline.producer_tail(tile_scheduler_pipe_producer_state); + } + } + // Mainloop Producer Warp + else if (producer_warp_role == ProducerWarpRole::Mainloop) { + int32_t curr_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx; + int32_t const mock_l_coord = 0; + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + + // Fetch a copy of tensormaps for the CTA + auto input_tensormaps = collective_mainloop.tensormaps_init(params.mainloop, shared_storage.tensormaps.mainloop, sm_count, sm_idx); + + // Update tensormap for the initial batch for the CTA + collective_mainloop.tensormaps_perform_update( + shared_storage.tensormaps.mainloop, + params.mainloop, + input_tensormaps, + problem_shape_MNKL, + curr_batch + ); + // Ensure warp is converged before issuing tensormap fence release + __syncwarp(); + // Entire warp must do this (i.e. it's aligned) + collective_mainloop.tensormaps_cp_fence_release(shared_storage.tensormaps.mainloop, input_tensormaps); + + bool do_load_order_arrive = true; + bool did_batch_change = true; + do { + if (!TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + continue; + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, mock_l_coord); + + // Get the number of K tiles to compute for this work as well as the starting K tile offset of the work. + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + auto work_k_tile_start = TileScheduler::get_work_k_tile_start(work_tile_info); + auto k_tile_iter = cute::make_coord_iterator(idx2crd(work_k_tile_start, shape<3>(gA_mkl)), shape<3>(gA_mkl)); + + if (did_batch_change) { + load_inputs = collective_mainloop.tensors_perform_update(load_inputs, params.mainloop, problem_shape_MNKL, curr_batch); + collective_mainloop.tensormaps_fence_acquire(input_tensormaps); + } + + collective_mainloop.load( + params.mainloop, + mainloop_pipeline, + mainloop_pipe_producer_state, + load_inputs, + input_tensormaps, + blk_coord, + k_tile_iter, work_k_tile_count, + lane_idx, + block_rank_in_cluster, + shared_storage.tensors.mainloop + ); + // Pipeline state is only advanced if there are K tiles to compute + mainloop_pipe_producer_state.advance(work_k_tile_count); + + // Signal for the epilogue load warp to begin + if (do_load_order_arrive) { + load_order_barrier.arrive(); + do_load_order_arrive = false; + } + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + auto next_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx + did_batch_change = next_batch != curr_batch; + if (work_tile_info.is_valid() && did_batch_change) { + curr_batch = next_batch; + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(curr_batch), 1); + } + collective_mainloop.tensormaps_perform_update( + shared_storage.tensormaps.mainloop, + params.mainloop, + input_tensormaps, + problem_shape_MNKL, + curr_batch + ); + // Ensure warp is converged before issuing tensor replace + __syncwarp(); + // Entire warp must do this (i.e. it's aligned) + collective_mainloop.tensormaps_cp_fence_release(shared_storage.tensormaps.mainloop, input_tensormaps); + } + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Make sure all Consumer Warp Groups have been waited upon + collective_mainloop.load_tail(mainloop_pipeline, mainloop_pipe_producer_state); + } // Mainloop Producer Warp End + else if (producer_warp_role == ProducerWarpRole::MainloopAux) { + if constexpr (IsMainloopAuxiliaryLoadNeeded) { + int32_t curr_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx; + int32_t const mock_l_coord = 0; + + bool did_batch_change = true; + do { + if (!TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + continue; + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, mock_l_coord); + + // Get the number of K tiles to compute for this work as well as the starting K tile offset of the work. + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + auto work_k_tile_start = TileScheduler::get_work_k_tile_start(work_tile_info); + auto k_tile_iter = cute::make_coord_iterator(idx2crd(work_k_tile_start, shape<3>(gA_mkl)), shape<3>(gA_mkl)); + + if (did_batch_change) { + load_inputs = collective_mainloop.tensors_perform_update(load_inputs, params.mainloop, problem_shape_MNKL, curr_batch); + } + + collective_mainloop.load_auxiliary( + params.mainloop, + mainloop_pipeline, + mainloop_pipe_producer_state, + load_inputs, + blk_coord, + k_tile_iter, work_k_tile_count, + lane_idx, + block_rank_in_cluster, + shared_storage.tensors.mainloop + ); + + // Update starting pipeline state for the next tile + mainloop_pipe_producer_state.advance(work_k_tile_count); + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + auto next_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx + did_batch_change = next_batch != curr_batch; + if (work_tile_info.is_valid() && did_batch_change) { + curr_batch = next_batch; + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(curr_batch), 1); + } + } + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + } // End of auxiliary load needed check + } // Mainloop Auxiliary Load Producer Warp End + // Epilogue Producer Warp + else if (producer_warp_role == ProducerWarpRole::Epilogue && collective_epilogue.is_producer_load_needed()) { + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + + auto epi_load_tensormap = get<0>(collective_epilogue.load_init(params.epilogue, shared_storage.tensormaps.epilogue, sm_count, sm_idx)); + + bool did_batch_change = true; + constexpr bool IsEpiLoad = true; + + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_load_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + 0 + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, epi_load_tensormap, 0); + + load_order_barrier.wait(); + + do { + int32_t curr_batch = work_tile_info.L_idx; + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + + if (TileScheduler::compute_epilogue(work_tile_info, params.scheduler)) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto l_coord = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, l_coord); + + if (did_batch_change) { + collective_epilogue.template tensormaps_fence_acquire(epi_load_tensormap); + } + + epi_load_pipe_producer_state = collective_epilogue.load( + epi_load_pipeline, + epi_load_pipe_producer_state, + problem_shape_MNKL, + blk_shape, + blk_coord, + tiled_mma, + lane_idx, + shared_storage.tensors.epilogue, + epi_load_tensormap, + work_tile_info.reduction_subtile_idx() + ); + } + + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + did_batch_change = curr_batch != work_tile_info.L_idx; + + if (work_tile_info.is_valid() && did_batch_change) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + // tensormap update + { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_load_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + 0 + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, epi_load_tensormap, 0); + } + } + + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Make sure all Consumer Warp Groups have been waited upon + collective_epilogue.load_tail(epi_load_pipeline, epi_load_pipe_producer_state); + } // Epilogue Producer Warp End + } // Producer Warp Group End + + else if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + if constexpr (!IsLowRegisterPressure) { + cutlass::arch::warpgroup_reg_alloc(); + } + + // Index of warp group within consumer warp groups + int consumer_warp_group_idx = warp_group_role == WarpGroupRole::Consumer0 ? 0 : 1; + + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + // Do we potentially issue tail arrives for TMA stores, if epilogue load is waiting for it + bool do_store_tail = false; + // Get a copy of tensormaps + auto epi_store_tensormap = get<0>(collective_epilogue.store_init(params.epilogue, shared_storage.tensormaps.epilogue, sm_count, sm_idx, consumer_warp_group_idx)); + + bool did_batch_change = true; + constexpr bool IsEpiLoad = false; + + if (warp_idx_in_warp_group == 0) { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_store_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + consumer_warp_group_idx + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, + epi_store_tensormap, + consumer_warp_group_idx); + } + + do { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + int32_t curr_batch = work_tile_info.L_idx; + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto l_coord = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, l_coord); + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + + // Allocate the accumulators for the (M,N) blk_shape + // + // MSVC CTAD breaks if we say "Tensor" here, so we use "auto" instead. + auto accumulators = partition_fragment_C(tiled_mma, take<0,2>(blk_shape)); // (MMA,MMA_M,MMA_N) + + if (TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + + if constexpr (IsSm120Family) { + collective_mainloop.mma( + mainloop_pipeline, + mainloop_pipe_consumer_state, + accumulators, + work_k_tile_count, + mma_thread_idx, + shared_storage.tensors.mainloop, + params.mainloop, + blk_coord + ); + } + else { + collective_mainloop.mma( + mainloop_pipeline, + mainloop_pipe_consumer_state, + accumulators, + work_k_tile_count, + mma_thread_idx, + shared_storage.tensors.mainloop, + params.mainloop + ); + } + + // Make sure the math instructions are done and free buffers before entering the epilogue + collective_mainloop.mma_tail( + mainloop_pipeline, + mainloop_pipe_consumer_state, + work_k_tile_count + ); + + // Update starting mainloop pipeline state for the next tile + mainloop_pipe_consumer_state.advance(work_k_tile_count); + } + + // Perform reduction across splits, if needed + TileScheduler::fixup( + params.scheduler, work_tile_info, accumulators, NumMmaWarpGroups, consumer_warp_group_idx); + + if (did_batch_change) { + collective_epilogue.template tensormaps_fence_acquire(epi_store_tensormap); + } + + if (TileScheduler::compute_epilogue(work_tile_info, params.scheduler)) { + + // Epilogue and write to gD + auto [epi_load_pipe_consumer_state_next, epi_store_pipe_producer_state_next] = + collective_epilogue.store( + epi_load_pipeline, + epi_load_pipe_consumer_state, + epi_store_pipeline, + epi_store_pipe_producer_state, + problem_shape_MNKL, + blk_shape, + blk_coord, + accumulators, + tiled_mma, + mma_thread_idx, + shared_storage.tensors.epilogue, + epi_store_tensormap, + work_tile_info.reduction_subtile_idx() + ); + + epi_load_pipe_consumer_state = epi_load_pipe_consumer_state_next; + epi_store_pipe_producer_state = epi_store_pipe_producer_state_next; + do_store_tail = true; + // n52: this tile's D is stored; signal its band, the last arriver runs the band pass. +#ifndef N52_NO_HOOK + if (params.band.mode >= 0) { + n52_band_hook(params.band, int(work_tile_info.L_idx), int(work_tile_info.M_idx), + int(get<1>(problem_shape_MNKL)), mma_thread_idx); + } +#endif + } + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + + if (!next_work_tile_info.is_valid()) { + cutlass::arch::launch_dependent_grids(); + } + + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + + did_batch_change = curr_batch != work_tile_info.L_idx; + if (work_tile_info.is_valid() && did_batch_change) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + if (warp_idx_in_warp_group == 0) { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_store_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + consumer_warp_group_idx + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, + epi_store_tensormap, + consumer_warp_group_idx); + } + } + + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Cooperative only needs TMA to complete at the very end of the kernel + if (do_store_tail) { + collective_epilogue.store_tail( + epi_load_pipeline, + epi_load_pipe_consumer_state, + epi_store_pipeline, + epi_store_pipe_producer_state + ); + } + } // Consumer Warp Groups End +#endif + } +}; + + +} // namespace cutlass::gemm::kernel + +namespace sglang::n381c_band { + +using namespace cute; + +// ---- GEMM types: FlashInfer's builder arguments for <128, 128, 256, SwapAB false>, ElementD bf16, ElementC void. ---- +using ElementA = cutlass::float_e2m1_t; +using ElementB = cutlass::float_e2m1_t; +using ElementSF = cutlass::float_ue4m3_t; +using ElementD = cutlass::bfloat16_t; +constexpr int AlignmentA = 128 / cutlass::sizeof_bits::value; +constexpr int AlignmentB = 128 / cutlass::sizeof_bits::value; +constexpr int AlignmentD = 128 / cutlass::sizeof_bits::value; +using ElementAccumulator = float; +using ElementCompute = float; +using ElementAMainloop = cutlass::nv_float4_t; +using ElementBMainloop = cutlass::nv_float4_t; +using ProblemShape = cutlass::gemm::GroupProblemShape>; +using LayoutA = cutlass::layout::RowMajor; +using LayoutB = cutlass::layout::ColumnMajor; +using LayoutD = cutlass::layout::RowMajor; +using ClusterShape = Shape<_1, _1, _1>; +#ifndef N381_PP +#define N381_PP 0 +#endif +#ifndef N381_TILE_K +#define N381_TILE_K 256 +#endif +static_assert(N381_TILE_K == 128 || N381_TILE_K == 256, "N381_TILE_K"); +using ThreadBlockShape = Shape<_128, _128, cute::Int>; // n381: tile_k 128 (4 stages) or 256 (served) +using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< + cutlass::arch::Sm120, + cutlass::arch::OpClassBlockScaledTensorOp, + ThreadBlockShape, + ClusterShape, + cutlass::epilogue::collective::EpilogueTileAuto, + ElementAccumulator, + ElementCompute, + void, + LayoutD*, + AlignmentD, + ElementD, + LayoutD*, + AlignmentD, +#if N381_PP + cutlass::epilogue::PtrArrayTmaWarpSpecializedPingpong>::CollectiveOp; +#else + cutlass::epilogue::collective::EpilogueScheduleAuto>::CollectiveOp; +#endif +using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< + cutlass::arch::Sm120, + cutlass::arch::OpClassBlockScaledTensorOp, + ElementAMainloop, + LayoutA*, + AlignmentA, + ElementBMainloop, + LayoutB*, + AlignmentB, + ElementAccumulator, + ThreadBlockShape, + ClusterShape, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, +#if N381_PP + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedPingpong>::CollectiveOp; +static_assert( + cute::is_base_of_v< + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedPingpong, + typename CollectiveMainloop::DispatchPolicy::Schedule>, + "n381 PP: the ptr-array ping-pong kernel"); +using GemmKernel = cutlass::gemm::kernel::GemmUniversal; +#else + cutlass::gemm::collective::KernelScheduleAuto>::CollectiveOp; +static_assert( + cute::is_base_of_v< + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedCooperative, + typename CollectiveMainloop::DispatchPolicy::Schedule>, + "the served config builds the ptr-array cooperative kernel; N381CKernel is a copy of that kernel"); +using GemmKernel = cutlass::gemm::kernel::N381CKernel; +#endif +using Gemm = cutlass::gemm::device::GemmUniversalAdapter; +static_assert(GemmKernel::SharedStorageSize <= 101376, "dynamic smem must fit sm_120's 99 KB per block"); +using StrideA = typename Gemm::GemmKernel::InternalStrideA; +using StrideB = typename Gemm::GemmKernel::InternalStrideB; +using StrideD = typename Gemm::GemmKernel::InternalStrideD; +using ScaleConfig = typename Gemm::GemmKernel::CollectiveMainloop::Sm1xxBlkScaledConfig; +using LayoutSFA = typename Gemm::GemmKernel::CollectiveMainloop::InternalLayoutSFA; +using LayoutSFB = typename Gemm::GemmKernel::CollectiveMainloop::InternalLayoutSFB; +constexpr int ScaleGranularity = Gemm::GemmKernel::CollectiveMainloop::TiledMma::SFVecSize; +static_assert(ScaleGranularity == 16); +using UnderlyingProblemShape = typename ProblemShape::UnderlyingProblemShape; + +template +__host__ __device__ __forceinline__ T* inc_ptr(T* ptr, size_t offset) { + constexpr int adjustment = (cutlass::sizeof_bits::value < 8) ? (8 / cutlass::sizeof_bits::value) : 1; + return ptr + offset / adjustment; +} + +// FlashInfer's compute_sm120_cutlass_nvfp4_group_gemm_args (SwapAB false), line for line. +__global__ void group_args( + ElementA* A, + ElementB* B, + ElementSF* SFA, + ElementSF* SFB, + ElementD* D, + int const* m_indptr, + int n, + int k, + int num_groups, + UnderlyingProblemShape* problem_sizes, + ElementA const** A_ptr, + ElementB const** B_ptr, + ElementSF const** SFA_ptr, + ElementSF const** SFB_ptr, + ElementD** D_ptr, + StrideA* stride_A, + StrideB* stride_B, + StrideD* stride_D, + LayoutSFA* layout_SFA, + LayoutSFB* layout_SFB) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= num_groups) return; + constexpr size_t alignment_swizzled_mn = 128; + constexpr size_t alignment_swizzled_k = static_cast(ScaleGranularity) * 4; + size_t sf_n = (static_cast(n) + alignment_swizzled_mn - 1) / alignment_swizzled_mn * alignment_swizzled_mn; + size_t swizzled_k = (static_cast(k) + alignment_swizzled_k - 1) / alignment_swizzled_k * alignment_swizzled_k; + size_t sf_k = swizzled_k / static_cast(ScaleGranularity); + asm volatile("griddepcontrol.wait;"); + asm volatile("griddepcontrol.launch_dependents;"); + int m_offset = m_indptr[i]; + int m_offset_next = m_indptr[i + 1]; + size_t m = static_cast(m_offset_next) - static_cast(m_offset); + size_t sf_m_offset = (static_cast(m_offset) + static_cast(i) * (alignment_swizzled_mn - 1)) / + alignment_swizzled_mn * alignment_swizzled_mn; + problem_sizes[i] = UnderlyingProblemShape(int(m), n, k); + stride_A[i] = cutlass::make_cute_packed_stride(StrideA{}, {int(m), k, 1}); + stride_B[i] = cutlass::make_cute_packed_stride(StrideB{}, {n, k, 1}); + stride_D[i] = cutlass::make_cute_packed_stride(StrideD{}, {int(m), n, 1}); + A_ptr[i] = inc_ptr(A, static_cast(m_offset) * static_cast(k)); + B_ptr[i] = inc_ptr(B, static_cast(i) * static_cast(n) * static_cast(k)); + D_ptr[i] = D + static_cast(m_offset) * static_cast(n); + layout_SFA[i] = ScaleConfig::tile_atom_to_shape_SFA( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFA_ptr[i] = inc_ptr(SFA, sf_m_offset * sf_k); + layout_SFB[i] = ScaleConfig::tile_atom_to_shape_SFB( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFB_ptr[i] = inc_ptr(SFB, static_cast(i) * sf_n * sf_k); +} + +inline size_t align16(size_t x) { + return (x + 15) / 16 * 16; +} + +#if !N381_PP +// values [rows, k/2] u8, weight [E, n, k/2] u8, scales (SFA, u8), weight_scales [E, n, k/16] u8 view, m_indptr [E+1], +// acc_amax / gammas [rows] f32, w_amax [E] f32, w_den [1] f32, d [rows, n] bf16 scratch (the GEMM's D), +// out_values [rows, n/4] u8, out_scales (SFA of width n/2, u8), out_amax [rows] f32, counters [>= bands] i32 (zero), +// int_ws / float_ws u8 workspaces. mode: -1 stock, 0 signal, 1 discard, 2 pass + discard, 3 pass. raster: 0 AlongM, 1 AlongN. +void gate_up_band( + tvm::ffi::TensorView values, + tvm::ffi::TensorView weight, + tvm::ffi::TensorView scales, + tvm::ffi::TensorView weight_scales, + tvm::ffi::TensorView m_indptr, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_den, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView d, + tvm::ffi::TensorView out_values, + tvm::ffi::TensorView out_scales, + tvm::ffi::TensorView out_amax, + tvm::ffi::TensorView counters, + tvm::ffi::TensorView int_ws, + tvm::ffi::TensorView float_ws, + double gate_cap, + double up_cap, + int64_t mode, + int64_t raster, + int64_t sm_count) { + auto device = host::SymbolicDevice{}; + device.set_options(); + auto rows = host::SymbolicSize{"rows"}; + auto experts = host::SymbolicSize{"experts"}; + auto n = host::SymbolicSize{"n"}; + auto kp = host::SymbolicSize{"k/2"}; + host::TensorMatcher({rows, kp}).with_dtype().with_device(device).verify(values); + host::TensorMatcher({experts, n, kp}).with_dtype().with_device(device).verify(weight); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(out_amax); + host::TensorMatcher({experts}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_den); + host::TensorMatcher({rows, n}).with_dtype().with_device(device).verify(d); + int const num_groups = static_cast(experts.unwrap()); + int const N = static_cast(n.unwrap()), K = static_cast(kp.unwrap()) * 2; + int64_t const R = rows.unwrap(); + CHECK_HOST(N == 2304) << "n52 band pass is compiled for gate_up width 2304, got " << N; + CHECK_HOST(m_indptr.size(0) == num_groups + 1) << "m_indptr must hold experts + 1 offsets"; + CHECK_HOST(out_values.size(0) == R && out_values.size(1) == N / 4) << "out_values must be [rows, n / 4]"; + int64_t const bands = (R + 127 * int64_t(num_groups)) / 128 + 1; + CHECK_HOST(counters.numel() >= bands) << "counters need " << bands << " entries"; + CHECK_HOST(out_scales.numel() >= (R + 127 * int64_t(num_groups) + 127) / 128 * 128 * (N / 2 / 16)) + << "out_scales too small for the SFA layout"; + CHECK_HOST(mode >= -1 && mode <= 3) << "mode must be -1..3"; + cudaStream_t stream = host::LaunchKernel::resolve_device(device.unwrap()); + + uint8_t* ib = static_cast(int_ws.data_ptr()); + size_t off = 0; + auto take = [&](size_t bytes) { + void* p = ib + off; + off += align16(bytes); + return p; + }; + auto problem_sizes = static_cast(take(num_groups * sizeof(UnderlyingProblemShape))); + auto A_ptr = static_cast(take(num_groups * sizeof(void*))); + auto B_ptr = static_cast(take(num_groups * sizeof(void*))); + auto D_ptr = static_cast(take(num_groups * sizeof(void*))); + auto SFA_ptr = static_cast(take(num_groups * sizeof(void*))); + auto SFB_ptr = static_cast(take(num_groups * sizeof(void*))); + auto stride_A = static_cast(take(num_groups * sizeof(StrideA))); + auto stride_B = static_cast(take(num_groups * sizeof(StrideB))); + auto stride_D = static_cast(take(num_groups * sizeof(StrideD))); + auto layout_SFA = static_cast(take(num_groups * sizeof(LayoutSFA))); + auto layout_SFB = static_cast(take(num_groups * sizeof(LayoutSFB))); + CHECK_HOST(off <= size_t(int_ws.numel())) << "int workspace too small: need " << off; + + cudaLaunchConfig_t config{}; + config.gridDim = (num_groups + 1023) / 1024; + config.blockDim = std::min(num_groups, 1024); + config.dynamicSmemBytes = 0; + config.stream = stream; + cudaLaunchAttribute attrs[1]; + attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[0].val.programmaticStreamSerializationAllowed = true; + config.numAttrs = 1; + config.attrs = attrs; + cudaError_t const st = cudaLaunchKernelEx( + &config, + group_args, + static_cast(values.data_ptr()), + static_cast(weight.data_ptr()), + static_cast(scales.data_ptr()), + static_cast(weight_scales.data_ptr()), + static_cast(d.data_ptr()), + static_cast(m_indptr.data_ptr()), + N, + K, + num_groups, + problem_sizes, + A_ptr, + B_ptr, + SFA_ptr, + SFB_ptr, + D_ptr, + stride_A, + stride_B, + stride_D, + layout_SFA, + layout_SFB); + CHECK_HOST(st == cudaSuccess) << "n52 group args launch: " << cudaGetErrorString(st); + + cutlass::KernelHardwareInfo hw_info; + hw_info.device_id = device.unwrap().device_id; + hw_info.sm_count = static_cast(sm_count); + typename Gemm::Arguments arguments{ + cutlass::gemm::GemmUniversalMode::kGrouped, + {num_groups, problem_sizes, /*problem_sizes_host=*/nullptr}, + {A_ptr, stride_A, B_ptr, stride_B, SFA_ptr, layout_SFA, SFB_ptr, layout_SFB}, + {{}, nullptr, nullptr, D_ptr, stride_D}, + hw_info}; + auto& fusion_args = arguments.epilogue.thread; + fusion_args.alpha = 1.0f; // FlashInfer with alpha == nullptr (the served call passes none) + fusion_args.beta = 0; + fusion_args.alpha_ptr = nullptr; + fusion_args.dAlpha = {cute::_0{}, cute::_0{}, 0}; + using RasterOptions = decltype(arguments.scheduler.raster_order); + arguments.scheduler.raster_order = raster ? RasterOptions::AlongN : RasterOptions::AlongM; + BandParams& b = arguments.band; + b.mode = static_cast(mode); + b.counters = static_cast(counters.data_ptr()); + b.d = static_cast<__nv_bfloat16 const*>(d.data_ptr()); + b.n = N; + b.offsets = static_cast(m_indptr.data_ptr()); + b.acc_amax = static_cast(acc_amax.data_ptr()); + b.w_amax = static_cast(w_amax.data_ptr()); + b.w_den = static_cast(w_den.data_ptr()); + b.gammas = static_cast(gammas.data_ptr()); + b.values = static_cast(out_values.data_ptr()); + b.x_scales = static_cast(out_scales.data_ptr()); + b.amax_out = static_cast(out_amax.data_ptr()); + b.gate_cap = static_cast(gate_cap); + b.up_cap = static_cast(up_cap); + + Gemm gemm; + size_t const ws = Gemm::get_workspace_size(arguments); + CHECK_HOST(ws <= size_t(float_ws.numel())) << "float workspace too small: need " << ws; + CHECK_HOST(gemm.can_implement(arguments) == cutlass::Status::kSuccess) << "n52 gemm cannot implement"; + CHECK_HOST(gemm.initialize(arguments, float_ws.data_ptr()) == cutlass::Status::kSuccess) << "n52 gemm initialize"; + CHECK_HOST(gemm.run(stream, /*cuda_adapter=*/nullptr, /*launch_with_pdl=*/true) == cutlass::Status::kSuccess) + << "n52 gemm run"; +} + +#endif // !N381_PP (F1 gate_up_band needs the in-kernel hook kernel) + +// --------------------------------------------------------------------------------------------------------------------------- +// F2 (chunked L2 pass): the same GEMM type, hook off (band mode -1), launched once per chunk of TB padded 128-row bands (the +// band numbering of F1 = the SFA layout's), each launch covering every expert's M-tiles that fall in the chunk; after each GEMM +// launch a pass kernel runs the band arithmetic (band_row) over the chunk's rows reading D from L2 and discarding it. Kernel +// boundaries order D's writes before the pass (no counters, no fences). Exact for the same reason as F1: each tile is the +// served tile (same rows, same K order); a sub-problem starts on a 128-row tile of its expert, so its A / D / SFA pointers are +// the expert's plus whole tiles (the SFA layout is row-block outermost: 128 x sf_k bytes per block). + +__device__ __forceinline__ int band0_of(int const* offsets, int e) { + return (offsets[e] - offsets[0] + e * 127) / 128; +} + +// Expert of padded band b: the largest e with band0_of(e) <= b (bands between experts' last tile and the next start are unused). +__device__ __forceinline__ int expert_of_band(int const* offsets, int experts, int b) { + int lo = 0, hi = experts; + while (hi - lo > 1) { + int const mid = (lo + hi) / 2; + if (band0_of(offsets, mid) <= b) + lo = mid; + else + hi = mid; + } + return lo; +} + +// One thread per (chunk, group): the arrays of chunk c start at c * num_groups. +__global__ void chunk_args( + ElementA* A, + ElementB* B, + ElementSF* SFA, + ElementSF* SFB, + ElementD* D, + int const* m_indptr, + int n, + int k, + int num_groups, + int nchunks, + int tb, + UnderlyingProblemShape* problem_sizes, + ElementA const** A_ptr, + ElementB const** B_ptr, + ElementSF const** SFA_ptr, + ElementSF const** SFB_ptr, + ElementD** D_ptr, + StrideA* stride_A, + StrideB* stride_B, + StrideD* stride_D, + LayoutSFA* layout_SFA, + LayoutSFB* layout_SFB) { + int const t = blockIdx.x * blockDim.x + threadIdx.x; + asm volatile("griddepcontrol.wait;"); + asm volatile("griddepcontrol.launch_dependents;"); + if (t >= num_groups * nchunks) return; + int const c = t / num_groups, i = t % num_groups; + constexpr size_t alignment_swizzled_mn = 128; + constexpr size_t alignment_swizzled_k = static_cast(ScaleGranularity) * 4; + size_t sf_n = (static_cast(n) + alignment_swizzled_mn - 1) / alignment_swizzled_mn * alignment_swizzled_mn; + size_t swizzled_k = (static_cast(k) + alignment_swizzled_k - 1) / alignment_swizzled_k * alignment_swizzled_k; + size_t sf_k = swizzled_k / static_cast(ScaleGranularity); + int const m_offset = m_indptr[i], cnt = m_indptr[i + 1] - m_indptr[i]; + int const b0 = band0_of(m_indptr, i), nt = (cnt + 127) / 128; + int const lo = max(b0, c * tb), hi = min(b0 + nt, (c + 1) * tb); // this expert's bands inside chunk c + int const mt0 = hi > lo ? lo - b0 : 0; + int const m = hi > lo ? min(cnt, (hi - b0) * 128) - mt0 * 128 : 0; + int const row0 = m_offset + mt0 * 128; + size_t sf_m_offset = (static_cast(m_offset) + static_cast(i) * (alignment_swizzled_mn - 1)) / + alignment_swizzled_mn * alignment_swizzled_mn + static_cast(mt0) * 128; + problem_sizes[t] = UnderlyingProblemShape(m, n, k); + stride_A[t] = cutlass::make_cute_packed_stride(StrideA{}, {m, k, 1}); + stride_B[t] = cutlass::make_cute_packed_stride(StrideB{}, {n, k, 1}); + stride_D[t] = cutlass::make_cute_packed_stride(StrideD{}, {m, n, 1}); + A_ptr[t] = inc_ptr(A, static_cast(row0) * static_cast(k)); + B_ptr[t] = inc_ptr(B, static_cast(i) * static_cast(n) * static_cast(k)); + D_ptr[t] = D + static_cast(row0) * static_cast(n); + layout_SFA[t] = ScaleConfig::tile_atom_to_shape_SFA( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFA_ptr[t] = inc_ptr(SFA, sf_m_offset * sf_k); + layout_SFB[t] = ScaleConfig::tile_atom_to_shape_SFB( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFB_ptr[t] = inc_ptr(SFB, static_cast(i) * sf_n * sf_k); +} + +// Chunk pass: CTA j of chunk c covers padded rows [(c * tb) * 128 + 16 j, + 16), two per warp. Grid tb * 8, 256 threads. +template +__global__ void __launch_bounds__(256) chunk_pass(BandParams p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // the chunk's GEMM has completed (its D is in memory) + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; +#pragma unroll 1 + for (int h = 0; h < 2; ++h) { + int const pr = (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp; + int const band = pr / 128; + int const e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + if (local < cnt) { + int const row = p.offsets[e] + local; + band_row(p, e, row, lane, pass, discard); + if (pass && local == cnt - 1) band_tail(p, e, lane, 32); + } + } +} + + +// ---- n360 pass schedules (ADDED; the served chunk_pass above is unchanged) ---- +// band_row split in two: load (the served loads, in the served order) and finish (everything after the loads, verbatim). +template +struct RowRegs { + uint4 raw[N2 / 2 / 16 / 8]; +}; + +template +__device__ __forceinline__ void band_row_load(BandParams const& p, int row, int lane, RowRegs& r) { + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8; + int const bl = lane / 4, part = lane % 4; + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + uint4 const* src = reinterpret_cast(drow); +#pragma unroll + for (int i = 0; i < ITERS; ++i) + r.raw[i] = __ldcg(src + (i * 8 + bl) * 4 + part); +} + +template +__device__ __forceinline__ void band_row_finish(BandParams const& p, int e, int row, int lane, RowRegs const& r, bool discard) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8, LINES = N2 * 2 / 128; + int const bl = lane / 4, part = lane % 4; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *p.w_den)); + float const wa = p.w_amax[e]; + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + float const scale = __fmul_rn(__fmul_rn(p.acc_amax[row], wa), rcp); + float const gamma = p.gammas[row]; + float v[ITERS][4]; + float bmax[ITERS]; + float m = 0.0f; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(&r.raw[i]); +#pragma unroll + for (int j = 0; j < 4; ++j) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j + 1]), scale))); + v[i][j] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, p.gate_cap, p.up_cap))); + } + bmax[i] = part_max<4>(v[i]); + m = fmaxf(m, bmax[i]); + } +#pragma unroll + for (int s = 4; s < 32; s *= 2) + m = fmaxf(m, __shfl_xor_sync(0xFFFFFFFF, m, s)); + float const amax = m; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + uint32_t packed; + uint8_t sbits; + quantize_part<4>(v[i], amax, bmax[i], packed, sbits); + store_part<4>(p.values, p.x_scales, p.offsets, e, row, i * 8 + bl, part, NH, packed, sbits); + } + if (lane == 0) p.amax_out[row] = amax; + if (discard) { + __syncwarp(); + for (int l = lane; l < LINES; l += 32) + discard_l2(drow + l * 64); + } +} + +// Map padded row pr of chunk c to (expert, row); returns false when pr is past its expert's rows (as served). +__device__ __forceinline__ bool pass_row(BandParams const& p, int experts, int pr, int& e, int& row, bool& last) { + int const band = pr / 128; + e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + row = p.offsets[e] + local; + last = local == cnt - 1; + return local < cnt; +} + +// PV 1 / 4: one row per warp, CTA j of chunk c covers padded rows (c * tb) * 128 + 8 j + warp. Grid tb * 16. +template +__device__ __forceinline__ void pass_one_row(BandParams const& p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; + int e, row; + bool last; + if (pass_row(p, experts, (c * tb) * 128 + blockIdx.x * 8 + warp, e, row, last)) { + band_row(p, e, row, lane, pass, discard); + if (pass && last) band_tail(p, e, lane, 32); + } +} + +// PV 2: the served row mapping (rows h * 8 + warp of the CTA's 16), the second row's loads before the first row's arithmetic. +template +__device__ __forceinline__ void pass_two_rows(BandParams const& p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const discard = p.mode <= 2; + int e[2], row[2]; + bool last[2], ok[2]; + RowRegs r[2]; +#pragma unroll + for (int h = 0; h < 2; ++h) { + ok[h] = pass_row(p, experts, (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp, e[h], row[h], last[h]); + if (ok[h]) band_row_load(p, row[h], lane, r[h]); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + if (ok[h]) { + band_row_finish(p, e[h], row[h], lane, r[h], discard); + if (last[h]) band_tail(p, e[h], lane, 32); + } + } +} + +template +__global__ void __launch_bounds__(256) chunk_pass_1(BandParams p, int experts, int c, int tb) { pass_one_row(p, experts, c, tb); } +template +__global__ void __launch_bounds__(256) chunk_pass_2(BandParams p, int experts, int c, int tb) { pass_two_rows(p, experts, c, tb); } +template +__global__ void __launch_bounds__(256, 4) chunk_pass_4(BandParams p, int experts, int c, int tb) { pass_one_row(p, experts, c, tb); } +// PV 3: the served chunk_pass body, verbatim, under __launch_bounds__(256, 4). +template +__global__ void __launch_bounds__(256, 4) chunk_pass_3(BandParams p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // the chunk's GEMM has completed (its D is in memory) + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; +#pragma unroll 1 + for (int h = 0; h < 2; ++h) { + int const pr = (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp; + int const band = pr / 128; + int const e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + if (local < cnt) { + int const row = p.offsets[e] + local; + band_row(p, e, row, lane, pass, discard); + if (pass && local == cnt - 1) band_tail(p, e, lane, 32); + } + } +} + +// F2 host entry: as gate_up_band (mode 2 pass + discard, 3 pass), with tb bands per chunk. int_ws must hold the args of every +// chunk (~300 B x experts x chunks). +void gate_up_chunks( + tvm::ffi::TensorView values, + tvm::ffi::TensorView weight, + tvm::ffi::TensorView scales, + tvm::ffi::TensorView weight_scales, + tvm::ffi::TensorView m_indptr, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_den, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView d, + tvm::ffi::TensorView out_values, + tvm::ffi::TensorView out_scales, + tvm::ffi::TensorView out_amax, + tvm::ffi::TensorView int_ws, + tvm::ffi::TensorView float_ws, + double gate_cap, + double up_cap, + int64_t mode, + int64_t raster, + int64_t tb, + int64_t sm_count, + int64_t pv) { + auto device = host::SymbolicDevice{}; + device.set_options(); + auto rows = host::SymbolicSize{"rows"}; + auto experts = host::SymbolicSize{"experts"}; + auto n = host::SymbolicSize{"n"}; + auto kp = host::SymbolicSize{"k/2"}; + host::TensorMatcher({rows, kp}).with_dtype().with_device(device).verify(values); + host::TensorMatcher({experts, n, kp}).with_dtype().with_device(device).verify(weight); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(out_amax); + host::TensorMatcher({experts}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_den); + host::TensorMatcher({rows, n}).with_dtype().with_device(device).verify(d); + int const G = static_cast(experts.unwrap()); + int const N = static_cast(n.unwrap()), K = static_cast(kp.unwrap()) * 2; + int64_t const R = rows.unwrap(); + CHECK_HOST(N == 2304) << "n52 chunk pass is compiled for gate_up width 2304, got " << N; + CHECK_HOST(m_indptr.size(0) == G + 1) << "m_indptr must hold experts + 1 offsets"; + CHECK_HOST(out_values.size(0) == R && out_values.size(1) == N / 4) << "out_values must be [rows, n / 4]"; + CHECK_HOST(out_scales.numel() >= (R + 127 * int64_t(G) + 127) / 128 * 128 * (N / 2 / 16)) << "out_scales too small"; + CHECK_HOST(mode == 2 || mode == 3) << "chunk mode must be 2 (pass + discard) or 3 (pass)"; + CHECK_HOST(tb >= 1 && tb <= 4096) << "tb (bands per chunk) out of range"; + CHECK_HOST(pv >= 0 && pv <= 4) << "n360 pass variant 0..4"; + int const bands = static_cast((R + 127 * int64_t(G)) / 128 + 1); + int const nchunks = static_cast((bands + tb - 1) / tb); + cudaStream_t stream = host::LaunchKernel::resolve_device(device.unwrap()); + + uint8_t* ib = static_cast(int_ws.data_ptr()); + size_t off = 0; + size_t const NC = size_t(nchunks) * G; + auto take = [&](size_t bytes) { + void* q = ib + off; + off += align16(bytes); + return q; + }; + auto problem_sizes = static_cast(take(NC * sizeof(UnderlyingProblemShape))); + auto A_ptr = static_cast(take(NC * sizeof(void*))); + auto B_ptr = static_cast(take(NC * sizeof(void*))); + auto D_ptr = static_cast(take(NC * sizeof(void*))); + auto SFA_ptr = static_cast(take(NC * sizeof(void*))); + auto SFB_ptr = static_cast(take(NC * sizeof(void*))); + auto stride_A = static_cast(take(NC * sizeof(StrideA))); + auto stride_B = static_cast(take(NC * sizeof(StrideB))); + auto stride_D = static_cast(take(NC * sizeof(StrideD))); + auto layout_SFA = static_cast(take(NC * sizeof(LayoutSFA))); + auto layout_SFB = static_cast(take(NC * sizeof(LayoutSFB))); + CHECK_HOST(off <= size_t(int_ws.numel())) << "int workspace too small: need " << off; + + cudaLaunchAttribute attrs[1]; + attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[0].val.programmaticStreamSerializationAllowed = true; + cudaLaunchConfig_t config{}; + config.gridDim = static_cast((NC + 255) / 256); + config.blockDim = 256; + config.stream = stream; + config.numAttrs = 1; + config.attrs = attrs; + cudaError_t st = cudaLaunchKernelEx( + &config, chunk_args, static_cast(values.data_ptr()), static_cast(weight.data_ptr()), + static_cast(scales.data_ptr()), static_cast(weight_scales.data_ptr()), + static_cast(d.data_ptr()), static_cast(m_indptr.data_ptr()), N, K, G, nchunks, static_cast(tb), + problem_sizes, A_ptr, B_ptr, SFA_ptr, SFB_ptr, D_ptr, stride_A, stride_B, stride_D, layout_SFA, layout_SFB); + CHECK_HOST(st == cudaSuccess) << "n52 chunk args launch: " << cudaGetErrorString(st); + + BandParams b; + b.mode = static_cast(mode); + b.counters = nullptr; + b.d = static_cast<__nv_bfloat16 const*>(d.data_ptr()); + b.n = N; + b.offsets = static_cast(m_indptr.data_ptr()); + b.acc_amax = static_cast(acc_amax.data_ptr()); + b.w_amax = static_cast(w_amax.data_ptr()); + b.w_den = static_cast(w_den.data_ptr()); + b.gammas = static_cast(gammas.data_ptr()); + b.values = static_cast(out_values.data_ptr()); + b.x_scales = static_cast(out_scales.data_ptr()); + b.amax_out = static_cast(out_amax.data_ptr()); + b.gate_cap = static_cast(gate_cap); + b.up_cap = static_cast(up_cap); + + cutlass::KernelHardwareInfo hw_info; + hw_info.device_id = device.unwrap().device_id; + hw_info.sm_count = static_cast(sm_count); + for (int c = 0; c < nchunks; ++c) { + size_t const o = size_t(c) * G; + typename Gemm::Arguments arguments{ + cutlass::gemm::GemmUniversalMode::kGrouped, + {G, problem_sizes + o, /*problem_sizes_host=*/nullptr}, + {A_ptr + o, stride_A + o, B_ptr + o, stride_B + o, SFA_ptr + o, layout_SFA + o, SFB_ptr + o, layout_SFB + o}, + {{}, nullptr, nullptr, D_ptr + o, stride_D + o}, + hw_info}; + auto& fusion_args = arguments.epilogue.thread; + fusion_args.alpha = 1.0f; + fusion_args.beta = 0; + fusion_args.alpha_ptr = nullptr; + fusion_args.dAlpha = {cute::_0{}, cute::_0{}, 0}; + using RasterOptions = decltype(arguments.scheduler.raster_order); + arguments.scheduler.raster_order = raster ? RasterOptions::AlongN : RasterOptions::AlongM; +#if !N381_PP + arguments.band.mode = -1; // F2: no in-kernel hook +#endif + Gemm gemm; + size_t const ws = Gemm::get_workspace_size(arguments); + CHECK_HOST(ws <= size_t(float_ws.numel())) << "float workspace too small: need " << ws; + CHECK_HOST(gemm.can_implement(arguments) == cutlass::Status::kSuccess) << "n52 chunk gemm cannot implement"; + CHECK_HOST(gemm.initialize(arguments, float_ws.data_ptr()) == cutlass::Status::kSuccess) << "n52 chunk gemm initialize"; + CHECK_HOST(gemm.run(stream, /*cuda_adapter=*/nullptr, /*launch_with_pdl=*/true) == cutlass::Status::kSuccess) + << "n52 chunk gemm run"; + cudaLaunchConfig_t pc{}; + pc.gridDim = static_cast(tb * ((pv == 1 || pv == 4) ? 16 : 8)); // n360: one row per warp doubles the CTAs + pc.blockDim = 256; + pc.stream = stream; + pc.numAttrs = 1; + pc.attrs = attrs; + auto pass_kernel = pv == 1 ? chunk_pass_1<2304> : pv == 2 ? chunk_pass_2<2304> : pv == 3 ? chunk_pass_3<2304> + : pv == 4 ? chunk_pass_4<2304> : chunk_pass<2304>; // n360 pass schedules; 0 = the served kernel + st = cudaLaunchKernelEx(&pc, pass_kernel, b, G, c, static_cast(tb)); + CHECK_HOST(st == cudaSuccess) << "n52 chunk pass launch: " << cudaGetErrorString(st); + } +} + +// --------------------------------------------------------------------------------------------------------------------------- +// L5 (lean standalone swiglu-quant) and C5 (its null twin): the image's nvfp4_swiglu_quantize_routed (routed_quant_sm120.cuh) +// line for line, except capped_swiglu -> N52_SWIGLU: the lean unit (N52_LEAN 1) runs the proven divide rewrite (L5), the plain +// unit runs the image's capped_swiglu (C5 = a copy of the image kernel: its timing is the copy null). Same launch (grid_size, +// split_threads, PDL wait + trigger), same device helpers, so outputs are the image kernel's bit for bit. +using sglang::inkling2_routed_quant_sm120::zero_expert_tail; + +template +__global__ void __launch_bounds__(sglang::inkling2_routed_quant::split_threads(N)) swiglu_quantize_l5( + __nv_bfloat16 const* __restrict__ acc, + float const* __restrict__ acc_amax, + float const* __restrict__ w_amax, + float const* __restrict__ w_denominator, + float const* __restrict__ gammas, + uint8_t* values, + uint8_t* x_scales, + float* amax_out, + int32_t const* __restrict__ offsets, + int32_t experts, + float gate_cap, + float up_cap) { + using namespace sglang::inkling2_routed_quant; + constexpr int kThreads = split_threads(N), kSplit = split(N), E = 16 / kSplit; + static_assert(N % 64 == 0 && kSplit > 1 && E % 4 == 0); + __shared__ int32_t s_offsets[kMaxExperts + 1]; + __shared__ float red[2][kThreads / 32]; + device::PDLWaitPrimary(); + device::PDLTriggerSecondary(); + load_offsets(offsets, experts, s_offsets); + int32_t const block = threadIdx.x / kSplit, part = threadIdx.x % kSplit; + bool const active = block < N / 16; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *w_denominator)); + int32_t parity = 0; + for (int32_t row = s_offsets[0] + blockIdx.x; row < s_offsets[experts]; row += gridDim.x, parity ^= 1) { + int32_t const expert = row_expert(s_offsets, experts, row); + float v[E]; +#pragma unroll + for (int i = 0; i < E; ++i) + v[i] = 0.0f; + if (active) { + uint4 raw[E / 4]; + uint4 const* src = reinterpret_cast(acc + int64_t(row) * 2 * N + block * 32 + part * 2 * E); +#pragma unroll + for (int i = 0; i < E / 4; ++i) + raw[i] = src[i]; + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(raw); + float scale = __fmul_rn(__fmul_rn(acc_amax[row], w_amax[expert]), rcp); + float gamma = gammas[row]; +#pragma unroll + for (int i = 0; i < E; ++i) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * i]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * i + 1]), scale))); + v[i] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, gate_cap, up_cap))); + } + } + float block_max = part_max(v); + float amax = block_max_reduce(block_max, red[parity]); + uint32_t packed; + uint8_t scale_bits; + quantize_part(v, amax, block_max, packed, scale_bits); + if (active) { + if (threadIdx.x == 0) amax_out[row] = amax; + store_part(values, x_scales, s_offsets, expert, row, block, part, N, packed, scale_bits); + } + if (row == s_offsets[expert + 1] - 1) zero_expert_tail(s_offsets, expert, x_scales, (N + 63) / 64 * 4); + } +} + +// = the image's nvfp4_swiglu_quantize host wrapper for N = 1152 (same checks, grid and PDL launch), kernel swiglu_quantize_l5. +void swiglu_quant_l5( + tvm::ffi::TensorView acc, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_denominator, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView values, + tvm::ffi::TensorView x_scales, + tvm::ffi::TensorView amax, + tvm::ffi::TensorView offsets, + double gate_cap, + double up_cap, + int64_t sm_count) { + using namespace sglang::inkling2_routed_quant; + constexpr int N = 1152; + constexpr int64_t kPart = 16 / split(N); + auto rows = host::SymbolicSize{"routed rows"}; + auto scale_rows = host::SymbolicSize{"scale rows"}; + auto device = host::SymbolicDevice{}; + device.set_options(); + int32_t const experts = sglang::inkling2_routed_quant_sm120::verify_offsets(offsets, device); + host::TensorMatcher({rows, 2 * N}).with_dtype().with_device(device).ensure_alignment(16).verify(acc); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(amax); + host::TensorMatcher({int64_t{experts}}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_denominator); + host::TensorMatcher({rows, N / 2}).with_dtype().with_device(device).ensure_alignment(kPart / 2).verify(values); + host::TensorMatcher({scale_rows, N / 16}).with_dtype().with_device(device).verify(x_scales); + int32_t const num_rows = sglang::inkling2_routed_quant_sm120::verify_rows(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_size(num_rows, static_cast(sm_count)), split_threads(N), device.unwrap()) + .enable_pdl(true)( + swiglu_quantize_l5, + static_cast<__nv_bfloat16 const*>(acc.data_ptr()), + static_cast(acc_amax.data_ptr()), + static_cast(w_amax.data_ptr()), + static_cast(w_denominator.data_ptr()), + static_cast(gammas.data_ptr()), + static_cast(values.data_ptr()), + static_cast(x_scales.data_ptr()), + static_cast(amax.data_ptr()), + static_cast(offsets.data_ptr()), + experts, + static_cast(gate_cap), + static_cast(up_cap)); +} + +} // namespace sglang::n381c_band diff --git a/recipe/stack/cands/n362j-e35d7419/overlay_n362j/sitecustomize.py b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/sitecustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..232499d0e9f6123b342b398e9df4caf93f1a62d7 --- /dev/null +++ b/recipe/stack/cands/n362j-e35d7419/overlay_n362j/sitecustomize.py @@ -0,0 +1,116 @@ +"""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 os +import 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) diff --git a/recipe/stack/cands/n419ab-6d18f8eb/df-r1b2.json b/recipe/stack/cands/n419ab-6d18f8eb/df-r1b2.json new file mode 100644 index 0000000000000000000000000000000000000000..1a2945db923d228f97b1f29e90da865fbd9673fe --- /dev/null +++ b/recipe/stack/cands/n419ab-6d18f8eb/df-r1b2.json @@ -0,0 +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"}} \ No newline at end of file diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n320s/__init__.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n320s/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9daec93de1b3c7c2cbefbc0076a6cf4cc3ea08 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n320s/__init__.py @@ -0,0 +1,66 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/__init__.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00f48018d7f45b482883a0603699122ea004b98b --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/__init__.py @@ -0,0 +1,58 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows.py new file mode 100644 index 0000000000000000000000000000000000000000..cd6068f702a78ffe6d70f414e098d4793fcb15ca --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows.py @@ -0,0 +1,31 @@ +"""n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with the +layer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers.""" +import triton +import triton.language as tl +from triton.language.extra import libdevice # noqa: F401 +from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401 + + +@triton.jit +def _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) + diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows_ctl.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows_ctl.py new file mode 100644 index 0000000000000000000000000000000000000000..b36e7bdcb843262ee0a8795d5e001a232ae73f8e --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n329/n329_rows_ctl.py @@ -0,0 +1,31 @@ +"""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 the +layer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers.""" +import triton +import triton.language as tl +from triton.language.extra import libdevice # noqa: F401 +from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401 + + +@triton.jit +def _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 + diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n351/__init__.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n351/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..174048d0855b92121e5da00d2d63798911c84c38 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n351/__init__.py @@ -0,0 +1,68 @@ +"""inkling_n351: the MoE NVFP4 token quantize through an exact n351 variant (prefill seat, tree n351; enters the n320 package only +on 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 logging +import 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) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n355/__init__.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n355/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c8994d08341841d16b9701c420e0e587a3fe861f --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n355/__init__.py @@ -0,0 +1,69 @@ +"""inkling_n355: the MXFP8 swiglu-quant (layers 20-23) through an exact n355 variant (prefill seat, tree n355; enters a package +only 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 logging +import os + +STATE = {"installed": False, "routed": 0, "served": 0, "variant": None} +MIN_ROWS = 4096 # routed rows = tokens x top_k: 512 tokens, the n14 prefill threshold +VARIANTS = (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) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n381/__init__.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n381/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1276081848fd3ce2e98df4b6f92d629d7c4d6458 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n381/__init__.py @@ -0,0 +1,98 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/CREDITS.knapcio-v2.9.3.md b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/CREDITS.knapcio-v2.9.3.md new file mode 100644 index 0000000000000000000000000000000000000000..c21f38fd1177e6925575871e8052fa35d99fe663 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/CREDITS.knapcio-v2.9.3.md @@ -0,0 +1,94 @@ +# 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.1 +recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bit +draft 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. diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/LICENSE.knapcio-v2.9.3 b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/LICENSE.knapcio-v2.9.3 new file mode 100644 index 0000000000000000000000000000000000000000..272aceba2ac697cd358e703c7e849e738e9b83c3 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/LICENSE.knapcio-v2.9.3 @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Zbigniew Majewski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.knapcio-v2.9.3 b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.knapcio-v2.9.3 new file mode 100644 index 0000000000000000000000000000000000000000..d1ae19376d8e6f56690206da57d8a30de168440e --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.knapcio-v2.9.3 @@ -0,0 +1,54 @@ +Inkling-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; the +prompts 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. diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.n389 b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.n389 new file mode 100644 index 0000000000000000000000000000000000000000..9f3d6d5834274c2852cab6637ccb03b09267d2cc --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/NOTICE.n389 @@ -0,0 +1,3 @@ +inkling_n389/n389_fold.py contains a verbatim copy of _sconv_post_kernel from inkling_prologue/_triton.py (knapcio's inkling-2-mini +v2.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-p +recipe overlay) with an added store branch (FOLD) by the inkling2-spark prefill seat. diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/__init__.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab8bb1bd4a1a462044410baebacb6c7e532a517 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/__init__.py @@ -0,0 +1,307 @@ +"""inkling_n389: the KV-cache store folded into INKLING_PROLOGUE's SWA K / V kernel (prefill seat, tree n389; enters a package only +under 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 the +backend's store for that visit is skipped (FlashAttentionBackend.forward_extend gets save_kv_cache=False). Everything else is the +served 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 whose +store 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 a +visit the prologue would fuse logs its reason ONCE per distinct reason ('[inkling_n389] stock path: ...', with the values behind it), and +the 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 contextvars +import os +import 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, 1024 +BREAKABLE_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 True diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/n389_fold.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/n389_fold.py new file mode 100644 index 0000000000000000000000000000000000000000..e2205c2b7fe50be2528116486c3e0772373731c5 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n389/n389_fold.py @@ -0,0 +1,93 @@ +"""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; served +file 24d2e3d9 in the S3b-p recipe overlay) plus five trailing parameters. With FOLD=False (the default) it is the served +kernel: the CPU check requires its PTX to equal the served kernel's for POST 1 and 2 (debug sections stripped). With +FOLD=True only the final store changes: row i of the BF16 result goes to Dst[Loc[i], :] instead of Y[i, :], and rows whose +slot is SKIP (store_cache's reserved_skip_index, the CUDA-graph padding slot 0) are not written. That is the served +store_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 torch +import triton +import triton.language as tl + +from inkling_prologue import HEAD, SUM_ORDER +from inkling_prologue._triton import _row_sumsq, rsqrt_approx_f32 + + +@triton.jit +def _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) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/CREDITS.n395.md b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/CREDITS.n395.md new file mode 100644 index 0000000000000000000000000000000000000000..e5c41cc357c88ee911d08a82d72bf5b5b48b530e --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/CREDITS.n395.md @@ -0,0 +1,6 @@ +# 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). diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/LICENSE.sglang b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/LICENSE.sglang new file mode 100644 index 0000000000000000000000000000000000000000..9c422689c8f5c317c7c65153b1209349ec57007e --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/LICENSE.sglang @@ -0,0 +1,201 @@ + 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. diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/NOTICE.n395 b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/NOTICE.n395 new file mode 100644 index 0000000000000000000000000000000000000000..6e1b5f53e6bdf43b885d53a3096b8a22a80cc471 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/NOTICE.n395 @@ -0,0 +1,7 @@ +inkling_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 image +lmsysorg/sglang@sha256:efac853b46811ccb760545b7b29e7119bdf907537ccf6e863fac3011fe8b98de; Apache License 2.0, see LICENSE.sglang copied +unchanged from /sgl-workspace/sglang/LICENSE in that image), modified by the inkling2-spark prefill seat (2026-11-28): one-token CTAs for +the K clip, the output tile placed at KV-cache rows loc[token] with slot 0 skipped, and the constexpr-dead branches of these two calls +removed. Every modified line is marked 'n395' in the file. The rest of inkling_n395 is the prefill seat's own code, in the form of +inkling_n389 (work_prefill2/n389/rider3). diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/__init__.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ad25363e4c7361616521287d2d0b7386cf9f78 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/__init__.py @@ -0,0 +1,482 @@ +"""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.py +Inkling2Attention._prologue, digest-pinned): the stock dynamic k_sconv / v_sconv, tau, the stock q clip, then K and V go through +n395_fold.k_clip_fold / v_norm_fold (the n395-1 measured kernels: the image's QKL2ClipFwd / RMSNormFwd bodies with one-token CTAs and the +output tile at the cache rows) straight into the owner route's K / V layer buffers at out_cache_loc (slot 0 skipped = store_cache's +reserved_skip_index), then the stock rel clip; the backend's store for that visit is skipped (FlashAttentionBackend.forward_extend gets +save_kv_cache=False). Where the rows go is taken from the served objects (rider3's zero-row probe of the backend's own store with +memory_pool._set_kv_buffer_impl swapped for a recorder), and the probe's ids must BE forward_batch.out_cache_loc (the owner route; the +pointer-stable buffer under prefill CUDA graphs). SWA visits, decode / verify / MIXED / draft extends, < 2048 rows, a learnable K scale, a +weighted / missing value norm, breakable graphs, CP, MLA, MXFP8 KV, skip-KV, image masks, an unrecognised write route, int32 ids: the +chain 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 on +those outputs and the store runs (the conv never runs twice). Fail-closed: a folded visit whose store was not skipped, or whose attention +runs 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 the +visit'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 contextvars +import os +import 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, 2048 +BREAKABLE_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 True diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n395_fold.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n395_fold.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f1e866d0d215a75a95c0ef8bbb15e1a907c3c1 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n395_fold.py @@ -0,0 +1,354 @@ +# 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 clip +gets 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 producer +input (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 math +from functools import cache, partial + +import cutlass +import torch +from cutlass import Float32, const_expr, cute, range_constexpr + +from sglang.kernels.ops.attention.flash_attn.cute.utils import predicate_k +from 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 QKL2ClipFwd +from 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) + + +@cache +def 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") + + +@cache +def 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)) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n438_fold.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n438_fold.py new file mode 100644 index 0000000000000000000000000000000000000000..dee35e1aa4b68a0451b0c99b382a8c88e7b2453c --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n395/n438_fold.py @@ -0,0 +1,396 @@ +# 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 are +never written or re-read. Subclasses of n395_fold.py's QKL2ClipFold / RMSNormFold (c1064c8a, the n395-1 measured file); the kernel bodies +are 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 math +from functools import cache, partial + +import cutlass +import torch +from cutlass import Float32, const_expr, cute, range_constexpr +from cutlass._mlir.dialects import llvm +from cutlass.cutlass_dsl import T, dsl_user_op + +from sglang.kernels.ops.attention.flash_attn.cute.utils import predicate_k +from 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 = 4 +SCALE = (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_op +def fma_rn(a, b, c, *, loc=None, ip=None): + return _asm("fma.rn.f32 $0, $1, $2, $3;", a, b, c) + + +@dsl_user_op +def mul_rn(a, b, *, loc=None, ip=None): + return _asm("mul.rn.f32 $0, $1, $2;", a, b) + + +@dsl_user_op +def 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 visit +def _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 + + +@cache +def 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") + + +@cache +def 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)) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n437/__init__.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n437/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4910b4dea7e85e289037793aaa5f02f4551ad8 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/inkling_n437/__init__.py @@ -0,0 +1,96 @@ +"""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-side +launch 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 16 +too. 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_add_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 f412af06 +note): the first routed launch of EACH (GV, HAS_ADD) class logs one line ('n437: routed gv_add ...'), so a check boot can show BM 16 +reach 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 bool +WARPS, BM_NEW = 8, 16 +KW = {"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) diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n351_quant.cuh b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n351_quant.cuh new file mode 100644 index 0000000000000000000000000000000000000000..f71f8f11e828a889533de670f85efd6061525288 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n351_quant.cuh @@ -0,0 +1,175 @@ +// 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 + +#include + +#include "routed_quant_sm120.cuh" +#include + +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 +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 +__device__ __forceinline__ void load_part(__nv_bfloat16 const* src, float (&v)[E]) { + if constexpr (E == 8) { + uint4 raw = *reinterpret_cast(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(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 +__global__ void __launch_bounds__(Cfg::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::kThreads, kSplit = Cfg::kSplit, E = Cfg::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(); + device::PDLTriggerSecondary(); + 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(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(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(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(v); + float amax = block_max_reduce(block_max, red[parity]); // its __syncthreads also publishes s_row / s_exp + uint32_t packed; + uint8_t scale; + quantize_part(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(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(std::max(1, std::min(tokens, g))); +} + +// = n14_quant::nvfp4_quantize_tokens (same checks, grid rule and PDL launch) with the variant kernel. +template +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::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(); + int32_t const experts = verify_offsets(offsets, device); + host::TensorMatcher({tokens, K}).with_dtype().with_device(device).ensure_alignment(kPart * 2).verify(x); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(src2dst); + host::TensorMatcher({rows, K / 2}).with_dtype().with_device(device).ensure_alignment(kPart / 2).verify(values); + host::TensorMatcher({scale_rows, K / 16}).with_dtype().with_device(device).verify(x_scales); + host::TensorMatcher({rows}).with_dtype().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::kThreads, device.unwrap()) + .enable_pdl(true)( + nvfp4_quantize_tokens_kernel, + static_cast<__nv_bfloat16 const*>(x.data_ptr()), + static_cast(src2dst.data_ptr()), + static_cast(values.data_ptr()), + static_cast(x_scales.data_ptr()), + static_cast(amax.data_ptr()), + static_cast(offsets.data_ptr()), + num_tokens, + static_cast(top_k), + experts); +} + +} // namespace sglang::n351_quant diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n355_quant.cuh b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n355_quant.cuh new file mode 100644 index 0000000000000000000000000000000000000000..3c517a75bd8c6620ad921aba426411f3c9eb9a12 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n355_quant.cuh @@ -0,0 +1,216 @@ +// 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 + +#include + +#include "routed_quant_sm120.cuh" +#include + +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 +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 +__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(); + 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(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(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 +__global__ void __launch_bounds__(Cfg::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; + static_assert(N % 128 == 0 && N / 16 <= 1024); + constexpr bool kHoist = V & 1, kPrefetch = V & 2; + device::PDLWaitPrimary(); + 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(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(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 +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; + auto rows = host::SymbolicSize{"routed rows"}; + auto device = host::SymbolicDevice{}; + device.set_options(); + int32_t const experts = verify_offsets(offsets, device); + host::TensorMatcher({rows, 2 * N}) // + .with_dtype() + .with_device(device) + .ensure_alignment(16) + .verify(x); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(gammas); + host::TensorMatcher({rows, N}) // + .with_dtype() + .with_device(device) + .ensure_alignment(16) + .verify(values); + host::TensorMatcher({N / 128, m_padded}).with_dtype().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::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(sm_count)) // the image's launch for the copy + : std::max(1, std::min(iters, C::kGridMul * static_cast(sm_count))); + auto* kernel = V == 0 ? mxfp8_swiglu_quantize_copy : mxfp8_swiglu_quantize_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(gammas.data_ptr()), + static_cast(values.data_ptr()), + static_cast(exponents.data_ptr()), + static_cast(offsets.data_ptr()), + experts, + static_cast(gate_cap), + static_cast(up_cap), + static_cast(m_padded)); +} + +} // namespace sglang::n355_quant diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n381c_band.cuh b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n381c_band.cuh new file mode 100644 index 0000000000000000000000000000000000000000..ab6b42d35169e84e705a098312e5ab14466f2c99 --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/n381c_band.cuh @@ -0,0 +1,2062 @@ +// n381c (prefill seat, n381 implementation 3 + package rider unit): = work_moe/n360/kit/n360_band.cuh (n360-1's reviewed pass-variant source, +// b41a11aa) + n381-2's edits (825eaa0e, KEEP): tile_k = N381_TILE_K; with N381_PP 1 the F2 chunk GEMM is the stock CUTLASS ptr-array PING-PONG +// kernel (F2 runs the hook off), F1's gate_up_band compiled out; namespace sglang::n381c_band, class N381CKernel. Pass variants pv 0..4 as n360 +// (0 = the served chunk_pass). Same tile / K order / mma / epilogue and pass arithmetic: bitwise expected (n381-2 v2 and n360-1 p1 both exact). +// n360 F2b chunk-pass schedules: GENERATED by work_moe/n360/kit/gen_n360.py from n52_band.cuh e855abc8 (asserted edits + added pass kernels). +// SPDX-License-Identifier: Apache-2.0 +// n52 F1 (inkling2-spark moe seat, 2026-11-23): the SM120 MoE prefill visit's NVFP4 gate_up grouped GEMM with the swiglu + +// NVFP4 quantization done per 128-row band from L2 by the CTA that finishes the band's last tile ("band pass"). +// GENERATED by work_moe/n52/gen_n52.py from n52_head.cuh + CUTLASS's ptr-array cooperative kernel + n52_tail.cuh. +// +// - GEMM: FlashInfer 0.7.4's CutlassNVFP4GroupwiseScaledGroupGEMMSM120<128, 128, 256, SwapAB false> types (the served config +// above 3,072 tokens at K 2,304) with the stock BF16 TMA epilogue, so D = the served gate_up output bit for bit. +// - After each tile's epilogue store, the TMA-issuing warp waits for its bulk stores, fences the async proxy and the GPU, and +// thread 0 adds 1 to the band's counter (band = one 128-row M-tile of one expert, numbered like the SFA layout). The CTA +// whose add makes N / 128 (= 18) runs the band pass. +// - Band pass = the image's nvfp4_swiglu_quantize_routed arithmetic (its own device helpers from routed_quant.cuh, E = 4 lanes +// per 16-value block as the image's split for width 1,152) over the band's rows: D read with ld.global.cg (L2), per row +// scale and gamma loaded once, v = bf16(capped_swiglu(bf16(D * scale) pairs)), row amax, quantize_part, store_part, the +// expert's scale tail zeroed on its last band; then discard.global.L2 on the row's D lines (never written back). +// - mode (runtime): -1 stock (no hook), 0 signal only, 1 discard only, 2 pass + discard (the form), 3 pass without discard. +#include + +#include + +#include + +#include "routed_quant_sm120.cuh" + +#include "cute/tensor.hpp" +#include "cutlass/cutlass.h" +#include "cutlass/detail/sm100_blockscaled_layout.hpp" +#include "cutlass/epilogue/collective/collective_builder.hpp" +#include "cutlass/gemm/collective/collective_builder.hpp" +#include "cutlass/gemm/device/gemm_universal_adapter.h" +#include "cutlass/gemm/group_array_problem_shape.hpp" +#include "cutlass/gemm/kernel/gemm_universal.hpp" +#include "cutlass/util/packed_stride.hpp" + +#include + +namespace sglang::n381c_band { + +struct BandParams { + int mode = -1; // -1 stock, 0 signal, 1 discard, 2 pass + discard, 3 pass + int* counters = nullptr; // [bands], zero on entry; the last arriver resets its band to 0 + __nv_bfloat16 const* d = nullptr; // [rows, n] gate_up D (BF16), the GEMM's output + int n = 0; // gate_up width (2 x the swiglu width) + int const* offsets = nullptr; // [experts + 1] expert row offsets (m_indptr) + float const* acc_amax = nullptr; // [rows] amax of the quantized A rows + float const* w_amax = nullptr; // [experts] + float const* w_den = nullptr; // [1] + float const* gammas = nullptr; // [rows] + uint8_t* values = nullptr; // [rows, n / 4] NVFP4 of v + uint8_t* x_scales = nullptr; // SFA layout, 128-row padding per expert + float* amax_out = nullptr; // [rows] + float gate_cap = 0.f; + float up_cap = 0.f; +}; + +constexpr int kBandBarrier = 14; // named barrier id (CUTLASS reserves the low ids) +constexpr int kTileN = 128; + +// bar.red.or over the 256 consumer threads: returns 1 in every thread if any thread passed a nonzero pred. +__device__ __forceinline__ int bar_red_or(int pred) { + int r; + asm volatile( + "{ .reg .pred p, q; setp.ne.s32 p, %1, 0; bar.red.or.pred q, %2, %3, p; selp.s32 %0, 1, 0, q; }" + : "=r"(r) + : "r"(pred), "n"(kBandBarrier), "n"(256) + : "memory"); + return r; +} + +__device__ __forceinline__ void discard_l2(void const* p) { + asm volatile("discard.global.L2 [%0], 128;" ::"l"(p) : "memory"); +} + +#if defined(N52_LEAN) && N52_LEAN +// Build 2 ("lean"), for the checkpoint's caps (gate 4, up 25) only: n52_moe.py refuses lean for other caps. The image's +// capped_swiglu with its two IEEE divides replaced where provably equal on BF16 inputs (work_moe/n52/cpu/div25_proof.py, +// exact rationals over all 65,280 finite BF16 values: PASS): gate / 4 -> gate * 0.25; up / 25 -> q0 = up * RN(1/25), +// rem = fma(-q0, 25, up), fma(rem, RN(1/25), q0); a non-finite up takes the IEEE divide. gate and up are BF16-rounded before +// this call, as in the image kernel; sigmoid, tanh and the multiplies are the image's instructions in the image's order. +__device__ __forceinline__ float capped_swiglu_lean(float gate, float up, float gamma, float, float) { + float sigmoid; + asm("{ .reg .f32 t; mul.rn.f32 t, %1, 0fBFB8AA3B; " + "ex2.approx.ftz.f32 t, t; add.rn.f32 t, t, 0f3F800000; " + "rcp.approx.ftz.f32 %0, t; }" + : "=f"(sigmoid) + : "f"(gate)); + float t; + asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(__fmul_rn(gate, 0.25f))); + gate = __fmul_rn(4.0f, t); + float q = __fmul_rn(up, 0.04f); + q = __fmaf_rn(__fmaf_rn(-q, 25.0f, up), 0.04f, q); + if (!isfinite(up)) q = __fdiv_rn(up, 25.0f); + asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(q)); + up = __fmul_rn(25.0f, t); + return __fmul_rn(__fmul_rn(__fmul_rn(gate, sigmoid), up), gamma); +} +#define N52_SWIGLU capped_swiglu_lean +#else +#define N52_SWIGLU capped_swiglu +#endif + +// One row of expert e by one warp: lane = (block within the 8-block group) * 4 + part, as the image's E = 4 split, 9 groups of +// 8 blocks per 1,152-wide row. Used by the band pass (F1, one warp per row of the band) and the chunk pass (F2). +template +__device__ __forceinline__ void band_row(BandParams const& p, int e, int row, int lane, bool pass, bool discard) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8, LINES = N2 * 2 / 128; + static_assert(NH % 128 == 0 && N2 * 2 % 128 == 0, "whole 8-block groups and whole 128-byte lines per row"); + static_assert(split(NH) == 4, "the image quantizes width NH with E = 4 (4 lanes per block)"); + int const bl = lane / 4, part = lane % 4; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *p.w_den)); + float const wa = p.w_amax[e]; + { + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + if (pass) { + uint4 raw[ITERS]; + uint4 const* src = reinterpret_cast(drow); +#pragma unroll + for (int i = 0; i < ITERS; ++i) + raw[i] = __ldcg(src + (i * 8 + bl) * 4 + part); // block b = 8i + bl: D columns 32b + 8 part .. + 8 + float const scale = __fmul_rn(__fmul_rn(p.acc_amax[row], wa), rcp); + float const gamma = p.gammas[row]; + float v[ITERS][4]; + float bmax[ITERS]; + float m = 0.0f; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(&raw[i]); +#pragma unroll + for (int j = 0; j < 4; ++j) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j + 1]), scale))); + v[i][j] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, p.gate_cap, p.up_cap))); + } + bmax[i] = part_max<4>(v[i]); // max over the block's 16 values (xor 1, 2 within the lane quad) + m = fmaxf(m, bmax[i]); + } +#pragma unroll + for (int s = 4; s < 32; s *= 2) // the other 7 blocks of each group: all 72 block maxima of the row + m = fmaxf(m, __shfl_xor_sync(0xFFFFFFFF, m, s)); + float const amax = m; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + uint32_t packed; + uint8_t sbits; + quantize_part<4>(v[i], amax, bmax[i], packed, sbits); + store_part<4>(p.values, p.x_scales, p.offsets, e, row, i * 8 + bl, part, NH, packed, sbits); + } + if (lane == 0) p.amax_out[row] = amax; + } + if (discard) { + __syncwarp(); // every lane's loads of this row have returned (their values were consumed above) + for (int l = lane; l < LINES; l += 32) + discard_l2(drow + l * 64); + } + } +} + +// One band's rows, one warp per row (rows w, w + 8, ...). +template +__device__ __forceinline__ void band_rows(BandParams const& p, int e, int r0, int r1, int tid, bool pass, bool discard) { + int const warp = tid / 32, lane = tid % 32; + for (int row = r0 + warp; row < r1; row += 8) + band_row(p, e, row, lane, pass, discard); +} + +// zero_expert_tail for the expert's last 128-row tile (the image's bytes), by threads tid = 0 .. nthreads - 1. +template +__device__ __forceinline__ void band_tail(BandParams const& p, int e, int tid, int nthreads = 256) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, SCALE_K = (NH + 63) / 64 * 4, ATOMS = SCALE_K / 4; + int const count = p.offsets[e + 1] - p.offsets[e]; + int const used = count % 128; + if (used == 0) return; + uint8_t* tile = p.x_scales + scale_base(p.offsets, e, SCALE_K) + int64_t(count / 128) * ATOMS * 512; + for (int item = tid; item < ATOMS * 32; item += nthreads) { + int const lane = item % 32; + uint32_t* atom = reinterpret_cast(tile + (item / 32) * 512 + lane * 16); +#pragma unroll + for (int i = 0; i < 4; ++i) + if (lane + 32 * i >= used) atom[i] = 0; + } +} + +// Called by all 256 consumer threads after each tile's epilogue store (tid = mma_thread_idx; warp 0 issued the TMA stores). +template +__device__ __forceinline__ void n52_band_hook(BandParams const& p, int e, int mt, int n, int tid) { + if (tid < 32) { + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); // this tile's D stores are complete (not just read) + asm volatile("fence.proxy.async.global;" ::: "memory"); // async-proxy writes ordered before generic accesses + __syncwarp(); + } + int const base = p.offsets[0]; + int const band = (p.offsets[e] - base + e * 127) / 128 + mt; + int last = 0; + if (tid == 0) { + __threadfence(); + int const old = atomicAdd(p.counters + band, 1); + __threadfence(); + last = old == (n + kTileN - 1) / kTileN - 1; + } + if (!bar_red_or(last)) return; + __threadfence(); + if (p.mode >= 1) { + int const r0 = p.offsets[e] + mt * 128; + int const r1 = min(r0 + 128, p.offsets[e + 1]); + bool const pass = p.mode >= 2, discard = p.mode <= 2; + if (n == N2) { + band_rows(p, e, r0, r1, tid, pass, discard); + if (pass && r1 == p.offsets[e + 1]) band_tail(p, e, tid); + } + } + if (tid == 0) p.counters[band] = 0; +} + +} // namespace sglang::n381c_band + +namespace cutlass::gemm::kernel { + +// ---- N381CKernel: cutlass/gemm/kernel/sm90_gemm_array_tma_warpspecialized_cooperative.hpp (md5 3b39c38d712b5f27af49baea07e8c8b4) with the n52 edits ---- +using sglang::n381c_band::BandParams; +using sglang::n381c_band::n52_band_hook; + +template < + class ProblemShape_, + class CollectiveMainloop_, + class CollectiveEpilogue_, + class TileScheduler_ +> +class N381CKernel +{ + // Get the type of the scheduler response. + template + struct TileSchedulerResponseGetter { + using Type = typename TileScheduler::CLCResponse; + }; + + template + struct TileSchedulerResponseGetter> { + using Type = typename TileScheduler::SchedulerResponse; + }; + +public: + // + // Type Aliases + // + using ProblemShape = ProblemShape_; + static_assert(rank(typename ProblemShape::UnderlyingProblemShape{}) == 3 or rank(typename ProblemShape::UnderlyingProblemShape{}) == 4, + "ProblemShape{} should be or "); + + static_assert(cute::is_base_of_v); + + static constexpr bool IsGdcEnabled = false; + + // Mainloop derived types + using CollectiveMainloop = CollectiveMainloop_; + using TileShape = typename CollectiveMainloop::TileShape; + using TiledMma = typename CollectiveMainloop::TiledMma; + using ArchTag = typename CollectiveMainloop::ArchTag; + using ElementA = typename CollectiveMainloop::ElementA; + using StrideA = typename CollectiveMainloop::StrideA; + using InternalStrideA = typename CollectiveMainloop::InternalStrideA; + using ElementB = typename CollectiveMainloop::ElementB; + using InternalStrideB = typename CollectiveMainloop::InternalStrideB; + using StrideB = typename CollectiveMainloop::StrideB; + using DispatchPolicy = typename CollectiveMainloop::DispatchPolicy; + using Schedule = typename DispatchPolicy::Schedule; + using ElementAccumulator = typename CollectiveMainloop::ElementAccumulator; + using ClusterShape = typename DispatchPolicy::ClusterShape; + using MainloopArguments = typename CollectiveMainloop::Arguments; + using MainloopParams = typename CollectiveMainloop::Params; + + // Epilogue derived types + using CollectiveEpilogue = CollectiveEpilogue_; + using ElementC = typename CollectiveEpilogue::ElementC; + using StrideC = typename CollectiveEpilogue::StrideC; + using InternalStrideC = typename CollectiveEpilogue::InternalStrideC; + using ElementD = typename CollectiveEpilogue::ElementD; + using StrideD = typename CollectiveEpilogue::StrideD; + using InternalStrideD = typename CollectiveEpilogue::InternalStrideD; + using EpilogueArguments = typename CollectiveEpilogue::Arguments; + using EpilogueParams = typename CollectiveEpilogue::Params; + + static_assert(ArchTag::kMinComputeCapability >= 90); + + static constexpr bool IsGroupedGemmKernel = !cute::is_same_v; + static constexpr uint32_t MinTensorMapWorkspaceAlignment = 64; + + static_assert( + cute::is_void_v + or ( + IsGroupedGemmKernel + and cute::is_any_of_v + ), + "Ptr-Array Cooperative and Grouped Gemm Cooperative kernel only supports the default scheduler."); + + using SchedulerTag = cute::conditional_t< + cute::is_void_v, + cute::conditional_t< + IsGroupedGemmKernel, + GroupScheduler, // Special grouped gemm scheduler + void // Default scheduler for non-grouped kernels + >, + TileScheduler_ + >; + + using TileScheduler = typename detail::TileSchedulerSelector< + SchedulerTag, + ArchTag, + TileShape, + ClusterShape, + 8, // SchedulerPipelineStageCount -- Grouped GEMM scheduler will benefit from a larger number of stages. + cute::conditional_t, void, ProblemShape> // Use void for default scheduler. + >::Scheduler; + + using TileSchedulerArguments = typename TileScheduler::Arguments; + using TileSchedulerParams = typename TileScheduler::Params; + using TileSchedulerResponse = typename TileSchedulerResponseGetter::Type; + + static constexpr auto TileSchedulerStages = 8; + + static constexpr uint32_t NumLoadWarpGroups = 1; + static constexpr uint32_t NumMmaThreads = size(TiledMma{}); + static constexpr uint32_t NumMmaWarpGroups = NumMmaThreads / NumThreadsPerWarpGroup; + static constexpr uint32_t MaxThreadsPerBlock = NumMmaThreads + (NumLoadWarpGroups * NumThreadsPerWarpGroup); + static constexpr uint32_t MinBlocksPerMultiprocessor = 1; + static constexpr uint32_t NumProducerThreads = CollectiveMainloop::NumProducerThreadEvents; + static constexpr bool IsMainloopAuxiliaryLoadNeeded = detail::HasAuxiliaryLoad_v; + + /// Register requirement for Load and Math WGs + static constexpr int RegsPerThread = + 2 * size<0>(TileShape{}) * size<1>(TileShape{}) / NumMmaThreads * + sizeof(ElementAccumulator) / sizeof(uint32_t); + + // Detect if this is SM120 blockscaled kernel which hits low register pressure + // on smaller tiles + template + struct IsSm120BlockScaled : cute::false_type {}; + + template + struct IsSm120BlockScaled> + : cute::true_type {}; + + static constexpr bool IsLowRegisterPressure = IsSm120BlockScaled::value && (RegsPerThread <= 64); + + /// Register requirement for Load and Math WGs + static constexpr uint32_t LoadRegisterRequirement = 40; + static constexpr uint32_t MmaRegisterRequirement = 232; + + static constexpr bool IsSm120Family = cute::is_same_v; + + // 1 stage ordered sequence between mainloop and epilogue producer load threads + using LoadWarpOrderBarrier = cutlass::OrderedSequenceBarrier<1,2>; + + // Kernel level shared memory storage + struct SharedStorage { + struct TensorStorage : cute::aligned_struct<128, _1> { + using MainloopTensorStorage = typename CollectiveMainloop::TensorStorage; + using EpilogueTensorStorage = typename CollectiveEpilogue::TensorStorage; + + MainloopTensorStorage mainloop; + EpilogueTensorStorage epilogue; + } tensors; + + struct PipelineStorage : cute::aligned_struct<16, _1> { + using TileSchedulerPipelineStorage = typename TileScheduler::PipelineStorage; + using MainloopPipelineStorage = typename CollectiveMainloop::PipelineStorage; + using EpiLoadPipelineStorage = typename CollectiveEpilogue::PipelineStorage; + + alignas(16) TileSchedulerPipelineStorage scheduler; + alignas(16) MainloopPipelineStorage mainloop; + alignas(16) EpiLoadPipelineStorage epi_load; + alignas(16) typename LoadWarpOrderBarrier::SharedStorage load_order; + } pipelines; + + alignas(16) TileSchedulerResponse scheduler_response[TileSchedulerStages]; + + struct TensorMapStorage : cute::aligned_struct<128, _1> { + using MainloopTensorMapStorage = typename CollectiveMainloop::TensorMapStorage; + using EpilogueTensorMapStorage = typename CollectiveEpilogue::TensorMapStorage; + + alignas(128) MainloopTensorMapStorage mainloop; + alignas(128) EpilogueTensorMapStorage epilogue; + } tensormaps; + }; + + static constexpr int SharedStorageSize = sizeof(SharedStorage); + + // Device side arguments + struct Arguments { + GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopArguments mainloop{}; + EpilogueArguments epilogue{}; + KernelHardwareInfo hw_info{}; + TileSchedulerArguments scheduler{}; + BandParams band{}; // n52 + }; + + // Kernel entry point API + struct Params { + GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopParams mainloop{}; + EpilogueParams epilogue{}; + KernelHardwareInfo hw_info{}; + TileSchedulerParams scheduler{}; + void* workspace{nullptr}; + BandParams band{}; // n52 + }; + + // + // Methods + // + + // Convert to underlying arguments. In this case, a simple copy for the aliased type. + static + Params + to_underlying_arguments(Arguments const& args, void* workspace) { + CUTLASS_TRACE_HOST("to_underlying_arguments():"); + + ProblemShape problem_shapes = args.problem_shape; + + // Get SM count if needed, otherwise use user supplied SM count + int sm_count = args.hw_info.sm_count; + if (sm_count <= 0) { + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid SM count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the SM count."); + sm_count = KernelHardwareInfo::query_device_multiprocessor_count(args.hw_info.device_id); + } + CUTLASS_TRACE_HOST("to_underlying_arguments(): Setting persistent grid SM count to " << sm_count); + + // Get maximum number of clusters that could co-exist on the target device + int max_active_clusters = args.hw_info.max_active_clusters; + if (max_active_clusters <= 0) { + max_active_clusters = 0; + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid max cluster count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the max_active_clusters."); + } + else { + CUTLASS_TRACE_HOST("to_underlying_arguments(): Setting persistent grid cluster count to " << max_active_clusters); + } + + KernelHardwareInfo hw_info{args.hw_info.device_id, sm_count, max_active_clusters}; + + // Calculate workspace pointers + uint8_t* workspace_ptr = reinterpret_cast(workspace); + size_t workspace_offset = 0; + + void* epilogue_workspace = workspace_ptr + workspace_offset; + workspace_offset += CollectiveEpilogue::get_workspace_size(problem_shapes, args.epilogue, sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + void* mainloop_workspace = workspace_ptr + workspace_offset; + workspace_offset += CollectiveMainloop::get_workspace_size(problem_shapes, args.mainloop, sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + void* scheduler_workspace = workspace_ptr + workspace_offset; + workspace_offset += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + TileSchedulerParams scheduler; + if constexpr (IsGroupedGemmKernel) { + scheduler = TileScheduler::to_underlying_arguments( + problem_shapes, TileShape{}, ClusterShape{}, hw_info, args.scheduler, scheduler_workspace); + } + else { + scheduler = TileScheduler::to_underlying_arguments( + problem_shapes.get_host_problem_shape(), TileShape{}, ClusterShape{}, hw_info, args.scheduler, scheduler_workspace); + } + + return { + args.mode, + problem_shapes, + CollectiveMainloop::to_underlying_arguments(problem_shapes, args.mainloop, mainloop_workspace), + CollectiveEpilogue::to_underlying_arguments(problem_shapes, args.epilogue, epilogue_workspace), + hw_info, + scheduler, + workspace, + args.band // n52 + }; + } + + static bool + can_implement(Arguments const& args) { + bool implementable = true; + if constexpr (IsGroupedGemmKernel) { + // Group GEMM currently only supports rank-3 problem shapes + implementable &= (args.mode == GemmUniversalMode::kGrouped && rank(typename ProblemShape::UnderlyingProblemShape{}) == 3); + } + else { + implementable &= (args.mode == GemmUniversalMode::kArray && rank(typename ProblemShape::UnderlyingProblemShape{}) == 4); + } + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Arguments or Problem Shape don't meet the requirements for Ptr Array Gemm or Grouped Gemm.\n"); + return implementable; + } + implementable &= CollectiveMainloop::can_implement(args.problem_shape, args.mainloop); + implementable &= CollectiveEpilogue::can_implement(args.problem_shape, args.epilogue); + implementable &= TileScheduler::can_implement(args.scheduler); + return implementable; + } + + static size_t + get_workspace_size(Arguments const& args) { + size_t workspace_size = 0; + constexpr uint32_t NumEpilogueSubTiles = CollectiveEpilogue::get_store_pipe_increment(TileShape{}); + + // Get SM count if needed, otherwise use user supplied SM count + int sm_count = args.hw_info.sm_count; + if (sm_count <= 0) { + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid SM count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the SM count."); + sm_count = KernelHardwareInfo::query_device_multiprocessor_count(args.hw_info.device_id); + } + + workspace_size += CollectiveEpilogue::get_workspace_size(args.problem_shape, args.epilogue, sm_count); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + workspace_size += CollectiveMainloop::get_workspace_size(args.problem_shape, args.mainloop, sm_count); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + workspace_size += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + return workspace_size; + } + + static cutlass::Status + initialize_workspace(Arguments const& args, void* workspace = nullptr, cudaStream_t stream = nullptr, + CudaHostAdapter* cuda_adapter = nullptr) { + Status status = Status::kSuccess; + uint8_t* workspace_ptr = reinterpret_cast(workspace); + size_t workspace_offset = 0; + constexpr uint32_t NumEpilogueSubTiles = CollectiveEpilogue::get_store_pipe_increment(TileShape{}); + static constexpr uint32_t NumAccumulatorMtxs = 1; + + status = CollectiveEpilogue::initialize_workspace(args.problem_shape, args.epilogue, workspace_ptr + workspace_offset, stream, cuda_adapter); + workspace_offset += CollectiveEpilogue::get_workspace_size(args.problem_shape, args.epilogue, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + status = CollectiveMainloop::initialize_workspace(args.problem_shape, args.mainloop, workspace_ptr + workspace_offset, stream, cuda_adapter); + workspace_offset += CollectiveMainloop::get_workspace_size(args.problem_shape, args.mainloop, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + status = TileScheduler::template initialize_workspace( + args.scheduler, workspace_ptr + workspace_offset, stream, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles, NumAccumulatorMtxs, cuda_adapter); + workspace_offset += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + return status; + } + + // Computes the kernel launch grid shape based on runtime parameters + static dim3 + get_grid_shape(Params const& params) { + // Given device SM count, set grid size s.t. we do not launch more thread blocks than we can run concurrently + TileSchedulerArguments args{}; + args.raster_order = params.scheduler.raster_order_ == TileScheduler::RasterOrder::AlongN ? TileScheduler::RasterOrderOptions::AlongN : TileScheduler::RasterOrderOptions::AlongM; + dim3 grid_shape; + if constexpr (IsGroupedGemmKernel) { + grid_shape = TileScheduler::get_grid_shape(params.scheduler, params.problem_shape, TileShape{}, ClusterShape{}, params.hw_info, args); + } + else { + grid_shape = TileScheduler::get_grid_shape(params.scheduler, params.problem_shape.get_host_problem_shape(), TileShape{}, ClusterShape{}, params.hw_info, args); + } + return grid_shape; + } + + static dim3 + get_block_shape() { + return dim3(MaxThreadsPerBlock, 1, 1); + } + + CUTLASS_DEVICE + void + operator()(Params const& params, char* smem_buf) { + using namespace cute; + using X = Underscore; + +# if (defined(__CUDA_ARCH_FEAT_SM90_ALL) || defined(__CUDA_ARCH_FEAT_SM120_ALL) || defined(__CUDA_ARCH_FEAT_SM121_ALL) ||\ + CUDA_ARCH_CONDITIONAL_OR_FAMILY(1200) || CUDA_ARCH_CONDITIONAL_OR_FAMILY(1210)) +# define ENABLE_SM90_KERNEL_LEVEL 1 +# endif + +// Any Tensor Op MMA Atom in the ISA is arch conditional. +#if ! defined(ENABLE_SM90_KERNEL_LEVEL) + CUTE_INVALID_CONTROL_PATH("ERROR : Arch conditional MMA instruction used without targeting appropriate compute capability. Aborting.\n"); +#else + + // Preconditions + static_assert(size(TiledMma{}) == 256, "Cooperative kernel must have TiledMMA operating using 256 threads."); + static_assert(size<0>(TileShape{}) >= 128, + "Cooperative kernel requires Tile Size to be greater than or equal to 128 along the M-dimension."); + static_assert(NumMmaWarpGroups == 2, "Cooperative kernels currently only support NumMmaWarpGroups == 2"); + + if constexpr (cutlass::epilogue::collective::detail::sm90_is_ptr_array_tma_dispatch_policy_v) { + static_assert(NumMmaWarpGroups == CollectiveEpilogue::NumEpilogueWarpGroups, + "Tiled MmA does not match expected warp groups performing the epilogue"); + } + + static_assert(cute::rank(InternalStrideA{}) == 3, "StrideA must be rank-3: [M, K, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideB{}) == 3, "StrideB must be rank-3: [N, K, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideC{}) == 3, "StrideC must be rank-3: [M, N, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideD{}) == 3, "StrideD must be rank-3: [M, N, L]. If batch mode is not needed, set L stride to Int<0>."); + + /* In the Cooperative kernel, Consumer0 and Consumer1 collaborate on the same tile */ + enum class WarpGroupRole { + Producer = 0, + Consumer0 = 1, + Consumer1 = 2 + }; + enum class ProducerWarpRole { + Mainloop = 0, + MainloopAux = 1, + Epilogue = 2, + Scheduler = 3 + }; + + // Kernel level shared memory storage + SharedStorage& shared_storage = *reinterpret_cast(smem_buf); + + // In a warp specialized kernel, collectives expose data movement and compute operations separately + CollectiveMainloop collective_mainloop; + CollectiveEpilogue collective_epilogue(params.epilogue, shared_storage.tensors.epilogue); + + int thread_idx = int(threadIdx.x); + int lane_idx = canonical_lane_idx(); + int warp_idx = canonical_warp_idx_sync(); + int warp_idx_in_warp_group = warp_idx % NumWarpsPerWarpGroup; + int warp_group_thread_idx = thread_idx % NumThreadsPerWarpGroup; + int mma_thread_idx = thread_idx % size(TiledMma{}); + auto warp_group_idx = canonical_warp_group_idx(); + auto warp_group_role = WarpGroupRole(warp_group_idx); + auto producer_warp_role = ProducerWarpRole(warp_idx_in_warp_group); + int lane_predicate = cute::elect_one_sync(); + uint32_t block_rank_in_cluster = cute::block_rank_in_cluster(); + + // Note: Tma Descriptor Prefetch (from either const or param) is not applicable here + + // TileScheduler pipeline + using TileSchedulerPipeline = typename TileScheduler::Pipeline; + typename TileSchedulerPipeline::Params tile_scheduler_pipeline_params; + if constexpr (cute::is_same_v) { + if (warp_group_role == WarpGroupRole::Producer + && producer_warp_role == ProducerWarpRole::Scheduler) { + tile_scheduler_pipeline_params.role = TileSchedulerPipeline::ThreadCategory::Producer; + } + else { + tile_scheduler_pipeline_params.role = TileSchedulerPipeline::ThreadCategory::Consumer; + } + tile_scheduler_pipeline_params.consumer_arv_count = NumMmaThreads + + NumThreadsPerWarp * ( + 1 // Main DMA warp + + (collective_epilogue.is_producer_load_needed() ? 1 : 0) // Epilog DMA warp + + (IsMainloopAuxiliaryLoadNeeded ? 1 : 0) // Aux DMA warp + ); + tile_scheduler_pipeline_params.producer_arv_count = 1; + } + TileSchedulerPipeline tile_scheduler_pipeline(shared_storage.pipelines.scheduler, tile_scheduler_pipeline_params); + // Mainloop Load pipeline + using MainloopPipeline = typename CollectiveMainloop::MainloopPipeline; + typename MainloopPipeline::Params mainloop_pipeline_params; + if (warp_group_role == WarpGroupRole::Producer + && (producer_warp_role == ProducerWarpRole::Mainloop + || producer_warp_role == ProducerWarpRole::MainloopAux)) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Producer; + } + if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Consumer; + } + mainloop_pipeline_params.is_leader = warp_group_thread_idx == 0; + mainloop_pipeline_params.num_consumers = NumMmaThreads; + mainloop_pipeline_params.num_producers = NumProducerThreads; + mainloop_pipeline_params.transaction_bytes = params.mainloop.tma_transaction_bytes; + MainloopPipeline mainloop_pipeline(shared_storage.pipelines.mainloop, mainloop_pipeline_params, ClusterShape{}); + + // Epilogue Load pipeline + using EpiLoadPipeline = typename CollectiveEpilogue::LoadPipeline; + typename EpiLoadPipeline::Params epi_load_pipeline_params; + if (warp_group_role == WarpGroupRole::Producer && producer_warp_role == ProducerWarpRole::Epilogue) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Producer; + } + if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Consumer; + } + epi_load_pipeline_params.dst_blockid = cute::block_rank_in_cluster(); + epi_load_pipeline_params.producer_arv_count = NumThreadsPerWarp; + epi_load_pipeline_params.consumer_arv_count = size(TiledMma{}); + if constexpr (CollectiveEpilogue::RequiresTransactionBytes) { + epi_load_pipeline_params.transaction_bytes = params.epilogue.tma_transaction_bytes; + } + EpiLoadPipeline epi_load_pipeline(shared_storage.pipelines.epi_load, epi_load_pipeline_params); + + // Epilogue Store pipeline + using EpiStorePipeline = typename CollectiveEpilogue::StorePipeline; + typename EpiStorePipeline::Params epi_store_pipeline_params; + epi_store_pipeline_params.always_wait = true; + EpiStorePipeline epi_store_pipeline(epi_store_pipeline_params); + + typename LoadWarpOrderBarrier::Params params_load_order_barrier; + params_load_order_barrier.group_id = producer_warp_role == ProducerWarpRole::Mainloop ? 0 : 1; + params_load_order_barrier.group_size = NumThreadsPerWarp; + LoadWarpOrderBarrier load_order_barrier(shared_storage.pipelines.load_order, params_load_order_barrier); + + // Initialize starting pipeline states for the collectives + // Epilogue store pipe is producer-only (consumer is TMA unit, waits via scoreboarding) + typename TileSchedulerPipeline::PipelineState tile_scheduler_pipe_consumer_state; + typename CollectiveMainloop::PipelineState mainloop_pipe_consumer_state; + typename CollectiveEpilogue::LoadPipelineState epi_load_pipe_consumer_state; + + // For the DMA Load (producer) we start with an opposite phase + // i.e., we skip all waits since we know that the buffer is indeed empty + PipelineState tile_scheduler_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState mainloop_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState epi_load_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState epi_store_pipe_producer_state = cutlass::make_producer_start_state(); + + auto cluster_wait_fn = [] () { + // We need this to guarantee that the Pipeline init is visible + // To all producers and consumer thread blocks in the Cluster + if constexpr (size(ClusterShape{}) > 1) { + cute::cluster_arrive_relaxed(); + return [] () { cute::cluster_wait(); }; + } + else { + __syncthreads(); + return [] () {}; // do nothing + } + } (); + + // Get the appropriate blocks for this thread block -- potential for thread block locality + TiledMma tiled_mma; + const auto blk_shape = TileShape{}; // (BLK_M,BLK_N,BLK_K) + const auto c_tile_count = CollectiveEpilogue::get_load_pipe_increment(blk_shape); + const auto d_tile_count = CollectiveEpilogue::get_store_pipe_increment(blk_shape); + + // Wait for all thread blocks in the Cluster + cluster_wait_fn(); + + // Ensure memory ops in this kernel are not done prior to completion of dependent grids. + cutlass::arch::wait_on_dependent_grids(); + + auto scheduler = [&] () { + // Group scheduler requires a different constructor that takes a response ptr + if constexpr (cute::is_same_v) { + return TileScheduler{params.scheduler, shared_storage.scheduler_response}; + } + else { + return TileScheduler{params.scheduler}; + } + } (); + + auto work_tile_info = scheduler.initial_work_tile_info(ClusterShape{}); + + if (not work_tile_info.is_valid()) { + // When problem shapes are only on device, the grid launched may be larger than the total number of blocks across groups + return; + } + + // Optionally append 1s until problem shape is rank-4 in case it is only rank-3 (MNK) + auto problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + + // Prepare and partition the input tensors. Expects a tuple of tensors where: + // get<0>(load_inputs) is the tma tensor A after local tiling so that it has shape (BLK_M,BLK_K,m,k,l) + // get<1>(load_inputs) is the tma tensor B after local tiling so that it has shape (BLK_N,BLK_K,n,k,l) + auto load_inputs = collective_mainloop.load_init(problem_shape_MNKL, params.mainloop); + static_assert(cute::tuple_size_v >= 2, "Output of load_init must have at least two elements (A, B)"); + + // Extract out partitioned A and B. + Tensor gA_mkl = get<0>(load_inputs); + Tensor gB_nkl = get<1>(load_inputs); + + // Get pipeline stage increments from tensor shapes + auto k_tile_count = size<3>(gA_mkl); + + if (warp_group_role == WarpGroupRole::Producer) { + if constexpr (!IsLowRegisterPressure) { + cutlass::arch::warpgroup_reg_dealloc(); + } + + if (producer_warp_role == ProducerWarpRole::Scheduler) { + // GroupScheduler requires a producer warp to iterate over the group infos and push + // the work tile infos to the downstream pipelines. + if constexpr (cute::is_same_v) { + do { + auto [next_work_tile_info, increment_pipe] = scheduler.advance_to_next_work(tile_scheduler_pipeline, tile_scheduler_pipe_producer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_producer_state; + } + } while (work_tile_info.is_valid()); + tile_scheduler_pipeline.producer_tail(tile_scheduler_pipe_producer_state); + } + } + // Mainloop Producer Warp + else if (producer_warp_role == ProducerWarpRole::Mainloop) { + int32_t curr_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx; + int32_t const mock_l_coord = 0; + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + + // Fetch a copy of tensormaps for the CTA + auto input_tensormaps = collective_mainloop.tensormaps_init(params.mainloop, shared_storage.tensormaps.mainloop, sm_count, sm_idx); + + // Update tensormap for the initial batch for the CTA + collective_mainloop.tensormaps_perform_update( + shared_storage.tensormaps.mainloop, + params.mainloop, + input_tensormaps, + problem_shape_MNKL, + curr_batch + ); + // Ensure warp is converged before issuing tensormap fence release + __syncwarp(); + // Entire warp must do this (i.e. it's aligned) + collective_mainloop.tensormaps_cp_fence_release(shared_storage.tensormaps.mainloop, input_tensormaps); + + bool do_load_order_arrive = true; + bool did_batch_change = true; + do { + if (!TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + continue; + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, mock_l_coord); + + // Get the number of K tiles to compute for this work as well as the starting K tile offset of the work. + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + auto work_k_tile_start = TileScheduler::get_work_k_tile_start(work_tile_info); + auto k_tile_iter = cute::make_coord_iterator(idx2crd(work_k_tile_start, shape<3>(gA_mkl)), shape<3>(gA_mkl)); + + if (did_batch_change) { + load_inputs = collective_mainloop.tensors_perform_update(load_inputs, params.mainloop, problem_shape_MNKL, curr_batch); + collective_mainloop.tensormaps_fence_acquire(input_tensormaps); + } + + collective_mainloop.load( + params.mainloop, + mainloop_pipeline, + mainloop_pipe_producer_state, + load_inputs, + input_tensormaps, + blk_coord, + k_tile_iter, work_k_tile_count, + lane_idx, + block_rank_in_cluster, + shared_storage.tensors.mainloop + ); + // Pipeline state is only advanced if there are K tiles to compute + mainloop_pipe_producer_state.advance(work_k_tile_count); + + // Signal for the epilogue load warp to begin + if (do_load_order_arrive) { + load_order_barrier.arrive(); + do_load_order_arrive = false; + } + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + auto next_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx + did_batch_change = next_batch != curr_batch; + if (work_tile_info.is_valid() && did_batch_change) { + curr_batch = next_batch; + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(curr_batch), 1); + } + collective_mainloop.tensormaps_perform_update( + shared_storage.tensormaps.mainloop, + params.mainloop, + input_tensormaps, + problem_shape_MNKL, + curr_batch + ); + // Ensure warp is converged before issuing tensor replace + __syncwarp(); + // Entire warp must do this (i.e. it's aligned) + collective_mainloop.tensormaps_cp_fence_release(shared_storage.tensormaps.mainloop, input_tensormaps); + } + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Make sure all Consumer Warp Groups have been waited upon + collective_mainloop.load_tail(mainloop_pipeline, mainloop_pipe_producer_state); + } // Mainloop Producer Warp End + else if (producer_warp_role == ProducerWarpRole::MainloopAux) { + if constexpr (IsMainloopAuxiliaryLoadNeeded) { + int32_t curr_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx; + int32_t const mock_l_coord = 0; + + bool did_batch_change = true; + do { + if (!TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + continue; + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, mock_l_coord); + + // Get the number of K tiles to compute for this work as well as the starting K tile offset of the work. + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + auto work_k_tile_start = TileScheduler::get_work_k_tile_start(work_tile_info); + auto k_tile_iter = cute::make_coord_iterator(idx2crd(work_k_tile_start, shape<3>(gA_mkl)), shape<3>(gA_mkl)); + + if (did_batch_change) { + load_inputs = collective_mainloop.tensors_perform_update(load_inputs, params.mainloop, problem_shape_MNKL, curr_batch); + } + + collective_mainloop.load_auxiliary( + params.mainloop, + mainloop_pipeline, + mainloop_pipe_producer_state, + load_inputs, + blk_coord, + k_tile_iter, work_k_tile_count, + lane_idx, + block_rank_in_cluster, + shared_storage.tensors.mainloop + ); + + // Update starting pipeline state for the next tile + mainloop_pipe_producer_state.advance(work_k_tile_count); + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + auto next_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx + did_batch_change = next_batch != curr_batch; + if (work_tile_info.is_valid() && did_batch_change) { + curr_batch = next_batch; + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(curr_batch), 1); + } + } + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + } // End of auxiliary load needed check + } // Mainloop Auxiliary Load Producer Warp End + // Epilogue Producer Warp + else if (producer_warp_role == ProducerWarpRole::Epilogue && collective_epilogue.is_producer_load_needed()) { + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + + auto epi_load_tensormap = get<0>(collective_epilogue.load_init(params.epilogue, shared_storage.tensormaps.epilogue, sm_count, sm_idx)); + + bool did_batch_change = true; + constexpr bool IsEpiLoad = true; + + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_load_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + 0 + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, epi_load_tensormap, 0); + + load_order_barrier.wait(); + + do { + int32_t curr_batch = work_tile_info.L_idx; + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + + if (TileScheduler::compute_epilogue(work_tile_info, params.scheduler)) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto l_coord = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, l_coord); + + if (did_batch_change) { + collective_epilogue.template tensormaps_fence_acquire(epi_load_tensormap); + } + + epi_load_pipe_producer_state = collective_epilogue.load( + epi_load_pipeline, + epi_load_pipe_producer_state, + problem_shape_MNKL, + blk_shape, + blk_coord, + tiled_mma, + lane_idx, + shared_storage.tensors.epilogue, + epi_load_tensormap, + work_tile_info.reduction_subtile_idx() + ); + } + + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + did_batch_change = curr_batch != work_tile_info.L_idx; + + if (work_tile_info.is_valid() && did_batch_change) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + // tensormap update + { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_load_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + 0 + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, epi_load_tensormap, 0); + } + } + + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Make sure all Consumer Warp Groups have been waited upon + collective_epilogue.load_tail(epi_load_pipeline, epi_load_pipe_producer_state); + } // Epilogue Producer Warp End + } // Producer Warp Group End + + else if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + if constexpr (!IsLowRegisterPressure) { + cutlass::arch::warpgroup_reg_alloc(); + } + + // Index of warp group within consumer warp groups + int consumer_warp_group_idx = warp_group_role == WarpGroupRole::Consumer0 ? 0 : 1; + + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + // Do we potentially issue tail arrives for TMA stores, if epilogue load is waiting for it + bool do_store_tail = false; + // Get a copy of tensormaps + auto epi_store_tensormap = get<0>(collective_epilogue.store_init(params.epilogue, shared_storage.tensormaps.epilogue, sm_count, sm_idx, consumer_warp_group_idx)); + + bool did_batch_change = true; + constexpr bool IsEpiLoad = false; + + if (warp_idx_in_warp_group == 0) { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_store_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + consumer_warp_group_idx + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, + epi_store_tensormap, + consumer_warp_group_idx); + } + + do { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + int32_t curr_batch = work_tile_info.L_idx; + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto l_coord = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, l_coord); + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + + // Allocate the accumulators for the (M,N) blk_shape + // + // MSVC CTAD breaks if we say "Tensor" here, so we use "auto" instead. + auto accumulators = partition_fragment_C(tiled_mma, take<0,2>(blk_shape)); // (MMA,MMA_M,MMA_N) + + if (TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + + if constexpr (IsSm120Family) { + collective_mainloop.mma( + mainloop_pipeline, + mainloop_pipe_consumer_state, + accumulators, + work_k_tile_count, + mma_thread_idx, + shared_storage.tensors.mainloop, + params.mainloop, + blk_coord + ); + } + else { + collective_mainloop.mma( + mainloop_pipeline, + mainloop_pipe_consumer_state, + accumulators, + work_k_tile_count, + mma_thread_idx, + shared_storage.tensors.mainloop, + params.mainloop + ); + } + + // Make sure the math instructions are done and free buffers before entering the epilogue + collective_mainloop.mma_tail( + mainloop_pipeline, + mainloop_pipe_consumer_state, + work_k_tile_count + ); + + // Update starting mainloop pipeline state for the next tile + mainloop_pipe_consumer_state.advance(work_k_tile_count); + } + + // Perform reduction across splits, if needed + TileScheduler::fixup( + params.scheduler, work_tile_info, accumulators, NumMmaWarpGroups, consumer_warp_group_idx); + + if (did_batch_change) { + collective_epilogue.template tensormaps_fence_acquire(epi_store_tensormap); + } + + if (TileScheduler::compute_epilogue(work_tile_info, params.scheduler)) { + + // Epilogue and write to gD + auto [epi_load_pipe_consumer_state_next, epi_store_pipe_producer_state_next] = + collective_epilogue.store( + epi_load_pipeline, + epi_load_pipe_consumer_state, + epi_store_pipeline, + epi_store_pipe_producer_state, + problem_shape_MNKL, + blk_shape, + blk_coord, + accumulators, + tiled_mma, + mma_thread_idx, + shared_storage.tensors.epilogue, + epi_store_tensormap, + work_tile_info.reduction_subtile_idx() + ); + + epi_load_pipe_consumer_state = epi_load_pipe_consumer_state_next; + epi_store_pipe_producer_state = epi_store_pipe_producer_state_next; + do_store_tail = true; + // n52: this tile's D is stored; signal its band, the last arriver runs the band pass. +#ifndef N52_NO_HOOK + if (params.band.mode >= 0) { + n52_band_hook(params.band, int(work_tile_info.L_idx), int(work_tile_info.M_idx), + int(get<1>(problem_shape_MNKL)), mma_thread_idx); + } +#endif + } + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + + if (!next_work_tile_info.is_valid()) { + cutlass::arch::launch_dependent_grids(); + } + + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + + did_batch_change = curr_batch != work_tile_info.L_idx; + if (work_tile_info.is_valid() && did_batch_change) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + if (warp_idx_in_warp_group == 0) { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_store_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + consumer_warp_group_idx + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, + epi_store_tensormap, + consumer_warp_group_idx); + } + } + + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Cooperative only needs TMA to complete at the very end of the kernel + if (do_store_tail) { + collective_epilogue.store_tail( + epi_load_pipeline, + epi_load_pipe_consumer_state, + epi_store_pipeline, + epi_store_pipe_producer_state + ); + } + } // Consumer Warp Groups End +#endif + } +}; + + +} // namespace cutlass::gemm::kernel + +namespace sglang::n381c_band { + +using namespace cute; + +// ---- GEMM types: FlashInfer's builder arguments for <128, 128, 256, SwapAB false>, ElementD bf16, ElementC void. ---- +using ElementA = cutlass::float_e2m1_t; +using ElementB = cutlass::float_e2m1_t; +using ElementSF = cutlass::float_ue4m3_t; +using ElementD = cutlass::bfloat16_t; +constexpr int AlignmentA = 128 / cutlass::sizeof_bits::value; +constexpr int AlignmentB = 128 / cutlass::sizeof_bits::value; +constexpr int AlignmentD = 128 / cutlass::sizeof_bits::value; +using ElementAccumulator = float; +using ElementCompute = float; +using ElementAMainloop = cutlass::nv_float4_t; +using ElementBMainloop = cutlass::nv_float4_t; +using ProblemShape = cutlass::gemm::GroupProblemShape>; +using LayoutA = cutlass::layout::RowMajor; +using LayoutB = cutlass::layout::ColumnMajor; +using LayoutD = cutlass::layout::RowMajor; +using ClusterShape = Shape<_1, _1, _1>; +#ifndef N381_PP +#define N381_PP 0 +#endif +#ifndef N381_TILE_K +#define N381_TILE_K 256 +#endif +static_assert(N381_TILE_K == 128 || N381_TILE_K == 256, "N381_TILE_K"); +using ThreadBlockShape = Shape<_128, _128, cute::Int>; // n381: tile_k 128 (4 stages) or 256 (served) +using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< + cutlass::arch::Sm120, + cutlass::arch::OpClassBlockScaledTensorOp, + ThreadBlockShape, + ClusterShape, + cutlass::epilogue::collective::EpilogueTileAuto, + ElementAccumulator, + ElementCompute, + void, + LayoutD*, + AlignmentD, + ElementD, + LayoutD*, + AlignmentD, +#if N381_PP + cutlass::epilogue::PtrArrayTmaWarpSpecializedPingpong>::CollectiveOp; +#else + cutlass::epilogue::collective::EpilogueScheduleAuto>::CollectiveOp; +#endif +using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< + cutlass::arch::Sm120, + cutlass::arch::OpClassBlockScaledTensorOp, + ElementAMainloop, + LayoutA*, + AlignmentA, + ElementBMainloop, + LayoutB*, + AlignmentB, + ElementAccumulator, + ThreadBlockShape, + ClusterShape, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, +#if N381_PP + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedPingpong>::CollectiveOp; +static_assert( + cute::is_base_of_v< + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedPingpong, + typename CollectiveMainloop::DispatchPolicy::Schedule>, + "n381 PP: the ptr-array ping-pong kernel"); +using GemmKernel = cutlass::gemm::kernel::GemmUniversal; +#else + cutlass::gemm::collective::KernelScheduleAuto>::CollectiveOp; +static_assert( + cute::is_base_of_v< + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedCooperative, + typename CollectiveMainloop::DispatchPolicy::Schedule>, + "the served config builds the ptr-array cooperative kernel; N381CKernel is a copy of that kernel"); +using GemmKernel = cutlass::gemm::kernel::N381CKernel; +#endif +using Gemm = cutlass::gemm::device::GemmUniversalAdapter; +static_assert(GemmKernel::SharedStorageSize <= 101376, "dynamic smem must fit sm_120's 99 KB per block"); +using StrideA = typename Gemm::GemmKernel::InternalStrideA; +using StrideB = typename Gemm::GemmKernel::InternalStrideB; +using StrideD = typename Gemm::GemmKernel::InternalStrideD; +using ScaleConfig = typename Gemm::GemmKernel::CollectiveMainloop::Sm1xxBlkScaledConfig; +using LayoutSFA = typename Gemm::GemmKernel::CollectiveMainloop::InternalLayoutSFA; +using LayoutSFB = typename Gemm::GemmKernel::CollectiveMainloop::InternalLayoutSFB; +constexpr int ScaleGranularity = Gemm::GemmKernel::CollectiveMainloop::TiledMma::SFVecSize; +static_assert(ScaleGranularity == 16); +using UnderlyingProblemShape = typename ProblemShape::UnderlyingProblemShape; + +template +__host__ __device__ __forceinline__ T* inc_ptr(T* ptr, size_t offset) { + constexpr int adjustment = (cutlass::sizeof_bits::value < 8) ? (8 / cutlass::sizeof_bits::value) : 1; + return ptr + offset / adjustment; +} + +// FlashInfer's compute_sm120_cutlass_nvfp4_group_gemm_args (SwapAB false), line for line. +__global__ void group_args( + ElementA* A, + ElementB* B, + ElementSF* SFA, + ElementSF* SFB, + ElementD* D, + int const* m_indptr, + int n, + int k, + int num_groups, + UnderlyingProblemShape* problem_sizes, + ElementA const** A_ptr, + ElementB const** B_ptr, + ElementSF const** SFA_ptr, + ElementSF const** SFB_ptr, + ElementD** D_ptr, + StrideA* stride_A, + StrideB* stride_B, + StrideD* stride_D, + LayoutSFA* layout_SFA, + LayoutSFB* layout_SFB) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= num_groups) return; + constexpr size_t alignment_swizzled_mn = 128; + constexpr size_t alignment_swizzled_k = static_cast(ScaleGranularity) * 4; + size_t sf_n = (static_cast(n) + alignment_swizzled_mn - 1) / alignment_swizzled_mn * alignment_swizzled_mn; + size_t swizzled_k = (static_cast(k) + alignment_swizzled_k - 1) / alignment_swizzled_k * alignment_swizzled_k; + size_t sf_k = swizzled_k / static_cast(ScaleGranularity); + asm volatile("griddepcontrol.wait;"); + asm volatile("griddepcontrol.launch_dependents;"); + int m_offset = m_indptr[i]; + int m_offset_next = m_indptr[i + 1]; + size_t m = static_cast(m_offset_next) - static_cast(m_offset); + size_t sf_m_offset = (static_cast(m_offset) + static_cast(i) * (alignment_swizzled_mn - 1)) / + alignment_swizzled_mn * alignment_swizzled_mn; + problem_sizes[i] = UnderlyingProblemShape(int(m), n, k); + stride_A[i] = cutlass::make_cute_packed_stride(StrideA{}, {int(m), k, 1}); + stride_B[i] = cutlass::make_cute_packed_stride(StrideB{}, {n, k, 1}); + stride_D[i] = cutlass::make_cute_packed_stride(StrideD{}, {int(m), n, 1}); + A_ptr[i] = inc_ptr(A, static_cast(m_offset) * static_cast(k)); + B_ptr[i] = inc_ptr(B, static_cast(i) * static_cast(n) * static_cast(k)); + D_ptr[i] = D + static_cast(m_offset) * static_cast(n); + layout_SFA[i] = ScaleConfig::tile_atom_to_shape_SFA( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFA_ptr[i] = inc_ptr(SFA, sf_m_offset * sf_k); + layout_SFB[i] = ScaleConfig::tile_atom_to_shape_SFB( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFB_ptr[i] = inc_ptr(SFB, static_cast(i) * sf_n * sf_k); +} + +inline size_t align16(size_t x) { + return (x + 15) / 16 * 16; +} + +#if !N381_PP +// values [rows, k/2] u8, weight [E, n, k/2] u8, scales (SFA, u8), weight_scales [E, n, k/16] u8 view, m_indptr [E+1], +// acc_amax / gammas [rows] f32, w_amax [E] f32, w_den [1] f32, d [rows, n] bf16 scratch (the GEMM's D), +// out_values [rows, n/4] u8, out_scales (SFA of width n/2, u8), out_amax [rows] f32, counters [>= bands] i32 (zero), +// int_ws / float_ws u8 workspaces. mode: -1 stock, 0 signal, 1 discard, 2 pass + discard, 3 pass. raster: 0 AlongM, 1 AlongN. +void gate_up_band( + tvm::ffi::TensorView values, + tvm::ffi::TensorView weight, + tvm::ffi::TensorView scales, + tvm::ffi::TensorView weight_scales, + tvm::ffi::TensorView m_indptr, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_den, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView d, + tvm::ffi::TensorView out_values, + tvm::ffi::TensorView out_scales, + tvm::ffi::TensorView out_amax, + tvm::ffi::TensorView counters, + tvm::ffi::TensorView int_ws, + tvm::ffi::TensorView float_ws, + double gate_cap, + double up_cap, + int64_t mode, + int64_t raster, + int64_t sm_count) { + auto device = host::SymbolicDevice{}; + device.set_options(); + auto rows = host::SymbolicSize{"rows"}; + auto experts = host::SymbolicSize{"experts"}; + auto n = host::SymbolicSize{"n"}; + auto kp = host::SymbolicSize{"k/2"}; + host::TensorMatcher({rows, kp}).with_dtype().with_device(device).verify(values); + host::TensorMatcher({experts, n, kp}).with_dtype().with_device(device).verify(weight); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(out_amax); + host::TensorMatcher({experts}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_den); + host::TensorMatcher({rows, n}).with_dtype().with_device(device).verify(d); + int const num_groups = static_cast(experts.unwrap()); + int const N = static_cast(n.unwrap()), K = static_cast(kp.unwrap()) * 2; + int64_t const R = rows.unwrap(); + CHECK_HOST(N == 2304) << "n52 band pass is compiled for gate_up width 2304, got " << N; + CHECK_HOST(m_indptr.size(0) == num_groups + 1) << "m_indptr must hold experts + 1 offsets"; + CHECK_HOST(out_values.size(0) == R && out_values.size(1) == N / 4) << "out_values must be [rows, n / 4]"; + int64_t const bands = (R + 127 * int64_t(num_groups)) / 128 + 1; + CHECK_HOST(counters.numel() >= bands) << "counters need " << bands << " entries"; + CHECK_HOST(out_scales.numel() >= (R + 127 * int64_t(num_groups) + 127) / 128 * 128 * (N / 2 / 16)) + << "out_scales too small for the SFA layout"; + CHECK_HOST(mode >= -1 && mode <= 3) << "mode must be -1..3"; + cudaStream_t stream = host::LaunchKernel::resolve_device(device.unwrap()); + + uint8_t* ib = static_cast(int_ws.data_ptr()); + size_t off = 0; + auto take = [&](size_t bytes) { + void* p = ib + off; + off += align16(bytes); + return p; + }; + auto problem_sizes = static_cast(take(num_groups * sizeof(UnderlyingProblemShape))); + auto A_ptr = static_cast(take(num_groups * sizeof(void*))); + auto B_ptr = static_cast(take(num_groups * sizeof(void*))); + auto D_ptr = static_cast(take(num_groups * sizeof(void*))); + auto SFA_ptr = static_cast(take(num_groups * sizeof(void*))); + auto SFB_ptr = static_cast(take(num_groups * sizeof(void*))); + auto stride_A = static_cast(take(num_groups * sizeof(StrideA))); + auto stride_B = static_cast(take(num_groups * sizeof(StrideB))); + auto stride_D = static_cast(take(num_groups * sizeof(StrideD))); + auto layout_SFA = static_cast(take(num_groups * sizeof(LayoutSFA))); + auto layout_SFB = static_cast(take(num_groups * sizeof(LayoutSFB))); + CHECK_HOST(off <= size_t(int_ws.numel())) << "int workspace too small: need " << off; + + cudaLaunchConfig_t config{}; + config.gridDim = (num_groups + 1023) / 1024; + config.blockDim = std::min(num_groups, 1024); + config.dynamicSmemBytes = 0; + config.stream = stream; + cudaLaunchAttribute attrs[1]; + attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[0].val.programmaticStreamSerializationAllowed = true; + config.numAttrs = 1; + config.attrs = attrs; + cudaError_t const st = cudaLaunchKernelEx( + &config, + group_args, + static_cast(values.data_ptr()), + static_cast(weight.data_ptr()), + static_cast(scales.data_ptr()), + static_cast(weight_scales.data_ptr()), + static_cast(d.data_ptr()), + static_cast(m_indptr.data_ptr()), + N, + K, + num_groups, + problem_sizes, + A_ptr, + B_ptr, + SFA_ptr, + SFB_ptr, + D_ptr, + stride_A, + stride_B, + stride_D, + layout_SFA, + layout_SFB); + CHECK_HOST(st == cudaSuccess) << "n52 group args launch: " << cudaGetErrorString(st); + + cutlass::KernelHardwareInfo hw_info; + hw_info.device_id = device.unwrap().device_id; + hw_info.sm_count = static_cast(sm_count); + typename Gemm::Arguments arguments{ + cutlass::gemm::GemmUniversalMode::kGrouped, + {num_groups, problem_sizes, /*problem_sizes_host=*/nullptr}, + {A_ptr, stride_A, B_ptr, stride_B, SFA_ptr, layout_SFA, SFB_ptr, layout_SFB}, + {{}, nullptr, nullptr, D_ptr, stride_D}, + hw_info}; + auto& fusion_args = arguments.epilogue.thread; + fusion_args.alpha = 1.0f; // FlashInfer with alpha == nullptr (the served call passes none) + fusion_args.beta = 0; + fusion_args.alpha_ptr = nullptr; + fusion_args.dAlpha = {cute::_0{}, cute::_0{}, 0}; + using RasterOptions = decltype(arguments.scheduler.raster_order); + arguments.scheduler.raster_order = raster ? RasterOptions::AlongN : RasterOptions::AlongM; + BandParams& b = arguments.band; + b.mode = static_cast(mode); + b.counters = static_cast(counters.data_ptr()); + b.d = static_cast<__nv_bfloat16 const*>(d.data_ptr()); + b.n = N; + b.offsets = static_cast(m_indptr.data_ptr()); + b.acc_amax = static_cast(acc_amax.data_ptr()); + b.w_amax = static_cast(w_amax.data_ptr()); + b.w_den = static_cast(w_den.data_ptr()); + b.gammas = static_cast(gammas.data_ptr()); + b.values = static_cast(out_values.data_ptr()); + b.x_scales = static_cast(out_scales.data_ptr()); + b.amax_out = static_cast(out_amax.data_ptr()); + b.gate_cap = static_cast(gate_cap); + b.up_cap = static_cast(up_cap); + + Gemm gemm; + size_t const ws = Gemm::get_workspace_size(arguments); + CHECK_HOST(ws <= size_t(float_ws.numel())) << "float workspace too small: need " << ws; + CHECK_HOST(gemm.can_implement(arguments) == cutlass::Status::kSuccess) << "n52 gemm cannot implement"; + CHECK_HOST(gemm.initialize(arguments, float_ws.data_ptr()) == cutlass::Status::kSuccess) << "n52 gemm initialize"; + CHECK_HOST(gemm.run(stream, /*cuda_adapter=*/nullptr, /*launch_with_pdl=*/true) == cutlass::Status::kSuccess) + << "n52 gemm run"; +} + +#endif // !N381_PP (F1 gate_up_band needs the in-kernel hook kernel) + +// --------------------------------------------------------------------------------------------------------------------------- +// F2 (chunked L2 pass): the same GEMM type, hook off (band mode -1), launched once per chunk of TB padded 128-row bands (the +// band numbering of F1 = the SFA layout's), each launch covering every expert's M-tiles that fall in the chunk; after each GEMM +// launch a pass kernel runs the band arithmetic (band_row) over the chunk's rows reading D from L2 and discarding it. Kernel +// boundaries order D's writes before the pass (no counters, no fences). Exact for the same reason as F1: each tile is the +// served tile (same rows, same K order); a sub-problem starts on a 128-row tile of its expert, so its A / D / SFA pointers are +// the expert's plus whole tiles (the SFA layout is row-block outermost: 128 x sf_k bytes per block). + +__device__ __forceinline__ int band0_of(int const* offsets, int e) { + return (offsets[e] - offsets[0] + e * 127) / 128; +} + +// Expert of padded band b: the largest e with band0_of(e) <= b (bands between experts' last tile and the next start are unused). +__device__ __forceinline__ int expert_of_band(int const* offsets, int experts, int b) { + int lo = 0, hi = experts; + while (hi - lo > 1) { + int const mid = (lo + hi) / 2; + if (band0_of(offsets, mid) <= b) + lo = mid; + else + hi = mid; + } + return lo; +} + +// One thread per (chunk, group): the arrays of chunk c start at c * num_groups. +__global__ void chunk_args( + ElementA* A, + ElementB* B, + ElementSF* SFA, + ElementSF* SFB, + ElementD* D, + int const* m_indptr, + int n, + int k, + int num_groups, + int nchunks, + int tb, + UnderlyingProblemShape* problem_sizes, + ElementA const** A_ptr, + ElementB const** B_ptr, + ElementSF const** SFA_ptr, + ElementSF const** SFB_ptr, + ElementD** D_ptr, + StrideA* stride_A, + StrideB* stride_B, + StrideD* stride_D, + LayoutSFA* layout_SFA, + LayoutSFB* layout_SFB) { + int const t = blockIdx.x * blockDim.x + threadIdx.x; + asm volatile("griddepcontrol.wait;"); + asm volatile("griddepcontrol.launch_dependents;"); + if (t >= num_groups * nchunks) return; + int const c = t / num_groups, i = t % num_groups; + constexpr size_t alignment_swizzled_mn = 128; + constexpr size_t alignment_swizzled_k = static_cast(ScaleGranularity) * 4; + size_t sf_n = (static_cast(n) + alignment_swizzled_mn - 1) / alignment_swizzled_mn * alignment_swizzled_mn; + size_t swizzled_k = (static_cast(k) + alignment_swizzled_k - 1) / alignment_swizzled_k * alignment_swizzled_k; + size_t sf_k = swizzled_k / static_cast(ScaleGranularity); + int const m_offset = m_indptr[i], cnt = m_indptr[i + 1] - m_indptr[i]; + int const b0 = band0_of(m_indptr, i), nt = (cnt + 127) / 128; + int const lo = max(b0, c * tb), hi = min(b0 + nt, (c + 1) * tb); // this expert's bands inside chunk c + int const mt0 = hi > lo ? lo - b0 : 0; + int const m = hi > lo ? min(cnt, (hi - b0) * 128) - mt0 * 128 : 0; + int const row0 = m_offset + mt0 * 128; + size_t sf_m_offset = (static_cast(m_offset) + static_cast(i) * (alignment_swizzled_mn - 1)) / + alignment_swizzled_mn * alignment_swizzled_mn + static_cast(mt0) * 128; + problem_sizes[t] = UnderlyingProblemShape(m, n, k); + stride_A[t] = cutlass::make_cute_packed_stride(StrideA{}, {m, k, 1}); + stride_B[t] = cutlass::make_cute_packed_stride(StrideB{}, {n, k, 1}); + stride_D[t] = cutlass::make_cute_packed_stride(StrideD{}, {m, n, 1}); + A_ptr[t] = inc_ptr(A, static_cast(row0) * static_cast(k)); + B_ptr[t] = inc_ptr(B, static_cast(i) * static_cast(n) * static_cast(k)); + D_ptr[t] = D + static_cast(row0) * static_cast(n); + layout_SFA[t] = ScaleConfig::tile_atom_to_shape_SFA( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFA_ptr[t] = inc_ptr(SFA, sf_m_offset * sf_k); + layout_SFB[t] = ScaleConfig::tile_atom_to_shape_SFB( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFB_ptr[t] = inc_ptr(SFB, static_cast(i) * sf_n * sf_k); +} + +// Chunk pass: CTA j of chunk c covers padded rows [(c * tb) * 128 + 16 j, + 16), two per warp. Grid tb * 8, 256 threads. +template +__global__ void __launch_bounds__(256) chunk_pass(BandParams p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // the chunk's GEMM has completed (its D is in memory) + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; +#pragma unroll 1 + for (int h = 0; h < 2; ++h) { + int const pr = (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp; + int const band = pr / 128; + int const e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + if (local < cnt) { + int const row = p.offsets[e] + local; + band_row(p, e, row, lane, pass, discard); + if (pass && local == cnt - 1) band_tail(p, e, lane, 32); + } + } +} + + +// ---- n360 pass schedules (ADDED; the served chunk_pass above is unchanged) ---- +// band_row split in two: load (the served loads, in the served order) and finish (everything after the loads, verbatim). +template +struct RowRegs { + uint4 raw[N2 / 2 / 16 / 8]; +}; + +template +__device__ __forceinline__ void band_row_load(BandParams const& p, int row, int lane, RowRegs& r) { + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8; + int const bl = lane / 4, part = lane % 4; + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + uint4 const* src = reinterpret_cast(drow); +#pragma unroll + for (int i = 0; i < ITERS; ++i) + r.raw[i] = __ldcg(src + (i * 8 + bl) * 4 + part); +} + +template +__device__ __forceinline__ void band_row_finish(BandParams const& p, int e, int row, int lane, RowRegs const& r, bool discard) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8, LINES = N2 * 2 / 128; + int const bl = lane / 4, part = lane % 4; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *p.w_den)); + float const wa = p.w_amax[e]; + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + float const scale = __fmul_rn(__fmul_rn(p.acc_amax[row], wa), rcp); + float const gamma = p.gammas[row]; + float v[ITERS][4]; + float bmax[ITERS]; + float m = 0.0f; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(&r.raw[i]); +#pragma unroll + for (int j = 0; j < 4; ++j) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j + 1]), scale))); + v[i][j] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, p.gate_cap, p.up_cap))); + } + bmax[i] = part_max<4>(v[i]); + m = fmaxf(m, bmax[i]); + } +#pragma unroll + for (int s = 4; s < 32; s *= 2) + m = fmaxf(m, __shfl_xor_sync(0xFFFFFFFF, m, s)); + float const amax = m; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + uint32_t packed; + uint8_t sbits; + quantize_part<4>(v[i], amax, bmax[i], packed, sbits); + store_part<4>(p.values, p.x_scales, p.offsets, e, row, i * 8 + bl, part, NH, packed, sbits); + } + if (lane == 0) p.amax_out[row] = amax; + if (discard) { + __syncwarp(); + for (int l = lane; l < LINES; l += 32) + discard_l2(drow + l * 64); + } +} + +// Map padded row pr of chunk c to (expert, row); returns false when pr is past its expert's rows (as served). +__device__ __forceinline__ bool pass_row(BandParams const& p, int experts, int pr, int& e, int& row, bool& last) { + int const band = pr / 128; + e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + row = p.offsets[e] + local; + last = local == cnt - 1; + return local < cnt; +} + +// PV 1 / 4: one row per warp, CTA j of chunk c covers padded rows (c * tb) * 128 + 8 j + warp. Grid tb * 16. +template +__device__ __forceinline__ void pass_one_row(BandParams const& p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; + int e, row; + bool last; + if (pass_row(p, experts, (c * tb) * 128 + blockIdx.x * 8 + warp, e, row, last)) { + band_row(p, e, row, lane, pass, discard); + if (pass && last) band_tail(p, e, lane, 32); + } +} + +// PV 2: the served row mapping (rows h * 8 + warp of the CTA's 16), the second row's loads before the first row's arithmetic. +template +__device__ __forceinline__ void pass_two_rows(BandParams const& p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const discard = p.mode <= 2; + int e[2], row[2]; + bool last[2], ok[2]; + RowRegs r[2]; +#pragma unroll + for (int h = 0; h < 2; ++h) { + ok[h] = pass_row(p, experts, (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp, e[h], row[h], last[h]); + if (ok[h]) band_row_load(p, row[h], lane, r[h]); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + if (ok[h]) { + band_row_finish(p, e[h], row[h], lane, r[h], discard); + if (last[h]) band_tail(p, e[h], lane, 32); + } + } +} + +template +__global__ void __launch_bounds__(256) chunk_pass_1(BandParams p, int experts, int c, int tb) { pass_one_row(p, experts, c, tb); } +template +__global__ void __launch_bounds__(256) chunk_pass_2(BandParams p, int experts, int c, int tb) { pass_two_rows(p, experts, c, tb); } +template +__global__ void __launch_bounds__(256, 4) chunk_pass_4(BandParams p, int experts, int c, int tb) { pass_one_row(p, experts, c, tb); } +// PV 3: the served chunk_pass body, verbatim, under __launch_bounds__(256, 4). +template +__global__ void __launch_bounds__(256, 4) chunk_pass_3(BandParams p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // the chunk's GEMM has completed (its D is in memory) + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; +#pragma unroll 1 + for (int h = 0; h < 2; ++h) { + int const pr = (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp; + int const band = pr / 128; + int const e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + if (local < cnt) { + int const row = p.offsets[e] + local; + band_row(p, e, row, lane, pass, discard); + if (pass && local == cnt - 1) band_tail(p, e, lane, 32); + } + } +} + +// F2 host entry: as gate_up_band (mode 2 pass + discard, 3 pass), with tb bands per chunk. int_ws must hold the args of every +// chunk (~300 B x experts x chunks). +void gate_up_chunks( + tvm::ffi::TensorView values, + tvm::ffi::TensorView weight, + tvm::ffi::TensorView scales, + tvm::ffi::TensorView weight_scales, + tvm::ffi::TensorView m_indptr, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_den, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView d, + tvm::ffi::TensorView out_values, + tvm::ffi::TensorView out_scales, + tvm::ffi::TensorView out_amax, + tvm::ffi::TensorView int_ws, + tvm::ffi::TensorView float_ws, + double gate_cap, + double up_cap, + int64_t mode, + int64_t raster, + int64_t tb, + int64_t sm_count, + int64_t pv) { + auto device = host::SymbolicDevice{}; + device.set_options(); + auto rows = host::SymbolicSize{"rows"}; + auto experts = host::SymbolicSize{"experts"}; + auto n = host::SymbolicSize{"n"}; + auto kp = host::SymbolicSize{"k/2"}; + host::TensorMatcher({rows, kp}).with_dtype().with_device(device).verify(values); + host::TensorMatcher({experts, n, kp}).with_dtype().with_device(device).verify(weight); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(out_amax); + host::TensorMatcher({experts}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_den); + host::TensorMatcher({rows, n}).with_dtype().with_device(device).verify(d); + int const G = static_cast(experts.unwrap()); + int const N = static_cast(n.unwrap()), K = static_cast(kp.unwrap()) * 2; + int64_t const R = rows.unwrap(); + CHECK_HOST(N == 2304) << "n52 chunk pass is compiled for gate_up width 2304, got " << N; + CHECK_HOST(m_indptr.size(0) == G + 1) << "m_indptr must hold experts + 1 offsets"; + CHECK_HOST(out_values.size(0) == R && out_values.size(1) == N / 4) << "out_values must be [rows, n / 4]"; + CHECK_HOST(out_scales.numel() >= (R + 127 * int64_t(G) + 127) / 128 * 128 * (N / 2 / 16)) << "out_scales too small"; + CHECK_HOST(mode == 2 || mode == 3) << "chunk mode must be 2 (pass + discard) or 3 (pass)"; + CHECK_HOST(tb >= 1 && tb <= 4096) << "tb (bands per chunk) out of range"; + CHECK_HOST(pv >= 0 && pv <= 4) << "n360 pass variant 0..4"; + int const bands = static_cast((R + 127 * int64_t(G)) / 128 + 1); + int const nchunks = static_cast((bands + tb - 1) / tb); + cudaStream_t stream = host::LaunchKernel::resolve_device(device.unwrap()); + + uint8_t* ib = static_cast(int_ws.data_ptr()); + size_t off = 0; + size_t const NC = size_t(nchunks) * G; + auto take = [&](size_t bytes) { + void* q = ib + off; + off += align16(bytes); + return q; + }; + auto problem_sizes = static_cast(take(NC * sizeof(UnderlyingProblemShape))); + auto A_ptr = static_cast(take(NC * sizeof(void*))); + auto B_ptr = static_cast(take(NC * sizeof(void*))); + auto D_ptr = static_cast(take(NC * sizeof(void*))); + auto SFA_ptr = static_cast(take(NC * sizeof(void*))); + auto SFB_ptr = static_cast(take(NC * sizeof(void*))); + auto stride_A = static_cast(take(NC * sizeof(StrideA))); + auto stride_B = static_cast(take(NC * sizeof(StrideB))); + auto stride_D = static_cast(take(NC * sizeof(StrideD))); + auto layout_SFA = static_cast(take(NC * sizeof(LayoutSFA))); + auto layout_SFB = static_cast(take(NC * sizeof(LayoutSFB))); + CHECK_HOST(off <= size_t(int_ws.numel())) << "int workspace too small: need " << off; + + cudaLaunchAttribute attrs[1]; + attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[0].val.programmaticStreamSerializationAllowed = true; + cudaLaunchConfig_t config{}; + config.gridDim = static_cast((NC + 255) / 256); + config.blockDim = 256; + config.stream = stream; + config.numAttrs = 1; + config.attrs = attrs; + cudaError_t st = cudaLaunchKernelEx( + &config, chunk_args, static_cast(values.data_ptr()), static_cast(weight.data_ptr()), + static_cast(scales.data_ptr()), static_cast(weight_scales.data_ptr()), + static_cast(d.data_ptr()), static_cast(m_indptr.data_ptr()), N, K, G, nchunks, static_cast(tb), + problem_sizes, A_ptr, B_ptr, SFA_ptr, SFB_ptr, D_ptr, stride_A, stride_B, stride_D, layout_SFA, layout_SFB); + CHECK_HOST(st == cudaSuccess) << "n52 chunk args launch: " << cudaGetErrorString(st); + + BandParams b; + b.mode = static_cast(mode); + b.counters = nullptr; + b.d = static_cast<__nv_bfloat16 const*>(d.data_ptr()); + b.n = N; + b.offsets = static_cast(m_indptr.data_ptr()); + b.acc_amax = static_cast(acc_amax.data_ptr()); + b.w_amax = static_cast(w_amax.data_ptr()); + b.w_den = static_cast(w_den.data_ptr()); + b.gammas = static_cast(gammas.data_ptr()); + b.values = static_cast(out_values.data_ptr()); + b.x_scales = static_cast(out_scales.data_ptr()); + b.amax_out = static_cast(out_amax.data_ptr()); + b.gate_cap = static_cast(gate_cap); + b.up_cap = static_cast(up_cap); + + cutlass::KernelHardwareInfo hw_info; + hw_info.device_id = device.unwrap().device_id; + hw_info.sm_count = static_cast(sm_count); + for (int c = 0; c < nchunks; ++c) { + size_t const o = size_t(c) * G; + typename Gemm::Arguments arguments{ + cutlass::gemm::GemmUniversalMode::kGrouped, + {G, problem_sizes + o, /*problem_sizes_host=*/nullptr}, + {A_ptr + o, stride_A + o, B_ptr + o, stride_B + o, SFA_ptr + o, layout_SFA + o, SFB_ptr + o, layout_SFB + o}, + {{}, nullptr, nullptr, D_ptr + o, stride_D + o}, + hw_info}; + auto& fusion_args = arguments.epilogue.thread; + fusion_args.alpha = 1.0f; + fusion_args.beta = 0; + fusion_args.alpha_ptr = nullptr; + fusion_args.dAlpha = {cute::_0{}, cute::_0{}, 0}; + using RasterOptions = decltype(arguments.scheduler.raster_order); + arguments.scheduler.raster_order = raster ? RasterOptions::AlongN : RasterOptions::AlongM; +#if !N381_PP + arguments.band.mode = -1; // F2: no in-kernel hook +#endif + Gemm gemm; + size_t const ws = Gemm::get_workspace_size(arguments); + CHECK_HOST(ws <= size_t(float_ws.numel())) << "float workspace too small: need " << ws; + CHECK_HOST(gemm.can_implement(arguments) == cutlass::Status::kSuccess) << "n52 chunk gemm cannot implement"; + CHECK_HOST(gemm.initialize(arguments, float_ws.data_ptr()) == cutlass::Status::kSuccess) << "n52 chunk gemm initialize"; + CHECK_HOST(gemm.run(stream, /*cuda_adapter=*/nullptr, /*launch_with_pdl=*/true) == cutlass::Status::kSuccess) + << "n52 chunk gemm run"; + cudaLaunchConfig_t pc{}; + pc.gridDim = static_cast(tb * ((pv == 1 || pv == 4) ? 16 : 8)); // n360: one row per warp doubles the CTAs + pc.blockDim = 256; + pc.stream = stream; + pc.numAttrs = 1; + pc.attrs = attrs; + auto pass_kernel = pv == 1 ? chunk_pass_1<2304> : pv == 2 ? chunk_pass_2<2304> : pv == 3 ? chunk_pass_3<2304> + : pv == 4 ? chunk_pass_4<2304> : chunk_pass<2304>; // n360 pass schedules; 0 = the served kernel + st = cudaLaunchKernelEx(&pc, pass_kernel, b, G, c, static_cast(tb)); + CHECK_HOST(st == cudaSuccess) << "n52 chunk pass launch: " << cudaGetErrorString(st); + } +} + +// --------------------------------------------------------------------------------------------------------------------------- +// L5 (lean standalone swiglu-quant) and C5 (its null twin): the image's nvfp4_swiglu_quantize_routed (routed_quant_sm120.cuh) +// line for line, except capped_swiglu -> N52_SWIGLU: the lean unit (N52_LEAN 1) runs the proven divide rewrite (L5), the plain +// unit runs the image's capped_swiglu (C5 = a copy of the image kernel: its timing is the copy null). Same launch (grid_size, +// split_threads, PDL wait + trigger), same device helpers, so outputs are the image kernel's bit for bit. +using sglang::inkling2_routed_quant_sm120::zero_expert_tail; + +template +__global__ void __launch_bounds__(sglang::inkling2_routed_quant::split_threads(N)) swiglu_quantize_l5( + __nv_bfloat16 const* __restrict__ acc, + float const* __restrict__ acc_amax, + float const* __restrict__ w_amax, + float const* __restrict__ w_denominator, + float const* __restrict__ gammas, + uint8_t* values, + uint8_t* x_scales, + float* amax_out, + int32_t const* __restrict__ offsets, + int32_t experts, + float gate_cap, + float up_cap) { + using namespace sglang::inkling2_routed_quant; + constexpr int kThreads = split_threads(N), kSplit = split(N), E = 16 / kSplit; + static_assert(N % 64 == 0 && kSplit > 1 && E % 4 == 0); + __shared__ int32_t s_offsets[kMaxExperts + 1]; + __shared__ float red[2][kThreads / 32]; + device::PDLWaitPrimary(); + device::PDLTriggerSecondary(); + load_offsets(offsets, experts, s_offsets); + int32_t const block = threadIdx.x / kSplit, part = threadIdx.x % kSplit; + bool const active = block < N / 16; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *w_denominator)); + int32_t parity = 0; + for (int32_t row = s_offsets[0] + blockIdx.x; row < s_offsets[experts]; row += gridDim.x, parity ^= 1) { + int32_t const expert = row_expert(s_offsets, experts, row); + float v[E]; +#pragma unroll + for (int i = 0; i < E; ++i) + v[i] = 0.0f; + if (active) { + uint4 raw[E / 4]; + uint4 const* src = reinterpret_cast(acc + int64_t(row) * 2 * N + block * 32 + part * 2 * E); +#pragma unroll + for (int i = 0; i < E / 4; ++i) + raw[i] = src[i]; + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(raw); + float scale = __fmul_rn(__fmul_rn(acc_amax[row], w_amax[expert]), rcp); + float gamma = gammas[row]; +#pragma unroll + for (int i = 0; i < E; ++i) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * i]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * i + 1]), scale))); + v[i] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, gate_cap, up_cap))); + } + } + float block_max = part_max(v); + float amax = block_max_reduce(block_max, red[parity]); + uint32_t packed; + uint8_t scale_bits; + quantize_part(v, amax, block_max, packed, scale_bits); + if (active) { + if (threadIdx.x == 0) amax_out[row] = amax; + store_part(values, x_scales, s_offsets, expert, row, block, part, N, packed, scale_bits); + } + if (row == s_offsets[expert + 1] - 1) zero_expert_tail(s_offsets, expert, x_scales, (N + 63) / 64 * 4); + } +} + +// = the image's nvfp4_swiglu_quantize host wrapper for N = 1152 (same checks, grid and PDL launch), kernel swiglu_quantize_l5. +void swiglu_quant_l5( + tvm::ffi::TensorView acc, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_denominator, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView values, + tvm::ffi::TensorView x_scales, + tvm::ffi::TensorView amax, + tvm::ffi::TensorView offsets, + double gate_cap, + double up_cap, + int64_t sm_count) { + using namespace sglang::inkling2_routed_quant; + constexpr int N = 1152; + constexpr int64_t kPart = 16 / split(N); + auto rows = host::SymbolicSize{"routed rows"}; + auto scale_rows = host::SymbolicSize{"scale rows"}; + auto device = host::SymbolicDevice{}; + device.set_options(); + int32_t const experts = sglang::inkling2_routed_quant_sm120::verify_offsets(offsets, device); + host::TensorMatcher({rows, 2 * N}).with_dtype().with_device(device).ensure_alignment(16).verify(acc); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(amax); + host::TensorMatcher({int64_t{experts}}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_denominator); + host::TensorMatcher({rows, N / 2}).with_dtype().with_device(device).ensure_alignment(kPart / 2).verify(values); + host::TensorMatcher({scale_rows, N / 16}).with_dtype().with_device(device).verify(x_scales); + int32_t const num_rows = sglang::inkling2_routed_quant_sm120::verify_rows(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_size(num_rows, static_cast(sm_count)), split_threads(N), device.unwrap()) + .enable_pdl(true)( + swiglu_quantize_l5, + static_cast<__nv_bfloat16 const*>(acc.data_ptr()), + static_cast(acc_amax.data_ptr()), + static_cast(w_amax.data_ptr()), + static_cast(w_denominator.data_ptr()), + static_cast(gammas.data_ptr()), + static_cast(values.data_ptr()), + static_cast(x_scales.data_ptr()), + static_cast(amax.data_ptr()), + static_cast(offsets.data_ptr()), + experts, + static_cast(gate_cap), + static_cast(up_cap)); +} + +} // namespace sglang::n381c_band diff --git a/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/sitecustomize.py b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/sitecustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54a31d3e1c33fdeb03422da3557650baafde6e --- /dev/null +++ b/recipe/stack/cands/n419c-8f01ac06/overlay_n419c/sitecustomize.py @@ -0,0 +1,129 @@ +"""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 os +import 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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/__init__.py b/recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e560bb783f1e181399bc9d8463c1b0371439384a --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/__init__.py @@ -0,0 +1,134 @@ +"""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, or +dflash_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 global +theta, the stock __init__ runs with the module's get_rope_config returning (global theta, the stock rope_scaling); every +other line of the stock layer is unchanged, and every other layer is built exactly as stock. No layer index is +hard-coded: the layer map comes from config.json. After construction the layer's rotary_emb.base must equal the +intended base (else the process stops). A non-null global_yarn_scale refuses (not supported). An MLA drafter with a +full_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's +context K with layer 0's rotary_emb (one cos_sin_cache). With per-layer bases that would rotate the global layers' context K with +the sliding base. So DFlashDraftModel.__init__ is wrapped too: when its layers' rotary bases differ, the instance's +supports_fused_context_kv is set False (the stock opt-out, dflash_worker_v2.py:1622), and context K/V take the stock sequential +path (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 os +import 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 True diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/_hook.py b/recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..d461a95a091b5c0581fc024013d31b28437df871 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_dfglobal/inkling_dfglobal/_hook.py @@ -0,0 +1,83 @@ +"""Post-import hooks: run a callback right after a module finishes executing. + +Patches attach lazily so that processes which never import the model pay nothing +and never import sglang or torch. If the target module is already imported, the +callback 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 the +loader the next one returned), so every package's callbacks run. +""" + +import importlib.abc +import sys +import 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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n320s/__init__.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n320s/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9daec93de1b3c7c2cbefbc0076a6cf4cc3ea08 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n320s/__init__.py @@ -0,0 +1,66 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/__init__.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00f48018d7f45b482883a0603699122ea004b98b --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/__init__.py @@ -0,0 +1,58 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/n329_rows.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/n329_rows.py new file mode 100644 index 0000000000000000000000000000000000000000..cd6068f702a78ffe6d70f414e098d4793fcb15ca --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/n329_rows.py @@ -0,0 +1,31 @@ +"""n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with the +layer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers.""" +import triton +import triton.language as tl +from triton.language.extra import libdevice # noqa: F401 +from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401 + + +@triton.jit +def _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) + diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/n329_rows_ctl.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/n329_rows_ctl.py new file mode 100644 index 0000000000000000000000000000000000000000..b36e7bdcb843262ee0a8795d5e001a232ae73f8e --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n329/n329_rows_ctl.py @@ -0,0 +1,31 @@ +"""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 the +layer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers.""" +import triton +import triton.language as tl +from triton.language.extra import libdevice # noqa: F401 +from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401 + + +@triton.jit +def _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 + diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n351/__init__.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n351/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..174048d0855b92121e5da00d2d63798911c84c38 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n351/__init__.py @@ -0,0 +1,68 @@ +"""inkling_n351: the MoE NVFP4 token quantize through an exact n351 variant (prefill seat, tree n351; enters the n320 package only +on 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 logging +import 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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n355/__init__.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n355/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c8994d08341841d16b9701c420e0e587a3fe861f --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n355/__init__.py @@ -0,0 +1,69 @@ +"""inkling_n355: the MXFP8 swiglu-quant (layers 20-23) through an exact n355 variant (prefill seat, tree n355; enters a package +only 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 logging +import os + +STATE = {"installed": False, "routed": 0, "served": 0, "variant": None} +MIN_ROWS = 4096 # routed rows = tokens x top_k: 512 tokens, the n14 prefill threshold +VARIANTS = (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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n381/__init__.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n381/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1276081848fd3ce2e98df4b6f92d629d7c4d6458 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n381/__init__.py @@ -0,0 +1,98 @@ +"""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 logging +import 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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/CREDITS.knapcio-v2.9.3.md b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/CREDITS.knapcio-v2.9.3.md new file mode 100644 index 0000000000000000000000000000000000000000..c21f38fd1177e6925575871e8052fa35d99fe663 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/CREDITS.knapcio-v2.9.3.md @@ -0,0 +1,94 @@ +# 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.1 +recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bit +draft 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. diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/LICENSE.knapcio-v2.9.3 b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/LICENSE.knapcio-v2.9.3 new file mode 100644 index 0000000000000000000000000000000000000000..272aceba2ac697cd358e703c7e849e738e9b83c3 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/LICENSE.knapcio-v2.9.3 @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Zbigniew Majewski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/NOTICE.knapcio-v2.9.3 b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/NOTICE.knapcio-v2.9.3 new file mode 100644 index 0000000000000000000000000000000000000000..d1ae19376d8e6f56690206da57d8a30de168440e --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/NOTICE.knapcio-v2.9.3 @@ -0,0 +1,54 @@ +Inkling-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; the +prompts 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. diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/NOTICE.n389 b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/NOTICE.n389 new file mode 100644 index 0000000000000000000000000000000000000000..9f3d6d5834274c2852cab6637ccb03b09267d2cc --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/NOTICE.n389 @@ -0,0 +1,3 @@ +inkling_n389/n389_fold.py contains a verbatim copy of _sconv_post_kernel from inkling_prologue/_triton.py (knapcio's inkling-2-mini +v2.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-p +recipe overlay) with an added store branch (FOLD) by the inkling2-spark prefill seat. diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/__init__.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab8bb1bd4a1a462044410baebacb6c7e532a517 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/__init__.py @@ -0,0 +1,307 @@ +"""inkling_n389: the KV-cache store folded into INKLING_PROLOGUE's SWA K / V kernel (prefill seat, tree n389; enters a package only +under 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 the +backend's store for that visit is skipped (FlashAttentionBackend.forward_extend gets save_kv_cache=False). Everything else is the +served 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 whose +store 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 a +visit the prologue would fuse logs its reason ONCE per distinct reason ('[inkling_n389] stock path: ...', with the values behind it), and +the 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 contextvars +import os +import 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, 1024 +BREAKABLE_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 True diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/n389_fold.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/n389_fold.py new file mode 100644 index 0000000000000000000000000000000000000000..e2205c2b7fe50be2528116486c3e0772373731c5 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/inkling_n389/n389_fold.py @@ -0,0 +1,93 @@ +"""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; served +file 24d2e3d9 in the S3b-p recipe overlay) plus five trailing parameters. With FOLD=False (the default) it is the served +kernel: the CPU check requires its PTX to equal the served kernel's for POST 1 and 2 (debug sections stripped). With +FOLD=True only the final store changes: row i of the BF16 result goes to Dst[Loc[i], :] instead of Y[i, :], and rows whose +slot is SKIP (store_cache's reserved_skip_index, the CUDA-graph padding slot 0) are not written. That is the served +store_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 torch +import triton +import triton.language as tl + +from inkling_prologue import HEAD, SUM_ORDER +from inkling_prologue._triton import _row_sumsq, rsqrt_approx_f32 + + +@triton.jit +def _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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n351_quant.cuh b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n351_quant.cuh new file mode 100644 index 0000000000000000000000000000000000000000..f71f8f11e828a889533de670f85efd6061525288 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n351_quant.cuh @@ -0,0 +1,175 @@ +// 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 + +#include + +#include "routed_quant_sm120.cuh" +#include + +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 +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 +__device__ __forceinline__ void load_part(__nv_bfloat16 const* src, float (&v)[E]) { + if constexpr (E == 8) { + uint4 raw = *reinterpret_cast(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(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 +__global__ void __launch_bounds__(Cfg::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::kThreads, kSplit = Cfg::kSplit, E = Cfg::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(); + device::PDLTriggerSecondary(); + 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(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(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(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(v); + float amax = block_max_reduce(block_max, red[parity]); // its __syncthreads also publishes s_row / s_exp + uint32_t packed; + uint8_t scale; + quantize_part(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(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(std::max(1, std::min(tokens, g))); +} + +// = n14_quant::nvfp4_quantize_tokens (same checks, grid rule and PDL launch) with the variant kernel. +template +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::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(); + int32_t const experts = verify_offsets(offsets, device); + host::TensorMatcher({tokens, K}).with_dtype().with_device(device).ensure_alignment(kPart * 2).verify(x); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(src2dst); + host::TensorMatcher({rows, K / 2}).with_dtype().with_device(device).ensure_alignment(kPart / 2).verify(values); + host::TensorMatcher({scale_rows, K / 16}).with_dtype().with_device(device).verify(x_scales); + host::TensorMatcher({rows}).with_dtype().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::kThreads, device.unwrap()) + .enable_pdl(true)( + nvfp4_quantize_tokens_kernel, + static_cast<__nv_bfloat16 const*>(x.data_ptr()), + static_cast(src2dst.data_ptr()), + static_cast(values.data_ptr()), + static_cast(x_scales.data_ptr()), + static_cast(amax.data_ptr()), + static_cast(offsets.data_ptr()), + num_tokens, + static_cast(top_k), + experts); +} + +} // namespace sglang::n351_quant diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n355_quant.cuh b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n355_quant.cuh new file mode 100644 index 0000000000000000000000000000000000000000..3c517a75bd8c6620ad921aba426411f3c9eb9a12 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n355_quant.cuh @@ -0,0 +1,216 @@ +// 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 + +#include + +#include "routed_quant_sm120.cuh" +#include + +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 +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 +__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(); + 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(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(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 +__global__ void __launch_bounds__(Cfg::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; + static_assert(N % 128 == 0 && N / 16 <= 1024); + constexpr bool kHoist = V & 1, kPrefetch = V & 2; + device::PDLWaitPrimary(); + 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(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(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 +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; + auto rows = host::SymbolicSize{"routed rows"}; + auto device = host::SymbolicDevice{}; + device.set_options(); + int32_t const experts = verify_offsets(offsets, device); + host::TensorMatcher({rows, 2 * N}) // + .with_dtype() + .with_device(device) + .ensure_alignment(16) + .verify(x); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(gammas); + host::TensorMatcher({rows, N}) // + .with_dtype() + .with_device(device) + .ensure_alignment(16) + .verify(values); + host::TensorMatcher({N / 128, m_padded}).with_dtype().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::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(sm_count)) // the image's launch for the copy + : std::max(1, std::min(iters, C::kGridMul * static_cast(sm_count))); + auto* kernel = V == 0 ? mxfp8_swiglu_quantize_copy : mxfp8_swiglu_quantize_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(gammas.data_ptr()), + static_cast(values.data_ptr()), + static_cast(exponents.data_ptr()), + static_cast(offsets.data_ptr()), + experts, + static_cast(gate_cap), + static_cast(up_cap), + static_cast(m_padded)); +} + +} // namespace sglang::n355_quant diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n381c_band.cuh b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n381c_band.cuh new file mode 100644 index 0000000000000000000000000000000000000000..ab6b42d35169e84e705a098312e5ab14466f2c99 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/n381c_band.cuh @@ -0,0 +1,2062 @@ +// n381c (prefill seat, n381 implementation 3 + package rider unit): = work_moe/n360/kit/n360_band.cuh (n360-1's reviewed pass-variant source, +// b41a11aa) + n381-2's edits (825eaa0e, KEEP): tile_k = N381_TILE_K; with N381_PP 1 the F2 chunk GEMM is the stock CUTLASS ptr-array PING-PONG +// kernel (F2 runs the hook off), F1's gate_up_band compiled out; namespace sglang::n381c_band, class N381CKernel. Pass variants pv 0..4 as n360 +// (0 = the served chunk_pass). Same tile / K order / mma / epilogue and pass arithmetic: bitwise expected (n381-2 v2 and n360-1 p1 both exact). +// n360 F2b chunk-pass schedules: GENERATED by work_moe/n360/kit/gen_n360.py from n52_band.cuh e855abc8 (asserted edits + added pass kernels). +// SPDX-License-Identifier: Apache-2.0 +// n52 F1 (inkling2-spark moe seat, 2026-11-23): the SM120 MoE prefill visit's NVFP4 gate_up grouped GEMM with the swiglu + +// NVFP4 quantization done per 128-row band from L2 by the CTA that finishes the band's last tile ("band pass"). +// GENERATED by work_moe/n52/gen_n52.py from n52_head.cuh + CUTLASS's ptr-array cooperative kernel + n52_tail.cuh. +// +// - GEMM: FlashInfer 0.7.4's CutlassNVFP4GroupwiseScaledGroupGEMMSM120<128, 128, 256, SwapAB false> types (the served config +// above 3,072 tokens at K 2,304) with the stock BF16 TMA epilogue, so D = the served gate_up output bit for bit. +// - After each tile's epilogue store, the TMA-issuing warp waits for its bulk stores, fences the async proxy and the GPU, and +// thread 0 adds 1 to the band's counter (band = one 128-row M-tile of one expert, numbered like the SFA layout). The CTA +// whose add makes N / 128 (= 18) runs the band pass. +// - Band pass = the image's nvfp4_swiglu_quantize_routed arithmetic (its own device helpers from routed_quant.cuh, E = 4 lanes +// per 16-value block as the image's split for width 1,152) over the band's rows: D read with ld.global.cg (L2), per row +// scale and gamma loaded once, v = bf16(capped_swiglu(bf16(D * scale) pairs)), row amax, quantize_part, store_part, the +// expert's scale tail zeroed on its last band; then discard.global.L2 on the row's D lines (never written back). +// - mode (runtime): -1 stock (no hook), 0 signal only, 1 discard only, 2 pass + discard (the form), 3 pass without discard. +#include + +#include + +#include + +#include "routed_quant_sm120.cuh" + +#include "cute/tensor.hpp" +#include "cutlass/cutlass.h" +#include "cutlass/detail/sm100_blockscaled_layout.hpp" +#include "cutlass/epilogue/collective/collective_builder.hpp" +#include "cutlass/gemm/collective/collective_builder.hpp" +#include "cutlass/gemm/device/gemm_universal_adapter.h" +#include "cutlass/gemm/group_array_problem_shape.hpp" +#include "cutlass/gemm/kernel/gemm_universal.hpp" +#include "cutlass/util/packed_stride.hpp" + +#include + +namespace sglang::n381c_band { + +struct BandParams { + int mode = -1; // -1 stock, 0 signal, 1 discard, 2 pass + discard, 3 pass + int* counters = nullptr; // [bands], zero on entry; the last arriver resets its band to 0 + __nv_bfloat16 const* d = nullptr; // [rows, n] gate_up D (BF16), the GEMM's output + int n = 0; // gate_up width (2 x the swiglu width) + int const* offsets = nullptr; // [experts + 1] expert row offsets (m_indptr) + float const* acc_amax = nullptr; // [rows] amax of the quantized A rows + float const* w_amax = nullptr; // [experts] + float const* w_den = nullptr; // [1] + float const* gammas = nullptr; // [rows] + uint8_t* values = nullptr; // [rows, n / 4] NVFP4 of v + uint8_t* x_scales = nullptr; // SFA layout, 128-row padding per expert + float* amax_out = nullptr; // [rows] + float gate_cap = 0.f; + float up_cap = 0.f; +}; + +constexpr int kBandBarrier = 14; // named barrier id (CUTLASS reserves the low ids) +constexpr int kTileN = 128; + +// bar.red.or over the 256 consumer threads: returns 1 in every thread if any thread passed a nonzero pred. +__device__ __forceinline__ int bar_red_or(int pred) { + int r; + asm volatile( + "{ .reg .pred p, q; setp.ne.s32 p, %1, 0; bar.red.or.pred q, %2, %3, p; selp.s32 %0, 1, 0, q; }" + : "=r"(r) + : "r"(pred), "n"(kBandBarrier), "n"(256) + : "memory"); + return r; +} + +__device__ __forceinline__ void discard_l2(void const* p) { + asm volatile("discard.global.L2 [%0], 128;" ::"l"(p) : "memory"); +} + +#if defined(N52_LEAN) && N52_LEAN +// Build 2 ("lean"), for the checkpoint's caps (gate 4, up 25) only: n52_moe.py refuses lean for other caps. The image's +// capped_swiglu with its two IEEE divides replaced where provably equal on BF16 inputs (work_moe/n52/cpu/div25_proof.py, +// exact rationals over all 65,280 finite BF16 values: PASS): gate / 4 -> gate * 0.25; up / 25 -> q0 = up * RN(1/25), +// rem = fma(-q0, 25, up), fma(rem, RN(1/25), q0); a non-finite up takes the IEEE divide. gate and up are BF16-rounded before +// this call, as in the image kernel; sigmoid, tanh and the multiplies are the image's instructions in the image's order. +__device__ __forceinline__ float capped_swiglu_lean(float gate, float up, float gamma, float, float) { + float sigmoid; + asm("{ .reg .f32 t; mul.rn.f32 t, %1, 0fBFB8AA3B; " + "ex2.approx.ftz.f32 t, t; add.rn.f32 t, t, 0f3F800000; " + "rcp.approx.ftz.f32 %0, t; }" + : "=f"(sigmoid) + : "f"(gate)); + float t; + asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(__fmul_rn(gate, 0.25f))); + gate = __fmul_rn(4.0f, t); + float q = __fmul_rn(up, 0.04f); + q = __fmaf_rn(__fmaf_rn(-q, 25.0f, up), 0.04f, q); + if (!isfinite(up)) q = __fdiv_rn(up, 25.0f); + asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(q)); + up = __fmul_rn(25.0f, t); + return __fmul_rn(__fmul_rn(__fmul_rn(gate, sigmoid), up), gamma); +} +#define N52_SWIGLU capped_swiglu_lean +#else +#define N52_SWIGLU capped_swiglu +#endif + +// One row of expert e by one warp: lane = (block within the 8-block group) * 4 + part, as the image's E = 4 split, 9 groups of +// 8 blocks per 1,152-wide row. Used by the band pass (F1, one warp per row of the band) and the chunk pass (F2). +template +__device__ __forceinline__ void band_row(BandParams const& p, int e, int row, int lane, bool pass, bool discard) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8, LINES = N2 * 2 / 128; + static_assert(NH % 128 == 0 && N2 * 2 % 128 == 0, "whole 8-block groups and whole 128-byte lines per row"); + static_assert(split(NH) == 4, "the image quantizes width NH with E = 4 (4 lanes per block)"); + int const bl = lane / 4, part = lane % 4; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *p.w_den)); + float const wa = p.w_amax[e]; + { + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + if (pass) { + uint4 raw[ITERS]; + uint4 const* src = reinterpret_cast(drow); +#pragma unroll + for (int i = 0; i < ITERS; ++i) + raw[i] = __ldcg(src + (i * 8 + bl) * 4 + part); // block b = 8i + bl: D columns 32b + 8 part .. + 8 + float const scale = __fmul_rn(__fmul_rn(p.acc_amax[row], wa), rcp); + float const gamma = p.gammas[row]; + float v[ITERS][4]; + float bmax[ITERS]; + float m = 0.0f; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(&raw[i]); +#pragma unroll + for (int j = 0; j < 4; ++j) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j + 1]), scale))); + v[i][j] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, p.gate_cap, p.up_cap))); + } + bmax[i] = part_max<4>(v[i]); // max over the block's 16 values (xor 1, 2 within the lane quad) + m = fmaxf(m, bmax[i]); + } +#pragma unroll + for (int s = 4; s < 32; s *= 2) // the other 7 blocks of each group: all 72 block maxima of the row + m = fmaxf(m, __shfl_xor_sync(0xFFFFFFFF, m, s)); + float const amax = m; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + uint32_t packed; + uint8_t sbits; + quantize_part<4>(v[i], amax, bmax[i], packed, sbits); + store_part<4>(p.values, p.x_scales, p.offsets, e, row, i * 8 + bl, part, NH, packed, sbits); + } + if (lane == 0) p.amax_out[row] = amax; + } + if (discard) { + __syncwarp(); // every lane's loads of this row have returned (their values were consumed above) + for (int l = lane; l < LINES; l += 32) + discard_l2(drow + l * 64); + } + } +} + +// One band's rows, one warp per row (rows w, w + 8, ...). +template +__device__ __forceinline__ void band_rows(BandParams const& p, int e, int r0, int r1, int tid, bool pass, bool discard) { + int const warp = tid / 32, lane = tid % 32; + for (int row = r0 + warp; row < r1; row += 8) + band_row(p, e, row, lane, pass, discard); +} + +// zero_expert_tail for the expert's last 128-row tile (the image's bytes), by threads tid = 0 .. nthreads - 1. +template +__device__ __forceinline__ void band_tail(BandParams const& p, int e, int tid, int nthreads = 256) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, SCALE_K = (NH + 63) / 64 * 4, ATOMS = SCALE_K / 4; + int const count = p.offsets[e + 1] - p.offsets[e]; + int const used = count % 128; + if (used == 0) return; + uint8_t* tile = p.x_scales + scale_base(p.offsets, e, SCALE_K) + int64_t(count / 128) * ATOMS * 512; + for (int item = tid; item < ATOMS * 32; item += nthreads) { + int const lane = item % 32; + uint32_t* atom = reinterpret_cast(tile + (item / 32) * 512 + lane * 16); +#pragma unroll + for (int i = 0; i < 4; ++i) + if (lane + 32 * i >= used) atom[i] = 0; + } +} + +// Called by all 256 consumer threads after each tile's epilogue store (tid = mma_thread_idx; warp 0 issued the TMA stores). +template +__device__ __forceinline__ void n52_band_hook(BandParams const& p, int e, int mt, int n, int tid) { + if (tid < 32) { + asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); // this tile's D stores are complete (not just read) + asm volatile("fence.proxy.async.global;" ::: "memory"); // async-proxy writes ordered before generic accesses + __syncwarp(); + } + int const base = p.offsets[0]; + int const band = (p.offsets[e] - base + e * 127) / 128 + mt; + int last = 0; + if (tid == 0) { + __threadfence(); + int const old = atomicAdd(p.counters + band, 1); + __threadfence(); + last = old == (n + kTileN - 1) / kTileN - 1; + } + if (!bar_red_or(last)) return; + __threadfence(); + if (p.mode >= 1) { + int const r0 = p.offsets[e] + mt * 128; + int const r1 = min(r0 + 128, p.offsets[e + 1]); + bool const pass = p.mode >= 2, discard = p.mode <= 2; + if (n == N2) { + band_rows(p, e, r0, r1, tid, pass, discard); + if (pass && r1 == p.offsets[e + 1]) band_tail(p, e, tid); + } + } + if (tid == 0) p.counters[band] = 0; +} + +} // namespace sglang::n381c_band + +namespace cutlass::gemm::kernel { + +// ---- N381CKernel: cutlass/gemm/kernel/sm90_gemm_array_tma_warpspecialized_cooperative.hpp (md5 3b39c38d712b5f27af49baea07e8c8b4) with the n52 edits ---- +using sglang::n381c_band::BandParams; +using sglang::n381c_band::n52_band_hook; + +template < + class ProblemShape_, + class CollectiveMainloop_, + class CollectiveEpilogue_, + class TileScheduler_ +> +class N381CKernel +{ + // Get the type of the scheduler response. + template + struct TileSchedulerResponseGetter { + using Type = typename TileScheduler::CLCResponse; + }; + + template + struct TileSchedulerResponseGetter> { + using Type = typename TileScheduler::SchedulerResponse; + }; + +public: + // + // Type Aliases + // + using ProblemShape = ProblemShape_; + static_assert(rank(typename ProblemShape::UnderlyingProblemShape{}) == 3 or rank(typename ProblemShape::UnderlyingProblemShape{}) == 4, + "ProblemShape{} should be or "); + + static_assert(cute::is_base_of_v); + + static constexpr bool IsGdcEnabled = false; + + // Mainloop derived types + using CollectiveMainloop = CollectiveMainloop_; + using TileShape = typename CollectiveMainloop::TileShape; + using TiledMma = typename CollectiveMainloop::TiledMma; + using ArchTag = typename CollectiveMainloop::ArchTag; + using ElementA = typename CollectiveMainloop::ElementA; + using StrideA = typename CollectiveMainloop::StrideA; + using InternalStrideA = typename CollectiveMainloop::InternalStrideA; + using ElementB = typename CollectiveMainloop::ElementB; + using InternalStrideB = typename CollectiveMainloop::InternalStrideB; + using StrideB = typename CollectiveMainloop::StrideB; + using DispatchPolicy = typename CollectiveMainloop::DispatchPolicy; + using Schedule = typename DispatchPolicy::Schedule; + using ElementAccumulator = typename CollectiveMainloop::ElementAccumulator; + using ClusterShape = typename DispatchPolicy::ClusterShape; + using MainloopArguments = typename CollectiveMainloop::Arguments; + using MainloopParams = typename CollectiveMainloop::Params; + + // Epilogue derived types + using CollectiveEpilogue = CollectiveEpilogue_; + using ElementC = typename CollectiveEpilogue::ElementC; + using StrideC = typename CollectiveEpilogue::StrideC; + using InternalStrideC = typename CollectiveEpilogue::InternalStrideC; + using ElementD = typename CollectiveEpilogue::ElementD; + using StrideD = typename CollectiveEpilogue::StrideD; + using InternalStrideD = typename CollectiveEpilogue::InternalStrideD; + using EpilogueArguments = typename CollectiveEpilogue::Arguments; + using EpilogueParams = typename CollectiveEpilogue::Params; + + static_assert(ArchTag::kMinComputeCapability >= 90); + + static constexpr bool IsGroupedGemmKernel = !cute::is_same_v; + static constexpr uint32_t MinTensorMapWorkspaceAlignment = 64; + + static_assert( + cute::is_void_v + or ( + IsGroupedGemmKernel + and cute::is_any_of_v + ), + "Ptr-Array Cooperative and Grouped Gemm Cooperative kernel only supports the default scheduler."); + + using SchedulerTag = cute::conditional_t< + cute::is_void_v, + cute::conditional_t< + IsGroupedGemmKernel, + GroupScheduler, // Special grouped gemm scheduler + void // Default scheduler for non-grouped kernels + >, + TileScheduler_ + >; + + using TileScheduler = typename detail::TileSchedulerSelector< + SchedulerTag, + ArchTag, + TileShape, + ClusterShape, + 8, // SchedulerPipelineStageCount -- Grouped GEMM scheduler will benefit from a larger number of stages. + cute::conditional_t, void, ProblemShape> // Use void for default scheduler. + >::Scheduler; + + using TileSchedulerArguments = typename TileScheduler::Arguments; + using TileSchedulerParams = typename TileScheduler::Params; + using TileSchedulerResponse = typename TileSchedulerResponseGetter::Type; + + static constexpr auto TileSchedulerStages = 8; + + static constexpr uint32_t NumLoadWarpGroups = 1; + static constexpr uint32_t NumMmaThreads = size(TiledMma{}); + static constexpr uint32_t NumMmaWarpGroups = NumMmaThreads / NumThreadsPerWarpGroup; + static constexpr uint32_t MaxThreadsPerBlock = NumMmaThreads + (NumLoadWarpGroups * NumThreadsPerWarpGroup); + static constexpr uint32_t MinBlocksPerMultiprocessor = 1; + static constexpr uint32_t NumProducerThreads = CollectiveMainloop::NumProducerThreadEvents; + static constexpr bool IsMainloopAuxiliaryLoadNeeded = detail::HasAuxiliaryLoad_v; + + /// Register requirement for Load and Math WGs + static constexpr int RegsPerThread = + 2 * size<0>(TileShape{}) * size<1>(TileShape{}) / NumMmaThreads * + sizeof(ElementAccumulator) / sizeof(uint32_t); + + // Detect if this is SM120 blockscaled kernel which hits low register pressure + // on smaller tiles + template + struct IsSm120BlockScaled : cute::false_type {}; + + template + struct IsSm120BlockScaled> + : cute::true_type {}; + + static constexpr bool IsLowRegisterPressure = IsSm120BlockScaled::value && (RegsPerThread <= 64); + + /// Register requirement for Load and Math WGs + static constexpr uint32_t LoadRegisterRequirement = 40; + static constexpr uint32_t MmaRegisterRequirement = 232; + + static constexpr bool IsSm120Family = cute::is_same_v; + + // 1 stage ordered sequence between mainloop and epilogue producer load threads + using LoadWarpOrderBarrier = cutlass::OrderedSequenceBarrier<1,2>; + + // Kernel level shared memory storage + struct SharedStorage { + struct TensorStorage : cute::aligned_struct<128, _1> { + using MainloopTensorStorage = typename CollectiveMainloop::TensorStorage; + using EpilogueTensorStorage = typename CollectiveEpilogue::TensorStorage; + + MainloopTensorStorage mainloop; + EpilogueTensorStorage epilogue; + } tensors; + + struct PipelineStorage : cute::aligned_struct<16, _1> { + using TileSchedulerPipelineStorage = typename TileScheduler::PipelineStorage; + using MainloopPipelineStorage = typename CollectiveMainloop::PipelineStorage; + using EpiLoadPipelineStorage = typename CollectiveEpilogue::PipelineStorage; + + alignas(16) TileSchedulerPipelineStorage scheduler; + alignas(16) MainloopPipelineStorage mainloop; + alignas(16) EpiLoadPipelineStorage epi_load; + alignas(16) typename LoadWarpOrderBarrier::SharedStorage load_order; + } pipelines; + + alignas(16) TileSchedulerResponse scheduler_response[TileSchedulerStages]; + + struct TensorMapStorage : cute::aligned_struct<128, _1> { + using MainloopTensorMapStorage = typename CollectiveMainloop::TensorMapStorage; + using EpilogueTensorMapStorage = typename CollectiveEpilogue::TensorMapStorage; + + alignas(128) MainloopTensorMapStorage mainloop; + alignas(128) EpilogueTensorMapStorage epilogue; + } tensormaps; + }; + + static constexpr int SharedStorageSize = sizeof(SharedStorage); + + // Device side arguments + struct Arguments { + GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopArguments mainloop{}; + EpilogueArguments epilogue{}; + KernelHardwareInfo hw_info{}; + TileSchedulerArguments scheduler{}; + BandParams band{}; // n52 + }; + + // Kernel entry point API + struct Params { + GemmUniversalMode mode{}; + ProblemShape problem_shape{}; + MainloopParams mainloop{}; + EpilogueParams epilogue{}; + KernelHardwareInfo hw_info{}; + TileSchedulerParams scheduler{}; + void* workspace{nullptr}; + BandParams band{}; // n52 + }; + + // + // Methods + // + + // Convert to underlying arguments. In this case, a simple copy for the aliased type. + static + Params + to_underlying_arguments(Arguments const& args, void* workspace) { + CUTLASS_TRACE_HOST("to_underlying_arguments():"); + + ProblemShape problem_shapes = args.problem_shape; + + // Get SM count if needed, otherwise use user supplied SM count + int sm_count = args.hw_info.sm_count; + if (sm_count <= 0) { + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid SM count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the SM count."); + sm_count = KernelHardwareInfo::query_device_multiprocessor_count(args.hw_info.device_id); + } + CUTLASS_TRACE_HOST("to_underlying_arguments(): Setting persistent grid SM count to " << sm_count); + + // Get maximum number of clusters that could co-exist on the target device + int max_active_clusters = args.hw_info.max_active_clusters; + if (max_active_clusters <= 0) { + max_active_clusters = 0; + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid max cluster count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the max_active_clusters."); + } + else { + CUTLASS_TRACE_HOST("to_underlying_arguments(): Setting persistent grid cluster count to " << max_active_clusters); + } + + KernelHardwareInfo hw_info{args.hw_info.device_id, sm_count, max_active_clusters}; + + // Calculate workspace pointers + uint8_t* workspace_ptr = reinterpret_cast(workspace); + size_t workspace_offset = 0; + + void* epilogue_workspace = workspace_ptr + workspace_offset; + workspace_offset += CollectiveEpilogue::get_workspace_size(problem_shapes, args.epilogue, sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + void* mainloop_workspace = workspace_ptr + workspace_offset; + workspace_offset += CollectiveMainloop::get_workspace_size(problem_shapes, args.mainloop, sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + void* scheduler_workspace = workspace_ptr + workspace_offset; + workspace_offset += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + + TileSchedulerParams scheduler; + if constexpr (IsGroupedGemmKernel) { + scheduler = TileScheduler::to_underlying_arguments( + problem_shapes, TileShape{}, ClusterShape{}, hw_info, args.scheduler, scheduler_workspace); + } + else { + scheduler = TileScheduler::to_underlying_arguments( + problem_shapes.get_host_problem_shape(), TileShape{}, ClusterShape{}, hw_info, args.scheduler, scheduler_workspace); + } + + return { + args.mode, + problem_shapes, + CollectiveMainloop::to_underlying_arguments(problem_shapes, args.mainloop, mainloop_workspace), + CollectiveEpilogue::to_underlying_arguments(problem_shapes, args.epilogue, epilogue_workspace), + hw_info, + scheduler, + workspace, + args.band // n52 + }; + } + + static bool + can_implement(Arguments const& args) { + bool implementable = true; + if constexpr (IsGroupedGemmKernel) { + // Group GEMM currently only supports rank-3 problem shapes + implementable &= (args.mode == GemmUniversalMode::kGrouped && rank(typename ProblemShape::UnderlyingProblemShape{}) == 3); + } + else { + implementable &= (args.mode == GemmUniversalMode::kArray && rank(typename ProblemShape::UnderlyingProblemShape{}) == 4); + } + if (!implementable) { + CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Arguments or Problem Shape don't meet the requirements for Ptr Array Gemm or Grouped Gemm.\n"); + return implementable; + } + implementable &= CollectiveMainloop::can_implement(args.problem_shape, args.mainloop); + implementable &= CollectiveEpilogue::can_implement(args.problem_shape, args.epilogue); + implementable &= TileScheduler::can_implement(args.scheduler); + return implementable; + } + + static size_t + get_workspace_size(Arguments const& args) { + size_t workspace_size = 0; + constexpr uint32_t NumEpilogueSubTiles = CollectiveEpilogue::get_store_pipe_increment(TileShape{}); + + // Get SM count if needed, otherwise use user supplied SM count + int sm_count = args.hw_info.sm_count; + if (sm_count <= 0) { + CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid SM count.\n" + " For optimal performance, populate the arguments KernelHardwareInfo struct with the SM count."); + sm_count = KernelHardwareInfo::query_device_multiprocessor_count(args.hw_info.device_id); + } + + workspace_size += CollectiveEpilogue::get_workspace_size(args.problem_shape, args.epilogue, sm_count); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + workspace_size += CollectiveMainloop::get_workspace_size(args.problem_shape, args.mainloop, sm_count); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + workspace_size += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles); + workspace_size = round_nearest(workspace_size, MinTensorMapWorkspaceAlignment); + + return workspace_size; + } + + static cutlass::Status + initialize_workspace(Arguments const& args, void* workspace = nullptr, cudaStream_t stream = nullptr, + CudaHostAdapter* cuda_adapter = nullptr) { + Status status = Status::kSuccess; + uint8_t* workspace_ptr = reinterpret_cast(workspace); + size_t workspace_offset = 0; + constexpr uint32_t NumEpilogueSubTiles = CollectiveEpilogue::get_store_pipe_increment(TileShape{}); + static constexpr uint32_t NumAccumulatorMtxs = 1; + + status = CollectiveEpilogue::initialize_workspace(args.problem_shape, args.epilogue, workspace_ptr + workspace_offset, stream, cuda_adapter); + workspace_offset += CollectiveEpilogue::get_workspace_size(args.problem_shape, args.epilogue, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + status = CollectiveMainloop::initialize_workspace(args.problem_shape, args.mainloop, workspace_ptr + workspace_offset, stream, cuda_adapter); + workspace_offset += CollectiveMainloop::get_workspace_size(args.problem_shape, args.mainloop, args.hw_info.sm_count); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + + status = TileScheduler::template initialize_workspace( + args.scheduler, workspace_ptr + workspace_offset, stream, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles, NumAccumulatorMtxs, cuda_adapter); + workspace_offset += TileScheduler::template get_workspace_size( + args.scheduler, typename ProblemShape::UnderlyingProblemShape{}, args.hw_info, NumMmaWarpGroups, NumEpilogueSubTiles); + workspace_offset = round_nearest(workspace_offset, MinTensorMapWorkspaceAlignment); + if (status != Status::kSuccess) { + return status; + } + return status; + } + + // Computes the kernel launch grid shape based on runtime parameters + static dim3 + get_grid_shape(Params const& params) { + // Given device SM count, set grid size s.t. we do not launch more thread blocks than we can run concurrently + TileSchedulerArguments args{}; + args.raster_order = params.scheduler.raster_order_ == TileScheduler::RasterOrder::AlongN ? TileScheduler::RasterOrderOptions::AlongN : TileScheduler::RasterOrderOptions::AlongM; + dim3 grid_shape; + if constexpr (IsGroupedGemmKernel) { + grid_shape = TileScheduler::get_grid_shape(params.scheduler, params.problem_shape, TileShape{}, ClusterShape{}, params.hw_info, args); + } + else { + grid_shape = TileScheduler::get_grid_shape(params.scheduler, params.problem_shape.get_host_problem_shape(), TileShape{}, ClusterShape{}, params.hw_info, args); + } + return grid_shape; + } + + static dim3 + get_block_shape() { + return dim3(MaxThreadsPerBlock, 1, 1); + } + + CUTLASS_DEVICE + void + operator()(Params const& params, char* smem_buf) { + using namespace cute; + using X = Underscore; + +# if (defined(__CUDA_ARCH_FEAT_SM90_ALL) || defined(__CUDA_ARCH_FEAT_SM120_ALL) || defined(__CUDA_ARCH_FEAT_SM121_ALL) ||\ + CUDA_ARCH_CONDITIONAL_OR_FAMILY(1200) || CUDA_ARCH_CONDITIONAL_OR_FAMILY(1210)) +# define ENABLE_SM90_KERNEL_LEVEL 1 +# endif + +// Any Tensor Op MMA Atom in the ISA is arch conditional. +#if ! defined(ENABLE_SM90_KERNEL_LEVEL) + CUTE_INVALID_CONTROL_PATH("ERROR : Arch conditional MMA instruction used without targeting appropriate compute capability. Aborting.\n"); +#else + + // Preconditions + static_assert(size(TiledMma{}) == 256, "Cooperative kernel must have TiledMMA operating using 256 threads."); + static_assert(size<0>(TileShape{}) >= 128, + "Cooperative kernel requires Tile Size to be greater than or equal to 128 along the M-dimension."); + static_assert(NumMmaWarpGroups == 2, "Cooperative kernels currently only support NumMmaWarpGroups == 2"); + + if constexpr (cutlass::epilogue::collective::detail::sm90_is_ptr_array_tma_dispatch_policy_v) { + static_assert(NumMmaWarpGroups == CollectiveEpilogue::NumEpilogueWarpGroups, + "Tiled MmA does not match expected warp groups performing the epilogue"); + } + + static_assert(cute::rank(InternalStrideA{}) == 3, "StrideA must be rank-3: [M, K, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideB{}) == 3, "StrideB must be rank-3: [N, K, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideC{}) == 3, "StrideC must be rank-3: [M, N, L]. If batch mode is not needed, set L stride to Int<0>."); + static_assert(cute::rank(InternalStrideD{}) == 3, "StrideD must be rank-3: [M, N, L]. If batch mode is not needed, set L stride to Int<0>."); + + /* In the Cooperative kernel, Consumer0 and Consumer1 collaborate on the same tile */ + enum class WarpGroupRole { + Producer = 0, + Consumer0 = 1, + Consumer1 = 2 + }; + enum class ProducerWarpRole { + Mainloop = 0, + MainloopAux = 1, + Epilogue = 2, + Scheduler = 3 + }; + + // Kernel level shared memory storage + SharedStorage& shared_storage = *reinterpret_cast(smem_buf); + + // In a warp specialized kernel, collectives expose data movement and compute operations separately + CollectiveMainloop collective_mainloop; + CollectiveEpilogue collective_epilogue(params.epilogue, shared_storage.tensors.epilogue); + + int thread_idx = int(threadIdx.x); + int lane_idx = canonical_lane_idx(); + int warp_idx = canonical_warp_idx_sync(); + int warp_idx_in_warp_group = warp_idx % NumWarpsPerWarpGroup; + int warp_group_thread_idx = thread_idx % NumThreadsPerWarpGroup; + int mma_thread_idx = thread_idx % size(TiledMma{}); + auto warp_group_idx = canonical_warp_group_idx(); + auto warp_group_role = WarpGroupRole(warp_group_idx); + auto producer_warp_role = ProducerWarpRole(warp_idx_in_warp_group); + int lane_predicate = cute::elect_one_sync(); + uint32_t block_rank_in_cluster = cute::block_rank_in_cluster(); + + // Note: Tma Descriptor Prefetch (from either const or param) is not applicable here + + // TileScheduler pipeline + using TileSchedulerPipeline = typename TileScheduler::Pipeline; + typename TileSchedulerPipeline::Params tile_scheduler_pipeline_params; + if constexpr (cute::is_same_v) { + if (warp_group_role == WarpGroupRole::Producer + && producer_warp_role == ProducerWarpRole::Scheduler) { + tile_scheduler_pipeline_params.role = TileSchedulerPipeline::ThreadCategory::Producer; + } + else { + tile_scheduler_pipeline_params.role = TileSchedulerPipeline::ThreadCategory::Consumer; + } + tile_scheduler_pipeline_params.consumer_arv_count = NumMmaThreads + + NumThreadsPerWarp * ( + 1 // Main DMA warp + + (collective_epilogue.is_producer_load_needed() ? 1 : 0) // Epilog DMA warp + + (IsMainloopAuxiliaryLoadNeeded ? 1 : 0) // Aux DMA warp + ); + tile_scheduler_pipeline_params.producer_arv_count = 1; + } + TileSchedulerPipeline tile_scheduler_pipeline(shared_storage.pipelines.scheduler, tile_scheduler_pipeline_params); + // Mainloop Load pipeline + using MainloopPipeline = typename CollectiveMainloop::MainloopPipeline; + typename MainloopPipeline::Params mainloop_pipeline_params; + if (warp_group_role == WarpGroupRole::Producer + && (producer_warp_role == ProducerWarpRole::Mainloop + || producer_warp_role == ProducerWarpRole::MainloopAux)) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Producer; + } + if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + mainloop_pipeline_params.role = MainloopPipeline::ThreadCategory::Consumer; + } + mainloop_pipeline_params.is_leader = warp_group_thread_idx == 0; + mainloop_pipeline_params.num_consumers = NumMmaThreads; + mainloop_pipeline_params.num_producers = NumProducerThreads; + mainloop_pipeline_params.transaction_bytes = params.mainloop.tma_transaction_bytes; + MainloopPipeline mainloop_pipeline(shared_storage.pipelines.mainloop, mainloop_pipeline_params, ClusterShape{}); + + // Epilogue Load pipeline + using EpiLoadPipeline = typename CollectiveEpilogue::LoadPipeline; + typename EpiLoadPipeline::Params epi_load_pipeline_params; + if (warp_group_role == WarpGroupRole::Producer && producer_warp_role == ProducerWarpRole::Epilogue) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Producer; + } + if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + epi_load_pipeline_params.role = EpiLoadPipeline::ThreadCategory::Consumer; + } + epi_load_pipeline_params.dst_blockid = cute::block_rank_in_cluster(); + epi_load_pipeline_params.producer_arv_count = NumThreadsPerWarp; + epi_load_pipeline_params.consumer_arv_count = size(TiledMma{}); + if constexpr (CollectiveEpilogue::RequiresTransactionBytes) { + epi_load_pipeline_params.transaction_bytes = params.epilogue.tma_transaction_bytes; + } + EpiLoadPipeline epi_load_pipeline(shared_storage.pipelines.epi_load, epi_load_pipeline_params); + + // Epilogue Store pipeline + using EpiStorePipeline = typename CollectiveEpilogue::StorePipeline; + typename EpiStorePipeline::Params epi_store_pipeline_params; + epi_store_pipeline_params.always_wait = true; + EpiStorePipeline epi_store_pipeline(epi_store_pipeline_params); + + typename LoadWarpOrderBarrier::Params params_load_order_barrier; + params_load_order_barrier.group_id = producer_warp_role == ProducerWarpRole::Mainloop ? 0 : 1; + params_load_order_barrier.group_size = NumThreadsPerWarp; + LoadWarpOrderBarrier load_order_barrier(shared_storage.pipelines.load_order, params_load_order_barrier); + + // Initialize starting pipeline states for the collectives + // Epilogue store pipe is producer-only (consumer is TMA unit, waits via scoreboarding) + typename TileSchedulerPipeline::PipelineState tile_scheduler_pipe_consumer_state; + typename CollectiveMainloop::PipelineState mainloop_pipe_consumer_state; + typename CollectiveEpilogue::LoadPipelineState epi_load_pipe_consumer_state; + + // For the DMA Load (producer) we start with an opposite phase + // i.e., we skip all waits since we know that the buffer is indeed empty + PipelineState tile_scheduler_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState mainloop_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState epi_load_pipe_producer_state = cutlass::make_producer_start_state(); + PipelineState epi_store_pipe_producer_state = cutlass::make_producer_start_state(); + + auto cluster_wait_fn = [] () { + // We need this to guarantee that the Pipeline init is visible + // To all producers and consumer thread blocks in the Cluster + if constexpr (size(ClusterShape{}) > 1) { + cute::cluster_arrive_relaxed(); + return [] () { cute::cluster_wait(); }; + } + else { + __syncthreads(); + return [] () {}; // do nothing + } + } (); + + // Get the appropriate blocks for this thread block -- potential for thread block locality + TiledMma tiled_mma; + const auto blk_shape = TileShape{}; // (BLK_M,BLK_N,BLK_K) + const auto c_tile_count = CollectiveEpilogue::get_load_pipe_increment(blk_shape); + const auto d_tile_count = CollectiveEpilogue::get_store_pipe_increment(blk_shape); + + // Wait for all thread blocks in the Cluster + cluster_wait_fn(); + + // Ensure memory ops in this kernel are not done prior to completion of dependent grids. + cutlass::arch::wait_on_dependent_grids(); + + auto scheduler = [&] () { + // Group scheduler requires a different constructor that takes a response ptr + if constexpr (cute::is_same_v) { + return TileScheduler{params.scheduler, shared_storage.scheduler_response}; + } + else { + return TileScheduler{params.scheduler}; + } + } (); + + auto work_tile_info = scheduler.initial_work_tile_info(ClusterShape{}); + + if (not work_tile_info.is_valid()) { + // When problem shapes are only on device, the grid launched may be larger than the total number of blocks across groups + return; + } + + // Optionally append 1s until problem shape is rank-4 in case it is only rank-3 (MNK) + auto problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + + // Prepare and partition the input tensors. Expects a tuple of tensors where: + // get<0>(load_inputs) is the tma tensor A after local tiling so that it has shape (BLK_M,BLK_K,m,k,l) + // get<1>(load_inputs) is the tma tensor B after local tiling so that it has shape (BLK_N,BLK_K,n,k,l) + auto load_inputs = collective_mainloop.load_init(problem_shape_MNKL, params.mainloop); + static_assert(cute::tuple_size_v >= 2, "Output of load_init must have at least two elements (A, B)"); + + // Extract out partitioned A and B. + Tensor gA_mkl = get<0>(load_inputs); + Tensor gB_nkl = get<1>(load_inputs); + + // Get pipeline stage increments from tensor shapes + auto k_tile_count = size<3>(gA_mkl); + + if (warp_group_role == WarpGroupRole::Producer) { + if constexpr (!IsLowRegisterPressure) { + cutlass::arch::warpgroup_reg_dealloc(); + } + + if (producer_warp_role == ProducerWarpRole::Scheduler) { + // GroupScheduler requires a producer warp to iterate over the group infos and push + // the work tile infos to the downstream pipelines. + if constexpr (cute::is_same_v) { + do { + auto [next_work_tile_info, increment_pipe] = scheduler.advance_to_next_work(tile_scheduler_pipeline, tile_scheduler_pipe_producer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_producer_state; + } + } while (work_tile_info.is_valid()); + tile_scheduler_pipeline.producer_tail(tile_scheduler_pipe_producer_state); + } + } + // Mainloop Producer Warp + else if (producer_warp_role == ProducerWarpRole::Mainloop) { + int32_t curr_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx; + int32_t const mock_l_coord = 0; + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + + // Fetch a copy of tensormaps for the CTA + auto input_tensormaps = collective_mainloop.tensormaps_init(params.mainloop, shared_storage.tensormaps.mainloop, sm_count, sm_idx); + + // Update tensormap for the initial batch for the CTA + collective_mainloop.tensormaps_perform_update( + shared_storage.tensormaps.mainloop, + params.mainloop, + input_tensormaps, + problem_shape_MNKL, + curr_batch + ); + // Ensure warp is converged before issuing tensormap fence release + __syncwarp(); + // Entire warp must do this (i.e. it's aligned) + collective_mainloop.tensormaps_cp_fence_release(shared_storage.tensormaps.mainloop, input_tensormaps); + + bool do_load_order_arrive = true; + bool did_batch_change = true; + do { + if (!TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work( + work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + continue; + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, mock_l_coord); + + // Get the number of K tiles to compute for this work as well as the starting K tile offset of the work. + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + auto work_k_tile_start = TileScheduler::get_work_k_tile_start(work_tile_info); + auto k_tile_iter = cute::make_coord_iterator(idx2crd(work_k_tile_start, shape<3>(gA_mkl)), shape<3>(gA_mkl)); + + if (did_batch_change) { + load_inputs = collective_mainloop.tensors_perform_update(load_inputs, params.mainloop, problem_shape_MNKL, curr_batch); + collective_mainloop.tensormaps_fence_acquire(input_tensormaps); + } + + collective_mainloop.load( + params.mainloop, + mainloop_pipeline, + mainloop_pipe_producer_state, + load_inputs, + input_tensormaps, + blk_coord, + k_tile_iter, work_k_tile_count, + lane_idx, + block_rank_in_cluster, + shared_storage.tensors.mainloop + ); + // Pipeline state is only advanced if there are K tiles to compute + mainloop_pipe_producer_state.advance(work_k_tile_count); + + // Signal for the epilogue load warp to begin + if (do_load_order_arrive) { + load_order_barrier.arrive(); + do_load_order_arrive = false; + } + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + auto next_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx + did_batch_change = next_batch != curr_batch; + if (work_tile_info.is_valid() && did_batch_change) { + curr_batch = next_batch; + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(curr_batch), 1); + } + collective_mainloop.tensormaps_perform_update( + shared_storage.tensormaps.mainloop, + params.mainloop, + input_tensormaps, + problem_shape_MNKL, + curr_batch + ); + // Ensure warp is converged before issuing tensor replace + __syncwarp(); + // Entire warp must do this (i.e. it's aligned) + collective_mainloop.tensormaps_cp_fence_release(shared_storage.tensormaps.mainloop, input_tensormaps); + } + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Make sure all Consumer Warp Groups have been waited upon + collective_mainloop.load_tail(mainloop_pipeline, mainloop_pipe_producer_state); + } // Mainloop Producer Warp End + else if (producer_warp_role == ProducerWarpRole::MainloopAux) { + if constexpr (IsMainloopAuxiliaryLoadNeeded) { + int32_t curr_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx; + int32_t const mock_l_coord = 0; + + bool did_batch_change = true; + do { + if (!TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + continue; + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, mock_l_coord); + + // Get the number of K tiles to compute for this work as well as the starting K tile offset of the work. + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + auto work_k_tile_start = TileScheduler::get_work_k_tile_start(work_tile_info); + auto k_tile_iter = cute::make_coord_iterator(idx2crd(work_k_tile_start, shape<3>(gA_mkl)), shape<3>(gA_mkl)); + + if (did_batch_change) { + load_inputs = collective_mainloop.tensors_perform_update(load_inputs, params.mainloop, problem_shape_MNKL, curr_batch); + } + + collective_mainloop.load_auxiliary( + params.mainloop, + mainloop_pipeline, + mainloop_pipe_producer_state, + load_inputs, + blk_coord, + k_tile_iter, work_k_tile_count, + lane_idx, + block_rank_in_cluster, + shared_storage.tensors.mainloop + ); + + // Update starting pipeline state for the next tile + mainloop_pipe_producer_state.advance(work_k_tile_count); + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + auto next_batch = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); // Usually just returns work_tile_info.L_idx + did_batch_change = next_batch != curr_batch; + if (work_tile_info.is_valid() && did_batch_change) { + curr_batch = next_batch; + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(curr_batch), 1); + } + } + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + } // End of auxiliary load needed check + } // Mainloop Auxiliary Load Producer Warp End + // Epilogue Producer Warp + else if (producer_warp_role == ProducerWarpRole::Epilogue && collective_epilogue.is_producer_load_needed()) { + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + + auto epi_load_tensormap = get<0>(collective_epilogue.load_init(params.epilogue, shared_storage.tensormaps.epilogue, sm_count, sm_idx)); + + bool did_batch_change = true; + constexpr bool IsEpiLoad = true; + + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_load_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + 0 + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, epi_load_tensormap, 0); + + load_order_barrier.wait(); + + do { + int32_t curr_batch = work_tile_info.L_idx; + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + + if (TileScheduler::compute_epilogue(work_tile_info, params.scheduler)) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto l_coord = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, l_coord); + + if (did_batch_change) { + collective_epilogue.template tensormaps_fence_acquire(epi_load_tensormap); + } + + epi_load_pipe_producer_state = collective_epilogue.load( + epi_load_pipeline, + epi_load_pipe_producer_state, + problem_shape_MNKL, + blk_shape, + blk_coord, + tiled_mma, + lane_idx, + shared_storage.tensors.epilogue, + epi_load_tensormap, + work_tile_info.reduction_subtile_idx() + ); + } + + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + did_batch_change = curr_batch != work_tile_info.L_idx; + + if (work_tile_info.is_valid() && did_batch_change) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + // tensormap update + { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_load_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + 0 + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, epi_load_tensormap, 0); + } + } + + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Make sure all Consumer Warp Groups have been waited upon + collective_epilogue.load_tail(epi_load_pipeline, epi_load_pipe_producer_state); + } // Epilogue Producer Warp End + } // Producer Warp Group End + + else if (warp_group_role == WarpGroupRole::Consumer0 || warp_group_role == WarpGroupRole::Consumer1) { + if constexpr (!IsLowRegisterPressure) { + cutlass::arch::warpgroup_reg_alloc(); + } + + // Index of warp group within consumer warp groups + int consumer_warp_group_idx = warp_group_role == WarpGroupRole::Consumer0 ? 0 : 1; + + int32_t const sm_idx = blockIdx.x + (blockIdx.y * gridDim.x); + int32_t const sm_count = params.hw_info.sm_count; + // Do we potentially issue tail arrives for TMA stores, if epilogue load is waiting for it + bool do_store_tail = false; + // Get a copy of tensormaps + auto epi_store_tensormap = get<0>(collective_epilogue.store_init(params.epilogue, shared_storage.tensormaps.epilogue, sm_count, sm_idx, consumer_warp_group_idx)); + + bool did_batch_change = true; + constexpr bool IsEpiLoad = false; + + if (warp_idx_in_warp_group == 0) { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_store_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + consumer_warp_group_idx + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, + epi_store_tensormap, + consumer_warp_group_idx); + } + + do { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + + int32_t curr_batch = work_tile_info.L_idx; + + // Compute m_coord, n_coord, l_coord with the post-tiled m-shape and n-shape + auto m_coord = idx2crd(work_tile_info.M_idx, shape<2>(gA_mkl)); + auto n_coord = idx2crd(work_tile_info.N_idx, shape<2>(gB_nkl)); + auto l_coord = idx2crd(work_tile_info.L_idx, shape<4>(gB_nkl)); + auto blk_coord = make_coord(m_coord, n_coord, _, l_coord); + auto work_k_tile_count = TileScheduler::get_work_k_tile_count(work_tile_info, problem_shape_MNKL, blk_shape); + + // Allocate the accumulators for the (M,N) blk_shape + // + // MSVC CTAD breaks if we say "Tensor" here, so we use "auto" instead. + auto accumulators = partition_fragment_C(tiled_mma, take<0,2>(blk_shape)); // (MMA,MMA_M,MMA_N) + + if (TileScheduler::valid_warpgroup_in_work_tile(work_tile_info)) { + + if constexpr (IsSm120Family) { + collective_mainloop.mma( + mainloop_pipeline, + mainloop_pipe_consumer_state, + accumulators, + work_k_tile_count, + mma_thread_idx, + shared_storage.tensors.mainloop, + params.mainloop, + blk_coord + ); + } + else { + collective_mainloop.mma( + mainloop_pipeline, + mainloop_pipe_consumer_state, + accumulators, + work_k_tile_count, + mma_thread_idx, + shared_storage.tensors.mainloop, + params.mainloop + ); + } + + // Make sure the math instructions are done and free buffers before entering the epilogue + collective_mainloop.mma_tail( + mainloop_pipeline, + mainloop_pipe_consumer_state, + work_k_tile_count + ); + + // Update starting mainloop pipeline state for the next tile + mainloop_pipe_consumer_state.advance(work_k_tile_count); + } + + // Perform reduction across splits, if needed + TileScheduler::fixup( + params.scheduler, work_tile_info, accumulators, NumMmaWarpGroups, consumer_warp_group_idx); + + if (did_batch_change) { + collective_epilogue.template tensormaps_fence_acquire(epi_store_tensormap); + } + + if (TileScheduler::compute_epilogue(work_tile_info, params.scheduler)) { + + // Epilogue and write to gD + auto [epi_load_pipe_consumer_state_next, epi_store_pipe_producer_state_next] = + collective_epilogue.store( + epi_load_pipeline, + epi_load_pipe_consumer_state, + epi_store_pipeline, + epi_store_pipe_producer_state, + problem_shape_MNKL, + blk_shape, + blk_coord, + accumulators, + tiled_mma, + mma_thread_idx, + shared_storage.tensors.epilogue, + epi_store_tensormap, + work_tile_info.reduction_subtile_idx() + ); + + epi_load_pipe_consumer_state = epi_load_pipe_consumer_state_next; + epi_store_pipe_producer_state = epi_store_pipe_producer_state_next; + do_store_tail = true; + // n52: this tile's D is stored; signal its band, the last arriver runs the band pass. +#ifndef N52_NO_HOOK + if (params.band.mode >= 0) { + n52_band_hook(params.band, int(work_tile_info.L_idx), int(work_tile_info.M_idx), + int(get<1>(problem_shape_MNKL)), mma_thread_idx); + } +#endif + } + + // Get next work tile + auto [next_work_tile_info, increment_pipe] = scheduler.fetch_next_work(work_tile_info, tile_scheduler_pipeline, tile_scheduler_pipe_consumer_state); + + if (!next_work_tile_info.is_valid()) { + cutlass::arch::launch_dependent_grids(); + } + + work_tile_info = next_work_tile_info; + if (increment_pipe) { + ++tile_scheduler_pipe_consumer_state; + } + + did_batch_change = curr_batch != work_tile_info.L_idx; + if (work_tile_info.is_valid() && did_batch_change) { + if constexpr (IsGroupedGemmKernel) { + problem_shape_MNKL = append<4>(params.problem_shape.get_problem_shape(work_tile_info.L_idx), 1); + } + if (warp_idx_in_warp_group == 0) { + collective_epilogue.template tensormaps_perform_update( + shared_storage.tensormaps.epilogue, + params.epilogue, + epi_store_tensormap, + problem_shape_MNKL, + work_tile_info.L_idx, + consumer_warp_group_idx + ); + + // Converge before issuing tensormap fence release since fence is aligned + __syncwarp(); + collective_epilogue.template tensormaps_cp_fence_release(shared_storage.tensormaps.epilogue, + epi_store_tensormap, + consumer_warp_group_idx); + } + } + + } while (work_tile_info.is_valid()); // Scheduler work fetch loop + + // Cooperative only needs TMA to complete at the very end of the kernel + if (do_store_tail) { + collective_epilogue.store_tail( + epi_load_pipeline, + epi_load_pipe_consumer_state, + epi_store_pipeline, + epi_store_pipe_producer_state + ); + } + } // Consumer Warp Groups End +#endif + } +}; + + +} // namespace cutlass::gemm::kernel + +namespace sglang::n381c_band { + +using namespace cute; + +// ---- GEMM types: FlashInfer's builder arguments for <128, 128, 256, SwapAB false>, ElementD bf16, ElementC void. ---- +using ElementA = cutlass::float_e2m1_t; +using ElementB = cutlass::float_e2m1_t; +using ElementSF = cutlass::float_ue4m3_t; +using ElementD = cutlass::bfloat16_t; +constexpr int AlignmentA = 128 / cutlass::sizeof_bits::value; +constexpr int AlignmentB = 128 / cutlass::sizeof_bits::value; +constexpr int AlignmentD = 128 / cutlass::sizeof_bits::value; +using ElementAccumulator = float; +using ElementCompute = float; +using ElementAMainloop = cutlass::nv_float4_t; +using ElementBMainloop = cutlass::nv_float4_t; +using ProblemShape = cutlass::gemm::GroupProblemShape>; +using LayoutA = cutlass::layout::RowMajor; +using LayoutB = cutlass::layout::ColumnMajor; +using LayoutD = cutlass::layout::RowMajor; +using ClusterShape = Shape<_1, _1, _1>; +#ifndef N381_PP +#define N381_PP 0 +#endif +#ifndef N381_TILE_K +#define N381_TILE_K 256 +#endif +static_assert(N381_TILE_K == 128 || N381_TILE_K == 256, "N381_TILE_K"); +using ThreadBlockShape = Shape<_128, _128, cute::Int>; // n381: tile_k 128 (4 stages) or 256 (served) +using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< + cutlass::arch::Sm120, + cutlass::arch::OpClassBlockScaledTensorOp, + ThreadBlockShape, + ClusterShape, + cutlass::epilogue::collective::EpilogueTileAuto, + ElementAccumulator, + ElementCompute, + void, + LayoutD*, + AlignmentD, + ElementD, + LayoutD*, + AlignmentD, +#if N381_PP + cutlass::epilogue::PtrArrayTmaWarpSpecializedPingpong>::CollectiveOp; +#else + cutlass::epilogue::collective::EpilogueScheduleAuto>::CollectiveOp; +#endif +using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< + cutlass::arch::Sm120, + cutlass::arch::OpClassBlockScaledTensorOp, + ElementAMainloop, + LayoutA*, + AlignmentA, + ElementBMainloop, + LayoutB*, + AlignmentB, + ElementAccumulator, + ThreadBlockShape, + ClusterShape, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, +#if N381_PP + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedPingpong>::CollectiveOp; +static_assert( + cute::is_base_of_v< + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedPingpong, + typename CollectiveMainloop::DispatchPolicy::Schedule>, + "n381 PP: the ptr-array ping-pong kernel"); +using GemmKernel = cutlass::gemm::kernel::GemmUniversal; +#else + cutlass::gemm::collective::KernelScheduleAuto>::CollectiveOp; +static_assert( + cute::is_base_of_v< + cutlass::gemm::KernelPtrArrayTmaWarpSpecializedCooperative, + typename CollectiveMainloop::DispatchPolicy::Schedule>, + "the served config builds the ptr-array cooperative kernel; N381CKernel is a copy of that kernel"); +using GemmKernel = cutlass::gemm::kernel::N381CKernel; +#endif +using Gemm = cutlass::gemm::device::GemmUniversalAdapter; +static_assert(GemmKernel::SharedStorageSize <= 101376, "dynamic smem must fit sm_120's 99 KB per block"); +using StrideA = typename Gemm::GemmKernel::InternalStrideA; +using StrideB = typename Gemm::GemmKernel::InternalStrideB; +using StrideD = typename Gemm::GemmKernel::InternalStrideD; +using ScaleConfig = typename Gemm::GemmKernel::CollectiveMainloop::Sm1xxBlkScaledConfig; +using LayoutSFA = typename Gemm::GemmKernel::CollectiveMainloop::InternalLayoutSFA; +using LayoutSFB = typename Gemm::GemmKernel::CollectiveMainloop::InternalLayoutSFB; +constexpr int ScaleGranularity = Gemm::GemmKernel::CollectiveMainloop::TiledMma::SFVecSize; +static_assert(ScaleGranularity == 16); +using UnderlyingProblemShape = typename ProblemShape::UnderlyingProblemShape; + +template +__host__ __device__ __forceinline__ T* inc_ptr(T* ptr, size_t offset) { + constexpr int adjustment = (cutlass::sizeof_bits::value < 8) ? (8 / cutlass::sizeof_bits::value) : 1; + return ptr + offset / adjustment; +} + +// FlashInfer's compute_sm120_cutlass_nvfp4_group_gemm_args (SwapAB false), line for line. +__global__ void group_args( + ElementA* A, + ElementB* B, + ElementSF* SFA, + ElementSF* SFB, + ElementD* D, + int const* m_indptr, + int n, + int k, + int num_groups, + UnderlyingProblemShape* problem_sizes, + ElementA const** A_ptr, + ElementB const** B_ptr, + ElementSF const** SFA_ptr, + ElementSF const** SFB_ptr, + ElementD** D_ptr, + StrideA* stride_A, + StrideB* stride_B, + StrideD* stride_D, + LayoutSFA* layout_SFA, + LayoutSFB* layout_SFB) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= num_groups) return; + constexpr size_t alignment_swizzled_mn = 128; + constexpr size_t alignment_swizzled_k = static_cast(ScaleGranularity) * 4; + size_t sf_n = (static_cast(n) + alignment_swizzled_mn - 1) / alignment_swizzled_mn * alignment_swizzled_mn; + size_t swizzled_k = (static_cast(k) + alignment_swizzled_k - 1) / alignment_swizzled_k * alignment_swizzled_k; + size_t sf_k = swizzled_k / static_cast(ScaleGranularity); + asm volatile("griddepcontrol.wait;"); + asm volatile("griddepcontrol.launch_dependents;"); + int m_offset = m_indptr[i]; + int m_offset_next = m_indptr[i + 1]; + size_t m = static_cast(m_offset_next) - static_cast(m_offset); + size_t sf_m_offset = (static_cast(m_offset) + static_cast(i) * (alignment_swizzled_mn - 1)) / + alignment_swizzled_mn * alignment_swizzled_mn; + problem_sizes[i] = UnderlyingProblemShape(int(m), n, k); + stride_A[i] = cutlass::make_cute_packed_stride(StrideA{}, {int(m), k, 1}); + stride_B[i] = cutlass::make_cute_packed_stride(StrideB{}, {n, k, 1}); + stride_D[i] = cutlass::make_cute_packed_stride(StrideD{}, {int(m), n, 1}); + A_ptr[i] = inc_ptr(A, static_cast(m_offset) * static_cast(k)); + B_ptr[i] = inc_ptr(B, static_cast(i) * static_cast(n) * static_cast(k)); + D_ptr[i] = D + static_cast(m_offset) * static_cast(n); + layout_SFA[i] = ScaleConfig::tile_atom_to_shape_SFA( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFA_ptr[i] = inc_ptr(SFA, sf_m_offset * sf_k); + layout_SFB[i] = ScaleConfig::tile_atom_to_shape_SFB( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFB_ptr[i] = inc_ptr(SFB, static_cast(i) * sf_n * sf_k); +} + +inline size_t align16(size_t x) { + return (x + 15) / 16 * 16; +} + +#if !N381_PP +// values [rows, k/2] u8, weight [E, n, k/2] u8, scales (SFA, u8), weight_scales [E, n, k/16] u8 view, m_indptr [E+1], +// acc_amax / gammas [rows] f32, w_amax [E] f32, w_den [1] f32, d [rows, n] bf16 scratch (the GEMM's D), +// out_values [rows, n/4] u8, out_scales (SFA of width n/2, u8), out_amax [rows] f32, counters [>= bands] i32 (zero), +// int_ws / float_ws u8 workspaces. mode: -1 stock, 0 signal, 1 discard, 2 pass + discard, 3 pass. raster: 0 AlongM, 1 AlongN. +void gate_up_band( + tvm::ffi::TensorView values, + tvm::ffi::TensorView weight, + tvm::ffi::TensorView scales, + tvm::ffi::TensorView weight_scales, + tvm::ffi::TensorView m_indptr, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_den, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView d, + tvm::ffi::TensorView out_values, + tvm::ffi::TensorView out_scales, + tvm::ffi::TensorView out_amax, + tvm::ffi::TensorView counters, + tvm::ffi::TensorView int_ws, + tvm::ffi::TensorView float_ws, + double gate_cap, + double up_cap, + int64_t mode, + int64_t raster, + int64_t sm_count) { + auto device = host::SymbolicDevice{}; + device.set_options(); + auto rows = host::SymbolicSize{"rows"}; + auto experts = host::SymbolicSize{"experts"}; + auto n = host::SymbolicSize{"n"}; + auto kp = host::SymbolicSize{"k/2"}; + host::TensorMatcher({rows, kp}).with_dtype().with_device(device).verify(values); + host::TensorMatcher({experts, n, kp}).with_dtype().with_device(device).verify(weight); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(out_amax); + host::TensorMatcher({experts}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_den); + host::TensorMatcher({rows, n}).with_dtype().with_device(device).verify(d); + int const num_groups = static_cast(experts.unwrap()); + int const N = static_cast(n.unwrap()), K = static_cast(kp.unwrap()) * 2; + int64_t const R = rows.unwrap(); + CHECK_HOST(N == 2304) << "n52 band pass is compiled for gate_up width 2304, got " << N; + CHECK_HOST(m_indptr.size(0) == num_groups + 1) << "m_indptr must hold experts + 1 offsets"; + CHECK_HOST(out_values.size(0) == R && out_values.size(1) == N / 4) << "out_values must be [rows, n / 4]"; + int64_t const bands = (R + 127 * int64_t(num_groups)) / 128 + 1; + CHECK_HOST(counters.numel() >= bands) << "counters need " << bands << " entries"; + CHECK_HOST(out_scales.numel() >= (R + 127 * int64_t(num_groups) + 127) / 128 * 128 * (N / 2 / 16)) + << "out_scales too small for the SFA layout"; + CHECK_HOST(mode >= -1 && mode <= 3) << "mode must be -1..3"; + cudaStream_t stream = host::LaunchKernel::resolve_device(device.unwrap()); + + uint8_t* ib = static_cast(int_ws.data_ptr()); + size_t off = 0; + auto take = [&](size_t bytes) { + void* p = ib + off; + off += align16(bytes); + return p; + }; + auto problem_sizes = static_cast(take(num_groups * sizeof(UnderlyingProblemShape))); + auto A_ptr = static_cast(take(num_groups * sizeof(void*))); + auto B_ptr = static_cast(take(num_groups * sizeof(void*))); + auto D_ptr = static_cast(take(num_groups * sizeof(void*))); + auto SFA_ptr = static_cast(take(num_groups * sizeof(void*))); + auto SFB_ptr = static_cast(take(num_groups * sizeof(void*))); + auto stride_A = static_cast(take(num_groups * sizeof(StrideA))); + auto stride_B = static_cast(take(num_groups * sizeof(StrideB))); + auto stride_D = static_cast(take(num_groups * sizeof(StrideD))); + auto layout_SFA = static_cast(take(num_groups * sizeof(LayoutSFA))); + auto layout_SFB = static_cast(take(num_groups * sizeof(LayoutSFB))); + CHECK_HOST(off <= size_t(int_ws.numel())) << "int workspace too small: need " << off; + + cudaLaunchConfig_t config{}; + config.gridDim = (num_groups + 1023) / 1024; + config.blockDim = std::min(num_groups, 1024); + config.dynamicSmemBytes = 0; + config.stream = stream; + cudaLaunchAttribute attrs[1]; + attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[0].val.programmaticStreamSerializationAllowed = true; + config.numAttrs = 1; + config.attrs = attrs; + cudaError_t const st = cudaLaunchKernelEx( + &config, + group_args, + static_cast(values.data_ptr()), + static_cast(weight.data_ptr()), + static_cast(scales.data_ptr()), + static_cast(weight_scales.data_ptr()), + static_cast(d.data_ptr()), + static_cast(m_indptr.data_ptr()), + N, + K, + num_groups, + problem_sizes, + A_ptr, + B_ptr, + SFA_ptr, + SFB_ptr, + D_ptr, + stride_A, + stride_B, + stride_D, + layout_SFA, + layout_SFB); + CHECK_HOST(st == cudaSuccess) << "n52 group args launch: " << cudaGetErrorString(st); + + cutlass::KernelHardwareInfo hw_info; + hw_info.device_id = device.unwrap().device_id; + hw_info.sm_count = static_cast(sm_count); + typename Gemm::Arguments arguments{ + cutlass::gemm::GemmUniversalMode::kGrouped, + {num_groups, problem_sizes, /*problem_sizes_host=*/nullptr}, + {A_ptr, stride_A, B_ptr, stride_B, SFA_ptr, layout_SFA, SFB_ptr, layout_SFB}, + {{}, nullptr, nullptr, D_ptr, stride_D}, + hw_info}; + auto& fusion_args = arguments.epilogue.thread; + fusion_args.alpha = 1.0f; // FlashInfer with alpha == nullptr (the served call passes none) + fusion_args.beta = 0; + fusion_args.alpha_ptr = nullptr; + fusion_args.dAlpha = {cute::_0{}, cute::_0{}, 0}; + using RasterOptions = decltype(arguments.scheduler.raster_order); + arguments.scheduler.raster_order = raster ? RasterOptions::AlongN : RasterOptions::AlongM; + BandParams& b = arguments.band; + b.mode = static_cast(mode); + b.counters = static_cast(counters.data_ptr()); + b.d = static_cast<__nv_bfloat16 const*>(d.data_ptr()); + b.n = N; + b.offsets = static_cast(m_indptr.data_ptr()); + b.acc_amax = static_cast(acc_amax.data_ptr()); + b.w_amax = static_cast(w_amax.data_ptr()); + b.w_den = static_cast(w_den.data_ptr()); + b.gammas = static_cast(gammas.data_ptr()); + b.values = static_cast(out_values.data_ptr()); + b.x_scales = static_cast(out_scales.data_ptr()); + b.amax_out = static_cast(out_amax.data_ptr()); + b.gate_cap = static_cast(gate_cap); + b.up_cap = static_cast(up_cap); + + Gemm gemm; + size_t const ws = Gemm::get_workspace_size(arguments); + CHECK_HOST(ws <= size_t(float_ws.numel())) << "float workspace too small: need " << ws; + CHECK_HOST(gemm.can_implement(arguments) == cutlass::Status::kSuccess) << "n52 gemm cannot implement"; + CHECK_HOST(gemm.initialize(arguments, float_ws.data_ptr()) == cutlass::Status::kSuccess) << "n52 gemm initialize"; + CHECK_HOST(gemm.run(stream, /*cuda_adapter=*/nullptr, /*launch_with_pdl=*/true) == cutlass::Status::kSuccess) + << "n52 gemm run"; +} + +#endif // !N381_PP (F1 gate_up_band needs the in-kernel hook kernel) + +// --------------------------------------------------------------------------------------------------------------------------- +// F2 (chunked L2 pass): the same GEMM type, hook off (band mode -1), launched once per chunk of TB padded 128-row bands (the +// band numbering of F1 = the SFA layout's), each launch covering every expert's M-tiles that fall in the chunk; after each GEMM +// launch a pass kernel runs the band arithmetic (band_row) over the chunk's rows reading D from L2 and discarding it. Kernel +// boundaries order D's writes before the pass (no counters, no fences). Exact for the same reason as F1: each tile is the +// served tile (same rows, same K order); a sub-problem starts on a 128-row tile of its expert, so its A / D / SFA pointers are +// the expert's plus whole tiles (the SFA layout is row-block outermost: 128 x sf_k bytes per block). + +__device__ __forceinline__ int band0_of(int const* offsets, int e) { + return (offsets[e] - offsets[0] + e * 127) / 128; +} + +// Expert of padded band b: the largest e with band0_of(e) <= b (bands between experts' last tile and the next start are unused). +__device__ __forceinline__ int expert_of_band(int const* offsets, int experts, int b) { + int lo = 0, hi = experts; + while (hi - lo > 1) { + int const mid = (lo + hi) / 2; + if (band0_of(offsets, mid) <= b) + lo = mid; + else + hi = mid; + } + return lo; +} + +// One thread per (chunk, group): the arrays of chunk c start at c * num_groups. +__global__ void chunk_args( + ElementA* A, + ElementB* B, + ElementSF* SFA, + ElementSF* SFB, + ElementD* D, + int const* m_indptr, + int n, + int k, + int num_groups, + int nchunks, + int tb, + UnderlyingProblemShape* problem_sizes, + ElementA const** A_ptr, + ElementB const** B_ptr, + ElementSF const** SFA_ptr, + ElementSF const** SFB_ptr, + ElementD** D_ptr, + StrideA* stride_A, + StrideB* stride_B, + StrideD* stride_D, + LayoutSFA* layout_SFA, + LayoutSFB* layout_SFB) { + int const t = blockIdx.x * blockDim.x + threadIdx.x; + asm volatile("griddepcontrol.wait;"); + asm volatile("griddepcontrol.launch_dependents;"); + if (t >= num_groups * nchunks) return; + int const c = t / num_groups, i = t % num_groups; + constexpr size_t alignment_swizzled_mn = 128; + constexpr size_t alignment_swizzled_k = static_cast(ScaleGranularity) * 4; + size_t sf_n = (static_cast(n) + alignment_swizzled_mn - 1) / alignment_swizzled_mn * alignment_swizzled_mn; + size_t swizzled_k = (static_cast(k) + alignment_swizzled_k - 1) / alignment_swizzled_k * alignment_swizzled_k; + size_t sf_k = swizzled_k / static_cast(ScaleGranularity); + int const m_offset = m_indptr[i], cnt = m_indptr[i + 1] - m_indptr[i]; + int const b0 = band0_of(m_indptr, i), nt = (cnt + 127) / 128; + int const lo = max(b0, c * tb), hi = min(b0 + nt, (c + 1) * tb); // this expert's bands inside chunk c + int const mt0 = hi > lo ? lo - b0 : 0; + int const m = hi > lo ? min(cnt, (hi - b0) * 128) - mt0 * 128 : 0; + int const row0 = m_offset + mt0 * 128; + size_t sf_m_offset = (static_cast(m_offset) + static_cast(i) * (alignment_swizzled_mn - 1)) / + alignment_swizzled_mn * alignment_swizzled_mn + static_cast(mt0) * 128; + problem_sizes[t] = UnderlyingProblemShape(m, n, k); + stride_A[t] = cutlass::make_cute_packed_stride(StrideA{}, {m, k, 1}); + stride_B[t] = cutlass::make_cute_packed_stride(StrideB{}, {n, k, 1}); + stride_D[t] = cutlass::make_cute_packed_stride(StrideD{}, {m, n, 1}); + A_ptr[t] = inc_ptr(A, static_cast(row0) * static_cast(k)); + B_ptr[t] = inc_ptr(B, static_cast(i) * static_cast(n) * static_cast(k)); + D_ptr[t] = D + static_cast(row0) * static_cast(n); + layout_SFA[t] = ScaleConfig::tile_atom_to_shape_SFA( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFA_ptr[t] = inc_ptr(SFA, sf_m_offset * sf_k); + layout_SFB[t] = ScaleConfig::tile_atom_to_shape_SFB( + make_shape(static_cast(m), static_cast(sf_n), static_cast(swizzled_k), 1)); + SFB_ptr[t] = inc_ptr(SFB, static_cast(i) * sf_n * sf_k); +} + +// Chunk pass: CTA j of chunk c covers padded rows [(c * tb) * 128 + 16 j, + 16), two per warp. Grid tb * 8, 256 threads. +template +__global__ void __launch_bounds__(256) chunk_pass(BandParams p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // the chunk's GEMM has completed (its D is in memory) + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; +#pragma unroll 1 + for (int h = 0; h < 2; ++h) { + int const pr = (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp; + int const band = pr / 128; + int const e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + if (local < cnt) { + int const row = p.offsets[e] + local; + band_row(p, e, row, lane, pass, discard); + if (pass && local == cnt - 1) band_tail(p, e, lane, 32); + } + } +} + + +// ---- n360 pass schedules (ADDED; the served chunk_pass above is unchanged) ---- +// band_row split in two: load (the served loads, in the served order) and finish (everything after the loads, verbatim). +template +struct RowRegs { + uint4 raw[N2 / 2 / 16 / 8]; +}; + +template +__device__ __forceinline__ void band_row_load(BandParams const& p, int row, int lane, RowRegs& r) { + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8; + int const bl = lane / 4, part = lane % 4; + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + uint4 const* src = reinterpret_cast(drow); +#pragma unroll + for (int i = 0; i < ITERS; ++i) + r.raw[i] = __ldcg(src + (i * 8 + bl) * 4 + part); +} + +template +__device__ __forceinline__ void band_row_finish(BandParams const& p, int e, int row, int lane, RowRegs const& r, bool discard) { + using namespace sglang::inkling2_routed_quant; + constexpr int NH = N2 / 2, BLOCKS = NH / 16, ITERS = BLOCKS / 8, LINES = N2 * 2 / 128; + int const bl = lane / 4, part = lane % 4; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *p.w_den)); + float const wa = p.w_amax[e]; + __nv_bfloat16 const* drow = p.d + int64_t(row) * N2; + float const scale = __fmul_rn(__fmul_rn(p.acc_amax[row], wa), rcp); + float const gamma = p.gammas[row]; + float v[ITERS][4]; + float bmax[ITERS]; + float m = 0.0f; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(&r.raw[i]); +#pragma unroll + for (int j = 0; j < 4; ++j) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * j + 1]), scale))); + v[i][j] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, p.gate_cap, p.up_cap))); + } + bmax[i] = part_max<4>(v[i]); + m = fmaxf(m, bmax[i]); + } +#pragma unroll + for (int s = 4; s < 32; s *= 2) + m = fmaxf(m, __shfl_xor_sync(0xFFFFFFFF, m, s)); + float const amax = m; +#pragma unroll + for (int i = 0; i < ITERS; ++i) { + uint32_t packed; + uint8_t sbits; + quantize_part<4>(v[i], amax, bmax[i], packed, sbits); + store_part<4>(p.values, p.x_scales, p.offsets, e, row, i * 8 + bl, part, NH, packed, sbits); + } + if (lane == 0) p.amax_out[row] = amax; + if (discard) { + __syncwarp(); + for (int l = lane; l < LINES; l += 32) + discard_l2(drow + l * 64); + } +} + +// Map padded row pr of chunk c to (expert, row); returns false when pr is past its expert's rows (as served). +__device__ __forceinline__ bool pass_row(BandParams const& p, int experts, int pr, int& e, int& row, bool& last) { + int const band = pr / 128; + e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + row = p.offsets[e] + local; + last = local == cnt - 1; + return local < cnt; +} + +// PV 1 / 4: one row per warp, CTA j of chunk c covers padded rows (c * tb) * 128 + 8 j + warp. Grid tb * 16. +template +__device__ __forceinline__ void pass_one_row(BandParams const& p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; + int e, row; + bool last; + if (pass_row(p, experts, (c * tb) * 128 + blockIdx.x * 8 + warp, e, row, last)) { + band_row(p, e, row, lane, pass, discard); + if (pass && last) band_tail(p, e, lane, 32); + } +} + +// PV 2: the served row mapping (rows h * 8 + warp of the CTA's 16), the second row's loads before the first row's arithmetic. +template +__device__ __forceinline__ void pass_two_rows(BandParams const& p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const discard = p.mode <= 2; + int e[2], row[2]; + bool last[2], ok[2]; + RowRegs r[2]; +#pragma unroll + for (int h = 0; h < 2; ++h) { + ok[h] = pass_row(p, experts, (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp, e[h], row[h], last[h]); + if (ok[h]) band_row_load(p, row[h], lane, r[h]); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + if (ok[h]) { + band_row_finish(p, e[h], row[h], lane, r[h], discard); + if (last[h]) band_tail(p, e[h], lane, 32); + } + } +} + +template +__global__ void __launch_bounds__(256) chunk_pass_1(BandParams p, int experts, int c, int tb) { pass_one_row(p, experts, c, tb); } +template +__global__ void __launch_bounds__(256) chunk_pass_2(BandParams p, int experts, int c, int tb) { pass_two_rows(p, experts, c, tb); } +template +__global__ void __launch_bounds__(256, 4) chunk_pass_4(BandParams p, int experts, int c, int tb) { pass_one_row(p, experts, c, tb); } +// PV 3: the served chunk_pass body, verbatim, under __launch_bounds__(256, 4). +template +__global__ void __launch_bounds__(256, 4) chunk_pass_3(BandParams p, int experts, int c, int tb) { + asm volatile("griddepcontrol.wait;" ::: "memory"); // the chunk's GEMM has completed (its D is in memory) + asm volatile("griddepcontrol.launch_dependents;"); + int const warp = threadIdx.x / 32, lane = threadIdx.x % 32; + bool const pass = p.mode >= 2, discard = p.mode <= 2; +#pragma unroll 1 + for (int h = 0; h < 2; ++h) { + int const pr = (c * tb) * 128 + blockIdx.x * 16 + h * 8 + warp; + int const band = pr / 128; + int const e = expert_of_band(p.offsets, experts, band); + int const cnt = p.offsets[e + 1] - p.offsets[e]; + int const local = (band - band0_of(p.offsets, e)) * 128 + pr % 128; + if (local < cnt) { + int const row = p.offsets[e] + local; + band_row(p, e, row, lane, pass, discard); + if (pass && local == cnt - 1) band_tail(p, e, lane, 32); + } + } +} + +// F2 host entry: as gate_up_band (mode 2 pass + discard, 3 pass), with tb bands per chunk. int_ws must hold the args of every +// chunk (~300 B x experts x chunks). +void gate_up_chunks( + tvm::ffi::TensorView values, + tvm::ffi::TensorView weight, + tvm::ffi::TensorView scales, + tvm::ffi::TensorView weight_scales, + tvm::ffi::TensorView m_indptr, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_den, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView d, + tvm::ffi::TensorView out_values, + tvm::ffi::TensorView out_scales, + tvm::ffi::TensorView out_amax, + tvm::ffi::TensorView int_ws, + tvm::ffi::TensorView float_ws, + double gate_cap, + double up_cap, + int64_t mode, + int64_t raster, + int64_t tb, + int64_t sm_count, + int64_t pv) { + auto device = host::SymbolicDevice{}; + device.set_options(); + auto rows = host::SymbolicSize{"rows"}; + auto experts = host::SymbolicSize{"experts"}; + auto n = host::SymbolicSize{"n"}; + auto kp = host::SymbolicSize{"k/2"}; + host::TensorMatcher({rows, kp}).with_dtype().with_device(device).verify(values); + host::TensorMatcher({experts, n, kp}).with_dtype().with_device(device).verify(weight); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(out_amax); + host::TensorMatcher({experts}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_den); + host::TensorMatcher({rows, n}).with_dtype().with_device(device).verify(d); + int const G = static_cast(experts.unwrap()); + int const N = static_cast(n.unwrap()), K = static_cast(kp.unwrap()) * 2; + int64_t const R = rows.unwrap(); + CHECK_HOST(N == 2304) << "n52 chunk pass is compiled for gate_up width 2304, got " << N; + CHECK_HOST(m_indptr.size(0) == G + 1) << "m_indptr must hold experts + 1 offsets"; + CHECK_HOST(out_values.size(0) == R && out_values.size(1) == N / 4) << "out_values must be [rows, n / 4]"; + CHECK_HOST(out_scales.numel() >= (R + 127 * int64_t(G) + 127) / 128 * 128 * (N / 2 / 16)) << "out_scales too small"; + CHECK_HOST(mode == 2 || mode == 3) << "chunk mode must be 2 (pass + discard) or 3 (pass)"; + CHECK_HOST(tb >= 1 && tb <= 4096) << "tb (bands per chunk) out of range"; + CHECK_HOST(pv >= 0 && pv <= 4) << "n360 pass variant 0..4"; + int const bands = static_cast((R + 127 * int64_t(G)) / 128 + 1); + int const nchunks = static_cast((bands + tb - 1) / tb); + cudaStream_t stream = host::LaunchKernel::resolve_device(device.unwrap()); + + uint8_t* ib = static_cast(int_ws.data_ptr()); + size_t off = 0; + size_t const NC = size_t(nchunks) * G; + auto take = [&](size_t bytes) { + void* q = ib + off; + off += align16(bytes); + return q; + }; + auto problem_sizes = static_cast(take(NC * sizeof(UnderlyingProblemShape))); + auto A_ptr = static_cast(take(NC * sizeof(void*))); + auto B_ptr = static_cast(take(NC * sizeof(void*))); + auto D_ptr = static_cast(take(NC * sizeof(void*))); + auto SFA_ptr = static_cast(take(NC * sizeof(void*))); + auto SFB_ptr = static_cast(take(NC * sizeof(void*))); + auto stride_A = static_cast(take(NC * sizeof(StrideA))); + auto stride_B = static_cast(take(NC * sizeof(StrideB))); + auto stride_D = static_cast(take(NC * sizeof(StrideD))); + auto layout_SFA = static_cast(take(NC * sizeof(LayoutSFA))); + auto layout_SFB = static_cast(take(NC * sizeof(LayoutSFB))); + CHECK_HOST(off <= size_t(int_ws.numel())) << "int workspace too small: need " << off; + + cudaLaunchAttribute attrs[1]; + attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[0].val.programmaticStreamSerializationAllowed = true; + cudaLaunchConfig_t config{}; + config.gridDim = static_cast((NC + 255) / 256); + config.blockDim = 256; + config.stream = stream; + config.numAttrs = 1; + config.attrs = attrs; + cudaError_t st = cudaLaunchKernelEx( + &config, chunk_args, static_cast(values.data_ptr()), static_cast(weight.data_ptr()), + static_cast(scales.data_ptr()), static_cast(weight_scales.data_ptr()), + static_cast(d.data_ptr()), static_cast(m_indptr.data_ptr()), N, K, G, nchunks, static_cast(tb), + problem_sizes, A_ptr, B_ptr, SFA_ptr, SFB_ptr, D_ptr, stride_A, stride_B, stride_D, layout_SFA, layout_SFB); + CHECK_HOST(st == cudaSuccess) << "n52 chunk args launch: " << cudaGetErrorString(st); + + BandParams b; + b.mode = static_cast(mode); + b.counters = nullptr; + b.d = static_cast<__nv_bfloat16 const*>(d.data_ptr()); + b.n = N; + b.offsets = static_cast(m_indptr.data_ptr()); + b.acc_amax = static_cast(acc_amax.data_ptr()); + b.w_amax = static_cast(w_amax.data_ptr()); + b.w_den = static_cast(w_den.data_ptr()); + b.gammas = static_cast(gammas.data_ptr()); + b.values = static_cast(out_values.data_ptr()); + b.x_scales = static_cast(out_scales.data_ptr()); + b.amax_out = static_cast(out_amax.data_ptr()); + b.gate_cap = static_cast(gate_cap); + b.up_cap = static_cast(up_cap); + + cutlass::KernelHardwareInfo hw_info; + hw_info.device_id = device.unwrap().device_id; + hw_info.sm_count = static_cast(sm_count); + for (int c = 0; c < nchunks; ++c) { + size_t const o = size_t(c) * G; + typename Gemm::Arguments arguments{ + cutlass::gemm::GemmUniversalMode::kGrouped, + {G, problem_sizes + o, /*problem_sizes_host=*/nullptr}, + {A_ptr + o, stride_A + o, B_ptr + o, stride_B + o, SFA_ptr + o, layout_SFA + o, SFB_ptr + o, layout_SFB + o}, + {{}, nullptr, nullptr, D_ptr + o, stride_D + o}, + hw_info}; + auto& fusion_args = arguments.epilogue.thread; + fusion_args.alpha = 1.0f; + fusion_args.beta = 0; + fusion_args.alpha_ptr = nullptr; + fusion_args.dAlpha = {cute::_0{}, cute::_0{}, 0}; + using RasterOptions = decltype(arguments.scheduler.raster_order); + arguments.scheduler.raster_order = raster ? RasterOptions::AlongN : RasterOptions::AlongM; +#if !N381_PP + arguments.band.mode = -1; // F2: no in-kernel hook +#endif + Gemm gemm; + size_t const ws = Gemm::get_workspace_size(arguments); + CHECK_HOST(ws <= size_t(float_ws.numel())) << "float workspace too small: need " << ws; + CHECK_HOST(gemm.can_implement(arguments) == cutlass::Status::kSuccess) << "n52 chunk gemm cannot implement"; + CHECK_HOST(gemm.initialize(arguments, float_ws.data_ptr()) == cutlass::Status::kSuccess) << "n52 chunk gemm initialize"; + CHECK_HOST(gemm.run(stream, /*cuda_adapter=*/nullptr, /*launch_with_pdl=*/true) == cutlass::Status::kSuccess) + << "n52 chunk gemm run"; + cudaLaunchConfig_t pc{}; + pc.gridDim = static_cast(tb * ((pv == 1 || pv == 4) ? 16 : 8)); // n360: one row per warp doubles the CTAs + pc.blockDim = 256; + pc.stream = stream; + pc.numAttrs = 1; + pc.attrs = attrs; + auto pass_kernel = pv == 1 ? chunk_pass_1<2304> : pv == 2 ? chunk_pass_2<2304> : pv == 3 ? chunk_pass_3<2304> + : pv == 4 ? chunk_pass_4<2304> : chunk_pass<2304>; // n360 pass schedules; 0 = the served kernel + st = cudaLaunchKernelEx(&pc, pass_kernel, b, G, c, static_cast(tb)); + CHECK_HOST(st == cudaSuccess) << "n52 chunk pass launch: " << cudaGetErrorString(st); + } +} + +// --------------------------------------------------------------------------------------------------------------------------- +// L5 (lean standalone swiglu-quant) and C5 (its null twin): the image's nvfp4_swiglu_quantize_routed (routed_quant_sm120.cuh) +// line for line, except capped_swiglu -> N52_SWIGLU: the lean unit (N52_LEAN 1) runs the proven divide rewrite (L5), the plain +// unit runs the image's capped_swiglu (C5 = a copy of the image kernel: its timing is the copy null). Same launch (grid_size, +// split_threads, PDL wait + trigger), same device helpers, so outputs are the image kernel's bit for bit. +using sglang::inkling2_routed_quant_sm120::zero_expert_tail; + +template +__global__ void __launch_bounds__(sglang::inkling2_routed_quant::split_threads(N)) swiglu_quantize_l5( + __nv_bfloat16 const* __restrict__ acc, + float const* __restrict__ acc_amax, + float const* __restrict__ w_amax, + float const* __restrict__ w_denominator, + float const* __restrict__ gammas, + uint8_t* values, + uint8_t* x_scales, + float* amax_out, + int32_t const* __restrict__ offsets, + int32_t experts, + float gate_cap, + float up_cap) { + using namespace sglang::inkling2_routed_quant; + constexpr int kThreads = split_threads(N), kSplit = split(N), E = 16 / kSplit; + static_assert(N % 64 == 0 && kSplit > 1 && E % 4 == 0); + __shared__ int32_t s_offsets[kMaxExperts + 1]; + __shared__ float red[2][kThreads / 32]; + device::PDLWaitPrimary(); + device::PDLTriggerSecondary(); + load_offsets(offsets, experts, s_offsets); + int32_t const block = threadIdx.x / kSplit, part = threadIdx.x % kSplit; + bool const active = block < N / 16; + float const rcp = __frcp_rn(__fmul_rn(1536.0f, *w_denominator)); + int32_t parity = 0; + for (int32_t row = s_offsets[0] + blockIdx.x; row < s_offsets[experts]; row += gridDim.x, parity ^= 1) { + int32_t const expert = row_expert(s_offsets, experts, row); + float v[E]; +#pragma unroll + for (int i = 0; i < E; ++i) + v[i] = 0.0f; + if (active) { + uint4 raw[E / 4]; + uint4 const* src = reinterpret_cast(acc + int64_t(row) * 2 * N + block * 32 + part * 2 * E); +#pragma unroll + for (int i = 0; i < E / 4; ++i) + raw[i] = src[i]; + __nv_bfloat16 const* a = reinterpret_cast<__nv_bfloat16 const*>(raw); + float scale = __fmul_rn(__fmul_rn(acc_amax[row], w_amax[expert]), rcp); + float gamma = gammas[row]; +#pragma unroll + for (int i = 0; i < E; ++i) { + float gate = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * i]), scale))); + float up = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(a[2 * i + 1]), scale))); + v[i] = __bfloat162float(__float2bfloat16_rn(N52_SWIGLU(gate, up, gamma, gate_cap, up_cap))); + } + } + float block_max = part_max(v); + float amax = block_max_reduce(block_max, red[parity]); + uint32_t packed; + uint8_t scale_bits; + quantize_part(v, amax, block_max, packed, scale_bits); + if (active) { + if (threadIdx.x == 0) amax_out[row] = amax; + store_part(values, x_scales, s_offsets, expert, row, block, part, N, packed, scale_bits); + } + if (row == s_offsets[expert + 1] - 1) zero_expert_tail(s_offsets, expert, x_scales, (N + 63) / 64 * 4); + } +} + +// = the image's nvfp4_swiglu_quantize host wrapper for N = 1152 (same checks, grid and PDL launch), kernel swiglu_quantize_l5. +void swiglu_quant_l5( + tvm::ffi::TensorView acc, + tvm::ffi::TensorView acc_amax, + tvm::ffi::TensorView w_amax, + tvm::ffi::TensorView w_denominator, + tvm::ffi::TensorView gammas, + tvm::ffi::TensorView values, + tvm::ffi::TensorView x_scales, + tvm::ffi::TensorView amax, + tvm::ffi::TensorView offsets, + double gate_cap, + double up_cap, + int64_t sm_count) { + using namespace sglang::inkling2_routed_quant; + constexpr int N = 1152; + constexpr int64_t kPart = 16 / split(N); + auto rows = host::SymbolicSize{"routed rows"}; + auto scale_rows = host::SymbolicSize{"scale rows"}; + auto device = host::SymbolicDevice{}; + device.set_options(); + int32_t const experts = sglang::inkling2_routed_quant_sm120::verify_offsets(offsets, device); + host::TensorMatcher({rows, 2 * N}).with_dtype().with_device(device).ensure_alignment(16).verify(acc); + host::TensorMatcher({rows}).with_dtype().with_device(device).verify(acc_amax).verify(gammas).verify(amax); + host::TensorMatcher({int64_t{experts}}).with_dtype().with_device(device).verify(w_amax); + host::TensorMatcher({1}).with_dtype().with_device(device).verify(w_denominator); + host::TensorMatcher({rows, N / 2}).with_dtype().with_device(device).ensure_alignment(kPart / 2).verify(values); + host::TensorMatcher({scale_rows, N / 16}).with_dtype().with_device(device).verify(x_scales); + int32_t const num_rows = sglang::inkling2_routed_quant_sm120::verify_rows(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_size(num_rows, static_cast(sm_count)), split_threads(N), device.unwrap()) + .enable_pdl(true)( + swiglu_quantize_l5, + static_cast<__nv_bfloat16 const*>(acc.data_ptr()), + static_cast(acc_amax.data_ptr()), + static_cast(w_amax.data_ptr()), + static_cast(w_denominator.data_ptr()), + static_cast(gammas.data_ptr()), + static_cast(values.data_ptr()), + static_cast(x_scales.data_ptr()), + static_cast(amax.data_ptr()), + static_cast(offsets.data_ptr()), + experts, + static_cast(gate_cap), + static_cast(up_cap)); +} + +} // namespace sglang::n381c_band diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/sitecustomize.py b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/sitecustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..65a0a02a51338efee5bab92abe8ea1c65b35aa7d --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_n419j/sitecustomize.py @@ -0,0 +1,123 @@ +"""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 os +import 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_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) diff --git a/recipe/stack/cands/n419j3-2416d17a/overlay_pcopyro/inkling_pcopyro/__init__.py b/recipe/stack/cands/n419j3-2416d17a/overlay_pcopyro/inkling_pcopyro/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d67c71741dace254fee1fd7a15e7153f462cbc91 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/overlay_pcopyro/inkling_pcopyro/__init__.py @@ -0,0 +1,170 @@ +"""inkling_pcopyro (n405, dflash): inkling_pcopy's prompt copy on a RING-OFF DFLASH drafter (the n391 Global-L13 forms). + + INKLING_DFLASH_PCOPY_RINGOFF=1 (needs INKLING_DFLASH_PCOPY=12 and inkling_pcopy installed first; unset -> nothing) + +inkling_pcopy (knapcio v2.9.7, MIT, byte-identical; untouched here) arms only through the draft KV ring: + - its history is allocated in a wrapper of DFlashWorkerV2._init_draft_kv_ring, which the stock worker calls only when + speculative_dflash_draft_kv_ring is set (dflash_worker_v2.py:1127-1128, inside alloc_memory_pool); + - its history is charged to the KV budget in a wrapper of KVCacheConfigurator._dflash_draft_kv_ring_bytes, which returns + early when the stock value is <= 0, and that value is 0 ring-off (kv_cache_configurator.py:2954-2956; subtracted at :3311); + - its refusal() returns 'no DFLASH draft KV ring'. +Nothing else in the lever reads the ring (history / matcher / fused / rule / the three step hooks). So this overlay adds, for +ring-off servers only, two OUTER wrappers registered on inkling_pcopy's own import hook (after its patches): + 1. KVCacheConfigurator._dflash_draft_kv_ring_bytes: on the target configurator (not is_draft_worker) with the ring off, add the + history bytes, using pcopy's own rows / cap formula, and record them in inkling_pcopy.patch.STATE['charged']; + 2. DFlashWorkerV2.alloc_memory_pool: after the stock body, with the ring off, run pcopy's OWN init (make_init_ring around a + no-op), with a sentinel in worker.draft_kv_ring for the duration of that call. pcopy's refusal() then skips only its + ring line and keeps every other refusal (the verify-cap steplog included); the sentinel is removed before anything else + runs. On success pcopy logs its own 'prompt copy armed: ...' and this overlay logs 'armed ring-off'. +Ring on: both wrappers are pass-through. Every wrapped or relied-on source is pinned by sha256 (the image's two functions +and inkling_pcopy/patch.py's refusal / make_init_ring / make_ring_bytes / _disable); any drift refuses at start-up. +Logged: '[inkling_pcopyro pid=N] installed', '... history X MiB charged ring-off (R rows x C positions)', '... armed ring-off'. +""" + +import os +import sys + +ENV = "INKLING_DFLASH_PCOPY_RINGOFF" +MARK = "_inkling_pcopyro" +STATE = {"installed": False, "charged": None, "armed": 0} +PINS_SGLANG = { + "srt/speculative/dflash_worker_v2.py": { + "DFlashWorkerV2.alloc_memory_pool": "580e303e9b136958878833c58cd257a0c44b848f8459b902822aba9934f63c46", + }, + "srt/mem_cache/kv_cache_configurator.py": { + "KVCacheConfigurator._dflash_draft_kv_ring_bytes": "40c31b2ba28694b9c39b0f27ae14595294e8042998009656b21f88350a1ed471", + }, +} +PINS_PCOPY = { # inkling_pcopy/patch.py (the logic this overlay calls) + "refusal": "7aff15499b5b9bea049d05fe63e214e0f882546784c6daa29a1b94d47c944795", + "make_init_ring": "2ce88a78265a1bab90d47a8e67967af04598b0bf73302b68b2b19a4a4cba8ed5", + "make_ring_bytes": "0a886701162861df93a59b45a588f932137237f8de6e110221cc44ec6bbec271", + "_disable": "6bf4ff029282a04e040f89386d1ffec87103768bea4db2f54979333cc0b0c5ba", +} + + +class _RingSentinel: + """Stands in for the draft KV ring only inside pcopy's own init call (its refusal checks 'is None' and nothing else).""" + + +def _log(msg): + sys.stderr.write(f"[inkling_pcopyro pid={os.getpid()}] {msg}\n") + sys.stderr.flush() + + +def check_sources(sglang_root=None, pcopy_patch_path=None): + """Refuses (RuntimeError) on any pinned-source drift.""" + import inkling_pcopy._sources as S + + base = sglang_root or S.sglang_root() + bad = [] + for rel, pins in PINS_SGLANG.items(): + with open(os.path.join(base, rel), encoding="utf-8") as fh: + text = fh.read() + bad += [(rel, q, (S.digest(text, q) or "missing")[:12]) for q, want in pins.items() if S.digest(text, q) != want] + if pcopy_patch_path is None: + import inkling_pcopy.patch as P + pcopy_patch_path = P.__file__ + with open(pcopy_patch_path, encoding="utf-8") as fh: + text = fh.read() + bad += [("inkling_pcopy/patch.py", q, (S.digest(text, q) or "missing")[:12]) for q, want in PINS_PCOPY.items() if S.digest(text, q) != want] + if bad: + raise RuntimeError(f"inkling_pcopyro: pinned sources differ: {bad} (set DFLASH_PCOPY_RINGOFF=0 to run without it)") + + +def make_charge(orig): + def _dflash_draft_kv_ring_bytes(self): + value = orig(self) + from sglang.srt.runtime_context import get_schedule, get_spec + + if self.is_draft_worker or get_spec().speculative_dflash_draft_kv_ring: + return value # the draft configurator, or ring on: inkling_pcopy's own path + import inkling_pcopy.history as hmod + import inkling_pcopy.patch as P + + max_num_reqs = max(1, get_schedule().max_running_requests // self.attn_dp_size) + rows = self._req_pool_rows(max_num_reqs) + self._req_pool_pre_alloc_size() + 2 # = pcopy's formula (patch.py:54-56) + cap = int(self.model_config.context_len) + P.CAP_PAD + hist = hmod.History.bytes_for(rows, cap) + P.STATE["charged"] = hist + STATE["charged"] = hist + _log(f"history {hist / 2**20:.1f} MiB charged ring-off ({rows} rows x {cap} positions)") + return value + hist + + _dflash_draft_kv_ring_bytes.__wrapped__ = orig + setattr(_dflash_draft_kv_ring_bytes, MARK, True) + return _dflash_draft_kv_ring_bytes + + +def arm(worker): + """pcopy's own init on a ring-off worker; returns True when armed.""" + import inkling_pcopy.patch as P + + if getattr(worker, "draft_kv_ring", None) is not None or getattr(worker, "_inkling_pcopy", None) is not None: + return False + init = P.make_init_ring(lambda self: None) + worker.draft_kv_ring = _RingSentinel() + try: + init(worker) + finally: + worker.draft_kv_ring = None + if getattr(worker, "_inkling_pcopy", None) is None: + return False # pcopy logged its own 'prompt copy inert: ' + STATE["armed"] += 1 + _log("armed ring-off") + return True + + +def make_alloc(orig): + def alloc_memory_pool(self, *args, **kwargs): + out = orig(self, *args, **kwargs) + arm(self) + return out + + alloc_memory_pool.__wrapped__ = orig + setattr(alloc_memory_pool, MARK, True) + return alloc_memory_pool + + +def patch_config(mod): + cls = getattr(mod, "KVCacheConfigurator", None) + fn = getattr(cls, "_dflash_draft_kv_ring_bytes", None) + if fn is None or not getattr(fn, "_inkling_pcopy", False): + raise RuntimeError("inkling_pcopyro: inkling_pcopy's charge wrapper is not installed (install inkling_pcopy first)") + if getattr(fn, MARK, False): + return False + cls._dflash_draft_kv_ring_bytes = make_charge(fn) + return True + + +def patch_worker(mod): + cls = getattr(mod, "DFlashWorkerV2", None) + if cls is None or not getattr(getattr(cls, "_plan_verify", None), "_inkling_pcopy", False): + raise RuntimeError("inkling_pcopyro: inkling_pcopy's worker hooks are not installed (install inkling_pcopy first)") + if getattr(cls.alloc_memory_pool, MARK, False): + return False + cls.alloc_memory_pool = make_alloc(cls.alloc_memory_pool) + return True + + +def install(env=None, sglang_root=None): + env = os.environ if env is None else env + if STATE["installed"] or env.get(ENV, "").strip() in ("", "0"): + return False + if env.get(ENV, "").strip() != "1": + raise RuntimeError(f"inkling_pcopyro: {ENV}={env.get(ENV)!r}: only 1 (or 0 / unset) is supported") + import inkling_pcopy + from inkling_pcopy import _hook + import inkling_pcopy.patch as P + + if not inkling_pcopy.STATE.get("installed") or not inkling_pcopy.STATE.get("key"): + raise RuntimeError("inkling_pcopyro: inkling_pcopy is not installed with a key (INKLING_DFLASH_PCOPY=12 first)") + check_sources(sglang_root) + loaded = [m for m in P.MODULES if m in sys.modules] + if loaded: + raise RuntimeError(f"inkling_pcopyro: install before {loaded} are imported") + STATE["installed"] = True + _hook.when_imported(P.CONFIG_MODULE, patch_config) # pcopy's own hook: its callbacks (registered first) run first + _hook.when_imported(P.WORKER_MODULE, patch_worker) + _log("installed") + return True diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/CREDITS.md b/recipe/stack/cands/n419j3-2416d17a/recipe/CREDITS.md new file mode 100644 index 0000000000000000000000000000000000000000..c21f38fd1177e6925575871e8052fa35d99fe663 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/CREDITS.md @@ -0,0 +1,94 @@ +# 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.1 +recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bit +draft 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. diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/LICENSE b/recipe/stack/cands/n419j3-2416d17a/recipe/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..272aceba2ac697cd358e703c7e849e738e9b83c3 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Zbigniew Majewski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/NOTICE b/recipe/stack/cands/n419j3-2416d17a/recipe/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..d1ae19376d8e6f56690206da57d8a30de168440e --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/NOTICE @@ -0,0 +1,54 @@ +Inkling-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; the +prompts 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. diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/CREDITS.knapcio-v2.9.3.md b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/CREDITS.knapcio-v2.9.3.md new file mode 100644 index 0000000000000000000000000000000000000000..c21f38fd1177e6925575871e8052fa35d99fe663 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/CREDITS.knapcio-v2.9.3.md @@ -0,0 +1,94 @@ +# 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.1 +recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bit +draft 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. diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/LICENSE.knapcio-v2.9.3 b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/LICENSE.knapcio-v2.9.3 new file mode 100644 index 0000000000000000000000000000000000000000..272aceba2ac697cd358e703c7e849e738e9b83c3 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/LICENSE.knapcio-v2.9.3 @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Zbigniew Majewski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/NOTICE.knapcio-v2.9.3 b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/NOTICE.knapcio-v2.9.3 new file mode 100644 index 0000000000000000000000000000000000000000..d1ae19376d8e6f56690206da57d8a30de168440e --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/NOTICE.knapcio-v2.9.3 @@ -0,0 +1,54 @@ +Inkling-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; the +prompts 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. diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/README.md b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..84f2346ef41f258c87b699dfe577386f3c506a01 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/README.md @@ -0,0 +1,164 @@ +# inkling_attn: prefill attention with the relative bias computed in-kernel + +Switch: `INKLING_ATTN=prefill_swa[,prefill_global]` (or `all`); unset = nothing is imported. + +## What it replaces + +Stock prefill, per layer visit (`Inkling2Attention._forward`, non-compact branch): + +1. `RelLogitsProj`: cuBLAS einsum `thd,de->the`, writes BF16 `[t, 24, 1024]` (403 MB for an 8K chunk); +2. FA4 SM120 (`flash_attn_with_kvcache` -> `_flash_attn_varlen_func`): a shear kernel copies it into + `[round_up(t, 64), 24, 1280]`, then the attention mainloop TMA-loads 2 bytes of bias per score. + +(`inkling_prefill.bias_layout` fuses 1 and the shear copy; the mainloop still reads the sheared tensor.) + +With this package, one CUDA kernel (`csrc/attn_kernel.cuh`) computes the bias inside the attention mainloop: each +warp holds its 16 query rows' `r` (`[16, 16]`, the rel-clip output) as an MMA A fragment, multiplies it by the +`proj` columns of the tile's 79 distances (10 extra m16n8k16 MMAs per 16 x 64 tile, about +8 % MMA work), stages +the BF16-rounded `[16, 80]` result in shared memory and reads it back sheared. No `[t, 24, 1024]` tensor exists. +FA2-style kernel: 4 warps x 16 rows (BM 64), 64-key tiles, Q in registers, cp.async K/V from the paged cache +(page 128), ldmatrix on XOR-swizzled rows, FP32 online softmax, BF16 P, FP32 output + LSE in FA4's layout. +232-236 registers, no spills, 43 KB smem, 2 CTAs per SM. `proj` is repacked per call by a tiny kernel so each lane loads its +B fragment with one 8-byte load. + +| lever | layers | taken calls | +|---|---|---| +| `prefill_swa` | 40 sliding-window visits per token (window 1024) | prefill / extend, BF16 KV, no CP, no breakable graph | +| `prefill_global` | 8 global visits per token | same; bias work only on tiles within 1024 keys of the diagonal | + +Decode, target verify and draft extend never enter a visit (stock paths untouched). + +## Long prefixes: 8 warps from `INKLING_ATTN_W8_FROM` keys (default 131072) + +The 4-warp kernel (BM 64, 2 CTAs / SM) keeps ~71 TF/s up to ~256-320K prefix keys in isolation (~150K in serving) +and falls to the stock rate (~47 TF/s) at 512K-1M as its K/V traffic per FLOP stops being served from L2. The 8-warp +instantiation (BM 128, half the bytes per FLOP) holds ~69 TF/s at every prefix and computes every row +bit-identically. On global layers, for the BF16 loader and the packed-prefix loader alike, the binding launches two +grids per call (`launch_global`): requests whose prefix (seqused_k - new rows) is >= `INKLING_ATTN_W8_FROM` run on +8 warps, the others on 4; each CTA reads its request's lengths on the device and returns before any shared-memory +access when the other grid owns the request (no host sync, CUDA-graph capturable). `INKLING_ATTN_W8_FROM=0`, SWA +layers and `INKLING_ATTN_WARPS=8` keep a single launch. Checks: `tests/test_w8split_cpu.py`, +a development GPU check, not shipped (both loaders, 256K-1M, graph replay). + +## Math and exactness + +Same math as stock: bias = BF16(FP32 dot of r and proj) for distances 0..1023 (0 beyond on global layers), +s = qk * scale + bias in FP32, causal (+ window 1023 on SWA layers), P rounded to BF16 before PV, FP32 output, +natural-log LSE (-inf for a row with no key). Differences are FP32 accumulation order (QK, bias dot, PV and +online-softmax tile boundaries: 64 keys here, 128 in FA4). Measured against an FP32 reference (no TF32) on real +`proj` weights: see Results; the kernel's error is at or below stock FA4's at every shape. + +## Patch points (patch.py) + +- `Inkling2Attention._forward`: marks an eligible visit (context variable); nothing else changes. +- `RelLogitsProj.__call__`: inside the visit returns `r` itself (no einsum); SGLang then narrows it like any + `rel_bias` (row prefix views keep the data pointer). +- `flash_attention_v4_sm120._flash_attn_varlen_func`: a `rel_bias` that is (a row prefix of) the visit's `r` runs + `ops.prefill_attention` with the layer's `proj` and returns FA4's `(out, lse)`; a call the kernel does not cover + falls back to stock FA4 with the einsum bias; an `r` marker outside its visit raises. + +Install-time checks: `check_sources` looks for the exact code the patches rely on in the installed sglang +(`_forward`, `RelLogitsProj`, the SM120 wrapper, the backend's `rel_bias` / LSE handling, FA4's bias application +and shear pads, the SM120 module selection, CP and breakable-graph helpers); a mismatch raises (exit 78 through +sitecustomize). `RelLogitsProj.forward`'s signature is checked at patch time. + +## Arming (sitecustomize.py) + +Add after the `INKLING_PREFILL` block (order does not matter for correctness; see coexistence): + +```python + if _on("INKLING_ATTN"): + import inkling_attn + inkling_attn.install() +``` + +and forward `INKLING_ATTN` into the container in `scripts/launch.sh` like the other switches. The extension is +built when the model imports `inkling2_attn` (before any CUDA-graph capture), about 1 min on the first start, then +reused from `INKLING_ATTN_CACHE` (default `/root/.cache/inkling-attn`). Pre-build once with +`python3 -m inkling_attn.build`. Start-up log: `[inkling_attn pid=...] enabled prefill_swa ...` and +`extension built|reused ...`. `inkling_attn.patch.STATS` counts kernel / fallback / shadowed visits (eager mode). + +## Coexistence with inkling_prefill + +- `bias_layout` becomes unnecessary for the layers this package takes: in their visits `RelLogitsProj.__call__` + returns `r` before `bias_layout`'s `forward` wrapper runs, and `bias_layout`'s varlen wrapper passes the width-16 + marker through. Layers not taken (e.g. global layers with only `prefill_swa`) still get `bias_layout`. Keeping + `bias_layout` armed is therefore harmless and useful for `prefill_swa`-only. +- Works in either install order (dispatch is at `__call__`, one level before any `forward` wrapper). +- `qkvr_split`, `quant_once`, `partial_bf16`: independent. + +## CUDA graphs + +SGLang captures prefill graphs for this model (Backend.FULL, buckets up to `chunked_prefill_size` 8192, chunks +with a prefix replay too; docs/prefill/PREFILL.md 2.3). The kernel is captured inside them: static grid +`(cdiv(q rows, 64) + requests) x heads`, every request split read from `cu_seqlens_q` / `seqused_k` on the device, +no host sync, no allocation except the LSE `torch.empty` (graph pool). Rows past `cu_seqlens_q[-1]` are not +written, as FA4. Breakable prefill graphs (attention replayed outside the visit) are excluded. + +## Results (GB10, clocks untouched, 2026-11-21) + +`results/kbench/round2/attn/check_attn.py`, run5 (`runs/run5.log`, `runs/results_run5.json`). Inputs: real layer-0 / layer-5 +`proj`, q, k ~ N(0, 1.5^2), v ~ N(0, 1), r ~ N(0, 2^2), shuffled pages of 128. + +**Correctness**: max abs error vs an FP32 reference (no TF32, the stock BF16-rounded bias), sampled rows incl. +query-block edges, all 24 heads: + +| case | kind | out err ours / stock | LSE err ours / stock | +|---|---|---|---| +| chunk 8192, prefix 0 | SWA / global | 5.149e-3 / 5.149e-3, 3.437e-3 / 3.437e-3 | 1.647e-3 / 1.646e-3, 5.7e-6 / 1.5e-5 | +| chunk 8192, prefix 8K | SWA / global | 3.678e-3 / 3.682e-3, 2.463e-3 / 2.452e-3 | 2.375e-4 / 2.384e-4, 7.06e-5 / 7.15e-5 | +| chunk 8192, prefix 32K | SWA / global | 2.609e-3 / 2.606e-3, 5.686e-3 / 5.735e-3 | 4.0e-5 / 4.0e-5, 1.698e-3 / 1.698e-3 | +| chunk 2048, prefix 0 | SWA / global | 3.633e-3 / 3.634e-3, 3.870e-3 / 3.869e-3 | 3.8e-6 / 3.8e-6, 9.3e-5 / 9.3e-5 | +| 5 requests + empty slots | SWA / global | 3.732e-3 / 3.732e-3, 3.548e-3 / 3.548e-3 | 2.77e-5 / 2.67e-5, 4.1e-5 / 4.1e-5 | +| tiny rows (1, 3, 65, 17) | SWA / global | 3.653e-3 / 3.653e-3, 3.141e-3 / 3.141e-3 | 1.9e-6 / 2.9e-6, 1.9e-6 / 2.9e-6 | + +Ours and stock are equally far from the reference (both dominated by the BF16 rounding of P); the worst relative +excess is +0.4 % on out and +3.6 % on one LSE at the 1e-5 absolute level. No NaN, every covered row written. +CUDA-graph capture replayed with 4 different request splits: bit-equal to eager, rows past `cu_seqlens_q[-1]` +untouched. Patch routing: wrapper == direct call, fallback == stock bit for bit, escaped marker raises, +RelLogitsProj dispatch correct in both install orders with bias_layout. CPU emulation of the lane-level index +math (`emulate_kernel.py`) matches a dense FP64 reference. + +**Speed** (cold L2: 128 MiB read before each rep; median of 20; useful FLOPs = 4 * 24 * 128 * visible keys; +stock = einsum + FA4 with shear; bias_layout = Triton sheared bias + FA4 presheared; ours = repack + kernel): + +| kind | chunk | prefix | stock us (TF/s) | bias_layout us (TF/s) | ours us (TF/s) | vs stock | vs bias_layout | +|---|---|---|---|---|---|---|---| +| SWA | 2048 | 0 | 2336 (8.3) | 1561 (12.4) | 427 (45.2) | 5.47x | 3.65x | +| SWA | 2048 | 8K | 2453 (10.5) | 1680 (15.3) | 524 (49.2) | 4.68x | 3.20x | +| SWA | 2048 | 32K | 2465 (10.5) | 1672 (15.4) | 520 (49.5) | 4.74x | 3.21x | +| SWA | 8192 | 0 | 9659 (10.0) | 6245 (15.5) | 1846 (52.3) | 5.23x | 3.38x | +| SWA | 8192 | 8K | 9830 (10.5) | 6420 (16.1) | 1933 (53.3) | 5.08x | 3.32x | +| SWA | 8192 | 32K | 9816 (10.5) | 6419 (16.1) | 1966 (52.4) | 4.99x | 3.26x | +| global | 2048 | 0 | 2460 (10.5) | 1684 (15.3) | 520 (49.6) | 4.73x | 3.24x | +| global | 2048 | 8K | 6735 (34.4) | 5881 (39.4) | 3298 (70.3) | 2.04x | 1.78x | +| global | 2048 | 32K | 19753 (43.1) | 18934 (44.9) | 12063 (70.5) | 1.64x | 1.57x | +| global | 8192 | 0 | 16780 (24.6) | 13336 (30.9) | 6259 (65.9) | 2.68x | 2.13x | +| global | 8192 | 8K | 33887 (36.5) | 30264 (40.9) | 17916 (69.0) | 1.89x | 1.69x | +| global | 8192 | 32K | 86358 (43.0) | 82526 (45.0) | 53135 (69.8) | 1.63x | 1.55x | +| global | 8192 | 120K | 279140 (45.8) | 275093 (46.5) | 179440 (71.2) | 1.56x | 1.53x | + +(The einsum alone is 2.0 ms per 8K chunk.) Global layers reach the bias-free FA4 rate (67-70 TF/s in +docs/prefill/PREFILL.md); SWA reaches 52-53 TF/s against FA4's bias-free 55-56. + +Variants measured (run4): `INKLING_ATTN_WARPS=8` (BM 128, 1 CTA / SM) is 4-15 % slower; the unpacked proj loads +(4 x LDG.16 per fragment instead of one 8-byte load) are 10-12 % slower on SWA. Defaults: 4 warps, packed. + +**End-to-end estimate** (`estimate_e2e.py`: per 8K chunk, 40 SWA + 8 global visits at the measured per-visit +times, global interpolated over the prefix): + +| prompt | recipe today (all inkling_prefill levers) | + inkling_attn (SWA only) | + inkling_attn (SWA + global) | +|---|---|---|---| +| 8K | 1.93 s, 4,253 tok/s | 1.75 s | 1.69 s, ~4,840 tok/s (-12 %) | +| 32K | 8.28 s, 3,958 tok/s | 7.57 s | 7.08 s, ~4,630 tok/s (-15 %) | +| 128K | 47.7 s, 2,749 tok/s | 44.8 s | 38.3 s, ~3,420 tok/s (-20 %) | + +Against the stock engine (no inkling_prefill): 2.40 -> 2.00 s, 10.1 -> 8.2 s, 54.0 -> 42.0 s. Microbench-based; +to be confirmed by the serving benchmark. + +## Files + +- `csrc/attn_kernel.cuh` kernel, `csrc/inkling_attn_ext.cu` binding, `build.py`, `ops.py`, `patch.py`, `__init__.py`. +- Tests: `tests/test_install.py` (CPU: env parsing, source checks). GPU tests and bench (scratch): `results/kbench/round2/attn/check_attn.py` (GPU: correctness vs FP32 reference and stock, graph + replay, patch routing, microbench), `emulate_kernel.py` (CPU emulation of the kernel's lane-level index math), + `estimate_e2e.py` (end-to-end estimate from the bench). diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/__init__.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..789f18b8ffaa237c9f342de9540389b1b618d3bd --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/__init__.py @@ -0,0 +1,170 @@ +"""Inkling-2-Mini prefill attention overlay for SGLang on DGX Spark (GB10, sm_121). + + INKLING_ATTN=prefill_swa[,prefill_global] (or "all") + unset / empty: install() does nothing and nothing is imported. + +prefill_swa sliding-window layers (40 of the 48 layer visits) at prefill / extend: one CUDA kernel computes + the relative-position bias inside the attention mainloop (from r [t, 24, 16] and proj [16, 1024]) + instead of the stock einsum -> [t, 24, 1024] BF16 tensor -> FA4 shear copy -> FA4 with bias. +prefill_global the same for the 8 global (causal) visits; the bias is non-zero only within 1024 keys of the + diagonal, so most key tiles of a long prefix run without bias work. + +Decode, target verify and draft extend are untouched. Same math as stock (BF16-rounded bias, FP32 scores, +BF16 P, FP32 output and LSE); differences are FP32 accumulation order only (see README.md for the measured +error against an FP32 reference, side by side with stock FA4's). + +install() parses the env, checks the patch targets in the installed sglang sources (without importing sglang), +registers post-import hooks and prints one line. Problems raise RuntimeError (the combined sitecustomize then +exits with code 78). The CUDA extension is built (or reused from INKLING_ATTN_CACHE, default +~/.cache/inkling-attn) when the Inkling attention module is imported, before any CUDA graph capture. +INKLING_ATTN_VERBOSE=1 logs each applied patch. +""" + +import importlib.util +import os +import sys + +from . import _hook + +LEVERS = ("prefill_swa", "prefill_global") + +ATTN = "srt/models/inkling_common/inkling2_attn.py" + +_SOURCE_CHECKS = ( + (ATTN, ( + "class Inkling2Attention(", + "def _forward(self, hidden_states, positions, forward_batch, *, attn, attn_padded):", + "rel_bias = self.rel_logits_proj(r)", + "attention_kwargs = dict(rel_bias=rel_bias, **bias_kwargs)", + "from sglang.srt.model_executor.forward_context import get_attn_backend", + "from sglang.srt.runtime_context import get_model, get_parallel, get_platform", + "self.rel_extent = config.sliding_window_size if is_local else config.rel_extent", + "sliding_window_size=config.sliding_window_size - 1 if is_local else -1", + "out_dtype=torch.float32", + "pack_gqa=False", + "return_lse=True,", + "r = self.rel_l2_clip(", + )), + ("srt/models/inkling_common/attn.py", ( + "class RelLogitsProj(", + "log_scaling_tau: torch.Tensor | None = None", + "self.proj = nn.Parameter(torch.empty(d_rel, rel_extent), requires_grad=False)", + 'return torch.einsum("thd,de->the", r, self.proj)', + )), + ("kernels/ops/attention/flash_attention_v4_sm120.py", ( + "_flash_attn_varlen_func,", + "result = _flash_attn_varlen_func(", + "seqused_k=cache_seqlens,", + 'rel_bias_kwargs["rel_bias"] = rel_bias', + "if window_size == (-1, -1):", + )), + ("srt/layers/attention/flashattention_backend.py", ( + 'kwargs["rel_bias"] = rel_bias', + "softmax_lse.T", + "cache_seqlens=cache_seqlens,", + )), + ("kernels/ops/attention/fa4_sm120/flash_fwd.py", ( + "acc_S[i] = acc_S[i] * base_softmax_scale", + "sBias[row, col, consumer_state.index].to(", + )), + ("kernels/ops/attention/flash_attn/cute/shearing_bias.py", ( + "-Float32.inf if const_expr(window_size_left is not None) else 0.0", + )), + ("kernels/ops/attention/flash_attn/cute/interface.py", ( + "else (num_head, total_q)", + )), + ("srt/model_executor/runner_backend_utils/breakable_cuda_graph/context.py", ( + "def is_in_breakable_cuda_graph(", + )), + ("srt/layers/cp/utils.py", ( + "def is_cp_active(forward_batch) -> bool:", + )), + ("srt/layers/attention/flashattention_backend.py", ( + "if device_capability[0] == 12:", + "from sglang.kernels.ops.attention.flash_attention_v4_sm120 import (", + )), +) + +STATE = {"installed": False, "levers": (), "applied": []} + + +def _log(msg): + sys.stderr.write(f"[inkling_attn pid={os.getpid()}] {msg}\n") + sys.stderr.flush() + + +def parse_levers(value): + items = [v.strip() for v in value.split(",") if v.strip()] + items = [v for v in items if v.lower() not in ("0", "off", "none", "false", "no")] + if "all" in items: + items = list(LEVERS) + [v for v in items if v != "all"] + levers = tuple(dict.fromkeys(items)) + unknown = [v for v in levers if v not in LEVERS] + if unknown: + raise RuntimeError(f"inkling_attn: unknown INKLING_ATTN entries {unknown}; known: {', '.join(LEVERS)}, all") + return levers + + +def sglang_root(): + spec = importlib.util.find_spec("sglang") # does not execute sglang + if spec is None or not spec.submodule_search_locations: + raise RuntimeError("inkling_attn: the sglang package is not importable") + return list(spec.submodule_search_locations)[0] + + +def check_sources(root=None): + root = root or sglang_root() + for rel, needles in _SOURCE_CHECKS: + path = os.path.join(root, rel) + try: + with open(path, encoding="utf-8") as f: + text = f.read() + except OSError as exc: + raise RuntimeError(f"inkling_attn: patch target {path} is missing") from exc + missing = [n for n in needles if n not in text] + if missing: + raise RuntimeError(f"inkling_attn: patch target {path} lacks {missing}") + + +def _attach(module_name, fn): + def callback(module): + fn(module) + STATE["applied"].append(module_name) + if os.environ.get("INKLING_ATTN_VERBOSE"): + _log(f"patched {module_name}") + + _hook.when_imported(module_name, callback) + + +def _register(levers): + from . import patch + + kinds = tuple(lv.split("_", 1)[1] for lv in levers) # "swa" / "global" + + def attn_cb(module): + patch.patch_attn(module, kinds) + if not os.environ.get("INKLING_ATTN_LAZY_BUILD"): + from . import build + + build.load() + info = build.INFO + _log(f"extension {'reused' if info['cached'] else 'built'} in {info['seconds']:.1f} s ({info['tag']})") + + _attach(patch.SM120_MODULE, patch.patch_sm120) + _attach(patch.COMMON_ATTN_MODULE, patch.patch_common_attn) + _attach(patch.ATTN_MODULE, attn_cb) + + +def install(levers=None, root=None): + """Activate the levers named in INKLING_ATTN (or `levers`). Idempotent.""" + if STATE["installed"]: + return STATE["levers"] + levers = parse_levers(os.environ.get("INKLING_ATTN", "") if levers is None else ",".join(levers)) + if not levers: + STATE["installed"] = True + return () + check_sources(root) + _register(levers) + STATE.update(installed=True, levers=levers) + _log("enabled " + " ".join(levers)) + return levers diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/_hook.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..d461a95a091b5c0581fc024013d31b28437df871 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/_hook.py @@ -0,0 +1,83 @@ +"""Post-import hooks: run a callback right after a module finishes executing. + +Patches attach lazily so that processes which never import the model pay nothing +and never import sglang or torch. If the target module is already imported, the +callback 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 the +loader the next one returned), so every package's callbacks run. +""" + +import importlib.abc +import sys +import 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) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/build.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/build.py new file mode 100644 index 0000000000000000000000000000000000000000..e39d2649dd43f5a2a5f2cf609e1a0183f9b4bb4a --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/build.py @@ -0,0 +1,102 @@ +"""Build (or reuse) the inkling_attn CUDA extension with torch.utils.cpp_extension. + +Sources: csrc/inkling_attn_ext.cu (binding) + csrc/attn_kernel.cuh (kernel), compiled for sm_121a into +//, where is INKLING_ATTN_CACHE (default ~/.cache/inkling-attn, i.e. /root/.cache/inkling-attn +in the container) and hashes the sources, the flags and the torch / CUDA versions, so a changed input never +reuses a stale build. Needs nvcc and ninja (both in the SGLang image); no GPU is needed to build. + + python3 -m inkling_attn.build # build now (once, before serving); prints the path +""" + +import hashlib +import os +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +SOURCES = (os.path.join(HERE, "csrc", "inkling_attn_ext.cu"),) +HEADERS = (os.path.join(HERE, "csrc", "attn_kernel.cuh"),) +NAME = "inkling_attn_ext" + +_UNDEF = ( + "-U__CUDA_NO_HALF_OPERATORS__", + "-U__CUDA_NO_HALF_CONVERSIONS__", + "-U__CUDA_NO_BFLOAT16_CONVERSIONS__", + "-U__CUDA_NO_HALF2_OPERATORS__", +) + + +def default_cache_dir(): + return os.environ.get("INKLING_ATTN_CACHE") or os.path.join(os.path.expanduser("~"), ".cache", "inkling-attn") + + +def cuda_flags(arch="121a"): + return [ + f"-gencode=arch=compute_{arch},code=sm_{arch}", + "-O3", + "-std=c++20", + "-lineinfo", + *_UNDEF, + ] + + +def build_tag(flags, torch_version, cuda_version): + h = hashlib.sha256() + for path in SOURCES + HEADERS: + with open(path, "rb") as f: + h.update(os.path.basename(path).encode() + b"\0" + f.read() + b"\0") + h.update("\0".join(flags).encode()) + h.update(f"\0{torch_version}\0{cuda_version}".encode()) + return h.hexdigest()[:16] + + +_EXT = None +INFO = {} + + +def load(cache_dir=None, arch="121a", verbose=False): + """Import the extension, building it first when / holds no build of these inputs.""" + global _EXT + if _EXT is not None: + return _EXT + import torch + from torch.utils import cpp_extension + + flags = cuda_flags(arch) + tag = build_tag(flags, torch.__version__, torch.version.cuda) + build_dir = os.path.join(cache_dir or default_cache_dir(), tag) + os.makedirs(build_dir, exist_ok=True) + cached = any(f.endswith(".so") and f.startswith(NAME) for f in os.listdir(build_dir)) + t0 = time.monotonic() + try: + ext = cpp_extension.load( + name=NAME, + sources=list(SOURCES), + extra_cuda_cflags=flags, + extra_include_paths=[os.path.join(HERE, "csrc")], + build_directory=build_dir, + verbose=verbose, + ) + except Exception as exc: # noqa: BLE001 + raise RuntimeError(f"inkling_attn: building the extension in {build_dir} failed: {exc}") from exc + if not callable(getattr(ext, "fwd", None)): + raise RuntimeError(f"inkling_attn: extension in {build_dir} lacks fwd()") + INFO.update(build_dir=build_dir, cached=cached, seconds=time.monotonic() - t0, tag=tag) + _EXT = ext + return ext + + +def main(argv=None): + import argparse + + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument("--cache", default=default_cache_dir()) + p.add_argument("--verbose", action="store_true") + a = p.parse_args(argv) + load(a.cache, verbose=a.verbose) + print(f"inkling_attn extension {'reused' if INFO['cached'] else 'built'} in {INFO['seconds']:.1f} s: {INFO['build_dir']}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/csrc/attn_kernel.cuh b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/csrc/attn_kernel.cuh new file mode 100644 index 0000000000000000000000000000000000000000..84948f6c6ed4c76de2e97baed070638609deae93 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/csrc/attn_kernel.cuh @@ -0,0 +1,555 @@ +// inkling_attn: prefill/extend attention for Inkling-2-Mini on GB10 (sm_121) with the relative-position bias +// computed inside the kernel. +// +// Math (the same as SGLang's FA4 path with rel_bias, flash_attn/cute/interface.py + fa4_sm120/flash_fwd.py): +// for request b, query row i (0 <= i < sq), absolute position p = i + (sk - sq), key j (0 <= j < sk): +// visible j <= p, and for sliding-window layers also j >= p - window_left +// d = p - j (relative distance) +// bias = bf16( sum_e r[t, h, e] * proj[e, d] ) if d < rel_extent, else 0 (FP32 dot, BF16 round: +// the stock cuBLAS einsum thd,de->the writes a BF16 tensor) +// s = qk * softmax_scale + bias (FP32) +// out = softmax_j(s) @ V (P rounded to BF16 before the PV MMA, as FA4 does), FP32 [T, H, 128] +// lse = ln(sum_j exp(s)) FP32 [H, T] (-inf when a row sees no key) +// +// Instead of reading a materialised [T, H, rel_extent] tensor (2 bytes per score from DRAM), each warp +// computes the bias of its 16 query rows x 64 keys tile from r (a 16 x 16 A fragment held in registers) and +// proj (10 B fragments, L1-cached loads) with 10 extra m16n8k16 MMAs, stages the 16 x 80 BF16 result in shared +// memory and reads it back sheared (element (a, b) of the score tile is T[a][a + 63 - b]). +// +// FA2-style: 4 warps x 16 query rows (BM = 64), BN = 64 keys a tile, Q fragments in registers, K and V single +// buffered with cp.async (the K load of the next tile overlaps PV, the V load overlaps QK + softmax), ldmatrix +// on 128-byte XOR-swizzled rows, online softmax in FP32. Paged KV (page size a multiple of 64), GQA by head index. +#pragma once + +#include +#include + +namespace inkling_attn { + +constexpr int kD = 128; // head dim +constexpr int kBN = 64; // keys a tile +constexpr int kDRel = 16; // r / proj inner dim +constexpr int kTCols = 16 + kBN; // staged bias columns a warp tile (79 used, +1 for the odd-row shift) +constexpr int kTStride = 88; // BF16 elements a staged row (bank-conflict check: <= 2-way) +constexpr float kLog2e = 1.4426950408889634f; +constexpr int tstage_bytes(int warps) { return warps * 16 * kTStride * 2; } + +struct Params { + const __nv_bfloat16* q; // [T, H, 128] + long long q_st, q_sh; + const __nv_bfloat16* k; // [pages, page_size, H_kv, 128] + long long k_sp, k_ss, k_sh; + const __nv_bfloat16* v; + long long v_sp, v_ss, v_sh; + // Packed planes share the byte stride of the allocator's page envelope. + const uint8_t *sm, *ex; + const int *esc, *off, *overflow_ref, *flags; + const uint16_t *staging, *overflow; + long long packed_stride; + int kv_heads, stage_slots, overflow_slots; + const int* page_table; // [B, max_pages] + long long pt_s; + const int* cu_q; // [n_req + 1] + const int* seq_k; // [>= n_req] + int n_req; + const __nv_bfloat16* r; // [T, H, 16] + long long r_st, r_sh; + const __nv_bfloat16* proj; // [16, rel_extent] contiguous + const __nv_bfloat16* projp; // optional packed copy [rel_extent + 1, 16] (pack_proj), row rel_extent = 0 + int rel_extent; + float* out; // [T, H, 128] + long long o_st, o_sh; + float* lse; // lse[h * lse_sh + t] + long long lse_sh; + int heads, group, page_size; + int total_q; // rows of q (guards cu_seqlens_q) + int pt_cols; // page_table columns (guards seqused_k) + int num_pages; // pages of the KV cache (guards page ids) + float scale; + int window_left; // sliding-window layers only + // request selection (global layers, two launches of different warp counts over one call, see ops.W8_FROM): + // 0 = every request; 1 = requests whose prefix (seqused_k - new rows) is < sel_keys; 2 = prefix >= sel_keys. + int sel_mode, sel_keys; + // gated epilogue (kGate, sliding-window BF16 path): y[t, h*128 + d] = bf16(x * sigmoid(gate) * sigmoid(lse - sink)) + // with x = O / l, exactly SGLang's gate_sink kernel (inkling2/gate_sink.cuh) on the FP32 out and LSE this kernel + // would have written; out is then not written (lse still is). + const __nv_bfloat16* gate; // [T, H * 128], row stride g_st (16-byte aligned rows: staged with 16-byte loads) + long long g_st; + const __nv_bfloat16* sink; // [T, H], row stride s_st + long long s_st; + __nv_bfloat16* y; // [T, H * 128], row stride y_st + long long y_st; +}; + +namespace dev { + +__device__ __forceinline__ uint32_t smem_u32(const void* p) { + return static_cast(__cvta_generic_to_shared(p)); +} + +__device__ __forceinline__ void cp_async16(uint32_t dst, const void* src, bool valid) { + const int n = valid ? 16 : 0; // 0: zero-fill, nothing read + asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(dst), "l"(src), "r"(n) : "memory"); +} +__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;\n" ::: "memory"); } +__device__ __forceinline__ void cp_wait_all() { asm volatile("cp.async.wait_group 0;\n" ::: "memory"); } + +__device__ __forceinline__ void ldsm_x4(uint32_t& r0, uint32_t& r1, uint32_t& r2, uint32_t& r3, uint32_t addr) { + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) + : "r"(addr) + : "memory"); +} +__device__ __forceinline__ void ldsm_x4_t(uint32_t& r0, uint32_t& r1, uint32_t& r2, uint32_t& r3, uint32_t addr) { + asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) + : "r"(addr) + : "memory"); +} + +// D += A * B, m16n8k16, BF16 inputs, FP32 accumulate +__device__ __forceinline__ void mma(float (&c)[4], const uint32_t (&a)[4], 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"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); +} + +__device__ __forceinline__ float ex2(float x) { + float y; + asm("ex2.approx.ftz.f32 %0, %1;\n" : "=f"(y) : "f"(x)); + return y; +} + +__device__ __forceinline__ uint32_t pack_bf16(float lo, float hi) { + const __nv_bfloat162 v = __floats2bfloat162_rn(lo, hi); + return *reinterpret_cast(&v); +} + +__device__ __forceinline__ uint32_t ld_u32(const __nv_bfloat16* p) { + return __ldg(reinterpret_cast(p)); +} + +__device__ __forceinline__ uint32_t ld_u16(const __nv_bfloat16* p) { + return static_cast(__ldg(reinterpret_cast(p))); +} + +} // namespace dev + +// proj [16, E] -> projp [E + 1, 16]: row d = {P(0,d),P(1,d),P(8,d),P(9,d), P(2,d),P(3,d),P(10,d),P(11,d), ...}, +// i.e. lane qd's B-fragment words {P(2qd,d),P(2qd+1,d)} and {P(2qd+8,d),P(2qd+9,d)} are 8 contiguous bytes; +// row E is zero (distances beyond the extent). +__global__ void pack_proj(const __nv_bfloat16* __restrict__ proj, __nv_bfloat16* __restrict__ projp, int E) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; // one output element + if (i >= (E + 1) * kDRel) return; + const int d = i / kDRel, slot = i % kDRel; + const int qd = slot / 4, w = slot % 4; + const int e = 2 * qd + (w & 1) + 8 * (w >> 1); + projp[i] = d < E ? proj[e * E + d] : __float2bfloat16_rn(0.f); +} + +// Eight BF16 words for one swizzled shared-memory vector. No FP conversion. +__device__ __forceinline__ uint4 packed_vector(const Params& p, int page, int kind, + int head, int row, int dim, bool valid) { + const uint4 zero = make_uint4(0, 0, 0, 0); + if (!valid || page <= 0 || page >= p.num_pages) return zero; + const long long start = static_cast(page) * p.packed_stride; + const int flag = p.flags[start / sizeof(int)]; + if (flag <= 0) return zero; + const int element = ((kind * 128 + row) * p.kv_heads + head) * kD + dim; + if (flag >= 2) { + // The low byte stores valid rows plus one. The high bits store the slot. + const int slot = flag >> 8; + const int count = (flag & 255) - 1; + if (slot >= p.stage_slots || row >= count || count > 128) return zero; + const auto* src = p.staging + static_cast(slot) * 2 * 128 * p.kv_heads * kD; + return *reinterpret_cast(src + element); + } + const int lane = head * 2 + kind; + const int ref = p.overflow_ref[start / sizeof(int) + lane]; + if (ref) { + if (ref < 0 || ref > p.overflow_slots) return zero; + const auto* src = p.overflow + static_cast(ref - 1) * 128 * kD; + return *reinterpret_cast(src + row * kD + dim); + } + const auto sm = *reinterpret_cast(p.sm + start + element); + const uint32_t ex = *reinterpret_cast(p.ex + start + element / 2); + uint32_t words[4] = {}; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const uint32_t bits = ((i < 4 ? sm.x : sm.y) >> (8 * (i & 3))) & 255; + const uint32_t code = (ex >> (4 * i)) & 15; + const uint32_t exponent = code == 15 ? 0 : code + 116; + const uint32_t word = ((bits & 128) << 8) | (exponent << 7) | (bits & 127); + words[i / 2] |= word << (16 * (i & 1)); + } + if (((ex & (ex >> 1) & (ex >> 2) & (ex >> 3)) & 0x11111111u) != 0) { + const int* offsets = p.off + start / sizeof(int) + lane * 5 + row / 32; + const int* entries = p.esc + start / sizeof(int) + lane * 64; + const int begin = offsets[0], end = offsets[1]; + const int limit = begin >= 0 && end >= begin && end <= 64 ? end : begin; + for (int i = begin; i < limit; ++i) { + const unsigned entry = entries[i]; + const int column = (entry >> 16) & 127; + if (((entry >> 23) & 127) == row && column >= dim && column < dim + 8) { + const int index = column - dim, shift = (index & 1) * 16; + words[index / 2] = (words[index / 2] & ~(0xffffu << shift)) | ((entry & 0xffffu) << shift); + } + } + } + return make_uint4(words[0], words[1], words[2], words[3]); +} + +// kW warps x 16 query rows a CTA (BM = 16 kW): 4 warps -> 2 CTAs / SM, 8 warps -> 1 CTA / SM (half the K/V +// shared-memory fills per FLOP). Dynamic shared memory: tstage_bytes(kW). +// gate_sink.cuh's sigmoid: ex2.approx / rcp.approx with round-to-nearest multiply and add +__device__ __forceinline__ float gs_sigmoid(float x) { + float e, r; + float const t = __fmul_rn(-x, 1.4426950408889634f); + asm("ex2.approx.f32 %0, %1;" : "=f"(e) : "f"(t)); + asm("rcp.approx.f32 %0, %1;" : "=f"(r) : "f"(__fadd_rn(e, 1.0f))); + return r; +} + +template +__global__ void __launch_bounds__(kW * 32, 8 / kW) prefill_fwd(const Params p) { + constexpr int kThr = kW * 32; + constexpr int kBMw = 16 * kW; + using namespace dev; + __shared__ __align__(128) __nv_bfloat16 sK[kBN * kD]; + __shared__ __align__(128) __nv_bfloat16 sV[kBN * kD]; + extern __shared__ __align__(16) __nv_bfloat16 sT[]; // kW * 16 * kTStride (dynamic) + + const int tid = threadIdx.x; + const int warp = tid >> 5, lane = tid & 31, g = lane >> 2, qd = lane & 3; + + // ---- work item: heads fastest (the 24 heads of one query block share K/V in L2), the last query blocks + // (the most keys on causal global layers) first. + const int lin = static_cast(gridDim.x - 1 - blockIdx.x); + const int head = lin % p.heads; + int tile = lin / p.heads; + int b = -1, start = 0, sq = 0; + int prev_end = 0; + for (int i = 0; i < p.n_req; ++i) { + // metadata guards (CTA-uniform): rows inside q and never shared by two requests, keys inside the page table + const int s = max(p.cu_q[i], prev_end); + const int e = min(p.cu_q[i + 1], p.total_q); + const int len = e > s ? e - s : 0; + prev_end = max(prev_end, e); + const int nb = (len + kBMw - 1) / kBMw; + if (tile < nb) { + b = i; + start = s; + sq = len; + break; + } + tile -= nb; + } + if (b < 0) return; + + const int sk = min(max(p.seq_k[b], 0), p.pt_cols * p.page_size); + const int off = sk - sq; // prefix length + if (p.sel_mode != 0) { // the other launch takes request b (decided on the unclamped prefix) + const long long pre = static_cast(p.seq_k[b]) - sq; + if ((pre >= p.sel_keys) != (p.sel_mode == 2)) return; + } + const int m0 = tile * kBMw; + const int kvh = head / p.group; + const int wl = p.window_left; + const int lo_key = kLocal ? max(0, m0 + off - wl) : 0; + const int hi_key = static_cast(min(static_cast(sk), static_cast(m0) + kBMw + off)); + const int nb_lo = lo_key / kBN; + const int nb_hi = hi_key > lo_key ? hi_key / kBN + (hi_key % kBN != 0) : nb_lo; // exclusive + + const int wrow0 = m0 + warp * 16; // request-relative first row of this warp + const bool warp_rows = wrow0 < sq; + const int pw0 = wrow0 + off; // its absolute position + + // ---- Q and r fragments (A operands), rows wrow0 + g and + 8 + uint32_t qa[8][4]; + uint32_t ra[4]; + { + const int r0 = wrow0 + g, r1 = r0 + 8; + const bool v0 = r0 < sq, v1 = r1 < sq; + const long long t0 = start + (v0 ? r0 : 0), t1 = start + (v1 ? r1 : 0); + const __nv_bfloat16* q0 = p.q + t0 * p.q_st + static_cast(head) * p.q_sh; + const __nv_bfloat16* q1 = p.q + t1 * p.q_st + static_cast(head) * p.q_sh; +#pragma unroll + for (int kk = 0; kk < 8; ++kk) { + const int c = 16 * kk + 2 * qd; + qa[kk][0] = v0 ? ld_u32(q0 + c) : 0u; + qa[kk][1] = v1 ? ld_u32(q1 + c) : 0u; + qa[kk][2] = v0 ? ld_u32(q0 + c + 8) : 0u; + qa[kk][3] = v1 ? ld_u32(q1 + c + 8) : 0u; + } + const __nv_bfloat16* rr0 = p.r + t0 * p.r_st + static_cast(head) * p.r_sh; + const __nv_bfloat16* rr1 = p.r + t1 * p.r_st + static_cast(head) * p.r_sh; + ra[0] = v0 ? ld_u32(rr0 + 2 * qd) : 0u; + ra[1] = v1 ? ld_u32(rr1 + 2 * qd) : 0u; + ra[2] = v0 ? ld_u32(rr0 + 2 * qd + 8) : 0u; + ra[3] = v1 ? ld_u32(rr1 + 2 * qd + 8) : 0u; + } + + float o[16][4]; +#pragma unroll + for (int i = 0; i < 16; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.f; + float mrow[2] = {-INFINITY, -INFINITY}; + float lrow[2] = {0.f, 0.f}; + + // ---- one K or V tile of 64 keys -> shared memory (row = key, 16 chunks of 16 B, chunk ^= row & 7); + // keys outside [lo_key, sk) are zero-filled (never read from memory). + const long long pt_row = static_cast(b) * p.pt_s; + auto load_tile = [&](__nv_bfloat16* dst, const __nv_bfloat16* base, long long sp, long long ss, long long sh, + int nb, int kind) { + const int n0 = nb * kBN; + const int col = n0 / p.page_size; + const int page = col >= 0 && col < p.pt_cols ? p.page_table[pt_row + col] : -1; + const bool page_ok = page >= 0 && page < p.num_pages; // a bad page id reads nothing (zero tile) + const int slot0 = n0 % p.page_size; + const int chunk = tid & 15; +#pragma unroll + for (int i = 0; i < kBN * 16 / kThr; ++i) { + const int row = (tid >> 4) + i * (kThr / 16); + const int j = n0 + row; + const bool ok = page_ok && j >= lo_key && j < sk; + auto* target = dst + row * kD + ((chunk ^ (row & 7)) * 8); + if constexpr (kPackedKV) { + *reinterpret_cast(target) = packed_vector(p, page, kind, kvh, slot0 + row, chunk * 8, ok); + } else { + const auto* src0 = base + static_cast(page_ok ? page : 0) * sp + static_cast(kvh) * sh; + const auto* src = ok ? src0 + static_cast(slot0 + row) * ss + chunk * 8 : src0; + cp_async16(smem_u32(target), src, ok); + } + } + }; + + __nv_bfloat16* tw = sT + warp * 16 * kTStride; + const int par = g & 1; // odd rows are staged one column to the right so sheared reads are 4-byte aligned + const __nv_bfloat16* proj = p.proj; + const int ext = p.rel_extent; + + if (nb_hi > nb_lo) load_tile(sK, p.k, p.k_sp, p.k_ss, p.k_sh, nb_hi - 1, 0); + cp_commit(); + + for (int nb = nb_hi - 1; nb >= nb_lo; --nb) { + const int n0 = nb * kBN; + cp_wait_all(); + __syncthreads(); // K(nb) visible; every warp is done with V(nb + 1) + load_tile(sV, p.v, p.v_sp, p.v_ss, p.v_sh, nb, 1); + cp_commit(); + + // this warp's rows see keys [pw0 - wl, pw0 + 15] + const bool active = warp_rows && n0 <= pw0 + 15 && (!kLocal || n0 + kBN - 1 >= pw0 - wl); + float s[8][4]; + if (active) { +#pragma unroll + for (int i = 0; i < 8; ++i) s[i][0] = s[i][1] = s[i][2] = s[i][3] = 0.f; + // S = Q K^T +#pragma unroll + for (int kk = 0; kk < 8; ++kk) { +#pragma unroll + for (int np = 0; np < 4; ++np) { + const int key = 8 * (2 * np + (lane >> 4)) + (lane & 7); + const int chunk = 2 * kk + ((lane >> 3) & 1); + uint32_t b0, b1, b2, b3; + ldsm_x4(b0, b1, b2, b3, smem_u32(sK + key * kD + ((chunk ^ (key & 7)) * 8))); + mma(s[2 * np], qa[kk], b0, b1); + mma(s[2 * np + 1], qa[kk], b2, b3); + } + } + // relative bias: d(a, b) = pw0 + a - (n0 + b) = dbase + c, c = a + 63 - b in [0, 78] + const int dbase = pw0 - n0 - (kBN - 1); + if (dbase < ext) { + float t[10][4]; +#pragma unroll + for (int ct = 0; ct < 10; ++ct) { + t[ct][0] = t[ct][1] = t[ct][2] = t[ct][3] = 0.f; + const int d = dbase + 8 * ct + g; + const bool in = d >= 0 && d < ext; // d < 0: masked (causal); d >= ext: bias 0 + if constexpr (kPacked) { + const int row = in ? d : ext; // the zero row + const uint2 w = __ldg(reinterpret_cast(p.projp + static_cast(row) * kDRel) + qd); + mma(t[ct], ra, w.x, w.y); + } else { + const __nv_bfloat16* pc = proj + (in ? d : 0); + const uint32_t k0 = in ? ld_u16(pc + (2 * qd) * ext) : 0u; + const uint32_t k1 = in ? ld_u16(pc + (2 * qd + 1) * ext) : 0u; + const uint32_t k8 = in ? ld_u16(pc + (2 * qd + 8) * ext) : 0u; + const uint32_t k9 = in ? ld_u16(pc + (2 * qd + 9) * ext) : 0u; + mma(t[ct], ra, k0 | (k1 << 16), k8 | (k9 << 16)); + } + } +#pragma unroll + for (int ct = 0; ct < 10; ++ct) { + const int col = 8 * ct + 2 * qd + par; + tw[g * kTStride + col] = __float2bfloat16_rn(t[ct][0]); + tw[g * kTStride + col + 1] = __float2bfloat16_rn(t[ct][1]); + tw[(g + 8) * kTStride + col] = __float2bfloat16_rn(t[ct][2]); + tw[(g + 8) * kTStride + col + 1] = __float2bfloat16_rn(t[ct][3]); + } + __syncwarp(); +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int a = g + 8 * h; + const int s1 = a + (kBN - 2) - 8 * nt - 2 * qd + par; // even + const uint32_t w = *reinterpret_cast(tw + a * kTStride + s1); + const float b_e0 = __uint_as_float(w & 0xffff0000u); // column c -> key n0 + 8nt + 2qd + const float b_e1 = __uint_as_float(w << 16); // column c-1 -> key n0 + 8nt + 2qd + 1 + s[nt][2 * h] = fmaf(s[nt][2 * h], p.scale, b_e0); + s[nt][2 * h + 1] = fmaf(s[nt][2 * h + 1], p.scale, b_e1); + } + } + } else { +#pragma unroll + for (int i = 0; i < 8; ++i) { + s[i][0] *= p.scale; + s[i][1] *= p.scale; + s[i][2] *= p.scale; + s[i][3] *= p.scale; + } + } + // mask: causal diagonal, window left edge (rows past sq see zero-filled keys and are never stored) + const bool need_mask = (n0 + kBN - 1 > pw0) || (kLocal && n0 < pw0 + 15 - wl); + if (need_mask) { +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int a = g + 8 * (e >> 1); + const int j = n0 + 8 * nt + 2 * qd + (e & 1); + const int pr = pw0 + a; + if (j > pr || (kLocal && j < pr - wl)) s[nt][e] = -INFINITY; + } + } + } + // online softmax (natural-log units, exp2 with log2(e) like FA4) +#pragma unroll + for (int h = 0; h < 2; ++h) { + float mx = -INFINITY; +#pragma unroll + for (int nt = 0; nt < 8; ++nt) mx = fmaxf(mx, fmaxf(s[nt][2 * h], s[nt][2 * h + 1])); + mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 1)); + mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 2)); + const float mnew = fmaxf(mrow[h], mx); + const float muse = mnew == -INFINITY ? 0.f : mnew; + const float alpha = ex2((mrow[h] - muse) * kLog2e); + mrow[h] = mnew; + float sum = 0.f; +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { + const float p0 = ex2((s[nt][2 * h] - muse) * kLog2e); + const float p1 = ex2((s[nt][2 * h + 1] - muse) * kLog2e); + s[nt][2 * h] = p0; + s[nt][2 * h + 1] = p1; + sum += p0 + p1; + } + lrow[h] = lrow[h] * alpha + sum; +#pragma unroll + for (int dn = 0; dn < 16; ++dn) { + o[dn][2 * h] *= alpha; + o[dn][2 * h + 1] *= alpha; + } + } + } + + cp_wait_all(); + __syncthreads(); // V(nb) visible; every warp is done with K(nb) + if (nb - 1 >= nb_lo) load_tile(sK, p.k, p.k_sp, p.k_ss, p.k_sh, nb - 1, 0); + cp_commit(); + + if (active) { + // O += P V +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + uint32_t pa[4]; + pa[0] = pack_bf16(s[2 * kk][0], s[2 * kk][1]); + pa[1] = pack_bf16(s[2 * kk][2], s[2 * kk][3]); + pa[2] = pack_bf16(s[2 * kk + 1][0], s[2 * kk + 1][1]); + pa[3] = pack_bf16(s[2 * kk + 1][2], s[2 * kk + 1][3]); +#pragma unroll + for (int dp = 0; dp < 8; ++dp) { + const int i4 = lane >> 3; + const int key = 16 * kk + 8 * (i4 & 1) + (lane & 7); + const int chunk = 2 * dp + (i4 >> 1); + uint32_t v0, v1, v2, v3; + ldsm_x4_t(v0, v1, v2, v3, smem_u32(sV + key * kD + ((chunk ^ (key & 7)) * 8))); + mma(o[2 * dp], pa, v0, v1); + mma(o[2 * dp + 1], pa, v2, v3); + } + } + } + } + cp_wait_all(); + + // ---- epilogue: O / l (FP32), LSE = m + ln(l) + // Gated (kGate): the warp's 16 x 128 gate tile is staged in shared memory (sK / sV are free once every warp left the + // mainloop) with coalesced 16-byte loads, y is computed in place in the MMA layout, then stored with coalesced + // 16-byte stores. 16-byte chunks are XOR-swizzled by row so the MMA-layout accesses are bank-conflict free. + __nv_bfloat16* wbuf = nullptr; + if constexpr (kGate) { + __syncthreads(); + wbuf = (warp < 4 ? sK + warp * 16 * kD : sV + (warp - 4) * 16 * kD); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int rr = 2 * i + (lane >> 4), cc = (lane & 15) * 8; + if (wrow0 + rr < sq) { + const long long t = start + wrow0 + rr; + *reinterpret_cast(wbuf + rr * kD + (((cc >> 3) ^ (rr & 7)) * 8)) = + *reinterpret_cast(p.gate + t * p.g_st + static_cast(head) * kD + cc); + } + } + __syncwarp(); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + float l = lrow[h]; + l += __shfl_xor_sync(0xffffffffu, l, 1); + l += __shfl_xor_sync(0xffffffffu, l, 2); + const int row = wrow0 + g + 8 * h; + if (row < sq) { + const bool ok = l > 0.f && l == l; + const float inv = ok ? 1.f / l : 0.f; + const long long t = start + row; + if constexpr (kGate) { + const float lse_v = ok ? mrow[h] + logf(l) : -INFINITY; + if (qd == 0) p.lse[static_cast(head) * p.lse_sh + t] = lse_v; + const float sc = gs_sigmoid(__fsub_rn(lse_v, __bfloat162float(p.sink[t * p.s_st + head]))); + const int rl = g + 8 * h; // row within the warp's staged tile +#pragma unroll + for (int dn = 0; dn < 16; ++dn) { + __nv_bfloat162* cell = reinterpret_cast<__nv_bfloat162*>(wbuf + rl * kD + ((dn ^ (rl & 7)) * 8) + 2 * qd); + const __nv_bfloat162 gg = *cell; + const float x0 = o[dn][2 * h] * inv, x1 = o[dn][2 * h + 1] * inv; + __nv_bfloat162 yy; + yy.x = __float2bfloat16_rn(__fmul_rn(__fmul_rn(x0, gs_sigmoid(__low2float(gg))), sc)); + yy.y = __float2bfloat16_rn(__fmul_rn(__fmul_rn(x1, gs_sigmoid(__high2float(gg))), sc)); + *cell = yy; // in place: each element is read and written by this thread only + } + } else { + float* orow = p.out + t * p.o_st + static_cast(head) * p.o_sh; +#pragma unroll + for (int dn = 0; dn < 16; ++dn) { + *reinterpret_cast(orow + 8 * dn + 2 * qd) = make_float2(o[dn][2 * h] * inv, o[dn][2 * h + 1] * inv); + } + if (qd == 0) p.lse[static_cast(head) * p.lse_sh + t] = ok ? mrow[h] + logf(l) : -INFINITY; + } + } + } + if constexpr (kGate) { + __syncwarp(); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int rr = 2 * i + (lane >> 4), cc = (lane & 15) * 8; + if (wrow0 + rr < sq) { + const long long t = start + wrow0 + rr; + *reinterpret_cast(p.y + t * p.y_st + static_cast(head) * kD + cc) = + *reinterpret_cast(wbuf + rr * kD + (((cc >> 3) ^ (rr & 7)) * 8)); + } + } + } +} + +} // namespace inkling_attn diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/csrc/inkling_attn_ext.cu b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/csrc/inkling_attn_ext.cu new file mode 100644 index 0000000000000000000000000000000000000000..54720cd6065772200a3a328d8f06787b9e8c9a8c --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/csrc/inkling_attn_ext.cu @@ -0,0 +1,326 @@ +// inkling_attn: PyTorch binding of the prefill attention kernel (attn_kernel.cuh). +// +// fwd(q, k_cache, v_cache, page_table, cu_seqlens_q, seqused_k, r, proj, out, lse, softmax_scale, window_left) +// q [T, H, 128] bf16 (last dim contiguous) +// k_cache [pages, page_size, H_kv, 128] bf16, v_cache the same (any strides of the first three dims) +// page_table [B, max_pages] int32, cu_seqlens_q [n_req + 1] int32, seqused_k [>= n_req] int32 +// r [T, H, 16] bf16, proj [16, rel_extent] bf16 contiguous +// out [T, H, 128] fp32 (written for the rows cu_seqlens_q covers), lse [H, T] fp32 (same rows) +// window_left < 0: global (causal) layer; >= 0: sliding window [p - window_left, p] +// No allocation, no host sync: the launch goes to PyTorch's current stream and is CUDA-graph capturable. +// Rows of q past cu_seqlens_q[-1] are left untouched, as FA4 leaves them. +// w8_from_keys > 0 (global layers, warps 4, BF16 or packed KV): requests with a prefix of >= w8_from_keys keys run +// on 8 warps (BM 128), the others on 4, in two launches whose CTAs pick their requests on the device (no host sync, +// CUDA-graph capturable). Both variants compute every row bit-identically. +#include +#include + +#include +#include +#include + +#include "attn_kernel.cuh" + +namespace { + +using inkling_attn::Params; + +bool aligned(const void* p, size_t n) { return reinterpret_cast(p) % n == 0; } + +// Gated launches: the kernel writes y only for rows < cu_q[n_req]; the rows after it (bucket padding of a captured +// prefill graph) are zeroed here on the device, so a smaller replay never leaves an earlier replay's rows in y. +__global__ void zero_tail_rows(__nv_bfloat16* y, long long y_st, int cols, const int* cu_q, int n_req, int rows) { + const int end = cu_q[n_req]; + for (int r = blockIdx.x; r < rows; r += gridDim.x) { + if (r < end) continue; + for (int c = threadIdx.x * 8; c < cols; c += blockDim.x * 8) + *reinterpret_cast(y + r * y_st + c) = make_uint4(0, 0, 0, 0); + } +} + +template +void launch_w(const Params& p, dim3 blocks, cudaStream_t stream) { + constexpr int smem = inkling_attn::tstage_bytes(kW); + static bool configured[256] = {}; // per instantiation and device (the attribute is per context) + int dev = 0; + C10_CUDA_CHECK(cudaGetDevice(&dev)); + TORCH_CHECK(dev >= 0 && dev < 256, "inkling_attn: device index out of range"); + if (!configured[dev]) { + C10_CUDA_CHECK(cudaFuncSetAttribute(inkling_attn::prefill_fwd, + cudaFuncAttributeMaxDynamicSharedMemorySize, smem)); + configured[dev] = true; + } + inkling_attn::prefill_fwd<<>>(p); +} + +template +void launch(const Params& p, dim3 blocks, int64_t warps, cudaStream_t stream) { + if (warps == 8) launch_w(p, blocks, stream); + else launch_w(p, blocks, stream); +} + +// global layers: one launch, or the 8-warp (long prefixes) + 4-warp (the rest) pair +template +void launch_global(const Params& p, dim3 blocks, int64_t warps, int64_t w8_from_keys, int64_t grid8, + cudaStream_t stream) { + if (warps != 4 || w8_from_keys <= 0) { + launch(p, blocks, warps, stream); + return; + } + Params p8 = p; // long-prefix requests first on 8 warps (half the K/V traffic per FLOP) + p8.sel_mode = 2; + p8.sel_keys = static_cast(w8_from_keys); + launch(p8, dim3(static_cast(grid8)), 8, stream); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + Params p4 = p; + p4.sel_mode = 1; + p4.sel_keys = static_cast(w8_from_keys); + launch(p4, blocks, 4, stream); +} + +void fwd(const torch::Tensor& q, const torch::Tensor& k, const torch::Tensor& v, const torch::Tensor& page_table, + const torch::Tensor& cu_q, const torch::Tensor& seq_k, const torch::Tensor& r, const torch::Tensor& proj, + const torch::Tensor& out, const torch::Tensor& lse, double scale, int64_t window_left, + const c10::optional& projp_buf, int64_t warps, + const c10::optional>& packed_kv, int64_t w8_from_keys, + const c10::optional& gate, const c10::optional& sinks, + const c10::optional& y, bool zero_tail) { + TORCH_CHECK(warps == 4 || warps == 8, "inkling_attn: warps must be 4 or 8"); + TORCH_CHECK(w8_from_keys >= 0 && w8_from_keys < (int64_t(1) << 31), "inkling_attn: w8_from_keys out of range"); + TORCH_CHECK(q.is_cuda() && q.scalar_type() == at::kBFloat16 && q.dim() == 3 && q.size(2) == inkling_attn::kD && + q.stride(2) == 1, + "inkling_attn: q must be CUDA bf16 [T, H, 128] with a contiguous last dim"); + const int64_t T = q.size(0), H = q.size(1); + int64_t page_size, hkv, num_pages; + if (packed_kv) { + TORCH_CHECK(window_left < 0 && packed_kv->size() == 8, "inkling_attn: invalid packed KV cache"); + const auto& sm = (*packed_kv)[0]; + TORCH_CHECK(sm.dim() == 5 && sm.size(1) == 2 && sm.size(2) == 128 && sm.size(4) == 128, + "inkling_attn: invalid packed SM plane"); + num_pages = sm.size(0); + page_size = 128; + hkv = sm.size(3); + } else { + for (const auto* c : {&k, &v}) { + TORCH_CHECK(c->is_cuda() && c->scalar_type() == at::kBFloat16 && c->dim() == 4 && c->size(3) == inkling_attn::kD && + c->stride(3) == 1, + "inkling_attn: k/v cache must be CUDA bf16 [pages, page_size, H_kv, 128] with a contiguous last dim"); + TORCH_CHECK(c->stride(0) % 8 == 0 && c->stride(1) % 8 == 0 && c->stride(2) % 8 == 0 && aligned(c->data_ptr(), 16), + "inkling_attn: k/v cache rows must be 16-byte aligned"); + } + TORCH_CHECK(k.sizes() == v.sizes(), "inkling_attn: k and v caches differ in shape"); + page_size = k.size(1); + hkv = k.size(2); + num_pages = k.size(0); + TORCH_CHECK(page_size > 0 && page_size % inkling_attn::kBN == 0, "inkling_attn: page size must be a positive multiple of 64"); + } + TORCH_CHECK(H > 0, "inkling_attn: no heads"); + TORCH_CHECK(hkv > 0 && H % hkv == 0, "inkling_attn: q heads must be a multiple of kv heads"); + TORCH_CHECK(q.stride(0) % 2 == 0 && q.stride(1) % 2 == 0 && aligned(q.data_ptr(), 4), "inkling_attn: q alignment"); + TORCH_CHECK(page_table.is_cuda() && page_table.scalar_type() == at::kInt && page_table.dim() == 2 && + page_table.stride(1) == 1, + "inkling_attn: page_table must be CUDA int32 [B, max_pages] with a contiguous last dim"); + TORCH_CHECK(cu_q.is_cuda() && cu_q.scalar_type() == at::kInt && cu_q.dim() == 1 && cu_q.is_contiguous() && + cu_q.numel() >= 1, + "inkling_attn: cu_seqlens_q must be a contiguous CUDA int32 vector"); + const int64_t n_req = cu_q.numel() - 1; + TORCH_CHECK(seq_k.is_cuda() && seq_k.scalar_type() == at::kInt && seq_k.dim() == 1 && seq_k.is_contiguous() && + seq_k.numel() >= n_req, + "inkling_attn: seqused_k must be a contiguous CUDA int32 vector with one entry a request"); + TORCH_CHECK(page_table.size(0) >= n_req, "inkling_attn: page_table has fewer rows than requests"); + TORCH_CHECK(num_pages > 0 && num_pages < (int64_t(1) << 31) && + page_table.size(1) * page_size < (int64_t(1) << 31), + "inkling_attn: invalid KV cache or page table size"); + TORCH_CHECK(r.is_cuda() && r.scalar_type() == at::kBFloat16 && r.dim() == 3 && r.size(0) == T && r.size(1) == H && + r.size(2) == inkling_attn::kDRel && r.stride(2) == 1, + "inkling_attn: r must be CUDA bf16 [T, H, 16] with a contiguous last dim"); + TORCH_CHECK(r.stride(0) % 2 == 0 && r.stride(1) % 2 == 0 && aligned(r.data_ptr(), 4), "inkling_attn: r alignment"); + TORCH_CHECK(proj.is_cuda() && proj.scalar_type() == at::kBFloat16 && proj.dim() == 2 && + proj.size(0) == inkling_attn::kDRel && proj.is_contiguous() && proj.size(1) > 0, + "inkling_attn: proj must be a contiguous CUDA bf16 [16, rel_extent]"); + TORCH_CHECK(out.is_cuda() && out.scalar_type() == at::kFloat && out.dim() == 3 && out.size(0) == T && + out.size(1) == H && out.size(2) == inkling_attn::kD && out.stride(2) == 1, + "inkling_attn: out must be CUDA fp32 [T, H, 128] with a contiguous last dim"); + TORCH_CHECK(out.stride(0) % 2 == 0 && out.stride(1) % 2 == 0 && aligned(out.data_ptr(), 8), + "inkling_attn: out alignment"); + TORCH_CHECK(lse.is_cuda() && lse.scalar_type() == at::kFloat && lse.dim() == 2 && lse.size(0) == H && + lse.size(1) == T && lse.stride(1) == 1, + "inkling_attn: lse must be CUDA fp32 [H, T] with a contiguous last dim"); + for (const auto* t : {&k, &v, &page_table, &cu_q, &seq_k, &r, &proj, &out, &lse}) + TORCH_CHECK(t->device() == q.device(), "inkling_attn: all tensors must be on q's device"); + TORCH_CHECK(T < (int64_t(1) << 30) && n_req < (int64_t(1) << 20), "inkling_attn: too many rows"); + if (T == 0 || (n_req == 0 && !y.has_value())) return; // gated with no requests: y is cleared after validation + + Params p{}; + p.q = reinterpret_cast(q.data_ptr()); + p.q_st = q.stride(0); + p.q_sh = q.stride(1); + if (packed_kv) { + const auto& planes = *packed_kv; + const std::vector inner_shapes[] = { + {2, 128, hkv, 128}, {2, 128, hkv, 64}, {hkv, 2, 64}, {hkv, 2, 5}, + {hkv, 2}, {1}, {2, 128, hkv, 128}, {128, 128}, + }; + for (int i = 0; i < 8; ++i) { + const auto& plane = planes[i]; + const auto dtype = i < 2 ? at::kByte : i < 6 ? at::kInt : at::kShort; + TORCH_CHECK(plane.device() == q.device() && plane.scalar_type() == dtype && plane.dim() > 0 && + plane.sizes().slice(1) == at::IntArrayRef(inner_shapes[i]), + "inkling_attn: invalid packed KV device, dtype or shape"); + if (i < 6) { + TORCH_CHECK(plane.size(0) == num_pages && plane.select(0, 0).is_contiguous() && + plane.stride(0) * plane.element_size() == planes[0].stride(0), + "inkling_attn: packed planes must share a page stride"); + } else { + TORCH_CHECK(plane.is_contiguous() && plane.size(0) < (int64_t(1) << 31), + "inkling_attn: invalid packed side arena layout"); + } + } + p.sm = planes[0].data_ptr(); + p.ex = planes[1].data_ptr(); + p.esc = planes[2].data_ptr(); + p.off = planes[3].data_ptr(); + p.overflow_ref = planes[4].data_ptr(); + p.flags = planes[5].data_ptr(); + p.staging = reinterpret_cast(planes[6].data_ptr()); + p.overflow = reinterpret_cast(planes[7].data_ptr()); + p.packed_stride = planes[0].stride(0); + p.kv_heads = static_cast(hkv); + p.stage_slots = static_cast(planes[6].size(0)); + p.overflow_slots = static_cast(planes[7].size(0)); + } else { + p.k = reinterpret_cast(k.data_ptr()); + p.k_sp = k.stride(0); + p.k_ss = k.stride(1); + p.k_sh = k.stride(2); + p.v = reinterpret_cast(v.data_ptr()); + p.v_sp = v.stride(0); + p.v_ss = v.stride(1); + p.v_sh = v.stride(2); + } + p.page_table = page_table.data_ptr(); + p.pt_s = page_table.stride(0); + p.cu_q = cu_q.data_ptr(); + p.seq_k = seq_k.data_ptr(); + p.n_req = static_cast(n_req); + p.r = reinterpret_cast(r.data_ptr()); + p.r_st = r.stride(0); + p.r_sh = r.stride(1); + p.proj = reinterpret_cast(proj.data_ptr()); + p.rel_extent = static_cast(proj.size(1)); + p.out = out.data_ptr(); + p.o_st = out.stride(0); + p.o_sh = out.stride(1); + p.lse = lse.data_ptr(); + p.lse_sh = lse.stride(0); + p.heads = static_cast(H); + p.group = static_cast(H / hkv); + p.page_size = static_cast(page_size); + p.total_q = static_cast(T); + p.pt_cols = static_cast(page_table.size(1)); + p.num_pages = static_cast(num_pages); + p.scale = static_cast(scale); + p.window_left = static_cast(window_left); + p.sel_mode = 0; + p.sel_keys = 0; + const bool gated = gate.has_value(); + TORCH_CHECK(gated == sinks.has_value() && gated == y.has_value(), "inkling_attn: gate, sinks and y go together"); + if (gated) { + const auto& g = *gate; + const auto& sk = *sinks; + const auto& yy = *y; + TORCH_CHECK(g.is_cuda() && g.device() == q.device() && g.scalar_type() == at::kBFloat16 && g.dim() == 2 && + g.size(0) >= T && g.size(1) == H * inkling_attn::kD && g.stride(1) == 1 && g.stride(0) % 8 == 0 && + aligned(g.data_ptr(), 16), + "inkling_attn: gate must be CUDA bf16 [>= T, H * 128], contiguous last dim, 16-byte aligned rows"); + TORCH_CHECK(sk.is_cuda() && sk.device() == q.device() && sk.scalar_type() == at::kBFloat16 && sk.dim() == 2 && + sk.size(0) >= T && sk.size(1) == H && sk.stride(1) == 1, + "inkling_attn: sinks must be CUDA bf16 [>= T, H] with a contiguous last dim"); + TORCH_CHECK(yy.is_cuda() && yy.device() == q.device() && yy.scalar_type() == at::kBFloat16 && yy.dim() == 2 && + yy.size(0) == T && yy.size(1) == H * inkling_attn::kD && yy.is_contiguous() && + aligned(yy.data_ptr(), 16), + "inkling_attn: y must be a contiguous CUDA bf16 [T, H * 128]"); + { // y is written by many CTAs: it must not overlap anything the kernel reads or writes + const auto y0 = reinterpret_cast(yy.data_ptr()), y1 = y0 + yy.numel() * 2; + for (const auto* t : {&q, &k, &v, &r, &proj, &out, &lse, &g, &sk}) { + const auto t0 = reinterpret_cast(t->data_ptr()); + const auto t1 = t0 + (t->numel() ? (t->storage().nbytes() - t->storage_offset() * t->element_size()) : 0); + TORCH_CHECK(y1 <= t0 || t1 <= y0, "inkling_attn: y overlaps an input or output buffer"); + } + } + if (n_req == 0) { // no request rows: all of y is tail + if (zero_tail) yy.zero_(); + return; + } + p.gate = reinterpret_cast(g.data_ptr()); + p.g_st = g.stride(0); + p.sink = reinterpret_cast(sk.data_ptr()); + p.s_st = sk.stride(0); + p.y = reinterpret_cast<__nv_bfloat16*>(yy.data_ptr()); + p.y_st = yy.stride(0); + } + + const int64_t bm = 16 * warps; + const int64_t tiles = (T + bm - 1) / bm + n_req; + const int64_t grid = tiles * H; + TORCH_CHECK(grid < (int64_t(1) << 31), "inkling_attn: grid too large"); + const int64_t grid8 = ((T + 127) / 128 + n_req) * H; + const c10::cuda::CUDAGuard guard(q.device()); + const auto stream = at::cuda::getCurrentCUDAStream(); + TORCH_CHECK(window_left < 0 || proj.size(1) == window_left + 1, + "inkling_attn: sliding-window layers need rel_extent == window + 1"); + const bool packed = projp_buf.has_value(); + if (packed) { + const auto& pb = *projp_buf; + TORCH_CHECK(pb.is_cuda() && pb.device() == q.device() && pb.scalar_type() == at::kBFloat16 && pb.is_contiguous() && + pb.numel() == (proj.size(1) + 1) * inkling_attn::kDRel && aligned(pb.data_ptr(), 16), + "inkling_attn: projp buffer must be a contiguous 16-byte aligned bf16 [(rel_extent + 1) * 16]"); + const auto pb0 = reinterpret_cast(pb.data_ptr()), pb1 = pb0 + pb.numel() * 2; + const auto pr0 = reinterpret_cast(proj.data_ptr()), pr1 = pr0 + proj.numel() * 2; + TORCH_CHECK(pb1 <= pr0 || pr1 <= pb0, "inkling_attn: projp buffer overlaps proj"); + p.projp = reinterpret_cast(pb.data_ptr()); + const int n = static_cast(pb.numel()); + inkling_attn::pack_proj<<<(n + 255) / 256, 256, 0, stream>>>(p.proj, reinterpret_cast<__nv_bfloat16*>(pb.data_ptr()), + p.rel_extent); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + const dim3 blocks(static_cast(grid)); + if (gated && zero_tail) { // zero_tail=false: a second launch into the same y (it must not clear the first's rows) + const int zb = static_cast(std::min(T, 1024)); + zero_tail_rows<<>>(p.y, p.y_st, static_cast(H * inkling_attn::kD), p.cu_q, + static_cast(n_req), static_cast(T)); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + if (packed_kv) { + if (gated) { + if (packed) launch_global(p, blocks, warps, w8_from_keys, grid8, stream); + else launch_global(p, blocks, warps, w8_from_keys, grid8, stream); + } else if (packed) launch_global(p, blocks, warps, w8_from_keys, grid8, stream); + else launch_global(p, blocks, warps, w8_from_keys, grid8, stream); + } else if (window_left >= 0) { + if (gated) { + if (packed) launch(p, blocks, warps, stream); + else launch(p, blocks, warps, stream); + } else if (packed) launch(p, blocks, warps, stream); + else launch(p, blocks, warps, stream); + } else { + if (gated) { + if (packed) launch_global(p, blocks, warps, w8_from_keys, grid8, stream); + else launch_global(p, blocks, warps, w8_from_keys, grid8, stream); + } else if (packed) launch_global(p, blocks, warps, w8_from_keys, grid8, stream); + else launch_global(p, blocks, warps, w8_from_keys, grid8, stream); + } + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +} // namespace + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("fwd", &fwd, "Inkling-2-Mini prefill attention with the relative bias computed in-kernel", + py::arg("q"), py::arg("k"), py::arg("v"), py::arg("page_table"), py::arg("cu_q"), py::arg("seq_k"), + py::arg("r"), py::arg("proj"), py::arg("out"), py::arg("lse"), py::arg("scale"), py::arg("window_left"), + py::arg("projp_buf") = py::none(), py::arg("warps") = 4, + py::arg("packed_kv") = py::none(), py::arg("w8_from_keys") = 0, + py::arg("gate") = py::none(), py::arg("sinks") = py::none(), py::arg("y") = py::none(), + py::arg("zero_tail") = true); +} diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/ops.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..452b74f834fe525fde7714790940587699d587b2 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/ops.py @@ -0,0 +1,76 @@ +"""Python entry point of the inkling_attn kernel (imported on the GPU path only).""" + +from . import build + +D_REL = 16 +HEAD_DIM = 128 + + +import os + +WARPS = int(os.environ.get("INKLING_ATTN_WARPS", "4")) # 4: BM 64, 2 CTAs / SM; 8: BM 128, 1 CTA / SM +PACKED_PROJ = True # repack proj per call (one tiny launch) so each lane loads its B fragment with one 8-byte load +# Global layers with WARPS 4 (BF16 and packed KV): a request whose prefix holds >= W8_FROM keys runs on 8 warps +# (BM 128), the others on 4 (two launches, requests picked on the device). BM 64 holds ~71 TF/s up to ~256K prefix +# keys in isolation (~150K in serving) and falls to ~47 TF/s at 512K-1M; BM 128 holds ~69 TF/s at every prefix and +# is ~3-5 % slower below 256K. Bit-identical rows either way. 0 = off. +W8_FROM = int(os.environ.get("INKLING_ATTN_W8_FROM", "131072")) + + +def prefill_attention(q, k_cache, v_cache, page_table, cu_seqlens_q, seqused_k, r, proj, softmax_scale, + window_left, out=None, packed=None, warps=None, w8_from=None, lse=None, gate=None, sinks=None, + y=None, zero_tail=True): + """FA4-compatible (out, lse) of the Inkling prefill attention with the relative bias computed in-kernel. + + q [T, H, 128] bf16; k_cache / v_cache [pages, page_size, H_kv, 128] bf16; page_table [B, max_pages] int32; + cu_seqlens_q [n_req + 1] int32; seqused_k [n_req] int32 (prefix + new tokens); r [T, H, 16] bf16 (after the + rel L2 clip, the RelLogitsProj input); proj [16, rel_extent] bf16; window_left: the layer's left window + (sliding-window layers, rel_extent == window_left + 1) or None / negative (global causal layers). + Returns out [T, H, 128] fp32 and lse [H, T] fp32 (FA4's varlen layout). Rows past cu_seqlens_q[-1] are not + written. With gate [T, H*128] / sinks [T, H] / y [T, H*128] (any layer): the kernel writes + y = bf16(out * sigmoid(gate) * sigmoid(lse - sink)) (SGLang's gate_sink on these values) instead of out and + returns (y, lse). It first zeroes y's rows past cu_seqlens_q[-1] on the device; zero_tail=False skips that + for a second launch into the same y (whose first launch already did it). + """ + import torch + + ext = build.load() + t, heads, _ = q.shape + if out is None: + out = torch.empty((t, heads, HEAD_DIM), dtype=torch.float32, device=q.device) + if lse is None: + lse = torch.empty((heads, t), dtype=torch.float32, device=q.device) + wl = -1 if window_left is None or window_left < 0 else int(window_left) + if r.stride(-1) != 1: + r = r.contiguous() + packed = PACKED_PROJ if packed is None else packed + projp = torch.empty(((proj.shape[1] + 1) * D_REL,), dtype=torch.bfloat16, device=q.device) if packed else None + ext.fwd(q, k_cache, v_cache, page_table, cu_seqlens_q, seqused_k, r, proj, out, lse, float(softmax_scale), wl, + projp, WARPS if warps is None else int(warps), + w8_from_keys=W8_FROM if w8_from is None else int(w8_from), gate=gate, sinks=sinks, y=y, + zero_tail=bool(zero_tail)) + return (out, lse) if y is None else (y, lse) + + +def packed_prefill_attention(q, layer, page_table, cu_seqlens_q, seqused_k, softmax_scale, *, + r, proj, out=None, warps=None, w8_from=None, gate=None, sinks=None, y=None, + zero_tail=True): + """Run fused projected-bias prefill with exact KV reconstructed in shared memory.""" + import torch + + from inkling_kv12s.storage import validate_paged + + validate_paged(q, layer, page_table, seqused_k, cu_seqlens_q) + t, heads, _ = q.shape + if out is None: + out = torch.empty((t, heads, HEAD_DIM), dtype=torch.float32, device=q.device) + lse = torch.empty((heads, t), dtype=torch.float32, device=q.device) + if r.stride(-1) != 1: + r = r.contiguous() + projp = torch.empty(((proj.shape[1] + 1) * D_REL,), dtype=torch.bfloat16, device=q.device) if PACKED_PROJ else None + planes = [*layer.planes, layer.stage, layer.overflow] + ext = build.load() + ext.fwd(q, layer.raw, layer.raw, page_table, cu_seqlens_q, seqused_k, r, proj, out, lse, + float(softmax_scale), -1, projp, WARPS if warps is None else int(warps), planes, + W8_FROM if w8_from is None else int(w8_from), gate=gate, sinks=sinks, y=y, zero_tail=bool(zero_tail)) + return (out, lse) if y is None else (y, lse) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/patch.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/patch.py new file mode 100644 index 0000000000000000000000000000000000000000..070ddae3a823b655ae36e7978d15e4b9edd6c8a7 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/patch.py @@ -0,0 +1,562 @@ +"""Patch points of inkling_attn (prefill / extend attention with the relative bias computed in-kernel). + +Stock prefill path per layer visit (inkling2_attn.py Inkling2Attention._forward, the non-compact branch): + rel_bias = self.rel_logits_proj(r) # cuBLAS einsum -> BF16 [t, 24, rel_extent] + attn(q, k, v, forward_batch, return_lse=True, rel_bias=rel_bias) + -> FlashAttentionBackend.forward_extend -> flash_attn_with_kvcache (SM120) + -> flash_attn_varlen_func -> _flash_attn_varlen_func (FA4: shear copy + attention with the sheared bias) + +With this overlay, inside an eligible visit (prefill/extend only, see _visit_for): + 1. Inkling2Attention._forward is wrapped to mark the visit (a context variable; nothing else changes); + 2. RelLogitsProj.forward returns r itself (the [t, H, 16] rel-clip output, no einsum) and records it in the + visit: r travels to the backend in the rel_bias slot, so every narrowing SGLang applies to rel_bias + (graph_utils.attention_input_scope / _attention_on_real_rows slice rows) applies to r the same way; + 3. flash_attention_v4_sm120._flash_attn_varlen_func (the module global the SM120 wrapper calls) is wrapped: + a rel_bias that is (a row prefix of) the visit's r runs ops.prefill_attention with the layer's proj, + returning FA4's (out, lse). Any call shape the kernel does not cover falls back to the stock call with + the materialised einsum bias (same math as stock). An r-shaped rel_bias (width 16) that reaches FA4 + outside its visit raises instead of being misread. + +Breakable prefill graphs replay attention as a deferred eager call outside the visit, so they are excluded at +the visit check (as inkling_prefill.bias_layout does). Decode, target verify and draft extend never enter a visit. + +Coexistence with inkling_prefill.bias_layout: both mark visits and wrap FA4's varlen entry, and bias_layout +wraps RelLogitsProj.forward. This package dispatches one level earlier, at RelLogitsProj.__call__ (before +nn.Module.__call__ reaches any forward wrapper), so in an eligible visit r is returned whatever order the two +packages were installed in; bias_layout's forward wrapper is not reached, its varlen wrapper sees a width-16 +rel_bias it did not make and passes it through, and layers this package does not take (e.g. global layers with +only prefill_swa armed) still get bias_layout's sheared bias. Should anything else consume an eligible visit +first, the _forward wrapper notices (the visit's r stays unset) and logs it once. + +Device route: the visit requires a CUDA device of compute capability 12.x, the condition under which +FlashAttentionBackend._load_fa4_kernels uses the patched SM120 module, and no context-parallel extend. +""" + +import contextvars +import os +import sys +import weakref + +ATTN_MODULE = "sglang.srt.models.inkling_common.inkling2_attn" +COMMON_ATTN_MODULE = "sglang.srt.models.inkling_common.attn" +SM120_MODULE = "sglang.kernels.ops.attention.flash_attention_v4_sm120" +BREAKABLE_MODULE = "sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.context" +CP_MODULE = "sglang.srt.layers.cp.utils" +MARK = "inkling_attn_prefill" +D_REL = 16 +HEAD_DIM = 128 + +_CTX = contextvars.ContextVar("inkling_attn_ctx", default=None) +STATS = {"kernel": 0, "fallback": 0, "shadowed": 0, "gated": 0, "gate_fallback": 0} +# INKLING_ATTN_GATE=1: sliding-window prefill visits run the gated epilogue (gate_sink inside the attention kernel, +# bit-identical to SGLang's gate_sink on the FP32 out + LSE). The visit records the gate / sinks its +# _project_sources returns (an instance-level hook for the duration of the visit); the FA4 call then launches the +# gated kernel (BF16 y + LSE; the FP32 out stays unwritten) and the visit's gate_sink call returns y. +# INKLING_ATTN_GATE=all (or 2): global prefill visits too (BF16 and KV12S packed readers, via gate_begin / gate_commit). +_GATE_ENV = os.environ.get("INKLING_ATTN_GATE", "").strip().lower() +GATE_ALL = _GATE_ENV in ("all", "2") +GATE = GATE_ALL or _GATE_ENV in ("1", "on", "true", "yes", "swa") + + +def _kernel_api_logging(): + """SGLang's kernel API logging (SGLANG_KERNEL_API_LOGLEVEL > 0, parsed like kernel_api_logging._get_env) logs and + may dump the FA4 wrapper's returned FP32 out before gate_sink runs; a gated launch leaves that buffer unwritten, + so the gated epilogue stays off while it is enabled.""" + try: + return int(os.environ.get("SGLANG_KERNEL_API_LOGLEVEL", "0") or 0) != 0 + except ValueError: + return False + + +GATE_OFF_FOR_LOGGING = GATE and _kernel_api_logging() +if GATE_OFF_FOR_LOGGING: + GATE = False + GATE_ALL = False +_LOGGED = set() + + +def _log_once(key, msg): + if key in _LOGGED: + return + _LOGGED.add(key) + sys.stderr.write(f"[inkling_attn pid={os.getpid()}] {msg}\n") + sys.stderr.flush() + + +if GATE_OFF_FOR_LOGGING: + _log_once("gate_off", "gated epilogue OFF: SGLANG_KERNEL_API_LOGLEVEL is set (it reads the FA4 output buffer)") + + +class _Visit: + __slots__ = ("owner", "local", "window_left", "r", "proj", "gate", "sinks", "tokens", "gated") + + def __init__(self, owner, local, window_left, proj): + self.owner = owner + self.local = local + self.window_left = window_left + self.proj = proj + self.r = None + self.gate = self.sinks = self.tokens = None # from the visit's _project_sources (INKLING_ATTN_GATE) + self.gated = None # (FP32 out buffer left unwritten, BF16 y) of a gated launch, until gate_sink takes y + + +class use_visit: + """Context manager for direct calls (tools / tests): inside it, the patched varlen wrapper treats `r` + (or a row prefix of it) passed as rel_bias as this package's marker for a layer with `proj`.""" + + def __init__(self, r, proj, window_left=None): + local = window_left is not None and window_left >= 0 + self._visit = _Visit(None, local, window_left if local else None, proj) + self._visit.r = r + _PRODUCED.append(weakref.ref(r)) + del _PRODUCED[:-256] + self._token = None + + def __enter__(self): + self._token = _CTX.set(self._visit) + return self._visit + + def __exit__(self, *exc): + _CTX.reset(self._token) + return False + + +_SM12X = {} + + +def _is_sm12x(device): + """FlashAttentionBackend._load_fa4_kernels takes the SM120 FA4 module (the one patched here) iff major == 12.""" + import torch + + idx = device.index if device.index is not None else torch.cuda.current_device() + if idx not in _SM12X: + # GB10 only: the extension is built for sm_121a, and capability 12.x is what makes the backend use the + # patched SM120 FA4 module + _SM12X[idx] = tuple(torch.cuda.get_device_capability(idx)) == (12, 1) + return _SM12X[idx] + + +def _visit_for(self, forward_batch, attn, get_attn_backend, get_model, in_breakable, kinds, cp_active=None): + import torch + + local = bool(getattr(self, "is_local", False)) + if ("swa" if local else "global") not in kinds: + return None + if in_breakable is not None and in_breakable(): + return None + if cp_active is not None and cp_active(forward_batch): + return None + mode = forward_batch.forward_mode + if not mode.is_extend() or mode.is_decode() or mode.is_target_verify(): + return None + for name in ("is_draft_extend", "is_draft_extend_v2"): + fn = getattr(mode, name, None) + if fn is not None and fn(): + return None + if getattr(attn, "pack_gqa", None): + return None + try: + if get_model().kv_cache_dtype == "mxfp8": + return None + except Exception: # noqa: BLE001 + return None + contains = getattr(forward_batch, "contains_mm_inputs", None) + if contains is not None and contains(): + return None + backend = get_attn_backend() + if getattr(backend, "fa_skip_kv_cache", False) or getattr(backend, "use_mla", False): + return None + meta = getattr(backend, "forward_metadata", None) + if meta is None: + return None + for name in ("swa_spec_metadata", "image_token_ranges", "local_attn_metadata"): + if getattr(meta, name, None) is not None: + return None + if getattr(self, "head_dim", None) != HEAD_DIM or getattr(self, "d_rel", None) != D_REL: + return None + heads, kv_heads = self.num_tp_heads, self.num_tp_kv_heads + if kv_heads <= 0 or heads % kv_heads: + return None + proj = getattr(getattr(self, "rel_logits_proj", None), "proj", None) + rel = self.rel_extent + if not ( + isinstance(proj, torch.Tensor) + and proj.is_cuda + and _is_sm12x(proj.device) + and proj.dtype == torch.bfloat16 + and proj.dim() == 2 + and tuple(proj.shape) == (D_REL, rel) + and proj.is_contiguous() + ): + return None + window = getattr(attn, "sliding_window_size", None) + if local: + if window is None or window < 0 or window + 1 != rel: + return None + elif window not in (None, -1): + return None + return _Visit(self, local, window if local else None, proj) + + +def make_forward(prev, get_attn_backend, get_model, in_breakable, kinds, cp_active=None): + def _forward(self, hidden_states, positions, forward_batch, *, attn, attn_padded): + visit = _visit_for(self, forward_batch, attn, get_attn_backend, get_model, in_breakable, kinds, cp_active) + if visit is None: + if GATE and _CTX.get() is not None: # an ineligible nested visit must not see the outer one + token = _CTX.set(None) + try: + return prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) + finally: + _CTX.reset(token) + return prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) + token = _CTX.set(visit) + hooked = False + if GATE and (visit.local or GATE_ALL) and "_project_sources" not in self.__dict__: + project = self._project_sources # the full (class-level, wrapped) chain + + def _project_sources(sources): + res = project(sources) + if isinstance(res, tuple) and len(res) == 6: + visit.gate, visit.sinks = res[4], res[5] + visit.tokens = res[0].shape[0] + return res + + self.__dict__["_project_sources"] = _project_sources # instance attribute shadows the method + hooked = True + try: + result = prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) + finally: + if hooked: + self.__dict__.pop("_project_sources", None) + _CTX.reset(token) + if visit.gated is not None: + raise RuntimeError("inkling_attn: a gated attention output never reached gate_sink") + if visit.r is None: + STATS["shadowed"] += 1 + _log_once( + "shadowed", + "an eligible visit never reached RelLogitsProj.__call__ with an r this package takes " + "(something else produced the bias); that visit ran without this package", + ) + return result + + _forward.__wrapped__ = prev + setattr(_forward, MARK, True) + return _forward + + +_PRODUCED = [] # weak references to the last r markers handed out (bounded) + + +def make_rel_call(prev): + """RelLogitsProj.__call__: inside an eligible visit return r itself (the marker) before nn.Module.__call__, + i.e. before every RelLogitsProj.forward wrapper, whatever order the overlays were installed in.""" + import torch + + def __call__(self, *args, **kwargs): + r_out = args[0] if args else kwargs.get("r_out") + log_scaling_tau = args[1] if len(args) > 1 else kwargs.get("log_scaling_tau") + visit = _CTX.get() + if ( + visit is not None + and visit.r is None + and log_scaling_tau is None + and visit.owner is not None + and visit.owner.rel_logits_proj is self + and self.proj is visit.proj + and isinstance(r_out, torch.Tensor) + and r_out.dim() == 3 + and r_out.is_cuda + and r_out.dtype == torch.bfloat16 + and r_out.shape[1] == visit.owner.num_tp_heads + and r_out.shape[2] == D_REL + and r_out.stride(2) == 1 + and len(args) + len(kwargs) <= 2 + ): + visit.r = r_out + _PRODUCED.append(weakref.ref(r_out)) + del _PRODUCED[:-256] + return r_out + return prev(self, *args, **kwargs) + + __call__.__wrapped__ = prev + setattr(__call__, MARK, True) + return __call__ + + +def _is_produced(bias): + for ref in _PRODUCED: + r = ref() + if r is not None and r.device == bias.device and _same_storage_rows(bias, r): + return True + return False + + +def _same_storage_rows(bias, r): + return ( + bias.dim() == 3 + and bias.data_ptr() == r.data_ptr() + and bias.shape[1:] == r.shape[1:] + and bias.stride() == r.stride() + and bias.shape[0] <= r.shape[0] + ) + + +def packed_rel_projection(bias): + """Resolve a fused projection marker intercepted by a packed attention reader.""" + visit = _CTX.get() + if visit is not None and visit.r is not None and _same_storage_rows(bias, visit.r): + return visit.proj + if bias.shape[-1] == D_REL and _is_produced(bias): + raise RuntimeError("inkling_attn: packed reader received a marker outside its visit") + return None + + +def _kernel_call(visit, bias, kwargs): + """Arguments for ops.prefill_attention, or None when this call is outside what the kernel covers.""" + import torch + + q = kwargs.get("q") + k = kwargs.get("k") + v = kwargs.get("v") + page_table = kwargs.get("page_table") + cu_q = kwargs.get("cu_seqlens_q") + seq_k = kwargs.get("seqused_k") + out = kwargs.get("out") + for name in ( + "qv", "cu_seqlens_k", "seqused_q", "learnable_sink", "score_mod", "mask_mod", "aux_tensors", + "q_descale", "k_descale", "v_descale", "sfq", "sfk", "sfv", "gather_kv_indices", "block_sparse_tensors", + "aux_scalars", + ): + if kwargs.get(name) is not None: + return None + if kwargs.get("softcap") not in (None, 0.0) or kwargs.get("rel_bias_presheared"): + return None + if not kwargs.get("causal", False) or kwargs.get("num_splits", 1) not in (0, 1) or kwargs.get("pack_gqa"): + return None + window = tuple(kwargs.get("window_size", (None, None))) + if visit.local: + if window != (visit.window_left, 0): + return None + elif window not in ((None, None), (-1, -1), (None, 0), (-1, 0)): + return None + scale = kwargs.get("softmax_scale") + if scale is None: + return None + if not all(isinstance(t, torch.Tensor) for t in (q, k, v, page_table, cu_q, seq_k)): + return None + if k.dim() != 4 or k.shape[1] <= 0 or k.shape[2] <= 0 or cu_q.numel() < 2 or q.dim() != 3 or q.shape[1] <= 0: + return None + if not ( + q.dtype == k.dtype == v.dtype == torch.bfloat16 + and q.dim() == 3 + and q.shape[2] == HEAD_DIM + and q.shape[1] == bias.shape[1] + and q.shape[0] == bias.shape[0] + and k.dim() == 4 + and k.shape == v.shape + and k.shape[3] == HEAD_DIM + and k.shape[1] % 64 == 0 + and q.shape[1] % k.shape[2] == 0 + and page_table.dtype == cu_q.dtype == seq_k.dtype == torch.int32 + and page_table.dim() == 2 + and page_table.stride(1) == 1 + and cu_q.is_contiguous() + and seq_k.is_contiguous() + ): + return None + if out is not None and not ( + out.dtype == torch.float32 and tuple(out.shape) == (q.shape[0], q.shape[1], HEAD_DIM) and out.stride(2) == 1 + ): + return None + if out is None: + return None # FA4 would return q.dtype; Inkling always passes an FP32 out + dev = q.device + if not all(t.device == dev for t in (k, v, page_table, cu_q, seq_k, bias, out, visit.proj)): + return None + if not ( + q.stride(2) == 1 and q.stride(0) % 2 == 0 and q.stride(1) % 2 == 0 and q.data_ptr() % 4 == 0 + and all(c.stride(3) == 1 and c.stride(0) % 8 == 0 and c.stride(1) % 8 == 0 and c.stride(2) % 8 == 0 + and c.data_ptr() % 16 == 0 for c in (k, v)) + and bias.stride(0) % 2 == 0 and bias.stride(1) % 2 == 0 and bias.data_ptr() % 4 == 0 + and out.stride(0) % 2 == 0 and out.stride(1) % 2 == 0 and out.data_ptr() % 8 == 0 + and cu_q.dim() == 1 and seq_k.dim() == 1 and seq_k.numel() >= cu_q.numel() - 1 + and page_table.shape[0] >= cu_q.numel() - 1 + ): + return None + return dict( + q=q, k_cache=k, v_cache=v, page_table=page_table, cu_seqlens_q=cu_q, seqused_k=seq_k, r=bias, + proj=visit.proj, softmax_scale=float(scale), window_left=visit.window_left if visit.local else None, out=out, + ) + + +def make_varlen(stock): + import torch + + def _flash_attn_varlen_func(*args, **kwargs): + bias = kwargs.get("rel_bias") + if bias is not None and not args: + visit = _CTX.get() + if visit is not None and visit.r is not None and _same_storage_rows(bias, visit.r): + call = _kernel_call(visit, bias, kwargs) + if call is not None: + from . import ops + + STATS["kernel"] += 1 + if GATE and (visit.local or GATE_ALL) and visit.gated is None and _gate_ok(visit, call): + gate, sinks = visit.gate, visit.sinks + y = torch.empty(tuple(gate.shape), dtype=torch.bfloat16, device=gate.device) + _, lse = ops.prefill_attention(**call, gate=gate, sinks=sinks, y=y) + visit.gated = (call["out"], y) + STATS["gated"] += 1 + kind = "SWA" if visit.local else "global" + _log_once(f"gated_first_{kind}", f"first gated {kind} prefill launch ({call['q'].shape[0]} rows)") + return call["out"], lse # out stays unwritten: only gate_sink consumes it, and returns y + return ops.prefill_attention(**call) + STATS["fallback"] += 1 + _log_once("fallback", "a marked call is outside the kernel's coverage; running stock FA4 for it") + kwargs["rel_bias"] = torch.einsum("thd,de->the", bias, visit.proj) + kwargs.pop("rel_bias_presheared", None) + return stock(**kwargs) + if bias is not None and bias.dim() == 3 and bias.shape[-1] == D_REL and _is_produced(bias): + raise RuntimeError( + "inkling_attn: an r-shaped rel_bias (width 16) reached FA4 outside the layer visit that made it" + ) + return stock(*args, **kwargs) + + _flash_attn_varlen_func.__wrapped__ = stock + setattr(_flash_attn_varlen_func, MARK, True) + return _flash_attn_varlen_func + + +def _gate_ok(visit, call): + """The gated launch is taken only for a whole-visit call (the q rows _project_sources returned, so no + real-rows narrowing between the visit and the backend) with gate / sinks in the layouts the kernel reads.""" + import torch + + gate, sinks, q, out = visit.gate, visit.sinks, call["q"], call["out"] + if gate is None or sinks is None or visit.tokens != q.shape[0]: + return False + t, heads = q.shape[0], q.shape[1] + ok = ( + gate.dtype == sinks.dtype == torch.bfloat16 + and gate.dim() == 2 and tuple(gate.shape) == (t, heads * HEAD_DIM) + and gate.stride(1) == 1 and gate.stride(0) % 8 == 0 and gate.data_ptr() % 16 == 0 + and sinks.dim() == 2 and tuple(sinks.shape) == (t, heads) and sinks.stride(1) == 1 + and gate.device == sinks.device == q.device + and tuple(out.shape[:2]) == (t, heads) + ) + if not ok: + STATS["gate_fallback"] += 1 + _log_once("gate_fallback", "gated epilogue: unexpected gate / sinks layout; stock gate_sink used") + return ok + + +def gate_begin(q, out): + """For a packed (KV12S) global prefill reader: the gate / sinks / y kwargs of a gated launch when this visit's + gate_sink can take the kernel's y (INKLING_ATTN_GATE=all, whole-visit rows, kernel layouts), else None. The + caller launches with them and then calls gate_commit(g, out).""" + import torch + + if not GATE_ALL: + return None + visit = _CTX.get() + if visit is None or visit.local or visit.gated is not None or out is None: + return None + if not _gate_ok(visit, {"q": q, "out": out}): + return None + y = torch.empty(tuple(visit.gate.shape), dtype=torch.bfloat16, device=visit.gate.device) + return {"gate": visit.gate, "sinks": visit.sinks, "y": y, "_visit": visit} + + +def gate_commit(g, out): + """After the gated launch(es) of gate_begin's kwargs: the visit's gate_sink returns y (out stays unwritten).""" + visit = g["_visit"] + visit.gated = (out, g["y"]) + STATS["gated"] += 1 + _log_once("gated_first_global", f"first gated global prefill launch ({visit.tokens} rows, packed reader)") + + +def make_gate_sink(stock): + """inkling2_attn's gate_sink: after a gated launch in this visit, return its BF16 y (the FP32 out it was handed + was never written, so anything else is an error); every other call is the stock function.""" + + def gate_sink(output, gate, lse, sinks, *, output_dtype, head_groups=None): + visit = _CTX.get() + done = visit.gated if visit is not None else None + if done is None: + return stock(output, gate, lse, sinks, output_dtype=output_dtype, head_groups=head_groups) + out, y = done + visit.gated = None + if (output.data_ptr() != out.data_ptr() or output.numel() != out.numel() or head_groups is not None + or gate is not visit.gate or sinks is not visit.sinks or tuple(y.shape) != tuple(gate.shape)): + raise RuntimeError("inkling_attn: gate_sink did not receive the gated visit's attention output") + import torch + + if output_dtype != torch.bfloat16: + raise RuntimeError("inkling_attn: gated epilogue writes BF16, gate_sink asked for another dtype") + return y + + gate_sink.__wrapped__ = stock + setattr(gate_sink, MARK, True) + return gate_sink + + +def patch_sm120(module): + stock = getattr(module, "_flash_attn_varlen_func", None) + if stock is None: + raise RuntimeError(f"inkling_attn: {SM120_MODULE}._flash_attn_varlen_func is missing") + if getattr(stock, MARK, False): + return False + module._flash_attn_varlen_func = make_varlen(stock) + return True + + +def patch_common_attn(module): + import inspect + + cls = getattr(module, "RelLogitsProj", None) + fwd = getattr(cls, "forward", None) if cls is not None else None + if fwd is None: + raise RuntimeError(f"inkling_attn: {COMMON_ATTN_MODULE}.RelLogitsProj.forward is missing") + params = list(inspect.signature(inspect.unwrap(fwd)).parameters) + if params[:3] != ["self", "r_out", "log_scaling_tau"]: + raise RuntimeError(f"inkling_attn: RelLogitsProj.forward signature changed: {params}") + prev = cls.__call__ + if getattr(prev, MARK, False): + return False + cls.__call__ = make_rel_call(prev) + return True + + +def patch_attn(module, kinds): + import importlib + + cls = getattr(module, "Inkling2Attention", None) + prev = getattr(cls, "_forward", None) if cls is not None else None + get_attn_backend = getattr(module, "get_attn_backend", None) + get_model = getattr(module, "get_model", None) + if prev is None or get_attn_backend is None or get_model is None: + raise RuntimeError( + f"inkling_attn: {ATTN_MODULE}.Inkling2Attention._forward, get_attn_backend or get_model is missing" + ) + if getattr(prev, MARK, False): + return False + in_breakable = getattr(importlib.import_module(BREAKABLE_MODULE), "is_in_breakable_cuda_graph", None) + if in_breakable is None: + raise RuntimeError(f"inkling_attn: {BREAKABLE_MODULE}.is_in_breakable_cuda_graph is missing") + cp_active = getattr(importlib.import_module(CP_MODULE), "is_cp_active", None) + if cp_active is None: + raise RuntimeError(f"inkling_attn: {CP_MODULE}.is_cp_active is missing") + cls._forward = make_forward(prev, get_attn_backend, get_model, in_breakable, frozenset(kinds), cp_active) + if GATE_OFF_FOR_LOGGING: + _log_once("gate_off", "gated epilogue OFF: SGLANG_KERNEL_API_LOGLEVEL is set (it reads the FA4 output buffer)") + if GATE: + gs = getattr(module, "gate_sink", None) + if gs is None: + raise RuntimeError(f"inkling_attn: {ATTN_MODULE}.gate_sink is missing (INKLING_ATTN_GATE)") + if not getattr(gs, MARK, False): + module.gate_sink = make_gate_sink(gs) + _log_once("gate", "gated epilogue on: " + ("sliding-window and global" if GATE_ALL else "sliding-window") + + " prefill visits run gate_sink inside the attention kernel") + return True diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/tests/test_install.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/tests/test_install.py new file mode 100644 index 0000000000000000000000000000000000000000..3f5b7aa3fc4540b7d6f4caeea5cde74dd69c6af7 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/tests/test_install.py @@ -0,0 +1,54 @@ +"""CPU tests of inkling_attn's install logic (no torch, no GPU). + + python3 -m unittest discover -s inkling_attn/tests (from the overlay directory) + INKLING_ATTN_SGLANG_ROOT=/path/to/sglang additionally checks the patch targets of that source tree. +""" +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +import inkling_attn # noqa: E402 + + +class ParseLevers(unittest.TestCase): + def test_values(self): + self.assertEqual(inkling_attn.parse_levers(""), ()) + self.assertEqual(inkling_attn.parse_levers("0"), ()) + self.assertEqual(inkling_attn.parse_levers("prefill_swa"), ("prefill_swa",)) + self.assertEqual(inkling_attn.parse_levers("all"), ("prefill_swa", "prefill_global")) + self.assertEqual(inkling_attn.parse_levers(" prefill_global , prefill_swa,prefill_swa"), + ("prefill_global", "prefill_swa")) + with self.assertRaises(RuntimeError): + inkling_attn.parse_levers("prefill_swa,decode") + + +class SourceChecks(unittest.TestCase): + def _tree(self, drop=None): + root = tempfile.mkdtemp() + for rel, needles in inkling_attn._SOURCE_CHECKS: + path = os.path.join(root, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "a", encoding="utf-8") as f: + for n in needles: + if n != drop: + f.write(n + "\n") + return root + + def test_complete_tree_passes(self): + inkling_attn.check_sources(self._tree()) + + def test_missing_needle_fails(self): + needle = inkling_attn._SOURCE_CHECKS[0][1][2] + with self.assertRaises(RuntimeError): + inkling_attn.check_sources(self._tree(drop=needle)) + + @unittest.skipUnless(os.environ.get("INKLING_ATTN_SGLANG_ROOT"), "no sglang tree given") + def test_real_tree(self): + inkling_attn.check_sources(os.environ["INKLING_ATTN_SGLANG_ROOT"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/tests/test_w8split_cpu.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/tests/test_w8split_cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbe6c2208f0482018787241ae4c8a2ac2e971d1 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_attn/tests/test_w8split_cpu.py @@ -0,0 +1,118 @@ +"""CPU check of the per-request 4/8-warp split (ops.W8_FROM): a mirror of the kernel's work-item loop and selection +block in csrc/attn_kernel.cuh + + if (p.sel_mode != 0) { pre = (long long)seq_k[b] - sq; if ((pre >= sel_keys) != (sel_mode == 2)) return; } + +and of the two launches in csrc/inkling_attn_ext.cu (grid8: sel_mode 2, 128-row blocks, ceil(T/128) + n_req tiles; +grid: sel_mode 1, 64-row blocks). T (rows of q) is independent of cu_seqlens_q. Checks, per head: + - the union of the two launches writes exactly the physical rows the single 4-warp launch writes, each once; + - every request goes entirely to the launch its unclamped prefix (seqused_k - its rows) selects. + +Run: python3 overlay/inkling_attn/tests/test_w8split_cpu.py (or pytest) +""" +import random + + +def launch_rows(cu_q, seq_k, T, pt_cols, page_size, bm, sel_mode, sel_keys): + """[(physical row, request)] written by one launch (one head).""" + n_req = len(cu_q) - 1 + tiles = (T + bm - 1) // bm + n_req + rows = [] + for lin in range(tiles): + tile = lin + b, start, sq, prev_end = -1, 0, 0, 0 + for i in range(n_req): + s = max(cu_q[i], prev_end) + e = min(cu_q[i + 1], T) + ln = e - s if e > s else 0 + prev_end = max(prev_end, e) + nb = (ln + bm - 1) // bm + if tile < nb: + b, start, sq = i, s, ln + break + tile -= nb + if b < 0: + continue + sk = min(max(seq_k[b], 0), pt_cols * page_size) # used by the attention itself, not by the selection + del sk + if sel_mode != 0: + pre = seq_k[b] - sq + if (pre >= sel_keys) != (sel_mode == 2): + continue + m0 = tile * bm + rows += [(start + r, b) for r in range(m0, min(m0 + bm, sq))] + return rows + + +def request_rows(cu_q, T): + """rows each request owns under the kernel's guards: [max(cu[i], prev_end), min(cu[i+1], T)).""" + out, prev_end = [], 0 + for i in range(len(cu_q) - 1): + s, e = max(cu_q[i], prev_end), min(cu_q[i + 1], T) + prev_end = max(prev_end, e) + out.append(max(0, e - s)) + return out + + +def check(cu_q, seq_k, T, pt_cols, page_size, w8_from): + single = launch_rows(cu_q, seq_k, T, pt_cols, page_size, 64, 0, 0) + r8 = launch_rows(cu_q, seq_k, T, pt_cols, page_size, 128, 2, w8_from) + r4 = launch_rows(cu_q, seq_k, T, pt_cols, page_size, 64, 1, w8_from) + phys = [r for r, _ in r8 + r4] + assert len(phys) == len(set(phys)), "a physical row is written twice" + assert sorted(r8 + r4) == sorted(single), "the split writes other rows than the single launch" + lens = request_rows(cu_q, T) + for b, sq in enumerate(lens): + if sq == 0: + continue + want8 = seq_k[b] - sq >= w8_from + owners = {"8" for _, rb in r8 if rb == b} | {"4" for _, rb in r4 if rb == b} + assert owners == ({"8"} if want8 else {"4"}), (b, owners, want8) + + +def test_random(): + rng = random.Random(0) + for _ in range(4000): + page_size = rng.choice([64, 128]) + n_req = rng.randint(1, 6) + sqs = [rng.choice([0, 1, 7, 63, 64, 65, 127, 128, 129, 300, 2048]) for _ in range(n_req)] + w8_from = rng.choice([1, 64, 128, 1000, 131072]) + pre = [rng.choice([0, 5, w8_from - 1, w8_from, w8_from + 1, 2 * w8_from, 300000]) for _ in range(n_req)] + seq_k = [s + max(p, 0) for s, p in zip(sqs, pre)] + if rng.random() < 0.15: + seq_k[rng.randrange(n_req)] = rng.choice([0, 3]) # inconsistent metadata (sk < sq) + cu = [0] + for s in sqs: + cu.append(cu[-1] + s) + if rng.random() < 0.1 and cu[-1] > 0: + cu[rng.randrange(1, len(cu))] -= rng.randint(1, 70) # non-monotone cu_seqlens: the kernel's guards apply + cu = [max(0, c) for c in cu] + T = max(cu) + rng.choice([0, 0, 1, 63, 200]) # q rows independent of cu_seqlens_q (padded buckets) + if rng.random() < 0.1: + T = max(0, max(cu) - rng.randint(1, 100)) # cu_seqlens_q beyond q: guarded by total_q + pt_cols = (max(max(seq_k), 1) + page_size - 1) // page_size + if rng.random() < 0.15: + pt_cols = max(1, pt_cols // 4) # page table narrower than seq_k: attention clamps, selection does not + check(cu, seq_k, T, pt_cols, page_size, w8_from) + + +def test_threshold_direction(): + # one request exactly at / one below the threshold: owners must be 8 / 4 warps + r8 = launch_rows([0, 100, 200], [100 + 1000, 100 + 999], 256, 64, 128, 128, 2, 1000) + r4 = launch_rows([0, 100, 200], [100 + 1000, 100 + 999], 256, 64, 128, 64, 1, 1000) + assert {b for _, b in r8} == {0} and {b for _, b in r4} == {1} + # clamped page table: sq 16, seqused_k 256, capacity 128 keys, W8_FROM 128 -> 8 warps + assert {b for _, b in launch_rows([0, 16], [256], 16, 1, 128, 128, 2, 128)} == {0} + + +def test_serving_shapes(): + for pfx in (0, 131071, 131072, 262144, 1048576 - 8192): + check([0, 8192], [8192 + pfx], 8192, 8192, 128, 131072) + check([0, 100, 4196, 8192], [100 + 300000, 4096 + 7, 3996 + 131072], 8192, 8192, 128, 131072) + + +if __name__ == "__main__": + test_random() + test_threshold_direction() + test_serving_shapes() + print("ok") diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/README.md b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a049a2a5a9a1e0bc10494f680569057c12090069 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/README.md @@ -0,0 +1,197 @@ +# inkling_cert: certified greedy argmax of the target LM head + +On greedy verify steps only the argmax of each row's 201,024 logits matters. This package reads a 6-bit copy of +the head (358 MB) instead of pico's coded head (715 MB), bounds every logit rigorously, and runs pico's exact head +GEMV only on the 16-row tiles that can hold the argmax. Every other logit is written as -inf. The stock softcap, +padding mask and argmax then run unchanged and return the same token as the full head, bit for bit. + +Status (2026-11-21): written, CPU-tested (21 tests), and GPU-checked on GB10 with real weights: +`tools/gpu_check_cert.py` PASS, `tools/smoke_hooks.py` PASS (all hooks land on the image's sglang, cert outside +pico). Not yet run in a serving boot: the next step is `INKLING_CERT_HEAD=check` for a few thousand steps, then an +A/B against `=0`. + +## GPU check (2026-11-21, GB10, real head, 5,983 real LM-head rows from the CPU oracle) + +| gate | result | +|---|---| +| 6-bit copy decodes to the quantised head (by the kernel's rule); tables finite | ok | +| screen accumulation error / model (C_ACC ||D|| ||x||), 512 rows x 201,024 ids | max 0.0002 | +| pico accumulation error / model (C_ACC ||W|| ||x||) | max 0.0004 | +| s - B <= pico <= s + B for every logit | 0 outside; max abs(pico - s) / B = 0.13 | +| certified token == full-head token (stock softcap, mask, argmax), M = 8 | 5,976 rows, 0 mismatches, 747/747 steps certified | +| same, M = 16 | 5,968 rows, 0 mismatches, 373/373 certified | +| computed tiles bit-identical to pico's full head, others -inf | 0 bad steps | +| `on` = 0 equals pico's full head bit for bit | ok | +| near-tie rows (x along W_a + W_b, norms 150-800) | 2,048 rows, 0 mismatches | +| duplicate head rows (1 pair in the vocab): exact tie resolves to the lower id | ok | +| CUDA graph replay == eager, 40 steps with `on` toggled | ok | + +Candidate tiles per step: M = 8 mean 57.6, p50 29, p90 96, p99 238, max 9,639 (one flat row; still exact, just +slower). M = 16: mean 105, p50 52, p99 433. + +Microbench (L2 flushed with a 256 MiB read before each rep, CUDA events, median of 30): + +| | M = 8 | M = 16 | +|---|---:|---:| +| pico full head (current `lmhead`) | 2.898 ms (247 GB/s) | 3.036 ms (236 GB/s) | +| certified path, median-candidate batch (18 / 30 tiles) | **1.671 ms** | **1.730 ms** | +| certified path, p90 batch (40 / 61 tiles) | 1.680 ms | 1.730 ms | +| screen alone (screen + rowmax + select) | 1.569 ms = 228 GB/s of 358 MB | 1.618 ms = 221 GB/s | +| `on` = 0 step (full head through the masked kernel) | 2.971 ms | 3.027 ms | + +Final kernel (`gpu4.log`). Saving per certified step: -1.23 ms at c1 and -1.31 ms at c2. A persistent grid-stride screen (96-384 CTAs, x +loaded once per CTA) was tried and rejected: 140 GB/s at M = 8 and 202 at M = 16, because the x loads then go +ahead of the weight stream. A step that is not eligible pays about +90 us over +pico. + +## Switch + +| env | default | meaning | +|---|---|---| +| `INKLING_CERT_HEAD` | unset (off) | `1`: certified head on eligible steps; `check`: serve pico's full head, build the certified result beside it and count token mismatches (must stay 0); `0`: off | +| `INKLING_CERT_HEAD_LOG_EVERY` | 2000 | counter line every N verify steps (0 = never) | +| `INKLING_CERT_HEAD_CACHE` | `~/.cache/inkling-cert` | extension build cache | + +The package needs `INKLING_PICO12` with `lmhead`, installed first. pico's GEMV is both the exact pass and the +fallback, and the certified token must equal pico's. + +Arming in `sitecustomize.py`, after the `INKLING_PICO12` block: + +```python + if _on("INKLING_CERT_HEAD"): # after inkling_pico12: wraps its lm-head function and reads its coded head + import inkling_cert + inkling_cert.install() +``` + +`_on()` already treats `check` as on, and `install()` reads the mode itself. `scripts/launch.sh` passes the +variable through `SGLANG_ENV` (`-e INKLING_CERT_HEAD=1`); `scripts/launch.sh` sets it from `CERT_HEAD`. + +## Measured before building (kill-check) + +Real LM-head inputs: 5,983 rows from the CPU oracle (`engine/ref/inkling2_ref.py`, FP32). They come from +teacher-forcing the 16 speedbench greedy transcripts, rounded to BF16. The real unembedding was used. Script: +`results/kbench/round2/cert/cand_count.py`. The head rows have norm 1.00 and ||x|| is about 223. The top logit has a median of +50.7, and the gap to the second logit has a median of 13.6. + +| screen | MB read | bound B (median) | candidate tiles / step c1 (mean, p99, max) | c2 (mean, p99) | est. ms | +|---|---:|---:|---|---|---:| +| INT8 per row | 471 | 2.0 | 13, 25, 26 | | 2.06 | +| **INT6, FP16 scale per 192** | **358** | **6.2** | **43, 236, 606** | **78, 328** | **1.59** | +| INT6, FP16 scale per 32 | 382 | 5.0 | 23, 92, 213 | 43, 138 | 1.68 | +| INT7, scale per 192 | 416 | 3.1 | 14, 37, 52 | 26, 57 | 1.82 | +| INT5, scale per 32 | 324 | 10.4 | 305, 1638, 2279 | | 1.52 (heavy tail) | +| INT4, scale per 32 | 290 | 21 | ~10k (everything) | | dead | + +The estimate charges screen bytes at 235 GB/s, candidate tiles at 57 KB each at 200 GB/s, plus 50 us of small +kernels. pico's full head is 2.90 ms at 8 rows. The measured screen error is about 1.4 % of the bound, because the +Cauchy-Schwarz bound is far from tight. Only the very peaked logits make it work. + +## Per step (M <= 16 verify rows, all in the verify CUDA graph) + +| kernel | what | +|---|---| +| `k_screen` (12564 CTAs x 12 warps) | Computes s = x . D^T from the 6-bit copy with BF16 MMAs. Each warp covers one 192-value group and scales its partial by the group's FP16 scale. ||x_g|| is computed from the same registers. Epilogue: B, then lo/hi, then the max of lo and of hi per (row, 16-row tile) over the real vocab. A non-finite value sets a flag. | +| `k_rowmax` | T[m] = max lo, H[m] = max hi | +| `k_select` | Per tile: a mask byte, set when some row has hi >= T - delta in that tile. All tiles are set when the step is not eligible (`on` = 0), a value was non-finite, or a row fails the softcap range test. Also updates the counters. | +| `k_exact` | pico's `gemv16_body` on the masked CTAs. This is the code of pico's coded-head GEMV (the same file, compiled into this extension) and gives its bits. Every other CTA writes -inf. | + +Then the stock code continues: `fused_softcap` in place, ids >= `vocab_size` set to -inf, and the folded greedy +accept's argmax. + +## Why the token is the same (cert_math.py has the full statement) + +1. **Bound.** |pico - | <= C_ACC ||W_v|| ||x|| and |s - | <= C_ACC ||D_v|| ||x||, where + C_ACC = (K/16 * 17 + 32) 2^-23 is the tensor-core accumulation model (an assumption, measured by the GPU check; + pico12's own check already gates pico at (K/16 + 32) 2^-23). Also || <= sum_g ||R_vg|| ||x_g|| + (Cauchy-Schwarz per group). Every table is rounded up, and every FP32 step is inflated, so lo <= l <= hi. +2. **The winner is computed.** Let w be the stock token and u the id with lo_u = T. If l_w >= l_u, then + hi_w >= T. Otherwise f(l_w) >= f(l_u) with l_w < l_u, where f is the stock FP32 softcap, which is monotone only + up to E = 2^-14. Then l_u - l_w <= delta = 2 * 2E / exp(-2L/30) on the range L checked on the device, so + hi_w >= T - delta. +3. **No -inf beats it.** f(-inf) = -30, and f(l_w) >= 30 tanh(T/30) - E > -30 under the range test (|T|, |H| up + to about 160; real logits are 50-70). +4. **Ties.** Computed ids hold the stock values. The set of maximisers among them therefore contains w, the lowest + stock maximiser, and nothing below it. The stock argmax (lowest index) returns w. + +x is finite, so every logit is finite and no NaN reaches the argmax. A non-finite screen value forces the full +head anyway. + +## When the certified path runs (`on` = 1) + +The device flag is written before each verify replay by the `TargetVerifyExecutor.run_non_compact` wrapper. It is +1 only when all of these hold: +- `begin_static_step(bs, armed)` was called with `armed = fold_eligible`. That means a static-mode step whose + in-graph folded greedy accept is used: all requests greedy, `verify_logits_adjustments_are_noop` (no penalties, + logit bias, grammar mask or custom processor), and no grammar. +- The batch has no `return_logprob`, no watermark candidates and no sampling-mask capture. +- None of the DSpark debug observers that read the verify logits is set (checked at load; the package disables + itself if one is). + +`begin_step` (compact mode, idle participation) sets it to 0. Eager forwards (no graph) always compute the full +head. The first eager call per row bucket goes through these kernels in full-fallback mode, and later eager calls +go straight to pico. Rows > 16 (c3 and up) never reach here: pico itself takes only 1-16. + +### On the DFLASH worker (`dflash.py`, `SPEC=dflash2`, launch `CERT_DFLASH` / `CERT_WIDE_DFLASH`) + +DFLASH has no verify epilogue: its accept runs eagerly after the target-verify graph, as the argmax of the verify +logits on greedy batches. A wrapper of `DFlashWorkerV2.forward_batch_generation` marks the step, and a wrapper of +`TpModelWorker.forward_batch_generation` sets `on` right before that step's target verify to +`batch_ok(batch)` and `DFlashWorkerV2._can_skip_verify_logits(batch, sampling_info)` (all greedy, no grammar, +logprobs, logit adjustments or selector sample), and back to 0 right after it, so no other replay reads a stale 1. +- Narrow head (<= 16 rows): it writes pico's exact logits on the candidate tiles and -inf elsewhere, so the stock + argmax over the verify logits returns the certified token. Under the verify cap (`inkling_vcap` on DFLASH, + `STATE.src_index`), dead rows are given their anchor's hidden row before the screen, selected on the device by + `on`, so they add no candidate tiles; live rows keep their own rows and no accept reads a dead row's token. +- Wide head (17..`INKLING_CERT_WIDE_MAX_ROWS` rows): the certified IDs, which the wide head returns instead of + writing the logits, are looked up after each target-verify replay (`DecodeCudaGraphRunner._process_output_after_replay`, + from the replayed graph's own output) and passed to `DFlashWorkerV2._accept_block` as its target prediction. A wide + replay whose IDs cannot be identified stops the server; the compact ragged verify layout is refused. +- Check mode (`CERT_DFLASH=check`): 34,808 rows, 0 mismatches. + +## Patch points + +| target | what | +|---|---| +| `models/inkling2.py: Inkling2LogitsProcessor._get_logits` | marks target-verify calls (`forward_mode.is_target_verify()`) | +| `models/inkling2.py: Inkling2ForConditionalGeneration.post_load_weights` | after pico coded the head: builds the 6-bit copy and the tables on the GPU (chunked, float64), runs the self-test (full fallback == pico bit for bit, certified argmax == full argmax on random rows at M = 8 and 16; this also loads every kernel before capture), and logs one line | +| `layers/quantization/unquant.py: sm12x_fp32_lm_head` | wraps pico's wrapper. It takes target-verify calls that pico would take, as long as the processor has softcap 30, no `logit_scale`, no TP gather, and `vocab_size` <= rows. Everything else goes to pico or stock. | +| `speculative/dspark_components/dspark_verify.py: DsparkVerifyEpilogue.begin_static_step / begin_step, TargetVerifyExecutor.run_non_compact` | the per-step device flag (above) and the periodic counter line | + +Source strings are checked at `install()`, and attributes when each module is imported. A mismatch exits with 78. +TP > 1 disables the package with a log line. + +Coexistence: +- `inkling_pico12`: required, and its wrapper sits inside ours. +- `inkling_vcap`: under DSpark, independent: dead rows are still verify rows with real hidden states, and their + logits are certified like the others. Under DFLASH, see above (dead rows take their anchor's row). +- `inkling_draftbytes`: the draft head is not touched. + +## Cost and memory + +- Extra memory is 358 MB (Q 347.4, scales 4.8, residual norms 4.8, row norms 0.8) plus about 1.7 MB of buffers. +- A step that is not eligible (`on` = 0: sampled, logprobs, ...) costs pico's head plus about 20-30 us. The screen + and row-max kernels return at once, and the masked kernel runs every tile (pico's full head). An eligible step + that fails the range test pays the screen and the full head; this is never seen on real rows. + +## Reviews and logs + +- GPU logs (GB10): `results/kbench/round2/cert/gpu2.log` (first PASS), `gpu3.log` (persistent variant, rejected), + `gpu4.log` (final kernel). + +## Files + +| path | origin | +|---|---| +| `csrc/cert_ext.cu`, `*.py`, `tests/`, `tools/` | ours (ported in spirit from our GLM-5.3-Flash `glm_cert_head.py` / `cert_math.py`) | +| pico's `gemv16.cu`, `common.cuh`, `dsk.h`, `check.h` | not copied: `#include`d from `../inkling_pico12/third_party/pico` (MIT, Copyright (c) 2026 Andy Shu) | + +## Checks + +- CPU: `python3 -m unittest discover -s inkling_cert/tests -v` from `overlay/` (needs numpy and torch). It covers + pack/unpack, the lane/MMA k-mapping of the packed layout, tables (torch vs numpy), bound coverage, adversarial + screen errors, exact ties, softcap ties, padded ids, range fallback and the fill. +- GPU: `python3 inkling_cert/tools/gpu_check_cert.py --model /model --hidden DIR`, where DIR holds real LM-head + input rows as `.npz`. It gates the packing, the accumulation model (screen and pico vs FP64), coverage + (lo <= pico <= hi for every logit), and token identity on every real row at M = 8 and 16. It also gates near-tie + rows, duplicate head rows, computed tiles bit-identical to pico, `on` = 0 equal to pico, and graph replay equal + to eager. It then benches. diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/__init__.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57beab2da984105fe608ae89c156f97afca316b2 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/__init__.py @@ -0,0 +1,172 @@ +"""Inkling-2-Mini on DGX Spark: certified greedy argmax of the target LM head (exact; see README.md). + + INKLING_CERT_HEAD=1 | check | 0 (default: unset -> install() does nothing) + +1 greedy target-verify steps (the in-graph folded greedy accept, no logprobs / grammar / penalties / logit bias / + watermark / sampling masks) read a 6-bit copy of the head (358 MB) plus pico's exact head GEMV on the + candidate tiles instead of pico's whole coded head (715 MB); every other step runs the head unchanged. +check serve pico's full head; build the certified result beside it and count token mismatches (must be 0). + +INKLING_CERT_WIDE=1 with INKLING_CERT_HEAD=1 also certifies 17–192 rows +when the packed, unsplit inkling_wide head would serve the same call. + INKLING_CERT_WIDE_MAX_ROWS largest verify batch (rows, 17..192) the wide path serves (default + WIDE_MAX_ROWS_DEFAULT); larger batches run the head unchanged + INKLING_CERT_WIDE_STATS=1 diagnostic: count wide outcomes (certified / unsafe / too many / off) and the + candidate-tile union per batch size in the graph, logged with the counters line + +Needs INKLING_PICO12 with `lmhead` armed first (pico's GEMV is the exact pass and the fallback). Other settings: + INKLING_CERT_HEAD_LOG_EVERY counters line every N verify steps (default 2000, 0 = never) + INKLING_CERT_HEAD_CACHE extension build cache (default ~/.cache/inkling-cert) +""" + +import importlib.util +import os +import sys + +STATE = {"installed": False, "mode": "0", "cfg": None} + +_SOURCE_CHECKS = ( + ("srt/layers/quantization/unquant.py", ("def sm12x_fp32_lm_head(", "def sm12x_fp32_lm_head_applies(")), + ("srt/layers/logits_processor.py", ("sm12x_fp32_lm_head_applies(hidden_states, lm_head.weight, out)", + "logits = self._compute_lm_head(")), + ("srt/models/inkling2.py", ("class Inkling2LogitsProcessor(", "def _get_logits(", "fused_softcap(logits, self.shard_softcap)", + "logits[..., self.config.vocab_size :] = float(\"-inf\")", "def post_load_weights(")), + ("srt/speculative/dspark_components/dspark_verify.py", + ("class DsparkVerifyEpilogue:", "def begin_static_step(self, bs: int, armed: bool)", + "def begin_step(self, verify_lens, armed: bool)", "def run_non_compact(", + "target_predict = sampling_argmax(logits).view(-1)")), + ("srt/speculative/dspark_components/dspark_worker_v2.py", + ("self._verify_epilogue.begin_static_step(bs, fold_eligible)", "and (sampling_info is None or sampling_info.is_all_greedy)", + "and verify_logits_adjustments_are_noop(sampling_info)", "compute_spec_logprobs(")), +) + +_WIDE_SOURCE_CHECKS = ( + ("kernels/ops/activation/softcap.py", + ("x = x / softcapping_value", "x = libdevice.tanh(x)", "x = x * softcapping_value")), + ("kernels/ops/speculative/dspark/dspark_accept.py", + ("target_predict: Optional[torch.Tensor] = None", "if target_predict is None:")), + ("srt/speculative/dspark_components/dspark_verify.py", + ("AcceptGreedy.execute(", "target_logits=logits", "logits=out.next_token_logits")), + ("srt/model_executor/runner/decode_cuda_graph_runner.py", + ("class DecodeCudaGraphRunner(", "def execute(", "output = self.backend.replay(")), +) + +UNQUANT = "sglang.srt.layers.quantization.unquant" +MODEL = "sglang.srt.models.inkling2" +VERIFY = "sglang.srt.speculative.dspark_components.dspark_verify" +GRAPH_RUNNER = "sglang.srt.model_executor.runner.decode_cuda_graph_runner" + + +def _log(msg): + sys.stderr.write(f"[inkling_cert pid={os.getpid()}] {msg}\n") + sys.stderr.flush() + + +# Largest verify batch (rows) the wide certified head serves; larger batches run the head unchanged. GB10 sweep +# 2026-11-24 (tools/gpu_check_certwide.py, CW_ROWS 64..192, real head, captured rows): at 129-192 rows the screen +# runs the 12-row-group kernel at 1 CTA/SM (143 registers) and takes 4.85-5.92 ms, so even a fully certified batch +# is 0.09-0.19 ms slower than the dense head at 136/160/176/192 rows (+0.01 at 144); at 128 rows (2 CTAs/SM) the +# certified head wins 1.65 ms and loses 2.70 ms on an overflow (break-even at a 38 % fallback rate). +WIDE_MAX_ROWS_DEFAULT = 128 + + +def parse_mode(value): + v = (value or "").strip().lower() + if v in ("", "0", "off", "none", "false", "no"): + return "0" + if v in ("1", "on", "true", "yes"): + return "1" + if v == "check": + return "check" + raise RuntimeError(f"inkling_cert: INKLING_CERT_HEAD={value!r}: 1, check or 0") + + +def config_from_env(env): + raw = env.get("INKLING_CERT_HEAD_LOG_EVERY", "").strip() + try: + every = int(raw) if raw else 2000 + except ValueError as exc: + raise RuntimeError(f"inkling_cert: INKLING_CERT_HEAD_LOG_EVERY={raw!r}") from exc + cache = env.get("INKLING_CERT_HEAD_CACHE", "").strip() or os.path.join(os.path.expanduser("~"), ".cache", + "inkling-cert") + wide = parse_mode(env.get("INKLING_CERT_WIDE", "")) + if wide == "check": + raise RuntimeError("inkling_cert: INKLING_CERT_WIDE accepts 0 or 1") + raw = env.get("INKLING_CERT_WIDE_MAX_ROWS", "").strip() + try: + max_rows = int(raw) if raw else WIDE_MAX_ROWS_DEFAULT + except ValueError as exc: + raise RuntimeError(f"inkling_cert: INKLING_CERT_WIDE_MAX_ROWS={raw!r}") from exc + if not 17 <= max_rows <= 192: + raise RuntimeError(f"inkling_cert: INKLING_CERT_WIDE_MAX_ROWS={max_rows} outside 17..192") + stats = parse_mode(env.get("INKLING_CERT_WIDE_STATS", "")) + if stats == "check": + raise RuntimeError("inkling_cert: INKLING_CERT_WIDE_STATS accepts 0 or 1") + return {"log_every": max(0, every), "cache_dir": cache, "wide": wide == "1", "wide_max_rows": max_rows, + "wide_stats": stats == "1"} + + +def check_sources(root=None, wide=False): + if root is None: + spec = importlib.util.find_spec("sglang") + if spec is None or not spec.submodule_search_locations: + raise RuntimeError("inkling_cert: the sglang package is not importable") + root = list(spec.submodule_search_locations)[0] + checks = _SOURCE_CHECKS + (_WIDE_SOURCE_CHECKS if wide else ()) + for rel, needles in checks: + path = os.path.join(root, rel) + try: + with open(path, encoding="utf-8") as f: + text = f.read() + except OSError as exc: + raise RuntimeError(f"inkling_cert: patch target {path} is missing") from exc + missing = [n for n in needles if n not in text] + if missing: + raise RuntimeError(f"inkling_cert: patch target {path} lacks {missing}") + + +def _callback(name): + def run(module): + try: + from . import patches + + if patches.STATE["cfg"] is None: + patches.STATE.update(mode=STATE["mode"], cfg=STATE["cfg"], log=_log) + except BaseException as exc: # noqa: BLE001 + _log(f"FATAL importing the patches: {exc!r}") + os._exit(78) + patches._guarded(getattr(patches, name))(module) + + run.__name__ = f"inkling_cert.{name}" + return run + + +def install(env=None, sglang_root=None): + """Arm INKLING_CERT_HEAD. Idempotent; returns the mode ("0" = nothing armed).""" + if STATE["installed"]: + return STATE["mode"] + env = os.environ if env is None else env + mode = parse_mode(env.get("INKLING_CERT_HEAD", "")) + STATE["installed"] = True + STATE["mode"] = mode + if mode == "0": + return mode + pico = sys.modules.get("inkling_pico12") + if pico is None or "lmhead" not in tuple(pico.STATE.get("levers", ())): + raise RuntimeError("inkling_cert: INKLING_CERT_HEAD needs inkling_pico12 installed first with `lmhead`") + STATE["cfg"] = config_from_env(env) + if STATE["cfg"]["wide"]: + wide = sys.modules.get("inkling_wide") + if mode != "1" or wide is None or "lmhead" not in tuple(wide.STATE.get("levers", ())): + raise RuntimeError("inkling_cert: INKLING_CERT_WIDE needs INKLING_CERT_HEAD=1 and INKLING_WIDE with lmhead") + check_sources(sglang_root, wide=STATE["cfg"]["wide"]) + from . import _hook + + for module, cb in ((UNQUANT, "patch_unquant"), (MODEL, "patch_model"), (VERIFY, "patch_verify")): + _hook.when_imported(module, _callback(cb)) + if STATE["cfg"]["wide"]: + _hook.when_imported(GRAPH_RUNNER, _callback("patch_graph_runner")) + # DFLASH worker (SPEC=dflash2): per-step arming on greedy verify steps (dflash.py); inert under DSpark + _hook.when_imported("sglang.srt.speculative.dflash_worker_v2", _callback("patch_dflash_worker")) + _hook.when_imported("sglang.srt.managers.tp_worker", _callback("patch_dflash_tp_worker")) + return mode diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/_hook.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..d11eff38cb26fbad1c9ee6888c4ca8aab709dd8f --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/_hook.py @@ -0,0 +1,78 @@ +"""Post-import hooks: run a callback right after a module finishes executing. + +The overlay must not import sglang (and torch) in every Python process that the +container starts, so patches are attached to their target modules lazily. If the +target module is already imported when the hook is registered, the callback runs +immediately. A callback that raises makes the import of its target fail. +""" + +import importlib.abc +import sys +import threading + +_lock = threading.RLock() +_callbacks: dict[str, list] = {} +_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): + # get_source, get_filename, is_package, ... for inspect / linecache. + 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) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/build.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/build.py new file mode 100644 index 0000000000000000000000000000000000000000..f29f13c763db6acdf2998e99b4469f93725eeeb8 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/build.py @@ -0,0 +1,102 @@ +"""Build (or reuse) the inkling_cert CUDA extension with torch.utils.cpp_extension. + +The only source is csrc/cert_ext.cu; it #includes pico's gemv16.cu from inkling_pico12's vendored copy +(../inkling_pico12/third_party/pico, MIT, Andy Shu), so the exact pass is compiled from the very file the +`lmhead` GEMV is built from. Flags are pico's. The build directory is /, a hash of every source +and header, the flags, torch's and CUDA's versions. = INKLING_CERT_CACHE (default ~/.cache/inkling-cert). + + python3 -m inkling_cert.build # build now (in the container, no GPU needed); prints the path +""" + +import hashlib +import os +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +PICO = os.path.join(os.path.dirname(HERE), "inkling_pico12", "third_party", "pico") +SOURCES = (os.path.join(HERE, "csrc", "cert_ext.cu"),) +HEADERS = ( + os.path.join(HERE, "csrc", "screen6.cuh"), + os.path.join(HERE, "csrc", "certwide_screen.cuh"), + os.path.join(PICO, "kernels", "gemv16.cu"), + os.path.join(PICO, "kernels", "dsk.h"), + os.path.join(PICO, "kernels", "common.cuh"), + os.path.join(PICO, "common", "check.h"), +) +NAME = "inkling_cert_ext" +_UNDEF = ( + "-U__CUDA_NO_HALF_OPERATORS__", + "-U__CUDA_NO_HALF_CONVERSIONS__", + "-U__CUDA_NO_BFLOAT16_CONVERSIONS__", + "-U__CUDA_NO_HALF2_OPERATORS__", +) + + +def default_cache_dir(): + return os.path.join(os.path.expanduser("~"), ".cache", "inkling-cert") + + +def cuda_flags(std="c++20", arch="121a"): + return [f"-gencode=arch=compute_{arch},code=sm_{arch}", "-O3", f"-std={std}", "--expt-relaxed-constexpr", + "-lineinfo", *_UNDEF] + + +def build_tag(flags, torch_version, cuda_version): + h = hashlib.sha256() + for path in SOURCES + HEADERS: + with open(path, "rb") as f: + h.update(os.path.basename(path).encode() + b"\0" + f.read() + b"\0") + h.update("\0".join(flags).encode()) + h.update(f"\0{torch_version}\0{cuda_version}".encode()) + return h.hexdigest()[:16] + + +_EXT = None +INFO = {} + + +def load(cache_dir=None, std="c++20", arch="121a", verbose=False): + global _EXT + if _EXT is not None: + return _EXT + import torch + from torch.utils import cpp_extension + + missing = [p for p in SOURCES + HEADERS if not os.path.isfile(p)] + if missing: + raise RuntimeError(f"inkling_cert: sources missing (inkling_pico12 must sit next to inkling_cert): {missing}") + flags = cuda_flags(std, arch) + tag = build_tag(flags, torch.__version__, torch.version.cuda) + build_dir = os.path.join(cache_dir or default_cache_dir(), tag) + os.makedirs(build_dir, exist_ok=True) + cached = any(f.endswith(".so") and f.startswith(NAME) for f in os.listdir(build_dir)) + t0 = time.monotonic() + try: + ext = cpp_extension.load(name=NAME, sources=list(SOURCES), extra_cuda_cflags=flags, + extra_include_paths=[PICO], build_directory=build_dir, verbose=verbose) + except Exception as exc: # noqa: BLE001 + raise RuntimeError(f"inkling_cert: building the extension in {build_dir} failed: {exc}") from exc + for attr in ("screen", "exact", "prepare_certwide", "screen_wide", "screen_wide_info", "debug_select_wide"): + if not callable(getattr(ext, attr, None)): + raise RuntimeError(f"inkling_cert: extension in {build_dir} lacks {attr}()") + INFO.update(build_dir=build_dir, cached=cached, seconds=time.monotonic() - t0, tag=tag) + _EXT = ext + return ext + + +def main(argv=None): + import argparse + + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument("--cache", default=os.environ.get("INKLING_CERT_CACHE") or default_cache_dir()) + p.add_argument("--verbose", action="store_true") + a = p.parse_args(argv) + load(a.cache, verbose=a.verbose) + print(f"inkling_cert extension {'reused' if INFO['cached'] else 'built'} in {INFO['seconds']:.1f} s: " + f"{INFO['build_dir']}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/cert_math.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/cert_math.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9cb8252422df39e98da87cc652a5f20575810d --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/cert_math.py @@ -0,0 +1,163 @@ +"""NumPy model of the certified greedy LM-head argmax (what cert_ext.cu computes), for the CPU tests and as the +statement of the argument. No torch, no sglang. + +Stock pipeline (the reference the certificate must reproduce), per verify row m: + l = pico's FP32 head GEMV of x_m (inkling_pico12 `lmhead`), f(l) = fl(fl(tanh(fl(l / c))) * c) (stock softcap, + c = 30), y_v = f(l_v) for v < v_real and -inf for the padded ids, token = the lowest v with y_v = max y (the + stock argmax kernel's tie rule; with finite x every l is finite, so there is no NaN). + +Certified pipeline: + screen s_v ~ (6-bit copy), B_v = sum_g Rt[g, v] ||x_g|| + CN Nv[v] ||x||, lo = s - B - slop, + hi = s + B + slop; T = max_{v < v_real} lo_v; H = max hi. + select tile (16 ids) is computed iff some row has a tile member with hi >= T - delta, where delta (from T, H) makes + every pair a < b in [T - DMAX, H] with f(a) >= f(b) satisfy b - a <= delta. Not certifiable (all tiles + computed): the step is not eligible, a non-finite value, or the range test fails. + exact computed tiles hold pico's l (the same kernel body: the same bits); every other id holds -inf. Then the + stock softcap, padding mask and argmax run unchanged. + +Why the token is the same. (1) |acc - | and |s - | are both <= C_ACC * N_v * ||x|| (accumulation +model below; flushed subnormal inputs or products add at most K * 2^-126 * (||W_v||_1 + ||x||_1), covered by the +absolute slop while ||x|| <= 2^20, which the screen checks) and || <= sum_g ||R_vg|| ||x_g|| +(Cauchy-Schwarz per group), so lo_v <= l_v <= hi_v. (2) Let w be the stock token and u the id with lo_u = T, so +T <= l_u <= hi_u <= H, and f(l_w) >= f(l_u) with |f - g| <= E, g = c tanh(. / c) increasing. If l_w >= l_u then +hi_w >= l_w >= l_u >= T. Otherwise g(l_u) - g(l_w) <= 2E. Every y in [l_u - DMAX, l_u] has |y| <= L = max(|T| + DMAX, +|H|) and g' = sech^2(y / c) >= exp(-2L / c) there; if l_u - l_w > DMAX then g(l_u) - g(l_w) >= DMAX exp(-2L / c) +>= delta exp(-2L / c) = 4E > 2E (the device checks delta <= DMAX), a contradiction; so l_u - l_w <= DMAX and then +(l_u - l_w) exp(-2L / c) <= 2E, i.e. l_u - l_w <= delta / 2. Either way hi_w >= l_w >= T - delta: w's tile is +computed. (3) Every other id holds -inf, f(-inf) = -c, and y_w >= f(l_u) >= g(T) - E >= -c + c exp(-2L / c) - E > -c +(the device checks c exp(-2L / c) > 8E), so no uncomputed id reaches the maximum. (4) Computed ids hold the stock +values, so the maximum and the set of ids attaining it among computed ids are the stock ones restricted to computed +ids, and that set contains w, the lowest stock maximiser. Hence the stock argmax returns w on the certified buffer. +E = 2^-14 covers Triton's div.full (<= 2 ulp), libdevice tanhf (<= 2 ulp) and the final multiply for every |l| +(about 2.5e-5 at |f| ~ 30; tanhf saturates exactly to +-1 for large |l|). + +Accumulation model (an ASSUMPTION about the tensor cores, validated on the GPU): products of BF16 values are exact in +FP32, and each chained m16n8k16 MMA step adds at most 17 rounding errors of one FP32 ulp of the running magnitude +(Fasi, Higham, Mikaitis, Pranesh 2021); with K / 16 chained steps and the cross-warp FP32 sums this gives +C_ACC = (K / 16 * 17 + 32) * 2^-23 per unit of sum |w_k x_k| <= ||w|| ||x||. inkling_pico12's GPU check already +gates pico's head against FP64 with the tighter (K / 16 + 32) * 2^-23; tools/gpu_check_cert.py measures both the +screen and the exact pass against FP64 and against this bound. +""" + +import math + +import numpy as np + +K = 2304 +GROUP = 192 +NGROUPS = K // GROUP +TILE = 16 +QMAX = 31 +C_ACC = (K / 16 * 17 + 32) * 2.0 ** -23 +CN = 2.0 * C_ACC # exact path + screen +CAP = 30.0 # final_logit_softcapping +E_SOFTCAP = 2.0 ** -14 # |stock f(l) - c tanh(l / c)| (div.full + libdevice tanhf + one multiply: ~2.5e-5) +TWO_E = 2.0 * E_SOFTCAP +DMAX = 16.0 +INFL = 1.0 + 2.0 ** -16 +X_ABS = 2.0 ** -58 # covers squares of tiny activations that underflow in FP32 + + +def f32(a): + return np.asarray(a, dtype=np.float32) + + +def bf16_round(a): + u = np.ascontiguousarray(a, dtype=np.float32).view(np.uint32).astype(np.uint64) + r = ((u >> 16) & 1) + 0x7FFF + return ((u + r) >> 16 << 16).astype(np.uint32).view(np.float32) + + +def round_up_f16(x): + h = np.asarray(x, dtype=np.float64).astype(np.float16) + bump = h.astype(np.float64) < x + return np.where(bump, np.nextafter(h, np.float16(np.inf)), h).astype(np.float16) + + +def round_up_f32(x): + f = np.asarray(x, dtype=np.float64).astype(np.float32) + bump = f.astype(np.float64) < x + return np.where(bump, np.nextafter(f, np.float32(np.inf)), f).astype(np.float32) + + +def quantize(W): + """W [V, K] -> (q int8, sc fp16 [V, NGROUPS], D float64).""" + V = W.shape[0] + w = W.astype(np.float64).reshape(V, NGROUPS, GROUP) + amax = np.abs(w).max(-1) + sc = round_up_f16(amax / QMAX) + s = sc.astype(np.float64) + q = np.where(s[..., None] > 0, np.clip(np.rint(w / np.where(s > 0, s, 1)[..., None]), -QMAX, QMAX), 0) + return q.reshape(V, K).astype(np.int8), sc, (q * s[..., None]).reshape(V, K) + + +def tables(W, D): + V = W.shape[0] + R = (W.astype(np.float64) - D).reshape(V, NGROUPS, GROUP) + rt = round_up_f16(np.sqrt((R ** 2).sum(-1)) * (1 + 2.0 ** -40)) + nv = round_up_f32(np.maximum(np.linalg.norm(W.astype(np.float64), axis=1), np.linalg.norm(D, axis=1)) * (1 + 2.0 ** -40)) + return rt, nv + + +def screen(x, D, rt, nv, v_real, s_err=None): + """-> (lo, hi) float32 [M, V], mirrors the kernel epilogue. s_err: an injected screen error (tests).""" + M = x.shape[0] + x64 = x.astype(np.float64) + s = x64 @ D.T + if s_err is not None: + s = s + s_err + s = f32(s) + xg2 = f32((x64.reshape(M, NGROUPS, GROUP) ** 2).sum(-1)) + xg2 = f32(np.where(xg2 < 2.0 ** -126, 0.0, xg2)) # worst case: everything below the normal range is lost + xg = f32(np.sqrt(xg2) * np.float32(INFL) + np.float32(X_ABS)) + xn = f32(np.sqrt(xg2.sum(-1, dtype=np.float32)) * np.float32(INFL) + np.float32(4 * X_ABS)) + b = f32(xg.astype(np.float64) @ rt.astype(np.float64).T) + b = f32((b * np.float32(INFL) + np.float32(CN) * nv[None, :] * xn[:, None]) * np.float32(INFL)) + slop = f32((np.abs(s) + b) * np.float32(2.0 ** -20) + np.float32(1e-30)) + lo, hi = f32(s - b - slop), f32(s + b + slop) + lo[:, v_real:] = -np.inf + hi[:, v_real:] = -np.inf + return lo, hi + + +def select(lo, hi, on=True, bad=False): + """-> (tile mask bool [V/16], certified bool). Mirrors k_rowmax + k_select.""" + M, V = lo.shape + T, H = lo.max(1), hi.max(1) + ht = hi.reshape(M, V // TILE, TILE).max(-1) + full = (not on) or bad + thr = np.empty(M, np.float32) + for m in range(M): + L = max(abs(float(T[m])) + DMAX, abs(float(H[m]))) + ex = math.exp(-2.0 * L / CAP) + delta = 2.0 * TWO_E / max(ex, 1e-30) + ok = math.isfinite(T[m]) and math.isfinite(H[m]) and L < 1e4 and delta <= DMAX and CAP * ex > 4 * TWO_E + full |= not ok + thr[m] = T[m] - (delta if ok else 0.0) + if full: + return np.ones(V // TILE, bool), False + return (ht >= thr[:, None]).any(0), True + + +def softcap(l): + """The stock softcap in FP32 (division, tanh, multiply each rounded once).""" + l = f32(l) + with np.errstate(invalid="ignore", over="ignore"): + return f32(f32(np.tanh(f32(l / np.float32(CAP)))) * np.float32(CAP)) + + +def stock_token(l, v_real, f=softcap): + y = f(l) + y[..., v_real:] = -np.inf + return y.argmax(-1) # numpy argmax: first maximum = lowest id (no NaN here) + + +def certified_buffer(l, mask): + buf = np.full_like(l, -np.inf, dtype=np.float32) + cols = np.repeat(mask, TILE) + buf[:, cols] = l[:, cols] + return buf + + +def certified_token(l, mask, v_real, f=softcap): + return stock_token(certified_buffer(l, mask), v_real, f) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide.py new file mode 100644 index 0000000000000000000000000000000000000000..00599667215428b9dab0bb8d60c7e760a3f23e7e --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide.py @@ -0,0 +1,140 @@ +"""Certified packed head for 17–192 activation rows. The public result is token IDs.""" + +import threading + +import torch + +from . import cert_math, quant + +MIN_ROWS = 17 +MAX_ROWS = 192 +MAX_TILES = 2048 +PARTS = 16 +# Give each path 2 * C_ACC to cover the compounded rounding model. +CN = 4 * cert_math.C_ACC +MAX_WEIGHT_NORM = 2.0**28 +ABS_SLOP = 2.0**-78 + +CERTIFIED, UNSAFE, TOO_MANY, OFF, INVALID = range(5) + + +def weight_radius(tables): + """Upper bound on ||W-D|| + CN * max(||W||, ||D||), one FP32 value per vocab ID.""" + nv = tables["nv"] + if not bool((nv <= MAX_WEIGHT_NORM).all()): + raise ValueError("inkling_certwide: weight norms outside the supported range") + r = tables["rt"].double().square().sum(0).sqrt() + CN * nv.double() + return quant.round_up_f32(r * (1.0 + 2.0**-40)).contiguous() + + +class CertWide: + """Caller-owned fallback logit buffer. Launches and scratch are fixed under graph capture. + + All serving replays and gate writes use one host thread and CUDA stream. + Standalone callers must maintain the same ordering through reduction. + """ + + def __init__(self, screen_ext, wide_ext, entry, tables, capacity=MAX_TILES): + from . import certwide_reduce + + self.screen_ext, self.wide_ext, self.entry = screen_ext, wide_ext, entry + self.reduce = certwide_reduce.reduce + self.q, self.sc = tables["q"], tables["sc"] + self.radius = weight_radius(tables) + self.V = entry.n + if entry.k != cert_math.K or self.V <= 0 or self.V % cert_math.TILE: + raise ValueError("inkling_certwide: invalid packed head geometry") + self._replay_owner = None + self._owner_lock = threading.Lock() + self.ntiles = self.V // cert_math.TILE + self.capacity = min(int(capacity), self.ntiles) + if self.capacity < 1: + raise ValueError("inkling_certwide: tile capacity must be positive") + device = self.q.device + self.lower = torch.empty((MAX_ROWS, self.ntiles), dtype=torch.float32, device=device) + self.upper = torch.empty_like(self.lower) + self.norms = torch.empty(MAX_ROWS, dtype=torch.float32, device=device) + self.threshold = torch.empty_like(self.norms) + self.state = torch.empty(2, dtype=torch.int32, device=device) + self.tiles = torch.empty(self.capacity, dtype=torch.int32, device=device) + self.groups = torch.empty_like(self.tiles) + self.sparse = torch.empty((MAX_ROWS, self.capacity * cert_math.TILE), dtype=torch.float32, device=device) + self.partial = torch.empty((MAX_ROWS, PARTS), dtype=torch.int64, device=device) + self.empty = torch.empty(0, dtype=torch.float32, device=device) + self.stats = None # optional [MAX_ROWS + 1, 5 outcomes, UNION_BUCKETS] int64 (enable_stats) + self.counting = True # False while the startup / reload self-tests run + screen_ext.prepare_certwide(device.index) + wide_ext.prepare_certwide(device.index) + + def require_replay_stream(self): + stream = torch.cuda.current_stream(self.q.device) + owner = (threading.current_thread(), stream) + with self._owner_lock: + if self._replay_owner is None: + self._replay_owner = owner + elif self._replay_owner != owner: + raise RuntimeError("inkling_certwide: verify gate and replay must use the owning thread and CUDA stream") + + def screen(self, x, on, v_real, debug=None, *, three_stages=False): + s, lo, hi = (self.empty,) * 3 if debug is None else debug + self.screen_ext.screen_wide( + x, self.q, self.sc, self.radius, self.V, v_real, self.norms, self.lower, self.upper, + self.threshold, on, self.state, self.tiles, self.groups, s, lo, hi, + cert_math.CAP, cert_math.TWO_E, cert_math.DMAX, three_stages, + ) + + def exact(self, x, fallback, v_real, settings): + self.wide_ext.certwide_exact( + x, self.entry.buf, fallback, self.sparse[:x.shape[0]], + self.state, self.tiles, self.groups, self.entry.n, v_real, settings.mt, settings.mg, settings.pfd, + ) + + def run(self, x, fallback, on, v_real, settings, *, debug=None, capped=None, three_stages=False): + """Return [M] int64 IDs. On fallback only, also write capped, masked logits.""" + m = x.shape[0] + if capped is not None and (capped.shape != self.sparse.shape or capped.device != self.sparse.device + or capped.dtype != self.sparse.dtype or not capped.is_contiguous()): + raise ValueError("inkling_certwide: invalid capped debug buffer") + ids = torch.empty(m, dtype=torch.int64, device=x.device) + self.screen(x, on, v_real, debug, three_stages=three_stages) + self.exact(x, fallback, v_real, settings) + self.reduce(fallback, self.sparse, self.state, self.tiles, self.groups, + self.partial, ids, v_real, cert_math.CAP, capped) + if self.stats is not None and self.counting: + self._count(m) + return ids + + UNION_STEP = 256 # tiles per union bucket + UNION_BUCKETS = 17 # the last one holds unions >= 16 * UNION_STEP (> the 2048-tile capacity) + + def enable_stats(self): + """Diagnostic counters, written inside the graph after each run (three small launches, no sync).""" + device = self.state.device + self.stats = torch.zeros((MAX_ROWS + 1, 5, self.UNION_BUCKETS), dtype=torch.int64, device=device) + self._one = torch.ones(1, dtype=torch.int64, device=device) + + def _count(self, m): + reason = self.state[0:1].clamp(0, 4).long() # CERTIFIED, UNSAFE, TOO_MANY, OFF, INVALID + bucket = torch.div(self.state[1:2], self.UNION_STEP, rounding_mode="floor").clamp_(0, self.UNION_BUCKETS - 1) + self.stats[m].view(-1).index_add_(0, reason * self.UNION_BUCKETS + bucket.long(), self._one) + + def describe_stats(self, host): + names = ("cert", "unsafe", "too_many", "off", "invalid") + parts = [] + for m in range(host.shape[0]): + per = host[m] + if int(per.sum()) == 0: + continue + counts = " ".join(f"{names[r]}={int(per[r].sum())}" for r in range(5) if int(per[r].sum())) + union = ",".join(f"{b * self.UNION_STEP}+:{int(per[:3, b].sum())}" + for b in range(self.UNION_BUCKETS) if int(per[:3, b].sum())) + parts.append(f"M={m}: {counts} (union tiles {union})") + return "; ".join(parts) if parts else "none" + + def refresh(self, entry, tables): + # The graph captures the table and packed-buffer addresses. + if (entry.n != self.V or entry.k != self.entry.k + or self.entry.buf.data_ptr() != entry.buf.data_ptr()): + raise ValueError("inkling_certwide: reload changed a graph buffer address") + self.radius.copy_(weight_radius(tables)) + self.entry = entry diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide_math.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide_math.py new file mode 100644 index 0000000000000000000000000000000000000000..12ab166a374a5e2b9a3d5533824a6582b81e7688 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide_math.py @@ -0,0 +1,74 @@ +"""CPU model of the wide certificate's intervals and candidate selection.""" + +import numpy as np + +from . import cert_math as cm +from .certwide import ABS_SLOP, CN, MAX_WEIGHT_NORM + + +def weight_radius(rt, nv): + """rt is [vocab, 12] and already rounded up, as is nv [vocab].""" + if not np.all(nv <= MAX_WEIGHT_NORM): + raise ValueError("weight norms outside the supported range") + radius = np.sqrt(np.square(rt.astype(np.float64)).sum(-1)) + CN * nv.astype(np.float64) + return cm.round_up_f32(radius * (1 + 2.0**-40)) + + +def activation_norm(x): + x64 = x.astype(np.float64) + norm = np.linalg.norm(x64, axis=-1).astype(np.float32) + return norm * np.float32(cm.INFL) + np.float32(4 * cm.X_ABS) + + +def intervals(screen, norm, radius): + """Reference intervals for FP32 screen logits. Absolute slop covers FTZ.""" + b = cm.round_up_f32(norm.astype(np.float64)[:, None] * radius.astype(np.float64)[None, :]) + s = screen.astype(np.float32, copy=False) + e = (np.abs(s) + b) * np.float32(2.0**-20) + np.float32(ABS_SLOP) + return s - b - e, s + b + e + + +def derivative_lower(L): + """CPU model of the device's downward-rounded repeated squaring.""" + z = np.nextafter(2 * L.astype(np.float64) / cm.CAP, np.inf) + base = np.nextafter(1 - np.minimum(z, 32) * 2.0**-20, -np.inf) + for _ in range(20): + base = np.nextafter(base * base, -np.inf) + return np.where(z <= 32, -cm.round_up_f32(-base), np.float32(0)) + + +def thresholds(T, H): + """Return an inclusive cutoff and a safe flag per row.""" + with np.errstate(invalid="ignore", divide="ignore", under="ignore", over="ignore"): + L = np.maximum(cm.round_up_f32(np.abs(T.astype(np.float64)) + cm.DMAX), np.abs(H)) + slope = derivative_lower(L) + delta = cm.round_up_f32(2.0 * cm.TWO_E / slope.astype(np.float64)) + rounded_down = -cm.round_up_f32(delta.astype(np.float64) - T.astype(np.float64)) + ok = np.isfinite(T) & np.isfinite(H) & (delta <= cm.DMAX) + return rounded_down, ok + + +def select(lo, hi, v_real, capacity, norm, on=True): + """Return (row mask, union mask, wide activation-group mask, sparse route).""" + m, v = lo.shape + ht = hi.copy() + ht[:, v_real:] = -np.inf + ht = ht.reshape(m, v // cm.TILE, cm.TILE).max(-1) + thr, ok = thresholds(lo[:, :v_real].max(-1), ht.max(-1)) + rows = (ht >= thr[:, None]) & (np.arange(v // cm.TILE) * cm.TILE < v_real) + union = rows.any(0) + groups = np.zeros(v // cm.TILE, np.uint16) + for start in range(0, m, 16): + groups |= rows[start:start + 16].any(0).astype(np.uint16) << (start // 16) + count = int(union.sum()) + sparse = on and np.all(ok & (norm <= 2.0**20)) and 0 < count <= capacity and count < len(union) + return rows, union, groups, bool(sparse) + + +def compact_token(logits, v_real, groups, f=cm.softcap): + """Model the CUDA reduction, including its lowest-ID rule and NaN handling.""" + m, _ = logits.shape + tile = np.arange(v_real) // cm.TILE + live = (groups[tile][None, :] & (1 << (np.arange(m) // 16))[:, None]) != 0 + capped = f(logits[:, :v_real]) + return np.where(live & ~np.isnan(capped), capped, -np.inf).argmax(-1) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide_reduce.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..f79220af44802e3ac3eab8aed0d972111c12c079 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/certwide_reduce.py @@ -0,0 +1,68 @@ +"""Device-gated softcap and argmax over the compact or fallback wide head.""" + +import triton as tr +import triton.language as tl +from triton.language.extra import libdevice + + +@tr.jit +def _key(value, col): + # Match the stock CUDA argmax. NaNs never win and both signs of zero tie. + value = tl.where(value == value, value, -float("inf")) + bits = tl.where(value == 0.0, 0, value.to(tl.uint32, bitcast=True)).to(tl.uint32) + ordered = tl.where((bits & 0x80000000) != 0, ~bits, bits ^ 0x80000000) + return (ordered.to(tl.uint64) << 32) | (~col.to(tl.uint32)).to(tl.uint64) + + +@tr.jit +def _partials(Dense, Sparse, State, Tiles, Groups, Partial, Capped, cap, + N: tl.constexpr, REAL: tl.constexpr, SLOTS: tl.constexpr, + PARTS: tl.constexpr, BLOCK: tl.constexpr, EMIT: tl.constexpr): + row = tl.program_id(0) + row64 = row.to(tl.int64) + part = tl.program_id(1) + best = tl.full((BLOCK,), 0, tl.uint64) + if tl.load(State) == 0: + count = tl.load(State + 1) * 16 + for base in range(part * BLOCK, count, PARTS * BLOCK): + idx = base + tl.arange(0, BLOCK) + tile = tl.load(Tiles + idx // 16, idx < count, other=0) + gr = tl.load(Groups + idx // 16, idx < count, other=0) + col = tile * 16 + idx % 16 + valid = ((gr >> (row // 16)) & 1) != 0 + valid = valid & (idx < count) & (col < REAL) + x = tl.load(Sparse + row64 * (SLOTS * 16) + idx, valid, other=0) + # Same Triton FP32 division, libdevice tanh, and multiply as + # sglang.kernels.ops.activation.softcap (dynamic FP32 cap). + y = libdevice.tanh(x / cap) * cap + if EMIT: + tl.store(Capped + row64 * (SLOTS * 16) + idx, y, valid) + best = tl.maximum(best, tl.where(valid, _key(y, col), 0)) + else: + # Ineligible replays can have consumers of logits after the graph. + # Publish the normal capped and padded output for every fallback. + for base in range(part * BLOCK, N, PARTS * BLOCK): + col = base.to(tl.int64) + tl.arange(0, BLOCK) + ptr = Dense + row64 * N + col + x = tl.load(ptr, col < N, other=0) + y = libdevice.tanh(x / cap) * cap + y = tl.where(col < REAL, y, -float("inf")) + tl.store(ptr, y, col < N) + best = tl.maximum(best, tl.where(col < REAL, _key(y, col), 0)) + tl.store(Partial + row * PARTS + part, tl.max(best, 0)) + + +@tr.jit +def _finish(Partial, Out, PARTS: tl.constexpr): + row = tl.program_id(0) + bitkey = tl.max(tl.load(Partial + row * PARTS + tl.arange(0, PARTS)).to(tl.uint64), 0) + tl.store(Out + row, (~bitkey.to(tl.uint32)).to(tl.int64)) + + +def reduce(dense, sparse, state, tiles, groups, partial, ids, v_real, cap, capped=None): + parts = partial.shape[1] + _partials[(ids.numel(), parts)]( + dense, sparse, state, tiles, groups, partial, sparse if capped is None else capped, cap, + dense.shape[1], v_real, tiles.numel(), parts, 512, capped is not None, num_warps=4, + ) + _finish[(ids.numel(),)](partial, ids, parts, num_warps=1) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/cert_ext.cu b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/cert_ext.cu new file mode 100644 index 0000000000000000000000000000000000000000..6701ac91be1701d440c180a79257127de939b0d2 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/cert_ext.cu @@ -0,0 +1,549 @@ +// inkling_cert: certified greedy argmax of the target LM head (FP32 logits) on GB10. Ours, except the exact pass: +// it runs pico's coded-head GEMV body (gemv16_body, kBF16X; pico by Andy Shu, MIT, vendored by inkling_pico12 in +// third_party/pico and compiled into this extension from that same copy) on the CTAs a device mask selects. +// +// Per step, for the M <= 16 verify rows x [M][K] (K = 2304) and the V-row head (V % 16 == 0): +// screen s = x . D^T from a 6-bit copy D of the head (q in [-31, 31], one FP16 scale per row and 192-value group), +// the bound B = sum_g Rt[g][v] ||x_g|| + CN * Nv[v] ||x|| (Rt: residual group norms, Nv: max(||W_v||, ||D_v||), +// both rounded up), lo / hi = s -+ (B + slop); per pico CTA tile of 16 vocab rows and per row m: the max of lo +// and of hi over the tile's real-vocab rows (lt / ht); a non-finite s or B sets flags[1]. +// rowmax T[m] = max lo, H[m] = max hi over all tiles. +// select per tile: mask = 1 if the step is not certifiable (on == 0, flags[1], a row outside the softcap range), +// else OR over rows of (ht[m][tile] >= T[m] - delta[m]); counters. +// exact pico's head GEMV for the masked tiles (its own arithmetic, the bits of the full call); every other tile's +// outputs are set to -inf. +// No host sync, no allocation, fixed grids: CUDA-graph safe. The bound and its proof: ../README.md, ../cert_math.py. +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "kernels/gemv16.cu" // pico (MIT): gemv16_body, mma_bf16, streaming loads (this TU's own copy) + +#include "screen6.cuh" +#include "certwide_screen.cuh" + +namespace cert { + +using namespace screen6; + +template +__global__ void __launch_bounds__(32 * kGroups) k_screen(const __nv_bfloat16* __restrict__ x, int M, + const uint8_t* __restrict__ Q, const uint16_t* __restrict__ SC, + const uint16_t* __restrict__ RT, const float* __restrict__ NV, + int V, int v_real, float cn, float* __restrict__ lt, + float* __restrict__ ht, int ncta, int* __restrict__ flags, + const int* __restrict__ on, float* __restrict__ sdbg, + float* __restrict__ bdbg) { + constexpr bool kHi = RB > 8; + if (*on == 0) return; // not eligible: select computes every tile, lt / ht are not read + __shared__ float red[kGroups][RB][kRowsCta]; + __shared__ float xg2[kGroups][RB]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3; + const bool live = g < M, live2 = kHi && g + 8 < M; + // one 16-row tile per CTA (a persistent grid-stride variant with x loaded once measured 140-200 GB/s: the x + // loads then precede the weight stream) + const int cta = blockIdx.x, n_cta = cta * kRowsCta; + + // weights first: 2 tiles x 3 steps, 12 bytes each per lane + uint2 wn[2][kStepsPerGroup]; + uint32_t wh[2][kStepsPerGroup]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const size_t tile = (size_t)(n_cta / 8 + i) * kSteps; +#pragma unroll + for (int u = 0; u < kStepsPerGroup; ++u) { + const uint8_t* base = Q + (tile + warp * kStepsPerGroup + u) * kTileBytes; + wn[i][u] = dsk::ldg_stream64(base + 8 * lane); + wh[i][u] = dsk::ldg_stream32(base + 256 + 4 * lane); + } + } + // activations: row g (and g + 8), the lane's 16 values of each step + const int k0 = warp * kGroup + 16 * t; + uint4 xa[kStepsPerGroup][2], xb[kStepsPerGroup][2]; +#pragma unroll + for (int u = 0; u < kStepsPerGroup; ++u) { + const __nv_bfloat16* xr = x + (size_t)(live ? g : 0) * kK + k0 + u * kStep; + xa[u][0] = live ? __ldg(reinterpret_cast(xr)) : make_uint4(0, 0, 0, 0); + xa[u][1] = live ? __ldg(reinterpret_cast(xr + 8)) : make_uint4(0, 0, 0, 0); + if constexpr (kHi) { + const __nv_bfloat16* xr2 = x + (size_t)(live2 ? g + 8 : 0) * kK + k0 + u * kStep; + xb[u][0] = live2 ? __ldg(reinterpret_cast(xr2)) : make_uint4(0, 0, 0, 0); + xb[u][1] = live2 ? __ldg(reinterpret_cast(xr2 + 8)) : make_uint4(0, 0, 0, 0); + } else { + xb[u][0] = xb[u][1] = make_uint4(0, 0, 0, 0); + } + } + // ||x_g||^2 of this warp's group (sum of the lane's squares, then over the 4 lanes of a row) + float sq = 0.f, sq2 = 0.f; +#pragma unroll + for (int u = 0; u < kStepsPerGroup; ++u) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const uint32_t* a = &xa[u][h].x; + const uint32_t* b = &xb[u][h].x; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float a0 = dsk::bf16_lo(a[j]), a1 = dsk::bf16_hi(a[j]); + sq = fmaf(a0, a0, fmaf(a1, a1, sq)); + if constexpr (kHi) { + const float b0 = dsk::bf16_lo(b[j]), b1 = dsk::bf16_hi(b[j]); + sq2 = fmaf(b0, b0, fmaf(b1, b1, sq2)); + } + } + } + sq += __shfl_xor_sync(0xffffffffu, sq, 1); + sq += __shfl_xor_sync(0xffffffffu, sq, 2); + if constexpr (kHi) { + sq2 += __shfl_xor_sync(0xffffffffu, sq2, 1); + sq2 += __shfl_xor_sync(0xffffffffu, sq2, 2); + } + if (t == 0) { + if (g < RB) xg2[warp][g] = live ? sq : 0.f; + if constexpr (kHi) xg2[warp][g + 8] = live2 ? sq2 : 0.f; + } + + float c[2][4]; +#pragma unroll + for (int i = 0; i < 2; ++i) c[i][0] = c[i][1] = c[i][2] = c[i][3] = 0.f; +#pragma unroll + for (int u = 0; u < kStepsPerGroup; ++u) +#pragma unroll + for (int j4 = 0; j4 < 4; ++j4) { + const uint4& av = xa[u][j4 >> 1]; + const uint4& bv = xb[u][j4 >> 1]; + const uint32_t a0 = (j4 & 1) ? av.z : av.x, a2 = (j4 & 1) ? av.w : av.y; + const uint32_t a1 = (j4 & 1) ? bv.z : bv.x, a3 = (j4 & 1) ? bv.w : bv.y; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const uint32_t nib = (j4 < 2) ? wn[i][u].x : wn[i][u].y; + const uint32_t b0 = six_pair(nib, wh[i][u], 2 * j4), b1 = six_pair(nib, wh[i][u], 2 * j4 + 1); + dsk::mma_bf16(c[i], a0, a1, a2, a3, b0, b1); + } + } + // group scale (fp16, [kGroups][V]) of the lane's two columns per tile, then the partials to shared memory +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int n = n_cta + 8 * i + 2 * t; + const uint32_t s2 = __ldg(reinterpret_cast(SC + (size_t)warp * V + n)); + const float s0 = half_to_float_u16((uint16_t)(s2 & 0xFFFFu)), s1 = half_to_float_u16((uint16_t)(s2 >> 16)); + const int r = 8 * i + 2 * t; + if (g < RB) { + red[warp][g][r] = c[i][0] * s0; + red[warp][g][r + 1] = c[i][1] * s1; + } + if constexpr (kHi) { + red[warp][g + 8][r] = c[i][2] * s0; + red[warp][g + 8][r + 1] = c[i][3] * s1; + } + } + __syncthreads(); + + // epilogue: one thread per (row m, column r) of the CTA, m < RB + const int e = threadIdx.x; + if (e < RB * kRowsCta) { + const int m = e / kRowsCta, r = e % kRowsCta, n = n_cta + r; + float s = 0.f; +#pragma unroll + for (int w = 0; w < kGroups; ++w) s += red[w][m][r]; + float b = 0.f, xx = 0.f; +#pragma unroll + for (int w = 0; w < kGroups; ++w) { + const float q2 = xg2[w][m]; + xx += q2; + // >= ||x_g||: fp32 sum of 192 squares (relative error < 2^-16 after sqrt), sqrt rounding, and squares that + // underflow (each < 2^-126 is at worst lost: 192 * 2^-126 < 2^-116, sqrt < 2^-58) + const float xg = sqrtf(q2) * kInfl + kXAbs; + b = fmaf(half_to_float_u16(__ldg(RT + (size_t)w * V + n)), xg, b); + } + const float xn = sqrtf(xx) * kInfl + 4.f * kXAbs; + b = (b * kInfl + cn * __ldg(NV + n) * xn) * kInfl; + const float slop = (fabsf(s) + b) * (1.0f / 1048576.0f) + 1e-30f; + float lo = s - b - slop, hi = s + b + slop; + const bool real = m < M && n < v_real; + if (sdbg != nullptr && m < M) sdbg[(size_t)m * V + n] = s, bdbg[(size_t)m * V + n] = b; // GPU check only + // outside the supported domain (non-finite, or ||x|| > 2^20 where the absolute underflow allowance in slop would + // no longer cover flushed subnormal products): the whole step takes the full head + if (m < M && n < V && !(isfinite(s) && isfinite(b) && xn <= 1048576.f)) atomicOr(flags + 1, 1); + lo = real ? lo : -INFINITY; + hi = real ? hi : -INFINITY; + // max over the 16 columns of row m: 16 consecutive lanes +#pragma unroll + for (int o = 8; o >= 1; o >>= 1) { + lo = fmaxf(lo, __shfl_xor_sync(0xffffffffu, lo, o)); + hi = fmaxf(hi, __shfl_xor_sync(0xffffffffu, hi, o)); + } + if (r == 0 && m < M) { + lt[(size_t)m * ncta + cta] = lo; + ht[(size_t)m * ncta + cta] = hi; + } + } +} + +// T[m] = max lo, H[m] = max hi over the tiles (grid M, 1024 threads) +__global__ void __launch_bounds__(1024) k_rowmax(const float* __restrict__ lt, const float* __restrict__ ht, int ncta, + float* __restrict__ tm, float* __restrict__ hm, + const int* __restrict__ on) { + __shared__ float sl[32], sh[32]; + const int m = blockIdx.x; + if (*on == 0) return; + float lo = -INFINITY, hi = -INFINITY; + for (int i = threadIdx.x; i < ncta; i += blockDim.x) { + lo = fmaxf(lo, lt[(size_t)m * ncta + i]); + hi = fmaxf(hi, ht[(size_t)m * ncta + i]); + } + lo = dsk::warp_max(lo); + hi = dsk::warp_max(hi); + if ((threadIdx.x & 31) == 0) sl[threadIdx.x >> 5] = lo, sh[threadIdx.x >> 5] = hi; + __syncthreads(); + if (threadIdx.x < 32) { + lo = threadIdx.x < (int)(blockDim.x >> 5) ? sl[threadIdx.x] : -INFINITY; + hi = threadIdx.x < (int)(blockDim.x >> 5) ? sh[threadIdx.x] : -INFINITY; + lo = dsk::warp_max(lo); + hi = dsk::warp_max(hi); + if (threadIdx.x == 0) tm[m] = lo, hm[m] = hi; + } +} + +// Softcap margin. The stock path applies f(l) = fl(fl(tanh(fl(l / c))) * c) (Triton: div.full, libdevice tanhf), +// |f(l) - c tanh(l / c)| <= E. With every relevant logit in [T - DMAX, H] and |T| + DMAX, |H| <= L: +// f(a) >= f(b), a < b => b - a <= 2E / min sech^2 <= 2E / exp(-2L / c) (sech^2 y >= exp(-2|y|)); +// we use delta = 2 * 2E / exp(-2L / c) (2x margin for __expf), and require delta <= DMAX; +// and the -inf fill (f = -c) stays below every candidate maximum when c (1 - tanh(L / c)) >= c exp(-2L / c) > E; +// we require c exp(-2L / c) > 4 * 2E. +__global__ void __launch_bounds__(256) k_select(const float* __restrict__ ht, int ncta, int M, const float* __restrict__ tm, + const float* __restrict__ hm, const int* __restrict__ on, + int* __restrict__ flags, uint8_t* __restrict__ mask, + unsigned long long* __restrict__ stats, float cap, float two_e, float dmax) { + __shared__ float thr[16]; + __shared__ int full_s; + __shared__ int cnt; + if (threadIdx.x == 0) { + int full = (*on == 0) || (flags[1] != 0); + cnt = 0; + for (int m = 0; m < M && !full; ++m) { + const float T = tm[m], H = hm[m]; + const float L = fmaxf(fabsf(T) + dmax, fabsf(H)); + const float ex = __expf(-2.f * L / cap); // sech^2(L / c) >= ex + const float delta = 2.f * two_e / fmaxf(ex, 1e-30f); // 2x the bound 2E / ex + const bool ok = isfinite(T) && isfinite(H) && L < 1e4f && delta <= dmax && cap * ex > 4.f * two_e; + if (!ok) full = 1; + thr[m] = T - (ok ? delta : 0.f); + } + full_s = full; + } + __syncthreads(); + const int full = full_s; + const int tile = blockIdx.x * blockDim.x + threadIdx.x; + int set = 0; + if (tile < ncta) { + if (full) { + set = 1; + } else { + for (int m = 0; m < M; ++m) set |= ht[(size_t)m * ncta + tile] >= thr[m]; + } + mask[tile] = (uint8_t)set; + } + if (!full && set) atomicAdd(&cnt, 1); + __syncthreads(); + if (threadIdx.x == 0) { + if (!full && cnt) atomicAdd(stats + 0, (unsigned long long)cnt); + if (blockIdx.x == 0) { + if (*on == 0) atomicAdd(stats + 4, 1ULL); + else if (full) atomicAdd(stats + 2, 1ULL); + else atomicAdd(stats + 1, 1ULL); + flags[2] = (*on != 0) && !full; // certified step (read by the check mode) + } + } +} + +// pico's coded-head GEMV (gemv_bf16x, mt 2, wn 1) on the masked CTAs; -inf for the others. Same body, template +// arguments and launch bounds as pico's k_gemv16 (RB 8) / k_gemv16_r16 (RB 16). +template +__device__ __forceinline__ void exact_cta(const uint8_t* __restrict__ mask, const __nv_bfloat16* __restrict__ x, int M, + const uint8_t* __restrict__ X, int N, int K, float* __restrict__ yf, int wk, + int* __restrict__ flags) { + if (blockIdx.x == 0 && threadIdx.x == 0) flags[1] = 0; // the screen's non-finite flag (select has read it) + if (!mask[blockIdx.x]) { + const int n_cta = blockIdx.x * kRowsCta; + for (int idx = threadIdx.x; idx < M * kRowsCta; idx += blockDim.x) + yf[(size_t)(idx / kRowsCta) * N + n_cta + idx % kRowsCta] = -INFINITY; + return; + } + dsk::gemv16_body(x, M, X, nullptr, N, K, N, yf, nullptr, nullptr, nullptr, 1, wk, + dsk::NormIn{}); +} + +__global__ void __launch_bounds__(512) k_exact8(const uint8_t* __restrict__ mask, const __nv_bfloat16* __restrict__ x, + int M, const uint8_t* __restrict__ X, int N, int K, + float* __restrict__ yf, int wk, int* __restrict__ flags) { + exact_cta(mask, x, M, X, N, K, yf, wk, flags); +} + +__global__ void __launch_bounds__(512, 1) k_exact16(const uint8_t* __restrict__ mask, const __nv_bfloat16* __restrict__ x, + int M, const uint8_t* __restrict__ X, int N, int K, + float* __restrict__ yf, int wk, int* __restrict__ flags) { + exact_cta(mask, x, M, X, N, K, yf, wk, flags); +} + +} // namespace cert + +namespace { + +void check_x(const torch::Tensor& x) { + TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::kBFloat16 && x.dim() == 2 && x.size(1) == cert::kK, + "inkling_cert: x must be CUDA bf16 [M, 2304]"); + TORCH_CHECK(x.size(0) >= 1 && x.size(0) <= 16, "inkling_cert: rows ", x.size(0), " not in [1, 16]"); + TORCH_CHECK(x.stride(1) == 1 && (x.size(0) == 1 || x.stride(0) == cert::kK), "inkling_cert: x rows not contiguous"); + TORCH_CHECK(reinterpret_cast(x.data_ptr()) % 16 == 0, "inkling_cert: x not 16-byte aligned"); +} + +void check_dev(const torch::Tensor& t, const torch::Tensor& like, at::ScalarType dt, int64_t numel, const char* what) { + TORCH_CHECK(t.is_cuda() && t.device() == like.device() && t.scalar_type() == dt && t.is_contiguous() && + t.numel() >= numel, + "inkling_cert: bad ", what); +} + +// screen + rowmax + select (the candidate mask for exact()) +void screen(const torch::Tensor& x, const torch::Tensor& q, const torch::Tensor& sc, const torch::Tensor& rt, + const torch::Tensor& nv, int64_t V, int64_t v_real, double cn, const torch::Tensor& lt, + const torch::Tensor& ht, const torch::Tensor& tm, const torch::Tensor& hm, const torch::Tensor& on, + const torch::Tensor& flags, const torch::Tensor& mask, const torch::Tensor& stats, double cap, + double two_e, double dmax, const torch::Tensor& sdbg, const torch::Tensor& bdbg) { + check_x(x); + const int64_t M = x.size(0), ncta = V / cert::kRowsCta; + TORCH_CHECK(V % cert::kRowsCta == 0 && v_real <= V && v_real > 0, "inkling_cert: V=", V, " v_real=", v_real); + check_dev(q, x, at::kByte, V * cert::kK * 3 / 4, "q"); + check_dev(sc, x, at::kHalf, cert::kGroups * V, "sc"); + check_dev(rt, x, at::kHalf, cert::kGroups * V, "rt"); + check_dev(nv, x, at::kFloat, V, "nv"); + check_dev(lt, x, at::kFloat, M * ncta, "lt"); + check_dev(ht, x, at::kFloat, M * ncta, "ht"); + check_dev(tm, x, at::kFloat, M, "tm"); + check_dev(hm, x, at::kFloat, M, "hm"); + check_dev(on, x, at::kInt, 1, "on"); + check_dev(flags, x, at::kInt, 4, "flags"); + check_dev(mask, x, at::kByte, ncta, "mask"); + check_dev(stats, x, at::kLong, 8, "stats"); + const c10::cuda::CUDAGuard guard(x.device()); + const auto st = at::cuda::getCurrentCUDAStream(); + const auto* xp = reinterpret_cast(x.data_ptr()); + const auto* scp = reinterpret_cast(sc.data_ptr()); + const auto* rtp = reinterpret_cast(rt.data_ptr()); + float* sd = nullptr; + float* bd = nullptr; + if (sdbg.numel() > 0) { + check_dev(sdbg, x, at::kFloat, M * V, "sdbg"); + check_dev(bdbg, x, at::kFloat, M * V, "bdbg"); + sd = sdbg.data_ptr(); + bd = bdbg.data_ptr(); + } + if (M <= 8) + cert::k_screen<8><<>>(xp, (int)M, q.data_ptr(), scp, rtp, + nv.data_ptr(), (int)V, (int)v_real, (float)cn, + lt.data_ptr(), ht.data_ptr(), (int)ncta, + flags.data_ptr(), on.data_ptr(), sd, bd); + else + cert::k_screen<16><<>>(xp, (int)M, q.data_ptr(), scp, rtp, + nv.data_ptr(), (int)V, (int)v_real, (float)cn, + lt.data_ptr(), ht.data_ptr(), (int)ncta, + flags.data_ptr(), on.data_ptr(), sd, bd); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + cert::k_rowmax<<>>(lt.data_ptr(), ht.data_ptr(), (int)ncta, tm.data_ptr(), + hm.data_ptr(), on.data_ptr()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + cert::k_select<<<(ncta + 255) / 256, 256, 0, st>>>(ht.data_ptr(), (int)ncta, (int)M, tm.data_ptr(), + hm.data_ptr(), on.data_ptr(), flags.data_ptr(), + mask.data_ptr(), reinterpret_cast(stats.data_ptr()), (float)cap, + (float)two_e, (float)dmax); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +// out[M, N] = pico's coded head GEMV on the masked CTAs, -inf elsewhere +void exact(const torch::Tensor& x, const torch::Tensor& packed, int64_t N, int64_t K, const torch::Tensor& mask, + const torch::Tensor& out, int64_t wk, const torch::Tensor& flags) { + check_x(x); + TORCH_CHECK(K == cert::kK && N % cert::kRowsCta == 0, "inkling_cert: exact N=", N, " K=", K); + TORCH_CHECK(wk >= 1 && wk <= 16 && wk <= K / 32, "inkling_cert: wk=", wk); + TORCH_CHECK(packed.is_cuda() && packed.scalar_type() == at::kByte && packed.is_contiguous(), "inkling_cert: packed"); + check_dev(mask, x, at::kByte, N / cert::kRowsCta, "mask"); + check_dev(flags, x, at::kInt, 4, "flags"); + TORCH_CHECK(out.is_cuda() && out.scalar_type() == at::kFloat && out.dim() == 2 && out.size(0) == x.size(0) && + out.size(1) == N && out.stride(1) == 1 && (out.size(0) == 1 || out.stride(0) == N), + "inkling_cert: out must be fp32 [M, N] with contiguous rows"); + const c10::cuda::CUDAGuard guard(x.device()); + const auto st = at::cuda::getCurrentCUDAStream(); + const int M = (int)x.size(0); + const auto* xp = reinterpret_cast(x.data_ptr()); + const int ncta = (int)(N / cert::kRowsCta); + if (M <= dsk::kLowRows) { + const size_t smem = (size_t)wk * dsk::kLowRows * cert::kRowsCta * sizeof(float); + cert::k_exact8<<>>(mask.data_ptr(), xp, M, + packed.data_ptr(), (int)N, (int)K, + out.data_ptr(), (int)wk, flags.data_ptr()); + } else { + const size_t smem = (size_t)wk * dsk::kMaxRows * cert::kRowsCta * sizeof(float); + cert::k_exact16<<>>(mask.data_ptr(), xp, M, + packed.data_ptr(), (int)N, (int)K, + out.data_ptr(), (int)wk, flags.data_ptr()); + } + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +template +void prepare_screen_wide() { + C10_CUDA_CHECK(cudaFuncSetAttribute(certwide::k_screen_wide, cudaFuncAttributeMaxDynamicSharedMemorySize, + Stages * MR * 16 * certwide::kRowBytes)); +} + +void prepare_certwide(int64_t device) { + const c10::cuda::CUDAGuard guard((c10::DeviceIndex)device); + prepare_screen_wide<4, 3>(); + prepare_screen_wide<8, 3>(); + prepare_screen_wide<12, 2>(); + prepare_screen_wide<12, 3>(); +} + +template +auto dispatch_screen_wide(int M, bool three_stages, Fn launch) { + using Three = std::integral_constant; + if (M <= 64) return launch(std::integral_constant{}, Three{}); + if (M <= 128) return launch(std::integral_constant{}, Three{}); + if (three_stages) return launch(std::integral_constant{}, Three{}); + return launch(std::integral_constant{}, std::integral_constant{}); +} + +std::tuple screen_wide_info(int64_t device, int M, bool three_stages) { + using namespace certwide; + TORCH_CHECK(M >= 17 && M <= kMaxM, "inkling_certwide: unsupported screen rows"); + const c10::cuda::CUDAGuard guard((c10::DeviceIndex)device); + return dispatch_screen_wide(M, three_stages, [](auto bucket, auto stages) { + constexpr int MR = decltype(bucket)::value, Stages = decltype(stages)::value; + constexpr int smem = Stages * MR * 16 * kRowBytes; + auto kernel = k_screen_wide; + cudaFuncAttributes attr{}; + int blocks = 0; + C10_CUDA_CHECK(cudaFuncGetAttributes(&attr, kernel)); + C10_CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&blocks, kernel, kThreads, smem)); + return std::make_tuple(attr.numRegs, attr.localSizeBytes, smem, blocks); + }); +} + +void select_wide(const torch::Tensor& lower, const torch::Tensor& upper, const torch::Tensor& threshold, + const torch::Tensor& state, const torch::Tensor& tiles, const torch::Tensor& groups, + int M, int ntiles, float cap, float two_e, float dmax, cudaStream_t st) { + using namespace certwide; + auto* sp = state.data_ptr(); + k_threshold<<>>(lower.data_ptr(), upper.data_ptr(), ntiles, + threshold.data_ptr(), sp, cap, two_e, dmax); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + const int capacity = tiles.numel(); + k_candidates<<<(ntiles + 255) / 256, 256, 0, st>>>(upper.data_ptr(), threshold.data_ptr(), M, + ntiles, sp, tiles.data_ptr(), groups.data_ptr(), capacity); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + k_finish<<<1, 1, 0, st>>>(sp, capacity, ntiles); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +void debug_select_wide(const torch::Tensor& lower, const torch::Tensor& upper, const torch::Tensor& threshold, + const torch::Tensor& state, const torch::Tensor& tiles, const torch::Tensor& groups, + double cap, double two_e, double dmax) { + TORCH_CHECK(lower.dim() == 2 && lower.size(0) > 0 && lower.size(0) <= certwide::kMaxM && + lower.size(1) > 0 && lower.size(1) <= INT32_MAX / 16 && lower.sizes() == upper.sizes() && + tiles.numel() > 0 && tiles.numel() <= lower.size(1), "inkling_certwide: bad debug maxima shape"); + const int M = lower.size(0), ntiles = lower.size(1); + check_dev(lower, lower, at::kFloat, lower.numel(), "lower"); + check_dev(upper, lower, at::kFloat, lower.numel(), "upper"); + check_dev(threshold, lower, at::kFloat, M, "threshold"); + check_dev(state, lower, at::kInt, 2, "state"); + check_dev(tiles, lower, at::kInt, tiles.numel(), "tiles"); + check_dev(groups, lower, at::kInt, tiles.numel(), "groups"); + const c10::cuda::CUDAGuard guard(lower.device()); + const auto st = at::cuda::getCurrentCUDAStream(); + C10_CUDA_CHECK(cudaMemsetAsync(state.data_ptr(), 0, 2 * sizeof(int), st)); + select_wide(lower, upper, threshold, state, tiles, groups, M, ntiles, cap, two_e, dmax, st); +} + +void screen_wide(const torch::Tensor& x, const torch::Tensor& q, const torch::Tensor& sc, + const torch::Tensor& radius, int64_t V, int64_t v_real, const torch::Tensor& norms, + const torch::Tensor& lower, const torch::Tensor& upper, const torch::Tensor& threshold, + const torch::Tensor& on, const torch::Tensor& state, const torch::Tensor& tiles, + const torch::Tensor& groups, const torch::Tensor& dbg_s, const torch::Tensor& dbg_lo, + const torch::Tensor& dbg_hi, double cap, double two_e, double dmax, bool three_stages) { + using namespace certwide; + TORCH_CHECK(x.dim() == 2 && x.size(0) >= 17 && x.size(0) <= kMaxM && x.size(1) == kK, + "inkling_certwide: x must be [17..192, 2304]"); + const int M = (int)x.size(0); + const int64_t ntiles = V / 16, capacity = tiles.numel(); + TORCH_CHECK(V > 0 && V <= INT32_MAX && V % 16 == 0 && v_real > 0 && v_real <= V && + capacity > 0 && capacity <= ntiles, "inkling_certwide: bad vocab or capacity"); + check_dev(x, x, at::kBFloat16, M * kK, "x"); + check_dev(q, x, at::kByte, V * kK * 3 / 4, "q"); + check_dev(sc, x, at::kHalf, kGroups * V, "sc"); + check_dev(radius, x, at::kFloat, V, "radius"); + check_dev(norms, x, at::kFloat, M, "norms"); + check_dev(lower, x, at::kFloat, M * ntiles, "lower"); + check_dev(upper, x, at::kFloat, M * ntiles, "upper"); + check_dev(threshold, x, at::kFloat, M, "threshold"); + check_dev(on, x, at::kInt, 1, "on"); + check_dev(state, x, at::kInt, 2, "state"); + check_dev(tiles, x, at::kInt, capacity, "tiles"); + check_dev(groups, x, at::kInt, capacity, "groups"); + TORCH_CHECK(reinterpret_cast(x.data_ptr()) % 16 == 0 && + reinterpret_cast(q.data_ptr()) % 8 == 0, "inkling_certwide: misaligned screen input"); + float* sd = nullptr; + float* ld = nullptr; + float* hd = nullptr; + if (dbg_s.numel() || dbg_lo.numel() || dbg_hi.numel()) { + check_dev(dbg_s, x, at::kFloat, M * V, "debug screen logits"); + check_dev(dbg_lo, x, at::kFloat, M * V, "debug lower endpoints"); + check_dev(dbg_hi, x, at::kFloat, M * V, "debug upper endpoints"); + TORCH_CHECK(reinterpret_cast(dbg_s.data_ptr()) % 8 == 0 && + reinterpret_cast(dbg_lo.data_ptr()) % 8 == 0 && + reinterpret_cast(dbg_hi.data_ptr()) % 8 == 0, + "inkling_certwide: misaligned float2 debug output"); + sd = dbg_s.data_ptr(); + ld = dbg_lo.data_ptr(); + hd = dbg_hi.data_ptr(); + } + const c10::cuda::CUDAGuard guard(x.device()); + const auto st = at::cuda::getCurrentCUDAStream(); + const auto* xp = reinterpret_cast(x.data_ptr()); + const auto* scp = reinterpret_cast(sc.data_ptr()); + auto* sp = state.data_ptr(); + C10_CUDA_CHECK(cudaMemsetAsync(sp, 0, 2 * sizeof(int), st)); + k_norm<<>>(xp, norms.data_ptr(), sp, on.data_ptr()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + auto launch = [&](auto bucket, auto stages) { + constexpr int MR = decltype(bucket)::value; + constexpr int Stages = decltype(stages)::value; + k_screen_wide<<<(V + kCols - 1) / kCols, kThreads, Stages * MR * 16 * kRowBytes, st>>>( + xp, q.data_ptr(), scp, radius.data_ptr(), norms.data_ptr(), M, (int)V, (int)v_real, + lower.data_ptr(), upper.data_ptr(), sp, sd, ld, hd); + }; + dispatch_screen_wide(M, three_stages, launch); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + select_wide(lower, upper, threshold, state, tiles, groups, M, (int)ntiles, cap, two_e, dmax, st); +} + +} // namespace + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.doc() = "inkling_cert: certified greedy LM-head argmax (6-bit screen + pico's exact head GEMV on candidates)"; + m.def("screen", &screen, "6-bit screen, row maxima and candidate mask"); + m.def("screen_wide", &screen_wide, "batched 6-bit screen and candidate compaction"); + m.def("screen_wide_info", &screen_wide_info, "registers, local bytes, dynamic shared bytes and resident blocks per SM"); + m.def("debug_select_wide", &debug_select_wide, "select candidates from supplied tile maxima"); + m.def("prepare_certwide", &prepare_certwide, "prepare batched screen kernels"); + m.def("exact", &exact, "pico's coded head GEMV on the masked CTAs, -inf elsewhere"); + m.attr("K") = cert::kK; + m.attr("GROUP") = cert::kGroup; + m.attr("ROWS_CTA") = cert::kRowsCta; +} diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/certwide_screen.cuh b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/certwide_screen.cuh new file mode 100644 index 0000000000000000000000000000000000000000..f5bdf9471ad96201bcb7823b43d94e8467c00ead --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/certwide_screen.cuh @@ -0,0 +1,256 @@ +#pragma once + +namespace certwide { + +using namespace screen6; + +constexpr int kMaxM = 192; +constexpr int kWarps = 8; // eight n8 warps, or four candidate tiles per CTA +constexpr int kCols = 8 * kWarps; +constexpr int kThreads = 32 * kWarps; +constexpr int kRowBytes = 2 * kStep; +constexpr float kMaxX = 0x1p20f; +constexpr float kAbsSlop = 0x1p-78f; + +enum Reason { kCertified, kUnsafe, kTooMany, kOff }; + +// One block per activation row. Sum squares before screening so each vocab CTA +// can use the same upper bound on ||x||. Infl covers the serial and tree sums. +__global__ void k_norm(const __nv_bfloat16* x, float* norms, int* state, const int* on) { + if (!*on) { + if (threadIdx.x == 0 && blockIdx.x == 0) state[0] = kOff; + return; + } + __shared__ float warp_sums[8]; + const auto* row = x + (size_t)blockIdx.x * kK; + float sum = 0.f; + for (int k = threadIdx.x; k < kK; k += blockDim.x) { + const float a = __bfloat162float(row[k]); + sum = fmaf(a, a, sum); + } + for (int d = 16; d; d >>= 1) sum += __shfl_down_sync(0xffffffffu, sum, d); + if ((threadIdx.x & 31) == 0) warp_sums[threadIdx.x >> 5] = sum; + __syncthreads(); + if (threadIdx.x < 32) { + sum = threadIdx.x < 8 ? warp_sums[threadIdx.x] : 0.f; + for (int d = 4; d; d >>= 1) sum += __shfl_down_sync(0xffffffffu, sum, d); + if (threadIdx.x == 0) { + const float norm = sqrtf(sum) * kInfl + 4.f * kXAbs; + norms[blockIdx.x] = norm; + if (!(norm <= kMaxX)) atomicOr(state, kUnsafe); + } + } +} + +__device__ __forceinline__ void copy_x(void* dst, const void* src, bool valid) { + asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" :: + "r"((uint32_t)__cvta_generic_to_shared(dst)), "l"(src), "r"(valid ? 16 : 0) : "memory"); +} + +// Stream one 64-vocab CTA of Q. Each step is loaded by one warp per n8 +// tile, decoded once in that warp, and used for every m16 fragment before +// advancing K. Shared stages hold only activations. +template +__global__ void __launch_bounds__(kThreads) k_screen_wide( + const __nv_bfloat16* x, const uint8_t* q, const uint16_t* sc, const float* radius, + const float* norms, int M, int V, int v_real, float* lower, float* upper, const int* state, + float* debug_s, float* debug_lo, float* debug_hi) { + if (state[0] != kCertified) return; + constexpr int kStage = MR * 16 * kRowBytes; + extern __shared__ __align__(16) uint8_t work[]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3; + const int nt = blockIdx.x * kWarps + warp, n = nt * 8 + 2 * t; + const int m16 = (M + 15) / 16; + const bool live_tile = nt < V / 8; + const uint8_t* qw = q + (size_t)(live_tile ? nt : 0) * kSteps * kTileBytes; + const float r0 = live_tile ? __ldg(radius + n) : 0.f; + const float r1 = live_tile ? __ldg(radius + n + 1) : 0.f; + + auto issue_x = [&](int step) { + auto* dst = work + (step % Stages) * kStage; + if (step < kSteps) { + for (int c = threadIdx.x; c < m16 * 16 * 8; c += kThreads) { + const int row = c / 8, ch = c % 8; + copy_x(dst + row * kRowBytes + (ch ^ ((row & 1) << 2)) * 16, + x + (size_t)(row < M ? row : 0) * kK + step * kStep + ch * 8, row < M); + } + } + asm volatile("cp.async.commit_group;" ::: "memory"); + }; + + float sum[MR][4] = {}; + issue_x(0); + if constexpr (Stages == 3) issue_x(1); + for (int group = 0; group < kGroups; ++group) { + const float s0 = live_tile ? half_to_float_u16(__ldg(sc + (size_t)group * V + n)) : 0.f; + const float s1 = live_tile ? half_to_float_u16(__ldg(sc + (size_t)group * V + n + 1)) : 0.f; + float partial[MR][4] = {}; + for (int u = 0; u < kStepsPerGroup; ++u) { + const int step = group * kStepsPerGroup + u; + const uint8_t* base = qw + step * kTileBytes; + const uint2 nib = live_tile ? dsk::ldg_stream64(base + 8 * lane) : make_uint2(0, 0); + const uint32_t high = live_tile ? dsk::ldg_stream32(base + 256 + 4 * lane) : 0; + asm volatile("cp.async.wait_group %0;" :: "n"(Stages - 2) : "memory"); + __syncthreads(); + // This stage was last read by the previous step, which has now + // finished in every warp of the CTA. + issue_x(step + Stages - 1); + if (live_tile) { + uint32_t b[8]; +#pragma unroll + for (int p = 0; p < 8; ++p) b[p] = six_pair(p < 4 ? nib.x : nib.y, high, p); + const uint8_t* xb = work + (step % Stages) * kStage; + const int off = ((2 * t) ^ ((g & 1) << 2)) * 16; +#pragma unroll + for (int j = 0; j < MR; ++j) { + if (j >= m16) break; + const auto* a = reinterpret_cast(xb + (j * 16 + g) * kRowBytes + off); + const auto* a2 = reinterpret_cast(xb + (j * 16 + g + 8) * kRowBytes + off); + const uint4 a0 = a[0], a1 = a[1], a20 = a2[0], a21 = a2[1]; + dsk::mma_bf16(partial[j], a0.x, a20.x, a0.y, a20.y, b[0], b[1]); + dsk::mma_bf16(partial[j], a0.z, a20.z, a0.w, a20.w, b[2], b[3]); + dsk::mma_bf16(partial[j], a1.x, a21.x, a1.y, a21.y, b[4], b[5]); + dsk::mma_bf16(partial[j], a1.z, a21.z, a1.w, a21.w, b[6], b[7]); + } + } + } +#pragma unroll + for (int j = 0; j < MR; ++j) { + sum[j][0] = fmaf(partial[j][0], s0, sum[j][0]); + sum[j][1] = fmaf(partial[j][1], s1, sum[j][1]); + sum[j][2] = fmaf(partial[j][2], s0, sum[j][2]); + sum[j][3] = fmaf(partial[j][3], s1, sum[j][3]); + } + } + asm volatile("cp.async.wait_group 0;" ::: "memory"); + __syncthreads(); + + // Reuse the activation storage for maxima. Four lanes handle an n8 row. + auto* lo8 = reinterpret_cast(work); + auto* hi8 = lo8 + kWarps * MR * 16; + auto epilogue = [&](int row, float s0, float s1) { + if (row >= M) return; + const float norm = __ldg(norms + row); + const float b0 = __fmul_ru(r0, norm), b1 = __fmul_ru(r1, norm); + const float e0 = (fabsf(s0) + b0) * 0x1p-20f + kAbsSlop; + const float e1 = (fabsf(s1) + b1) * 0x1p-20f + kAbsSlop; + const float lo0 = n < v_real ? s0 - b0 - e0 : -INFINITY; + const float lo1 = n + 1 < v_real ? s1 - b1 - e1 : -INFINITY; + const float hi0 = n < v_real ? s0 + b0 + e0 : -INFINITY; + const float hi1 = n + 1 < v_real ? s1 + b1 + e1 : -INFINITY; + if (debug_s && live_tile) { + reinterpret_cast(debug_s + (size_t)row * V + n)[0] = make_float2(s0, s1); + reinterpret_cast(debug_lo + (size_t)row * V + n)[0] = make_float2(lo0, lo1); + reinterpret_cast(debug_hi + (size_t)row * V + n)[0] = make_float2(hi0, hi1); + } + float lo = fmaxf(lo0, lo1), hi = fmaxf(hi0, hi1); + const unsigned lanes = 0xfu << (4 * g); + lo = fmaxf(lo, __shfl_xor_sync(lanes, lo, 1)); + lo = fmaxf(lo, __shfl_xor_sync(lanes, lo, 2)); + hi = fmaxf(hi, __shfl_xor_sync(lanes, hi, 1)); + hi = fmaxf(hi, __shfl_xor_sync(lanes, hi, 2)); + if (t == 0) { + lo8[warp * MR * 16 + row] = lo; + hi8[warp * MR * 16 + row] = hi; + } + }; +#pragma unroll + for (int j = 0; j < MR; ++j) { + epilogue(16 * j + g, sum[j][0], sum[j][1]); + epilogue(16 * j + g + 8, sum[j][2], sum[j][3]); + } + __syncthreads(); + for (int i = threadIdx.x; i < M * (kCols / 16); i += kThreads) { + const int row = i / (kCols / 16), pair = i % (kCols / 16); + const int tile = blockIdx.x * (kCols / 16) + pair; + if (tile >= V / 16) continue; + const int a = 2 * pair * MR * 16 + row, b = a + MR * 16; + const size_t addr = (size_t)row * (V / 16) + tile; + lower[addr] = fmaxf(lo8[a], lo8[b]); + upper[addr] = fmaxf(hi8[a], hi8[b]); + } +} + +// (1 - z / 2^20)^(2^20) <= exp(-z). Use downward rounding at each +// operation on this nonnegative base, including the final FP32 conversion. +__device__ float derivative_lower(float L, float cap) { + const double z = __ddiv_ru(2.0 * (double)L, (double)cap); + if (!(z <= 32.0)) return 0.f; + double lower = __dsub_rd(1.0, z * 0x1p-20); + for (int i = 0; i < 20; ++i) lower = __dmul_rd(lower, lower); + return __double2float_rd(lower); +} + +__global__ void k_threshold(const float* lower, const float* upper, int ntiles, + float* threshold, int* state, float cap, float two_e, float dmax) { + // An earlier range failure can also suppress this block. The candidate + // pass ignores every threshold whenever any row has forced fallback. + __shared__ int reason; + if (threadIdx.x == 0) reason = atomicAdd(state, 0); + __syncthreads(); + if (reason != kCertified) return; + __shared__ float los[8], his[8]; + const int row = blockIdx.x; + float lo = -INFINITY, hi = -INFINITY; + const size_t base = (size_t)row * ntiles; + for (int i = threadIdx.x; i < ntiles; i += blockDim.x) { + lo = fmaxf(lo, lower[base + i]); + hi = fmaxf(hi, upper[base + i]); + } + lo = dsk::warp_max(lo); + hi = dsk::warp_max(hi); + if ((threadIdx.x & 31) == 0) { + los[threadIdx.x >> 5] = lo; + his[threadIdx.x >> 5] = hi; + } + __syncthreads(); + if (threadIdx.x < 32) { + lo = dsk::warp_max(threadIdx.x < 8 ? los[threadIdx.x] : -INFINITY); + hi = dsk::warp_max(threadIdx.x < 8 ? his[threadIdx.x] : -INFINITY); + if (threadIdx.x == 0) { + const float L = fmaxf(__fadd_ru(fabsf(lo), dmax), fabsf(hi)); + const float slope = derivative_lower(L, cap); + const float delta = __fdiv_ru(2.f * two_e, slope); + if (!(isfinite(lo) && isfinite(hi) && delta <= dmax)) + atomicOr(state, kUnsafe); + threshold[row] = __fsub_rd(lo, delta); + } + } +} + +// Compact the union once. The mask retains the m16 groups in which at least +// one row selected the tile. One reservation per warp with live candidates. +__global__ void k_candidates(const float* upper, const float* threshold, int M, int ntiles, + int* state, int* tiles, int* groups, int capacity) { + if (state[0] != kCertified) return; + __shared__ float thr[kMaxM]; + if (threadIdx.x < M) thr[threadIdx.x] = threshold[threadIdx.x]; + __syncthreads(); + const int tile = blockIdx.x * blockDim.x + threadIdx.x; + unsigned group_mask = 0; + if (tile < ntiles) { + for (int m = 0; m < M; ++m) { + if (upper[(size_t)m * ntiles + tile] >= thr[m]) group_mask |= 1u << (m / 16); + } + } + const unsigned selected = __ballot_sync(0xffffffffu, group_mask != 0); + if (!selected) return; + int start = 0; + const int lane = threadIdx.x & 31; + if (lane == 0) start = atomicAdd(state + 1, __popc(selected)); + start = __shfl_sync(0xffffffffu, start, 0); + if (group_mask) { + const int slot = start + __popc(selected & ((1u << lane) - 1)); + if (slot < capacity) { + tiles[slot] = tile; + groups[slot] = group_mask; + } + } +} + +__global__ void k_finish(int* state, int capacity, int ntiles) { + if (state[0] == kCertified && (state[1] > capacity || state[1] == ntiles || state[1] == 0)) + state[0] = kTooMany; +} + +} // namespace certwide diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/screen6.cuh b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/screen6.cuh new file mode 100644 index 0000000000000000000000000000000000000000..4383778e28d4c59b4d9fad0f02e3af15d35255c8 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/csrc/screen6.cuh @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include +#include + +namespace screen6 { + +constexpr int kK = 2304; +constexpr int kStep = 64; +constexpr int kSteps = kK / kStep; +constexpr int kGroup = 192; +constexpr int kGroups = kK / kGroup; +constexpr int kStepsPerGroup = kGroup / kStep; +constexpr int kTileBytes = 384; +constexpr int kRowsCta = 16; +constexpr float kInfl = 1.0f + 1.0f / 65536.0f; +constexpr float kXAbs = 0x1p-58f; + +// q + 32 in [1, 63]. Form BF16(128 + q + 32) and subtract 160 exactly. +__device__ __forceinline__ uint32_t six_pair(uint32_t nib, uint32_t hi, int p) { + const uint32_t lo = (nib >> (4 * (p & 3))) & 0x000F000Fu; + const uint32_t h2 = ((hi >> (2 * p)) & 0x00030003u) << 4; + uint32_t v = lo | h2 | 0x43004300u; + const __nv_bfloat162 off = __floats2bfloat162_rn(160.f, 160.f); + __nv_bfloat162 r = __hsub2(*reinterpret_cast<__nv_bfloat162*>(&v), off); + return *reinterpret_cast(&r); +} + +__device__ __forceinline__ float half_to_float_u16(uint16_t h) { return __half2float(__ushort_as_half(h)); } + +} // namespace screen6 diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/dflash.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/dflash.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd292c94815a079f42b35be87f56104ca17b797 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/dflash.py @@ -0,0 +1,212 @@ +"""inkling_cert on the DFLASH worker (SPEC=dflash2): the certified head (<= 16 rows) on greedy verify steps. + +DSpark arms the certified head from its verify epilogue (patches.patch_verify). The DFLASH worker has no such +epilogue: its accept runs eagerly after the target verify graph, as `argmax(next_token_logits)` on all-greedy +batches whose logits nothing else reads (DFlashWorkerV2._can_skip_verify_logits: no grammar, no logprobs, no +logit adjustments, no selector sample). This module: + + DFlashWorkerV2.forward_batch_generation records (worker, batch) for the step (a context variable) + TpModelWorker.forward_batch_generation on that step's target verify (is_verify=True): cert.on = + batch_ok(...) and _can_skip_verify_logits(batch, sampling_info), written + on the stream before the replay, and reset to 0 right after it, so no + other graph replay (prefill, the next step) ever reads a stale 1 + +The narrow certified head (<= 16 rows: c1 / c2 with 8-row verify blocks) writes pico's exact logits on every +candidate tile and -inf elsewhere, so the stock softcap / mask / argmax over next_token_logits returns the same +token as the full head, bit for bit, also for ragged verify layouts. + +The wide head (17..INKLING_CERT_WIDE_MAX_ROWS rows) returns the certified IDs and writes the logits buffer only on a +fallback. Its IDs are handed to the accept instead of argmax(next_token_logits): + patches._wide_logits (capture) WIDE_IDS[(logits data_ptr, rows)] = that graph's ID buffer + DecodeCudaGraphRunner._process_output_after_replay (target verify, every replay) REPLAY["ids"] = the ID buffer + of the graph that just replayed, looked up by its (padded) output logits + DFlashWorkerV2._accept_block on an armed step whose replay produced IDs: target_predict = ids[:bs * block] + (the stock greedy branch; with the verify cap's cutoff, AcceptGreedy) +Not with SGLANG_RAGGED_VERIFY_MODE=compact (rows not request-major): refused at patch time. +""" + +import contextvars +import functools +import sys + +import torch + +WORKER = "sglang.srt.speculative.dflash_worker_v2" +TP_WORKER = "sglang.srt.managers.tp_worker" +_STEP = contextvars.ContextVar("inkling_cert_dflash_step", default=None) +COUNTS = {"steps": 0, "armed": 0, "live_gather": 0, "wide_injected": 0} +WIDE_IDS = {} # (data_ptr, rows) of a captured target-verify logits buffer -> [certified-ID buffers] +REPLAY = {"ids": None, "wide": False} # the replayed target-verify graph's IDs; wide: it contained the wide head +ACTIVE = {"dflash": False} # set when the DFLASH worker is patched (this process serves DFLASH) + + +def _state(): + from . import patches + + return patches + + +def note_wide_ids(out, ids): + """patches._wide_logits, at capture (the IDs also ride on the returned logits object as _inkling_certwide_ids).""" + WIDE_IDS.setdefault((out.data_ptr(), int(out.shape[0])), []).append(ids) + + +def _replayed_ids(logits): + """(ids, wide) for a target-verify replay's padded output logits. The graph's static output object carries the + attribute when the logits processor returned our view unchanged; otherwise the (buffer, rows) registry is used + if exactly one captured graph matches. A wide graph whose IDs cannot be identified is fatal (its logits buffer + is not written on certified steps).""" + if not isinstance(logits, torch.Tensor) or logits.dim() != 2: + return None, False + ids = getattr(logits, "_inkling_certwide_ids", None) + if ids is not None: + return ids, True + found = WIDE_IDS.get((logits.data_ptr(), int(logits.shape[0]))) + if not found: + return None, False + if len(found) == 1: + return found[0], True + return None, True + + +def patch_runner(mod): + """Record which captured wide-certified graph (if any) a target-verify replay ran.""" + p = _state() + cls = getattr(mod, "DecodeCudaGraphRunner", None) + p._need(cls, ["_process_output_after_replay"], "DecodeCudaGraphRunner") + orig = cls._process_output_after_replay + if getattr(orig, "_inkling_cert", False): + return + + @functools.wraps(orig) + def _process_output_after_replay(self, output, forward_batch): + output = orig(self, output, forward_batch) + if self.capture_forward_mode.is_target_verify() and not self.model_runner.is_draft_worker: + REPLAY["ids"], REPLAY["wide"] = _replayed_ids(getattr(output, "next_token_logits", None)) + return output + + _process_output_after_replay._inkling_cert = True + cls._process_output_after_replay = _process_output_after_replay + p.STATE["patched"].append("DecodeCudaGraphRunner._process_output_after_replay (DFLASH wide IDs)") + + +def dead_rows_to_anchor(x2, cert): + """Under the verify cap (inkling_vcap on DFLASH: STATE.src_index, live row r <=> src_index[r] == r, dead rows + -> their request's anchor row, identity on uncapped steps), give every dead row its anchor's hidden row before + the certified head, so dead rows (whose hidden states the cap's expert remap made meaningless) add no candidate + tiles of their own and cannot force a fallback. Captured into the verify graph; selected on the device: + with cert.on == 0 (the full head serves, e.g. sampled steps) the rows stay as they are, bit for bit. + Exact for every row an accept reads: live rows keep their own hidden rows, and the cap's cutoff never reads a + dead row's token (_accept_block's cutoff_verify_lens).""" + if not ACTIVE["dflash"]: + return x2 + vs = sys.modules.get("inkling_vcap.state") + st = getattr(vs, "STATE", None) + src = getattr(st, "src_index", None) + stride = int(getattr(st, "stride", 0) or 0) + m = x2.shape[0] + if (not isinstance(src, torch.Tensor) or not src.is_cuda or src.dtype != torch.int64 or src.numel() < m + or src.device != x2.device or stride <= 0 or m % stride): + return x2 + # src_index addresses the uniform request-major layout (stride rows per request); a compact ragged verify packs + # rows differently, so the gather is only used without it + try: + from sglang.srt.speculative.ragged_verify import ragged_verify_compact_enabled + + if ragged_verify_compact_enabled(): + return x2 + except ImportError: + return x2 + COUNTS["live_gather"] += 1 + gathered = x2.index_select(0, src[:m]) + return torch.where(cert.on.view(1, 1) != 0, gathered, x2) + + +def patch_worker(mod): + p = _state() + p._need(mod, ["DFlashWorkerV2"], WORKER) + cls = mod.DFlashWorkerV2 + p._need(cls, ["forward_batch_generation", "_can_skip_verify_logits"], f"{WORKER}.DFlashWorkerV2") + if getattr(cls.forward_batch_generation, "_inkling_cert", False): + return + p._need(cls, ["_accept_block"], f"{WORKER}.DFlashWorkerV2") + if p.STATE["cfg"].get("wide"): + from sglang.srt.speculative.ragged_verify import ragged_verify_compact_enabled + + if ragged_verify_compact_enabled(): + raise p.ops.CertFatal("inkling_cert: INKLING_CERT_WIDE with SGLANG_RAGGED_VERIFY_MODE=compact under DFLASH " + "(the certified IDs are request-major)") + fbg, accept = cls.forward_batch_generation, cls._accept_block + ACTIVE["dflash"] = True + + @functools.wraps(fbg) + def forward_batch_generation(self, batch, *args, **kwargs): + token = _STEP.set((self, batch, {"armed": False})) + try: + return fbg(self, batch, *args, **kwargs) + finally: + _STEP.reset(token) + + @functools.wraps(accept) + def _accept_block(self, *args, **kwargs): + ids = REPLAY["ids"] + step = _STEP.get() + armed = step is not None and step[2]["armed"] + if armed and REPLAY["wide"] and ids is None: + raise p.ops.CertFatal("inkling_cert: a wide-certified verify graph replayed but its IDs are ambiguous") + if (ids is not None and armed and kwargs.get("target_predict") is None + and kwargs.get("verify_shard") is None): + n = int(kwargs["bs"]) * int(self.block_size) + if ids.shape[0] < n: + raise p.ops.CertFatal("inkling_cert: certified IDs shorter than the verify block") + kwargs["target_predict"] = ids[:n] + COUNTS["wide_injected"] += 1 + return accept(self, *args, **kwargs) + + forward_batch_generation._inkling_cert = True + _accept_block._inkling_cert = True + cls.forward_batch_generation = forward_batch_generation + cls._accept_block = _accept_block + p.STATE["patched"].append("DFlashWorkerV2.forward_batch_generation/_accept_block") + + +def patch_tp_worker(mod): + p = _state() + p._need(mod, ["TpModelWorker"], TP_WORKER) + cls = mod.TpModelWorker + p._need(cls, ["forward_batch_generation"], f"{TP_WORKER}.TpModelWorker") + orig = cls.forward_batch_generation + if getattr(orig, "_inkling_cert_dflash", False): + return + + @functools.wraps(orig) + def forward_batch_generation(self, *args, **kwargs): + step = _STEP.get() + cert = p.STATE["cert"] + if step is None or cert is None or not kwargs.get("is_verify", False): + return orig(self, *args, **kwargs) + worker, batch, flags = step + si = getattr(batch, "sampling_info", None) + # mode "check" serves pico's full head and builds the certified result beside it (cert.run_check) + armed = bool(p.STATE["mode"] in ("1", "check") and p.STATE["disabled"] is None and p.batch_ok(batch, si) + and worker._can_skip_verify_logits(batch, si)) + COUNTS["steps"] += 1 + COUNTS["armed"] += armed + p.STATE["calls"] += 1 + every = p.STATE["cfg"]["log_every"] + if every and p.STATE["calls"] % every == 0: + p._report(cert) + flags["armed"] = armed + REPLAY["ids"], REPLAY["wide"] = None, False # set again only by a captured target-verify replay + cert.set_on(armed) + try: + out = orig(self, *args, **kwargs) + finally: + cert.set_on(0) # enqueued after the replay: no later replay reads a stale 1 + if not armed: + REPLAY["ids"], REPLAY["wide"] = None, False + return out + + forward_batch_generation._inkling_cert_dflash = True + cls.forward_batch_generation = forward_batch_generation + p.STATE["patched"].append("TpModelWorker.forward_batch_generation (DFLASH verify arming)") diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/ops.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba063556464d533fb82a712fdb9900aaa457e06 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/ops.py @@ -0,0 +1,84 @@ +"""Per-call device work of the certified head (graph-safe: fixed launches, no host sync, no allocation besides +torch.empty in the graph pool) and the start-up self-test. + +Cert.run(x2, out, on) launches screen (k_screen, k_rowmax, k_select) and exact (k_exact): out holds pico's FP32 +logits on the candidate tiles and -inf elsewhere when the device flag `on` is 1 and the step is certifiable, and +pico's logits everywhere otherwise (the masked kernel then runs every tile: the full head, the same bits). +""" + +import torch + +from . import cert_math + +K = cert_math.K +MAX_ROWS = 16 + + +class CertFatal(BaseException): + """A broken patch target or an impossible state (not caught by `except Exception`).""" + + +class Cert: + def __init__(self, ext, pack, tables, wk, device): + self.ext, self.pack, self.wk = ext, pack, int(wk) + self.V = int(pack.n) + if pack.k != K or self.V % 16: + raise CertFatal(f"inkling_cert: head [{pack.n}x{pack.k}] is not [16n x {K}]") + self.q, self.sc, self.rt, self.nv = tables["q"], tables["sc"], tables["rt"], tables["nv"] + self.eps = float(tables["eps"]) + self.ncta = self.V // 16 + f32, i32 = torch.float32, torch.int32 + self.lt = torch.empty((MAX_ROWS, self.ncta), dtype=f32, device=device) + self.ht = torch.empty((MAX_ROWS, self.ncta), dtype=f32, device=device) + self.tm = torch.empty((MAX_ROWS,), dtype=f32, device=device) + self.hm = torch.empty((MAX_ROWS,), dtype=f32, device=device) + self.on = torch.zeros((1,), dtype=i32, device=device) # host-written before each verify replay + self.off = torch.zeros((1,), dtype=i32, device=device) # eager calls: always the full head + self.force = torch.ones((1,), dtype=i32, device=device) # tests / self-test: certify if possible + self.flags = torch.zeros((4,), dtype=i32, device=device) + self.mask = torch.empty((self.ncta,), dtype=torch.uint8, device=device) + # stats: 0 candidate tiles on certified steps, 1 certified steps, 2 eligible but not certifiable, + # 3 (unused), 4 steps with on = 0, 5 rows checked, 6 token mismatches (check mode), 7 check steps + self.stats = torch.zeros((8,), dtype=torch.int64, device=device) + self.on_host = 0 + self._empty = torch.empty((0,), dtype=f32, device=device) + self.warm = set() + + @property + def screen_bytes(self): + return sum(t.numel() * t.element_size() for t in (self.q, self.sc, self.rt, self.nv)) + + def set_on(self, v): + v = 1 if v else 0 + if v != self.on_host: + self.on.fill_(v) + self.on_host = v + + def screen(self, x2, on, v_real, cap, sdbg=None, bdbg=None): + e = self._empty + self.ext.screen(x2, self.q, self.sc, self.rt, self.nv, self.V, int(v_real), cert_math.CN, self.lt, self.ht, + self.tm, self.hm, on, self.flags, self.mask, self.stats, float(cap), cert_math.TWO_E, + cert_math.DMAX, e if sdbg is None else sdbg, e if bdbg is None else bdbg) + + def run(self, x2, out, on, v_real, cap): + self.screen(x2, on, v_real, cap) + self.ext.exact(x2, self.pack.buf, self.V, K, self.mask, out, self.wk, self.flags) + return out + + def run_check(self, x2, out, on, v_real, cap, full_fn, softcap_fn, argmax_fn): + """Check mode: out gets pico's full head (what is served); the certified buffer is built beside it and both + go through the stock softcap, padding mask and argmax; mismatching rows of certified steps are counted.""" + c = torch.empty_like(out) + self.run(x2, c, on, v_real, cap) + full_fn(x2, out) + a = c.clone() + b = out.clone() + softcap_fn(a, cap) + softcap_fn(b, cap) + a[:, v_real:] = float("-inf") + b[:, v_real:] = float("-inf") + cert = self.flags[2:3].to(torch.int64) + self.stats[5:6].add_(cert * x2.shape[0]) + self.stats[6:7].add_((argmax_fn(a) != argmax_fn(b)).sum().view(1) * cert) + self.stats[7:8].add_(cert) + return out diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/patches.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/patches.py new file mode 100644 index 0000000000000000000000000000000000000000..44dfe932798702ed280635d74035d6d6de36eabc --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/patches.py @@ -0,0 +1,566 @@ +"""SGLang patch points of inkling_cert (README.md has the table and the argument). + + inkling2 Inkling2LogitsProcessor._get_logits: marks target-verify calls (the only ones the certificate takes) + Inkling2ForConditionalGeneration.post_load_weights: builds the 6-bit copy and the bound tables after + inkling_pico12 coded the head, then runs the start-up self-test + unquant sm12x_fp32_lm_head: target-verify calls that pico's `lmhead` takes (1-16 rows) go through the + certified head; everything else to the wrapped function (pico's, which wraps the stock one) + dspark_verify DsparkVerifyEpilogue.begin_static_step / begin_step: remember whether the step arms the in-graph + greedy accept; TargetVerifyExecutor.run_non_compact: writes the device flag `on` before the replay +""" + +import functools +import os +import sys +import time + +import torch + +from . import build, cert_math, ops, quant + +K = cert_math.K +UNQUANT = "sglang.srt.layers.quantization.unquant" +MODEL = "sglang.srt.models.inkling2" +VERIFY = "sglang.srt.speculative.dspark_components.dspark_verify" + +# Debug observers that read the verify logits after a folded greedy accept (dspark_observability.py) +OBSERVER_ENVS = ("SGLANG_DSPARK_STS_COLLECT_PATH", "SGLANG_DSPARK_DEBUG_CONFIDENCE_METRICS", + "SGLANG_DSPARK_DEBUG_DUMP", "SGLANG_DSPARK_ENABLE_SPS_RECORD") + +STATE = {"mode": "1", "cfg": None, "log": None, "patched": [], "cert": None, "disabled": None, "calls": 0} +CTX = {"lp": None} # the Inkling2LogitsProcessor of the target-verify call in progress +EXIT = os._exit + + +def _log(msg): + (STATE["log"] or (lambda m: sys.stderr.write(m + "\n")))(msg) + + +def _need(owner, names, where): + missing = [n for n in names if getattr(owner, n, None) is None] + if missing: + raise ops.CertFatal(f"inkling_cert: patch target {where} lacks {missing}") + + +def _guarded(fn): + @functools.wraps(fn) + def run(*args, **kwargs): + try: + return fn(*args, **kwargs) + except (KeyboardInterrupt, SystemExit): + raise + except BaseException as exc: # noqa: BLE001 + _log(f"FATAL: {exc!r}") + EXIT(78) + + return run + + +def _disable(why): + if STATE["disabled"] is None: + STATE["disabled"] = why + _log(f"disabled: {why}; the head runs unchanged") + + +def _pico(): + """inkling_pico12's patches / ops modules, or None when its `lmhead` lever is not armed.""" + pp = sys.modules.get("inkling_pico12.patches") + po = sys.modules.get("inkling_pico12.ops") + if pp is None or po is None or "lmhead" not in tuple(pp.STATE.get("levers", ())): + return None, None + return pp, po + + +# ---- inkling2: verify context and table build ------------------------------------------------------------------ + + +def make_get_logits(inner): + def _get_logits(self, hidden_states, lm_head, logits_metadata, *args, **kwargs): + mode = getattr(logits_metadata, "forward_mode", None) + verify = mode is not None and mode.is_target_verify() + if verify: + result = _wide_logits(self, hidden_states, lm_head, logits_metadata, *args, **kwargs) + if result is not None: + return result + prev = CTX["lp"] + CTX["lp"] = self if verify else None + try: + return inner(self, hidden_states, lm_head, logits_metadata, *args, **kwargs) + finally: + CTX["lp"] = prev + + _get_logits.__wrapped__ = inner + _get_logits._inkling_cert = True + return _get_logits + + +def _wide_modules(): + return sys.modules.get("inkling_wide.patches"), sys.modules.get("inkling_wide.ops") + + +def _wide_logits(lp, x, head, meta, embedding_bias=None, use_logits_buffer=True): + cert = STATE["cert"] + wide = getattr(cert, "wide", None) + if (wide is None or STATE["disabled"] is not None or STATE["mode"] != "1" + or not x.is_cuda or not torch.cuda.is_current_stream_capturing()): + return None + from . import certwide + + wp, wo = _wide_modules() + weight = getattr(head, "weight", None) + entry = wide.entry + m = wo.rows_of(x) + if (not certwide.MIN_ROWS <= m <= min(certwide.MAX_ROWS, STATE["cfg"].get("wide_max_rows", certwide.MAX_ROWS)) + or x.dim() != 2 + or not isinstance(weight, torch.Tensor) or wp.HEADS.get(weight.data_ptr()) is not entry + or tuple(weight.shape) != (entry.n, entry.k) or not wo.eligible(x, entry) + or wo.choose_split(entry.n, entry.k, m, entry.kind) != 1): + return None + if (embedding_bias is not None or not getattr(lp, "use_fp32_lm_head", False) + or getattr(lp, "shard_softcap", None) != cert_math.CAP + or getattr(lp, "logit_scale", None) is not None + or getattr(lp, "final_logit_softcapping", None) is not None + or getattr(lp, "do_tensor_parallel_all_gather", False) + or getattr(lp, "do_tensor_parallel_all_gather_dp_attn", False) + or getattr(lp, "vocab_size", None) != entry.n + or getattr(meta, "extend_return_logprob", False) + or hasattr(head, "set_lora")): + return None + from sglang.srt.layers.logits_processor import should_apply_lm_head_quant_method + + if should_apply_lm_head_quant_method(head, getattr(head, "quant_method", None)): + return None + v_real = int(lp.config.vocab_size) + if not 0 < v_real <= entry.n: + return None + out = meta.next_token_logits_buffer if use_logits_buffer else None + # The stock implementation discards a buffer with a different shape. + if out is not None and tuple(out.shape) != (m, entry.n): + out = None + if out is None: + out = torch.empty((m, entry.n), dtype=torch.float32, device=x.device) + if (not wo.out_ok(out, m, entry, torch.float32, x.device) or out.data_ptr() % 32 + or not out.is_contiguous()): + return None + # The tensor is the graph's existing fallback buffer. Its attribute is + # consumed at capture by the folded accept, which records the ID pointer. + out = out.view_as(out) # keep the attribute off the graph's shared buffer object + out._inkling_certwide_ids = wide.run(wo.as_rows(x, entry.k), out, cert.on, v_real, wo.SET) + from . import dflash + + dflash.note_wide_ids(out, out._inkling_certwide_ids) # DFLASH: the eager accept looks them up after replay + return out + + +def _prepare_wide(cert, w, lp, tables): + from . import certwide + + wp, wo = _wide_modules() + entry = wp.HEADS.get(w.data_ptr()) if wp is not None else None + if entry is None or entry.fmt != wo.BF16X or entry.pack is not cert.pack: + raise ops.CertFatal("inkling_certwide: needs the wide head registered with pico's packed weights") + if wo.choose_split(entry.n, entry.k, certwide.MAX_ROWS, entry.kind) != 1: + raise ops.CertFatal("inkling_certwide: needs the unsplit packed wide head") + if getattr(cert, "wide", None) is None: + cert.wide = certwide.CertWide(cert.ext, wo.EXT, entry, tables) + else: + cert.wide.refresh(entry, tables) + + cert.wide.counting = False # the self-tests below are not served steps + with torch.inference_mode(): + # Warm the CUDA/Triton paths before capture. Use peaked BF16 rows so + # the sparse arithmetic and the forced full fallback are both checked. + for m in (17, 33, 64, 96, 128, 192): + x = (w[:m].float() * 60).to(torch.bfloat16) + out = torch.empty((m, entry.n), dtype=torch.float32, device=w.device) + ref = torch.empty_like(out) + wo.gemm(x, entry, ref, m) + v_real = int(lp.config.vocab_size) + expected = _softcap_argmax(ref, v_real) + for on in (cert.force, cert.off): + ids = cert.wide.run(x, out, on, v_real, wo.SET) + if not torch.equal(ids, expected): + raise ops.CertFatal(f"inkling_certwide: M={m} self-test token mismatch") + if on is cert.off and not torch.equal(out.view(torch.int32), ref.view(torch.int32)): + raise ops.CertFatal(f"inkling_certwide: M={m} fallback logit mismatch") + cert.wide.counting = True + if STATE["cfg"].get("wide_stats") and cert.wide.stats is None: # once: graphs capture the counter address + cert.wide.enable_stats() + _log(f"wide certified packed head armed (17–{STATE['cfg'].get('wide_max_rows', certwide.MAX_ROWS)} rows, " + f"compact capacity {cert.wide.capacity} tiles{', outcome stats on' if cert.wide.stats is not None else ''})") + + +def prepare(model): + if STATE["mode"] == "0": + return + for env in OBSERVER_ENVS: + if os.environ.get(env, "").strip() not in ("", "0", "false", "False"): + _disable(f"{env} is set (that observer reads the verify logits)") + return + pp, po = _pico() + if pp is None: + raise ops.CertFatal("inkling_cert: needs INKLING_PICO12 with `lmhead` (pico's GEMV is the exact pass)") + lm_head = getattr(getattr(model, "llm", None), "lm_head", None) + w = getattr(lm_head, "weight", None) + pack = pp.HEADS.get(w.data_ptr()) if isinstance(w, torch.Tensor) else None + if pack is None: + raise ops.CertFatal("inkling_cert: inkling_pico12 has not coded the head (hook order: pico12 must come first)") + try: + from sglang.srt.distributed import get_tensor_model_parallel_world_size + + tp = get_tensor_model_parallel_world_size() + except Exception: # noqa: BLE001 + tp = 1 + if tp != 1: + _disable(f"tensor parallel size {tp} (TP1 only)") + return + unq = sys.modules.get(UNQUANT) + if unq is None or not getattr(unq.sm12x_fp32_lm_head, "_inkling_cert", False): + raise ops.CertFatal("inkling_cert: unquant.sm12x_fp32_lm_head is not ours (another overlay wrapped it after us)") + t0 = time.monotonic() + ext = build.load(STATE["cfg"]["cache_dir"]) + t_ext = time.monotonic() - t0 + old = STATE["cert"] + _require_wide_replay_stream() + tables = quant.build_tables(w.data) + if old is not None: # a reload: refresh in place (captured graphs hold these pointers) + for name in ("q", "sc", "rt", "nv"): + getattr(old, name).copy_(tables[name]) + old.pack = pack + cert = old + else: + cert = ops.Cert(ext, pack, tables, po.SET.wk, w.device) + lp = getattr(getattr(model, "llm", None), "logits_processor", None) + if STATE["cfg"].get("wide"): + _prepare_wide(cert, w, lp, tables) + del tables + if torch.cuda.is_available(): + torch.cuda.empty_cache() + selftest(cert, po, v_real=int(getattr(getattr(lp, "config", None), "vocab_size", 0) or 0) or None) + STATE["cert"] = cert + info = build.INFO + _log(f"active (mode {STATE['mode']}): 6-bit screen of the [{cert.V}x{K}] head, {cert.screen_bytes / 1e6:.1f} MB " + f"read per certified step (pico's coded head: {pack.nbytes / 1e6:.1f} MB), eps {cert.eps * 100:.2f} %; " + f"patched {', '.join(STATE['patched'])}; ext {'reused' if info.get('cached') else 'built'} in {t_ext:.1f} s; " + f"tables {time.monotonic() - t0 - t_ext:.1f} s; wk={cert.wk}") + + +@torch.inference_mode() +def selftest(cert, po, v_real=None, n=4): + """Start-up check on random rows (M = 8 and 16): the not-certified path equals pico's full head bit for bit, + the certified path gives the full head's softcapped argmax. Also loads every kernel before graph capture.""" + dev = cert.q.device + g = torch.Generator(device=dev) + g.manual_seed(1234) + v_real = v_real or cert.V + for m in (8, 16): + for i in range(n): + x = (torch.randn((m, K), generator=g, device=dev) * (1.0 + i)).to(torch.bfloat16) + ref = torch.empty((m, cert.V), dtype=torch.float32, device=dev) + po.gemv(x, cert.pack, ref) + a = torch.empty_like(ref) + cert.run(x, a, cert.off, v_real, cert_math.CAP) + if not torch.equal(a.view(torch.int32), ref.view(torch.int32)): + raise ops.CertFatal(f"inkling_cert: self-test M={m}: the full fallback differs from pico's head") + b = torch.empty_like(ref) + cert.run(x, b, cert.force, v_real, cert_math.CAP) + ta = _softcap_argmax(b, v_real) + tb = _softcap_argmax(ref.clone(), v_real) + if not torch.equal(ta, tb): + raise ops.CertFatal(f"inkling_cert: self-test M={m}: certified argmax differs from the full head") + cert.stats.zero_() + torch.cuda.synchronize() + + +def _softcap_argmax(logits, v_real, cap=cert_math.CAP): + sc, am = _stock_fns() + sc(logits, cap) + logits[:, v_real:] = float("-inf") + return am(logits) + + +_FNS = [] + + +def _stock_fns(): + if not _FNS: + from sglang.kernels.ops.activation.softcap import softcap_inplace_logits + from sglang.kernels.ops.sampling import argmax as sampling_argmax + + _FNS.extend([softcap_inplace_logits, sampling_argmax]) + return _FNS[0], _FNS[1] + + +def patch_model(mod): + _need(mod, ["Inkling2LogitsProcessor", "Inkling2ForConditionalGeneration"], MODEL) + lp_cls = mod.Inkling2LogitsProcessor + _need(lp_cls, ["_get_logits", "_compute_lm_head"], f"{MODEL}.Inkling2LogitsProcessor") + if not getattr(lp_cls._get_logits, "_inkling_cert", False): + lp_cls._get_logits = make_get_logits(lp_cls._get_logits) + STATE["patched"].append("Inkling2LogitsProcessor._get_logits") + cls = mod.Inkling2ForConditionalGeneration + _need(cls, ["post_load_weights"], f"{MODEL}.Inkling2ForConditionalGeneration") + orig = cls.post_load_weights + if getattr(orig, "_inkling_cert", False): + return + + @functools.wraps(orig) + def post_load_weights(self, *args, **kwargs): + result = orig(self, *args, **kwargs) # inkling_pico12 (if armed before us) codes the head in here + _guarded(prepare)(self) + return result + + post_load_weights._inkling_cert = True + cls.post_load_weights = post_load_weights + STATE["patched"].append("Inkling2ForConditionalGeneration.post_load_weights") + + +# ---- unquant: the head --------------------------------------------------------------------------------------- + + +def _eligible(lp, x, weight, out, cert): + """Our call iff pico's `lmhead` would take it (the reference bits are pico's) and the processor is as assumed.""" + pp, po = _pico() + if pp is None or cert is None: + return None + pack = pp.HEADS.get(weight.data_ptr()) if isinstance(weight, torch.Tensor) else None + if pack is None or pack is not cert.pack or tuple(weight.shape) != (pack.n, pack.k): + return None + m = po.rows_of(x) + if not (1 <= m <= ops.MAX_ROWS) or not po.eligible(x, pack): + return None + if out is not None and not po.out_ok(out, m, pack, torch.float32, x.device): + return None + cap = getattr(lp, "shard_softcap", None) + if cap is None or float(cap) != cert_math.CAP or getattr(lp, "logit_scale", None) is not None: + _disable(f"logits processor softcap {cap!r} / logit_scale {getattr(lp, 'logit_scale', None)!r} not as assumed") + return None + if getattr(lp, "do_tensor_parallel_all_gather", False) or getattr(lp, "do_tensor_parallel_all_gather_dp_attn", False): + _disable("logits gather across ranks") + return None + v_real = int(getattr(getattr(lp, "config", None), "vocab_size", 0) or 0) + if not 0 < v_real <= pack.n: + _disable(f"vocab_size {v_real} not in (0, {pack.n}]") + return None + return po, pack, m, v_real + + +def make_lm_head(inner): + def sm12x_fp32_lm_head(x, weight, out): + lp = CTX["lp"] + cert = STATE["cert"] + if lp is None or cert is None or STATE["disabled"] is not None or STATE["mode"] == "0": + return inner(x, weight, out) + got = _eligible(lp, x, weight, out, cert) + if got is None: + return inner(x, weight, out) + po, pack, m, v_real = got + capturing = x.is_cuda and torch.cuda.is_current_stream_capturing() + if not capturing: + # eager target verify (warm-up, or a batch without a graph): pico's full head; the first call per row + # bucket goes through the kernels (full fallback, the same bits) so every launch is loaded before capture + bucket = 8 if m <= 8 else 16 + if bucket in cert.warm: + return inner(x, weight, out) + cert.warm.add(bucket) + lead = x.shape[:-1] + x2 = po.as_rows(x, K) + if out is None: + out = torch.empty((m, pack.n), dtype=torch.float32, device=x.device) + on = cert.on if capturing else cert.off + if capturing: + from . import dflash + + x2 = dflash.dead_rows_to_anchor(x2, cert) # DFLASH + verify cap only; identity otherwise + if STATE["mode"] == "check": + sc, am = _stock_fns() + cert.run_check(x2, out, on, v_real, cert_math.CAP, lambda xx, oo: po.gemv(xx, pack, oo), sc, am) + else: + cert.run(x2, out, on, v_real, cert_math.CAP) + return out.view(*lead, pack.n) + + sm12x_fp32_lm_head.__wrapped__ = inner + sm12x_fp32_lm_head._inkling_cert = True + # keep pico's marker visible so that its own hook (if it runs again) does not wrap a second time + sm12x_fp32_lm_head._pico12 = getattr(inner, "_pico12", False) or _over_pico(inner) + sm12x_fp32_lm_head._wide = getattr(inner, "_wide", False) # inkling_wide's hook must not wrap again + return sm12x_fp32_lm_head + + +def _over_pico(fn): + """True if fn is pico12's head function, or inkling_wide's wrapper directly over it (wide takes only + 17..256 rows; every call cert serves or falls back on has <= 16 rows and reaches pico's function).""" + if getattr(fn, "_pico12", False): + return True + return bool(getattr(fn, "_wide", False)) and getattr(getattr(fn, "__wrapped__", None), "_pico12", False) + + +def patch_unquant(mod): + _need(mod, ["sm12x_fp32_lm_head", "sm12x_fp32_lm_head_applies"], UNQUANT) + if getattr(mod.sm12x_fp32_lm_head, "_inkling_cert", False): + return + if not _over_pico(mod.sm12x_fp32_lm_head): + raise ops.CertFatal("inkling_cert: unquant.sm12x_fp32_lm_head is not inkling_pico12's (arm INKLING_PICO12 with " + "lmhead, before INKLING_CERT_HEAD)") + mod.sm12x_fp32_lm_head = make_lm_head(mod.sm12x_fp32_lm_head) + STATE["patched"].append("unquant.sm12x_fp32_lm_head (outside inkling_pico12)") + + +# ---- dspark_verify: the per-step device flag ------------------------------------------------------------------- + + +def _sampling_ok(si): + if si is None: + return True + return (bool(getattr(si, "is_all_greedy", False)) and not getattr(si, "has_watermark_candidates", False) + and getattr(si, "sampling_mask_batch_indices", None) is None) + + +def batch_ok(batch, sampling_info): + """Host-side conditions beyond the epilogue's own arming (fold_eligible: all greedy, no logit adjustments, no + grammar): nothing after the folded accept may read the verify logits. Both the sampling info the worker passes + and the batch's own are checked (simulated acceptance can pass None while the batch samples).""" + if getattr(batch, "return_logprob", False) or getattr(batch, "has_grammar", False): + return False + return _sampling_ok(sampling_info) and _sampling_ok(getattr(batch, "sampling_info", None)) + + +def _patch_wide_accept(mod): + _need(mod, ["AcceptGreedy", "sampling_argmax"], VERIFY) + original_argmax = mod.sampling_argmax + original_accept = mod.AcceptGreedy + + def sampling_argmax(logits): + ids = getattr(logits, "_inkling_certwide_ids", None) + return original_argmax(logits) if ids is None else ids + + class AcceptGreedy(original_accept): + @classmethod + def execute(cls, *args, **kwargs): + logits = kwargs.get("target_logits") + ids = getattr(logits, "_inkling_certwide_ids", None) + if ids is not None and kwargs.get("target_predict") is None: + kwargs["target_predict"] = ids + return original_accept.execute(*args, **kwargs) + + # Both the fused static tail and the ordinary accept (also used by vcap) + # get their predictions from the same capture output tensor. + mod.sampling_argmax = sampling_argmax + mod.AcceptGreedy = AcceptGreedy + + +def _require_wide_replay_stream(): + wide = getattr(STATE["cert"], "wide", None) + if wide is not None: + wide.require_replay_stream() + + +def patch_graph_runner(mod): + cls = mod.DecodeCudaGraphRunner + orig = cls.execute + if getattr(orig, "_inkling_certwide", False): + return + + @functools.wraps(orig) + def execute(self, *args, **kwargs): + if self.capture_forward_mode.is_target_verify() and not self.model_runner.is_draft_worker: + _require_wide_replay_stream() + return orig(self, *args, **kwargs) + + execute._inkling_certwide = True + cls.execute = execute + STATE["patched"].append("DecodeCudaGraphRunner.execute") + from . import dflash + + dflash.patch_runner(mod) + + +def patch_verify(mod): + _need(mod, ["DsparkVerifyEpilogue", "TargetVerifyExecutor"], VERIFY) + ep = mod.DsparkVerifyEpilogue + ex = mod.TargetVerifyExecutor + _need(ep, ["begin_static_step", "begin_step"], f"{VERIFY}.DsparkVerifyEpilogue") + _need(ex, ["run_non_compact"], f"{VERIFY}.TargetVerifyExecutor") + if getattr(ex.run_non_compact, "_inkling_cert", False): + return + if STATE["cfg"].get("wide"): + _patch_wide_accept(mod) + b_static, b_step, run = ep.begin_static_step, ep.begin_step, ex.run_non_compact + + @functools.wraps(b_static) + def begin_static_step(self, bs, armed): + _require_wide_replay_stream() + self.__dict__["_inkling_cert_armed"] = bool(armed) + return b_static(self, bs, armed) + + @functools.wraps(b_step) + def begin_step(self, verify_lens, armed): + _require_wide_replay_stream() + self.__dict__["_inkling_cert_armed"] = False + cert = STATE["cert"] + if cert is not None: + cert.set_on(0) + return b_step(self, verify_lens, armed) + + @functools.wraps(run) + def run_non_compact(self, *, batch, sampling_info, **kwargs): + cert = STATE["cert"] + if cert is not None: + epi = getattr(self, "verify_epilogue", None) + armed = epi is not None and bool(epi.__dict__.get("_inkling_cert_armed", False)) + # SGLANG_SIMULATE_ACC_LEN (a benchmark mode; its folded bonus may be sampled): never certify + simulated = getattr(self, "_simulated_correct_len", None) is not None or bool(getattr(epi, "simulate_fold", False)) + _require_wide_replay_stream() + cert.set_on(armed and not simulated and STATE["disabled"] is None and batch_ok(batch, sampling_info)) + STATE["calls"] += 1 + every = STATE["cfg"]["log_every"] + if every and STATE["calls"] % every == 0: + _report(cert) + return run(self, batch=batch, sampling_info=sampling_info, **kwargs) + + for f in (begin_static_step, begin_step, run_non_compact): + f._inkling_cert = True + ep.begin_static_step, ep.begin_step, ex.run_non_compact = begin_static_step, begin_step, run_non_compact + STATE["patched"].append("DsparkVerifyEpilogue.begin_static_step/begin_step, TargetVerifyExecutor.run_non_compact") + + +_PINNED = {} + + +def _report(cert): + """Print the counters copied at the previous report (no sync), then start the next copy.""" + prev = _PINNED.get("buf") + if prev is not None and _PINNED.get("ev") is not None and _PINNED["ev"].query(): + s = prev.tolist() + cert_steps = max(s[1], 1) + line = (f"steps certified {s[1]} (tiles/step {s[0] / cert_steps:.1f}), not certifiable {s[2]}, " + f"not eligible {s[4]}") + if STATE["mode"] == "check": + line += f"; check: {s[7]} steps, {s[5]} rows, mismatches {s[6]}" + _log(line) + wprev = _PINNED.get("wbuf") + if wprev is not None: + _log("wide outcomes " + getattr(cert, "wide").describe_stats(wprev)) + if prev is None: + _PINNED["buf"] = torch.zeros((8,), dtype=torch.int64, pin_memory=True) + wide = getattr(cert, "wide", None) + if wide is not None and wide.stats is not None: + _PINNED["wbuf"] = torch.zeros(wide.stats.shape, dtype=torch.int64, pin_memory=True) + _PINNED["buf"].copy_(cert.stats, non_blocking=True) + if _PINNED.get("wbuf") is not None: + _PINNED["wbuf"].copy_(cert.wide.stats, non_blocking=True) + ev = torch.cuda.Event() + ev.record() + _PINNED["ev"] = ev + + +def patch_dflash_worker(mod): + from . import dflash + + dflash.patch_worker(mod) + + +def patch_dflash_tp_worker(mod): + from . import dflash + + dflash.patch_tp_worker(mod) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/quant.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/quant.py new file mode 100644 index 0000000000000000000000000000000000000000..dd9ae9a362906425a78d2657eeca3fa81353d6d0 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/quant.py @@ -0,0 +1,124 @@ +"""The screening copy of the LM head and its bound tables (load time; torch, on the weight's device). + +Format (cert_ext.cu reads exactly this): + q int in [-31, 31], one FP16 scale per (row, 192-value group): D[v, k] = sc[g, v] * q[v, k] (real numbers) + Q uint8 [V/8 tiles][36 steps][384 B]: per (8-row tile, 64-value step), lane l = 4 * row + t (t = 0..3) holds the + row's values 16t .. 16t + 15 as u = q + 32 (0..63): bytes [8l, 8l + 8) the low nibbles, bytes [256 + 4l, + 4) + the high two bits. Nibble word h (h = 0, 1; bytes 8l + 4h ..): nibble slot j (bits 4j) = value 2(4h + j), slot + j + 4 = value 2(4h + j) + 1. High word: slot p (bits 2p) = value 2p, slot p + 8 = value 2p + 1 (p = 0..7). + sc fp16 [12][V] scales, rounded up so that 31 * sc >= the group's max |w| + rt fp16 [12][V] ||W_vg - D_vg||_2, computed in float64, rounded up + nv fp32 [V] max(||W_v||, ||D_v||), float64, rounded up +""" + +import torch + +K = 2304 +GROUP = 192 +NGROUPS = K // GROUP +STEP = 64 +STEPS = K // STEP +QMAX = 31 + + +def round_up_f32(x64): + """float64 (>= 0 or inf) -> the smallest fp32 >= x.""" + f = x64.float() + bump = f.double() < x64 + return torch.where(bump, (f.view(torch.int32) + 1).view(torch.float32), f) + + +def round_up_f16(x64): + """float64 (>= 0) -> the smallest fp16 >= x (inf above the fp16 range).""" + h = x64.half() + bump = h.double() < x64 + return torch.where(bump, (h.view(torch.int16) + 1).view(torch.float16), h) + + +def quantize_rows(w): + """w [r, K] (bf16 / fp32) -> (q int8 [r, K], sc fp16 [r, NGROUPS], D float64 [r, K]).""" + r = w.shape[0] + w64 = w.double().view(r, NGROUPS, GROUP) + amax = w64.abs().amax(-1) + sc = round_up_f16(amax / QMAX) + s64 = sc.double() + safe = torch.where(s64 > 0, s64, torch.ones_like(s64)) + q = torch.round(w64 / safe[..., None]).clamp(-QMAX, QMAX) + q = torch.where(s64[..., None] > 0, q, torch.zeros_like(q)) + d = q * s64[..., None] + return q.view(r, K).to(torch.int8), sc, d.view(r, K) + + +def pack6(q): + """q int8 [V, K] (V % 8 == 0) -> uint8 [V/8 * STEPS * 384] in the layout above.""" + V = q.shape[0] + u = (q.to(torch.int32) + 32).view(V // 8, 8, STEPS, 4, 16) # tile, row g, step, t, value j + u = u.permute(0, 2, 1, 3, 4).reshape(V // 8, STEPS, 32, 16) # tile, step, lane = 4g + t, j + lo = u & 0xF + hi = (u >> 4) & 0x3 + nib = torch.zeros((V // 8, STEPS, 32, 2), dtype=torch.int64, device=q.device) + for h in range(2): + for j in range(4): + p = 4 * h + j + nib[..., h] |= lo[..., 2 * p].long() << (4 * j) + nib[..., h] |= lo[..., 2 * p + 1].long() << (16 + 4 * j) + hw = torch.zeros((V // 8, STEPS, 32), dtype=torch.int64, device=q.device) + for p in range(8): + hw |= hi[..., 2 * p].long() << (2 * p) + hw |= hi[..., 2 * p + 1].long() << (16 + 2 * p) + nib_b = torch.stack([(nib >> (8 * b)) & 0xFF for b in range(4)], -1).view(V // 8, STEPS, 256) + hw_b = torch.stack([(hw >> (8 * b)) & 0xFF for b in range(4)], -1).view(V // 8, STEPS, 128) + return torch.cat([nib_b, hw_b], -1).to(torch.uint8).reshape(-1) + + +def unpack6(packed, V): + """Inverse of pack6 by the kernel's own extraction rule (tests): -> q int8 [V, K].""" + b = packed.view(V // 8, STEPS, 384).long() + nib = b[..., :256].view(V // 8, STEPS, 32, 2, 4) + nibw = (nib << (8 * torch.arange(4, device=b.device))).sum(-1) # [.., 32, 2] u32 words + hiw = (b[..., 256:].view(V // 8, STEPS, 32, 4) << (8 * torch.arange(4, device=b.device))).sum(-1) + vals = torch.empty((V // 8, STEPS, 32, 16), dtype=torch.int64, device=b.device) + for p in range(8): + w = nibw[..., p // 4] + lo = (w >> (4 * (p % 4))) & 0x000F000F + h2 = ((hiw >> (2 * p)) & 0x00030003) << 4 + v = lo | h2 + vals[..., 2 * p] = v & 0xFFFF + vals[..., 2 * p + 1] = v >> 16 + q = vals - 32 + return q.view(V // 8, STEPS, 8, 4, 16).permute(0, 2, 1, 3, 4).reshape(V, K).to(torch.int8) + + +@torch.inference_mode() +def build_tables(weight, chunk=4096): + """weight bf16 [V, K] -> dict(q=packed uint8, sc, rt, nv, eps). Runs on weight.device, chunk rows at a time.""" + if chunk % 8: + raise ValueError("inkling_cert: chunk must be a multiple of 8") + return _build(weight, chunk) + + +def _build(weight, chunk): + V, k = weight.shape + if k != K or V % 16: + raise ValueError(f"inkling_cert: head [{V}, {k}] is not [16n, {K}]") + dev = weight.device + packed = torch.empty((V // 8 * STEPS * 384,), dtype=torch.uint8, device=dev) + sc = torch.empty((NGROUPS, V), dtype=torch.float16, device=dev) + rt = torch.empty((NGROUPS, V), dtype=torch.float16, device=dev) + nv = torch.empty((V,), dtype=torch.float32, device=dev) + err = 0.0 + for r0 in range(0, V, chunk): + r1 = min(V, r0 + chunk) + w64 = weight[r0:r1].double() + q, s, d = quantize_rows(weight[r0:r1]) + packed[r0 // 8 * STEPS * 384 : r1 // 8 * STEPS * 384] = pack6(q) + sc[:, r0:r1] = s.t() + res = (w64 - d).view(r1 - r0, NGROUPS, GROUP) + rg = res.pow(2).sum(-1).sqrt() * (1.0 + 2.0 ** -40) + rt[:, r0:r1] = round_up_f16(rg).t() + n = torch.maximum(w64.norm(dim=1), d.norm(dim=1)) * (1.0 + 2.0 ** -40) + nv[r0:r1] = round_up_f32(n) + err += float((res.reshape(r1 - r0, K).norm(dim=1) / w64.norm(dim=1).clamp_min(1e-30)).sum()) + if not (torch.isfinite(rt.float()).all() and torch.isfinite(nv).all() and torch.isfinite(sc.float()).all()): + raise ValueError("inkling_cert: non-finite bound table (head weights out of the fp16 range?)") + return dict(q=packed, sc=sc.contiguous(), rt=rt.contiguous(), nv=nv, eps=err / V) diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_cert.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_cert.py new file mode 100644 index 0000000000000000000000000000000000000000..6779a74e54ab21f82b963ddecd41a2113a832c25 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_cert.py @@ -0,0 +1,231 @@ +"""CPU tests of inkling_cert (numpy + torch, no GPU, no sglang). From overlay/: + python3 -m unittest discover -s inkling_cert/tests -v +""" + +import math +import os +import sys +import unittest + +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) +from inkling_cert import cert_math as cm # noqa: E402 +from inkling_cert import quant # noqa: E402 + +K = cm.K + + +def head(V, seed=0, scale_rows=True): + """A head shaped like Inkling's: rows of norm ~1, a few heavy-tailed entries.""" + rng = np.random.default_rng(seed) + W = rng.standard_normal((V, K)) * (1 + 0.5 * rng.standard_normal((V, 1)) ** 2) + W[rng.random((V, K)) < 0.002] *= 6 + if scale_rows: + W /= np.linalg.norm(W, axis=1, keepdims=True) + return cm.bf16_round(W.astype(np.float32)) + + +def rows_like(W, M, seed=0, peak=0.25): + """Hidden rows with ||x|| ~ 220 and a peaked logit distribution (cos ~ peak with one or two rows).""" + rng = np.random.default_rng(seed) + V = W.shape[0] + X = rng.standard_normal((M, K)) + X /= np.linalg.norm(X, axis=1, keepdims=True) + for m in range(M): + tgt = rng.integers(0, V, size=2) + X[m] = X[m] * math.sqrt(1 - 2 * peak ** 2) + peak * W[tgt[0]] + peak * rng.random() * W[tgt[1]] + X *= 220.0 / np.linalg.norm(X, axis=1, keepdims=True) + return cm.bf16_round(X.astype(np.float32)) + + +def exact_logits(x, W): + return (x.astype(np.float64) @ W.astype(np.float64).T).astype(np.float32) + + +class PackTest(unittest.TestCase): + def test_roundtrip(self): + g = torch.Generator().manual_seed(0) + q = torch.randint(-31, 32, (48, K), generator=g, dtype=torch.int32).to(torch.int8) + p = quant.pack6(q) + self.assertEqual(p.numel(), 48 // 8 * quant.STEPS * 384) + self.assertTrue(torch.equal(quant.unpack6(p, 48), q)) + + def test_kernel_lane_mapping(self): + """The k index each lane / mma uses for B (decoded by the kernel's rule) equals the one it uses for A.""" + g = torch.Generator().manual_seed(1) + q = torch.randint(-31, 32, (16, K), generator=g, dtype=torch.int32).to(torch.int8) + b = quant.pack6(q).view(2, quant.STEPS, 384).long() + seen = np.zeros((16, K), int) + for i in range(2): # the CTA's two 8-row tiles + for s in range(quant.STEPS): + for lane in range(32): + gg, t = lane >> 2, lane & 3 + nib = [int(sum(int(b[i, s, 8 * lane + 4 * h + j]) << (8 * j) for j in range(4))) for h in range(2)] + hi = int(sum(int(b[i, s, 256 + 4 * lane + j]) << (8 * j) for j in range(4))) + for j4 in range(4): + for half, p in ((0, 2 * j4), (1, 2 * j4 + 1)): + w = nib[0] if j4 < 2 else nib[1] + v = ((w >> (4 * (p & 3))) & 0x000F000F) | (((hi >> (2 * p)) & 0x00030003) << 4) + # A operand of this register: x row, values 16t + 4 j4 + 2 half + {0, 1} of step s + ks = [64 * s + 16 * t + 4 * j4 + 2 * half, 64 * s + 16 * t + 4 * j4 + 2 * half + 1] + vals = [(v & 0xFFFF) - 32, (v >> 16) - 32] + for k, val in zip(ks, vals): + self.assertEqual(val, int(q[8 * i + gg, k])) + seen[8 * i + gg, k] += 1 + self.assertTrue((seen == 1).all()) + + def test_six_pair_exact_in_bf16(self): + u = np.arange(64, dtype=np.uint32) + bits = (0x4300 | u).astype(np.uint32) << 16 + vals = bits.view(np.float32) - np.float32(160.0) + self.assertTrue(np.array_equal(vals, u.astype(np.float32) - 32)) + + +class TablesTest(unittest.TestCase): + def test_torch_matches_numpy(self): + W = head(64, seed=3) + t = quant.build_tables(torch.from_numpy(W).to(torch.bfloat16), chunk=32) + q, sc, D = cm.quantize(W) + rt, nv = cm.tables(W, D) + self.assertTrue(torch.equal(quant.unpack6(t["q"], 64), torch.from_numpy(q))) + self.assertTrue(np.array_equal(t["sc"].numpy().T, sc)) + self.assertTrue(np.array_equal(t["rt"].numpy().T, rt)) + self.assertTrue(np.array_equal(t["nv"].numpy(), nv)) + self.assertLessEqual(np.abs(q).max(), 31) + + def test_bound_covers_exact(self): + W = head(4096, seed=4) + q, sc, D = cm.quantize(W) + rt, nv = cm.tables(W, D) + x = rows_like(W, 8, seed=5) + lo, hi = cm.screen(x, D, rt, nv, 4096) + l = x.astype(np.float64) @ W.astype(np.float64).T + self.assertTrue((lo <= l).all() and (l <= hi).all()) + + +class CertifyTest(unittest.TestCase): + V = 8192 + V_REAL = 8000 + + def setUp(self): + self.W = head(self.V, seed=7) + self.q, self.sc, self.D = cm.quantize(self.W) + self.rt, self.nv = cm.tables(self.W, self.D) + + def _check(self, x, l=None, s_err=None): + lo, hi = cm.screen(x, self.D, self.rt, self.nv, self.V_REAL, s_err=s_err) + mask, certified = cm.select(lo, hi) + l = exact_logits(x, self.W) if l is None else l + self.assertTrue(np.array_equal(cm.certified_token(l, mask, self.V_REAL), cm.stock_token(l, self.V_REAL))) + return mask, certified + + def test_peaked_rows(self): + x = rows_like(self.W, 16, seed=11) + mask, certified = self._check(x) + self.assertTrue(certified) + self.assertLess(mask.sum(), self.V // 16 // 4) + + def test_adversarial_screen_error(self): + """Screen errors pushed to the bound's accumulation term in the worst direction for each id.""" + x = rows_like(self.W, 8, seed=12) + l = exact_logits(x, self.W) + w = cm.stock_token(l, self.V_REAL) + xn = np.linalg.norm(x.astype(np.float64), axis=1) + err = cm.C_ACC * self.nv[None, :].astype(np.float64) * xn[:, None] * 0.999 + sign = -np.ones_like(err) + sign[np.arange(8), w] = -1.0 # the winner looks lower, every other id higher + sign[:, :] = np.where(np.arange(self.V)[None, :] == w[:, None], -1.0, 1.0) + self._check(x, s_err=sign * err) + + def test_exact_ties_lowest_id(self): + W = self.W.copy() + W[5000] = W[300] # identical rows: identical logits + W[6000] = W[300] + self.W = W + self.q, self.sc, self.D = cm.quantize(W) + self.rt, self.nv = cm.tables(W, self.D) + x = np.repeat(cm.bf16_round((W[300] * 220.0).astype(np.float32))[None], 4, 0) + mask, certified = self._check(x) + self.assertEqual(int(cm.certified_token(exact_logits(x, W), mask, self.V_REAL)[0]), 300) + + def test_softcap_ties(self): + """Distinct raw logits that the softcap maps to the same FP32 value: the lowest id must still win.""" + x = rows_like(self.W, 1, seed=13) + l = exact_logits(x, self.W) + w = int(cm.stock_token(l, self.V_REAL)[0]) + lw = l[0, w] + # put a lower-id token just below w in raw logit but equal after softcap (large logits saturate) + tested = 0 + for big in (45.0, 60.0, 90.0, 120.0): + l2 = l.copy() + l2[0, w] = big + other = 7 if w != 7 else 9 + cand = np.float32(big) + while cm.softcap(np.array([cand]))[0] == cm.softcap(np.array([np.float32(big)]))[0]: + cand = np.nextafter(cand, np.float32(-np.inf)) + cand = np.nextafter(cand, np.float32(np.inf)) + if cand == np.float32(big): + continue # no softcap tie below this value in FP32 + tested += 1 + l2[0, other] = cand + self.assertLess(l2[0, other], l2[0, w]) + self.assertEqual(int(cm.stock_token(l2, self.V_REAL)[0]), min(other, w)) + # bounds as tight as possible around the true values: the screen interval from l2 itself + lo = l2 - 1e-3 + hi = l2 + 1e-3 + lo[:, self.V_REAL:] = -np.inf + hi[:, self.V_REAL:] = -np.inf + mask, certified = cm.select(lo.astype(np.float32), hi.astype(np.float32)) + self.assertTrue(certified) + self.assertEqual(int(cm.certified_token(l2, mask, self.V_REAL)[0]), min(other, w)) + self.assertGreater(tested, 0) + del lw + + def test_padded_ids_never_raise_threshold(self): + x = rows_like(self.W, 2, seed=14) + l = exact_logits(x, self.W) + l[:, self.V_REAL:] = 1e4 # padded ids with huge logits must not matter + s_err = np.zeros_like(l, dtype=np.float64) + s_err[:, self.V_REAL:] = 1e4 + self._check(x, l=l, s_err=s_err) + + def test_out_of_range_falls_back(self): + x = rows_like(self.W, 2, seed=15) * np.float32(40.0) # logits in the thousands: not certifiable + lo, hi = cm.screen(x, self.D, self.rt, self.nv, self.V_REAL) + mask, certified = cm.select(lo, hi) + self.assertFalse(certified) + self.assertTrue(mask.all()) + + def test_not_on_is_full(self): + x = rows_like(self.W, 2, seed=16) + lo, hi = cm.screen(x, self.D, self.rt, self.nv, self.V_REAL) + mask, certified = cm.select(lo, hi, on=False) + self.assertFalse(certified) + self.assertTrue(mask.all()) + + def test_fill_below_any_winner(self): + """f(-inf) = -30 stays strictly below f(T) for every T the range test admits.""" + for T in (-150.0, -100.0, -30.0, 0.0): + lo = np.full((1, 32), -np.inf, np.float32) + hi = np.full((1, 32), -np.inf, np.float32) + lo[0, 0], hi[0, 0] = T, T + 1 + mask, certified = cm.select(lo, hi) + if certified: + self.assertGreater(cm.softcap(np.array([T], np.float32))[0], cm.softcap(np.array([-np.inf], np.float32))[0]) + + +class ModeTest(unittest.TestCase): + def test_parse(self): + import inkling_cert as ic + + self.assertEqual(ic.parse_mode(""), "0") + self.assertEqual(ic.parse_mode("1"), "1") + self.assertEqual(ic.parse_mode("check"), "check") + with self.assertRaises(RuntimeError): + ic.parse_mode("maybe") + + +if __name__ == "__main__": + unittest.main() diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_certwide.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_certwide.py new file mode 100644 index 0000000000000000000000000000000000000000..f3142476b5003536708d5852a4d962cb08862136 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_certwide.py @@ -0,0 +1,195 @@ +"""Batched bound, serving handoff and fallback tests (CPU).""" + +import threading +import types +import unittest +from unittest import mock + +import numpy as np +import torch + +from inkling_cert import cert_math as cm, certwide, certwide_math as wm, patches + + +class WideBoundTest(unittest.TestCase): + def test_weight_radius_covers_both_paths_and_matches_torch(self): + rng = np.random.default_rng(45) + w = cm.bf16_round(rng.normal(0, 0.021, (80, cm.K))) + _, _, d = cm.quantize(w) + rt, nv = cm.tables(w, d) + r = wm.weight_radius(rt, nv) + torch_r = certwide.weight_radius({"rt": torch.from_numpy(rt.T.copy()), "nv": torch.from_numpy(nv)}) + np.testing.assert_array_equal(r, torch_r.numpy()) + self.assertTrue(np.all(r.astype(np.float64) >= np.linalg.norm(w - d, axis=1) + certwide.CN * nv)) + x = cm.bf16_round(rng.normal(0, 5, (192, cm.K))) + norm = wm.activation_norm(x) + for sign in (-1, 1): + err = sign * 2 * cm.C_ACC * norm[:, None] * nv[None, :] + lo, hi = wm.intervals(x.astype(np.float64) @ d.T + err, norm, r) + exact = x.astype(np.float64) @ w.T - err + self.assertTrue(np.all((lo <= exact) & (exact <= hi))) + + def test_disjoint_rows_union_capped_ties_and_pad(self): + # Distinct m16 groups need distinct vocab tiles. The lower index lies + # in a different tile and has a slightly smaller *raw* logit. + def plateau(x): + return np.round(cm.softcap(x) * 2.0**15) * 2.0**-15 + + for m in (17, 24, 64, 128, 192): + with self.subTest(m=m): + logits = np.full((m, 512), -9, np.float32) + shift = 32 * (np.arange(m) // 16) + logits[np.arange(m), 4 + shift] = 100 + logits[np.arange(m), 19 + shift] = np.nextafter(np.float32(100), np.float32(np.inf)) + logits[:, -1] = 500 + lo, hi = wm.intervals(logits, np.ones(m, np.float32), np.full(512, 0.02, np.float32)) + rows, union, groups, safe = wm.select(lo, hi, 511, 2048, np.ones(m)) + self.assertTrue(safe) + self.assertTrue(np.all(rows.sum(1) == 2)) + self.assertEqual(union.sum(), 2 * ((m + 15) // 16)) + self.assertFalse(union[-1]) + np.testing.assert_array_equal(wm.compact_token(logits, 511, groups, plateau), 4 + shift) + np.testing.assert_array_equal(wm.compact_token(logits, 511, groups, plateau), + cm.stock_token(logits, 511, plateau)) + + def test_inclusive_threshold_and_overcapacity_fallback(self): + logit = np.zeros((24, 128), np.float32) + logit[:, 2] = 50 + cut, ok = wm.thresholds(logit.max(1), logit.max(1)) + self.assertTrue(ok.all()) + hi = logit.copy() + hi[:, 17] = cut + norm = np.ones(24) + rows, union, _, safe = wm.select(logit, hi, 128, 2, norm) + self.assertEqual(union.sum(), 2) + self.assertTrue(rows[:, 1].all()) + self.assertTrue(safe) + self.assertFalse(wm.select(logit, hi, 128, 1, norm)[-1]) + self.assertFalse(wm.select(logit, hi, 128, 2, norm, on=False)[-1]) + flat = np.zeros_like(logit) + self.assertFalse(wm.select(flat, flat, 128, 8, norm)[-1]) + + def test_derivative_and_cutoff_round_conservatively(self): + L = np.linspace(0, 500, 2049, dtype=np.float32) + self.assertTrue(np.all(wm.derivative_lower(L) <= np.exp(-2 * L.astype(np.float64) / cm.CAP))) + T = np.array([-150.4, -150.3, -100, -1, 0, 1, 100, 150.3, 150.4], np.float32) + H = np.maximum(T, 1) + cutoff, ok = wm.thresholds(T, H) + np.testing.assert_array_equal(ok, [False, True, True, True, True, True, True, True, False]) + ideal_slope = np.exp(-2 * np.maximum(np.abs(T.astype(np.float64)) + cm.DMAX, H) / cm.CAP) + self.assertTrue(np.all((T.astype(np.float64) - cutoff)[ok] * ideal_slope[ok] >= 2 * cm.TWO_E)) + + def test_one_unsafe_row_forces_full_head(self): + logits = np.zeros((192, 64), np.float32) + logits[:, 1] = 50 + norm = np.ones(192) + self.assertTrue(wm.select(logits, logits, 64, 4, norm)[-1]) + for bad in (200, np.inf, np.nan): + altered = logits.copy() + altered[-1, 1] = bad + self.assertFalse(wm.select(altered, altered, 64, 4, norm)[-1]) + norm[-1] = 2.0**21 + self.assertFalse(wm.select(logits, logits, 64, 4, norm)[-1]) + + def test_softcap_reversal_proof_uses_margin(self): + # The bounded softcap error can cause a slightly smaller raw logit + # to win outright. Its lower index and separate tile are incidental. + logits = np.full((17, 64), -np.inf, np.float32) + logits[:, 0], logits[:, 19] = 99.9999, 100 + def adversarial_softcap(x): + return cm.softcap(x) + np.where(x < 100, cm.E_SOFTCAP, -cm.E_SOFTCAP) + + rows, _, groups, safe = wm.select(logits, logits, 64, 4, np.ones(17)) + self.assertTrue(safe) + self.assertTrue(rows[:, 0].all()) + np.testing.assert_array_equal(wm.compact_token(logits, 64, groups, adversarial_softcap), 0) + + +class WideHookTest(unittest.TestCase): + def test_both_graph_accept_paths_consume_the_ids(self): + class AcceptGreedy: + @classmethod + def execute(cls, *, target_logits, target_predict=None): + return target_predict + + stock_ids = torch.tensor([3, 4]) + direct_ids = torch.tensor([8, 9]) + mod = types.SimpleNamespace(AcceptGreedy=AcceptGreedy, sampling_argmax=lambda logits: stock_ids) + patches._patch_wide_accept(mod) + shared = torch.empty(2, 32) + captured = shared.view_as(shared) + captured._inkling_certwide_ids = direct_ids + self.assertIs(mod.sampling_argmax(captured), direct_ids) + self.assertIs(mod.AcceptGreedy.execute(target_logits=captured), direct_ids) + self.assertIs(mod.AcceptGreedy.execute(target_logits=captured, target_predict=stock_ids), stock_ids) + self.assertIs(mod.sampling_argmax(shared), stock_ids) + self.assertIsNone(mod.AcceptGreedy.execute(target_logits=shared)) + + def test_head_handoff_is_target_verify_only(self): + mode = mock.Mock() + metadata = types.SimpleNamespace(forward_mode=mode) + stock = object() + direct = object() + wrapped = patches.make_get_logits(lambda *args: stock) + with mock.patch.object(patches, "_wide_logits", return_value=direct) as wide: + mode.is_target_verify.return_value = True + self.assertIs(wrapped(None, None, None, metadata), direct) + mode.is_target_verify.return_value = False + self.assertIs(wrapped(None, None, None, metadata), stock) + self.assertEqual(wide.call_count, 1) + + def test_grammar_and_logprobs_never_arm(self): + for blocked in ("has_grammar", "return_logprob"): + batch = types.SimpleNamespace(**{blocked: True}) + self.assertFalse(patches.batch_ok(batch, sampling_info=None)) + + def test_replay_workspace_rejects_other_streams_and_threads(self): + stack = certwide.CertWide.__new__(certwide.CertWide) + stack.q = types.SimpleNamespace(device="cuda:0") + stack._replay_owner = None + stack._owner_lock = threading.Lock() + with mock.patch.object(torch.cuda, "current_stream", return_value=1) as current: + stack.require_replay_stream() + stack.require_replay_stream() + with mock.patch.object(threading, "current_thread", return_value=object()): + with self.assertRaisesRegex(RuntimeError, "owning thread and CUDA stream"): + stack.require_replay_stream() + current.return_value = 2 + with self.assertRaisesRegex(RuntimeError, "owning thread and CUDA stream"): + stack.require_replay_stream() + + def test_target_graph_checks_owner_before_replay(self): + class Runner: + model_runner = types.SimpleNamespace(is_draft_worker=False) + capture_forward_mode = types.SimpleNamespace(is_target_verify=lambda: True) + replay = mock.Mock(return_value="output") + + def execute(self): + return self.replay() + + def _process_output_after_replay(self, output, forward_batch): + return output + + wide = mock.Mock() + with mock.patch.dict(patches.STATE, cert=types.SimpleNamespace(wide=wide), patched=[]): + patches.patch_graph_runner(types.SimpleNamespace(DecodeCudaGraphRunner=Runner)) + wide.require_replay_stream.side_effect = RuntimeError("wrong stream") + with self.assertRaisesRegex(RuntimeError, "wrong stream"): + Runner().execute() + Runner.replay.assert_not_called() + wide.require_replay_stream.side_effect = None + self.assertEqual(Runner().execute(), "output") + + def test_exact_passes_registered_width_to_binding(self): + stack = certwide.CertWide.__new__(certwide.CertWide) + stack.wide_ext = mock.Mock() + stack.entry = types.SimpleNamespace(n=128, buf=object()) + stack.sparse = torch.empty((24, 32)) + stack.state, stack.tiles, stack.groups = object(), object(), object() + x, wrong_width = torch.empty((24, cm.K)), torch.empty((24, 112)) + stack.exact(x, wrong_width, 120, types.SimpleNamespace(mt=0, mg=2, pfd=1)) + self.assertEqual(stack.wide_ext.certwide_exact.call_args.args[7:], (128, 120, 0, 2, 1)) + + +if __name__ == "__main__": + unittest.main() diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_dflash.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_dflash.py new file mode 100644 index 0000000000000000000000000000000000000000..1d3afd91053462c91dbf2cf13cbf15679896fbae --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_dflash.py @@ -0,0 +1,183 @@ +"""CPU tests of inkling_cert's DFLASH arming (fake worker classes).""" +import os +import sys +import types +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from inkling_cert import dflash, patches # noqa: E402 + + +class FakeCert: + def __init__(self): + self.log = [] + + def set_on(self, v): + self.log.append(1 if v else 0) + + +class Arming(unittest.TestCase): + def setUp(self): + self.saved = dict(patches.STATE) + patches.STATE.update(mode="1", disabled=None, cert=FakeCert(), cfg={"wide": False, "log_every": 0}, + patched=[], calls=0) + + def tearDown(self): + patches.STATE.clear() + patches.STATE.update(self.saved) + + def build(self, skip): + seen = [] + + class TpModelWorker: + def forward_batch_generation(self, *a, **k): + seen.append(patches.STATE["cert"].log[-1] if patches.STATE["cert"].log else None) + return "out" + + class DFlashWorkerV2: + def __init__(self): + self.target_worker = TpModelWorker() + + def _can_skip_verify_logits(self, batch, si): + return skip + + block_size = 8 + + def forward_batch_generation(self, batch, *a, **k): + self.target_worker.forward_batch_generation(batch=None, forward_batch=None, is_verify=False) + out = self.target_worker.forward_batch_generation(batch=None, forward_batch=None, is_verify=True) + self.accepted = self._accept_block(bs=2, next_token_logits=None, target_predict=None) + return out + + def _accept_block(self, **kw): + return kw["target_predict"] + + dflash.patch_worker(types.SimpleNamespace(DFlashWorkerV2=DFlashWorkerV2)) + dflash.patch_tp_worker(types.SimpleNamespace(TpModelWorker=TpModelWorker)) + return DFlashWorkerV2, seen + + def batch(self, greedy=True, logprob=False): + si = types.SimpleNamespace(is_all_greedy=greedy, has_watermark_candidates=False, + sampling_mask_batch_indices=None) + return types.SimpleNamespace(sampling_info=si, return_logprob=logprob, has_grammar=False) + + def test_greedy_armed_then_reset(self): + W, seen = self.build(True) + self.assertEqual(W().forward_batch_generation(self.batch()), "out") + log = patches.STATE["cert"].log + self.assertEqual(seen[-1], 1) # the verify forward saw on = 1 + self.assertEqual(log[-1], 0) # reset right after + self.assertIsNone(seen[0]) # the non-verify forward was not armed + + def test_not_armed(self): + for skip, batch in ((False, self.batch()), (True, self.batch(greedy=False)), (True, self.batch(logprob=True))): + patches.STATE["cert"] = FakeCert() + W, seen = self.build(skip) + W().forward_batch_generation(batch) + self.assertEqual(seen[-1], 0) + + def test_wide_ids_injected_only_when_armed(self): + import torch + + for skip, expect in ((True, True), (False, False)): + patches.STATE["cert"] = FakeCert() + W, seen = self.build(skip) + ids = torch.arange(24) + orig_tp = W().target_worker.forward_batch_generation + + w = W() + + def verify_then_replay(*a, _o=w.target_worker.forward_batch_generation, **k): + out = _o(*a, **k) + if k.get("is_verify"): + dflash.REPLAY.update(ids=ids, wide=True) # what the runner hook records on a wide replay + return out + + w.target_worker.forward_batch_generation = verify_then_replay + w.forward_batch_generation(self.batch()) + if expect: + self.assertTrue(torch.equal(w.accepted, ids[:16])) + else: + self.assertIsNone(w.accepted) + del orig_tp + + def test_ambiguous_wide_replay_is_fatal(self): + W, seen = self.build(True) + w = W() + + def verify(*a, _o=w.target_worker.forward_batch_generation, **k): + out = _o(*a, **k) + if k.get("is_verify"): + dflash.REPLAY.update(ids=None, wide=True) + return out + + w.target_worker.forward_batch_generation = verify + with self.assertRaises(BaseException): + w.forward_batch_generation(self.batch()) + + def test_outside_dflash_untouched(self): + W, seen = self.build(True) + W().target_worker.forward_batch_generation(is_verify=True) # no DFLASH step context + self.assertEqual(patches.STATE["cert"].log, []) + + def _wide_worker(self, compact): + patches.STATE["cfg"] = {"wide": True, "log_every": 0} + rv = types.ModuleType("sglang.srt.speculative.ragged_verify") + rv.ragged_verify_compact_enabled = lambda: compact + names = ["sglang", "sglang.srt", "sglang.srt.speculative", "sglang.srt.speculative.ragged_verify"] + saved = {n: sys.modules.get(n) for n in names} + for n in names[:-1]: + sys.modules.setdefault(n, types.ModuleType(n)) + sys.modules[names[-1]] = rv + + class DFlashWorkerV2: + def forward_batch_generation(self, batch): + pass + + def _accept_block(self, **kw): + pass + + def _can_skip_verify_logits(self, b, s): + return True + + try: + dflash.patch_worker(types.SimpleNamespace(DFlashWorkerV2=DFlashWorkerV2)) + finally: + for n, m in saved.items(): + if m is None: + sys.modules.pop(n, None) + else: + sys.modules[n] = m + return DFlashWorkerV2 + + def test_wide_refused_under_compact(self): + # the certified IDs are request-major: the wide head is refused with compact ragged verify + with self.assertRaises(BaseException): + self._wide_worker(compact=True) + + def test_wide_armed_static(self): + W = self._wide_worker(compact=False) + self.assertTrue(getattr(W.forward_batch_generation, "_inkling_cert", False)) + +@unittest.skipIf(__import__("importlib").util.find_spec("torch") is None, "needs torch") +class DeadRows(unittest.TestCase): + def test_gather_selected_by_on(self): + import torch + + vs = types.ModuleType("inkling_vcap.state") + vs.STATE = types.SimpleNamespace(src_index=None, stride=8) + sys.modules["inkling_vcap.state"] = vs + try: + dflash.ACTIVE["dflash"] = True + x = torch.arange(16 * 4, dtype=torch.float32).view(16, 4) + cert = types.SimpleNamespace(on=torch.ones(1, dtype=torch.int32)) + self.assertIs(dflash.dead_rows_to_anchor(x, cert), x) # no src_index: untouched (CPU / not CUDA) + finally: + dflash.ACTIVE["dflash"] = False + sys.modules.pop("inkling_vcap.state", None) + self.assertIs(dflash.dead_rows_to_anchor(x, cert), x) # not DFLASH: untouched + + +if __name__ == "__main__": + unittest.main() diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_patches.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_patches.py new file mode 100644 index 0000000000000000000000000000000000000000..f785a0d85d6a324ab940d9b6a15a77ea069fe84f --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tests/test_patches.py @@ -0,0 +1,196 @@ +"""CPU tests of inkling_cert's SGLang hooks with stand-in objects (no sglang, no GPU).""" + +import os +import sys +import types +import unittest + +import torch + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) +from inkling_cert import patches # noqa: E402 + + +class FakeCert: + def __init__(self, pack): + self.pack = pack + self.on_values = [] + self.runs = [] + self.warm = set() + self.on, self.off = "ON", "OFF" + + def set_on(self, v): + self.on_values.append(1 if v else 0) + + def run(self, x2, out, on, v_real, cap): + self.runs.append((x2.shape[0], on, v_real, cap)) + out.fill_(1.0) + return out + + +class Pack: + def __init__(self, n, k): + self.n, self.k = n, k + + +def install_fake_pico(weight, pack): + pp = types.ModuleType("inkling_pico12.patches") + pp.STATE = {"levers": ("lmhead",)} + pp.HEADS = {weight.data_ptr(): pack} + po = types.ModuleType("inkling_pico12.ops") + po.rows_of = lambda x: x.numel() // x.shape[-1] + po.eligible = lambda x, p: 0 < po.rows_of(x) <= 16 + po.out_ok = lambda out, m, p, dt, dev: tuple(out.shape) == (m, p.n) + po.as_rows = lambda x, k: x.reshape(-1, k) + sys.modules["inkling_pico12.patches"] = pp + sys.modules["inkling_pico12.ops"] = po + + +class Mode: + def __init__(self, verify): + self.verify = verify + + def is_target_verify(self): + return self.verify + + +class LP: + shard_softcap = 30.0 + logit_scale = None + do_tensor_parallel_all_gather = False + do_tensor_parallel_all_gather_dp_attn = False + + def __init__(self, vocab): + self.config = types.SimpleNamespace(vocab_size=vocab) + + +class HookTest(unittest.TestCase): + def setUp(self): + self.V, self.K = 64, 2304 + self.w = torch.zeros((self.V, self.K), dtype=torch.bfloat16) + self.pack = Pack(self.V, self.K) + install_fake_pico(self.w, self.pack) + self.cert = FakeCert(self.pack) + patches.STATE.update(mode="1", cfg={"log_every": 0, "cache_dir": "/tmp"}, cert=self.cert, disabled=None, + log=lambda m: None) + self.inner_calls = [] + + def inner(x, weight, out): + self.inner_calls.append(x.shape[0]) + return torch.zeros((x.shape[0], self.V)) + + inner._pico12 = True + self.head = patches.make_lm_head(inner) + self.lp = LP(60) + + def get_logits(lp, hidden, lm_head, meta): + return self.head(hidden, self.w, None) + + self.get_logits = patches.make_get_logits(get_logits) + + def x(self, m): + return torch.zeros((m, self.K), dtype=torch.bfloat16) + + def test_only_target_verify(self): + self.get_logits(self.lp, self.x(8), None, types.SimpleNamespace(forward_mode=Mode(False))) + self.assertEqual(self.inner_calls, [8]) + self.assertEqual(self.cert.runs, []) + self.assertIsNone(patches.CTX["lp"]) + + def test_eager_verify_first_call_warms_then_pico(self): + meta = types.SimpleNamespace(forward_mode=Mode(True)) + self.get_logits(self.lp, self.x(8), None, meta) # first eager M <= 8: kernels, full fallback + self.get_logits(self.lp, self.x(8), None, meta) # then pico directly + self.get_logits(self.lp, self.x(16), None, meta) # first eager M 9..16 + self.assertEqual([r[1] for r in self.cert.runs], ["OFF", "OFF"]) + self.assertEqual(self.inner_calls, [8]) + self.assertEqual(self.cert.runs[0][2:], (60, 30.0)) + + def test_rows_above_16_and_bad_processor(self): + meta = types.SimpleNamespace(forward_mode=Mode(True)) + self.get_logits(self.lp, self.x(24), None, meta) + self.assertEqual(self.inner_calls, [24]) + lp = LP(60) + lp.logit_scale = 2.0 + self.get_logits(lp, self.x(8), None, meta) + self.assertIsNotNone(patches.STATE["disabled"]) + self.get_logits(self.lp, self.x(8), None, meta) # disabled for good + self.assertEqual(self.cert.runs, []) + + def test_mode_off(self): + patches.STATE["mode"] = "0" + self.get_logits(self.lp, self.x(8), None, types.SimpleNamespace(forward_mode=Mode(True))) + self.assertEqual(self.cert.runs, []) + + +class VerifyFlagTest(unittest.TestCase): + def setUp(self): + self.cert = FakeCert(None) + patches.STATE.update(mode="1", cfg={"log_every": 0, "cache_dir": "/tmp"}, cert=self.cert, disabled=None, + log=lambda m: None) + calls = [] + + class Epi: + simulate_fold = False + + def begin_static_step(self, bs, armed): + calls.append(("static", armed)) + + def begin_step(self, verify_lens, armed): + calls.append(("step", armed)) + + class Exec: + _simulated_correct_len = None + + def __init__(self): + self.verify_epilogue = Epi() + + def run_non_compact(self, *, batch, draft_input, verify_ids_2d, verify_window, sampling_info): + calls.append(("run",)) + return "result" + + mod = types.ModuleType("dspark_verify") + mod.DsparkVerifyEpilogue, mod.TargetVerifyExecutor = Epi, Exec + patches.patch_verify(mod) + self.ex, self.calls = Exec(), calls + + def run_step(self, armed, batch=None, si=None): + self.ex.verify_epilogue.begin_static_step(1, armed) + batch = batch or types.SimpleNamespace(return_logprob=False, has_grammar=False, sampling_info=si) + r = self.ex.run_non_compact(batch=batch, draft_input=None, verify_ids_2d=None, verify_window=None, + sampling_info=si) + self.assertEqual(r, "result") + return self.cert.on_values[-1] + + def greedy(self, **kw): + d = dict(is_all_greedy=True, has_watermark_candidates=False, sampling_mask_batch_indices=None) + d.update(kw) + return types.SimpleNamespace(**d) + + def test_flag(self): + self.assertEqual(self.run_step(True, si=self.greedy()), 1) + self.assertEqual(self.run_step(False, si=self.greedy()), 0) + self.assertEqual(self.run_step(True, si=self.greedy(is_all_greedy=False)), 0) + self.assertEqual(self.run_step(True, si=self.greedy(has_watermark_candidates=True)), 0) + self.assertEqual(self.run_step(True, si=self.greedy(sampling_mask_batch_indices=torch.zeros(1))), 0) + b = types.SimpleNamespace(return_logprob=True, has_grammar=False, sampling_info=None) + self.assertEqual(self.run_step(True, batch=b, si=None), 0) + b = types.SimpleNamespace(return_logprob=False, has_grammar=False, sampling_info=self.greedy(is_all_greedy=False)) + self.assertEqual(self.run_step(True, batch=b, si=None), 0) # the batch samples although si is None + self.assertEqual(self.run_step(True, si=None), 1) + + def test_begin_step_clears(self): + self.assertEqual(self.run_step(True, si=self.greedy()), 1) + self.ex.verify_epilogue.begin_step(None, armed=True) + self.assertEqual(self.cert.on_values[-1], 0) + b = types.SimpleNamespace(return_logprob=False, has_grammar=False, sampling_info=None) + self.ex.run_non_compact(batch=b, draft_input=None, verify_ids_2d=None, verify_window=None, sampling_info=None) + self.assertEqual(self.cert.on_values[-1], 0) # not re-armed without begin_static_step + + def test_simulated_never(self): + self.ex._simulated_correct_len = torch.zeros(1) + self.assertEqual(self.run_step(True, si=self.greedy()), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tools/gpu_check_cert.py b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tools/gpu_check_cert.py new file mode 100644 index 0000000000000000000000000000000000000000..8a8c65b3a408bd87ac21f65befc8ec8b59c03906 --- /dev/null +++ b/recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_cert/tools/gpu_check_cert.py @@ -0,0 +1,307 @@ +#!/usr/bin/env python3 +"""GPU check + microbench of inkling_cert on the real Inkling-2-Mini head (run in the SGLang image, server stopped). + + python3 inkling_cert/tools/gpu_check_cert.py --model /model --hidden DIR [--quick] + +DIR holds *.npz with `hidden` (uint16 BF16 bits [T, 2304]): real LM-head input rows (inkling_cert/tools or the +CPU-oracle dump). Gates (any failure -> FAIL): + 1 packing: the 6-bit copy decodes (by the kernel's rule) to the quantised head; tables finite + 2 screen accuracy: |s - | and |pico - | within the accumulation model; lo <= pico <= hi everywhere + 3 exactness: certified token == full-head token (stock softcap + padding mask + stock argmax) on every real row, + at M = 8 and M = 16, plus near-tie rows (two ids within 1e-3, softcap saturation, exact duplicates if any); + computed tiles bit-identical to pico's full head, the rest -inf; on = 0 gives pico's full head bit for bit + 4 CUDA graph: replay with changing rows and on flag == eager +Bench (L2 flushed by reading 256 MiB before every rep, CUDA events, median of N): pico full head, cert path +(screen + exact), screen alone, at M = 8 and 16 with real candidate masks. Last line: `cert gpu_check result PASS|FAIL`. +""" + +import argparse +import glob +import json +import os +import struct +import sys +import time + +import numpy as np +import torch + +HERE = os.path.dirname(os.path.abspath(__file__)) +OVERLAY = os.path.dirname(os.path.dirname(HERE)) +sys.path.insert(0, OVERLAY) + +from inkling_cert import build as cbuild, cert_math as cm, ops as cops, quant # noqa: E402 +from inkling_pico12 import build as pbuild, ops as pops # noqa: E402 + +FAIL = [] + + +def gate(ok, msg): + print((" ok " if ok else " FAIL ") + msg, flush=True) + if not ok: + FAIL.append(msg) + + +def load_head(model_dir): + path = os.path.join(model_dir, "model-00001-of-00001.safetensors") + if not os.path.exists(path): + idx = json.load(open(os.path.join(model_dir, "model.safetensors.index.json")))["weight_map"] + path = os.path.join(model_dir, idx["model.llm.unembed.weight"]) + with open(path, "rb") as f: + n = struct.unpack("