Inkling-2-Mini DGX Spark recipe + t5a DFlash2 drafter (package 1741ea3c) (part 4)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/_hook.pyAdded+78
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/build.pyAdded+113
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/csrc/bf16x_format.cuhAdded+57
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/csrc/wide_ext.cuAdded+787
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/ops.pyAdded+313
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/patches.pyAdded+397
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/tests/fake_wide_ext.pyAdded+65
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/tests/test_wide.pyAdded+508
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/third_party/pico/LICENSEAdded+21
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/tools/gpu_check_wide.pyAdded+407
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/tools/gpu_integration_wide.pyAdded+201
- recipe/stack/cands/n419j3-2416d17a/recipe/overlay/sitecustomize.pyAdded+98
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/inkling2_attn.pyAdded+780
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/inkling2_loop.pyAdded+280
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/inkling2_loop_model.pyAdded+68
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n105_rnnhoist.pyAdded+1783
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n13_attn_global.pyAdded+37
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n13_fwd.pyAdded+655
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n140_kern.pyAdded+641
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n14_moe.pyAdded+216
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n14_quant.cuhAdded+237
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n15_fused.pyAdded+147
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n32_attn_local.pyAdded+226
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n32_fwd.pyAdded+1567
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n35_w8.pyAdded+128
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n35_w8gemv.pyAdded+64
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n37_tiles.pyAdded+28
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n50b_fused.pyAdded+314
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n52_band.cuhAdded+1886
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n52_moe.pyAdded+202
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n64_attn_global.pyAdded+233
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n64a_fwd.pyAdded+1138
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n64b_fwd.pyAdded+1597
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n66fb.pyAdded+369
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n71_resnorm.pyAdded+257
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n71_sconvres.pyAdded+135
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n75_c12.pyAdded+188
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n75_cuda.pyAdded+365
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n75_install.pyAdded+343
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n78_head.pyAdded+312
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n78_kern.pyAdded+417
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n80_cuda.pyAdded+171
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n80_draft.pyAdded+147
- recipe/stack/cands/n419j3-2416d17a/recipe/patch/n86_riders.pyAdded+448
- recipe/stack/cands/n419j3-2416d17a/recipe/serve/inkling2_mtp.pyAdded+667
- recipe/stack/cands/n419j3-2416d17a/recipe/serve/mixpin.shAdded+13
- recipe/stack/cands/n419j3-2416d17a/recipe/serve/serve.shAdded+189
- recipe/stack/cands/n419j3-2416d17a/recipe/serve/serve.sh.origAdded+189
- recipe/stack/cands/n419j3-2416d17a/recipe/serve/sl.jsonAdded
- recipe/stack/dflash2/sglang_inkling_dflash2.pyAdded+143
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""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 thecontainer starts, so patches are attached to their target modules lazily. If thetarget module is already imported when the hook is registered, the callback runsimmediately. A callback that raises makes the import of its target fail."""
import importlib.abcimport sysimport 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""Build (or reuse) the inkling_wide CUDA extension with torch.utils.cpp_extension.
Sources: csrc/wide_ext.cu (+ csrc/bf16x_format.cuh, pico's bf16x reader, MIT). Flags: -gencodearch=compute_121a,code=sm_121a -O3 -std=c++20 --expt-relaxed-constexpr -lineinfo. Built into <cache>/<tag>/,<cache> = INKLING_WIDE_CACHE (default ~/.cache/inkling-wide, i.e. /root/.cache/inkling-wide in the container),<tag> a hash of the sources, the flags and the torch / CUDA versions: a later start with the same inputs onlyimports the built .so, a changed input never reuses a stale build.
python3 -m inkling_wide.build # build now (no GPU needed); prints the path
Needs nvcc and ninja (both in the SGLang image)."""
import hashlibimport osimport sysimport time
HERE = os.path.dirname(os.path.abspath(__file__))SOURCES = (os.path.join(HERE, "csrc", "wide_ext.cu"),)HEADERS = (os.path.join(HERE, "csrc", "bf16x_format.cuh"),)NAME = "inkling_wide_ext"
# torch adds -D__CUDA_NO_{HALF,BFLOAT16}_* to every nvcc line; the kernel uses __floats2bfloat162_rn._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-wide")
def cuda_flags(arch="121a"): return [ f"-gencode=arch=compute_{arch},code=sm_{arch}", "-O3", "-std=c++20", "--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 = NoneINFO = {}
def load(cache_dir=None, arch="121a", verbose=False): """Import the extension, building it first when <cache>/<tag> 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) if verbose: flags = flags + ["-Xptxas=-v"] 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_wide: building the extension in {build_dir} failed: {exc}") from exc for attr in ("gemm", "decode", "prepare", "bucket", "kernel_info", "prepare_certwide", "certwide_exact"): if not callable(getattr(ext, attr, None)): raise RuntimeError(f"inkling_wide: 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_WIDE_CACHE") or default_cache_dir()) p.add_argument("--verbose", action="store_true") a = p.parse_args(argv) ext = load(a.cache, verbose=a.verbose) print( f"inkling_wide extension {'reused' if INFO['cached'] else 'built'} in {INFO['seconds']:.1f} s: " f"{INFO['build_dir']} (max_rows={ext.max_rows} block_n={ext.block_n})" ) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657// Reader of pico's exactly coded BF16 weight format (`bf16x`). The layout description, bf16x_raw_off, mad_imm,// bf16x_dec and ldg_bf16x below are copied from pico (dsgx10 ds41f-4xgx10-switchless/engine/kernels/gemv16.cu,// commit f2117916), MIT License, Copyright (c) 2026 Andy Shu; full licence text in third_party/pico/LICENSE.// Only the reader is copied; the coding itself (bf16x_encode / bf16x_check) stays in inkling_pico12, whose// packed buffers this package reads.//// pico's tiled layout of a BF16 weight W [N][K]: tile (n8, p) = rows 8*n8 .. 8*n8+7, values 32p .. 32p+31// (64 bytes of each row); lane l of a warp owns row l/4, values 32p + 8(l%4) .. +7 (16 bytes). With// T = N/8 * K/32 tiles, tile index i = n8 * (K/32) + p, the coded buffer holds:// [T][256 B] sign and mantissa bytes (sign << 7 | mantissa): lane l's 8 values at 8l// [T][128 B] exponent offsets: lane l's u32 at 4l, nibble j (bits 4j) value 2j, nibble 4 + j value 2j + 1// [T] u32 header: (b << 23) | (b << 7), b the tile's least exponent; raw tile r: 0x80000000 | r// [R][512 B] the raw tiles as they were, from the first multiple of 256 bytes after the headers// A raw tile's 512 bytes are the tile's 8 rows x 64 bytes, lane l's 16 bytes at 16l.#pragma once#include <cstddef>#include <cstdint>
namespace wide {
__host__ __device__ constexpr size_t bf16x_raw_off(size_t T) { return (T * 388 + 255) & ~(size_t)255; }
// a * M + c as one multiply-addtemplate <uint32_t M>__device__ __forceinline__ uint32_t mad_imm(uint32_t a, uint32_t c) { uint32_t d; asm("mad.lo.u32 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "n"(M), "r"(c)); return d;}
// A lane's 8 values of a coded tile (s0, s1: their sign-mantissa bytes; e: their exponent offsets; hb: the// tile's header) -> the raw tile's 16 bytes of that lane (4 words of bf16 pairs)__device__ __forceinline__ uint4 bf16x_dec(uint32_t s0, uint32_t s1, uint32_t e, uint32_t hb) { const uint32_t e2 = e >> 8; uint4 o; o.x = (__byte_perm(s0, 0, 0x1100) & 0x807F807Fu) | mad_imm<128>(e & 0x000F000Fu, hb); o.y = (__byte_perm(s0, 0, 0x3322) & 0x807F807Fu) | mad_imm<8>(e & 0x00F000F0u, hb); o.z = (__byte_perm(s1, 0, 0x1100) & 0x807F807Fu) | mad_imm<128>(e2 & 0x000F000Fu, hb); o.w = (__byte_perm(s1, 0, 0x3322) & 0x807F807Fu) | mad_imm<8>(e2 & 0x00F000F0u, hb); return o;}
// A lane's load of one tile by the tile's header h: a raw tile's 16 bytes at r, or a coded one's 8 at s and 4 at// e (x, y; z). Predicated rather than branched (h is warp-uniform). Streamed past L1.__device__ __forceinline__ uint4 ldg_bf16x(uint32_t h, const uint8_t* r, const uint8_t* s, const uint8_t* e) { uint4 v; asm volatile( "{\n\t.reg .pred p;\n\tsetp.lt.s32 p, %4, 0;\n\t" "@p ld.global.nc.L1::no_allocate.v4.u32 {%0, %1, %2, %3}, [%5];\n\t" "@!p ld.global.nc.L1::no_allocate.v2.u32 {%0, %1}, [%6];\n\t" "@!p ld.global.nc.L1::no_allocate.u32 %2, [%7];\n\t}" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "r"(h), "l"(r), "l"(s), "l"(e)); return v;}
} // namespace wide123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787// inkling_wide: weight-streaming BF16 GEMM for 17..256 activation rows (DSpark verify batches), on raw BF16// weights (natural [N][K] row-major, the layer's own storage) or on pico's exactly coded `bf16x` copy (built by// inkling_pico12; reader in bf16x_format.cuh, pico by Andy Shu, MIT).//// out[m, n] = sum_k x[m, k] W[n, k] BF16 operands, FP32 accumulation (mma.sync m16n8k16), FP32 or BF16 out//// Each weight byte is read from DRAM once per call. A CTA owns kBN = 128 weight rows (16 tiles of 8 rows) and a// K slice (split-K over gridDim.y CTAs, fixed-order reduction by the last CTA of a column block). Its warps own// MT tiles each (MT = 2 up to 128 rows, 1 above) and stream them straight into registers (16 bytes per lane and// tile step, one batch of 2 steps ahead), decode them in registers (bf16x) and multiply them with ALL M rows of// the activations: the weights are the MMA's B operand (n8 = 8 weight rows), the activations its A operand// (m16 = 16 rows), read from shared memory, where the CTA stages x[0:M, 64-value chunk] with cp.async (3 stages).//// A tile step's lane layout (lane (g, t): weight row g, values 8t .. 8t+7 of the step's 32) is the layout of the// mma B fragment with the k order permuted (pair j of the lane's 8 values is k position 2t + 8*(j&1) of MMA// (j>>1)); the A fragment is loaded with the same permutation (16 contiguous bytes of row g and of row g + 8), so// each MMA computes a correct partial dot product. Raw and coded weights give the same B registers after the// decode, so the two formats give the same bits.//// Stacked q/k/v (Inkling2Attention._project_sources with three sources): the CTA's column block picks its// activation source (columns [rb1, rb2): x1, [rb2, rb3): x2, else x0) and its output row offset (roff), so the// three sources share one read of the weight. Region bounds must be multiples of kBN (checked on the host).//// CUDA graphs: the launch allocates nothing and does not synchronise; split-K uses a caller-owned FP32 workspace// and a counter per column block that the reducing CTA resets to zero.// PDL: the first weight batch is loaded before griddepcontrol.wait; x, out, ws and cnt only after it. The weights// must therefore not be written by the kernel launched just before (they are load-time constants here).#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>#include <c10/cuda/CUDAException.h>#include <c10/cuda/CUDAGuard.h>#include <cuda_bf16.h>#include <cuda_runtime.h>
#include <algorithm>#include <cstdint>#include <tuple>
#include "bf16x_format.cuh"
namespace wide {
constexpr int kBN = 128; // weight rows (output columns) per CTAconstexpr int kTilesCta = kBN / 8; // 16 tiles of 8 rowsconstexpr int kStepK = 32; // k values per tile stepconstexpr int kBatch = 2; // steps per pipeline batchconstexpr int kStages = 3; // activation stages in shared memoryconstexpr int kRowB = kBatch * kStepK * 2; // 128 bytes of a staged activation rowconstexpr int kMaxM = 256;
enum Fmt { kRaw = 0, kBF16X = 2 };
struct Params { const __nv_bfloat16* x0; const __nv_bfloat16* x1; const __nv_bfloat16* x2; long long ldx; // row stride of every source (elements) int M; int rb1, rb2, rb3; // column regions: [rb1, rb2) -> x1, [rb2, rb3) -> x2, else x0 long long roff1, roff2; // output row offset of sources 1 and 2 (source 0: 0) const uint8_t* W; int N, K; void* out; long long ldo; // output row stride (elements) int f32; // 1: FP32 out, 0: BF16 out int S; // split-K slices (gridDim.y) int pfd; // L2 prefetch distance in batches (0: none) float* ws; // [S][M][N] partials (S > 1) int* cnt; // [gridDim.x] arrival counters, zero between calls (S > 1) const int* cert_state; // optional device gate [fallback reason, union size] const int* cert_tiles; // sparse slot -> original 16-column tile const int* cert_groups; // sparse slot -> bitmask of candidate m16 groups};
__device__ __forceinline__ void mma_bf16(float d[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"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));}
__device__ __forceinline__ uint4 ldg_stream128(const void* p) { uint4 r; asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(r.x), "=r"(r.y), "=r"(r.z), "=r"(r.w) : "l"(p)); return r;}
__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) { asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" ::"r"((uint32_t)__cvta_generic_to_shared(smem)), "l"(gmem) : "memory");}// 16 bytes, or 16 zero bytes when !live (src-size 0; src must still be a valid address)__device__ __forceinline__ void cp_async16_zfill(void* smem, const void* gmem, bool live) { asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" ::"r"((uint32_t)__cvta_generic_to_shared(smem)), "l"(gmem), "r"(live ? 16 : 0) : "memory");}__device__ __forceinline__ int atomic_add_acq_rel_gpu(int* p, int v) { int old; asm volatile("atom.acq_rel.gpu.global.add.s32 %0, [%1], %2;" : "=r"(old) : "l"(p), "r"(v) : "memory"); return old;}__device__ __forceinline__ void cp_async_commit() { asm volatile("cp.async.commit_group;" ::: "memory"); }template <int N>__device__ __forceinline__ void cp_async_wait() { asm volatile("cp.async.wait_group %0;" ::"n"(N) : "memory");}__device__ __forceinline__ void pdl_launch_dependents() { asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); }__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); }
// MT: tiles per warp. 2 up to 128 rows; above, 1 (16 warps, 64 accumulators a lane) or 2 (8 warps, 128// accumulators a lane, half the shared-memory traffic per MMA).constexpr int default_mt(int MI) { return MI <= 8 ? 2 : 1; }
// MG: warp groups along M. 1: every warp multiplies its tiles with all rows; 2 (buckets 6 and 8): two warps load// the same tiles and take half the rows each (16 warps a CTA, half the accumulators a lane; the second load of a// tile is an L2 hit).template <int MI, int MT_, int MG_ = 1>struct Cfg { static constexpr int MT = MT_; static constexpr int MG = MG_; static constexpr int MIW = MI / MG; // m16 tiles per warp static constexpr int NWN = kTilesCta / MT; // warps along N static constexpr int NW = NWN * MG; // warps per CTA static constexpr int NT = NW * 32; // threads per CTA static constexpr int MINB = (MI <= 4 && MG == 1) ? 2 : 1; // CTAs per SM the register budget aims at static constexpr int STAGE = MI * 16 * kRowB; // bytes of one activation stage static constexpr int SMEM = kStages * STAGE;};
template <int FMT, int MI, int MT_, int MG_, bool SPARSE = false>__global__ void __launch_bounds__(Cfg<MI, MT_, MG_>::NT, Cfg<MI, MT_, MG_>::MINB) k_wide(const Params p) { using C = Cfg<MI, MT_, MG_>; static_assert(MI % MG_ == 0, "rows split evenly between the warp groups"); constexpr int MT = C::MT; constexpr int MIW = C::MIW; constexpr int NT = C::NT; constexpr int STAGE = C::STAGE; extern __shared__ __align__(16) uint8_t smem[]; __shared__ int s_last; __shared__ unsigned active_m16; // The certificate is a preceding stream dependency; wait before using its // device-produced gate or indices. Regular wide still preloads weights first. if (p.cert_state) { pdl_wait(); const bool fallback = p.cert_state[0] != 0; if constexpr (SPARSE) { if (fallback || blockIdx.x * (kBN / 16) >= p.cert_state[1]) return; } else { if (!fallback) return; } }
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3; const int wn = warp % C::NWN, mg = warp / C::NWN; // the warp's tiles, its row group if constexpr (SPARSE) { if (warp == 0) { constexpr int slots_per_cta = kBN / 16; const int slot = blockIdx.x * slots_per_cta + lane; const unsigned mask = lane < slots_per_cta && slot < p.cert_state[1] ? p.cert_groups[slot] : 0u; const unsigned all_groups = __reduce_or_sync(0xffffffffu, mask); if (lane == 0) active_m16 = all_groups; } __syncthreads(); }
const int M = p.M, N = p.N, K = p.K; const int P = K / kStepK; // tile steps along K const int NB = P / kBatch; // batches along K const int S = p.S, s = blockIdx.y; const int b0 = (int)((long long)NB * s / S), b1 = (int)((long long)NB * (s + 1) / S); const int n_cta = blockIdx.x * kBN; const int ntiles = N / 8; const int src = (n_cta >= p.rb1 && n_cta < p.rb2) ? 1 : (n_cta >= p.rb2 && n_cta < p.rb3) ? 2 : 0; const __nv_bfloat16* __restrict__ xs = src == 1 ? p.x1 : src == 2 ? p.x2 : p.x0; const long long roff = src == 1 ? p.roff1 : src == 2 ? p.roff2 : 0;
// ---- this lane's weight pointers int nt[MT]; bool valid[MT]; unsigned groups[MT]; unsigned warp_groups = 0; const uint8_t* wptr[MT]; // raw: row 8*nt+g at value 8t; bf16x: tile (nt, 0)'s sign-mantissa bytes of the lane const uint8_t* eptr[MT]; // bf16x: exponent offsets of tile (nt, 0) of the lane const uint32_t* hptr[MT]; // bf16x: header of tile (nt, 0) const size_t T = (size_t)ntiles * P; // bf16x: the lane's bytes of raw tile 0, less 2^40: raw tile r (header h = 2^31 + r) at rawq + 512 h const uint64_t rawq = FMT == kBF16X ? reinterpret_cast<uint64_t>(p.W + bf16x_raw_off(T) + 16 * lane) - (1ull << 40) : 0;#pragma unroll for (int i = 0; i < MT; ++i) { const int slot = blockIdx.x * kTilesCta + wn * MT + i; if constexpr (SPARSE) { valid[i] = slot / 2 < p.cert_state[1]; nt[i] = valid[i] ? 2 * p.cert_tiles[slot / 2] + slot % 2 : 0; groups[i] = valid[i] ? p.cert_groups[slot / 2] : 0; warp_groups |= groups[i]; } else { nt[i] = slot; valid[i] = nt[i] < ntiles; } const size_t ti = (size_t)(valid[i] ? nt[i] : 0) * P; if constexpr (FMT == kBF16X) { wptr[i] = p.W + ti * 256 + 8 * lane; eptr[i] = p.W + T * 256 + ti * 128 + 4 * lane; hptr[i] = reinterpret_cast<const uint32_t*>(p.W + T * 384) + ti; } else { wptr[i] = p.W + ((size_t)(valid[i] ? nt[i] : 0) * 8 + g) * (size_t)K * 2 + 16 * t; eptr[i] = nullptr; hptr[i] = nullptr; } }
// bf16x: the headers of the warp's tiles in registers, loaded once (before the PDL wait: weights only): lane l // holds steps l, l + 32, l + 64 (P <= 96, checked on the host); a step's header is a shuffle from lane ps % 32. uint32_t hreg[MT][3];#pragma unroll for (int i = 0; i < MT; ++i)#pragma unroll for (int j = 0; j < 3; ++j) { const int ps = lane + 32 * j; hreg[i][j] = (FMT == kBF16X && valid[i] && ps < P) ? __ldg(hptr[i] + ps) : 0u; } auto hdr = [&](int i, int ps) -> uint32_t { const int j = ps >> 5; // warp-uniform const uint32_t v = j == 0 ? hreg[i][0] : j == 1 ? hreg[i][1] : hreg[i][2]; return __shfl_sync(0xffffffffu, v, ps & 31); };
// L2 prefetch of batch b's weight lines (fire and forget; group 0 only): lanes 16i .. 16i+15 for tile i. auto prefetch = [&](int b) { if (b >= b1 || mg != 0) return; const int i = MT == 2 ? (lane >> 4) : 0, li = lane & 15; if (MT == 1 && lane >= 16) return; const bool vi = MT == 2 ? (i == 0 ? valid[0] : valid[MT - 1]) : valid[0]; if (!vi) return; const int nti = MT == 2 ? (i == 0 ? nt[0] : nt[MT - 1]) : nt[0]; const uint8_t* a = nullptr; if constexpr (FMT == kBF16X) { const size_t ti = (size_t)nti * P; if (li < 4) a = p.W + ti * 256 + (size_t)b * 512 + li * 128; else if (li < 6) a = p.W + T * 256 + ti * 128 + (size_t)b * 256 + (li - 4) * 128; } else { if (li < 8) a = p.W + (((size_t)nti * 8 + li) * (size_t)K + (size_t)b * 64) * 2; } if (a) asm volatile("prefetch.global.L2 [%0];" ::"l"(a)); };
float acc[MT][MIW][4];#pragma unroll for (int i = 0; i < MT; ++i)#pragma unroll for (int j = 0; j < MIW; ++j) acc[i][j][0] = acc[i][j][1] = acc[i][j][2] = acc[i][j][3] = 0.f;
uint4 wa[kBatch][MT], wb[kBatch][MT]; uint32_t ha[kBatch][MT], hb[kBatch][MT];#pragma unroll for (int u = 0; u < kBatch; ++u)#pragma unroll for (int i = 0; i < MT; ++i) { wa[u][i] = wb[u][i] = make_uint4(0, 0, 0, 0); ha[u][i] = hb[u][i] = 0; }
auto load = [&](uint4 (&w)[kBatch][MT], uint32_t (&h)[kBatch][MT], int b) {#pragma unroll for (int u = 0; u < kBatch; ++u) { const int ps = b * kBatch + u;#pragma unroll for (int i = 0; i < MT; ++i) { if (!valid[i]) continue; if constexpr (FMT == kBF16X) { const uint32_t hh = hdr(i, ps); h[u][i] = hh; w[u][i] = ldg_bf16x(hh, reinterpret_cast<const uint8_t*>(rawq + (uint64_t)hh * 512), wptr[i] + (size_t)ps * 256, eptr[i] + (size_t)ps * 128); } else { w[u][i] = ldg_stream128(wptr[i] + (size_t)ps * 64); } } } };
// activation stage of batch b -> buffer `buf`: rows < M copied, rows M .. Mpad-1 (the last m16 tile's padding) // zero-filled; 8 chunks of 16 bytes a row; chunk c of row r lands at chunk c ^ 4 when r is odd, so that the two // rows (16mi+g, g = 2j and 2j+1) one 8-lane phase of a 128-bit load reads fall into different bank halves. const int Mpad = (M + 15) & ~15; auto issue_x = [&](int b, int buf) { uint8_t* dst = smem + buf * STAGE; const __nv_bfloat16* srcp = xs + (size_t)b * (kBatch * kStepK); for (int c = threadIdx.x; c < Mpad * 8; c += NT) { const int r = c >> 3, ch = c & 7; if constexpr (SPARSE) { if (!(active_m16 & (1u << (r / 16)))) continue; } const bool live = r < M; cp_async16_zfill(dst + r * kRowB + ((ch ^ ((r & 1) << 2)) << 4), srcp + (size_t)(live ? r : 0) * p.ldx + ch * 8, live); } };
auto comp = [&](uint4 (&w)[kBatch][MT], const uint32_t (&h)[kBatch][MT], int buf) { const uint8_t* xb = smem + buf * STAGE;#pragma unroll for (int u = 0; u < kBatch; ++u) { uint4 wd[MT];#pragma unroll for (int i = 0; i < MT; ++i) { wd[i] = w[u][i]; if constexpr (FMT == kBF16X) { if ((int)h[u][i] >= 0) wd[i] = bf16x_dec(wd[i].x, wd[i].y, wd[i].z, h[u][i]); } } const int off = ((u * 4 + t) ^ ((g & 1) << 2)) << 4; // rows 16mi+g and 16mi+g+8 have g's parity#pragma unroll for (int j = 0; j < MIW; ++j) { const int mi = mg * MIW + j; if (mi * 16 >= M) break; if constexpr (SPARSE) { if (!(warp_groups & (1u << mi))) continue; } const int r = mi * 16 + g; const uint4 a = *reinterpret_cast<const uint4*>(xb + r * kRowB + off); const uint4 a2 = *reinterpret_cast<const uint4*>(xb + (r + 8) * kRowB + off);#pragma unroll for (int i = 0; i < MT; ++i) { if constexpr (SPARSE) { if (!(groups[i] & (1u << mi))) continue; } mma_bf16(acc[i][j], a.x, a2.x, a.y, a2.y, wd[i].x, wd[i].y); mma_bf16(acc[i][j], a.z, a2.z, a.w, a2.w, wd[i].z, wd[i].w); } } } };
load(wa, ha, b0); for (int d = 1; d <= p.pfd; ++d) prefetch(b0 + d); pdl_launch_dependents(); pdl_wait(); issue_x(b0, 0); cp_async_commit(); if (b0 + 1 < b1) issue_x(b0 + 1, 1); cp_async_commit(); int stage = 0; for (int b = b0; b < b1; b += 2) { if (b + 1 < b1) load(wb, hb, b + 1); if (p.pfd) prefetch(b + 1 + p.pfd); cp_async_wait<1>(); __syncthreads(); if (b + 2 < b1) issue_x(b + 2, stage == 0 ? 2 : stage - 1); cp_async_commit(); comp(wa, ha, stage); stage = stage == 2 ? 0 : stage + 1; if (b + 1 >= b1) break; if (b + 2 < b1) load(wa, ha, b + 2); if (p.pfd) prefetch(b + 2 + p.pfd); cp_async_wait<1>(); __syncthreads(); if (b + 3 < b1) issue_x(b + 3, stage == 0 ? 2 : stage - 1); cp_async_commit(); comp(wb, hb, stage); stage = stage == 2 ? 0 : stage + 1; } cp_async_wait<0>();
// ---- epilogue. acc[i][mi]: c0, c1 = (row 16mi+g, columns 8nt+2t, +1), c2, c3 = (row 16mi+g+8, same columns) auto store2 = [&](int m, int n, float v0, float v1) { const size_t o = (size_t)(roff + m) * (size_t)p.ldo + n; if (p.f32) { *reinterpret_cast<float2*>(reinterpret_cast<float*>(p.out) + o) = make_float2(v0, v1); } else { *reinterpret_cast<__nv_bfloat162*>(reinterpret_cast<__nv_bfloat16*>(p.out) + o) = __floats2bfloat162_rn(v0, v1); } }; if (S == 1) {#pragma unroll for (int i = 0; i < MT; ++i) { if (!valid[i]) continue; const int out_tile = SPARSE ? blockIdx.x * kTilesCta + wn * MT + i : nt[i]; const int n = out_tile * 8 + 2 * t;#pragma unroll for (int j = 0; j < MIW; ++j) { const int mi = mg * MIW + j; if constexpr (SPARSE) { if (!(groups[i] & (1u << mi))) continue; } const int r = mi * 16 + g; if (r < M) store2(r, n, acc[i][j][0], acc[i][j][1]); if (r + 8 < M) store2(r + 8, n, acc[i][j][2], acc[i][j][3]); } } return; } if constexpr (SPARSE) return; // certified heads use S = 1
// split-K: every slice writes its partials; the last CTA of the column block sums slices 0..S-1 in order float* wsl = p.ws + (size_t)s * M * N;#pragma unroll for (int i = 0; i < MT; ++i) { if (!valid[i]) continue; const int n = nt[i] * 8 + 2 * t;#pragma unroll for (int j = 0; j < MIW; ++j) { const int r = (mg * MIW + j) * 16 + g; if (r < M) __stcg(reinterpret_cast<float2*>(wsl + (size_t)r * N + n), make_float2(acc[i][j][0], acc[i][j][1])); if (r + 8 < M) __stcg(reinterpret_cast<float2*>(wsl + (size_t)(r + 8) * N + n), make_float2(acc[i][j][2], acc[i][j][3])); } } // publication: every writer fences, the CTA barrier orders the writers before the leader's device-scope acq_rel // arrival (release: the CTA's partials; acquire, in the last CTA: every other CTA's), and the second barrier // orders the leader's acquire before the readers' loads. __threadfence(); __syncthreads(); if (threadIdx.x == 0) s_last = atomic_add_acq_rel_gpu(p.cnt + blockIdx.x, 1) == S - 1; __syncthreads(); if (!s_last) return; __threadfence();#pragma unroll for (int i = 0; i < MT; ++i) { if (!valid[i]) continue; const int n = nt[i] * 8 + 2 * t;#pragma unroll for (int jm = 0; jm < MIW; ++jm) {#pragma unroll for (int hf = 0; hf < 2; ++hf) { const int r = (mg * MIW + jm) * 16 + g + 8 * hf; if (r >= M) continue; float2 v = __ldcg(reinterpret_cast<const float2*>(p.ws + (size_t)r * N + n)); for (int j = 1; j < S; ++j) { const float2 q = __ldcg(reinterpret_cast<const float2*>(p.ws + ((size_t)j * M + r) * N + n)); v.x += q.x; v.y += q.y; } store2(r, n, v.x, v.y); } } } if (threadIdx.x == 0) p.cnt[blockIdx.x] = 0; // ready for the next call (stream order)}
// coded (bf16x) -> natural [N][K] BF16, through the same reader as k_wide: the GPU check compares it with the// layer's weight bit for bit. One warp per tile.__global__ void k_decode(const uint8_t* __restrict__ X, int N, int K, __nv_bfloat16* __restrict__ out) { const int P = K / kStepK; const size_t T = (size_t)(N / 8) * P; const int lane = threadIdx.x & 31; const uint64_t rawq = reinterpret_cast<uint64_t>(X + bf16x_raw_off(T) + 16 * lane) - (1ull << 40); for (size_t tile = (blockIdx.x * (size_t)blockDim.x + threadIdx.x) >> 5; tile < T; tile += ((size_t)gridDim.x * blockDim.x) >> 5) { const uint32_t h = reinterpret_cast<const uint32_t*>(X + T * 384)[tile]; uint4 v = ldg_bf16x(h, reinterpret_cast<const uint8_t*>(rawq + (uint64_t)h * 512), X + tile * 256 + 8 * lane, X + T * 256 + tile * 128 + 4 * lane); if ((int)h >= 0) v = bf16x_dec(v.x, v.y, v.z, h); const size_t n8 = tile / P, ps = tile % P; const size_t row = n8 * 8 + (lane >> 2), col = ps * kStepK + 8 * (lane & 3); *reinterpret_cast<uint4*>(out + row * K + col) = v; }}
template <int FMT, int MI, int MT, int MG, bool SPARSE = false>void launch_mi(const Params& p, int nblk, bool pdl, cudaStream_t st) { using C = Cfg<MI, MT, MG>; auto kern = k_wide<FMT, MI, MT, MG, SPARSE>; // its shared-memory attribute is set by prepare() at load time cudaLaunchConfig_t cfg{}; cfg.gridDim = dim3(nblk, p.S); cfg.blockDim = dim3(C::NT); cfg.dynamicSmemBytes = C::SMEM; cfg.stream = st; cudaLaunchAttribute attr[1]; attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; attr[0].val.programmaticStreamSerializationAllowed = 1; cfg.attrs = attr; cfg.numAttrs = pdl ? 1 : 0; C10_CUDA_CHECK(cudaLaunchKernelEx(&cfg, kern, p));}
// The m16-tile buckets: rows up to 16, 32, 48, 64, 96, 128, 192, 256.constexpr int kBuckets[] = {1, 2, 3, 4, 6, 8, 12, 16};
int bucket_of(int M) { const int need = (M + 15) / 16; for (int b : kBuckets) if (b >= need) return b; return -1;}
// The kernel of a bucket: mt 0 = default_mt; buckets 12 and 16 also exist with the other MT; buckets 6 and 8 also// with two warp groups along M (mg 2).int mt_of(int MI, int mt) { return MI >= 12 && (mt == 1 || mt == 2) ? mt : default_mt(MI); }int mg_of(int MI, int mg) { return (MI == 6 || MI == 8) && mg == 2 ? 2 : 1; }int key_of(int MI, int mt, int mg) { return MI * 16 + mt_of(MI, mt) * 4 + mg_of(MI, mg); }constexpr int kkey(int MI, int MT, int MG) { return MI * 16 + MT * 4 + MG; }
#define WIDE_KERNELS(X, FMT) \ X(FMT, 1, 2, 1) X(FMT, 2, 2, 1) X(FMT, 3, 2, 1) X(FMT, 4, 2, 1) X(FMT, 6, 2, 1) X(FMT, 6, 2, 2) X(FMT, 8, 2, 1) \ X(FMT, 8, 2, 2) X(FMT, 12, 1, 1) X(FMT, 12, 2, 1) X(FMT, 16, 1, 1) X(FMT, 16, 2, 1)
template <int FMT>void launch_fmt(const Params& p, int nblk, bool pdl, int mt, int mg, cudaStream_t st) { const int MI = bucket_of(p.M); TORCH_CHECK(MI > 0, "inkling_wide: M=", p.M, " not in [1, ", kMaxM, "]"); const int key = key_of(MI, mt, mg);#define WIDE_LAUNCH(F, MI_, MT_, MG_) \ if (key == kkey(MI_, MT_, MG_)) return launch_mi<F, MI_, MT_, MG_>(p, nblk, pdl, st); WIDE_KERNELS(WIDE_LAUNCH, FMT)#undef WIDE_LAUNCH TORCH_CHECK(false, "inkling_wide: no kernel for M=", p.M);}
template <int FMT>void prepare_fmt() { // cudaFuncSetAttribute for every instantiation at load time (outside any graph capture)#define WIDE_ATTR(F, MI, MT, MG) \ C10_CUDA_CHECK(cudaFuncSetAttribute(k_wide<F, MI, MT, MG>, cudaFuncAttributeMaxDynamicSharedMemorySize, \ Cfg<MI, MT, MG>::SMEM)); WIDE_KERNELS(WIDE_ATTR, FMT)#undef WIDE_ATTR}
// ---- bindings
void check_x(const torch::Tensor& x, int64_t M, int64_t K, const torch::Tensor& ref) { TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::kBFloat16 && x.dim() == 2, "inkling_wide: x must be CUDA bf16 [M, K]"); TORCH_CHECK(x.device() == ref.device(), "inkling_wide: x on another device"); TORCH_CHECK(x.size(0) >= M && x.size(1) == K && x.stride(1) == 1, "inkling_wide: x must be [>= M, K] with unit column stride"); TORCH_CHECK(x.stride(0) % 8 == 0 && reinterpret_cast<uintptr_t>(x.data_ptr()) % 16 == 0, "inkling_wide: x rows must be 16-byte aligned");}
// out[roff(n) + m, n] = sum_k x_src(n)[m, k] W[n, k] for m < M, every column n; see Params.// fmt 0: W is the BF16 weight [N, K] (contiguous); fmt 2: W is the bf16x coded uint8 buffer of [N, K].void gemm(const torch::Tensor& x0, const torch::Tensor& x1, const torch::Tensor& x2, int64_t M, const torch::Tensor& W, int64_t fmt, int64_t N, int64_t K, int64_t rb1, int64_t rb2, int64_t rb3, int64_t roff1, int64_t roff2, const torch::Tensor& out, int64_t S, const torch::Tensor& ws, const torch::Tensor& cnt, bool pdl, int64_t mt, int64_t mg, int64_t pfd) { TORCH_CHECK(M >= 1 && M <= kMaxM, "inkling_wide: M=", M, " not in [1, 256]"); TORCH_CHECK(N % 8 == 0 && N > 0 && K % 64 == 0 && K > 0 && N <= INT32_MAX && K <= INT32_MAX, "inkling_wide: N=", N, " K=", K, " (N a multiple of 8, K of 64)"); check_x(x0, M, K, W); check_x(x1, M, K, W); check_x(x2, M, K, W); TORCH_CHECK(x0.stride(0) == x1.stride(0) && x0.stride(0) == x2.stride(0), "inkling_wide: sources differ in row stride"); TORCH_CHECK(W.is_cuda() && W.is_contiguous() && W.device() == x0.device(), "inkling_wide: bad weight"); if (fmt == kRaw) { TORCH_CHECK(W.scalar_type() == at::kBFloat16 && W.dim() == 2 && W.size(0) == N && W.size(1) == K, "inkling_wide: raw weight must be bf16 [N, K]"); } else { TORCH_CHECK(fmt == kBF16X && W.scalar_type() == at::kByte && W.dim() == 1, "inkling_wide: fmt ", fmt); const size_t T = (size_t)(N / 8) * (K / 32); TORCH_CHECK(T < (1ull << 31) && (size_t)W.numel() >= bf16x_raw_off(T), "inkling_wide: coded buffer too small"); TORCH_CHECK(K <= 96 * 32, "inkling_wide: bf16x needs K <= 3072 (headers held in 3 registers a lane)"); } TORCH_CHECK(reinterpret_cast<uintptr_t>(W.data_ptr()) % 16 == 0, "inkling_wide: weight not 16-byte aligned"); const bool f32 = out.scalar_type() == at::kFloat; TORCH_CHECK(out.is_cuda() && out.device() == x0.device() && out.dim() == 2 && (f32 || out.scalar_type() == at::kBFloat16), "inkling_wide: out must be CUDA fp32 / bf16 [rows, N]"); TORCH_CHECK(out.size(1) == N && out.stride(1) == 1 && out.stride(0) >= N && out.stride(0) % 2 == 0 && reinterpret_cast<uintptr_t>(out.data_ptr()) % (f32 ? 8 : 4) == 0, "inkling_wide: out rows must hold N contiguous, aligned values"); TORCH_CHECK(roff1 >= 0 && roff2 >= 0 && out.size(0) >= M && roff1 <= out.size(0) - M && roff2 <= out.size(0) - M, "inkling_wide: out has ", out.size(0), " rows, row offsets ", roff1, ", ", roff2, " with M=", M); auto overlaps = [](const torch::Tensor& a, const torch::Tensor& b) { const auto a0 = reinterpret_cast<uintptr_t>(a.data_ptr()), b0 = reinterpret_cast<uintptr_t>(b.data_ptr()); const auto a1 = a0 + (uintptr_t)((a.size(0) - 1) * a.stride(0) + a.size(1)) * a.element_size(); const auto b1 = b0 + (uintptr_t)((b.size(0) - 1) * b.stride(0) + b.size(1)) * b.element_size(); return a0 < b1 && b0 < a1; }; TORCH_CHECK(!overlaps(out, x0) && !overlaps(out, x1) && !overlaps(out, x2), "inkling_wide: out overlaps x"); auto bound_ok = [&](int64_t b) { return b >= N || (b >= 0 && b % kBN == 0); }; TORCH_CHECK(bound_ok(rb1) && bound_ok(rb2) && bound_ok(rb3) && rb1 <= rb2 && rb2 <= rb3, "inkling_wide: column regions must be multiples of ", kBN, " (or >= N)"); const int nblk = (int)((N + kBN - 1) / kBN); const int64_t NB = K / 64; TORCH_CHECK(S >= 1 && S <= NB && S <= 64, "inkling_wide: split-K S=", S, " not in [1, ", NB, "]"); if (S > 1) { TORCH_CHECK(ws.is_cuda() && ws.device() == x0.device() && ws.scalar_type() == at::kFloat && ws.is_contiguous() && ws.numel() >= S * M * N && reinterpret_cast<uintptr_t>(ws.data_ptr()) % 16 == 0, "inkling_wide: split-K workspace too small, misaligned or on another device"); TORCH_CHECK(cnt.is_cuda() && cnt.device() == x0.device() && cnt.scalar_type() == at::kInt && cnt.is_contiguous() && cnt.numel() >= nblk, "inkling_wide: split-K counters too few or on another device"); } const c10::cuda::CUDAGuard guard(x0.device()); Params p{}; p.x0 = reinterpret_cast<const __nv_bfloat16*>(x0.data_ptr()); p.x1 = reinterpret_cast<const __nv_bfloat16*>(x1.data_ptr()); p.x2 = reinterpret_cast<const __nv_bfloat16*>(x2.data_ptr()); p.ldx = x0.stride(0); p.M = (int)M; p.rb1 = (int)std::min<int64_t>(rb1, INT32_MAX); p.rb2 = (int)std::min<int64_t>(rb2, INT32_MAX); p.rb3 = (int)std::min<int64_t>(rb3, INT32_MAX); p.roff1 = roff1; p.roff2 = roff2; p.W = reinterpret_cast<const uint8_t*>(W.data_ptr()); p.N = (int)N; p.K = (int)K; p.out = out.data_ptr(); p.ldo = out.stride(0); p.f32 = f32 ? 1 : 0; p.S = (int)S; p.ws = S > 1 ? ws.data_ptr<float>() : nullptr; p.cnt = S > 1 ? cnt.data_ptr<int>() : nullptr; TORCH_CHECK(pfd >= 0 && pfd <= 64, "inkling_wide: prefetch distance ", pfd); p.pfd = (int)pfd; const auto st = at::cuda::getCurrentCUDAStream(); if (fmt == kRaw) launch_fmt<kRaw>(p, nblk, pdl, (int)mt, (int)mg, st); else launch_fmt<kBF16X>(p, nblk, pdl, (int)mt, (int)mg, st);}
// S=1 head only. Use exactly the same weight decoder, fragment order, and// accumulation loop as the dense launch, with a compact column map.#define CERT_WIDE_BUCKETS(X) \ X(2, 2) X(3, 2) X(4, 2) X(6, 2) X(8, 2) X(12, 1)
void prepare_certwide(int64_t device) { const c10::cuda::CUDAGuard guard((c10::DeviceIndex)device);#define CERT_ATTR(MI, MT) \ C10_CUDA_CHECK(cudaFuncSetAttribute(k_wide<kBF16X, MI, MT, 1, true>, \ cudaFuncAttributeMaxDynamicSharedMemorySize, Cfg<MI, MT, 1>::SMEM)); CERT_WIDE_BUCKETS(CERT_ATTR)#undef CERT_ATTR}
// Both exact branches and the Triton reducer read this state after validation.// The caller keeps the state and workspace exclusive through reduction.__global__ void k_validate_certwide(int* state, const int* tiles, const int* groups, int slots, int ntiles, int live_tiles, unsigned row_groups) { constexpr int kInvalid = 4; __shared__ int count; __shared__ unsigned seen; if (threadIdx.x == 0) { const int reason = state[0], n = state[1]; count = reason == 0 && n > 0 && n <= slots && n < ntiles ? n : 0; if ((!count && reason == 0) || (unsigned)reason > kInvalid) state[0] = kInvalid; seen = 0; } __syncthreads(); if (!count) return; unsigned mask = 0; for (int i = threadIdx.x; i < count; i += blockDim.x) { const unsigned group = groups[i]; if ((unsigned)tiles[i] >= (unsigned)live_tiles || !group || (group & ~row_groups)) mask |= 1u << 31; mask |= group; } mask = __reduce_or_sync(0xffffffffu, mask); if ((threadIdx.x & 31) == 0) atomicOr(&seen, mask); __syncthreads(); if (threadIdx.x == 0 && seen != row_groups) state[0] = kInvalid;}
void certwide_exact(const torch::Tensor& x, const torch::Tensor& W, const torch::Tensor& dense, const torch::Tensor& compact, const torch::Tensor& state, const torch::Tensor& tiles, const torch::Tensor& groups, int64_t N, int64_t v_real, int64_t mt, int64_t mg, int64_t pfd) { constexpr int K = 2304; TORCH_CHECK(x.dim() == 2, "inkling_certwide: x must be [M, K]"); const int64_t M = x.size(0), slots = tiles.numel(); TORCH_CHECK(M >= 17 && M <= 192 && N > 0 && N % 16 == 0 && N <= INT32_MAX && v_real > 0 && v_real <= N, "inkling_certwide: bad head shape"); check_x(x, M, K, W); auto same = [&](const torch::Tensor& t, at::ScalarType dt) { return t.is_cuda() && t.device() == x.device() && t.is_contiguous() && t.scalar_type() == dt; }; const size_t T = (size_t)(N / 8) * (K / 32); TORCH_CHECK(same(W, at::kByte) && W.dim() == 1 && T < (1ull << 31) && (size_t)W.numel() >= bf16x_raw_off(T) && reinterpret_cast<uintptr_t>(W.data_ptr()) % 16 == 0, "inkling_certwide: bad packed weight"); TORCH_CHECK(same(state, at::kInt) && state.numel() == 2 && same(tiles, at::kInt) && same(groups, at::kInt) && groups.numel() == slots && slots > 0 && slots <= N / 16 && same(dense, at::kFloat) && dense.dim() == 2 && dense.size(0) == M && dense.size(1) == N && same(compact, at::kFloat) && compact.dim() == 2 && compact.size(0) == M && compact.size(1) == slots * 16 && reinterpret_cast<uintptr_t>(dense.data_ptr()) % 8 == 0 && reinterpret_cast<uintptr_t>(compact.data_ptr()) % 8 == 0, "inkling_certwide: bad exact workspace"); TORCH_CHECK(mt >= 0 && mt <= 2 && mg >= 1 && mg <= 2 && pfd >= 0 && pfd <= 64, "inkling_certwide: bad kernel settings"); // Disjoint address ranges, even when the caller takes views of one storage. const torch::Tensor* buffers[] = {&x, &W, &dense, &compact, &state, &tiles, &groups}; TORCH_CHECK(x.is_contiguous(), "inkling_certwide: x must be contiguous"); for (int i = 0; i < 7; ++i) { const auto a = reinterpret_cast<uintptr_t>(buffers[i]->data_ptr()); for (int j = 0; j < i; ++j) { const auto b = reinterpret_cast<uintptr_t>(buffers[j]->data_ptr()); TORCH_CHECK(a + buffers[i]->nbytes() <= b || b + buffers[j]->nbytes() <= a, "inkling_certwide: aliased exact buffers"); } } const c10::cuda::CUDAGuard guard(x.device()); const auto st = at::cuda::getCurrentCUDAStream(); k_validate_certwide<<<1, 256, 0, st>>>(state.data_ptr<int>(), tiles.data_ptr<int>(), groups.data_ptr<int>(), slots, N / 16, (v_real + 15) / 16, (1u << ((M + 15) / 16)) - 1u); C10_CUDA_KERNEL_LAUNCH_CHECK(); Params p{}; p.x0 = reinterpret_cast<const __nv_bfloat16*>(x.data_ptr()); p.ldx = x.stride(0); p.M = (int)M; p.rb1 = p.rb2 = p.rb3 = INT32_MAX; p.W = W.data_ptr<uint8_t>(); p.N = (int)N; p.K = K; p.f32 = p.S = 1; p.pfd = (int)pfd; p.cert_state = state.data_ptr<int>(); p.out = dense.data_ptr<float>(); p.ldo = N; launch_fmt<kBF16X>(p, (N + kBN - 1) / kBN, false, (int)mt, (int)mg, st);
p.out = compact.data_ptr<float>(); p.ldo = slots * 16; p.cert_tiles = tiles.data_ptr<int>(); p.cert_groups = groups.data_ptr<int>(); const int nblk = (p.ldo + kBN - 1) / kBN; const int mi = bucket_of(p.M);#define CERT_LAUNCH(MI, MT) \ if (mi == MI) return launch_mi<kBF16X, MI, MT, 1, true>(p, nblk, false, st); CERT_WIDE_BUCKETS(CERT_LAUNCH)#undef CERT_LAUNCH TORCH_CHECK(false, "inkling_certwide: unsupported M=", M);}#undef CERT_WIDE_BUCKETS
torch::Tensor decode(const torch::Tensor& X, int64_t N, int64_t K) { TORCH_CHECK(X.is_cuda() && X.scalar_type() == at::kByte && X.is_contiguous(), "inkling_wide: bad coded buffer"); TORCH_CHECK(N > 0 && K > 0 && N % 8 == 0 && K % 32 == 0 && N <= INT32_MAX && K <= INT32_MAX, "inkling_wide: N=", N, " K=", K); TORCH_CHECK(reinterpret_cast<uintptr_t>(X.data_ptr()) % 16 == 0, "inkling_wide: coded buffer not 16-byte aligned"); const size_t T = (size_t)(N / 8) * (K / 32); TORCH_CHECK(T < (1ull << 31) && (size_t)X.numel() >= bf16x_raw_off(T), "inkling_wide: coded buffer too small"); const c10::cuda::CUDAGuard guard(X.device()); auto out = torch::empty({N, K}, X.options().dtype(at::kBFloat16)); k_decode<<<1024, 256, 0, at::cuda::getCurrentCUDAStream()>>>(X.data_ptr<uint8_t>(), (int)N, (int)K, reinterpret_cast<__nv_bfloat16*>(out.data_ptr())); C10_CUDA_KERNEL_LAUNCH_CHECK(); return out;}
void prepare(int64_t device) { const c10::cuda::CUDAGuard guard((c10::DeviceIndex)device); prepare_fmt<kRaw>(); prepare_fmt<kBF16X>();}
// (registers, local bytes, max threads) of the kernel at fmt / bucket, for the build logstd::tuple<int64_t, int64_t, int64_t> kernel_info(int64_t fmt, int64_t M, int64_t mt, int64_t mg) { cudaFuncAttributes a{}; const int MI = bucket_of((int)M); TORCH_CHECK(MI > 0, "inkling_wide: M=", M); const int key = key_of(MI, (int)mt, (int)mg); const void* f = nullptr;#define WIDE_INFO(F, MI_, MT_, MG_) \ if (key == kkey(MI_, MT_, MG_)) f = (const void*)k_wide<F, MI_, MT_, MG_>; if (fmt == kRaw) { WIDE_KERNELS(WIDE_INFO, kRaw) } else { WIDE_KERNELS(WIDE_INFO, kBF16X) }#undef WIDE_INFO TORCH_CHECK(f != nullptr, "inkling_wide: no kernel for M=", M, " mt=", mt, " mg=", mg); C10_CUDA_CHECK(cudaFuncGetAttributes(&a, f)); return {a.numRegs, (int64_t)a.localSizeBytes, a.maxThreadsPerBlock};}
} // namespace wide
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.doc() = "inkling_wide: weight-streaming BF16 GEMM for 17..256 rows on raw or pico-coded (bf16x) weights"; m.def("gemm", &wide::gemm, "out[roff + m, n] = x_src[m] . W[n] (see wide_ext.cu)"); m.def("decode", &wide::decode, "bf16x coded buffer -> natural [N, K] bf16 (the kernel's reader)"); m.def("prepare_certwide", &wide::prepare_certwide, "prepare the sparse packed head kernels"); m.def("certwide_exact", &wide::certwide_exact, "guarded dense or compact packed head with FP32 outputs"); m.def("prepare", &wide::prepare, "set the kernels' shared-memory attribute on a device (load time)"); m.def("bucket", &wide::bucket_of, "m16 tiles of the kernel taking M rows"); m.def("kernel_info", &wide::kernel_info, "(regs, local bytes, max threads) of a kernel"); m.attr("max_rows") = wide::kMaxM; m.attr("block_n") = wide::kBN;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313"""Weights registered for the wide GEMM and the per-call paths (17..MAX_M rows).
A Wide entry points at the bytes the kernel streams: the layer's own BF16 weight (fmt RAW, natural [N, K]layout, no copy) or inkling_pico12's exactly coded copy of it (fmt BF16X, pico's `bf16x` format, ~0.775 of thebytes; read in place, never copied). Both formats give the same output bits (the decode restores the BF16values exactly and the MMA sequence is the same).
Math: out[m, n] = sum_k x[m, k] W[n, k], BF16 operands, FP32 accumulation over K in a fixed order (per 32-valuestep: two m16n8k16 MMAs; split-K slices summed in slice order), FP32 out or one rounding to BF16. Against the stockpath (cuBLAS) only the FP32 summation order differs.
Per call: torch.empty outputs (the graph pool under capture), one launch on the current stream, no host sync, nohost-device copy, a path chosen by shapes only; the split-K workspace and counters are allocated at load time."""
import torch
MAX_ROWS = 256 # rows the kernel takes (dsk-style buckets of 16..256)BLOCK_N = 128 # weight rows per CTA: stacked-region bounds must be multiples of itRAW, BF16X = 0, 2NO_REGION = 2**31 - 1
class Settings: min_m = 17 # rows of a call taken (plain calls; per source for stacked q/k/v calls) max_m = 256 # per weight kind: rows up to which wide beats cuBLAS on GB10 (gpu_check_wide, 2026-11-21, L2-cold): qkvr # 1.02x at 96 rows (stacked 1.13x at 85 per source), wo_ud 1.06x at 32 / 1.00x at 48, the head 1.18x at 256 max_m_kind = {"qkvr": 96, "wo": 32, "head": 256} pdl = True fmt = "auto" # auto: pico's coded copy when inkling_pico12 made one, else the raw weight; raw: always raw splitk = {} # kind -> forced split-K slices (env INKLING_WIDE_SPLITK) sms = 48 mt = 0 # tiles per warp above 128 rows: 0 = the kernel's default (1), 1 or 2 (env INKLING_WIDE_MT) mg = 2 # warp groups along M at 65..128 rows: 2 (default; wo 96 rows 89 -> 76 us, qkvr flat) or 1 (env INKLING_WIDE_MG) scope = "verify" # verify: only inside target decode / target-verify forwards (env INKLING_WIDE_SCOPE); all pfd = 1 # L2 prefetch distance in 64-value batches (env INKLING_WIDE_PFD; 0 = off): 1 best or flat everywhere require_cuda = True # CPU tests turn this off and install a stand-in EXT
SET = Settings()EXT = None_batch_invariant = None_warned = set()LOG = NoneWS = {"ws": None, "cnt": None}# True while the target model runs a decode or target-verify forward (set by the patched# Inkling2ForConditionalGeneration.forward from forward_batch.forward_mode, a Python attribute fixed at CUDA-graph# capture). With SET.scope == "verify" wide takes calls only then: prefill / extend chunks keep the stock path.IN_SCOPE = [False] # split-K workspace (FP32) and counters (int32), shared by every call
class WideFatal(BaseException): """A broken patch target or an impossible state: not caught by `except Exception`."""
def _warn_once(key, msg): if key not in _warned: _warned.add(key) if LOG is not None: LOG(msg)
def bucket(m): """m16 tiles of the kernel for m rows (the kernel's buckets).""" need = (m + 15) // 16 for b in (1, 2, 3, 4, 6, 8, 12, 16): if b >= need: return b raise ValueError(f"inkling_wide: {m} rows > {MAX_ROWS}")
def ctas_per_sm(m): """The occupancy the kernel is built for at m rows (launch bounds: 2 CTAs up to 64 rows).""" return 2 if bucket(m) <= 4 else 1
def choose_split(n, k, m, kind=None): """Split-K slices for an [n, k] weight at m rows: forced per kind (INKLING_WIDE_SPLITK), else from the GB10 sweep (gpu_check_wide --sweep, 2026-11-21): no split once the column blocks (128 rows each) cover the SMs (qkvr: 68 blocks, the head: 1571; every split measured slower); below that, enough slices for one CTA per SM up to 64 rows (wo_ud, 18 blocks: 3 slices; 4 measured within 2 %) and two thirds of that above (2 slices), where the FP32 partials' traffic starts to cost more than idle SMs. The partials must fit in L2.""" nb = k // 64 if kind is not None and kind in SET.splitk: return max(1, min(SET.splitk[kind], nb)) nblk = -(-n // BLOCK_N) if nblk >= SET.sms: return 1 want = SET.sms / nblk if m <= 64 else SET.sms / nblk / 1.5 s = max(1, min(-(-int(want * 1000) // 1000), nb // 4, 16)) while s > 1 and s * m * n * 4 > 24 * 2**20: s -= 1 return s
def shape_reason(n, k): if n % 8: return f"N={n} not a multiple of 8" if k % 64: return f"K={k} not a multiple of 64" if n >= 2**31 or k >= 2**31: return f"[{n}, {k}] too large" return None
class Wide: """One weight the wide GEMM reads: RAW (the BF16 tensor) or BF16X (pico's Pack, read through .buf)."""
__slots__ = ("n", "k", "fmt", "weight", "pack", "wptr", "label", "kind")
def __init__(self, weight, label, kind, pack=None): n, k = weight.shape self.n, self.k, self.label, self.kind = n, k, label, kind self.fmt = BF16X if pack is not None else RAW self.weight, self.pack = weight, pack self.wptr = weight.data_ptr()
def workspace_floats(self, min_m, max_m): """FP32 partials the largest split call of min_m..max_m rows needs (0: never splits).""" need = 0 for m in range(min_m, max_m + 1): s = choose_split(self.n, self.k, m, self.kind) if s > 1: need = max(need, s * m * self.n) return need
@property def buf(self): return self.pack.buf if self.fmt == BF16X else self.weight
@property def nbytes(self): return self.buf.numel() * self.buf.element_size()
def __repr__(self): return f"Wide({self.label} [{self.n}x{self.k}] {'bf16x' if self.fmt == BF16X else 'raw'} {self.kind})"
def make(weight, label, kind, pico_pack=None): """Register [N, K] BF16 `weight`; pico_pack (inkling_pico12's Pack of the same storage) selects BF16X.""" w = weight.detach() if w.dtype != torch.bfloat16 or w.dim() != 2: raise ValueError(f"inkling_wide: {label}: not a BF16 matrix") why = shape_reason(*w.shape) if why is not None: raise ValueError(f"inkling_wide: {label}: {why}") if not w.is_contiguous() or w.data_ptr() % 16: raise ValueError(f"inkling_wide: {label}: weight not contiguous or not 16-byte aligned") # the kernel holds a bf16x tile row's headers in 3 registers a lane: K <= 3072 (larger K reads the raw weight) use_pack = pico_pack is not None and SET.fmt == "auto" and w.shape[1] <= 3072 if use_pack and ((pico_pack.n, pico_pack.k) != tuple(w.shape) or pico_pack.wptr != w.data_ptr()): raise WideFatal(f"inkling_wide: {label}: inkling_pico12's pack is not of this weight") return Wide(w, label, kind, pico_pack if use_pack else None)
def ensure_workspace(entries, min_m, max_m, device, grow=False, floats=0): """Allocate (load time) the split-K workspace (FP32) and counters (int32, zero) for every entry that may split in min_m..max_m rows. The buffers are process-wide and referenced by captured CUDA graphs: they are never replaced unless `grow` (offline tools); a reload that needs more raises WideFatal (restart the server). Calls must not run concurrently on two streams (SGLang's forward runs on one).""" need = max([floats] + [e.workspace_floats(min_m, max_m) for e in entries]) nblk = max([1] + [-(-e.n // BLOCK_N) for e in entries]) ws, cnt = WS["ws"], WS["cnt"] if ws is None or (grow and (ws.numel() < need or cnt.numel() < nblk)): WS["ws"] = torch.empty(max(need, 4), dtype=torch.float32, device=device) WS["cnt"] = torch.zeros(max(nblk, 64), dtype=torch.int32, device=device) elif ws.numel() < need or cnt.numel() < nblk: raise WideFatal(f"inkling_wide: split-K workspace of {ws.numel()} floats / {cnt.numel()} counters (captured in " f"CUDA graphs) cannot hold {need} / {nblk} after a reload: restart the server") return 4 * WS["ws"].numel()
def mode_ok(): if torch.compiler.is_compiling(): return False return not (_batch_invariant is not None and _batch_invariant())
def rows_of(x): return x.numel() // x.shape[-1] if x.dim() >= 1 and x.shape[-1] else 0
def x_ok(x, k): return ( x.dtype == torch.bfloat16 and x.dim() >= 1 and x.shape[-1] == k and (x.is_cuda or not SET.require_cuda) and not x.requires_grad )
def in_range(m, kind=None): if SET.scope == "verify" and not IN_SCOPE[0]: return False return SET.min_m <= m <= min(SET.max_m, SET.max_m_kind.get(kind, SET.max_m))
def weight_current(weight, entry): if weight.data_ptr() == entry.wptr and (entry.fmt == RAW or entry.pack.wptr == entry.wptr): return True _warn_once(("wptr", entry.label), f"{entry.label}: weight storage changed since registration; stock path from now on") return False
def eligible(x, entry): return ( in_range(rows_of(x), entry.kind) and x_ok(x, entry.k) and (x.device == entry.weight.device or not SET.require_cuda) and mode_ok() )
def as_rows(x, k): """x[..., K] as [M, K] with unit column stride and 16-byte aligned rows (a copy only when x is not).""" x2 = x.reshape(-1, k) if x2.stride(-1) != 1 or (x2.shape[0] > 1 and x2.stride(0) != k): x2 = x2.contiguous() if x2.data_ptr() % 16: x2 = x2.clone() return x2
def out_ok(out, m, entry, dtype, device): return ( out.dtype == dtype and out.device == device and out.dim() == 2 and tuple(out.shape) == (m, entry.n) and out.stride(-1) == 1 and (m == 1 or out.stride(0) == entry.n) and out.data_ptr() % (8 if dtype == torch.float32 else 4) == 0 )
def gemm(x2, entry, out, m, x1=None, x2b=None, regions=(NO_REGION, NO_REGION, NO_REGION), roffs=(0, 0)): s = choose_split(entry.n, entry.k, m, entry.kind) EXT.gemm( x2, x2 if x1 is None else x1, x2 if x2b is None else x2b, m, entry.buf, entry.fmt, entry.n, entry.k, regions[0], regions[1], regions[2], roffs[0], roffs[1], out, s, WS["ws"], WS["cnt"], SET.pdl, SET.mt, SET.mg, SET.pfd, ) return out
def linear(x, entry, out_dtype, out=None): """x[..., K] @ W^T in out_dtype, into `out` ([M, N], checked by the caller) when given.""" lead = x.shape[:-1] x2 = as_rows(x, entry.k) m = x2.shape[0] if out is None: out = torch.empty((m, entry.n), dtype=out_dtype, device=x.device) gemm(x2, entry, out, m) return out.view(*lead, entry.n)
# ---- stacked qkvr ---------------------------------------------------------------------------------------
def regions_of(split_sizes): """Column regions (k_lo, v_lo, v_hi) of the k and v outputs of the qkvr projection (split order q, k, v, ...), or None if a bound is not a multiple of BLOCK_N (a CTA must serve one source).""" if len(split_sizes) < 3: return None a = int(split_sizes[0]) b = a + int(split_sizes[1]) c = b + int(split_sizes[2]) if a % BLOCK_N or b % BLOCK_N or c % BLOCK_N or not 0 < a < b < c: return None return a, b, c
def stacked_eligible(sources, entry, regions): q, k, v = sources if regions is None or q.dim() != 2 or not (q.shape == k.shape == v.shape): return False if not (q.dtype == k.dtype == v.dtype == torch.bfloat16) or not (q.device == k.device == v.device): return False return ( in_range(q.shape[0], entry.kind) and x_ok(q, entry.k) and (q.device == entry.weight.device or not SET.require_cuda) and not k.requires_grad and not v.requires_grad and mode_ok() )
def _rows(x, k): """x as [M, K] with rows of stride K (the three sources must share one row stride).""" if x.stride(-1) != 1 or (x.shape[0] > 1 and x.stride(0) != k) or x.data_ptr() % 16: x = x.contiguous() if x.data_ptr() % 16: x = x.clone() return x
def stacked_project(q, k, v, entry, regions): """BF16 [3M, N] with what qkvr(cat(q, k, v))[0] holds on every element Inkling2Attention._project_sources keeps: rows [0, M) on every column outside [k_lo, v_hi), rows [M, 2M) on the k columns, rows [2M, 3M) on the v columns, from one read of the weight. The other elements are left unwritten (never read).""" m = q.shape[0] q2, k2, v2 = _rows(q, entry.k), _rows(k, entry.k), _rows(v, entry.k) out = torch.empty((3 * m, entry.n), dtype=torch.bfloat16, device=q.device) return gemm(q2, entry, out, m, x1=k2, x2b=v2, regions=regions, roffs=(m, 2 * m))
def split_like_stock(out, split_sizes): """The (q, k, v, r, gate, sinks) views _project_sources returns for a stacked [3M, N] projection.""" q_proj, k_proj, v_proj = (chunk.split(split_sizes, dim=-1)[:6] for chunk in out.chunk(3)) q, _, _, r, gate, sinks = q_proj return q, k_proj[1], v_proj[2], r, gate, sinks123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397"""The SGLang patch points of inkling_wide (README.md has the list and the exactness argument).
unquant UnquantizedLinearMethod: a per-layer subclass (of whatever method class the layer has then, e.g. inkling_pico12's) whose apply / apply_into send calls of MIN_M..MAX_M rows of a registered layer to the wide GEMM; sm12x_fp32_lm_head(_applies): the FP32 LM head at MIN_M..MAX_M rows inkling2_attn Inkling2Attention._project_sources: the stacked q/k/v case (three distinct [M, K] sources) inkling2 Inkling2ForConditionalGeneration.post_load_weights: register the weights after every (re)load (after inkling_pico12 coded them, when it is armed: install inkling_wide after it)
Every patch falls back to the function it replaced for anything it does not take."""
import copyimport functoolsimport importlibimport sysimport time
import torch
from . import build, ops
UNQUANT = "sglang.srt.layers.quantization.unquant"ATTN = "sglang.srt.models.inkling_common.inkling2_attn"MODEL = "sglang.srt.models.inkling2"
STATE = {"levers": (), "cfg": None, "log": None, "patched": []}HEADS = {} # weight data_ptr -> Wide of the BF16 LM headEXIT = None # tests replace it; default os._exit
def _log(msg): (STATE["log"] or (lambda m: sys.stderr.write(m + "\n")))(msg)
def _exit(code): import os
(EXIT or os._exit)(code)
def _need(owner, names, where): missing = [n for n in names if getattr(owner, n, None) is None] if missing: raise ops.WideFatal(f"inkling_wide: patch target {where} lacks {missing}")
def _guarded(fn): """Run load-time work; any failure ends the process with code 78 (a half-armed overlay must not serve)."""
@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 in {fn.__name__}: {exc!r}") sys.stderr.flush() _exit(78) raise
return run
def _ext(): if ops.EXT is None: cfg = STATE["cfg"] ext = build.load(cfg["cache_dir"], verbose=cfg["verbose"]) ext.prepare(torch.cuda.current_device()) ops.EXT = ext return ops.EXT
_MARKERS = ("inkling_cfg", "inkling_pico12", "inkling_prefill_qkvr_split")
def _forward_markers(new, inner): """Keep the other _project_sources overlays' markers visible through our wrapper (as inkling_prefill does), so that none of them wraps a second time.""" for attr in _MARKERS: if hasattr(inner, attr): setattr(new, attr, getattr(inner, attr))
# ---- quant method subclass ----------------------------------------------------------------------------
_METHOD_CLASSES = {}
def method_class(base): """Subclass of a linear method class whose apply / apply_into run the wide GEMM for a registered layer.""" if getattr(base, "_wide_class", False): return base sub = _METHOD_CLASSES.get(base) if sub is not None: return sub base_apply = base.apply base_apply_into = getattr(base, "apply_into", None)
def apply(self, layer, x, bias=None): entry = layer.__dict__.get("_wide") if entry is not None and bias is None and ops.eligible(x, entry) and ops.weight_current(layer.weight, entry): return ops.linear(x, entry, x.dtype) return base_apply(self, layer, x, bias)
ns = {"apply": apply, "_wide_class": True, "__module__": __name__} if base_apply_into is not None:
def apply_into(self, layer, x, output, bias=None): entry = layer.__dict__.get("_wide") if ( entry is not None and bias is None and x.dim() == 2 and ops.eligible(x, entry) and ops.out_ok(output, x.shape[0], entry, torch.bfloat16, x.device) and ops.weight_current(layer.weight, entry) ): ops.gemm(ops.as_rows(x, entry.k), entry, output, x.shape[0]) return output return base_apply_into(self, layer, x, output, bias=bias)
ns["apply_into"] = apply_into sub = type("Wide" + base.__name__, (base,), ns) _METHOD_CLASSES[base] = sub return sub
def _unquantized_class(): mod = sys.modules.get(UNQUANT) or importlib.import_module(UNQUANT) cls = getattr(mod, "UnquantizedLinearMethod", None) if cls is None: raise ops.WideFatal(f"inkling_wide: {UNQUANT}.UnquantizedLinearMethod is missing") return cls
def linear_reason(layer): w = getattr(layer, "weight", None) if not isinstance(w, torch.Tensor) or w.dim() != 2 or w.dtype != torch.bfloat16: return "weight is not a BF16 matrix" if getattr(layer, "bias", None) is not None: return "has a bias" method = getattr(layer, "quant_method", None) if method is None or not isinstance(method, _unquantized_class()): return f"quant method {type(method).__name__}" if not w.is_contiguous(): return "weight not contiguous" return ops.shape_reason(*w.shape)
def _pico_wants(layer): """True if inkling_pico12 is armed for the target's dense layers (its pack must then exist).""" pico = sys.modules.get("inkling_pico12") return pico is not None and "dense" in tuple(getattr(pico, "STATE", {}).get("levers", ()))
def register_linear(layer, label, kind): """Register layer.weight for the wide GEMM and give the layer the wide method. Returns (entry, reason).""" why = linear_reason(layer) if why is not None: layer.__dict__.pop("_wide", None) return None, why pack = layer.__dict__.get("_pico12") if pack is None and ops.SET.fmt == "auto" and _pico_wants(layer): raise ops.WideFatal( f"inkling_wide: {label} has no inkling_pico12 pack although inkling_pico12 dense is armed: install " "inkling_wide after inkling_pico12 (its post_load_weights wrapper must run after pico's)" ) entry = ops.make(layer.weight, label, kind, pack) layer.__dict__["_wide"] = entry method = layer.quant_method if not getattr(type(method), "_wide_class", False): new = copy.copy(method) new.__class__ = method_class(type(method)) for attr in ("apply", "apply_into"): # instance-level wrappers would shadow ours new.__dict__.pop(attr, None) layer.quant_method = new return entry, None
# ---- unquant: LM head ---------------------------------------------------------------------------------
def make_lm_head(inner_fn, inner_applies): def entry_for(x, weight, out): if not isinstance(weight, torch.Tensor) or weight.dim() != 2: return None entry = HEADS.get(weight.data_ptr()) if entry is None or tuple(weight.shape) != (entry.n, entry.k) or not ops.eligible(x, entry): return None if out is not None and not ops.out_ok(out, ops.rows_of(x), entry, torch.float32, x.device): return None if not ops.weight_current(weight, entry): return None return entry
def sm12x_fp32_lm_head_applies(x, weight, out): return entry_for(x, weight, out) is not None or inner_applies(x, weight, out)
def sm12x_fp32_lm_head(x, weight, out): entry = entry_for(x, weight, out) if entry is None: return inner_fn(x, weight, out) return ops.linear(x, entry, torch.float32, out=out)
sm12x_fp32_lm_head.__wrapped__ = inner_fn sm12x_fp32_lm_head_applies.__wrapped__ = inner_applies sm12x_fp32_lm_head._wide = sm12x_fp32_lm_head_applies._wide = True return sm12x_fp32_lm_head, sm12x_fp32_lm_head_applies
def patch_unquant(mod): levers = STATE["levers"] _need(mod, ["UnquantizedLinearMethod", "is_batch_invariant_mode_enabled"], UNQUANT) _need(mod.UnquantizedLinearMethod, ["apply", "apply_into"], f"{UNQUANT}.UnquantizedLinearMethod") ops._batch_invariant = mod.is_batch_invariant_mode_enabled if "lmhead" in levers: _need(mod, ["sm12x_fp32_lm_head", "sm12x_fp32_lm_head_applies"], UNQUANT) if not getattr(mod.sm12x_fp32_lm_head, "_wide", False): fn, applies = make_lm_head(mod.sm12x_fp32_lm_head, mod.sm12x_fp32_lm_head_applies) mod.sm12x_fp32_lm_head, mod.sm12x_fp32_lm_head_applies = fn, applies STATE["patched"].append("unquant.sm12x_fp32_lm_head")
# ---- inkling2_attn: stacked qkvr ------------------------------------------------------------------------
def make_project_sources(inner): def _project_sources(self, sources): plan = self.__dict__.get("_wide_qkvr") if plan is not None: entry, regions = plan q, k, v = sources.q, sources.k, sources.v if ( len({id(q), id(k), id(v)}) == 3 and ops.stacked_eligible((q, k, v), entry, regions) and ops.weight_current(self.qkvr.weight, entry) ): out = ops.stacked_project(q, k, v, entry, regions) return ops.split_like_stock(out, self.split_sizes) return inner(self, sources)
_project_sources.__wrapped__ = inner _project_sources.inkling_wide = True _forward_markers(_project_sources, inner) return _project_sources
def patch_attn(mod): _need(mod, ["Inkling2Attention", "AttentionSources"], ATTN) cls = mod.Inkling2Attention _need(cls, ["_project_sources", "_project_qkvr"], f"{ATTN}.Inkling2Attention") if getattr(cls._project_sources, "inkling_wide", False): return cls._project_sources = make_project_sources(cls._project_sources) STATE["patched"].append("Inkling2Attention._project_sources")
# ---- inkling2: register the target's weights after every load -------------------------------------------
def _mb(n): return f"{n / 1e6:.1f} MB"
def _settings_text(): s = ops.SET caps = ",".join(f"{k}={v}" for k, v in s.max_m_kind.items()) return (f"min_m={s.min_m} max_m={s.max_m} ({caps}) scope={s.scope} fmt={s.fmt} pdl={int(s.pdl)} mg={s.mg} " f"pfd={s.pfd} " f"splitk={s.splitk or 'auto'}")
def prepare_target(model): levers = STATE["levers"] t0 = time.monotonic() _ext() t_ext = time.monotonic() - t0 entries, parts, skipped = [], [], {} device = None if "dense" in levers: attn_cls = getattr(sys.modules.get(ATTN), "Inkling2Attention", None) if attn_cls is None: raise ops.WideFatal(f"inkling_wide: {ATTN} not imported at weight load") n_q = n_wo = n_st = n_x = 0 for name, mod in model.named_modules(): if not isinstance(mod, attn_cls): continue e, why = register_linear(mod.qkvr, f"{name}.qkvr", "qkvr") if e is None: skipped[f"{name}.qkvr"] = why mod.__dict__.pop("_wide_qkvr", None) else: n_q += 1 n_x += e.fmt == ops.BF16X entries.append(e) device = e.weight.device regions = ops.regions_of(mod.split_sizes) if regions is not None: mod.__dict__["_wide_qkvr"] = (e, regions) n_st += 1 else: mod.__dict__.pop("_wide_qkvr", None) e, why = register_linear(mod.wo_ud, f"{name}.wo_ud", "wo") if e is None: skipped[f"{name}.wo_ud"] = why else: n_wo += 1 n_x += e.fmt == ops.BF16X entries.append(e) device = e.weight.device if n_q + n_wo == 0: raise ops.WideFatal("inkling_wide: dense is on but no Inkling2Attention qkvr / wo_ud was registered") parts.append(f"dense: qkvr {n_q} (stacked {n_st}) wo_ud {n_wo}, bf16x {n_x}/{n_q + n_wo}") if "lmhead" in levers: lm_head = getattr(getattr(model, "llm", None), "lm_head", None) w = getattr(lm_head, "weight", None) if not isinstance(w, torch.Tensor) or w.dim() != 2 or w.dtype != torch.bfloat16: raise ops.WideFatal(f"inkling_wide: lm head weight is {type(w).__name__} {getattr(w, 'dtype', '')}, " "not a BF16 matrix") pico_heads = getattr(sys.modules.get("inkling_pico12.patches"), "HEADS", {}) or {} pack = pico_heads.get(w.data_ptr()) pico = sys.modules.get("inkling_pico12") pico_head = pico is not None and {"lmhead", "drafthead"} & set(getattr(pico, "STATE", {}).get("levers", ())) if pack is None and ops.SET.fmt == "auto" and pico_head: raise ops.WideFatal("inkling_wide: the LM head has no inkling_pico12 pack although inkling_pico12 " "lmhead is armed: install inkling_wide after inkling_pico12") e = ops.make(w, "lm_head", "head", pack) HEADS.clear() HEADS[e.wptr] = e entries.append(e) device = e.weight.device parts.append(f"head [{e.n}x{e.k}] {'bf16x' if e.fmt == ops.BF16X else 'raw'}") if device is not None and device.type == "cuda": ops.SET.sms = torch.cuda.get_device_properties(device).multi_processor_count ws_bytes = ops.ensure_workspace(entries, ops.SET.min_m, ops.SET.max_m, device) if device is not None else 0 skip = "" if skipped: first = "; ".join(f"{k}: {v}" for k, v in list(skipped.items())[:3]) skip = f"; skipped {len(skipped)} ({first}{' ...' if len(skipped) > 3 else ''})" info = build.INFO how = f"ext {'reused' if info.get('cached') else 'built'} in {t_ext:.1f} s ({info.get('build_dir')})" if info \ else "ext stand-in" _log( f"active (target): {', '.join(parts)}; split-K workspace {_mb(ws_bytes)}{skip}; patched " f"{', '.join(STATE['patched']) or 'nothing'}; {how}; {_settings_text()}" )
def is_in_scope(forward_batch): """Decode or target-verify forward (the forward modes wide is built for).""" mode = getattr(forward_batch, "forward_mode", None) if mode is None: return False try: return bool(mode.is_decode() or mode.is_target_verify()) except AttributeError: return False
def make_forward(inner): """Mark the target forward's scope for ops.in_range (restored afterwards, also on error)."""
@functools.wraps(inner) def forward(self, input_ids, positions, forward_batch, *args, **kwargs): prev = ops.IN_SCOPE[0] ops.IN_SCOPE[0] = is_in_scope(forward_batch) try: return inner(self, input_ids, positions, forward_batch, *args, **kwargs) finally: ops.IN_SCOPE[0] = prev
forward._wide = True return forward
def patch_model(mod): _need(mod, ["Inkling2ForConditionalGeneration"], MODEL) cls = mod.Inkling2ForConditionalGeneration _need(cls, ["post_load_weights", "forward"], f"{MODEL}.Inkling2ForConditionalGeneration") if not getattr(cls.forward, "_wide", False): cls.forward = make_forward(cls.forward) STATE["patched"].append("Inkling2ForConditionalGeneration.forward (scope)") orig = cls.post_load_weights if getattr(orig, "_wide", False): return
@functools.wraps(orig) def post_load_weights(self, *args, **kwargs): result = orig(self, *args, **kwargs) _guarded(prepare_target)(self) return result
post_load_weights._wide = True cls.post_load_weights = post_load_weights STATE["patched"].append("Inkling2ForConditionalGeneration.post_load_weights")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""CPU stand-in of the built inkling_wide extension: the call contract of wide_ext.cu's gemm() (rows, strides,regions, split-K workspace) with reference math (BF16 operands, FP32 sums, one rounding), and a call log.
fmt 2 (bf16x) reads the weight through inkling_pico12's CPU stand-in buffer (the weight's own bytes, then pad)."""import torch
NO_REGION = 2**31 - 1
class FakeWideExt: max_rows = 256 block_n = 128
def __init__(self): self.calls = [] # (M, N, K, fmt, out dtype, S, stacked)
@staticmethod def bucket(m): need = (m + 15) // 16 for b in (1, 2, 3, 4, 6, 8, 12, 16): if b >= need: return b return -1
def prepare(self, device=0): pass
@staticmethod def weight_of(W, fmt, n, k): if fmt == 0: assert W.dtype == torch.bfloat16 and tuple(W.shape) == (n, k) and W.is_contiguous() return W assert fmt == 2 and W.dtype == torch.uint8 and W.dim() == 1 return W[: n * k * 2].view(torch.bfloat16).view(n, k)
def gemm(self, x0, x1, x2, M, W, fmt, N, K, rb1, rb2, rb3, roff1, roff2, out, S, ws, cnt, pdl, mt, mg, pfd): assert mt in (0, 1, 2) and mg in (0, 1, 2) and 0 <= pfd <= 64 assert 1 <= M <= 256, M assert N % 8 == 0 and K % 64 == 0 for x in (x0, x1, x2): assert x.dtype == torch.bfloat16 and x.dim() == 2 and x.shape[0] >= M and x.shape[1] == K assert x.stride(1) == 1 and x.stride(0) % 8 == 0 and x.data_ptr() % 16 == 0 assert x0.stride(0) == x1.stride(0) == x2.stride(0) assert out.dim() == 2 and out.shape[1] == N and out.stride(1) == 1 and out.stride(0) >= N assert out.dtype in (torch.float32, torch.bfloat16) assert out.shape[0] >= M + max(0, roff1, roff2) for b in (rb1, rb2, rb3): assert b >= N or b % 128 == 0, b assert rb1 <= rb2 <= rb3 assert 1 <= S <= K // 64 if S > 1: assert ws.dtype == torch.float32 and ws.numel() >= S * M * N nblk = -(-N // 128) assert cnt.dtype == torch.int32 and cnt.numel() >= nblk and int(cnt[:nblk].abs().sum()) == 0 w = self.weight_of(W, fmt, N, K).float() for c0 in range(0, N, 128): src = 1 if rb1 <= c0 < rb2 else 2 if rb2 <= c0 < rb3 else 0 x = (x0, x1, x2)[src][:M].float() r0 = (0, roff1, roff2)[src] c1 = min(N, c0 + 128) out[r0 : r0 + M, c0:c1] = (x @ w[c0:c1].T).to(out.dtype) self.calls.append((M, N, K, fmt, out.dtype, S, rb1 < N))
def reset(self): self.calls.clear()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508"""CPU unit tests of inkling_wide's Python side (torch CPU; no GPU, no nvcc, no sglang).
python3 -m unittest discover -s inkling_wide/tests -v (from overlay/)
The CUDA kernel is not run here (inkling_wide/tools/gpu_check_wide.py checks it on the Spark). A stand-in extension(fake_wide_ext.py) keeps the kernel's call contract and computes reference math; the stand-in sglang package andpico extension of tests/pico12 carry the stock code of the patched functions and inkling_pico12's packs. Covered:lever / settings parsing, the source checks, bucket and split-K choice, stacked regions, the dispatch of everypatch point (row range, bias, grad, batch-invariant mode, out shapes), the stacked view layout, the LM headwrapper, the composition with inkling_pico12 (pico <= 16 rows, wide above, bf16x buffers shared) and the wronginstall order (exit 78), reloads, and the no-op contract."""
import osimport sysimport typesimport unittest
import torch
HERE = os.path.dirname(os.path.abspath(__file__))OVERLAY = os.path.dirname(os.path.dirname(HERE))PICO_TESTS = os.path.join(OVERLAY, "tests", "pico12")FAKE_ROOT = os.path.join(PICO_TESTS, "fake_sglang")for p in (OVERLAY, FAKE_ROOT, PICO_TESTS, HERE): if p not in sys.path: sys.path.insert(0, p)
import inkling_pico12 # noqa: E402import inkling_wide # noqa: E402from fake_ext import FakeExt # noqa: E402 (inkling_pico12's stand-in)from fake_wide_ext import FakeWideExt # noqa: E402from inkling_pico12 import ops as pops # noqa: E402from inkling_pico12 import patches as ppatches # noqa: E402from inkling_wide import ops, patches # noqa: E402from sglang.srt import batch_invariant_ops # noqa: E402from sglang.srt.layers.quantization import unquant as uq # noqa: E402from sglang.srt.models import inkling2 # noqa: E402from sglang.srt.models.inkling_common import inkling2_attn as attn_mod # noqa: E402
STOCK_PROJECT = attn_mod.Inkling2Attention._project_sourcesSTOCK_HEAD = (uq.sm12x_fp32_lm_head, uq.sm12x_fp32_lm_head_applies)STOCK_POST_LOAD = inkling2.Inkling2ForConditionalGeneration.post_load_weightsSTOCK_FORWARD = inkling2.Inkling2ForConditionalGeneration.forwardWEXT = FakeWideExt()PEXT = FakeExt()LOGS = []EXITS = []
def restore_sglang(): attn_mod.Inkling2Attention._project_sources = STOCK_PROJECT uq.sm12x_fp32_lm_head, uq.sm12x_fp32_lm_head_applies = STOCK_HEAD inkling2.Inkling2ForConditionalGeneration.post_load_weights = STOCK_POST_LOAD inkling2.Inkling2ForConditionalGeneration.forward = STOCK_FORWARD
def configure(levers=("dense", "lmhead"), min_m=17, max_m=256, fmt="auto", splitk=None, scope="all"): restore_sglang() ops.SET.scope = scope ops.IN_SCOPE[0] = False ops.EXT = WEXT ops.SET.require_cuda = False ops.SET.min_m, ops.SET.max_m, ops.SET.fmt = min_m, max_m, fmt ops.SET.max_m_kind = {} ops.SET.splitk = dict(splitk or {}) ops.SET.sms = 48 ops.SET.pdl = True ops.LOG = LOGS.append ops._batch_invariant = batch_invariant_ops.is_batch_invariant_mode_enabled ops._warned.clear() ops.WS.update(ws=None, cnt=None) patches.STATE.update(levers=tuple(levers), cfg={"cache_dir": "/nonexistent", "verbose": False}, log=LOGS.append, patched=[]) patches.HEADS.clear() patches.EXIT = EXITS.append WEXT.reset() for key in uq.CALLS: uq.CALLS[key] = 0 uq.STOCK_GEMV[0] = True batch_invariant_ops.ENABLED[0] = False inkling_pico12.STATE["levers"] = ()
def configure_pico(levers=("dense", "lmhead")): pops.EXT = PEXT pops.SET.require_cuda = False pops.SET.max_m = pops.SET.stacked_max_m = 16 pops.SET.wk = 1 pops.LOG = LOGS.append pops._batch_invariant = batch_invariant_ops.is_batch_invariant_mode_enabled pops._warned.clear() ppatches.STATE.update(levers=tuple(levers), cfg={"cache_dir": "/x", "std": "c++20", "verbose": False}, log=LOGS.append, patched=[]) ppatches.HEADS.clear() PEXT.reset() PEXT.pad = 64 inkling_pico12.STATE["levers"] = tuple(levers)
def model(layers=1, **kw): kw.setdefault("hidden", 64) kw.setdefault("heads_dim", 128) return inkling2.Inkling2ForConditionalGeneration(layers=layers, **kw)
def bf16(*shape, seed=0): g = torch.Generator().manual_seed(seed) return torch.randn(shape, generator=g).to(torch.bfloat16)
def ref(x, w, dtype=torch.bfloat16): return (x.reshape(-1, x.shape[-1]).float() @ w.float().T).to(dtype).view(*x.shape[:-1], w.shape[0])
def bits_equal(a, b): if a.dtype != b.dtype or a.shape != b.shape: return False view = torch.int16 if a.dtype == torch.bfloat16 else torch.int32 return torch.equal(a.contiguous().view(view), b.contiguous().view(view))
class Settings(unittest.TestCase): def test_levers(self): self.assertEqual(inkling_wide.parse_levers(""), ()) self.assertEqual(inkling_wide.parse_levers(" dense , lmhead,dense"), ("dense", "lmhead")) self.assertEqual(inkling_wide.parse_levers("all"), ("dense", "lmhead")) self.assertEqual(inkling_wide.parse_levers("off"), ()) for bad in ("dense,draft", "off,dense"): with self.assertRaises(RuntimeError): inkling_wide.parse_levers(bad)
def test_config(self): cfg = inkling_wide.config_from_env({}) self.assertEqual((cfg["min_m"], cfg["max_m"], cfg["pdl"], cfg["fmt"], cfg["splitk"]), (17, 256, True, "auto", {})) self.assertTrue(cfg["cache_dir"].endswith(os.path.join(".cache", "inkling-wide"))) cfg = inkling_wide.config_from_env({"INKLING_WIDE_MIN_M": "9", "INKLING_WIDE_MAX_M": "128", "INKLING_WIDE_PDL": "0", "INKLING_WIDE_FORMAT": "raw", "INKLING_WIDE_SPLITK": "wo=4, head=1"}) self.assertEqual((cfg["min_m"], cfg["max_m"], cfg["pdl"], cfg["fmt"], cfg["splitk"]), (9, 128, False, "raw", {"wo": 4, "head": 1})) for env in ({"INKLING_WIDE_MAX_M": "257"}, {"INKLING_WIDE_MIN_M": "0"}, {"INKLING_WIDE_MIN_M": "64", "INKLING_WIDE_MAX_M": "32"}, {"INKLING_WIDE_FORMAT": "fp8"}, {"INKLING_WIDE_SPLITK": "wo"}, {"INKLING_WIDE_SPLITK": "lm=2"}, {"INKLING_WIDE_SPLITK": "wo=0"}): with self.assertRaises(ValueError, msg=str(env)): inkling_wide.config_from_env(env)
def test_kind_caps(self): cfg = inkling_wide.config_from_env({"INKLING_WIDE_MAX_M_KIND": "wo=64"}) self.assertEqual(cfg["max_m_kind"], {"qkvr": 96, "wo": 64, "head": 256}) with self.assertRaises(ValueError): inkling_wide.config_from_env({"INKLING_WIDE_MAX_M_KIND": "wo=300"}) configure() ops.SET.max_m_kind = {"wo": 32} self.assertTrue(ops.in_range(32, "wo") and not ops.in_range(33, "wo") and ops.in_range(200, "qkvr"))
def test_source_checks(self): import shutil import tempfile
# the stand-in sglang of tests/pico12 plus the strings the scope patch needs with tempfile.TemporaryDirectory() as tmp: root = os.path.join(tmp, "sglang") shutil.copytree(os.path.join(FAKE_ROOT, "sglang"), root) with open(os.path.join(root, "srt", "models", "inkling2.py"), "a") as f: f.write("\n# forward_batch: ForwardBatch,\n") os.makedirs(os.path.join(root, "srt", "model_executor"), exist_ok=True) with open(os.path.join(root, "srt", "model_executor", "forward_mode.py"), "w") as f: f.write("def is_decode(self):\ndef is_target_verify(self):\n") inkling_wide.check_sources(("dense", "lmhead"), root) with self.assertRaises(RuntimeError): inkling_wide.check_sources(("dense", "lmhead"), os.path.join(FAKE_ROOT, "sglang")) with self.assertRaises(RuntimeError): inkling_wide.check_sources(("dense",), os.path.join(HERE))
def test_noop_without_switch(self): saved = dict(inkling_wide.STATE) try: inkling_wide.STATE.update(installed=False, levers=(), cfg=None) self.assertEqual(inkling_wide.install(env={}), ()) finally: inkling_wide.STATE.update(saved)
class Shapes(unittest.TestCase): def setUp(self): configure()
def test_bucket(self): for m, b in ((1, 1), (16, 1), (17, 2), (32, 2), (33, 3), (48, 3), (49, 4), (64, 4), (65, 6), (96, 6), (97, 8), (128, 8), (129, 12), (192, 12), (193, 16), (256, 16)): self.assertEqual(ops.bucket(m), b, m) self.assertEqual(WEXT.bucket(m), b, m) with self.assertRaises(ValueError): ops.bucket(257)
def test_split(self): self.assertEqual(ops.choose_split(8600, 2304, 64, "qkvr"), 1) self.assertEqual(ops.choose_split(201024, 2304, 256, "head"), 1) self.assertEqual([ops.choose_split(2304, 3072, m, "wo") for m in (17, 32, 48, 64, 128, 256)], [3, 3, 3, 3, 2, 2]) self.assertEqual(ops.choose_split(8600, 2304, 256, "qkvr"), 1) ops.SET.splitk = {"wo": 3} self.assertEqual(ops.choose_split(2304, 3072, 64, "wo"), 3) ops.SET.splitk = {"wo": 99} self.assertEqual(ops.choose_split(2304, 3072, 64, "wo"), 3072 // 64)
def test_regions(self): self.assertEqual(ops.regions_of([3072, 1024, 1024, 384, 3072, 24]), (3072, 4096, 5120)) self.assertIsNone(ops.regions_of([3000, 1024, 1024])) self.assertIsNone(ops.regions_of([3072, 1000, 1024])) self.assertIsNone(ops.regions_of([3072, 1024]))
def test_shape_reason(self): self.assertIsNone(ops.shape_reason(8600, 2304)) self.assertIsNotNone(ops.shape_reason(8601, 2304)) self.assertIsNotNone(ops.shape_reason(8600, 2336))
class Dense(unittest.TestCase): def setUp(self): configure() patches.patch_attn(attn_mod) self.model = model() patches.prepare_target(self.model) self.attn = self.model.llm.layers[0].attn
def tearDown(self): restore_sglang()
def test_registered(self): self.assertEqual(type(self.attn.qkvr.quant_method).__name__, "WideUnquantizedLinearMethod") self.assertEqual(self.attn.qkvr.__dict__["_wide"].fmt, ops.RAW) self.assertIn("_wide", self.attn.wo_ud.__dict__) self.assertEqual(self.attn.__dict__["_wide_qkvr"][1], (3072, 4096, 5120)) self.assertTrue(any("active (target)" in m for m in LOGS))
def test_rows_range(self): w = self.attn.qkvr.weight for m, wide in ((8, False), (16, False), (17, True), (64, True), (256, True), (257, False)): WEXT.reset() uq.CALLS["apply"] = 0 x = bf16(m, 64, seed=m) y, _ = self.attn.qkvr(x) self.assertEqual(len(WEXT.calls), int(wide), m) self.assertEqual(uq.CALLS["apply"], int(not wide), m) self.assertTrue(bits_equal(y, ref(x, w)), m)
def test_3d_input_and_wo(self): x = bf16(3, 8, 128, seed=1) y, _ = self.attn.wo_ud(x) self.assertEqual(tuple(y.shape), (3, 8, 64)) self.assertTrue(bits_equal(y, ref(x, self.attn.wo_ud.weight))) self.assertEqual(WEXT.calls[-1][:3], (24, 64, 128))
def test_falls_back(self): x = bf16(32, 64) batch_invariant_ops.ENABLED[0] = True self.attn.qkvr(x) batch_invariant_ops.ENABLED[0] = False self.attn.qkvr(x) self.assertEqual(len(WEXT.calls), 1) self.assertEqual(uq.CALLS["apply"], 1) self.attn.qkvr.quant_method.apply(self.attn.qkvr, x, bias=torch.zeros(8600, dtype=torch.bfloat16)) self.assertEqual(uq.CALLS["apply"], 2)
def test_apply_into(self): x = bf16(40, 128, seed=2) out = torch.empty((40, 64), dtype=torch.bfloat16) self.attn.wo_ud(x, output_tensor=out) self.assertEqual(len(WEXT.calls), 1) self.assertTrue(bits_equal(out, ref(x, self.attn.wo_ud.weight))) bad = torch.empty((40, 128), dtype=torch.bfloat16)[:, :64] # rows not contiguous self.attn.wo_ud(x, output_tensor=bad) self.assertEqual(uq.CALLS["apply_into"], 1)
def test_stacked_layout_and_values(self): m = 20 q, k, v = bf16(m, 64, seed=3), bf16(m, 64, seed=4), bf16(m, 64, seed=5) src = attn_mod.AttentionSources(q, k, v) got = self.attn._project_sources(src) self.assertEqual(len(WEXT.calls), 1) self.assertTrue(WEXT.calls[0][-1]) # stacked stock = STOCK_PROJECT(self.attn, src) for a, b in zip(got, stock): self.assertEqual((a.shape, a.stride(), a.storage_offset()), (b.shape, b.stride(), b.storage_offset())) self.assertTrue(bits_equal(a, b))
def test_stacked_falls_back(self): for m in (8, 300): WEXT.reset() q, k, v = bf16(m, 64, seed=3), bf16(m, 64, seed=4), bf16(m, 64, seed=5) self.attn._project_sources(attn_mod.AttentionSources(q, k, v)) self.assertFalse(any(c[-1] for c in WEXT.calls), m) WEXT.reset() # shared sources go through the plain linear q = bf16(24, 64, seed=3) self.attn._project_sources(attn_mod.AttentionSources(q, q, q)) self.assertEqual([c[-1] for c in WEXT.calls], [False])
def test_reload_and_replaced_storage(self): w = self.attn.qkvr.weight w.data.copy_(bf16(*w.shape, seed=7)) # in place: still current x = bf16(32, 64, seed=8) y, _ = self.attn.qkvr(x) self.assertTrue(bits_equal(y, ref(x, w))) self.assertEqual(len(WEXT.calls), 1) self.attn.qkvr.weight = torch.nn.Parameter(bf16(*w.shape, seed=9), requires_grad=False) y, _ = self.attn.qkvr(x) self.assertEqual(len(WEXT.calls), 1) self.assertTrue(any("storage changed" in m for m in LOGS)) patches.prepare_target(self.model) # re-registration picks the new storage up self.attn.qkvr(x) self.assertEqual(len(WEXT.calls), 2)
def test_split_workspace(self): configure(splitk={"wo": 1, "qkvr": 2}) m2 = model(hidden=128) patches.prepare_target(m2) self.assertGreaterEqual(ops.WS["ws"].numel(), 2 * 256 * 8600) with self.assertRaises(ops.WideFatal): # a reload needing more cannot replace graph-referenced buffers ops.ensure_workspace(list(patches.HEADS.values()), 17, 256, "cpu", floats=10**9) x = bf16(48, 128, seed=10) y, _ = m2.llm.layers[0].attn.qkvr(x) self.assertEqual(WEXT.calls[-1][5], 2) self.assertTrue(bits_equal(y, ref(x, m2.llm.layers[0].attn.qkvr.weight)))
class Scope(unittest.TestCase): """INKLING_WIDE_SCOPE=verify: wide takes calls only inside a target decode / target-verify forward."""
class Mode: def __init__(self, name): self.name = name
def is_decode(self): return self.name == "decode"
def is_target_verify(self): return self.name == "verify"
def setUp(self): configure(scope="verify") self.model = model() patches.prepare_target(self.model) self.attn = self.model.llm.layers[0].attn
def tearDown(self): restore_sglang()
def run_in(self, mode, m=32): used = []
def inner(model_self, input_ids, positions, forward_batch, *a, **kw): WEXT.reset() self.attn.qkvr(bf16(m, 64, seed=1)) used.append(len(WEXT.calls)) return "out"
fwd = patches.make_forward(inner) fb = types.SimpleNamespace(forward_mode=self.Mode(mode)) if mode else types.SimpleNamespace() self.assertEqual(fwd(self.model, None, None, fb), "out") self.assertFalse(ops.IN_SCOPE[0]) # restored return used[0]
def test_scope(self): self.assertEqual(self.run_in("verify"), 1) self.assertEqual(self.run_in("decode"), 1) self.assertEqual(self.run_in("extend"), 0) self.assertEqual(self.run_in(None), 0) WEXT.reset() self.attn.qkvr(bf16(32, 64)) # outside any forward self.assertEqual(len(WEXT.calls), 0)
def test_restored_on_error(self): def inner(*a, **kw): raise RuntimeError("boom")
fwd = patches.make_forward(inner) with self.assertRaises(RuntimeError): fwd(self.model, None, None, types.SimpleNamespace(forward_mode=self.Mode("verify"))) self.assertFalse(ops.IN_SCOPE[0])
def test_patch_model_wraps_forward(self): patches.patch_model(inkling2) self.assertTrue(getattr(inkling2.Inkling2ForConditionalGeneration.forward, "_wide", False))
def test_config(self): self.assertEqual(inkling_wide.config_from_env({})["scope"], "verify") self.assertEqual(inkling_wide.config_from_env({"INKLING_WIDE_SCOPE": "all"})["scope"], "all") with self.assertRaises(ValueError): inkling_wide.config_from_env({"INKLING_WIDE_SCOPE": "prefill"})
class Head(unittest.TestCase): def setUp(self): configure() patches.patch_unquant(uq) self.model = model() patches.prepare_target(self.model) self.w = self.model.llm.lm_head.weight
def test_head(self): for m, wide in ((4, False), (20, True), (256, True)): WEXT.reset() uq.CALLS["lm_head"] = 0 x = bf16(m, 64, seed=m) self.assertTrue(uq.sm12x_fp32_lm_head_applies(x, self.w, None)) y = uq.sm12x_fp32_lm_head(x, self.w, None) self.assertEqual(y.dtype, torch.float32) self.assertTrue(bits_equal(y, ref(x, self.w, torch.float32))) self.assertEqual(len(WEXT.calls), int(wide)) self.assertEqual(uq.CALLS["lm_head"], int(not wide)) self.assertFalse(uq.sm12x_fp32_lm_head_applies(bf16(300, 64), self.w, None))
def test_head_out(self): x = bf16(33, 64, seed=1) out = torch.empty((33, 256), dtype=torch.float32) y = uq.sm12x_fp32_lm_head(x, self.w, out) self.assertEqual(y.data_ptr(), out.data_ptr()) self.assertTrue(bits_equal(out, ref(x, self.w, torch.float32))) wrong = torch.empty((33, 255), dtype=torch.float32) self.assertFalse(uq.sm12x_fp32_lm_head_applies(x, self.w, wrong))
class WithPico(unittest.TestCase): """inkling_pico12 installed first (as sitecustomize does): pico <= 16 rows, wide 17..256 on pico's buffers."""
def setUp(self): configure() configure_pico() ppatches.patch_unquant(uq) patches.patch_unquant(uq) ppatches.patch_attn(attn_mod) patches.patch_attn(attn_mod) ppatches.patch_model(inkling2) patches.patch_model(inkling2) self.model = model() self.model.post_load_weights() self.attn = self.model.llm.layers[0].attn
def tearDown(self): restore_sglang()
def test_formats_and_split_of_work(self): e = self.attn.qkvr.__dict__["_wide"] self.assertEqual(e.fmt, ops.BF16X) self.assertIs(e.pack, self.attn.qkvr.__dict__["_pico12"]) self.assertEqual(type(self.attn.qkvr.quant_method).__name__, "WidePico12UnquantizedLinearMethod") for m, who in ((8, "pico"), (16, "pico"), (17, "wide"), (128, "wide"), (257, "stock")): PEXT.reset(), WEXT.reset() uq.CALLS["apply"] = 0 x = bf16(m, 64, seed=m) y, _ = self.attn.qkvr(x) self.assertTrue(bits_equal(y, ref(x, self.attn.qkvr.weight)), m) self.assertEqual((len(PEXT.calls) > 0, len(WEXT.calls) > 0, uq.CALLS["apply"] > 0), (who == "pico", who == "wide", who == "stock"), m) self.attn.qkvr(bf16(40, 64)) self.assertEqual(WEXT.calls[-1][3], 2)
def test_head_bf16x(self): w = self.model.llm.lm_head.weight self.assertEqual(patches.HEADS[w.data_ptr()].fmt, ops.BF16X) x = bf16(40, 64, seed=3) y = uq.sm12x_fp32_lm_head(x, w, None) self.assertEqual(WEXT.calls[-1][3], 2) self.assertTrue(bits_equal(y, ref(x, w, torch.float32))) PEXT.reset() uq.sm12x_fp32_lm_head(bf16(8, 64), w, None) self.assertEqual(len(PEXT.calls), 1)
def test_stacked_order(self): for m, who in ((4, "pico"), (17, "wide")): PEXT.reset(), WEXT.reset() q, k, v = bf16(m, 64, seed=3), bf16(m, 64, seed=4), bf16(m, 64, seed=5) src = attn_mod.AttentionSources(q, k, v) got = self.attn._project_sources(src) for a, b in zip(got, STOCK_PROJECT(self.attn, src)): self.assertTrue(bits_equal(a, b), m) self.assertEqual((len(PEXT.calls) > 0, len(WEXT.calls) > 0), (who == "pico", who == "wide"), m) self.assertTrue(getattr(attn_mod.Inkling2Attention._project_sources, "inkling_pico12", False))
def test_raw_format_forced(self): configure(fmt="raw") configure_pico() m2 = model() ppatches.prepare_target(m2) patches.prepare_target(m2) self.assertEqual(m2.llm.layers[0].attn.qkvr.__dict__["_wide"].fmt, ops.RAW)
class WrongOrder(unittest.TestCase): def tearDown(self): restore_sglang()
def test_wide_before_pico_exits(self): configure() configure_pico() EXITS.clear() patches.patch_model(inkling2) # wide's wrapper inside ... ppatches.patch_model(inkling2) # ... pico's: wide registers before pico coded anything ppatches.EXIT = lambda code: EXITS.append(("pico", code)) with self.assertRaises(BaseException): model().post_load_weights() self.assertIn(78, EXITS) self.assertTrue(any("install inkling_wide after inkling_pico12" in m for m in LOGS))
if __name__ == "__main__": unittest.main()123456789101112131415161718192021MIT License
Copyright (c) 2026 Andy Shu
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407#!/usr/bin/env python3"""GPU check + microbenchmark of inkling_wide (weight-streaming BF16 GEMM, 17..256 rows) on a Spark. Run inside theSGLang container with the server STOPPED (peak ~5 GB of GPU memory, for the head):
docker run --rm --gpus all --ipc=host -v <repo>/overlay:/opt/inkling-overlay:ro -v <model dir>:/model:ro \ -v <cache dir>:/root/.cache -e PYTHONPATH=/opt/inkling-overlay --entrypoint python3 \ lmsysorg/sglang:inkling-2-mini /opt/inkling-overlay/inkling_wide/tools/gpu_check_wide.py
options: --model /model --layer 0 --check-ms ... --ms ... --iters 20 --no-real --no-time --sweep --quick
What it does: 1. builds (or reuses) inkling_wide's and inkling_pico12's extensions; prints registers / local memory per kernel; 2. for qkvr [8600 x 2304], wo [2304 x 3072] and the head [201024 x 2304] (real layer-L / unembed weights when /model is mounted, else random), codes the weight with inkling_pico12 (pico's bf16x) and [gated]: - the wide reader's decode of the coded buffer == the BF16 weight bit for bit; - at every --check-ms M: wide on the coded weight == wide on the raw weight bit for bit; PDL on == off; CUDA-graph replay == eager; split-K 1 and the default split both within the FP32-sum bound of an FP64 reference; wide's max error vs FP64 no worse than cuBLAS's (x1.25 slack, BF16 ulps for BF16 outputs); [reported]: max abs / max rel error vs FP64 of wide and cuBLAS, max |wide - cuBLAS|; 3. the stacked qkvr case (three distinct sources) [gated]: every kept element == the per-source plain call bit for bit, the views have the stock layout; [reported] vs cuBLAS on the 3M stacked rows; 4. times (median of --iters, L2 evicted before each call by READING a 256 MiB buffer) cuBLAS, pico (16-row calls of its packed GEMV, i.e. ceil(M/16) weight reads), wide packed and wide raw, and the stacked call; GB/s of the bytes one pass reads; summed dense time at M=64 (kill line: cuBLAS / wide >= 1.15); 5. --sweep: split-K sweep per shape and M.Last line: `wide gpu_check result PASS|FAIL (...)`; exit 0 on PASS, 1 on FAIL, 3 when refused by the memory guard."""
import argparseimport globimport osimport statisticsimport sysimport time
OVERLAY = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))if OVERLAY not in sys.path: sys.path.insert(0, OVERLAY)
FAILS = []SPLITS = [3072, 1024, 1024, 384, 3072, 24]PROJ = ("wq_du", "wk_dv", "wv_dv", "wr_du", "gate_attn", "attn_sink_proj")
def log(*a): print(*a, flush=True)
def gate(name, ok, detail=""): log(f"{name} {detail} {'PASS' if ok else 'FAIL'}") if not ok: FAILS.append(name)
def mem_available_gib(): try: with open("/proc/meminfo") as f: for line in f: if line.startswith("MemAvailable:"): return int(line.split()[1]) / 1048576 except OSError: pass return float("nan")
def load_real(model_dir, layer, dev, torch): from safetensors import safe_open
where = {} for path in sorted(glob.glob(os.path.join(model_dir, "*.safetensors"))): with safe_open(path, framework="pt", device="cpu") as h: for key in h.keys(): where.setdefault(key, path)
def get(name): if name not in where: raise SystemExit(f"wide real weights: {name} not in {model_dir}") with safe_open(where[name], framework="pt", device="cpu") as h: t = h.get_tensor(name) if t.dtype != torch.bfloat16 or t.dim() != 2: raise SystemExit(f"wide real weights: {name} is {t.dtype} {tuple(t.shape)}") return t
base = f"model.llm.layers.{layer}.attn." parts = [get(f"{base}{p}.weight") for p in PROJ] qkvr = torch.cat(parts).to(dev) splits = [t.shape[0] for t in parts] wo = get(f"{base}wo_ud.weight").to(dev) head = get("model.llm.unembed.weight").to(dev) log(f"wide real weights layer={layer} qkvr={tuple(qkvr.shape)} splits={splits} wo={tuple(wo.shape)} " f"head={tuple(head.shape)}") return [("qkvr", qkvr, splits), ("wo", wo, None), ("head", head, None)]
def main(): p = argparse.ArgumentParser() p.add_argument("--model", default="/model") p.add_argument("--layer", type=int, default=0) p.add_argument("--check-ms", default="17,24,40,64,65,80,96,100,128,160,192,256") p.add_argument("--head-check-ms", default="17,64,256") p.add_argument("--ms", default="9,16,17,24,32,48,64,96,128,192,256") p.add_argument("--stacked-ms", default="17,24,32,64,85") p.add_argument("--iters", type=int, default=20) p.add_argument("--warmup", type=int, default=3) p.add_argument("--flush-mib", type=int, default=256) p.add_argument("--min-avail-gib", type=float, default=12.0) p.add_argument("--no-real", action="store_true") p.add_argument("--no-time", action="store_true") p.add_argument("--sweep", action="store_true") p.add_argument("--quick", action="store_true", help="first run: few M, no head timing sweep") p.add_argument("--shapes", default="qkvr,wo,head") args = p.parse_args() if args.quick: args.check_ms, args.head_check_ms, args.ms, args.stacked_ms = "17,64,256", "17,256", "24,64,256", "24,64"
avail = mem_available_gib() log(f"wide memguard MemAvailable_GiB={avail:.1f} need_GiB={args.min_avail_gib:.1f}") if avail == avail and avail < args.min_avail_gib: log("wide gpu_check REFUSED: not enough MemAvailable (stop the server first)") sys.exit(3)
import torch import torch.nn.functional as F
import inkling_pico12 import inkling_wide from inkling_pico12 import build as pbuild from inkling_pico12 import ops as pops from inkling_wide import build, ops
dev = torch.device("cuda", torch.cuda.current_device()) prop = torch.cuda.get_device_properties(dev) log(f"wide device={prop.name} cc={prop.major}.{prop.minor} sms={prop.multi_processor_count} " f"torch={torch.__version__} cuda={torch.version.cuda}") wcfg = inkling_wide.config_from_env() t0 = time.monotonic() ext = build.load(wcfg["cache_dir"], verbose=wcfg["verbose"]) ext.prepare(dev.index) log(f"wide ext {'reused' if build.INFO['cached'] else 'built'} in {time.monotonic() - t0:.1f} s at " f"{build.INFO['build_dir']}") for fmt in (0, 2): for m in (16, 32, 48, 64, 96, 128, 192, 256): for mt, mg in (((1, 1), (2, 1)) if m > 128 else ((0, 1), (0, 2)) if m in (96, 128) else ((0, 1),)): regs, local, thr = ext.kernel_info(fmt, m, mt, mg) log(f"wide kernel fmt={'bf16x' if fmt else 'raw'} M<={m} mt={mt or 2} mg={mg} regs={regs} " f"local_bytes={local} threads={thr}") if local > 64: # a few bytes of header spill (bf16x, M <= 64) are tolerated and reported FAILS.append(f"spill fmt={fmt} M={m} mt={mt} mg={mg}") pcfg = inkling_pico12.config_from_env() pops.EXT = pbuild.load(pcfg["cache_dir"], pcfg["std"], verbose=False) pops.SET.wk, pops.SET.pdl = pcfg["wk"], pcfg["pdl"] ops.EXT = ext ops.SET.sms = prop.multi_processor_count ops.SET.min_m, ops.SET.max_m = 1, 256
flush = torch.empty(args.flush_mib * (1 << 20) // 4, device=dev, dtype=torch.float32).fill_(1.0) sink = torch.empty((), device=dev)
def timeit(fn, iters=None): iters = iters or args.iters for _ in range(args.warmup): fn() torch.cuda.synchronize() st = [torch.cuda.Event(enable_timing=True) for _ in range(iters)] en = [torch.cuda.Event(enable_timing=True) for _ in range(iters)] for i in range(iters): sink.copy_(flush.sum()) # reads 256 MiB: L2 (24 MiB) holds no weight afterwards st[i].record() fn() en[i].record() torch.cuda.synchronize() return statistics.median(s.elapsed_time(e) * 1000.0 for s, e in zip(st, en))
def gauss(n, k, seed): g = torch.Generator(device=dev).manual_seed(seed) sigma = 0.01 + 0.04 * (torch.arange(n, device=dev, dtype=torch.float32) * 0.618034 % 1.0) return (torch.randn((n, k), device=dev, generator=g) * sigma[:, None]).to(torch.bfloat16)
def acts(m, k, seed): g = torch.Generator(device=dev).manual_seed(seed) return (torch.rand((m, k), device=dev, generator=g) * 4 - 2).to(torch.bfloat16)
def bits_equal(a, b): view = torch.int16 if a.dtype == torch.bfloat16 else torch.int32 return a.shape == b.shape and torch.equal(a.contiguous().view(view), b.contiguous().view(view))
def ref64(x, w, chunk=16384): xd, xa = x.double(), x.double().abs() outs, mags = [], [] for r0 in range(0, w.shape[0], chunk): wd = w[r0 : r0 + chunk].double() outs.append(xd @ wd.T) mags.append(xa @ wd.abs().T) return torch.cat(outs, 1), torch.cat(mags, 1)
def bound_worst(y, ref, mag, k): tol = mag * 2.0**-23 * (k / 16 + 32) + 1e-30 if y.dtype == torch.bfloat16: tol = tol + ref.abs() * 2.0**-8 return float(((y.double() - ref).abs() / tol).max())
def errs(y, ref): e = (y.double() - ref).abs() return float(e.max()), float(e.max() / ref.abs().max().clamp_min(1e-30)), float(e.mean())
def cublas(x, w, f32): return torch.mm(x, w.T, out_dtype=torch.float32) if f32 else F.linear(x, w)
def pico_multi(x, pack, out): for r0 in range(0, x.shape[0], 16): r1 = min(x.shape[0], r0 + 16) pops.gemv(x[r0:r1], pack, out[r0:r1]) return out
if not args.no_real and os.path.isdir(args.model): weights = load_real(args.model, args.layer, dev, torch) else: log("wide note no real weights: random Gaussian weights") weights = [("qkvr", gauss(sum(SPLITS), 2304, 1), list(SPLITS)), ("wo", gauss(2304, 3072, 2), None), ("head", gauss(201024, 2304, 3), None)] shapes = set(args.shapes.split(",")) weights = [wt for wt in weights if wt[0] in shapes]
rows = [] # timing table dense64 = {} while weights: name, w, splits = weights.pop(0) n, k = w.shape f32 = name == "head" out_dtype = torch.float32 if f32 else torch.bfloat16 kind = {"qkvr": "qkvr", "wo": "wo", "head": "head"}[name] pack = pops.encode(w, name) dec = ext.decode(pack.buf, n, k) same = bits_equal(dec, w) del dec gate(f"wide decode {name}", same, f"[{n}x{k}] raw_MB={n * k * 2 / 1e6:.1f} packed_MB={pack.nbytes / 1e6:.1f} " f"ratio={pack.nbytes / (n * k * 2):.4f} raw_tiles={pack.raw_tiles}/{pack.tiles} decoded==weight") e_raw = ops.make(w, name, kind, None) ops.SET.fmt = "auto" e_x = ops.make(w, name, kind, pack) alt_max = 2 if f32 else 12 # forced splits below (check: 1 and alt; sweep up to 12, head up to 2) ops.ensure_workspace([e_raw, e_x], 1, 256, dev, grow=True, floats=alt_max * 256 * n) cms = [int(v) for v in (args.head_check_ms if f32 else args.check_ms).split(",") if v] for m in cms: x = acts(m, k, 100 + m) s_def = ops.choose_split(n, k, m, kind) y_x = torch.full((m, n), float("nan"), device=dev, dtype=out_dtype) ops.gemm(x, e_x, y_x, m) y_r = torch.full_like(y_x, float("nan")) ops.gemm(x, e_raw, y_r, m) ops.SET.pdl = False y_np = torch.full_like(y_x, float("nan")) ops.gemm(x, e_x, y_np, m) ops.SET.pdl = True ops.SET.splitk = {kind: 1} y_s1 = torch.full_like(y_x, float("nan")) ops.gemm(x, e_x, y_s1, m) s_alt = (2 if f32 else 3) if s_def == 1 else 1 ops.SET.splitk = {kind: s_alt} y_s2 = torch.full_like(y_x, float("nan")) ops.gemm(x, e_x, y_s2, m) ops.SET.splitk = {} y_mt = y_x if m > 64: # the bucket's other kernel (MT 2 above 128 rows, two warp groups at 65..128): same bits ops.SET.mt, ops.SET.mg = (2, 0) if m > 128 else (0, 2) y_mt = torch.full_like(y_x, float("nan")) ops.gemm(x, e_x, y_mt, m) ops.SET.mt = ops.SET.mg = 0 pfd0 = ops.SET.pfd ops.SET.pfd = 0 y_pf = torch.full_like(y_x, float("nan")) ops.gemm(x, e_x, y_pf, m) ops.SET.pfd = pfd0 yg = torch.full_like(y_x, float("nan")) side = torch.cuda.Stream() side.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(side): ops.gemm(x, e_x, yg, m) torch.cuda.current_stream().wait_stream(side) g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): ops.gemm(x, e_x, yg, m) yg.fill_(float("nan")) g.replay() g.replay() # twice: the split-K counters must be back at zero y_c = cublas(x, w, f32) torch.cuda.synchronize() ref, mag = ref64(x, w) wb = max(bound_worst(y_x, ref, mag, k), bound_worst(y_s1, ref, mag, k), bound_worst(y_s2, ref, mag, k)) ea, er, em = errs(y_x, ref) ca, cr, cm = errs(y_c, ref) nan = bool(torch.isnan(y_x).any() or torch.isnan(y_s1).any() or torch.isnan(y_s2).any()) no_worse = ea <= 1.25 * ca + (0 if f32 else 0) gate(f"wide bits {name} M={m}", bits_equal(y_x, y_r) and bits_equal(y_x, y_np) and bits_equal(y_x, yg) and bits_equal(y_x, y_mt) and bits_equal(y_x, y_pf) and wb <= 1.0 and not nan, f"split={s_def}/alt{s_alt} packed_vs_raw={'IDENTICAL' if bits_equal(y_x, y_r) else 'DIFFERENT'} " f"pdl_on_vs_off={'IDENTICAL' if bits_equal(y_x, y_np) else 'DIFFERENT'} " f"graph_vs_eager={'IDENTICAL' if bits_equal(y_x, yg) else 'DIFFERENT'} " f"variant={'IDENTICAL' if bits_equal(y_x, y_mt) else 'DIFFERENT'} " f"prefetch_off={'IDENTICAL' if bits_equal(y_x, y_pf) else 'DIFFERENT'} fp64_bound_worst={wb:.3f}") gate(f"wide accuracy {name} M={m}", no_worse, f"err_vs_fp64 wide max_abs={ea:.3e} max_rel={er:.3e} mean={em:.3e} | cublas max_abs={ca:.3e} " f"max_rel={cr:.3e} mean={cm:.3e} | max|wide-cublas|={float((y_x.double() - y_c.double()).abs().max()):.3e}") del ref, mag, y_x, y_r, y_np, y_s1, y_s2, yg, y_c, g, y_mt, y_pf torch.cuda.empty_cache()
if name == "qkvr" and splits is not None: regions = ops.regions_of(splits) gate("wide stacked regions", regions is not None, f"{regions}") for m in [int(v) for v in args.stacked_ms.split(",") if v]: q, kk, v = acts(m, k, 7), acts(m, k, 8), acts(m, k, 9) out = ops.stacked_project(q, kk, v, e_x, regions) views = ops.split_like_stock(out, splits) plain = [ops.linear(src, e_x, torch.bfloat16) for src in (q, kk, v)] st_out = cublas(torch.cat([q, kk, v]), w, False) st_views = ops.split_like_stock(st_out, splits) pq = plain[0].split(splits, dim=-1) exp = (pq[0], plain[1].split(splits, dim=-1)[1], plain[2].split(splits, dim=-1)[2], pq[3], pq[4], pq[5]) same = all(bits_equal(a, b) for a, b in zip(views, exp)) layout = all((a.shape, a.stride(), a.storage_offset()) == (b.shape, b.stride(), b.storage_offset()) for a, b in zip(views, st_views)) dmax = max(float((a.double() - b.double()).abs().max()) for a, b in zip(views, st_views)) gate(f"wide stacked M={m}", same and layout, f"kept==per-source {'IDENTICAL' if same else 'DIFFERENT'} layout={'stock' if layout else 'OTHER'} " f"max|wide-cublas_stacked|={dmax:.3e}") if not args.no_time: t_c = timeit(lambda: cublas(torch.cat([q, kk, v]), w, False)) t_x = timeit(lambda: ops.stacked_project(q, kk, v, e_x, regions)) t_r = timeit(lambda: ops.stacked_project(q, kk, v, e_raw, regions)) log(f"wide time stacked M={m}x3 cublas(cat+3M)_us={t_c:.1f} wide_x_us={t_x:.1f} " f"({pack.nbytes / t_x / 1e3:.0f} GB/s) wide_raw_us={t_r:.1f} ({n * k * 2 / t_r / 1e3:.0f} GB/s) " f"speedup_x={t_c / t_x:.2f}") rows.append(("qkvr-stacked", m, t_c, float("nan"), t_x, t_r, pack.nbytes, n * k * 2)) if m == 64: dense64["stacked"] = (t_c, t_x)
if not args.no_time: for m in [int(v) for v in args.ms.split(",") if v]: x = acts(m, k, 200 + m) y = torch.empty((m, n), device=dev, dtype=out_dtype) yp = torch.empty((m, n), device=dev, dtype=out_dtype) it = max(5, args.iters // 4) if f32 else args.iters t_c = timeit(lambda: cublas(x, w, f32), it) t_p = timeit(lambda: pico_multi(x, pack, yp), it) t_x = timeit(lambda: ops.gemm(x, e_x, y, m), it) t_r = timeit(lambda: ops.gemm(x, e_raw, y, m), it) rows.append((name, m, t_c, t_p, t_x, t_r, pack.nbytes, n * k * 2)) log(f"wide time {name} M={m} split={ops.choose_split(n, k, m, kind)} cublas_us={t_c:.1f} " f"({n * k * 2 / t_c / 1e3:.0f} GB/s) pico16x{-(-m // 16)}_us={t_p:.1f} wide_x_us={t_x:.1f} " f"({pack.nbytes / t_x / 1e3:.0f} GB/s packed, {n * k * 2 / t_x / 1e3:.0f} eff) wide_raw_us={t_r:.1f} " f"({n * k * 2 / t_r / 1e3:.0f} GB/s) speedup_x={t_c / t_x:.2f}") if m == 64 and name in ("qkvr", "wo"): dense64[name] = (t_c, t_x) if args.sweep: for m in ((24, 64, 96, 128, 256) if name != "head" else (64, 256)): x = acts(m, k, 300 + m) y = torch.empty((m, n), device=dev, dtype=out_dtype) res = [] for s in (1, 2, 3, 4, 6, 8, 12): if s > k // 64 or (name == "head" and s > 2): continue ops.SET.splitk = {kind: s} res.append((timeit(lambda: ops.gemm(x, e_x, y, m), max(5, args.iters // 2)), s)) ops.SET.splitk = {} log(f"wide sweep {name} M={m} " + " ".join(f"S{s}={t:.1f}" for t, s in res) + f" best=S{min(res)[1]} default=S{ops.choose_split(n, k, m, kind)}") pf = [] for d in (0, 1, 2, 4, 8, 16): ops.SET.pfd = d pf.append((timeit(lambda: ops.gemm(x, e_x, y, m), max(5, args.iters // 2)), d)) if name != "head": ops.SET.fmt = "raw" t_raw = timeit(lambda: ops.gemm(x, e_raw, y, m), max(5, args.iters // 2)) pf[-1] = pf[-1] + (t_raw,) ops.SET.pfd = 4 log(f"wide sweep {name} M={m} pfd " + " ".join( f"P{v[1]}={v[0]:.1f}" + (f"/raw{v[2]:.1f}" if len(v) > 2 else "") for v in pf)) if m > 64: for mt, mg in ((((1, 0), (2, 0)) if m > 128 else ((0, 1), (0, 2)))): ops.SET.mt, ops.SET.mg = mt, mg t_mt = timeit(lambda: ops.gemm(x, e_x, y, m), max(5, args.iters // 2)) log(f"wide sweep {name} M={m} mt={mt} mg={mg} us={t_mt:.1f} " f"split={ops.choose_split(n, k, m, kind)}") ops.SET.mt = ops.SET.mg = 0 del w, pack, e_raw, e_x torch.cuda.empty_cache()
if rows: log("wide summary (us, L2 cold; GB/s of one pass's bytes: packed for wide_x, raw BF16 for the others)") log("shape M cublas pico16x wide_x wide_raw GB/s:cublas wide_x wide_raw wide_x/cublas") for name, m, t_c, t_p, t_x, t_r, pb, rb in rows: log(f"{name:13s} {m:4d} {t_c:8.1f} {t_p:8.1f} {t_x:8.1f} {t_r:9.1f} {rb / t_c / 1e3:10.0f} " f"{pb / t_x / 1e3:6.0f} {rb / t_r / 1e3:8.0f} {t_c / t_x:12.2f}") if "qkvr" in dense64 and "wo" in dense64: c = dense64["qkvr"][0] + dense64["wo"][0] x = dense64["qkvr"][1] + dense64["wo"][1] log(f"wide dense M=64 (qkvr + wo) cublas_us={c:.1f} wide_x_us={x:.1f} ratio={c / x:.2f} " f"kill_line(>=1.15)={'MET' if c / x >= 1.15 else 'MISSED'}") log(f"wide gpu_check result {'PASS' if not FAILS else 'FAIL'} ({len(FAILS)} failed: {', '.join(FAILS[:8])})") sys.exit(0 if not FAILS else 1)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201#!/usr/bin/env python3"""Integration check of inkling_wide with the REAL sglang modules of the image (patch targets, hook order withinkling_pico12, dispatch), on stand-in layer objects that carry real UnquantizedLinearMethod instances and reallayer-0 / unembed weights. GPU, server stopped, ~3 GB.
PYTHONPATH=<overlay> python3 inkling_wide/tools/gpu_integration_wide.py [--model /model] [--no-pico]
Gated: install() of inkling_pico12 then inkling_wide applies every patch to the real modules; after both packages'prepare_target, qkvr / wo_ud / the head are served by pico at <= 16 rows and by wide at 17..256 (on pico's codedbuffers), by stock above; results match cuBLAS within the BF16 / FP32 summation tolerance; the real patchedInkling2Attention._project_sources returns the stock view layout for three sources at M = 24 and 64; captured in aCUDA graph, the stacked call replays bit for bit. Last line `wide integration result PASS|FAIL`."""
import argparseimport osimport sysimport types
OVERLAY = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))if OVERLAY not in sys.path: sys.path.insert(0, OVERLAY)
FAILS = []
def log(*a): print(*a, flush=True)
def gate(name, ok, detail=""): log(f"{name} {detail} {'PASS' if ok else 'FAIL'}") if not ok: FAILS.append(name)
def main(): p = argparse.ArgumentParser() p.add_argument("--model", default="/model") p.add_argument("--no-pico", action="store_true") args = p.parse_args() os.environ["INKLING_WIDE"] = "dense,lmhead" if not args.no_pico: os.environ["INKLING_PICO12"] = "dense,lmhead"
import inkling_pico12 import inkling_wide
if not args.no_pico: gate("wide integ pico install", inkling_pico12.install() == ("dense", "lmhead")) gate("wide integ install", inkling_wide.install() == ("dense", "lmhead"))
import torch import torch.nn.functional as F from torch import nn
from sglang.srt.layers.quantization import unquant as uq from sglang.srt.models.inkling_common import inkling2_attn as am import sglang.srt.models.inkling2 as mm
from inkling_pico12 import patches as ppatches from inkling_wide import ops, patches
gate("wide integ patched lm head", getattr(uq.sm12x_fp32_lm_head, "_wide", False) and getattr(uq.sm12x_fp32_lm_head_applies, "_wide", False)) gate("wide integ patched _project_sources", getattr(am.Inkling2Attention._project_sources, "inkling_wide", False) and (args.no_pico or getattr(am.Inkling2Attention._project_sources, "inkling_pico12", False))) gate("wide integ patched post_load_weights + forward (scope)", getattr(mm.Inkling2ForConditionalGeneration.post_load_weights, "_wide", False) and getattr(mm.Inkling2ForConditionalGeneration.forward, "_wide", False)) # the scope marker on a real ForwardMode from sglang.srt.model_executor.forward_mode import ForwardMode
sc = [patches.is_in_scope(types.SimpleNamespace(forward_mode=fm)) for fm in (ForwardMode.DECODE, ForwardMode.TARGET_VERIFY, ForwardMode.EXTEND)] gate("wide integ scope modes", sc == [True, True, False], f"decode/verify/extend={sc}") ops.SET.scope = "all" # the direct layer calls below run outside a model forward log(f"wide integ patched: {patches.STATE['patched']}")
dev = torch.device("cuda", torch.cuda.current_device()) from safetensors import safe_open import glob
where = {} for path in sorted(glob.glob(os.path.join(args.model, "*.safetensors"))): with safe_open(path, framework="pt", device="cpu") as h: for key in h.keys(): where.setdefault(key, path)
def get(name): with safe_open(where[name], framework="pt", device="cpu") as h: return h.get_tensor(name).to(dev)
base = "model.llm.layers.0.attn." parts = [get(base + n + ".weight") for n in ("wq_du", "wk_dv", "wv_dv", "wr_du", "gate_attn", "attn_sink_proj")] splits = [t.shape[0] for t in parts] w_qkvr = torch.cat(parts) del parts w_wo = get(base + "wo_ud.weight") w_head = get("model.llm.unembed.weight")
class Lin(nn.Module): def __init__(self, w): super().__init__() self.weight = nn.Parameter(w, requires_grad=False) self.bias = None self.quant_method = uq.UnquantizedLinearMethod()
def forward(self, x): return self.quant_method.apply(self, x, None), None
attn = am.Inkling2Attention.__new__(am.Inkling2Attention) nn.Module.__init__(attn) attn.qkvr, attn.wo_ud, attn.split_sizes = Lin(w_qkvr), Lin(w_wo), list(splits) model = nn.Module() model.llm = nn.Module() model.llm.layers = nn.ModuleList([nn.Module()]) model.llm.layers[0].attn = attn model.llm.lm_head = nn.Module() model.llm.lm_head.weight = nn.Parameter(w_head, requires_grad=False) if not args.no_pico: ppatches.prepare_target(model) patches.prepare_target(model) # the order the stacked post_load_weights wrappers give log(f"wide integ qkvr method {type(attn.qkvr.quant_method).__name__}, fmt " f"{'bf16x' if attn.qkvr.__dict__['_wide'].fmt == ops.BF16X else 'raw'}") gate("wide integ formats", all(e.fmt == (ops.RAW if args.no_pico else ops.BF16X) for e in (attn.qkvr.__dict__["_wide"], attn.wo_ud.__dict__["_wide"], next(iter(patches.HEADS.values())))))
calls = {"wide": 0} real_ext = ops.EXT
class Counting: def __getattr__(self, name): return getattr(real_ext, name)
def gemm(self, *a): calls["wide"] += 1 return real_ext.gemm(*a)
ops.EXT = Counting()
def close(y, ref, bf): tol = (2.0**-7 if bf else 2.0**-12) * float(ref.abs().max()) + 1e-6 d = float((y.float() - ref.float()).abs().max()) if d > tol: log(f"wide integ mismatch max_abs={d:.3e} tol={tol:.3e} ref_max={float(ref.abs().max()):.3e}") return d <= tol
g = torch.Generator(device=dev).manual_seed(1) ops.SET.max_m_kind = {} # every kind to 256 here (the dispatch, not the per-kind caps, is under test) for m, who in ((8, "pico"), (16, "pico"), (17, "wide"), (64, "wide"), (256, "wide"), (300, "stock")): if args.no_pico and who == "pico": who = "stock" x = (torch.rand((m, 2304), device=dev, generator=g) * 2 - 1).to(torch.bfloat16) xo = (torch.rand((m, 3072), device=dev, generator=g) * 2 - 1).to(torch.bfloat16) calls["wide"] = 0 y, _ = attn.qkvr(x) yo, _ = attn.wo_ud(xo) yh = uq.sm12x_fp32_lm_head(x, model.llm.lm_head.weight, None) if uq.sm12x_fp32_lm_head_applies( x, model.llm.lm_head.weight, None) else torch.mm(x, w_head.T, out_dtype=torch.float32) torch.cuda.synchronize() used = calls["wide"] # FP32 references (cuBLAS's own BF16 wo at 40..64 rows errs 2x more than wide vs FP64: not a reference) ok = (close(y, x.float() @ w_qkvr.float().T, True) and close(yo, xo.float() @ w_wo.float().T, True) and close(yh, x.float() @ w_head.float().T, False)) gate(f"wide integ dispatch M={m}", ok and (used == 3) == (who == "wide"), f"expected={who} wide_calls={used}")
for m in (24, 64): q, k, v = ((torch.rand((m, 2304), device=dev, generator=g) * 2 - 1).to(torch.bfloat16) for _ in range(3)) src = am.AttentionSources(q, k, v) calls["wide"] = 0 got = am.Inkling2Attention._project_sources(attn, src) used = calls["wide"] st = F.linear(torch.cat([q, k, v]), w_qkvr) q_p, k_p, v_p = (c.split(splits, dim=-1)[:6] for c in st.chunk(3)) exp = (q_p[0], k_p[1], v_p[2], q_p[3], q_p[4], q_p[5]) layout = all((a.shape, a.stride(), a.storage_offset()) == (b.shape, b.stride(), b.storage_offset()) for a, b in zip(got, exp)) vals = all(close(a, b, True) for a, b in zip(got, exp)) gate(f"wide integ stacked M={m}", layout and vals and used == 1, f"layout={'stock' if layout else 'OTHER'} " f"close={vals} wide_calls={used}") side = torch.cuda.Stream() side.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(side): am.Inkling2Attention._project_sources(attn, src) torch.cuda.current_stream().wait_stream(side) graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): gout = am.Inkling2Attention._project_sources(attn, src) graph.replay() torch.cuda.synchronize() same = all(torch.equal(a.contiguous().view(torch.int16), b.contiguous().view(torch.int16)) for a, b in zip(gout, got)) gate(f"wide integ stacked graph M={m}", same) log(f"wide integration result {'PASS' if not FAILS else 'FAIL'} ({', '.join(FAILS)})") sys.exit(0 if not FAILS else 1)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Combined loader for the Inkling-2-Mini SGLang overlays (verify cap, draft bytes, kernels, pico12, prefill).Each overlay activates only when its environment switch is set; with none set nothing is imported.A failing overlay stops the process (site.py would otherwise only print a warning and run the stock path)."""import osimport sys
def _on(name): return os.environ.get(name, "").strip().lower() not in ("", "0", "off", "none", "false", "no")
try: if _on("INKLING_KV12") and _on("INKLING_KV12S"): raise RuntimeError("INKLING_KV12S and INKLING_KV12 are mutually exclusive") if _on("INKLING_VERIFY_CAP"): from inkling_vcap import activate activate() if _on("INKLING_DRAFT_BYTES"): import inkling_draftbytes inkling_draftbytes.install() if _on("INKLING_KERNELS"): import inkling_kernels inkling_kernels.install() if _on("INKLING_MOE2"): # after inkling_kernels: per-token tile tables over moe_tiles' _tiles wrapper import inkling_moe2 inkling_moe2.install() if _on("INKLING_SCODES"): # NVFP4 expert scale codes (exact; wraps nvfp4_expert_matmul) import inkling_scodes inkling_scodes.install() if _on("INKLING_PICO12"): # after inkling_kernels: its _project_sources wrapper goes outside qkvr_gemv's import inkling_pico12 inkling_pico12.install() if _on("INKLING_PREFILL"): # last: its _project_sources wrapper (large M only) goes outermost import inkling_prefill inkling_prefill.install() if _on("INKLING_PFUSE"): # prefill glue fusion: Inkling2DecoderLayer._forward, extend only import inkling_pfuse inkling_pfuse.install() if _on("INKLING_PROLOGUE"): # SWA prefill: K conv + L2 clip, V conv + value norm fused (FP32-order class) import inkling_prologue inkling_prologue.install() if _on("INKLING_PFUSE_HOIST"): # prefill loop-bank hoist over pfuse's loop_mix (FP32-order class; needs PFUSE) import inkling_phoist inkling_phoist.install() if _on("INKLING_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_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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780import loggingimport osimport sysfrom functools import partialfrom typing import NamedTuple
import torchimport torch.nn.functional as Ffrom torch import nn
from sglang.kernels.ops.attention.inkling2_attn import ( combine_gate_sink, compute_log_scaling_tau, gate_sink, pad_head_groups,)from sglang.kernels.ops.attention.inkling2_attn_prologue import attention_prologuefrom sglang.kernels.ops.communication.inkling2_comm import ( all_reduce, oneshot_all_reduce, oneshot_all_reduce_input,)from sglang.kernels.ops.gemm.inkling2_linear import ( linear, linear_k_group_partials_pair, uses_k_groups,)from sglang.srt.environ import envsfrom sglang.srt.layers.linear import MergedColumnParallelLinear, RowParallelLinearfrom sglang.srt.layers.radix_attention import RadixAttentionfrom sglang.srt.layers.utils.common import add_prefix, set_weight_attrsfrom sglang.srt.model_executor.forward_context import get_attn_backendfrom sglang.srt.models.inkling_common.attn import ( RelLogitsProj, get_inkling_relative_attention_score_mod, serving_attention_backend,)from sglang.srt.models.inkling_common.inkling2_sconv import ShortConvolutionfrom sglang.srt.models.inkling_common.sconv import SconvTypefrom sglang.srt.runtime_context import get_model, get_parallel, get_platformfrom sglang.srt.utils import get_device_core_count
PADDED_DECODE_MIN_TOKENS = 8
def _ink_attn_visit(): """n218 k1: True inside a layer visit the inkling_attn package has taken (False when it is not loaded).""" m = sys.modules.get("inkling_attn.patch") return m is not None and m._CTX.get() is not None
# n2 (inkling2-spark prefill seat): per-source qkvr projection for 3-source visits at prefill sizes._INK_SPLIT_PROJ = os.environ.get("SGLANG_INKLING_SPLIT_PROJ", "0") == "1"_INK_SPLIT_PROJ_MIN_TOKENS = int(os.environ.get("SGLANG_INKLING_SPLIT_PROJ_MIN_TOKENS", "512"))_INK_SPLIT_PROJ_WRAPPED = os.environ.get("INKLING_SPLIT_PROJ_WRAPPED", "0") == "1"
def _is_unquant_method(method): from sglang.srt.layers.quantization.unquant import UnquantizedLinearMethod
return isinstance(method, UnquantizedLinearMethod)# linear() sums split-K partials up to this many rows (its tiles < 256 branch).PAIRED_PARTIALS_MAX_TOKENS = 2048VERIFY_REL_BIAS_MAX_TOKENS = 32
def wave_fill_splits(tiles, sms, max_splits=128, min_fill=0.9): """Smallest KV split count whose CTAs fill at least ``min_fill`` of the last SM wave; the fullest count up to ``max_splits`` otherwise.""" best, best_fill = 1, 0.0 for splits in range(1, max_splits + 1): ctas = tiles * splits fill = ctas / (-(-ctas // sms) * sms) if fill >= min_fill: return splits if fill > best_fill: best, best_fill = splits, fill return best
class AttentionSources(NamedTuple): q: torch.Tensor k: torch.Tensor v: torch.Tensor
def _stacked(sources): """torch.cat(sources) without a copy when the sources are adjacent in memory.""" q = sources.q storage = q.untyped_storage().data_ptr() adjacent = all( x.is_contiguous() and x.shape == q.shape and x.dtype == q.dtype and x.untyped_storage().data_ptr() == storage and x.data_ptr() == q.data_ptr() + i * q.nbytes for i, x in enumerate(sources) ) if adjacent and q.ndim == 2: return q.as_strided((3 * q.shape[0], q.shape[1]), q.stride()) return torch.cat(sources)
class QKL2Clip(nn.Module): def __init__(self, dim, threshold, eps, num_heads, learnable_scale, *, tp_rank=0): super().__init__() self.threshold = threshold self.eps = eps self.tp_rank = tp_rank if learnable_scale: self.scale = nn.Parameter(torch.empty(num_heads, dim), requires_grad=False) set_weight_attrs(self.scale, {"weight_loader": self.weight_loader}) else: self.register_parameter("scale", None)
def weight_loader(self, param, loaded_weight): if loaded_weight.shape != param.shape: loaded_weight = loaded_weight.narrow( 0, self.tp_rank * param.shape[0], param.shape[0] ) assert loaded_weight.shape == param.shape param.data.copy_(loaded_weight)
def forward(self, x, *, output_scale=None): from sglang.kernels.ops.layernorm.inkling2_qk_l2_clip import ( qk_l2_clip_fwd_cutedsl, )
output = qk_l2_clip_fwd_cutedsl( x, self.threshold, self.eps, scale=self.scale, output_scale=output_scale ) return output.view(x.shape)
class Inkling2Attention(nn.Module): def __init__(self, config, layer_id, is_local, prefix=""): super().__init__() parallel = get_parallel() self.tp_rank, self.tp_size = parallel.attn_tp_rank, parallel.attn_tp_size self.hidden_size = config.hidden_size self.num_total_heads = ( config.swa_num_attention_heads if is_local else config.num_attention_heads ) self.num_total_kv_heads = ( config.swa_num_key_value_heads if is_local else config.num_key_value_heads ) self.head_dim = config.swa_head_dim if is_local else config.head_dim assert self.num_total_heads % self.tp_size == 0 assert self.num_total_kv_heads % self.tp_size == 0, ( "Attention TP must divide the number of KV heads" ) self.num_tp_heads = self.num_total_heads // self.tp_size self.num_tp_kv_heads = self.num_total_kv_heads // self.tp_size self.d_rel = config.d_rel self.is_local = is_local self.layer_id = layer_id self.scaling = self.head_dim**-0.5 self.rel_extent = config.sliding_window_size if is_local else config.rel_extent self.log_scaling_n_floor = config.log_scaling_n_floor self.log_scaling_alpha = config.log_scaling_alpha self.split_sizes = [ self.num_tp_heads * self.head_dim, self.num_tp_kv_heads * self.head_dim, self.num_tp_kv_heads * self.head_dim, self.num_tp_heads * self.d_rel, self.num_tp_heads * self.head_dim, self.num_tp_heads, ] qkvr_pad_size = -sum(self.split_sizes) % 8 if qkvr_pad_size: self.split_sizes.append(qkvr_pad_size) self.qkvr = MergedColumnParallelLinear( config.hidden_size, [size * self.tp_size for size in self.split_sizes], bias=config.q_bias, parallel_group="attn_tp", prefix=add_prefix("qkvr", prefix), ) if self.qkvr.bias is not None: self.qkvr.bias.data.zero_() self.wo_ud = RowParallelLinear( self.head_dim * self.num_total_heads, config.hidden_size, bias=config.o_bias, parallel_group="attn_tp", reduce_results=False, use_dp_attention_reduce=True, prefix=add_prefix("wo_ud", prefix), ) self.rel_logits_proj = RelLogitsProj(self.d_rel, self.rel_extent) self.q_l2_clip = QKL2Clip( self.head_dim, config.qk_l2_clip_threshold, 1e-6, self.num_tp_heads, True, tp_rank=self.tp_rank, ) self.k_l2_clip = QKL2Clip( self.head_dim, config.qk_l2_clip_threshold, 1e-6, self.num_tp_kv_heads, False, ) self.rel_l2_clip = QKL2Clip( self.d_rel, config.rel_l2_clip_threshold, 1e-6, self.num_tp_heads, True, tp_rank=self.tp_rank, ) if config.use_value_norm_no_gamma: from sglang.srt.models.inkling_common.inkling2_norm import RMSNorm
self.v_norm = RMSNorm( self.head_dim, config.rms_norm_eps, elementwise_affine=False ) else: self.v_norm = None conv_args = { "hidden_size": self.head_dim * self.num_tp_kv_heads, "kernel_size": config.sconv_kernel_size, "layer_id": layer_id, "tp_rank": self.tp_rank, "tp_size": self.tp_size, "is_dynamic": not is_local, "dynamic_input_size": config.hidden_size, "n_heads": self.num_tp_kv_heads, } self.k_sconv = ShortConvolution( sconv_type=SconvType.K_LOCAL if is_local else SconvType.K_FULL, **conv_args ) self.v_sconv = ShortConvolution( sconv_type=SconvType.V_LOCAL if is_local else SconvType.V_FULL, **conv_args ) # A looped core layer visits num_passes times. Each visit keeps its own # conv state; KV is per pass too unless the passes share the cache. num_passes = ( config.loop_config["num_passes"] if layer_id in config.loop_core_layers else 1 ) self.conv_layer_ids = tuple( config.conv_layer_id(layer_id, pass_idx) for pass_idx in range(num_passes) ) pass_cache_layer_ids = [ config.cache_layer_id(layer_id, pass_idx) for pass_idx in range(num_passes) ] cache_layer_ids = list(dict.fromkeys(pass_cache_layer_ids)) self.pass_attn_index = tuple( cache_layer_ids.index(cache_layer_id) for cache_layer_id in pass_cache_layer_ids ) attention = [ RadixAttention( self.num_tp_heads, self.head_dim, self.scaling, self.num_tp_kv_heads, cache_layer_id, sliding_window_size=config.sliding_window_size - 1 if is_local else -1, prefix=add_prefix("attn", prefix), out_dtype=torch.float32, num_splits=1, pack_gqa=False, strided_lse=True, ) for cache_layer_id in cache_layer_ids ] self.attn = attention[0] if len(attention) == 1 else nn.ModuleList(attention) # FA4 packs GQA heads only for group sizes dividing 128, so decode pads # each KV group with zero query heads up to the next power of two. group = self.num_tp_heads // self.num_tp_kv_heads self.padded_group = 1 << (group - 1).bit_length() kv_heads = self.num_tp_kv_heads pad_rows = kv_heads * (self.padded_group - group) self.fused_decode_prologue = ( self.head_dim == 128 and self.d_rel == 16 and self.rel_extent % 128 == 0 and kv_heads & (kv_heads - 1) == 0 and pad_rows & (pad_rows - 1) == 0 and self.v_norm is not None and self.v_norm.weight is None and self.v_norm.pre_weight is None and self.q_l2_clip.threshold == self.k_l2_clip.threshold and self.q_l2_clip.eps == self.k_l2_clip.eps == self.rel_l2_clip.eps and self.k_sconv.use_residual and self.v_sconv.use_residual ) self.attn_padded = ( nn.ModuleList( RadixAttention( self.num_tp_kv_heads * self.padded_group, self.head_dim, self.scaling, self.num_tp_kv_heads, cache_layer_id, sliding_window_size=( config.sliding_window_size - 1 if is_local else -1 ), prefix=add_prefix("attn_padded", prefix), out_dtype=torch.float32, num_splits=0 if get_platform().is_sm90 else 1, pack_gqa=True, strided_lse=True, ) for cache_layer_id in cache_layer_ids ) if group > 1 and 128 % group else None ) self.verify_wave_splits = not get_platform().is_sm90 self.verify_max_splits = ( -(-config.sliding_window_size // 128) + 1 if is_local else 128 ) # SM120 has no NVLink multicast. self.group_all_reduce = get_platform().is_sm120
def _pad_heads(self, x): return pad_head_groups( x, self.num_tp_heads // self.num_tp_kv_heads, self.padded_group )
def _prologue(self, q, k, v, r, sources, positions, forward_batch): tokens = q.shape[0] k = self.k_sconv( k, positions, forward_batch, dynamic_input=None if self.is_local else sources.k, ) v = self.v_sconv( v, positions, forward_batch, dynamic_input=None if self.is_local else sources.v, ) tau = ( compute_log_scaling_tau( positions, self.log_scaling_n_floor, self.log_scaling_alpha ) if not self.is_local and 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 ) k = self.k_l2_clip(k.reshape(tokens, self.num_tp_kv_heads, self.head_dim)) v = v.reshape(tokens, self.num_tp_kv_heads, self.head_dim) if self.v_norm is not None: v = self.v_norm(v) r = self.rel_l2_clip( r.reshape(tokens, self.num_tp_heads, self.d_rel), output_scale=tau ) return q, k, v, r
def _decode_prologue( self, q, k, v, r, sources, positions, forward_batch, padded, *, verify=False, shear=None, ): """_prologue and rel_logits_proj in one kernel; q and the rel bias come out padded when padded. With verify (MTP verify tokens), the K/V conv windows are saved instead of updating the conv cache; shear: see attention_prologue.""" meta = self.k_sconv._conv_state(forward_batch) if self.is_local: k_weight, v_weight = self.k_sconv._weight_2d(), self.v_sconv._weight_2d() k_dynamic = v_dynamic = None else: k_weight, v_weight = self.k_sconv.static_w, self.v_sconv.static_w k_source, v_source = sources.k.to(k.dtype), sources.v.to(v.dtype) k_proj = self.k_sconv.weight_proj.to(k.dtype) v_proj = self.v_sconv.weight_proj.to(v.dtype) if ( uses_k_groups(k_source, k_proj) and k_source.shape[0] <= PAIRED_PARTIALS_MAX_TOKENS and k_source.stride() == v_source.stride() and k_proj.stride() == v_proj.stride() ): k_dynamic, v_dynamic = linear_k_group_partials_pair( k_source, k_proj, v_source, v_proj ) else: k_dynamic = linear(k_source, k_proj) v_dynamic = linear(v_source, v_proj) tau = not self.is_local and self.log_scaling_n_floor is not None group = self.num_tp_heads // self.num_tp_kv_heads return attention_prologue( q, k, v, r, self.num_tp_heads, self.num_tp_kv_heads, self.d_rel, self.padded_group if padded else group, k_weight, v_weight, self.k_sconv._sconv_cache(), self.v_sconv._sconv_cache(), meta.precomputed, self.q_l2_clip.scale, self.rel_l2_clip.scale, self.rel_logits_proj.proj, forward_batch.seq_lens, self.is_local, self.q_l2_clip.threshold, self.rel_l2_clip.threshold, self.q_l2_clip.eps, self.v_norm.eps, k_dynamic=k_dynamic, v_dynamic=v_dynamic, positions=positions if tau else None, tau_floor=self.log_scaling_n_floor, tau_alpha=self.log_scaling_alpha, track_mask=None if verify else forward_batch.mamba_track_mask, track_indices=None if verify else meta.track_cache_indices, shear=shear, verify_windows=( ( self.k_sconv._intermediate_window(), self.v_sconv._intermediate_window(), ) if verify else None ), )
def _split_proj_ok(self): ok = getattr(self, "_split_proj_ok_cached", None) if ok is None: weight = getattr(self.qkvr, "weight", None) ok = ( weight is not None and weight.dim() == 2 and weight.dtype in (torch.bfloat16, torch.float16, torch.float32) and self.qkvr.bias is None and ( type(self.qkvr.quant_method).__name__ == "UnquantizedLinearMethod" # n324 (c4cache): WIDE / PICO12 swap in per-layer subclasses (WidePico12UnquantizedLinearMethod) # that keep the BF16 weight; the split reads only that weight, so accept them (env-gated). or (_INK_SPLIT_PROJ_WRAPPED and _is_unquant_method(self.qkvr.quant_method)) ) and weight.shape[0] == sum(self.split_sizes) ) self._split_proj_ok_cached = ok logging.getLogger(__name__).info( "INK_SPLIT_PROJ layer %s enabled=%s (quant %s, weight %s)", self.layer_id, ok, type(self.qkvr.quant_method).__name__, None if weight is None else (tuple(weight.shape), weight.dtype), ) return ok
def _project_qkvr(self, x): projected, _ = self.qkvr(x) return projected.split(self.split_sizes, dim=-1)[:6]
def _project_sources(self, sources): if ( _INK_SPLIT_PROJ and len({id(sources.q), id(sources.k), id(sources.v)}) == 3 and sources.q.dim() == 2 and sources.q.shape[0] >= _INK_SPLIT_PROJ_MIN_TOKENS and self._split_proj_ok() ): # n2 (inkling2-spark prefill seat): three distinct sources (loop passes 2-3, global # layers). The stacked form below runs all 3T rows through the full qkvr weight and keeps a # third of each output; at prefill sizes that GEMM is FLOP-bound, so project each source # only onto the rows it uses (q/r/gate/sinks from q's source, k from k's, v from v's). weight = self.qkvr.weight sq, sk, sv, sr, sg, ss = self.split_sizes[:6] o_k, o_v, o_r = sq, sq + sk, sq + sk + sv end = o_r + sr + sg + ss q = F.linear(sources.q, weight[:o_k]) r, gate, sinks = F.linear(sources.q, weight[o_r:end]).split([sr, sg, ss], dim=-1) k = F.linear(sources.k, weight[o_k:o_v]) v = F.linear(sources.v, weight[o_v:o_r]) return q, k, v, r, gate, sinks if len({id(sources.q), id(sources.k), id(sources.v)}) == 3: q_proj, k_proj, v_proj = ( projected.split(self.split_sizes, dim=-1)[:6] for projected in self.qkvr(_stacked(sources))[0].chunk(3) ) q, _, _, r, gate, sinks = q_proj return q, k_proj[1], v_proj[2], r, gate, sinks q_proj = self._project_qkvr(sources.q) k_proj = q_proj if sources.k is sources.q else self._project_qkvr(sources.k) v_proj = ( q_proj if sources.v is sources.q else k_proj if sources.v is sources.k else self._project_qkvr(sources.v) ) q, _, _, r, gate, sinks = q_proj return q, k_proj[1], v_proj[2], r, gate, sinks
def forward(self, hidden_states, positions, forward_batch, *, pass_idx=0): index = self.pass_attn_index[pass_idx] attn = self.attn[index] if isinstance(self.attn, nn.ModuleList) else self.attn attn_padded = None if self.attn_padded is None else self.attn_padded[index] conv_layer_id = self.conv_layer_ids[pass_idx] with ( self.k_sconv.state_layer_override(conv_layer_id), self.v_sconv.state_layer_override(conv_layer_id), ): return self._forward( hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded, )
def _forward(self, hidden_states, positions, forward_batch, *, attn, attn_padded): assert serving_attention_backend(forward_batch) == "fa4", ( "Inkling2 requires FA4 attention" ) mxfp8 = get_model().kv_cache_dtype == "mxfp8" sources = ( AttentionSources(hidden_states, hidden_states, hidden_states) if isinstance(hidden_states, torch.Tensor) else hidden_states ) q, k, v, r, gate, sinks = self._project_sources(sources) tokens = q.shape[0] mode = forward_batch.forward_mode verify = mode.is_target_verify() compact = ( not mxfp8 and self.fused_decode_prologue and ( mode.is_decode() or verify and ( get_platform().is_sm90 or envs.SGLANG_OPT_INKLING2_VERIFY_REL_BIAS_KERNEL.get() and tokens <= VERIFY_REL_BIAS_MAX_TOKENS ) ) ) padded = ( attn_padded is not None and not compact and (get_platform().is_sm90 or tokens >= PADDED_DECODE_MIN_TOKENS) and (mode.is_decode() or verify) ) presheared = False if compact: q, k, v, rel_bias = self._decode_prologue( q, k, v, r, sources, positions, forward_batch, False, verify=verify ) elif padded and verify and self.fused_decode_prologue: fa_meta = get_attn_backend().forward_metadata # The MXFP8 score modifier consumes the unsheared relative-bias row; # SM120 FA4 tiles differ from the 128-row preshear layout, so it shears. presheared = ( not mxfp8 and not get_platform().is_sm90 and not get_platform().is_sm120 and fa_meta.swa_spec_metadata is None and fa_meta.max_seq_len_q * self.padded_group <= 128 ) shear = ( ( fa_meta.cache_seqlens_int32, attn.sliding_window_size if self.is_local else None, ) if presheared else None ) q, k, v, rel_bias = self._decode_prologue( q, k, v, r, sources, positions, forward_batch, True, verify=True, shear=shear, ) else: q, k, v, r = self._prologue(q, k, v, r, sources, positions, forward_batch) # n32 (inkling2-spark attn-bias seat): a sliding-layer EXTEND rel bias is built inside the FA4 SM120 kernel # (n32_attn_local.py); every other path gets self.rel_logits_proj(r) as before. # n218 k1: a visit taken by the knapcio v2.9.3 inkling_attn package keeps the image's own line (its source pin). if not _ink_attn_visit() and _n32_attn_local.wants( self, r, mode.name, padded, mxfp8 ): rel_bias = _n32_attn_local.N32RelBias(r, self.rel_logits_proj) else: rel_bias = self.rel_logits_proj(r) if padded: q, rel_bias = self._pad_heads(q), self._pad_heads(rel_bias) bias_kwargs = {"rel_bias_presheared": True} if presheared else {} output_dtype = q.dtype if mxfp8: from sglang.kernels.ops.quantization.mxfp8_quant import to_mxfp8
quantized_q = to_mxfp8(q.reshape(tokens, -1, self.head_dim)) q = quantized_q.data # MXFP8 dequant buffers leave no room for shared-memory bias staging. attention_kwargs = dict( score_mod=get_inkling_relative_attention_score_mod(self.rel_extent), aux_tensors=[rel_bias], q_descale=quantized_q.scale.view(torch.float8_e8m0fnu), ) else: attention_kwargs = dict(rel_bias=rel_bias, **bias_kwargs) if compact: output = attn( q, k, v, forward_batch, rel_bias=rel_bias, rel_bias_compact_decode=True, rel_bias_decode_epilogue=partial( combine_gate_sink, gate=gate, sinks=sinks ), ) elif padded: if self.verify_wave_splits: num_splits = 1 if verify and (not self.is_local or forward_batch.batch_size == 1): num_splits = wave_fill_splits( forward_batch.batch_size * self.num_tp_kv_heads * -( -tokens * self.padded_group // (128 * forward_batch.batch_size) ), get_device_core_count(q.device.index), self.verify_max_splits, ) attn_padded.num_splits = num_splits output, lse = attn_padded( q, k, v, forward_batch, return_lse=True, **attention_kwargs, ) head_groups = (self.num_tp_heads // self.num_tp_kv_heads, self.padded_group) else: output, lse = attn( q, k, v, forward_batch, return_lse=True, **attention_kwargs, ) head_groups = None if not compact: output = gate_sink( output.reshape(tokens, -1), gate, lse, sinks, output_dtype=output_dtype, head_groups=head_groups, ) parallel = get_parallel() multicast = parallel.moe_ep_size > 1 if self.group_all_reduce or ( multicast and (mode.is_decode() or verify) and envs.SGLANG_OPT_INKLING2_ATTN_PUSH_ALL_REDUCE.get() ): output, _ = self.wo_ud(output) return parallel.attn_tp_group.all_reduce(output) buffer = ( oneshot_all_reduce_input( parallel.attn_tp_group, tokens, self.hidden_size, output.dtype ) if multicast else None ) if buffer is not None: self.wo_ud(output, output_tensor=buffer) return oneshot_all_reduce(buffer, parallel.attn_tp_group) output, _ = self.wo_ud(output) return all_reduce(output, parallel.attn_tp_group, multicast=multicast)
# n13 (inkling2-spark attn-global seat, 2026-11-21): the global-layer rel-bias prefill FA4 SM120 kernel is built as# FlashAttentionForwardSm120BandSplit (fa4_sm120/n13_fwd.py, mounted): the only change to this file is this hook install.from sglang.srt.models.inkling_common import n13_attn_global as _n13_attn_global # noqa: E402
_n13_attn_global.install()
# n32 (inkling2-spark attn-bias seat, 2026-11-21): the sliding-layer prefill rel bias is computed inside the FA4 SM120 kernel# (fa4_sm120/n32_fwd.py + n32_attn_local.py, mounted), bitwise equal to the served path: this hook install and the guarded# rel_bias line in _forward are the only changes to n21's file.from sglang.srt.models.inkling_common import n32_attn_local as _n32_attn_local # noqa: E402
_n32_attn_local.install()
# n64 (inkling2-spark attn seat, 2026-11-22): global-layer prefill attention as kernel A (n54's band part + state store,# fa4_sm120/n64a_fwd.py) then kernel B (8 consumer warps on the far blocks, fa4_sm120/n64b_fwd.py), bitwise equal to n54's# kernel (hook n64_attn_global.py, after n32's; switch SGLANG_INKLING_N64). The only change to this file is this hook install.from sglang.srt.models.inkling_common import n64_attn_global as _n64_attn_global # noqa: E402
_n64_attn_global.install()
# n35 (inkling2-spark decode seat, 2026-11-21): MXFP8 W8A16 qkvr / wo_ud (and optionally the LM head) on decode / verify# forwards only (patch/n35_w8.py, selected by N35_W8; prefill unchanged). The only change to this file is this hook install.from sglang.srt.models.inkling_common import n35_w8 as _n35_w8 # noqa: E402
_n35_w8.install()
# n37 (inkling2-spark decode seat, 2026-11-21): NVFP4 grouped-GEMM decode tile_k 256 (patch/n37_tiles.py, bitwise equal).from sglang.srt.models.inkling_common import n37_tiles as _n37_tiles # noqa: E402
_n37_tiles.install()
# n14 (inkling2-spark moe seat, 2026-11-21): SM120 MoE prefill visits with token-major quantize-once and a BF16-direct combine# (patch/n14_moe.py + patch/n14_quant.cuh, mounted), bitwise equal to the image path; calls under 512 tokens keep the image path.# The only change to this file is this hook install.from sglang.srt.models.inkling_common import n14_moe as _n14_moe # noqa: E402
_n14_moe.install()
# n52 (inkling2-spark moe seat, 2026-11-23): on NVFP4 MoE prefill calls of >= 3,073 tokens, the gate_up grouped GEMM does the# swiglu + NVFP4 quantization per 128-row band from L2 (patch/n52_moe.py + patch/n52_band.cuh, mounted), bitwise equal to S3's# visit; installed after n14 (it wraps the method n14 installed; every other call goes to n14's path). Knobs N52_BAND (2 = on,# 0 = off), N52_RASTER, N52_LEAN. The only change to this file is this hook install.from sglang.srt.models.inkling_common import n52_moe as _n52_moe # noqa: E402
_n52_moe.install()
# n75 (inkling2-spark packed seat, 2026-11-22): exact 12-bit packed BF16 qkvr / wo_ud / LM head on the served small-M GEMV route# (patch/n75_install.py + patch/n75_c12.py, mounted; knob N75_C12 attn,lm | empty = off). The only change to this file is this# hook install.from sglang.srt.models.inkling_common import n75_install as _n75_install # noqa: E402
_n75_install.install()
# n86 (inkling2-spark stack seat, 2026-11-23): S1 riders G1 (MLP sconv + residual) and G2 (AttnRes + RMSNorm) on the served# decoder-layer extend path, and the n75 M / shape / build-2 gate (patch/n86_riders.py + n71_sconvres.py + n71_resnorm.py,# mounted; knobs N86_G1 / N86_G2, default off = the n54 code path). The only change to this file after n75's block is this install.from sglang.srt.models.inkling_common import n86_riders as _n86_riders # noqa: E402
_n86_riders.install()
# n78 certified greedy LM head, S8 (inkling2-spark packed seat, 2026-11-23): patch/n78_head.py + patch/n78_kern.py, mounted. Knob# N78_CERT 1 | empty = off (n54's path exactly); N78_CHECK 1 = check boot only. The only change to this file is this install.from sglang.srt.models.inkling_common import n78_head as _n78_head # noqa: E402
_n78_head.install()
# n80 exact 12-bit DSpark drafter linears (decode seat's rider; composed into S7 by the stack seat, tree n151, 2026-11-24): patch/n80_draft.py +# patch/n80_cuda.py + patch/n140_kern.py (n140's INT6 screen of n78_head.py), mounted. Knob N80_DRAFT ('' = off; B = qkv / o / gate_up on n75's build 2# and down_proj on c12mk); it needs n75 on (N75_C12 non-empty) and replaces n75_install._prepare with a wrapper that calls the original first, so it# installs after n75's and n86's installs (its draft classes pass the n86 gate only with patch/n86_riders.py = n86_riders_s7.py ecc4992b).# The only change to this file after n78's block is this install.from sglang.srt.models.inkling_common import n80_draft as _n80_draft # noqa: E402
_n80_draft.install()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280import functools
import torchimport tritonimport triton.language as tlfrom triton.language.extra import libdevice
from sglang.kernels.jit.utils import is_arch_support_pdl
@triton.jitdef _controller_norm( Dest, Message, Normed, T, DEST_STRIDE, MESSAGE_STRIDE, eps, W: tl.constexpr, BLOCK: tl.constexpr, USE_PDL: tl.constexpr,): if USE_PDL: tl.extra.cuda.gdc_wait() tl.extra.cuda.gdc_launch_dependents() t = tl.program_id(0).to(tl.int64) m = tl.program_id(1).to(tl.int64) cols = tl.arange(0, BLOCK) valid = cols < W dest = tl.load(Dest + m * DEST_STRIDE + t * W + cols, valid, other=0) message = tl.load(Message + m * MESSAGE_STRIDE + t * W + cols, valid, other=0) dest_rstd = libdevice.rsqrt(tl.div_rn(tl.sum(dest * dest), W) + eps) message_rstd = libdevice.rsqrt(tl.div_rn(tl.sum(message * message), W) + eps) out = Normed + (m * T + t) * (2 * W) tl.store(out + cols, (dest * dest_rstd).to(tl.bfloat16), valid) tl.store(out + W + cols, (message * message_rstd).to(tl.bfloat16), valid)
@triton.jitdef _controller_down( Normed, Down, Partials, T, R: tl.constexpr, K: tl.constexpr, SPLIT: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, USE_PDL: tl.constexpr,): """Per 1024-wide K group partials of normed @ down.T, summed in group order unless SPLIT, where each program writes one group's partial.""" if USE_PDL: tl.extra.cuda.gdc_wait() tl.extra.cuda.gdc_launch_dependents() GROUPS: tl.constexpr = (K + 1023) // 1024 rows = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) cols = tl.program_id(1) * BLOCK_N + tl.arange(0, BLOCK_N) z = tl.program_id(2) if SPLIT: m = z // GROUPS first = z % GROUPS count = 1 else: m = z first = 0 count = GROUPS out = Partials + (z.to(tl.int64) * T) * R X = Normed + (m.to(tl.int64) * T) * K Wd = Down + m.to(tl.int64) * R * K ks = tl.arange(0, BLOCK_K) total = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) for group in range(first, first + count): partial = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) for tile in range(1024 // BLOCK_K): k = group * 1024 + tile * BLOCK_K + ks x = tl.load( X + rows[:, None].to(tl.int64) * K + k[None, :], (rows[:, None] < T) & (k[None, :] < K), other=0, ) w = tl.load( Wd + cols[None, :] * K + k[:, None], (cols[None, :] < R) & (k[:, None] < K), other=0, ) partial = tl.dot(x, w, partial) if group == first: total = partial else: total = total + partial tl.store( out + rows[:, None].to(tl.int64) * R + cols[None, :], total, (rows[:, None] < T) & (cols[None, :] < R), )
@triton.jitdef _controller_mix( Partials, Gain, Forget, Dest, Message, Out, T, DEST_STRIDE, MESSAGE_STRIDE, W: tl.constexpr, R: tl.constexpr, BLOCK_R: tl.constexpr, GROUPS: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, COLS: tl.constexpr, STAGES: tl.constexpr, USE_PDL: tl.constexpr,): """Rows BLOCK_M x columns [pid2 * COLS, (pid2 + 1) * COLS) of controller pid1.""" if USE_PDL: tl.extra.cuda.gdc_wait() tl.extra.cuda.gdc_launch_dependents() rows = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) m = tl.program_id(1).to(tl.int64) first = tl.program_id(2) * COLS rank = tl.arange(0, BLOCK_R) row_ok = rows[:, None] < T hidden_ok = row_ok & (rank[None, :] < R) p = Partials + (m * GROUPS * T + rows[:, None]) * R + rank[None, :] hidden = tl.load(p, hidden_ok, other=0) for group in tl.static_range(1, GROUPS): hidden = hidden + tl.load(p + group * T * R, hidden_ok, other=0) hidden = hidden.to(tl.bfloat16) for start in tl.range(first, first + COLS, BLOCK_N, num_stages=STAGES): cols = start + tl.arange(0, BLOCK_N) col_ok = cols[None, :] < W weight_ok = col_ok & (rank[:, None] < R) weights = m * W * R + cols[None, :] * R + rank[:, None] offsets = rows[:, None].to(tl.int64) * W + cols[None, :] mask = row_ok & col_ok dest = tl.load(Dest + m * DEST_STRIDE + offsets, mask, other=0) message = tl.load(Message + m * MESSAGE_STRIDE + offsets, mask, other=0) gain = tl.dot(hidden, tl.load(Gain + weights, weight_ok, other=0)) forget = tl.dot(hidden, tl.load(Forget + weights, weight_ok, other=0)) output = (1.0 - libdevice.tanh(forget)) * dest + libdevice.tanh(gain) * message tl.store(Out + m * T * W + offsets, output, mask)
@functools.cachedef _sm_count(device_index: int) -> int: return torch.cuda.get_device_properties(device_index).multi_processor_count
@functools.cachedef _max_shared_mem(device_index: int) -> int: props = triton.runtime.driver.active.utils.get_device_properties(device_index) return props["max_shared_mem"]
def _stacked(rows: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, int]: """Base tensor and per-module element stride of equally shaped fp32 rows, without a copy when they already sit at a constant stride (0 for repeats).""" base = rows[0] assert base.dtype == torch.float32 and base.ndim == 2 and base.is_contiguous() assert all( r.shape == base.shape and r.dtype == base.dtype and r.is_contiguous() for r in rows ) if len(rows) == 1: return base, 0 step = rows[1].data_ptr() - base.data_ptr() if step % 4 == 0 and all( r.data_ptr() == base.data_ptr() + i * step for i, r in enumerate(rows) ): return base, step // 4 return torch.stack(rows), base.numel()
def message_controllers(dests, messages, down, gain, forget, eps=1e-6): """Mix messages[i] into dests[i] with controller i of the stacked weights into row i of the (len(dests), tokens, width) output: (1 - tanh(h @ forget.T)) * dest + tanh(h @ gain.T) * message, where h is the bf16 down projection of the bf16 RMS-normalized (dest, message) pair.""" num, rank, k = down.shape assert len(dests) == len(messages) == num assert gain.shape == forget.shape == (num, k // 2, rank) assert down.dtype == gain.dtype == forget.dtype == torch.bfloat16 assert down.is_contiguous() and gain.is_contiguous() and forget.is_contiguous() dest, dest_stride = _stacked(tuple(dests)) message, message_stride = _stacked(tuple(messages)) tokens, width = dests[0].shape assert width * 2 == k and messages[0].shape == dests[0].shape out = torch.empty((num, tokens, width), dtype=torch.float32, device=dest.device) if not tokens: return out pdl = is_arch_support_pdl() launch = {"launch_pdl": True} if pdl else {} normed = torch.empty((num, tokens, k), dtype=torch.bfloat16, device=dest.device) _controller_norm[(tokens, num)]( dest, message, normed, tokens, dest_stride, message_stride, eps, width, triton.next_power_of_2(width), pdl, num_warps=8, enable_fp_fusion=False, **launch, ) groups = triton.cdiv(k, 1024) decode = tokens <= 16 split = tokens <= 4096 block_m = 16 if decode else 64 block_n = 16 if decode else 64 block_k = 256 if tokens <= 1024 else 64 # 64 x 64 tiles with 256-wide K stages need 128 KB of shared memory; SM120 has 99 KB. if not decode and block_k == 256 and _max_shared_mem(dest.device.index) < 1 << 17: block_k = 128 partial_groups = groups if split else 1 partials = torch.empty( (num, partial_groups, tokens, rank), dtype=torch.float32, device=dest.device ) _controller_down[ (triton.cdiv(tokens, block_m), triton.cdiv(rank, block_n), num * partial_groups) ]( normed, down, partials, tokens, rank, k, split, block_m, block_n, block_k, pdl, num_warps=4, num_stages=3, enable_fp_fusion=False, **launch, ) mix_m, mix_n = (16, 64) if decode else (32, 64) row_blocks, col_tiles = triton.cdiv(tokens, mix_m), triton.cdiv(width, mix_n) tiles_per_program = ( 1 if decode else max(1, col_tiles * row_blocks * num // (12 * _sm_count(dest.device.index))) ) _controller_mix[(row_blocks, num, triton.cdiv(col_tiles, tiles_per_program))]( partials, gain, forget, dest, message, out, tokens, dest_stride, message_stride, width, rank, max(16, triton.next_power_of_2(rank)), partial_groups, mix_m, mix_n, tiles_per_program * mix_n, 1 if decode else 3, pdl, num_warps=4 if decode else 8, enable_fp_fusion=False, **launch, ) return out1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768from typing import Literal
import torchfrom torch import nn
from sglang.kernels.ops.elementwise.inkling2_loop import message_controllers
CONTROLLER_MODULES = ("attn", "k", "v", "mlp")_SIDE_ROWS = {"attn": slice(0, 3), "mlp": slice(3, 4)}
class Inkling2MessageController(nn.Module): def __init__(self, width: int, rank: int): super().__init__() self.down_weight = nn.Parameter( torch.empty(rank, 2 * width, dtype=torch.bfloat16) ) self.gain_weight = nn.Parameter(torch.empty(width, rank, dtype=torch.bfloat16)) self.forget_weight = nn.Parameter( torch.empty(width, rank, dtype=torch.bfloat16) )
def stack_controller_weights(controllers: nn.ModuleDict) -> tuple[torch.Tensor, ...]: """Stack each weight of the CONTROLLER_MODULES controllers into one tensor and point the parameters at its rows, so reloads update the stacked copy.""" stacked = [] for name in ("down_weight", "gain_weight", "forget_weight"): params = [getattr(controllers[m], name) for m in CONTROLLER_MODULES] weight = torch.stack([p.data for p in params]) for param, row in zip(params, weight): param.data = row stacked.append(weight) return tuple(stacked)
def scaled_loop_queries(queries: torch.Tensor, kv_queries: torch.Tensor): """(core layers, CONTROLLER_MODULES, width) message queries times width**-0.5.""" stacked = torch.stack( (queries[0::2], kv_queries[0::2], kv_queries[1::2], queries[1::2]), dim=1 ) return stacked.float() * (stacked.shape[-1] ** -0.5)
class LoopMessageBank: def __init__(self, blocks: tuple[torch.Tensor, ...], scaled_queries: torch.Tensor): assert blocks and scaled_queries.dtype == torch.float32 self.blocks = [x.contiguous() for x in blocks] self.scaled_queries = scaled_queries
def mix( self, layer: int, destinations: tuple[torch.Tensor, ...], weights: tuple[torch.Tensor, ...], side: Literal["attn", "mlp"], ) -> torch.Tensor: from sglang.kernels.ops.attention.inkling2_attn_res import attn_res
rows = _SIDE_ROWS[side] messages = attn_res( self.blocks, None, self.scaled_queries[layer, rows], normalize_values=True ) return message_controllers( tuple(d.float() for d in destinations), messages, *(w[rows] for w in weights), )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783"""n105 Build 3: Fast Certified 90%-Hoisted Exact Bitwise DSpark Markov RNN Projection (Inkling-2-Mini, GB10 sm_121).
Evolution from Build 2 (mb2 proved 100% bitwise exactness across 65,280 gates, 537,600 direct outputs, and22.5M full-walk logits, but hit NO_KEEP at -167.8 us due to (1) TwoSum + 208 subnormal branches in precompute= 102 us, and (2) 1-halfwarp/SM serial inline fixup = 130 us across 7 steps):
Build 3 (FAST-CERT90) fixes BOTH bottlenecks while keeping the mathematical bitwise-exact theorem:1. Precompute (init_state): Plain __fmaf_rn + |acc| running bound (ZERO TwoSum, ZERO subnormal branches!). By IEEE-754 FMA semantics, |fl_fma(w,x,a) - (a+w*x)| <= u*|fl| + eta unconditionally for ALL finite w,x,a (even subnormal w*x!), and Inf/NaN makes err_abs non-finite -> pre_err = INF -> exact fixup runs! Stores compact float2(pre_val, pre_err) (43 KB) and zeroes 7-step fix_cnts[7] in-place. Provides: - pre_bf16_sep<nw=2,4>: 2 rows/warp (384 warps), W_f once + W_h x7, 2-ahead ld.cs. - pre_bf16_splitg<nw=4,8>: 1 row/warp (768 warps = 16 warps/SM!), ty=0 g=0..8 & ty=1 g=9..17, 1 shuffle combine! - pre_c12_splitg<nw=4,8>: same 16 warps/SM split-g over lossless C12 (5.31 MB, BASE=109, 99.925% in-window).2. Step (x7 in walk, W_s = 0.786 MB L2-hot + parallel high-MLP exact stride-16 fixup on ~9% tripped rows): - step_fused_coop6 (128x96, 6 rows/block, 1 kernel/step): all 6 half-warps cooperatively prefetch 6 chunks/wave with double-buffering into 1.5 KB smem -> 6 waves instead of 36! Fuses _rnn_inputs + exact _rnn_gates.ptx. - step_fused_coop6_1t (256x96, 3 rows/block = 1 triple/block, 1 kernel/step): eliminates 2-tripped-rows/block straggler tail while keeping all 6 half-warps cooperating on any tripped row (6 waves!). - step_fast + step_fixup_coop8 + fast_gates (split 2/3-kernel): step_fast (192x64, ~2 us, zero fixup code) + step_fixup_coop8 (64x128 persistent blocks, 8 half-warps/tripped row -> 5 waves, zero block straggler!) + 1-block 256-thread exact _rnn_gates (~1.5 us). - step_proj_4ahead (192x64, 4-ahead register prefetch inline fixup, 0 barriers) + 1-block exact _rnn_gates.
Pointer-offset walk-step recovery adapts MIT-licensed code from knapcio/Inkling-2-Mini-1x-DGX-Spark(Copyright (c) 2026 Zbigniew Majewski, MIT License). Non-matching calls (bs != 1, etc.) fall back cleanly to stock."""from __future__ import annotations
import jsonimport loggingimport osimport sysimport threadingimport timefrom dataclasses import dataclassfrom typing import Optional
import torch
logger = logging.getLogger(__name__)
RANK = 256HIDDEN = 2304K_TOTAL = 2 * RANK + 2 * HIDDEN # 5120N_OUT = 3 * RANK # 768GAMMA = 7C12_BASE = 109 # [109..123] covers 99.925% of real rnn_proj.weight
CUDA_SRC = r'''#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <cuda_bf16.h>#include <stdint.h>#include <math.h>
static constexpr float U_F32 = 5.9604644775390625e-8f; // 2^-24static constexpr float A288_U = 5.9605668e-8f; // (1/(1-u))^288 * u
__device__ __forceinline__ uint4 ld_cs_u4(const uint4* ptr) { uint4 v; asm volatile("ld.global.cs.v4.u32 {%0, %1, %2, %3}, [%4];\n" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(ptr)); return v;}
__device__ __forceinline__ uint2 ld_cs_u2(const uint2* ptr) { uint2 v; asm volatile("ld.global.cs.v2.u32 {%0, %1}, [%2];\n" : "=r"(v.x), "=r"(v.y) : "l"(ptr)); return v;}
__device__ __forceinline__ uint32_t ld_cs_u32(const uint32_t* ptr) { uint32_t v; asm volatile("ld.global.cs.u32 %0, [%1];\n" : "=r"(v) : "l"(ptr)); return v;}
__device__ __forceinline__ float bf16_u16_to_f32(uint16_t bits) { return __uint_as_float((uint32_t)bits << 16);}
// Exact 8-step ascending FFMA (gemvx stride=16 order!)__device__ __forceinline__ float fma8_stride16(uint4 wv, const uint16_t* __restrict__ x_base, int tx, float acc) { uint32_t ww; ww = wv.x; acc = __fmaf_rn(__uint_as_float(ww << 16), bf16_u16_to_f32(__ldg(x_base + 0 * 16 + tx)), acc); acc = __fmaf_rn(__uint_as_float(ww & 0xFFFF0000u), bf16_u16_to_f32(__ldg(x_base + 1 * 16 + tx)), acc); ww = wv.y; acc = __fmaf_rn(__uint_as_float(ww << 16), bf16_u16_to_f32(__ldg(x_base + 2 * 16 + tx)), acc); acc = __fmaf_rn(__uint_as_float(ww & 0xFFFF0000u), bf16_u16_to_f32(__ldg(x_base + 3 * 16 + tx)), acc); ww = wv.z; acc = __fmaf_rn(__uint_as_float(ww << 16), bf16_u16_to_f32(__ldg(x_base + 4 * 16 + tx)), acc); acc = __fmaf_rn(__uint_as_float(ww & 0xFFFF0000u), bf16_u16_to_f32(__ldg(x_base + 5 * 16 + tx)), acc); ww = wv.w; acc = __fmaf_rn(__uint_as_float(ww << 16), bf16_u16_to_f32(__ldg(x_base + 6 * 16 + tx)), acc); acc = __fmaf_rn(__uint_as_float(ww & 0xFFFF0000u), bf16_u16_to_f32(__ldg(x_base + 7 * 16 + tx)), acc); return acc;}
// Plain FFMA + running |acc| bound (ZERO TwoSum, ZERO branches, unconditional FMA theorem!)__device__ __forceinline__ void fma8_bound(uint4 wv, const uint16_t* __restrict__ x_base, int tx, float& acc, float& err) { uint32_t ww; ww = wv.x; acc = __fmaf_rn(__uint_as_float(ww << 16), bf16_u16_to_f32(__ldg(x_base + 0 * 16 + tx)), acc); err = __fadd_rn(err, fabsf(acc)); acc = __fmaf_rn(__uint_as_float(ww & 0xFFFF0000u), bf16_u16_to_f32(__ldg(x_base + 1 * 16 + tx)), acc); err = __fadd_rn(err, fabsf(acc)); ww = wv.y; acc = __fmaf_rn(__uint_as_float(ww << 16), bf16_u16_to_f32(__ldg(x_base + 2 * 16 + tx)), acc); err = __fadd_rn(err, fabsf(acc)); acc = __fmaf_rn(__uint_as_float(ww & 0xFFFF0000u), bf16_u16_to_f32(__ldg(x_base + 3 * 16 + tx)), acc); err = __fadd_rn(err, fabsf(acc)); ww = wv.z; acc = __fmaf_rn(__uint_as_float(ww << 16), bf16_u16_to_f32(__ldg(x_base + 4 * 16 + tx)), acc); err = __fadd_rn(err, fabsf(acc)); acc = __fmaf_rn(__uint_as_float(ww & 0xFFFF0000u), bf16_u16_to_f32(__ldg(x_base + 5 * 16 + tx)), acc); err = __fadd_rn(err, fabsf(acc)); ww = wv.w; acc = __fmaf_rn(__uint_as_float(ww << 16), bf16_u16_to_f32(__ldg(x_base + 6 * 16 + tx)), acc); err = __fadd_rn(err, fabsf(acc)); acc = __fmaf_rn(__uint_as_float(ww & 0xFFFF0000u), bf16_u16_to_f32(__ldg(x_base + 7 * 16 + tx)), acc); err = __fadd_rn(err, fabsf(acc));}
// Decode 8 C12 weights (BASE=109, escape nibble 15 -> W_raw)__device__ __forceinline__ void decode_c12_8(uint2 sm, uint32_t e4, const uint16_t* __restrict__ w_raw_row, int k_base, int tx, float out[8]) { uint32_t has_esc = e4 & (e4 >> 1); has_esc = (has_esc & (has_esc >> 2)) & 0x11111111u; uint32_t sm_lo = sm.x, sm_hi = sm.y; #pragma unroll for (int i = 0; i < 4; ++i) { uint32_t s = (sm_lo >> (i * 8)) & 0xFFu; uint32_t c = (e4 >> (i * 4)) & 0xFu; out[i] = __uint_as_float(((s & 0x80u) << 24) | ((c + 109u) << 23) | ((s & 0x7Fu) << 16)); } #pragma unroll for (int i = 0; i < 4; ++i) { uint32_t s = (sm_hi >> (i * 8)) & 0xFFu; uint32_t c = (e4 >> ((i + 4) * 4)) & 0xFu; out[i + 4] = __uint_as_float(((s & 0x80u) << 24) | ((c + 109u) << 23) | ((s & 0x7Fu) << 16)); } if (__builtin_expect(has_esc != 0u, 0)) { #pragma unroll for (int i = 0; i < 8; ++i) { if (((e4 >> (i * 4)) & 0xFu) == 15u) { out[i] = bf16_u16_to_f32(__ldg(w_raw_row + k_base + i * 16 + tx)); } } }}
__device__ __forceinline__ float reduce16_sum(float v, unsigned int rmask) { v = __fadd_rn(v, __shfl_down_sync(rmask, v, 8, 16)); v = __fadd_rn(v, __shfl_down_sync(rmask, v, 4, 16)); v = __fadd_rn(v, __shfl_down_sync(rmask, v, 2, 16)); v = __fadd_rn(v, __shfl_down_sync(rmask, v, 1, 16)); return v;}
// ---------------------------------------------------------------------------// Exact Triton _rnn_gates.ptx math (__CUDA_FTZ=1 libdevice.exp / libdevice.tanh)// Proven 0/65,280 mismatches in mb2!// ---------------------------------------------------------------------------__device__ __forceinline__ float triton_expf(float x) { float res; asm("{\n" " .reg .f32 fa, fk, fb, fc, fd, fsc;\n" " .reg .b32 bk, bsc;\n" " fma.rn.ftz.f32 fa, %1, 0f3BBB989D, 0f3F000000;\n" " cvt.ftz.sat.f32.f32 fa, fa;\n" " fma.rm.ftz.f32 fk, fa, 0f437C0000, 0f4B400001;\n" " add.rn.f32 fb, fk, 0fCB40007F;\n" " neg.f32 fb, fb;\n" " fma.rn.ftz.f32 fc, %1, 0f3FB8AA3B, fb;\n" " fma.rn.ftz.f32 fc, %1, 0f32A57060, fc;\n" " ex2.approx.ftz.f32 fd, fc;\n" " mov.b32 bk, fk;\n" " shl.b32 bsc, bk, 23;\n" " mov.b32 fsc, bsc;\n" " mul.rn.f32 %0, fd, fsc;\n" "}\n" : "=f"(res) : "f"(x)); return res;}
__device__ __forceinline__ float triton_tanhf(float x) { float ax; asm("abs.ftz.f32 %0, %1;\n" : "=f"(ax) : "f"(x)); if (ax < __uint_as_float(0x3F19999Au)) { float x2 = __fmul_rn(x, x); float p; asm("fma.rn.ftz.f32 %0, 0f3C80F082, %1, 0fBD563CAE;\n" "fma.rn.ftz.f32 %0, %0, %1, 0f3E085941;\n" "fma.rn.ftz.f32 %0, %0, %1, 0fBEAAA9ED;\n" "fma.rn.ftz.f32 %0, %0, %1, 0f00000000;\n" "fma.rn.ftz.f32 %0, %0, %2, %2;\n" : "=f"(p) : "f"(x2), "f"(x)); return p; } else { float t = __fmul_rn(ax, __uint_as_float(0x4038AA3Bu)); float r; asm("ex2.approx.ftz.f32 %0, %1;\n" "add.rn.f32 %0, %0, 0f3F800000;\n" "rcp.approx.ftz.f32 %0, %0;\n" "fma.rn.ftz.f32 %0, %0, 0fC0000000, 0f3F800000;\n" : "=f"(r) : "f"(t)); if (ax >= __uint_as_float(0x41102CB4u)) r = 1.0f; return __uint_as_float(__float_as_uint(r) | (__float_as_uint(x) & 0x80000000u)); }}
__device__ __forceinline__ void apply_triton_gates( __nv_bfloat16 gate_b, __nv_bfloat16 cand_b, __nv_bfloat16 out_b, __nv_bfloat16 st_b, __nv_bfloat16& new_st, __nv_bfloat16& lat) { float gate_raw = __bfloat162float(gate_b); float cand_raw = __bfloat162float(cand_b); float out_raw = __bfloat162float(out_b); float st = __bfloat162float(st_b); float ex = triton_expf(-gate_raw); float gate_f = __fdiv_rn(1.0f, __fadd_rn(1.0f, ex)); float gate = __bfloat162float(__float2bfloat16_rn(gate_f)); float kept = __bfloat162float(__float2bfloat16_rn(__fmul_rn(gate, st))); float one_mg = __bfloat162float(__float2bfloat16_rn(__fsub_rn(1.0f, gate))); float cand = __bfloat162float(__float2bfloat16_rn(triton_tanhf(cand_raw))); float blend = __bfloat162float(__float2bfloat16_rn(__fmul_rn(one_mg, cand))); new_st = __float2bfloat16_rn(__fadd_rn(kept, blend)); lat = __float2bfloat16_rn(triton_tanhf(out_raw));}
// ---------------------------------------------------------------------------// Precompute 1A: Plain-FMA BF16 separated (2 rows/warp = 384 warps, 0 branches!)// Output pre_out: [7, 768] float2 = (pre_val_plus_bias, pre_err).// Also zeroes optional fix_cnts[7] for split-step kernels!// ---------------------------------------------------------------------------template <int NW>__global__ void __launch_bounds__(NW * 32)n105_pre_bf16_sep_kernel( const uint4* __restrict__ w_h, const uint4* __restrict__ w_f, const __nv_bfloat16* __restrict__ bias, const uint16_t* __restrict__ hidden_7, const uint16_t* __restrict__ f_rnn, float2* __restrict__ pre_out, int* __restrict__ fix_cnts, int hidden_step_bf16) { if (fix_cnts && blockIdx.x == 0 && threadIdx.x < 7) fix_cnts[threadIdx.x] = 0; const int warp = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int ty = lane >> 4; const int tx = lane & 15; const int n = (blockIdx.x * NW + warp) * 2 + ty; if (n >= 768) return; const unsigned int rmask = (ty == 0) ? 0x0000FFFFu : 0xFFFF0000u;
// Phase 1: W_f @ f_rnn (1x, 2-ahead ld.cs) const uint4* wf_row = w_f + (size_t)n * 288 + tx; float f_acc = 0.f, f_err = 0.f; uint4 wf0 = ld_cs_u4(wf_row + 0 * 16); uint4 wf1 = ld_cs_u4(wf_row + 1 * 16); #pragma unroll for (int g = 0; g < 18; ++g) { uint4 wcur = wf0; wf0 = wf1; if (g + 2 < 18) wf1 = ld_cs_u4(wf_row + (g + 2) * 16); fma8_bound(wcur, f_rnn + g * 128, tx, f_acc, f_err); } float f_end_abs = fabsf(f_acc); float rf = reduce16_sum(f_acc, rmask); float sum_f_err = reduce16_sum(f_err, rmask); float l1_f_end = reduce16_sum(f_end_abs, rmask); float b_val = (tx == 0) ? __bfloat162float(__ldg(bias + n)) : 0.f;
// Phase 2: W_h @ hidden_7 (7 steps, 2-ahead ld.cs) const uint4* wh_row = w_h + (size_t)n * 288 + tx; float h_acc[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; float h_err[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; uint4 wh0 = ld_cs_u4(wh_row + 0 * 16); uint4 wh1 = ld_cs_u4(wh_row + 1 * 16); #pragma unroll 2 for (int g = 0; g < 18; ++g) { uint4 wcur = wh0; wh0 = wh1; if (g + 2 < 18) wh1 = ld_cs_u4(wh_row + (g + 2) * 16); const uint16_t* hb = hidden_7 + g * 128; #pragma unroll for (int s = 0; s < 7; ++s) { fma8_bound(wcur, hb + s * hidden_step_bf16, tx, h_acc[s], h_err[s]); } }
#pragma unroll for (int s = 0; s < 7; ++s) { float h_end_abs = fabsf(h_acc[s]); float rh = reduce16_sum(h_acc[s], rmask); float sum_h_err = reduce16_sum(h_err[s], rmask); float l1_h_end = reduce16_sum(h_end_abs, rmask); if (tx == 0) { float pre_val = __fadd_rn(__fadd_rn(rh, rf), b_val); float e_lanes = A288_U * (144.0f * l1_h_end + 2.0f * (sum_h_err + sum_f_err)); float pre_err = 1.02f * (e_lanes + 9.05f * U_F32 * (l1_h_end + l1_f_end) + 4.05f * U_F32 * e_lanes + U_F32 * fabsf(pre_val)) + 1e-30f; if (!isfinite(pre_val) || !isfinite(pre_err)) pre_err = INFINITY; pre_out[s * 768 + n] = make_float2(pre_val, pre_err); } }}
// ---------------------------------------------------------------------------// Precompute 1B: Plain-FMA BF16 split-g (1 row/warp = 768 warps = 16 warps/SM!)// ty=0 processes g=0..8, ty=1 processes g=9..17 -> 2x occupancy + 0 branches!// ---------------------------------------------------------------------------template <int NW>__global__ void __launch_bounds__(NW * 32)n105_pre_bf16_splitg_kernel( const uint4* __restrict__ w_h, const uint4* __restrict__ w_f, const __nv_bfloat16* __restrict__ bias, const uint16_t* __restrict__ hidden_7, const uint16_t* __restrict__ f_rnn, float2* __restrict__ pre_out, int* __restrict__ fix_cnts, int hidden_step_bf16) { if (fix_cnts && blockIdx.x == 0 && threadIdx.x < 7) fix_cnts[threadIdx.x] = 0; const int warp = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int ty = lane >> 4; // 0 -> g=0..8, 1 -> g=9..17 const int tx = lane & 15; const int n = blockIdx.x * NW + warp; if (n >= 768) return; const unsigned int rmask = (ty == 0) ? 0x0000FFFFu : 0xFFFF0000u; const int g0 = ty * 9;
// Phase 1: W_f half (9 chunks, 4-ahead ld.cs to saturate DRAM!) const uint4* wf_row = w_f + (size_t)n * 288 + g0 * 16 + tx; float f_acc = 0.f, f_err = 0.f; uint4 wf0 = ld_cs_u4(wf_row + 0 * 16); uint4 wf1 = ld_cs_u4(wf_row + 1 * 16); uint4 wf2 = ld_cs_u4(wf_row + 2 * 16); uint4 wf3 = ld_cs_u4(wf_row + 3 * 16); #pragma unroll for (int k = 0; k < 9; ++k) { uint4 wcur = wf0; wf0 = wf1; wf1 = wf2; wf2 = wf3; if (k + 4 < 9) wf3 = ld_cs_u4(wf_row + (k + 4) * 16); fma8_bound(wcur, f_rnn + (g0 + k) * 128, tx, f_acc, f_err); } float f_end_abs = fabsf(f_acc); float rf_half = reduce16_sum(f_acc, rmask); float sum_f_err_h = reduce16_sum(f_err, rmask); float l1_f_end_h = reduce16_sum(f_end_abs, rmask); // Combine ty=0 and ty=1 on lane 0 (ty=0, tx=0) float rf_hi = __shfl_down_sync(0xFFFFFFFFu, rf_half, 16); float sum_f_err_2 = __shfl_down_sync(0xFFFFFFFFu, sum_f_err_h, 16); float l1_f_end_2 = __shfl_down_sync(0xFFFFFFFFu, l1_f_end_h, 16); float rf = __fadd_rn(rf_half, rf_hi); float sum_f_err = __fadd_rn(sum_f_err_h, sum_f_err_2); float l1_f1 = l1_f_end_h; float l1_f_tot = __fadd_rn(l1_f_end_h, l1_f_end_2); float b_val = (lane == 0) ? __bfloat162float(__ldg(bias + n)) : 0.f;
// Phase 2: W_h half (9 chunks x 7 steps, 2-ahead ld.cs) const uint4* wh_row = w_h + (size_t)n * 288 + g0 * 16 + tx; float h_acc[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; float h_err[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; uint4 wh0 = ld_cs_u4(wh_row + 0 * 16); uint4 wh1 = ld_cs_u4(wh_row + 1 * 16); #pragma unroll for (int k = 0; k < 9; ++k) { uint4 wcur = wh0; wh0 = wh1; if (k + 2 < 9) wh1 = ld_cs_u4(wh_row + (k + 2) * 16); const uint16_t* hb = hidden_7 + (g0 + k) * 128; #pragma unroll for (int s = 0; s < 7; ++s) { fma8_bound(wcur, hb + s * hidden_step_bf16, tx, h_acc[s], h_err[s]); } }
#pragma unroll for (int s = 0; s < 7; ++s) { float h_end_abs = fabsf(h_acc[s]); float rh_half = reduce16_sum(h_acc[s], rmask); float sum_h_err_h = reduce16_sum(h_err[s], rmask); float l1_h_end_h = reduce16_sum(h_end_abs, rmask); float rh_hi = __shfl_down_sync(0xFFFFFFFFu, rh_half, 16); float sum_h_err_2 = __shfl_down_sync(0xFFFFFFFFu, sum_h_err_h, 16); float l1_h_end_2 = __shfl_down_sync(0xFFFFFFFFu, l1_h_end_h, 16); if (lane == 0) { float rh = __fadd_rn(rh_half, rh_hi); float pre_val = __fadd_rn(__fadd_rn(rh, rf), b_val); float sum_h_err = __fadd_rn(sum_h_err_h, sum_h_err_2); float l1_h1 = l1_h_end_h; float l1_h2 = l1_h_end_2; // Gronwall over j=32..319 with split at j=104 (h1) and j=248 (f1): float e_lanes = A288_U * (216.0f * l1_h1 + 144.0f * l1_h2 + 72.0f * l1_f1 + 2.0f * (sum_h_err + sum_f_err)); float pre_err = 1.02f * (e_lanes + 10.05f * U_F32 * (l1_h1 + l1_h2 + l1_f_tot) + 4.05f * U_F32 * e_lanes + U_F32 * fabsf(pre_val)) + 1e-30f; if (!isfinite(pre_val) || !isfinite(pre_err)) pre_err = INFINITY; pre_out[s * 768 + n] = make_float2(pre_val, pre_err); } }}
// ---------------------------------------------------------------------------// Precompute 1C: Plain-FMA C12 split-g (16 warps/SM, lossless 5.31 MB, 0 TwoSum!)// ---------------------------------------------------------------------------template <int NW>__global__ void __launch_bounds__(NW * 32)n105_pre_c12_splitg_kernel( const uint2* __restrict__ wh_sm, const uint32_t* __restrict__ wh_e4, const uint2* __restrict__ wf_sm, const uint32_t* __restrict__ wf_e4, const uint16_t* __restrict__ w_raw, const __nv_bfloat16* __restrict__ bias, const uint16_t* __restrict__ hidden_7, const uint16_t* __restrict__ f_rnn, float2* __restrict__ pre_out, int* __restrict__ fix_cnts, int hidden_step_bf16) { if (fix_cnts && blockIdx.x == 0 && threadIdx.x < 7) fix_cnts[threadIdx.x] = 0; const int warp = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int ty = lane >> 4; const int tx = lane & 15; const int n = blockIdx.x * NW + warp; if (n >= 768) return; const unsigned int rmask = (ty == 0) ? 0x0000FFFFu : 0xFFFF0000u; const int g0 = ty * 9; const uint16_t* wraw_row = w_raw + (size_t)n * 5120;
// Phase 1: W_f half (C12, 9 chunks, 2-ahead) const uint2* wfsm = wf_sm + (size_t)n * 288 + g0 * 16 + tx; const uint32_t* wfe4 = wf_e4 + (size_t)n * 288 + g0 * 16 + tx; float f_acc = 0.f, f_err = 0.f; uint2 sm0 = ld_cs_u2(wfsm + 0 * 16); uint32_t e0 = ld_cs_u32(wfe4 + 0 * 16); uint2 sm1 = ld_cs_u2(wfsm + 1 * 16); uint32_t e1 = ld_cs_u32(wfe4 + 1 * 16); #pragma unroll for (int k = 0; k < 9; ++k) { uint2 smc = sm0; uint32_t ec = e0; sm0 = sm1; e0 = e1; if (k + 2 < 9) { sm1 = ld_cs_u2(wfsm + (k + 2) * 16); e1 = ld_cs_u32(wfe4 + (k + 2) * 16); } float w8[8]; decode_c12_8(smc, ec, wraw_row, 2816 + (g0 + k) * 128, tx, w8); const uint16_t* xb = f_rnn + (g0 + k) * 128; #pragma unroll for (int i = 0; i < 8; ++i) { f_acc = __fmaf_rn(w8[i], bf16_u16_to_f32(__ldg(xb + i * 16 + tx)), f_acc); f_err = __fadd_rn(f_err, fabsf(f_acc)); } } float f_end_abs = fabsf(f_acc); float rf_half = reduce16_sum(f_acc, rmask); float sum_f_err_h = reduce16_sum(f_err, rmask); float l1_f_end_h = reduce16_sum(f_end_abs, rmask); float rf_hi = __shfl_down_sync(0xFFFFFFFFu, rf_half, 16); float sum_f_err_2 = __shfl_down_sync(0xFFFFFFFFu, sum_f_err_h, 16); float l1_f_end_2 = __shfl_down_sync(0xFFFFFFFFu, l1_f_end_h, 16); float rf = __fadd_rn(rf_half, rf_hi); float sum_f_err = __fadd_rn(sum_f_err_h, sum_f_err_2); float l1_f1 = l1_f_end_h; float l1_f_tot = __fadd_rn(l1_f_end_h, l1_f_end_2); float b_val = (lane == 0) ? __bfloat162float(__ldg(bias + n)) : 0.f;
// Phase 2: W_h half (C12, 9 chunks x 7 steps) const uint2* whsm = wh_sm + (size_t)n * 288 + g0 * 16 + tx; const uint32_t* whe4 = wh_e4 + (size_t)n * 288 + g0 * 16 + tx; float h_acc[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; float h_err[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; sm0 = ld_cs_u2(whsm + 0 * 16); e0 = ld_cs_u32(whe4 + 0 * 16); sm1 = ld_cs_u2(whsm + 1 * 16); e1 = ld_cs_u32(whe4 + 1 * 16); for (int k = 0; k < 9; ++k) { uint2 smc = sm0; uint32_t ec = e0; sm0 = sm1; e0 = e1; if (k + 2 < 9) { sm1 = ld_cs_u2(whsm + (k + 2) * 16); e1 = ld_cs_u32(whe4 + (k + 2) * 16); } float w8[8]; decode_c12_8(smc, ec, wraw_row, 512 + (g0 + k) * 128, tx, w8); const uint16_t* hb = hidden_7 + (g0 + k) * 128; #pragma unroll for (int s = 0; s < 7; ++s) { const uint16_t* xb = hb + s * hidden_step_bf16; #pragma unroll for (int i = 0; i < 8; ++i) { h_acc[s] = __fmaf_rn(w8[i], bf16_u16_to_f32(__ldg(xb + i * 16 + tx)), h_acc[s]); h_err[s] = __fadd_rn(h_err[s], fabsf(h_acc[s])); } } }
#pragma unroll for (int s = 0; s < 7; ++s) { float h_end_abs = fabsf(h_acc[s]); float rh_half = reduce16_sum(h_acc[s], rmask); float sum_h_err_h = reduce16_sum(h_err[s], rmask); float l1_h_end_h = reduce16_sum(h_end_abs, rmask); float rh_hi = __shfl_down_sync(0xFFFFFFFFu, rh_half, 16); float sum_h_err_2 = __shfl_down_sync(0xFFFFFFFFu, sum_h_err_h, 16); float l1_h_end_2 = __shfl_down_sync(0xFFFFFFFFu, l1_h_end_h, 16); if (lane == 0) { float rh = __fadd_rn(rh_half, rh_hi); float pre_val = __fadd_rn(__fadd_rn(rh, rf), b_val); float sum_h_err = __fadd_rn(sum_h_err_h, sum_h_err_2); float l1_h1 = l1_h_end_h; float l1_h2 = l1_h_end_2; float e_lanes = A288_U * (216.0f * l1_h1 + 144.0f * l1_h2 + 72.0f * l1_f1 + 2.0f * (sum_h_err + sum_f_err)); float pre_err = 1.02f * (e_lanes + 10.05f * U_F32 * (l1_h1 + l1_h2 + l1_f_tot) + 4.05f * U_F32 * e_lanes + U_F32 * fabsf(pre_val)) + 1e-30f; if (!isfinite(pre_val) || !isfinite(pre_err)) pre_err = INFINITY; pre_out[s * 768 + n] = make_float2(pre_val, pre_err); } }}
// Shared fast-path helper: W_s exact a_31 + certificate check (0 TwoSum, 0 W_h/W_f loads!)__device__ __forceinline__ int eval_ws_cert( const uint4* __restrict__ w_s, const float2* __restrict__ pre_s, const uint16_t* __restrict__ state, const uint16_t* __restrict__ emb, int n, int tx, unsigned int rmask, float& acc_out, __nv_bfloat16& bf_out) { const uint4* ws = w_s + (size_t)n * 64 + tx; uint4 w0 = __ldg(ws + 0 * 16); uint4 w1 = __ldg(ws + 1 * 16); uint4 w2 = __ldg(ws + 2 * 16); uint4 w3 = __ldg(ws + 3 * 16); float acc = 0.f; acc = fma8_stride16(w0, state + 0, tx, acc); acc = fma8_stride16(w1, state + 128, tx, acc); acc = fma8_stride16(w2, emb + 0, tx, acc); acc = fma8_stride16(w3, emb + 128, tx, acc); acc_out = acc;
float l1_a31 = reduce16_sum(fabsf(acc), rmask); float r_a31 = reduce16_sum(acc, rmask); int need_fix = 0; if (tx == 0) { float2 p = __ldg(pre_s + n); // (pre_val, pre_err) float y_cand = __fadd_rn(p.x, r_a31); float e_dyn = (288.0f * A288_U + 8.05f * U_F32) * l1_a31; float delta = 1.02f * (p.y + e_dyn + 4.0f * U_F32 * fabsf(y_cand)) + 1e-29f; __nv_bfloat16 bf_lo = __float2bfloat16_rn(__fsub_rn(y_cand, delta)); __nv_bfloat16 bf_hi = __float2bfloat16_rn(__fadd_rn(y_cand, delta)); int cert = isfinite(y_cand) && isfinite(delta) && (fabsf(y_cand) > 1e-28f) && (*reinterpret_cast<uint16_t*>(&bf_lo) == *reinterpret_cast<uint16_t*>(&bf_hi)); need_fix = !cert; bf_out = bf_lo; } return __shfl_sync(rmask, need_fix, 0, 16);}
// ---------------------------------------------------------------------------// Step 2A: FUSED 1-kernel/step with 6-halfwarp cooperative double-buffered smem fixup// Grid = 128 blocks x 96 threads (6 rows = 2 triples/block). 6 waves instead of 36!// ---------------------------------------------------------------------------__global__ void __launch_bounds__(96)n105_step_fused_coop6_kernel( const uint4* __restrict__ w_s, const uint4* __restrict__ w_h, const uint4* __restrict__ w_f, const __nv_bfloat16* __restrict__ bias, const float2* __restrict__ pre_s, const uint16_t* __restrict__ state, const int64_t* __restrict__ prev_tok, const uint16_t* __restrict__ w1, const uint16_t* __restrict__ hidden, const uint16_t* __restrict__ f_rnn, __nv_bfloat16* __restrict__ new_state_out, __nv_bfloat16* __restrict__ latent_out, int* __restrict__ fix_cnt) { __shared__ uint4 sm_w[6][16]; __shared__ __nv_bfloat16 sm_out[6]; __shared__ int sm_need[6];
const int hw = threadIdx.x >> 4; // 0..5 const int tx = threadIdx.x & 15; // 0..15 const int g = hw >> 1; // 0, 1, 2 const int ty = hw & 1; // 0, 1 const int c = blockIdx.x * 2 + ty; const int n = g * 256 + c; const unsigned int rmask = (ty == 0) ? 0x0000FFFFu : 0xFFFF0000u; const uint16_t* emb = w1 + (size_t)(__ldg(prev_tok)) * 256;
float acc = 0.f; __nv_bfloat16 bf_v = __float2bfloat16_rn(0.f); int need_fix = eval_ws_cert(w_s, pre_s, state, emb, n, tx, rmask, acc, bf_v); if (tx == 0) { sm_out[hw] = bf_v; sm_need[hw] = need_fix; } __syncthreads();
uint32_t mask = (uint32_t)(sm_need[0]) | ((uint32_t)(sm_need[1]) << 1) | ((uint32_t)(sm_need[2]) << 2) | ((uint32_t)(sm_need[3]) << 3) | ((uint32_t)(sm_need[4]) << 4) | ((uint32_t)(sm_need[5]) << 5); if (__builtin_expect(mask != 0u, 0)) { for (int r = 0; r < 6; ++r) { if (!(mask & (1u << r))) continue; if (fix_cnt && threadIdx.x == 0) atomicAdd(fix_cnt, 1); const int nr = (r >> 1) * 256 + blockIdx.x * 2 + (r & 1); const uint4* wh_r = w_h + (size_t)nr * 288 + tx; const uint4* wf_r = w_f + (size_t)nr * 288 + tx; uint4 nxt = ld_cs_u4(wh_r + hw * 16); #pragma unroll for (int w = 0; w < 18; w += 6) { sm_w[hw][tx] = nxt; nxt = (w + 6 < 18) ? ld_cs_u4(wh_r + (w + 6 + hw) * 16) : ld_cs_u4(wf_r + hw * 16); __syncthreads(); if (hw == r) { #pragma unroll for (int k = 0; k < 6; ++k) acc = fma8_stride16(sm_w[k][tx], hidden + (w + k) * 128, tx, acc); } __syncthreads(); } #pragma unroll for (int w = 0; w < 18; w += 6) { sm_w[hw][tx] = nxt; if (w + 6 < 18) nxt = ld_cs_u4(wf_r + (w + 6 + hw) * 16); __syncthreads(); if (hw == r) { #pragma unroll for (int k = 0; k < 6; ++k) acc = fma8_stride16(sm_w[k][tx], f_rnn + (w + k) * 128, tx, acc); } __syncthreads(); } if (hw == r) { float v = reduce16_sum(acc, rmask); if (tx == 0) { float b = __bfloat162float(__ldg(bias + nr)); sm_out[r] = __float2bfloat16_rn(__fadd_rn(__fmaf_rn(1.0f, v, b), 0.0f)); } } } __syncthreads(); }
if (threadIdx.x < 2) { const int cc = blockIdx.x * 2 + threadIdx.x; const __nv_bfloat16* st_ptr = reinterpret_cast<const __nv_bfloat16*>(state); __nv_bfloat16 ns, la; apply_triton_gates(sm_out[0 + threadIdx.x], sm_out[2 + threadIdx.x], sm_out[4 + threadIdx.x], __ldg(st_ptr + cc), ns, la); new_state_out[cc] = ns; latent_out[cc] = la; }}
// ---------------------------------------------------------------------------// Step 2B: FUSED 1-kernel/step, 1 triple (3 rows) per block!// Grid = 256 blocks x 96 threads (6 half-warps). Only 3 rows/block -> eliminates// 2-tripped-rows/block straggler tail, while ALL 6 half-warps cooperate on fixup!// ---------------------------------------------------------------------------__global__ void __launch_bounds__(96)n105_step_fused_coop6_1t_kernel( const uint4* __restrict__ w_s, const uint4* __restrict__ w_h, const uint4* __restrict__ w_f, const __nv_bfloat16* __restrict__ bias, const float2* __restrict__ pre_s, const uint16_t* __restrict__ state, const int64_t* __restrict__ prev_tok, const uint16_t* __restrict__ w1, const uint16_t* __restrict__ hidden, const uint16_t* __restrict__ f_rnn, __nv_bfloat16* __restrict__ new_state_out, __nv_bfloat16* __restrict__ latent_out, int* __restrict__ fix_cnt) { __shared__ uint4 sm_w[6][16]; __shared__ __nv_bfloat16 sm_out[3]; __shared__ int sm_need[3];
const int hw = threadIdx.x >> 4; // 0..5 const int tx = threadIdx.x & 15; // 0..15 const int c = blockIdx.x; // 0..255 const unsigned int rmask = ((hw & 1) == 0) ? 0x0000FFFFu : 0xFFFF0000u; const uint16_t* emb = w1 + (size_t)(__ldg(prev_tok)) * 256;
float acc = 0.f; if (hw < 3) { const int n = hw * 256 + c; __nv_bfloat16 bf_v = __float2bfloat16_rn(0.f); int need_fix = eval_ws_cert(w_s, pre_s, state, emb, n, tx, rmask, acc, bf_v); if (tx == 0) { sm_out[hw] = bf_v; sm_need[hw] = need_fix; } } __syncthreads();
uint32_t mask = (uint32_t)(sm_need[0]) | ((uint32_t)(sm_need[1]) << 1) | ((uint32_t)(sm_need[2]) << 2); if (__builtin_expect(mask != 0u, 0)) { for (int r = 0; r < 3; ++r) { if (!(mask & (1u << r))) continue; if (fix_cnt && threadIdx.x == 0) atomicAdd(fix_cnt, 1); const int nr = r * 256 + c; const uint4* wh_r = w_h + (size_t)nr * 288 + tx; const uint4* wf_r = w_f + (size_t)nr * 288 + tx; uint4 nxt = ld_cs_u4(wh_r + hw * 16); #pragma unroll for (int w = 0; w < 18; w += 6) { sm_w[hw][tx] = nxt; nxt = (w + 6 < 18) ? ld_cs_u4(wh_r + (w + 6 + hw) * 16) : ld_cs_u4(wf_r + hw * 16); __syncthreads(); if (hw == r) { #pragma unroll for (int k = 0; k < 6; ++k) acc = fma8_stride16(sm_w[k][tx], hidden + (w + k) * 128, tx, acc); } __syncthreads(); } #pragma unroll for (int w = 0; w < 18; w += 6) { sm_w[hw][tx] = nxt; if (w + 6 < 18) nxt = ld_cs_u4(wf_r + (w + 6 + hw) * 16); __syncthreads(); if (hw == r) { #pragma unroll for (int k = 0; k < 6; ++k) acc = fma8_stride16(sm_w[k][tx], f_rnn + (w + k) * 128, tx, acc); } __syncthreads(); } if (hw == r) { float v = reduce16_sum(acc, rmask); if (tx == 0) { float b = __bfloat162float(__ldg(bias + nr)); sm_out[r] = __float2bfloat16_rn(__fadd_rn(__fmaf_rn(1.0f, v, b), 0.0f)); } } } __syncthreads(); }
if (threadIdx.x == 0) { const __nv_bfloat16* st_ptr = reinterpret_cast<const __nv_bfloat16*>(state); __nv_bfloat16 ns, la; apply_triton_gates(sm_out[0], sm_out[1], sm_out[2], __ldg(st_ptr + c), ns, la); new_state_out[c] = ns; latent_out[c] = la; }}
// ---------------------------------------------------------------------------// Step 2C: Split 2-kernel (step_fast + step_fixup_coop8) + 1-block exact gates// Zero block-straggler tail! 8 half-warps/tripped row -> 5 waves!// ---------------------------------------------------------------------------__global__ void __launch_bounds__(64)n105_step_fast_kernel( const uint4* __restrict__ w_s, const float2* __restrict__ pre_s, const uint16_t* __restrict__ state, const int64_t* __restrict__ prev_tok, const uint16_t* __restrict__ w1, __nv_bfloat16* __restrict__ proj_out, int* __restrict__ fix_cnt_step, int* __restrict__ fix_rows, float* __restrict__ fix_a31, int* __restrict__ fix_total_stat) { const int hw = threadIdx.x >> 4; const int tx = threadIdx.x & 15; const int n = blockIdx.x * 4 + hw; if (n >= 768) return; const unsigned int rmask = ((hw & 1) == 0) ? 0x0000FFFFu : 0xFFFF0000u; const uint16_t* emb = w1 + (size_t)(__ldg(prev_tok)) * 256;
float acc = 0.f; __nv_bfloat16 bf_v = __float2bfloat16_rn(0.f); int need_fix = eval_ws_cert(w_s, pre_s, state, emb, n, tx, rmask, acc, bf_v); if (!need_fix) { if (tx == 0) proj_out[n] = bf_v; } else { int slot = 0; if (tx == 0) { slot = atomicAdd(fix_cnt_step, 1); fix_rows[slot] = n; if (fix_total_stat) atomicAdd(fix_total_stat, 1); } slot = __shfl_sync(rmask, slot, 0, 16); fix_a31[slot * 16 + tx] = acc; }}
__global__ void __launch_bounds__(128)n105_step_fixup_coop8_kernel( const uint4* __restrict__ w_h, const uint4* __restrict__ w_f, const __nv_bfloat16* __restrict__ bias, const uint16_t* __restrict__ hidden, const uint16_t* __restrict__ f_rnn, const int* __restrict__ fix_cnt_step, const int* __restrict__ fix_rows, const float* __restrict__ fix_a31, __nv_bfloat16* __restrict__ proj_out) { __shared__ uint4 sm_w[8][16]; const int nfix = *fix_cnt_step; if (blockIdx.x >= nfix) return;
const int hw = threadIdx.x >> 4; // 0..7 const int tx = threadIdx.x & 15; // 0..15
for (int idx = blockIdx.x; idx < nfix; idx += gridDim.x) { const int nr = fix_rows[idx]; float acc = (hw == 0) ? fix_a31[idx * 16 + tx] : 0.f; const uint4* wh_r = w_h + (size_t)nr * 288 + tx; const uint4* wf_r = w_f + (size_t)nr * 288 + tx;
// 36 chunks total (0..17 in W_h, 18..35 in W_f) -> 4 full waves of 8 + 1 tail wave of 4! uint4 nxt = ld_cs_u4(wh_r + hw * 16); #pragma unroll for (int w = 0; w < 32; w += 8) { sm_w[hw][tx] = nxt; const int g_nxt = w + 8 + hw; if (g_nxt < 18) nxt = ld_cs_u4(wh_r + g_nxt * 16); else if (g_nxt < 36) nxt = ld_cs_u4(wf_r + (g_nxt - 18) * 16); __syncthreads(); if (hw == 0) { #pragma unroll for (int k = 0; k < 8; ++k) { const int g = w + k; const uint16_t* xb = (g < 18) ? (hidden + g * 128) : (f_rnn + (g - 18) * 128); acc = fma8_stride16(sm_w[k][tx], xb, tx, acc); } } __syncthreads(); } if (hw < 4) sm_w[hw][tx] = nxt; __syncthreads(); if (hw == 0) { #pragma unroll for (int k = 0; k < 4; ++k) { acc = fma8_stride16(sm_w[k][tx], f_rnn + (14 + k) * 128, tx, acc); } float v = reduce16_sum(acc, 0x0000FFFFu); if (tx == 0) { float b = __bfloat162float(__ldg(bias + nr)); proj_out[nr] = __float2bfloat16_rn(__fadd_rn(__fmaf_rn(1.0f, v, b), 0.0f)); } } __syncthreads(); }}
// ---------------------------------------------------------------------------// Step 2D: 4-ahead inline register-pipelined proj kernel (192x64, 0 barriers!)// ---------------------------------------------------------------------------__global__ void __launch_bounds__(64)n105_step_proj_4ahead_kernel( const uint4* __restrict__ w_s, const uint4* __restrict__ w_h, const uint4* __restrict__ w_f, const __nv_bfloat16* __restrict__ bias, const float2* __restrict__ pre_s, const uint16_t* __restrict__ state, const int64_t* __restrict__ prev_tok, const uint16_t* __restrict__ w1, const uint16_t* __restrict__ hidden, const uint16_t* __restrict__ f_rnn, __nv_bfloat16* __restrict__ proj_out, int* __restrict__ fix_cnt) { const int hw = threadIdx.x >> 4; const int tx = threadIdx.x & 15; const int n = blockIdx.x * 4 + hw; if (n >= 768) return; const unsigned int rmask = ((hw & 1) == 0) ? 0x0000FFFFu : 0xFFFF0000u; const uint16_t* emb = w1 + (size_t)(__ldg(prev_tok)) * 256;
float acc = 0.f; __nv_bfloat16 bf_v = __float2bfloat16_rn(0.f); int need_fix = eval_ws_cert(w_s, pre_s, state, emb, n, tx, rmask, acc, bf_v); if (__builtin_expect(need_fix != 0, 0)) { if (fix_cnt && tx == 0) atomicAdd(fix_cnt, 1); const uint4* wh = w_h + (size_t)n * 288 + tx; const uint4* wf = w_f + (size_t)n * 288 + tx; // 4-ahead pipelined streaming over 36 chunks (0..17 W_h, 18..35 W_f) uint4 q0 = ld_cs_u4(wh + 0 * 16); uint4 q1 = ld_cs_u4(wh + 1 * 16); uint4 q2 = ld_cs_u4(wh + 2 * 16); uint4 q3 = ld_cs_u4(wh + 3 * 16); #pragma unroll 2 for (int g = 0; g < 18; ++g) { uint4 cur = q0; q0 = q1; q1 = q2; q2 = q3; const int gn = g + 4; q3 = (gn < 18) ? ld_cs_u4(wh + gn * 16) : ld_cs_u4(wf + (gn - 18) * 16); acc = fma8_stride16(cur, hidden + g * 128, tx, acc); } #pragma unroll 2 for (int g = 0; g < 18; ++g) { uint4 cur = q0; q0 = q1; q1 = q2; q2 = q3; const int gn = g + 4; if (gn < 18) q3 = ld_cs_u4(wf + gn * 16); acc = fma8_stride16(cur, f_rnn + g * 128, tx, acc); } float v = reduce16_sum(acc, rmask); if (tx == 0) { float b = __bfloat162float(__ldg(bias + n)); bf_v = __float2bfloat16_rn(__fadd_rn(__fmaf_rn(1.0f, v, b), 0.0f)); } } if (tx == 0) proj_out[n] = bf_v;}
// Fast 1-block 256-thread exact Triton _rnn_gates kernel (16 regs, 0 spills!)__global__ void __launch_bounds__(256)n105_gates_kernel( const __nv_bfloat16* __restrict__ proj, const __nv_bfloat16* __restrict__ st, __nv_bfloat16* __restrict__ ns_out, __nv_bfloat16* __restrict__ la_out, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= n) return; __nv_bfloat16 ns, la; apply_triton_gates(proj[i], proj[n + i], proj[2 * n + i], st[i], ns, la); ns_out[i] = ns; la_out[i] = la;}
// ---------------------------------------------------------------------------// Diagnostic / non-bitwise fallback (per supervisor note: draft-only lever):// FAST90_nocert: plain-FMA 90% split-g precompute (ZERO err_abs, 16 warps/SM)// + W_s-only fused step (ZERO fixup, exact _rnn_gates.ptx). ~44 us total!// ---------------------------------------------------------------------------template <int NW>__global__ void __launch_bounds__(NW * 32)n105_pre_bf16_nocert_kernel( const uint4* __restrict__ w_h, const uint4* __restrict__ w_f, const __nv_bfloat16* __restrict__ bias, const uint16_t* __restrict__ hidden_7, const uint16_t* __restrict__ f_rnn, float* __restrict__ pre_out, int hidden_step_bf16) { const int warp = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int ty = lane >> 4; const int tx = lane & 15; const int n = blockIdx.x * NW + warp; if (n >= 768) return; const unsigned int rmask = (ty == 0) ? 0x0000FFFFu : 0xFFFF0000u; const int g0 = ty * 9;
const uint4* wf_row = w_f + (size_t)n * 288 + g0 * 16 + tx; float f_acc = 0.f; uint4 wf0 = ld_cs_u4(wf_row + 0 * 16); uint4 wf1 = ld_cs_u4(wf_row + 1 * 16); #pragma unroll for (int k = 0; k < 9; ++k) { uint4 wcur = wf0; wf0 = wf1; if (k + 2 < 9) wf1 = ld_cs_u4(wf_row + (k + 2) * 16); f_acc = fma8_stride16(wcur, f_rnn + (g0 + k) * 128, tx, f_acc); } float rf_half = reduce16_sum(f_acc, rmask); float rf = __fadd_rn(rf_half, __shfl_down_sync(0xFFFFFFFFu, rf_half, 16)); float b_val = (lane == 0) ? __bfloat162float(__ldg(bias + n)) : 0.f; float rf_b = __fadd_rn(rf, b_val);
const uint4* wh_row = w_h + (size_t)n * 288 + g0 * 16 + tx; float h_acc[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; uint4 wh0 = ld_cs_u4(wh_row + 0 * 16); uint4 wh1 = ld_cs_u4(wh_row + 1 * 16); #pragma unroll for (int k = 0; k < 9; ++k) { uint4 wcur = wh0; wh0 = wh1; if (k + 2 < 9) wh1 = ld_cs_u4(wh_row + (k + 2) * 16); const uint16_t* hb = hidden_7 + (g0 + k) * 128; #pragma unroll for (int s = 0; s < 7; ++s) { h_acc[s] = fma8_stride16(wcur, hb + s * hidden_step_bf16, tx, h_acc[s]); } } #pragma unroll for (int s = 0; s < 7; ++s) { float rh_half = reduce16_sum(h_acc[s], rmask); float rh = __fadd_rn(rh_half, __shfl_down_sync(0xFFFFFFFFu, rh_half, 16)); if (lane == 0) pre_out[s * 768 + n] = __fadd_rn(rh, rf_b); }}
__global__ void __launch_bounds__(96)n105_step_fused_nocert_kernel( const uint4* __restrict__ w_s, const float* __restrict__ pre_s, const uint16_t* __restrict__ state, const int64_t* __restrict__ prev_tok, const uint16_t* __restrict__ w1, __nv_bfloat16* __restrict__ new_state_out, __nv_bfloat16* __restrict__ latent_out) { __shared__ __nv_bfloat16 sm_out[6]; const int hw = threadIdx.x >> 4; const int tx = threadIdx.x & 15; const int g = hw >> 1; const int ty = hw & 1; const int c = blockIdx.x * 2 + ty; const int n = g * 256 + c; const unsigned int rmask = (ty == 0) ? 0x0000FFFFu : 0xFFFF0000u; const uint16_t* emb = w1 + (size_t)(__ldg(prev_tok)) * 256; const uint4* ws = w_s + (size_t)n * 64 + tx; uint4 w0 = __ldg(ws + 0 * 16); uint4 w1v = __ldg(ws + 1 * 16); uint4 w2 = __ldg(ws + 2 * 16); uint4 w3 = __ldg(ws + 3 * 16); float acc = 0.f; acc = fma8_stride16(w0, state + 0, tx, acc); acc = fma8_stride16(w1v, state + 128, tx, acc); acc = fma8_stride16(w2, emb + 0, tx, acc); acc = fma8_stride16(w3, emb + 128, tx, acc); float v = reduce16_sum(acc, rmask); if (tx == 0) sm_out[hw] = __float2bfloat16_rn(__fadd_rn(__ldg(pre_s + n), v)); __syncthreads(); if (threadIdx.x < 2) { const int cc = blockIdx.x * 2 + threadIdx.x; const __nv_bfloat16* st_ptr = reinterpret_cast<const __nv_bfloat16*>(state); __nv_bfloat16 ns, la; apply_triton_gates(sm_out[0 + threadIdx.x], sm_out[2 + threadIdx.x], sm_out[4 + threadIdx.x], __ldg(st_ptr + cc), ns, la); new_state_out[cc] = ns; latent_out[cc] = la; }}
// ---- C++ launchers ----void pre_bf16_sep(at::Tensor w_h, at::Tensor w_f, at::Tensor bias, at::Tensor hidden_7, at::Tensor f_rnn, at::Tensor pre_out, at::optional<at::Tensor> fix_cnts, int64_t nw) { auto stream = at::cuda::getCurrentCUDAStream(); int step_bf16 = (int)hidden_7.stride(1); int* fcp = fix_cnts.has_value() ? fix_cnts->data_ptr<int>() : nullptr; const auto* wh = reinterpret_cast<const uint4*>(w_h.data_ptr()); const auto* wf = reinterpret_cast<const uint4*>(w_f.data_ptr()); const auto* bi = reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()); const auto* h7 = reinterpret_cast<const uint16_t*>(hidden_7.data_ptr()); const auto* fr = reinterpret_cast<const uint16_t*>(f_rnn.data_ptr()); auto* po = reinterpret_cast<float2*>(pre_out.data_ptr()); if (nw == 2) n105_pre_bf16_sep_kernel<2><<<192, 64, 0, stream>>>(wh, wf, bi, h7, fr, po, fcp, step_bf16); else if (nw == 4) n105_pre_bf16_sep_kernel<4><<<96, 128, 0, stream>>>(wh, wf, bi, h7, fr, po, fcp, step_bf16); else TORCH_CHECK(false, "n105 pre_bf16_sep: unsupported nw ", nw); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void pre_bf16_splitg(at::Tensor w_h, at::Tensor w_f, at::Tensor bias, at::Tensor hidden_7, at::Tensor f_rnn, at::Tensor pre_out, at::optional<at::Tensor> fix_cnts, int64_t nw) { auto stream = at::cuda::getCurrentCUDAStream(); int step_bf16 = (int)hidden_7.stride(1); int* fcp = fix_cnts.has_value() ? fix_cnts->data_ptr<int>() : nullptr; const auto* wh = reinterpret_cast<const uint4*>(w_h.data_ptr()); const auto* wf = reinterpret_cast<const uint4*>(w_f.data_ptr()); const auto* bi = reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()); const auto* h7 = reinterpret_cast<const uint16_t*>(hidden_7.data_ptr()); const auto* fr = reinterpret_cast<const uint16_t*>(f_rnn.data_ptr()); auto* po = reinterpret_cast<float2*>(pre_out.data_ptr()); if (nw == 4) n105_pre_bf16_splitg_kernel<4><<<192, 128, 0, stream>>>(wh, wf, bi, h7, fr, po, fcp, step_bf16); else if (nw == 8) n105_pre_bf16_splitg_kernel<8><<<96, 256, 0, stream>>>(wh, wf, bi, h7, fr, po, fcp, step_bf16); else TORCH_CHECK(false, "n105 pre_bf16_splitg: unsupported nw ", nw); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void pre_c12_splitg(at::Tensor wh_sm, at::Tensor wh_e4, at::Tensor wf_sm, at::Tensor wf_e4, at::Tensor w_raw, at::Tensor bias, at::Tensor hidden_7, at::Tensor f_rnn, at::Tensor pre_out, at::optional<at::Tensor> fix_cnts, int64_t nw) { auto stream = at::cuda::getCurrentCUDAStream(); int step_bf16 = (int)hidden_7.stride(1); int* fcp = fix_cnts.has_value() ? fix_cnts->data_ptr<int>() : nullptr; const auto* hsm = reinterpret_cast<const uint2*>(wh_sm.data_ptr()); const auto* he4 = reinterpret_cast<const uint32_t*>(wh_e4.data_ptr()); const auto* fsm = reinterpret_cast<const uint2*>(wf_sm.data_ptr()); const auto* fe4 = reinterpret_cast<const uint32_t*>(wf_e4.data_ptr()); const auto* wr = reinterpret_cast<const uint16_t*>(w_raw.data_ptr()); const auto* bi = reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()); const auto* h7 = reinterpret_cast<const uint16_t*>(hidden_7.data_ptr()); const auto* fr = reinterpret_cast<const uint16_t*>(f_rnn.data_ptr()); auto* po = reinterpret_cast<float2*>(pre_out.data_ptr()); if (nw == 4) n105_pre_c12_splitg_kernel<4><<<192, 128, 0, stream>>>(hsm, he4, fsm, fe4, wr, bi, h7, fr, po, fcp, step_bf16); else if (nw == 8) n105_pre_c12_splitg_kernel<8><<<96, 256, 0, stream>>>(hsm, he4, fsm, fe4, wr, bi, h7, fr, po, fcp, step_bf16); else TORCH_CHECK(false, "n105 pre_c12_splitg: unsupported nw ", nw); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void step_fused_coop6(at::Tensor w_s, at::Tensor w_h, at::Tensor w_f, at::Tensor bias, at::Tensor pre_s, at::Tensor state, at::Tensor prev_tok, at::Tensor w1, at::Tensor hidden, at::Tensor f_rnn, at::Tensor new_state, at::Tensor latent, at::optional<at::Tensor> fix_cnt) { auto stream = at::cuda::getCurrentCUDAStream(); int* fc = fix_cnt.has_value() ? fix_cnt->data_ptr<int>() : nullptr; n105_step_fused_coop6_kernel<<<128, 96, 0, stream>>>( reinterpret_cast<const uint4*>(w_s.data_ptr()), reinterpret_cast<const uint4*>(w_h.data_ptr()), reinterpret_cast<const uint4*>(w_f.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()), reinterpret_cast<const float2*>(pre_s.data_ptr()), reinterpret_cast<const uint16_t*>(state.data_ptr()), prev_tok.data_ptr<int64_t>(), reinterpret_cast<const uint16_t*>(w1.data_ptr()), reinterpret_cast<const uint16_t*>(hidden.data_ptr()), reinterpret_cast<const uint16_t*>(f_rnn.data_ptr()), reinterpret_cast<__nv_bfloat16*>(new_state.data_ptr()), reinterpret_cast<__nv_bfloat16*>(latent.data_ptr()), fc); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void step_fused_coop6_1t(at::Tensor w_s, at::Tensor w_h, at::Tensor w_f, at::Tensor bias, at::Tensor pre_s, at::Tensor state, at::Tensor prev_tok, at::Tensor w1, at::Tensor hidden, at::Tensor f_rnn, at::Tensor new_state, at::Tensor latent, at::optional<at::Tensor> fix_cnt) { auto stream = at::cuda::getCurrentCUDAStream(); int* fc = fix_cnt.has_value() ? fix_cnt->data_ptr<int>() : nullptr; n105_step_fused_coop6_1t_kernel<<<256, 96, 0, stream>>>( reinterpret_cast<const uint4*>(w_s.data_ptr()), reinterpret_cast<const uint4*>(w_h.data_ptr()), reinterpret_cast<const uint4*>(w_f.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()), reinterpret_cast<const float2*>(pre_s.data_ptr()), reinterpret_cast<const uint16_t*>(state.data_ptr()), prev_tok.data_ptr<int64_t>(), reinterpret_cast<const uint16_t*>(w1.data_ptr()), reinterpret_cast<const uint16_t*>(hidden.data_ptr()), reinterpret_cast<const uint16_t*>(f_rnn.data_ptr()), reinterpret_cast<__nv_bfloat16*>(new_state.data_ptr()), reinterpret_cast<__nv_bfloat16*>(latent.data_ptr()), fc); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void step_split_coop8(at::Tensor w_s, at::Tensor w_h, at::Tensor w_f, at::Tensor bias, at::Tensor pre_s, at::Tensor state, at::Tensor prev_tok, at::Tensor w1, at::Tensor hidden, at::Tensor f_rnn, at::Tensor proj_buf, at::Tensor fix_cnt_step, at::Tensor fix_rows, at::Tensor fix_a31, at::Tensor new_state, at::Tensor latent, at::optional<at::Tensor> fix_total_stat) { auto stream = at::cuda::getCurrentCUDAStream(); int* fstat = fix_total_stat.has_value() ? fix_total_stat->data_ptr<int>() : nullptr; n105_step_fast_kernel<<<192, 64, 0, stream>>>( reinterpret_cast<const uint4*>(w_s.data_ptr()), reinterpret_cast<const float2*>(pre_s.data_ptr()), reinterpret_cast<const uint16_t*>(state.data_ptr()), prev_tok.data_ptr<int64_t>(), reinterpret_cast<const uint16_t*>(w1.data_ptr()), reinterpret_cast<__nv_bfloat16*>(proj_buf.data_ptr()), fix_cnt_step.data_ptr<int>(), fix_rows.data_ptr<int>(), fix_a31.data_ptr<float>(), fstat); n105_step_fixup_coop8_kernel<<<96, 128, 0, stream>>>( reinterpret_cast<const uint4*>(w_h.data_ptr()), reinterpret_cast<const uint4*>(w_f.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()), reinterpret_cast<const uint16_t*>(hidden.data_ptr()), reinterpret_cast<const uint16_t*>(f_rnn.data_ptr()), fix_cnt_step.data_ptr<int>(), fix_rows.data_ptr<int>(), fix_a31.data_ptr<float>(), reinterpret_cast<__nv_bfloat16*>(proj_buf.data_ptr())); n105_gates_kernel<<<1, 256, 0, stream>>>( reinterpret_cast<const __nv_bfloat16*>(proj_buf.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(state.data_ptr()), reinterpret_cast<__nv_bfloat16*>(new_state.data_ptr()), reinterpret_cast<__nv_bfloat16*>(latent.data_ptr()), 256); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void step_proj_4ahead_gates(at::Tensor w_s, at::Tensor w_h, at::Tensor w_f, at::Tensor bias, at::Tensor pre_s, at::Tensor state, at::Tensor prev_tok, at::Tensor w1, at::Tensor hidden, at::Tensor f_rnn, at::Tensor proj_buf, at::Tensor new_state, at::Tensor latent, at::optional<at::Tensor> fix_cnt) { auto stream = at::cuda::getCurrentCUDAStream(); int* fc = fix_cnt.has_value() ? fix_cnt->data_ptr<int>() : nullptr; n105_step_proj_4ahead_kernel<<<192, 64, 0, stream>>>( reinterpret_cast<const uint4*>(w_s.data_ptr()), reinterpret_cast<const uint4*>(w_h.data_ptr()), reinterpret_cast<const uint4*>(w_f.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()), reinterpret_cast<const float2*>(pre_s.data_ptr()), reinterpret_cast<const uint16_t*>(state.data_ptr()), prev_tok.data_ptr<int64_t>(), reinterpret_cast<const uint16_t*>(w1.data_ptr()), reinterpret_cast<const uint16_t*>(hidden.data_ptr()), reinterpret_cast<const uint16_t*>(f_rnn.data_ptr()), reinterpret_cast<__nv_bfloat16*>(proj_buf.data_ptr()), fc); n105_gates_kernel<<<1, 256, 0, stream>>>( reinterpret_cast<const __nv_bfloat16*>(proj_buf.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(state.data_ptr()), reinterpret_cast<__nv_bfloat16*>(new_state.data_ptr()), reinterpret_cast<__nv_bfloat16*>(latent.data_ptr()), 256); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void test_gates(at::Tensor proj, at::Tensor st, at::Tensor ns_out, at::Tensor la_out) { auto stream = at::cuda::getCurrentCUDAStream(); int n = (int)st.numel(); n105_gates_kernel<<<(n + 255) / 256, 256, 0, stream>>>( reinterpret_cast<const __nv_bfloat16*>(proj.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(st.data_ptr()), reinterpret_cast<__nv_bfloat16*>(ns_out.data_ptr()), reinterpret_cast<__nv_bfloat16*>(la_out.data_ptr()), n); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void pre_bf16_nocert(at::Tensor w_h, at::Tensor w_f, at::Tensor bias, at::Tensor hidden_7, at::Tensor f_rnn, at::Tensor pre_out, int64_t nw) { auto stream = at::cuda::getCurrentCUDAStream(); int step_bf16 = (int)hidden_7.stride(1); const auto* wh = reinterpret_cast<const uint4*>(w_h.data_ptr()); const auto* wf = reinterpret_cast<const uint4*>(w_f.data_ptr()); const auto* bi = reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()); const auto* h7 = reinterpret_cast<const uint16_t*>(hidden_7.data_ptr()); const auto* fr = reinterpret_cast<const uint16_t*>(f_rnn.data_ptr()); auto* po = pre_out.data_ptr<float>(); if (nw == 4) n105_pre_bf16_nocert_kernel<4><<<192, 128, 0, stream>>>(wh, wf, bi, h7, fr, po, step_bf16); else if (nw == 8) n105_pre_bf16_nocert_kernel<8><<<96, 256, 0, stream>>>(wh, wf, bi, h7, fr, po, step_bf16); else TORCH_CHECK(false, "n105 pre_bf16_nocert: unsupported nw ", nw); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void step_fused_nocert(at::Tensor w_s, at::Tensor pre_s, at::Tensor state, at::Tensor prev_tok, at::Tensor w1, at::Tensor new_state, at::Tensor latent) { auto stream = at::cuda::getCurrentCUDAStream(); n105_step_fused_nocert_kernel<<<128, 96, 0, stream>>>( reinterpret_cast<const uint4*>(w_s.data_ptr()), pre_s.data_ptr<float>(), reinterpret_cast<const uint16_t*>(state.data_ptr()), prev_tok.data_ptr<int64_t>(), reinterpret_cast<const uint16_t*>(w1.data_ptr()), reinterpret_cast<__nv_bfloat16*>(new_state.data_ptr()), reinterpret_cast<__nv_bfloat16*>(latent.data_ptr())); C10_CUDA_KERNEL_LAUNCH_CHECK();}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("pre_bf16_sep", &pre_bf16_sep); m.def("pre_bf16_splitg", &pre_bf16_splitg); m.def("pre_c12_splitg", &pre_c12_splitg); m.def("step_fused_coop6", &step_fused_coop6); m.def("step_fused_coop6_1t", &step_fused_coop6_1t); m.def("step_split_coop8", &step_split_coop8); m.def("step_proj_4ahead_gates", &step_proj_4ahead_gates); m.def("pre_bf16_nocert", &pre_bf16_nocert); m.def("step_fused_nocert", &step_fused_nocert); m.def("test_gates", &test_gates);}'''
_EXT = None
def build_ext(verbose: bool = False, build_dir: Optional[str] = None): global _EXT if _EXT is None: from torch.utils.cpp_extension import load_inline arch = os.environ.get("N105_CUDA_ARCH", "121a") kw = {} if build_dir: os.makedirs(build_dir, exist_ok=True) kw["build_directory"] = build_dir _EXT = load_inline( "n105_rnnhoist_b3_ext", 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
@dataclassclass RnnHoistPacks: w_s: torch.Tensor # [768, 4, 16, 8] BF16 (0.786 MB) w_h: torch.Tensor # [768, 18, 16, 8] BF16 (3.539 MB) w_f: torch.Tensor # [768, 18, 16, 8] BF16 (3.539 MB) wh_sm: Optional[torch.Tensor] # [768, 18, 16, 2] int32 (1.769 MB) wh_e4: Optional[torch.Tensor] # [768, 18, 16] int32 (0.885 MB) wf_sm: Optional[torch.Tensor] # [768, 18, 16, 2] int32 (1.769 MB) wf_e4: Optional[torch.Tensor] # [768, 18, 16] int32 (0.885 MB) w_raw: torch.Tensor # [768, 5120] BF16 (view of rnn_proj.weight) bias: torch.Tensor # [768] BF16 contiguous
def nbytes(self) -> int: tot = (self.w_s.numel() + self.w_h.numel() + self.w_f.numel() + self.bias.numel()) * 2 if self.wh_sm is not None: tot += (self.wh_sm.numel() + self.wh_e4.numel() + self.wf_sm.numel() + self.wf_e4.numel()) * 4 return tot
@dataclassclass WalkCtx: pre: torch.Tensor # [7, 768, 2] FP32 fix_cnts: Optional[torch.Tensor] # [7] int32 (used by split_coop8) fix_rows: Optional[torch.Tensor] # [768] int32 fix_a31: Optional[torch.Tensor] # [768, 16] FP32 proj_buf: Optional[torch.Tensor] # [1, 768] BF16 base_ptr: int step_bytes: int f_ptr: int gamma: int
def _pack_c12_block(w_block_bf16: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: u16 = w_block_bf16.view(torch.uint16).to(torch.int64) sign = (u16 >> 15) & 1 exp = (u16 >> 7) & 0xFF mant = u16 & 0x7F sm_byte = (sign << 7) | mant in_win = (exp >= C12_BASE) & (exp <= C12_BASE + 14) e4_nib = torch.where(in_win, exp - C12_BASE, torch.full_like(exp, 15)) sm_lo = (sm_byte[..., 0] | (sm_byte[..., 1] << 8) | (sm_byte[..., 2] << 16) | (sm_byte[..., 3] << 24)) sm_hi = (sm_byte[..., 4] | (sm_byte[..., 5] << 8) | (sm_byte[..., 6] << 16) | (sm_byte[..., 7] << 24)) sm = torch.stack([sm_lo, sm_hi], dim=-1).to(torch.uint32).view(torch.int32).contiguous() e4 = torch.zeros_like(e4_nib[..., 0]) for i in range(8): e4 = e4 | (e4_nib[..., i] << (i * 4)) e4 = e4.to(torch.uint32).view(torch.int32).contiguous() return sm, e4
def unpack_c12_check(sm: torch.Tensor, e4: torch.Tensor, w_raw_slice: torch.Tensor) -> torch.Tensor: sm_u = sm.view(torch.uint32).to(torch.int64) e4_u = e4.view(torch.uint32).to(torch.int64) raw_u = w_raw_slice.view(torch.uint16).to(torch.int64) cols = [] for i in range(8): word = sm_u[..., 0] if i < 4 else sm_u[..., 1] s = (word >> ((i % 4) * 8)) & 0xFF c = (e4_u >> (i * 4)) & 0xF dec = ((s & 0x80) << 8) | ((c + C12_BASE) << 7) | (s & 0x7F) dec = torch.where(c == 15, raw_u[..., i], dec) cols.append(dec) return torch.stack(cols, dim=-1).to(torch.uint16).view(torch.bfloat16)
def pack_rnn_weights( weight: torch.Tensor, bias: Optional[torch.Tensor], include_c12: bool = False,) -> RnnHoistPacks: assert weight.shape == (N_OUT, K_TOTAL) and weight.dtype == torch.bfloat16, (weight.shape, weight.dtype) w = weight.detach().contiguous() w3 = w.view(N_OUT, 320, 16) w_s = w3[:, :32, :].view(N_OUT, 4, 8, 16).permute(0, 1, 3, 2).contiguous() w_h = w3[:, 32:176, :].view(N_OUT, 18, 8, 16).permute(0, 1, 3, 2).contiguous() w_f = w3[:, 176:, :].view(N_OUT, 18, 8, 16).permute(0, 1, 3, 2).contiguous() wh_sm = wh_e4 = wf_sm = wf_e4 = None if include_c12: wh_sm, wh_e4 = _pack_c12_block(w_h) wf_sm, wf_e4 = _pack_c12_block(w_f) if bias is None: b = torch.zeros(N_OUT, dtype=torch.bfloat16, device=w.device) else: assert bias.shape == (N_OUT,) and bias.dtype == torch.bfloat16 b = bias.detach().contiguous() return RnnHoistPacks(w_s=w_s, w_h=w_h, w_f=w_f, wh_sm=wh_sm, wh_e4=wh_e4, wf_sm=wf_sm, wf_e4=wf_e4, w_raw=w, bias=b)
def unpack_check(packs: RnnHoistPacks) -> torch.Tensor: ws = packs.w_s.permute(0, 1, 3, 2).reshape(N_OUT, 32, 16) wh = packs.w_h.permute(0, 1, 3, 2).reshape(N_OUT, 144, 16) wf = packs.w_f.permute(0, 1, 3, 2).reshape(N_OUT, 144, 16) return torch.cat([ws, wh, wf], dim=1).reshape(N_OUT, K_TOTAL)
# ---- Pure-Python CPU reference (matches plain-FMA FAST-CERT90 + gemvx stride-16) ----def _get_fmaf(): import ctypes libm = ctypes.CDLL("libm.so.6") fn = libm.fmaf fn.argtypes = (ctypes.c_float, ctypes.c_float, ctypes.c_float) fn.restype = ctypes.c_float return fn
def gemvx_cpu_exact_stride16(w_bf16: torch.Tensor, b_bf16: torch.Tensor, x_bf16: torch.Tensor, nrows: int = N_OUT) -> torch.Tensor: import struct fmaf = _get_fmaf() wf = w_bf16[:nrows].float().tolist() xf = x_bf16.float().tolist() bf = b_bf16[:nrows].float().tolist() f32 = lambda v: struct.unpack("<f", struct.pack("<f", v))[0] out = [] for n in range(nrows): wn = wf[n] s = [0.0] * 16 for tx in range(16): acc = 0.0 for j in range(320): k = tx + 16 * j acc = fmaf(wn[k], xf[k], acc) s[tx] = acc for stride in (8, 4, 2, 1): for tx in range(stride): s[tx] = f32(s[tx] + s[tx + stride]) out.append(f32(fmaf(1.0, s[0], bf[n]) + 0.0)) return torch.tensor(out, dtype=torch.float32).to(torch.bfloat16)
def fast_cert90_cpu_walk( packs: RnnHoistPacks, hidden_7: torch.Tensor, f_rnn: torch.Tensor, states_7: torch.Tensor, embs_7: torch.Tensor, wrong_control: bool = False, nrows: int = 64,) -> tuple[torch.Tensor, int]: import math import struct fmaf = _get_fmaf() f32 = lambda v: struct.unpack("<f", struct.pack("<f", v))[0] bf16_bits = lambda v: torch.tensor([v], dtype=torch.float32).to(torch.bfloat16).view(torch.int16).item() U = 2.0 ** -24 A288_U = ((1.0 / (1.0 - U)) ** 288) * U
wraw = packs.w_raw[:nrows].float().tolist() bf = packs.bias[:nrows].float().tolist() h7 = hidden_7[0].float().tolist() fr = f_rnn[0].float().tolist() st7 = states_7.float().tolist() em7 = embs_7.float().tolist()
pre = [[(0.0, 0.0) for _ in range(nrows)] for _ in range(GAMMA)] for n in range(nrows): wn = wraw[n] f_acc = [0.0] * 16; f_err = [0.0] * 16 for tx in range(16): a = e = 0.0 for j in range(144): a = fmaf(wn[2816 + j * 16 + tx], fr[j * 16 + tx], a) e = f32(e + abs(a)) f_acc[tx], f_err[tx] = a, e rf = sum(f_acc); sum_f_err = sum(f_err); l1_f = sum(abs(v) for v in f_acc) for stp in range(GAMMA): hs = h7[stp] h_acc = [0.0] * 16; h_err = [0.0] * 16 for tx in range(16): a = e = 0.0 for j in range(144): a = fmaf(wn[512 + j * 16 + tx], hs[j * 16 + tx], a) e = f32(e + abs(a)) h_acc[tx], h_err[tx] = a, e rh = sum(h_acc); sum_h_err = sum(h_err); l1_h = sum(abs(v) for v in h_acc) pv = f32(f32(rh + (0.0 if wrong_control else rf)) + bf[n]) el = f32(A288_U * f32(f32(144.0 * l1_h) + f32(2.0 * f32(sum_h_err + sum_f_err)))) pe = f32(f32(1.02 * f32(el + 9.05 * U * (l1_h + l1_f) + 4.05 * U * el + U * abs(pv))) + 1e-30) pre[stp][n] = (pv, pe)
outs = [] n_fix = 0 for stp in range(GAMMA): hs, st, em = h7[stp], st7[stp], em7[stp] row_out = [] for n in range(nrows): wn = wraw[n] a31 = [0.0] * 16 for tx in range(16): a = 0.0 for j in range(16): a = fmaf(wn[j * 16 + tx], st[j * 16 + tx], a) for j in range(16): a = fmaf(wn[256 + j * 16 + tx], em[j * 16 + tx], a) a31[tx] = a l1_a = sum(abs(v) for v in a31) ra = sum(a31) pv, pe = pre[stp][n] yc = f32(pv + ra) ed = f32((288.0 * A288_U + 8.05 * U) * l1_a) delta = f32(f32(1.02 * f32(pe + ed + 4.0 * U * abs(yc))) + 1e-29) b_lo = bf16_bits(f32(yc - delta)) b_hi = bf16_bits(f32(yc + delta)) if math.isfinite(yc) and math.isfinite(delta) and abs(yc) > 1e-28 and b_lo == b_hi: row_out.append(f32(yc - delta)) else: n_fix += 1 lanes = list(a31) for tx in range(16): a = lanes[tx] for j in range(144): a = fmaf(wn[512 + j * 16 + tx], hs[j * 16 + tx], a) for j in range(144): a = fmaf(wn[2816 + j * 16 + tx], fr[j * 16 + tx], a) lanes[tx] = a for stride in (8, 4, 2, 1): for tx in range(stride): lanes[tx] = f32(lanes[tx] + lanes[tx + stride]) row_out.append(f32(fmaf(1.0, lanes[0], bf[n]) + 0.0)) outs.append(row_out) return torch.tensor(outs, dtype=torch.float32).to(torch.bfloat16), n_fix
# ---- Serving hook for S3 Inkling2MTPHead ----_STATE = { "installed": False, "mode": "bf16_splitg_coop6_1t", # <pre>_<step> "pre_nw": 8, "check": False, "reach": {"hoist_walks": 0, "hoist_steps": 0, "fallback_steps": 0, "captured_walks": 0}, "logged_hoist": False, "logged_capture": False, "logged_fallback": False, "chk_dev": None, # [4] int64: steps, state_mism, latent_mism, ctl_latent_mism "fix_dev": None, # [1] int32: fixup rows (check mode)}
def run_pre(packs: RnnHoistPacks, draft_hidden: torch.Tensor, f_rnn: torch.Tensor, pre_kind: str, pre_nw: int, need_split_bufs: bool) -> WalkCtx: dev = draft_hidden.device ext = build_ext() if pre_kind == "bf16_nocert": pre = torch.empty((GAMMA, N_OUT), dtype=torch.float32, device=dev) ext.pre_bf16_nocert(packs.w_h, packs.w_f, packs.bias, draft_hidden, f_rnn, pre, pre_nw) return WalkCtx(pre=pre, fix_cnts=None, fix_rows=None, fix_a31=None, proj_buf=None, base_ptr=draft_hidden.data_ptr(), step_bytes=draft_hidden.stride(1) * draft_hidden.element_size(), f_ptr=f_rnn.data_ptr(), gamma=GAMMA) pre = torch.empty((GAMMA, N_OUT, 2), dtype=torch.float32, device=dev) fix_cnts = torch.empty((GAMMA,), dtype=torch.int32, device=dev) if need_split_bufs else None fix_rows = torch.empty((N_OUT,), dtype=torch.int32, device=dev) if need_split_bufs else None fix_a31 = torch.empty((N_OUT, 16), dtype=torch.float32, device=dev) if need_split_bufs else None proj_buf = torch.empty((1, N_OUT), dtype=torch.bfloat16, device=dev) if need_split_bufs else None if pre_kind == "bf16_sep": ext.pre_bf16_sep(packs.w_h, packs.w_f, packs.bias, draft_hidden, f_rnn, pre, fix_cnts, pre_nw) elif pre_kind == "bf16_splitg": ext.pre_bf16_splitg(packs.w_h, packs.w_f, packs.bias, draft_hidden, f_rnn, pre, fix_cnts, pre_nw) elif pre_kind == "c12_splitg": ext.pre_c12_splitg(packs.wh_sm, packs.wh_e4, packs.wf_sm, packs.wf_e4, packs.w_raw, packs.bias, draft_hidden, f_rnn, pre, fix_cnts, pre_nw) else: raise ValueError(f"Unknown pre_kind {pre_kind}") return WalkCtx( pre=pre, fix_cnts=fix_cnts, fix_rows=fix_rows, fix_a31=fix_a31, proj_buf=proj_buf, base_ptr=draft_hidden.data_ptr(), step_bytes=draft_hidden.stride(1) * draft_hidden.element_size(), f_ptr=f_rnn.data_ptr(), gamma=GAMMA, )
def run_step(packs: RnnHoistPacks, walk: WalkCtx, step_idx: int, state: torch.Tensor, prev_tokens: torch.Tensor, w1: torch.Tensor, hidden: torch.Tensor, f_rnn: torch.Tensor, step_kind: str, pre_override: Optional[torch.Tensor] = None, fix_cnt: Optional[torch.Tensor] = None): ext = build_ext() pre_s = walk.pre[step_idx] if pre_override is None else pre_override new_state = torch.empty((1, RANK), dtype=torch.bfloat16, device=state.device) latent = torch.empty((1, RANK), dtype=torch.bfloat16, device=state.device) if step_kind == "nocert": ext.step_fused_nocert(packs.w_s, pre_s, state, prev_tokens, w1, new_state, latent) return new_state, latent if step_kind == "coop6": ext.step_fused_coop6(packs.w_s, packs.w_h, packs.w_f, packs.bias, pre_s, state, prev_tokens, w1, hidden, f_rnn, new_state, latent, fix_cnt) elif step_kind == "coop6_1t": ext.step_fused_coop6_1t(packs.w_s, packs.w_h, packs.w_f, packs.bias, pre_s, state, prev_tokens, w1, hidden, f_rnn, new_state, latent, fix_cnt) elif step_kind == "split_coop8": fc_step = walk.fix_cnts[step_idx:step_idx + 1] if pre_override is None else torch.zeros((1,), dtype=torch.int32, device=state.device) ext.step_split_coop8(packs.w_s, packs.w_h, packs.w_f, packs.bias, pre_s, state, prev_tokens, w1, hidden, f_rnn, walk.proj_buf, fc_step, walk.fix_rows, walk.fix_a31, new_state, latent, fix_cnt) elif step_kind == "proj4a": pbuf = walk.proj_buf if walk.proj_buf is not None else torch.empty((1, N_OUT), dtype=torch.bfloat16, device=state.device) ext.step_proj_4ahead_gates(packs.w_s, packs.w_h, packs.w_f, packs.bias, pre_s, state, prev_tokens, w1, hidden, f_rnn, pbuf, new_state, latent, fix_cnt) else: raise ValueError(f"Unknown step_kind {step_kind}") return new_state, latent
def parse_mode(mode: str) -> tuple[str, str]: if mode == "bf16_nocert": return "bf16_nocert", "nocert" for pk in ("bf16_sep", "bf16_splitg", "c12_splitg"): if mode.startswith(pk + "_"): return pk, mode[len(pk) + 1:] raise ValueError(f"Invalid N105_MODE: {mode}")
def _begin_walk(packs: RnnHoistPacks, draft_hidden: Optional[torch.Tensor], f_rnn: torch.Tensor) -> Optional[WalkCtx]: if ( draft_hidden is None or not draft_hidden.is_cuda or draft_hidden.dim() != 3 or draft_hidden.dtype != torch.bfloat16 or f_rnn.dtype != torch.bfloat16 ): return None bs, gamma, hid = draft_hidden.shape if ( bs != 1 or gamma != GAMMA or hid != HIDDEN or f_rnn.shape != (1, HIDDEN) or draft_hidden.stride(2) != 1 or draft_hidden.stride(1) % 8 != 0 or draft_hidden.data_ptr() % 16 != 0 or not f_rnn.is_contiguous() or f_rnn.data_ptr() % 16 != 0 ): return None pre_kind, step_kind = parse_mode(_STATE["mode"]) return run_pre(packs, draft_hidden, f_rnn, pre_kind, _STATE["pre_nw"], need_split_bufs=(step_kind in ("split_coop8", "proj4a")))
def _match_step(walk: Optional[WalkCtx], hidden: torch.Tensor, f_rnn: torch.Tensor, state: torch.Tensor, prev_tokens: torch.Tensor, w1: torch.Tensor) -> int: if ( walk is None or hidden.dim() != 2 or hidden.shape != (1, HIDDEN) or hidden.stride(1) != 1 or hidden.data_ptr() % 16 != 0 or f_rnn.data_ptr() != walk.f_ptr or state.shape != (1, RANK) or state.dtype != torch.bfloat16 or not state.is_contiguous() or state.data_ptr() % 16 != 0 or prev_tokens.numel() != 1 or prev_tokens.dtype != torch.int64 or not w1.is_contiguous() or w1.dtype != torch.bfloat16 or w1.data_ptr() % 16 != 0 ): return -1 off = hidden.data_ptr() - walk.base_ptr if off < 0 or off % walk.step_bytes != 0: return -1 s = off // walk.step_bytes return s if 0 <= s < walk.gamma else -1
def install(mtp_mod) -> bool: if os.environ.get("N105_RNNHOIST", "") != "1": return False if _STATE["installed"]: return True
_STATE["mode"] = os.environ.get("N105_MODE") or "bf16_splitg_coop6_1t" _STATE["pre_nw"] = int(os.environ.get("N105_PRE_NW") or "8") _STATE["check"] = os.environ.get("N105_CHECK", "") == "1" pre_kind, step_kind = parse_mode(_STATE["mode"])
head_cls = mtp_mod.Inkling2MTPHead model_cls = mtp_mod.Inkling2ForConditionalGenerationMTP orig_attach = model_cls.attach_shared_modules orig_init = head_cls.init_state orig_rnn = head_cls._rnn_step
def attach_shared_modules(self, *args, **kwargs): out = orig_attach(self, *args, **kwargs) mh = self.markov_head if ( mh.markov_rank == RANK and mh.hidden_size == HIDDEN and mh.rnn_proj.weight.is_cuda and mh.rnn_proj.weight.dtype == torch.bfloat16 and mh.rnn_proj.weight.shape == (N_OUT, K_TOTAL) ): t0 = time.time() cache_dir = os.environ.get("N105_BUILD_DIR") or "/root/.cache/n105_rnnhoist_b3" build_ext(build_dir=cache_dir) packs = pack_rnn_weights(mh.rnn_proj.weight, mh.rnn_proj.bias, include_c12=pre_kind.startswith("c12")) mh._n105_packs = packs mh._n105_walk = None dev = mh.rnn_proj.weight.device wh = torch.zeros((1, GAMMA, HIDDEN), dtype=torch.bfloat16, device=dev) wf = torch.zeros((1, HIDDEN), dtype=torch.bfloat16, device=dev) ws = torch.zeros((1, RANK), dtype=torch.bfloat16, device=dev) wt = torch.zeros((1,), dtype=torch.int64, device=dev) walk = _begin_walk(packs, wh, wf) assert walk is not None run_step(packs, walk, 0, ws, wt, mh.markov_w1.weight, wh[:, 0], wf, step_kind) if _STATE["check"]: _STATE["chk_dev"] = torch.zeros(4, dtype=torch.int64, device=dev) _STATE["fix_dev"] = torch.zeros(1, dtype=torch.int32, device=dev) _start_check_reporter() print( "N105RNN " + json.dumps({ "state": "ready", "mode": _STATE["mode"], "pre_nw": _STATE["pre_nw"], "check": _STATE["check"], "packed_mb": round(packs.nbytes() / 1e6, 2), "prepare_s": round(time.time() - t0, 2), }, sort_keys=True), file=sys.stderr, flush=True, ) else: print("N105RNN " + json.dumps({"state": "skipped", "shape": list(mh.rnn_proj.weight.shape)}), file=sys.stderr, flush=True) return out
def init_state(self, hidden_states): st = orig_init(self, hidden_states) packs = getattr(self, "_n105_packs", None) self._n105_walk = None if packs is not None and isinstance(st, tuple) and len(st) == 2: walk = _begin_walk(packs, hidden_states, st[1]) self._n105_walk = walk if walk is not None: _STATE["reach"]["hoist_walks"] += 1 if torch.cuda.is_current_stream_capturing(): _STATE["reach"]["captured_walks"] += 1 if not _STATE["logged_capture"]: _STATE["logged_capture"] = True print("N105RNN " + json.dumps({"state": "captured", "mode": _STATE["mode"], "reach": dict(_STATE["reach"])}, sort_keys=True), file=sys.stderr, flush=True) return st
def _rnn_step(self, state, prev_tokens, hidden, f_rnn): packs = getattr(self, "_n105_packs", None) walk = getattr(self, "_n105_walk", None) s = _match_step(walk, hidden, f_rnn, state, prev_tokens, self.markov_w1.weight) if packs is not None else -1 if s < 0: _STATE["reach"]["fallback_steps"] += 1 if not _STATE["logged_fallback"]: _STATE["logged_fallback"] = True print("N105RNN " + json.dumps({"state": "fallback_active", "bs": int(state.shape[0]), "in_capture": bool(torch.cuda.is_current_stream_capturing())}, sort_keys=True), file=sys.stderr, flush=True) return orig_rnn(self, state, prev_tokens, hidden, f_rnn) _STATE["reach"]["hoist_steps"] += 1 if not _STATE["logged_hoist"] and _STATE["reach"]["hoist_steps"] >= GAMMA: _STATE["logged_hoist"] = True print("N105RNN " + json.dumps({"state": "hoist_active", "mode": _STATE["mode"], "in_capture": bool(torch.cuda.is_current_stream_capturing()), "reach": dict(_STATE["reach"])}, sort_keys=True), file=sys.stderr, flush=True) ns, lat = run_step( packs, walk, s, state, prev_tokens, self.markov_w1.weight, hidden, f_rnn, step_kind, fix_cnt=_STATE["fix_dev"] if _STATE["check"] else None, ) if _STATE["check"] and _STATE["chk_dev"] is not None: ref_ns, ref_lat = orig_rnn(self, state, prev_tokens, hidden, f_rnn) ctl_ns, ctl_lat = run_step( packs, walk, s, state, prev_tokens, self.markov_w1.weight, hidden, f_rnn, step_kind, pre_override=torch.zeros_like(walk.pre[s]), ) c = _STATE["chk_dev"] c[0] += 1 c[1] += (ns.view(torch.int16) != ref_ns.view(torch.int16)).sum() c[2] += (lat.view(torch.int16) != ref_lat.view(torch.int16)).sum() c[3] += (ctl_lat.view(torch.int16) != ref_lat.view(torch.int16)).sum() return ns, lat
model_cls.attach_shared_modules = attach_shared_modules head_cls.init_state = init_state head_cls._rnn_step = _rnn_step _STATE["installed"] = True print("N105RNN " + json.dumps({"state": "installed", "mode": _STATE["mode"], "pre_nw": _STATE["pre_nw"], "check": _STATE["check"]}, sort_keys=True), file=sys.stderr, flush=True) return True
def _start_check_reporter(): def _loop(): while True: time.sleep(20) c = _STATE["chk_dev"] fc = _STATE["fix_dev"] if c is None: continue try: v = c.cpu().tolist() fv = int(fc.cpu().item()) if fc is not None else 0 tot_rows = max(1, v[0] * N_OUT) print( "N105CHECK " + json.dumps({ "steps": v[0], "state_mism": v[1], "latent_mism": v[2], "ctl_latent_mism": v[3], "fixup_rows": fv, "fixup_pct": round(100.0 * fv / tot_rows, 2) if v[0] > 0 else 0.0, "reach": dict(_STATE["reach"]), }, sort_keys=True), file=sys.stderr, flush=True, ) except Exception: pass t = threading.Thread(target=_loop, daemon=True, name="n105_check_reporter") t.start()12345678910111213141516171819202122232425262728293031323334353637"""n13 (inkling2-spark attn-global seat): route the global-layer (non-local) rel-bias prefill FA4 SM120 kernel toFlashAttentionForwardSm120BandSplit (n13_fwd.py). Scope: has_bias, not is_local, not pack_gqa, plainFlashAttentionForwardSm120 only, any split count (the served call is a 1-split split-KV launch: FP32 output) (slidinglayers, padded/packed verify and decode kernels are untouched). No switch: thekernel file is mounted as fa4_sm120/n13_fwd.py, which changes the FA4 CuTe AOT cache fingerprint (it hashes the fa4_sm120sources, not this file), so a switch would let two different kernels share one cache key. Control = the parent recipe.Imported once from the patched inkling2_attn.py."""import logging
_INSTALLED = Falselogger = logging.getLogger(__name__)
def install(): global _INSTALLED if _INSTALLED: return from sglang.kernels.ops.attention.fa4_sm120 import runtime as _rt from sglang.kernels.ops.attention.fa4_sm120.flash_fwd import FlashAttentionForwardSm120 from sglang.kernels.ops.attention.fa4_sm120.n13_fwd import FlashAttentionForwardSm120BandSplit
orig = _rt.Sm120ForwardPolicy.make_kernel
def make_kernel(**kw): k = orig(**kw) if (type(k) is FlashAttentionForwardSm120 and kw.get("has_bias") and not kw.get("is_local") and not kw.get("pack_gqa") and not k._uses_split_pv_warps()): k.__class__ = FlashAttentionForwardSm120BandSplit make_kernel.hits += 1 logger.warning("n13: FA4 SM120 band-split kernel built (global rel-bias prefill, tile %s x %s, hit %d)", k.tile_m, k.tile_n, make_kernel.hits) return k
make_kernel.hits = 0 _rt.Sm120ForwardPolicy.make_kernel = staticmethod(make_kernel) _INSTALLED = True logger.warning("n13: global-layer band-split FA4 hook installed")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655# Generated by work_attng/gen_n13.py from the image's sglang/kernels/ops/attention/fa4_sm120/flash_fwd.py (md5 f7161e38)."""n13 (inkling2-spark attn-global seat): FlashAttentionForwardSm120BandSplit = the image's SM120 FA4 forward kernel with therelative-bias specialization's unmasked-key loop split in two: the blocks inside the bias band (apply_bias True as a compile-timeconstant) and the far blocks (apply_bias False as a compile-time constant). The served kernel keeps apply_bias as a runtime branchin one loop, which keeps the bias path's state live across the far blocks (ptxas: 255 registers, spill reloads in the far loopbody). Every block is visited in the same order with the same instructions on its values, so outputs are meant to be bitwiseequal to the served kernel's (checked on the GPU). Only mma() is replaced; everything else is inherited."""from sglang.kernels.ops.attention.fa4_sm120 import flash_fwd as _baseglobals().update({k: v for k, v in vars(_base).items() if not k.startswith("__")})from sglang.kernels.ops.attention.fa4_sm120.flash_fwd import FlashAttentionForwardSm120
N13_BIAS_PLAIN = True # frozen (mb2/mb3 choice n13ep)N13_FAR_ADDR = True # frozen
class FlashAttentionForwardSm120BandSplit(FlashAttentionForwardSm120): """SM120 FA4 forward with the bias-band / far-key mainloop split (n13)."""
def _setup_attributes(self): super()._setup_attributes() if const_expr(self.has_bias and N13_BIAS_PLAIN): # n13: unswizzled row-major bias tile (same values; TMA SWIZZLE_NONE). Each thread's 64 bias reads become # immediate offsets from two row bases instead of 64 hoisted swizzled addresses held across the mainloop. atom = cute.make_composed_layout( cute.make_swizzle(0, 4, 3), 0, cute.make_layout((8, self.tile_n), stride=(self.tile_n, 1)) ) self.sBias_layout = cute.tile_to_shape( atom, (self.bias_block_size, self.tile_n, self.num_stages), (0, 1, 2) )
@cute.jit def mma( self, mQ: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], sQ: cute.Tensor, sK: cute.Tensor, sV: cute.Tensor, sO: cute.Tensor, sP: Optional[cute.Tensor], sRowScale: Optional[cute.Tensor], sLSE: Optional[cute.Tensor], learnable_sink: Optional[cute.Tensor], pipeline_k: PipelineAsync, pipeline_v: PipelineAsync, gmem_tiled_copy_Q: cute.TiledCopy, gmem_tiled_copy_O: cute.TiledCopy, tiled_mma_qk: cute.TiledMma, tiled_mma_pv: cute.TiledMma, tidx: Int32, softmax_scale_log2: Float32, softmax_scale: Optional[Float32], consumer_state: PipelineState, block_info: BlockInfo, seqlen: SeqlenInfoQK, n_block_min: Int32, n_block_max: Int32, m_block: Int32, head_idx: Int32, batch_idx: Int32, split_idx: Int32, is_qk_owner: cutlass.Constexpr[bool], aux_data: AuxData = AuxData(), fastdiv_mods=None, sBias: Optional[cute.Tensor] = None, pipeline_bias: Optional[PipelineAsync] = None, base_softmax_scale: Optional[Float32] = None, ): mQ_cur = seqlen.offset_batch_Q(mQ, batch_idx, dim=3)[None, None, head_idx] if const_expr(not self.pack_gqa): gQ = cute.local_tile(mQ_cur, (self.tile_m, self.tile_hdim), (m_block, 0)) num_bias_loads = Int32(0) if const_expr(self.has_bias): _, num_bias_loads = self._get_bias_load_info( block_info, seqlen, m_block, n_block_min, n_block_max, )
split_pv_warps = self._uses_split_pv_warps() thr_mma_pv = tiled_mma_pv.get_slice(tidx) acc_shape_O = thr_mma_pv.partition_shape_C((self.tile_m, self.tile_hdimv)) acc_O = cute.make_rmem_tensor(acc_shape_O, Float32) acc_O.fill(0.0)
smem_copy_atom_QK = cute.make_copy_atom( warp.LdMatrix8x8x16bOp(transpose=False, num_matrices=4), self.dtype ) smem_copy_atom_V = cute.make_copy_atom( warp.LdMatrix8x8x16bOp(transpose=True, num_matrices=4), self.dtype ) smem_thr_copy_V = utils.make_tiled_copy_B( smem_copy_atom_V, tiled_mma_pv ).get_slice(tidx) if const_expr(split_pv_warps): tOrV = thr_mma_pv.make_fragment_B(thr_mma_pv.partition_B(sV[None, None, 0])) tOsV = smem_thr_copy_V.partition_S(sV) smem_thr_copy_P = utils.make_tiled_copy_A( smem_copy_atom_QK, tiled_mma_pv ).get_slice(tidx) tPsP = smem_thr_copy_P.partition_S(sP) tOrP = thr_mma_pv.make_fragment_A(thr_mma_pv.partition_A(sP[None, None, 0])) if const_expr(not split_pv_warps or is_qk_owner): thr_mma_qk = tiled_mma_qk.get_slice(tidx) smem_thr_copy_Q = utils.make_tiled_copy_A( smem_copy_atom_QK, tiled_mma_qk ).get_slice(tidx) smem_thr_copy_K = utils.make_tiled_copy_B( smem_copy_atom_QK, tiled_mma_qk ).get_slice(tidx) if const_expr(split_pv_warps): tSrQ = thr_mma_qk.make_fragment_A(thr_mma_qk.partition_A(sQ)) tSrK = thr_mma_qk.make_fragment_B( thr_mma_qk.partition_B(sK[None, None, 0]) ) tSsQ = smem_thr_copy_Q.partition_S(sQ) tSsK = smem_thr_copy_K.partition_S(sK) smem_store_atom_P = utils.get_smem_store_atom( 120, self.dtype, ) smem_thr_store_P = cute.make_tiled_copy_C( smem_store_atom_P, tiled_mma_qk ).get_slice(tidx) tPsP_store = smem_thr_store_P.partition_D(sP)
if const_expr(not split_pv_warps or is_qk_owner): gmem_thr_copy_Q = gmem_tiled_copy_Q.get_slice(tidx) if const_expr(not self.pack_gqa): self.load_Q( gmem_thr_copy_Q, gQ, sQ, m_block, seqlen=seqlen.seqlen_q, headdim=mQ.shape[1], ) else: PackGQA( self.tile_m, self.tile_hdim, self.check_hdim_oob, self.qhead_per_kvhead, ).load_Q( mQ_cur, sQ, gmem_tiled_copy_Q, tidx, m_block, seqlen.seqlen_q, ) cute.arch.cp_async_commit_group() cute.arch.cp_async_wait_group(0) cute.arch.barrier( barrier_id=1, number_of_threads=self.num_Q_load_threads, )
if const_expr(not split_pv_warps or is_qk_owner): if const_expr(self._uses_n_distributed_qk()): softmax = None mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, tSrQ=tSrQ, tSrK=tSrK, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, tidx=tidx, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, tOsV=tOsV, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, smem_thr_store_P=( smem_thr_store_P if const_expr(self.split_qk_n) else None ), tPsP_store=(tPsP_store if const_expr(self.split_qk_n) else None), sQ=sQ, sK=sK, sP=sP, sRowScale=sRowScale, sLSE=sLSE, softmax_scale_log2=softmax_scale_log2, softmax_scale=softmax_scale, ) if const_expr(self.split_qk_n): mask = AttentionMask( self.tile_m, self.tile_n, seqlen, block_info.window_size_left, block_info.window_size_right, (self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1), enable_r2p_optimization=False, ) mask_fn = partial( mask.apply_mask, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, thr_mma=thr_mma_qk, mask_causal=self.is_causal, mask_local=self.is_local, aux_data=aux_data, fastdiv_mods=( fastdiv_mods if const_expr(self.mask_mod is not None) else None ), ) else: mask_fn = None else: softmax = Softmax.create( softmax_scale_log2, num_rows=acc_O.shape[0][0] * acc_O.shape[1], softmax_scale=softmax_scale, ) softmax.reset() if const_expr(split_pv_warps): mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, tSrQ=tSrQ, tSrK=tSrK, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, tSsQ=tSsQ, tSsK=tSsK, tOsV=tOsV, smem_thr_store_P=smem_thr_store_P, tPsP_store=tPsP_store, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, sRowScale=sRowScale, sLSE=sLSE, ) else: mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, acc_O=acc_O, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, sQ=sQ, sK=sK, sV=sV, ) mask = AttentionMask( self.tile_m, self.tile_n, seqlen, block_info.window_size_left, block_info.window_size_right, self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1, ) mask_fn = partial( mask.apply_mask, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, thr_mma=thr_mma_qk, mask_causal=self.is_causal, mask_local=self.is_local, aux_data=aux_data, fastdiv_mods=( fastdiv_mods if const_expr(self.mask_mod is not None) else None ), ) else: softmax = None mma_params = SimpleNamespace( thr_mma_pv=thr_mma_pv, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, ) smem_copy_params = SimpleNamespace( smem_thr_copy_V=smem_thr_copy_V, tOsV=tOsV, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, sRowScale=sRowScale, sLSE=sLSE, ) mask_fn = None if const_expr(split_pv_warps and not self._uses_n_distributed_qk()): compute_one_n_block = ( self.compute_one_n_block_split_pv_owner if const_expr(is_qk_owner) else self.compute_one_n_block_split_pv_helper ) elif const_expr(not self._uses_n_distributed_qk()): compute_one_n_block = self.compute_one_n_block if const_expr(not split_pv_warps or is_qk_owner): mask_fn_seqlen = partial(mask_fn, mask_mod=self.mask_mod, mask_seqlen=True) mask_fn_no_seqlen = partial( mask_fn, mask_mod=self.mask_mod, mask_seqlen=False ) else: mask_fn_seqlen = None mask_fn_no_seqlen = None n_block = cutlass.max(n_block_max - 1, 0) if const_expr(self._uses_n_distributed_qk()): consumer_state = self.compute_one_n_block_split_pv_distributed_qk( n_block, consumer_state, mma_params, smem_copy_params, None, pipeline_k, pipeline_v, score_mod=self.score_mod, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_seqlen, is_first_n_block=True, is_last_n_block=n_block == n_block_min, learnable_sink=learnable_sink, split_idx=split_idx, ) for n_tile in cutlass.range(n_block - n_block_min, unroll=1): consumer_state = self.compute_one_n_block_split_pv_distributed_qk( n_block - n_tile - 1, consumer_state, mma_params, smem_copy_params, None, pipeline_k, pipeline_v, score_mod=self.score_mod, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, is_last_n_block=n_block - n_tile - 1 == n_block_min, learnable_sink=learnable_sink, split_idx=split_idx, ) else: consumer_state = compute_one_n_block( n_block, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=n_block >= n_block_max - num_bias_loads, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_seqlen, is_first_n_block=True, ) n_block_upper = n_block if const_expr(self.is_causal or self.is_local): n_block_min_causal_local_mask = ( block_info.get_n_block_min_causal_local_mask( seqlen, m_block, n_block_min ) ) for n_tile in cutlass.range( n_block_max - 1 - n_block_min_causal_local_mask, unroll=1 ): n_block = n_block_max - 2 - n_tile consumer_state = compute_one_n_block( n_block, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=n_block >= n_block_max - num_bias_loads, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_seqlen, ) n_block_upper = cutlass.min( n_block_upper, n_block_min_causal_local_mask ) n_block_min_before_local_mask = ( block_info.get_n_block_min_before_local_mask( seqlen, m_block, n_block_min ) ) if const_expr(self.has_bias): # n13: blocks [n_far_top, n_block_upper) are inside the bias band (apply_bias True for every one of # them in the served loop), blocks below n_far_top are outside it (apply_bias False). Same blocks, # same order, same arithmetic; the bias branch is resolved at compile time in each loop. n_far_top = cutlass.max( cutlass.min(n_block_upper, n_block_max - num_bias_loads), n_block_min_before_local_mask, ) for n_tile in cutlass.range(n_block_upper - n_far_top, unroll=1): consumer_state = compute_one_n_block( n_block_upper - n_tile - 1, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=True, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, ) smem_copy_params_far = smem_copy_params if const_expr(N13_FAR_ADDR): # n13: fresh ldmatrix address set for the far loop. tidx_far == tidx at run time (seqlen_k < 2**30), # but ptxas cannot prove it, so these addresses are not the band loops' (spilled) values. tidx_far = tidx + (seqlen.seqlen_k >> 30) smem_copy_params_far = SimpleNamespace( smem_thr_copy_Q=utils.make_tiled_copy_A(smem_copy_atom_QK, tiled_mma_qk).get_slice(tidx_far), smem_thr_copy_K=utils.make_tiled_copy_B(smem_copy_atom_QK, tiled_mma_qk).get_slice(tidx_far), smem_thr_copy_V=utils.make_tiled_copy_B(smem_copy_atom_V, tiled_mma_pv).get_slice(tidx_far), sQ=sQ, sK=sK, sV=sV, ) for n_tile in cutlass.range( n_far_top - n_block_min_before_local_mask, unroll=1 ): consumer_state = compute_one_n_block( n_far_top - n_tile - 1, consumer_state, mma_params, smem_copy_params_far, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=False, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, ) else: for n_tile in cutlass.range( n_block_upper - n_block_min_before_local_mask, unroll=1 ): consumer_state = compute_one_n_block( n_block_upper - n_tile - 1, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=(n_block_upper - n_tile - 1 >= n_block_max - num_bias_loads), batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, ) if const_expr(self.is_local and block_info.window_size_left is not None): n_block_upper = cutlass.min( n_block_upper, n_block_min_before_local_mask ) for n_tile in cutlass.range(n_block_upper - n_block_min, unroll=1): consumer_state = compute_one_n_block( n_block_upper - n_tile - 1, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=( n_block_upper - n_tile - 1 >= n_block_max - num_bias_loads ), batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, )
if const_expr(self._uses_n_distributed_qk()): cO = cute.make_identity_tensor((self.tile_m, self.tile_hdimv)) tOcO_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_pv.partition_C(cO) ) num_rows_pv = acc_O.shape[0][0] * acc_O.shape[1] row_scale_pv = cute.make_rmem_tensor(num_rows_pv, Float32) lse = cute.make_rmem_tensor(num_rows_pv, Float32) for r in cutlass.range(cute.size(row_scale_pv), unroll_full=True): row = tOcO_mn_finalize[r, 0][0] row_scale_pv[r] = sRowScale[0, row] lse[r] = sLSE[row] self._rescale_O(acc_O, row_scale_pv) elif const_expr(split_pv_warps): if const_expr(is_qk_owner): sink_val = None if const_expr(learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = Float32(learnable_sink[head_idx]) else: sink_val = cute.make_rmem_tensor_like(softmax.row_max, Float32) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) for r in cutlass.range(cute.size(sink_val), unroll_full=True): row = m_block * self.tile_m + tScS_mn_finalize[r][0] q_head_idx = ( row % self.qhead_per_kvhead + head_idx * self.qhead_per_kvhead ) sink_val[r] = Float32(learnable_sink[q_head_idx]) if const_expr(self.is_split_kv and learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = sink_val if split_idx == 0 else -Float32.inf elif split_idx != 0: sink_val.fill(-Float32.inf) row_scale_qk = softmax.finalize(sink_val=sink_val) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) if tScS_mn_finalize[0][1] == 0: for r in cutlass.range(cute.size(row_scale_qk), unroll_full=True): row = tScS_mn_finalize[r][0] sRowScale[2, row] = row_scale_qk[r] sLSE[row] = softmax.row_sum[r] cute.arch.fence_view_async_shared() cute.arch.barrier( barrier_id=int(NamedBarrierFwd.PFull), number_of_threads=self.num_mma_threads, ) cO = cute.make_identity_tensor((self.tile_m, self.tile_hdimv)) tOcO_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_pv.partition_C(cO) ) num_rows_pv = acc_O.shape[0][0] * acc_O.shape[1] row_scale_pv = cute.make_rmem_tensor(num_rows_pv, Float32) lse = cute.make_rmem_tensor(num_rows_pv, Float32) for r in cutlass.range(cute.size(row_scale_pv), unroll_full=True): row = tOcO_mn_finalize[r, 0][0] row_scale_pv[r] = sRowScale[2, row] lse[r] = sLSE[row] self._rescale_O(acc_O, row_scale_pv) else: sink_val = None if const_expr(learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = Float32(learnable_sink[head_idx]) else: sink_val = cute.make_rmem_tensor_like(softmax.row_max, Float32) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) for r in cutlass.range(cute.size(sink_val), unroll_full=True): row = m_block * self.tile_m + tScS_mn_finalize[r][0] q_head_idx = ( row % self.qhead_per_kvhead + head_idx * self.qhead_per_kvhead ) sink_val[r] = Float32(learnable_sink[q_head_idx]) if const_expr(self.is_split_kv and learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = sink_val if split_idx == 0 else -Float32.inf elif split_idx != 0: sink_val.fill(-Float32.inf) row_scale = softmax.finalize(sink_val=sink_val) softmax.rescale_O(acc_O, row_scale) lse = softmax.row_sum
self.epilogue( acc_O, lse, mO, mLSE, sO, seqlen, gmem_tiled_copy_O, None, tiled_mma_pv, tidx, m_block, head_idx, batch_idx, split_idx, ) return consumer_state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641"""n140: INT6 screen for n78's certified greedy verify LM head (inkling2-spark decode seat, 2026-11-24).
WHAT CHANGES vs n78 S8 (work_packed/n78/n78_kern.py 77ba2186, served in S3 .. S5b): only K1, the screen. n78's K0 (x group norms),K2 (reduce), the served softcap, K3 (select) and K4 (E1 exact pass = the served _gemv_kernel body) run unchanged, on the samebuffers, so the certificate argument of 'RULE n78 mb' + amendments 1-2 carries over word for word: - the quantized head D is the one n78's pack(W, 6) makes (q in [-31, 31], FP16 scale per (id, 192-group) rounded up), and the bound tables R (FP16 ||W_vg - D_vg|| rounded up) and N (FP32 max(||W_v||, ||D_v||) rounded up) are n78's: pack6f() builds them with the same arithmetic and tests/test_n140_cpu.py T1 checks them bitwise against n78_kern.pack(W, 6). mb2's S6 row (the same D / R / N on 1,649 real bs-1 verify slots: 0 bound violations, 0 token misses, tiles p50 9 / p90 64 / max 5,868 / mean 47.3, not certifiable 0) is therefore the real-row tile evidence for this form; - the bound formula is n78 K1's: B = (qterm * sum_g ||x_g|| R_vg + cn N_v ||x||) (1 + 2^-18), slop = (|S| + B) 2^-20 + 1e-30, lo = S - B - slop, hi = S + B + slop, cn = 2 C_ACC(K); per (row, 32-id tile) FB = max hi over real ids, LOC = max lo over real ids, BAD = any non-finite S or B; ADDED guard: BAD also when ||x|| (K0's rounded-up norm) of a live row is outside [2^-10, 2^20] (DESIGN.md sec 2: below 2^-10 the absolute slop no longer covers squares that underflow in K0). - only S changes: FP32 S = sum_g sc_g * (MMA chain over the group's 12 k16 steps), a shorter-chain order than S6's Triton dot, inside the same C_ACC model (DESIGN.md sec 2 (ii)); the mb re-checks S against FP64 x.D on every row and id.
THE SCREEN (CUDA, built at prepare time with torch load_inline like n75 build 2): one CTA per 32-id tile (grid V / 32), 12 warps,warp g = the 192-value group g, 4 n8 sub-tiles x 3 64-K steps x 4 mma.sync.m16n8k16 (BF16 in, FP32 acc) per warp; A = x rows(rows >= M zero), B = the INT6 weights decoded in registers: (0x4300 | u) is the BF16 128 + u (u = q + 32 in [1, 63]) and onebf16x2 subtract of 160 gives q exactly. Stream in B-fragment order: per (tile, group) a 4,608-byte block of 9 x 512-byte warploads (16 B per lane): chunks 0-5 the low nibbles, chunks 6-8 the high 2-bit pairs. Inside each 16-wide MMA the k slots of lanequad t are mapped to 16 contiguous k (base + 16 t + 4 j4 + {0, 1, 2, 3}) for both A and B, so each lane's x and weights arecontiguous (the dot is order-free; the bound covers any order). Weights read once (ld.global.cs), x through the read-only path.Bytes: 347.4 MB stream + n78's tables (sc 4.8, R 4.8, N 0.8) = 357.8 MB, vs S8's 473.6 MB.
E3 (second exact form, carried into the mb): n78's select stays; a one-CTA compaction writes the ascending list of needed tiles,and the exact kernel's CTA p computes LIST[p] (p < count) with the served body and writes -inf on tile p when NEED[p] is 0: theneeded tiles start in the first wave instead of wherever their tile id falls in the 6,282-CTA sweep. Flag 0: LIST = 0..T-1, soCTA p computes tile p: the served schedule.
CPU: build_emu() compiles the SAME source with g++ (no __CUDACC__): the per-lane fragment / decode / epilogue code is shared, thewarp MMA is emulated from the PTX fragment layout. TESTF32 Cert6 runs the emulator screen + n78's Triton kernels interpreted."""import mathimport os
import torchimport tritonimport triton.language as tl
try: # served layout from sglang.srt.models.inkling_common import n78_kern as K78except Exception: # CPU tests / mb kit: n78_kern.py on sys.path import n78_kern as K78
GROUP, NG, TILE, KDIM = 192, 12, 32, 2304X_LO, X_HI = 2.0 ** -10, 2.0 ** 20 # live-row ||x|| domain of the certificate (outside: BAD -> every tile)
CUDA_SRC = r'''// ============================================================ n140 INT6 screen: shared host / device part#include <stdint.h>#include <math.h>#ifdef __CUDACC__#include <cuda_bf16.h>#define N140_HD __host__ __device__ __forceinline__#else#include <cmath>#define N140_HD static inlinestruct uint4 { uint32_t x, y, z, w; };#endif
namespace n140 {constexpr int KD = 2304, GROUP = 192, NG = 12, TILE = 32, SUB = 4, STEPS = 3, UNITS = 12, CHUNKS = 9, NWARP = 12, NT = 384;constexpr int RS = 40; // smem floats per (group, row): 32 ids + 8 pad
// uint4 index of chunk c of lane `lane` in the (tile, group) block of the B-fragment streamN140_HD size_t chunk_index(long tile, int g, int c, int lane) { return ((((size_t)tile * NG + g) * CHUNKS + c) << 5) + lane; }// unit U = 4 u + i (64-K step u, sub-tile i; step-major, so one step reads chunks 2u, 2u + 1 and 6 + u): nibble words in chunk// U >> 1, words 2 (U & 1) + {0, 1}; high word: chunk 6 + U / 4, word U % 4. Pair P = 0..7 of a unit holds values 2P, 2P + 1// (value j <-> k = 192 g + 64 u + 16 t + j, t = lane & 3; id = 32 tile + 8 i + lane / 4).N140_HD int unit_of(int i, int u) { return 4 * u + i; }N140_HD int nib_chunk(int U) { return U >> 1; }N140_HD int nib_word(int U, int P) { return 2 * (U & 1) + (P >> 2); }N140_HD int hi_chunk(int U) { return 6 + (U >> 2); }N140_HD int hi_word(int U) { return U & 3; }// bf16x2 (128 + u_{2P}, 128 + u_{2P+1}): low nibbles at bits 4p / 16 + 4p of the nibble word, high pairs at bits 2P / 16 + 2PN140_HD uint32_t magic_pair(uint32_t nib, uint32_t hiw, int P) { const uint32_t lo = (nib >> (4 * (P & 3))) & 0x000F000Fu; const uint32_t h2 = ((hiw >> (2 * P)) & 0x00030003u) << 4; return lo | h2 | 0x43004300u;}N140_HD uint32_t word_of(const uint4& v, int w) { return w == 0 ? v.x : (w == 1 ? v.y : (w == 2 ? v.z : v.w)); }// x words of one 64-K step for one row: xa = values 0..7, xb = values 8..15 of the lane's 16; MMA j4: a_lo = word 2 j4, a_hi = 2 j4 + 1N140_HD uint32_t xword(const uint4& xa, const uint4& xb, int wi) { return wi < 4 ? word_of(xa, wi) : word_of(xb, wi - 4); }
#if defined(__CUDA_ARCH__)N140_HD float mul_rn(float a, float b) { return __fmul_rn(a, b); }N140_HD float add_rn(float a, float b) { return __fadd_rn(a, b); }N140_HD float fma_rn(float a, float b, float c) { return __fmaf_rn(a, b, c); }#elseN140_HD float mul_rn(float a, float b) { return a * b; }N140_HD float add_rn(float a, float b) { return a + b; }N140_HD float fma_rn(float a, float b, float c) { return std::fma(a, b, c); }#endifN140_HD float h2f(uint16_t h) { // FP16 bits -> float (exact), no intrinsics: shared by host and device const uint32_t s = (uint32_t)(h & 0x8000u) << 16, e = (h >> 10) & 0x1Fu, m = h & 0x3FFu; float v; if (e == 0) v = (float)m * 5.9604644775390625e-08f; // subnormal: m * 2^-24 (exact) else if (e == 31) v = m ? NAN : INFINITY; else { union { uint32_t u; float f; } c; c.u = ((e + 112u) << 23) | (m << 13); v = c.f; } union { uint32_t u; float f; } r; r.f = v; r.u |= s; return r.f;}
struct Epi { float s, b, lo, hi; int fin; };// The bound per (row, id), n78 K1's formula; explicit roundings so host and device agree bit for bit.N140_HD Epi epilogue(const float* part, const float* sc, const float* xg, const float* rr, float xn, float nv, float qterm, float cn) { float s = 0.f, bq = 0.f; for (int g = 0; g < NG; ++g) s = fma_rn(part[g], sc[g], s); for (int g = 0; g < NG; ++g) bq = fma_rn(xg[g], rr[g], bq); const float b = mul_rn(add_rn(mul_rn(qterm, bq), mul_rn(cn, mul_rn(xn, nv))), 1.0f + 3.814697265625e-06f); // (1 + 2^-18) const float slop = add_rn(mul_rn(add_rn(fabsf(s), b), 9.5367431640625e-07f), 1e-30f); // 2^-20 Epi r; r.s = s; r.b = b; r.lo = add_rn(add_rn(s, -b), -slop); r.hi = add_rn(add_rn(s, b), slop); r.fin = (s == s) && (fabsf(s) < INFINITY) && (b == b) && (fabsf(b) < INFINITY); return r;}N140_HD int xn_in_domain(float xn) { return (xn >= 9.765625e-04f) && (xn <= 1048576.0f); } // [2^-10, 2^20], NaN -> 0} // namespace n140
#ifdef __CUDACC__// ============================================================ device#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <c10/cuda/CUDAGuard.h>
namespace n140 {__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));}// volatile asm loads keep program order against the volatile mma: the 9 weight loads issue first, each step's x loads are not// hoisted above the previous step's MMAs (register pressure: 2 CTAs of 384 threads per SM need <= 80 registers)__device__ __forceinline__ uint4 ld_cs_v4(const void* p) { uint4 r; asm volatile("ld.global.cs.v4.u32 {%0,%1,%2,%3}, [%4];\n" : "=r"(r.x), "=r"(r.y), "=r"(r.z), "=r"(r.w) : "l"(p)); return r;}__device__ __forceinline__ uint4 ld_nc_v4(const void* p) { uint4 r; asm volatile("ld.global.nc.v4.u32 {%0,%1,%2,%3}, [%4];\n" : "=r"(r.x), "=r"(r.y), "=r"(r.z), "=r"(r.w) : "l"(p)); return r;}__device__ __forceinline__ uint32_t sub160(uint32_t v) { // bf16x2 (128 + u) - 160 = q, exact (|q| <= 31) __nv_bfloat162 a = *reinterpret_cast<__nv_bfloat162*>(&v); __nv_bfloat162 r = __hsub2(a, __floats2bfloat162_rn(160.f, 160.f)); return *reinterpret_cast<uint32_t*>(&r);}
// MT 1: rows 0-7 (M <= 8); MT 2: rows 0-15. Grid = V / 32 CTAs (one per 32-id tile), NT threads.template <int MT>__global__ void __launch_bounds__(NT, 2) screen_kernel( const uint16_t* __restrict__ x, int SX, int M, const uint4* __restrict__ Qf, const uint16_t* __restrict__ SC, const uint16_t* __restrict__ R, const float* __restrict__ NV, const float* __restrict__ XG, const float* __restrict__ XN, const int* __restrict__ FLAG, float* __restrict__ FB, int T1, float* __restrict__ LOC, int NCTA, int* __restrict__ BAD, float* __restrict__ DS, float* __restrict__ DLO, float* __restrict__ DHI, int dbg, int V, int NREAL, float qterm, float cn) { if (*FLAG == 0) return; // flag 0: n78's select computes every tile; nothing here is read constexpr int MR = 8 * MT; __shared__ float red[NG][MR][RS]; __shared__ int bad_s; const int tile = blockIdx.x, warp = threadIdx.x >> 5, lane = threadIdx.x & 31, gid = lane >> 2, tq = lane & 3; if (threadIdx.x == 0) bad_s = 0; uint4 w[CHUNKS];#pragma unroll for (int c = 0; c < CHUNKS; ++c) w[c] = ld_cs_v4(Qf + chunk_index(tile, warp, c, lane)); float acc[SUB][4];#pragma unroll for (int i = 0; i < SUB; ++i) acc[i][0] = acc[i][1] = acc[i][2] = acc[i][3] = 0.f; const int kb = warp * GROUP + 16 * tq; const bool live0 = gid < M, live1 = MT == 2 && gid + 8 < M;#pragma unroll for (int u = 0; u < STEPS; ++u) { uint4 xa0 = make_uint4(0, 0, 0, 0), xb0 = xa0, xa1 = xa0, xb1 = xa0; if (live0) { const uint4* p = reinterpret_cast<const uint4*>(x + (size_t)gid * SX + kb + 64 * u); xa0 = ld_nc_v4(p); xb0 = ld_nc_v4(p + 1); } if (live1) { const uint4* p = reinterpret_cast<const uint4*>(x + (size_t)(gid + 8) * SX + kb + 64 * u); xa1 = ld_nc_v4(p); xb1 = ld_nc_v4(p + 1); }#pragma unroll for (int j4 = 0; j4 < 4; ++j4) { const uint32_t a0 = xword(xa0, xb0, 2 * j4), a2 = xword(xa0, xb0, 2 * j4 + 1); const uint32_t a1 = MT == 2 ? xword(xa1, xb1, 2 * j4) : 0u, a3 = MT == 2 ? xword(xa1, xb1, 2 * j4 + 1) : 0u;#pragma unroll for (int i = 0; i < SUB; ++i) { const int U = unit_of(i, u); const uint32_t hiw = word_of(w[hi_chunk(U)], hi_word(U)); const uint32_t b0 = sub160(magic_pair(word_of(w[nib_chunk(U)], nib_word(U, 2 * j4)), hiw, 2 * j4)); const uint32_t b1 = sub160(magic_pair(word_of(w[nib_chunk(U)], nib_word(U, 2 * j4 + 1)), hiw, 2 * j4 + 1)); mma16816(acc[i], a0, a1, a2, a3, b0, b1); } } }#pragma unroll for (int i = 0; i < SUB; ++i) { const int col = 8 * i + 2 * tq; red[warp][gid][col] = acc[i][0]; red[warp][gid][col + 1] = acc[i][1]; if (MT == 2) { red[warp][gid + 8][col] = acc[i][2]; red[warp][gid + 8][col + 1] = acc[i][3]; } } __syncthreads(); for (int e = threadIdx.x; e < MR * 32; e += NT) { // warp-uniform rows: NT is a multiple of 32 const int m = e >> 5, c = e & 31, n = tile * TILE + c; if (m >= M) continue; float part[NG], sc[NG], rr[NG], xg[NG];#pragma unroll for (int g = 0; g < NG; ++g) { part[g] = red[g][m][c]; sc[g] = h2f(__ldg(SC + (size_t)n * NG + g)); rr[g] = h2f(__ldg(R + (size_t)n * NG + g)); xg[g] = __ldg(XG + m * NG + g); } const float xn = __ldg(XN + m); const Epi r = epilogue(part, sc, xg, rr, xn, __ldg(NV + n), qterm, cn); if (!r.fin || !xn_in_domain(xn)) atomicOr(&bad_s, 1); // shared atomic: no write-write race for racecheck const bool real = n < NREAL; float hm = real ? r.hi : -INFINITY, lm = real ? r.lo : -INFINITY;#pragma unroll for (int o = 16; o >= 1; o >>= 1) { hm = fmaxf(hm, __shfl_xor_sync(0xffffffffu, hm, o)); lm = fmaxf(lm, __shfl_xor_sync(0xffffffffu, lm, o)); } if (c == 0) { FB[(size_t)m * T1 + tile] = hm; LOC[(size_t)m * NCTA + tile] = lm; } if (dbg) { DS[(size_t)m * V + n] = r.s; DLO[(size_t)m * V + n] = r.lo; DHI[(size_t)m * V + n] = r.hi; } } __syncthreads(); if (threadIdx.x == 0) BAD[tile] = bad_s;}} // namespace n140
static void chk(const torch::Tensor& t, at::ScalarType dt, int64_t numel, const torch::Tensor& like, const char* what) { TORCH_CHECK(t.is_cuda() && t.device() == like.device() && t.scalar_type() == dt && t.is_contiguous() && t.numel() >= numel, "n140: bad ", what);}
void screen(torch::Tensor x, torch::Tensor qf, torch::Tensor sc, torch::Tensor R, torch::Tensor nv, torch::Tensor xg, torch::Tensor xn, torch::Tensor flag, torch::Tensor fb, torch::Tensor loc, torch::Tensor bad, torch::Tensor ds, torch::Tensor dlo, torch::Tensor dhi, int64_t dbg, int64_t V, int64_t nreal, double qterm, double cn) { TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::kBFloat16 && x.dim() == 2 && x.size(1) == n140::KD && x.stride(1) == 1, "n140: x"); const int64_t M = x.size(0); TORCH_CHECK(M >= 1 && M <= 16 && (M == 1 || x.stride(0) % 8 == 0) && reinterpret_cast<uintptr_t>(x.data_ptr()) % 16 == 0, "n140: x rows / alignment"); TORCH_CHECK(V % n140::TILE == 0 && nreal > 0 && nreal <= V, "n140: V"); const int64_t T = V / n140::TILE; chk(qf, at::kByte, T * n140::NG * n140::CHUNKS * 32 * 16, x, "qf"); TORCH_CHECK(reinterpret_cast<uintptr_t>(qf.data_ptr()) % 16 == 0, "n140: qf alignment"); chk(sc, at::kHalf, V * n140::NG, x, "sc"); chk(R, at::kHalf, V * n140::NG, x, "R"); chk(nv, at::kFloat, V, x, "nv"); chk(xg, at::kFloat, 16 * n140::NG, x, "xg"); chk(xn, at::kFloat, 16, x, "xn"); chk(flag, at::kInt, 1, x, "flag"); TORCH_CHECK(fb.is_cuda() && fb.scalar_type() == at::kFloat && fb.dim() == 2 && fb.size(0) >= M && fb.size(1) == T + 1 && fb.is_contiguous(), "n140: fb"); TORCH_CHECK(loc.is_cuda() && loc.scalar_type() == at::kFloat && loc.dim() == 2 && loc.size(0) >= M && loc.size(1) == T && loc.is_contiguous(), "n140: loc"); chk(bad, at::kInt, T, x, "bad"); float *pds = nullptr, *plo = nullptr, *phi = nullptr; if (dbg) { chk(ds, at::kFloat, M * V, x, "ds"); chk(dlo, at::kFloat, M * V, x, "dlo"); chk(dhi, at::kFloat, M * V, x, "dhi"); pds = ds.data_ptr<float>(); plo = dlo.data_ptr<float>(); phi = dhi.data_ptr<float>(); } const c10::cuda::CUDAGuard guard(x.device()); auto st = at::cuda::getCurrentCUDAStream(); auto* xp = reinterpret_cast<const uint16_t*>(x.data_ptr()); auto* qp = reinterpret_cast<const uint4*>(qf.data_ptr()); auto* scp = reinterpret_cast<const uint16_t*>(sc.data_ptr()); auto* rp = reinterpret_cast<const uint16_t*>(R.data_ptr()); const int SX = M == 1 ? n140::KD : (int)x.stride(0); if (M <= 8) n140::screen_kernel<1><<<(unsigned)T, n140::NT, 0, st>>>(xp, SX, (int)M, qp, scp, rp, nv.data_ptr<float>(), xg.data_ptr<float>(), xn.data_ptr<float>(), flag.data_ptr<int>(), fb.data_ptr<float>(), (int)(T + 1), loc.data_ptr<float>(), (int)T, bad.data_ptr<int>(), pds, plo, phi, (int)dbg, (int)V, (int)nreal, (float)qterm, (float)cn); else n140::screen_kernel<2><<<(unsigned)T, n140::NT, 0, st>>>(xp, SX, (int)M, qp, scp, rp, nv.data_ptr<float>(), xg.data_ptr<float>(), xn.data_ptr<float>(), flag.data_ptr<int>(), fb.data_ptr<float>(), (int)(T + 1), loc.data_ptr<float>(), (int)T, bad.data_ptr<int>(), pds, plo, phi, (int)dbg, (int)V, (int)nreal, (float)qterm, (float)cn); C10_CUDA_KERNEL_LAUNCH_CHECK();}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("screen", &screen, "n140 INT6 screen (n78 K1 interface)"); }
#else// ============================================================ host emulator (CPU tests only): same per-lane code, warp MMA emulated#include <torch/extension.h>#include <cstring>#include <vector>
namespace n140 {static float bf2f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }static uint16_t f2bf_exact(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)(u >> 16); } // exact values onlystatic uint32_t sub160_host(uint32_t v) { const float lo = bf2f((uint16_t)(v & 0xFFFFu)) - 160.f, hi = bf2f((uint16_t)(v >> 16)) - 160.f; // exact: integers |q| <= 31 return (uint32_t)f2bf_exact(lo) | ((uint32_t)f2bf_exact(hi) << 16);}// one warp-wide mma.sync.m16n8k16 (row.col, bf16 -> f32) from the 32 lanes' fragments (PTX ISA fragment layout); FP32 sums in// k order (products of BF16 values are exact in FP32)static void warp_mma(float c[32][4], const uint32_t a[32][4], const uint32_t b[32][2]) { float A[16][16], B[16][8]; for (int L = 0; L < 32; ++L) { const int g = L >> 2, t = L & 3; for (int h = 0; h < 2; ++h) { A[g][2 * t + h] = bf2f((uint16_t)(a[L][0] >> (16 * h))); A[g + 8][2 * t + h] = bf2f((uint16_t)(a[L][1] >> (16 * h))); A[g][2 * t + 8 + h] = bf2f((uint16_t)(a[L][2] >> (16 * h))); A[g + 8][2 * t + 8 + h] = bf2f((uint16_t)(a[L][3] >> (16 * h))); B[2 * t + h][g] = bf2f((uint16_t)(b[L][0] >> (16 * h))); B[2 * t + 8 + h][g] = bf2f((uint16_t)(b[L][1] >> (16 * h))); } } float C[16][8]; for (int L = 0; L < 32; ++L) { const int g = L >> 2, t = L & 3; C[g][2 * t] = c[L][0]; C[g][2 * t + 1] = c[L][1]; C[g + 8][2 * t] = c[L][2]; C[g + 8][2 * t + 1] = c[L][3]; } for (int r = 0; r < 16; ++r) for (int n = 0; n < 8; ++n) { float s = C[r][n]; for (int k = 0; k < 16; ++k) s = s + A[r][k] * B[k][n]; C[r][n] = s; } for (int L = 0; L < 32; ++L) { const int g = L >> 2, t = L & 3; c[L][0] = C[g][2 * t]; c[L][1] = C[g][2 * t + 1]; c[L][2] = C[g + 8][2 * t]; c[L][3] = C[g + 8][2 * t + 1]; }}} // namespace n140
// q [V, K] int8 from the stream by the kernel's own extraction rule (chunk_index / magic_pair / sub160)torch::Tensor emu_decode(torch::Tensor qf, int64_t V) { using namespace n140; auto q = torch::zeros({V, KD}, torch::kInt8); const uint4* s = reinterpret_cast<const uint4*>(qf.data_ptr<uint8_t>()); int8_t* qp = q.data_ptr<int8_t>(); for (int64_t t = 0; t < V / TILE; ++t) for (int g = 0; g < NG; ++g) for (int L = 0; L < 32; ++L) { const int gid = L >> 2, tq = L & 3; uint4 w[CHUNKS]; for (int c = 0; c < CHUNKS; ++c) w[c] = s[chunk_index(t, g, c, L)]; for (int i = 0; i < SUB; ++i) for (int u = 0; u < STEPS; ++u) { const int U = unit_of(i, u); const int64_t n = t * TILE + 8 * i + gid; const uint32_t hiw = word_of(w[hi_chunk(U)], hi_word(U)); for (int P = 0; P < 8; ++P) { const uint32_t v = sub160_host(magic_pair(word_of(w[nib_chunk(U)], nib_word(U, P)), hiw, P)); const int k = g * GROUP + 64 * u + 16 * tq + 2 * P; qp[n * KD + k] = (int8_t)bf2f((uint16_t)(v & 0xFFFFu)); qp[n * KD + k + 1] = (int8_t)bf2f((uint16_t)(v >> 16)); } } } return q;}
// the screen kernel, warp by warp: returns nothing; writes fb, loc, bad (and ds / dlo / dhi when dbg) like the device kernelvoid emu_screen(torch::Tensor x, torch::Tensor qf, torch::Tensor sc, torch::Tensor R, torch::Tensor nv, torch::Tensor xg, torch::Tensor xn, torch::Tensor flag, torch::Tensor fb, torch::Tensor loc, torch::Tensor bad, torch::Tensor ds, torch::Tensor dlo, torch::Tensor dhi, int64_t dbg, int64_t V, int64_t nreal, double qterm, double cn) { using namespace n140; if (flag.data_ptr<int>()[0] == 0) return; const int M = (int)x.size(0), SX = (int)x.stride(0), MT = M <= 8 ? 1 : 2, MR = 8 * MT; const uint16_t* xp = reinterpret_cast<const uint16_t*>(x.data_ptr()); const uint4* s = reinterpret_cast<const uint4*>(qf.data_ptr<uint8_t>()); const uint16_t* scp = reinterpret_cast<const uint16_t*>(sc.data_ptr()); const uint16_t* rp = reinterpret_cast<const uint16_t*>(R.data_ptr()); const float* nvp = nv.data_ptr<float>(); const float* xgp = xg.data_ptr<float>(); const float* xnp = xn.data_ptr<float>(); float* fbp = fb.data_ptr<float>(); float* locp = loc.data_ptr<float>(); int* badp = bad.data_ptr<int>(); const int64_t T = V / TILE, T1 = T + 1; std::vector<float> red((size_t)NG * MR * TILE); for (int64_t t = 0; t < T; ++t) { for (int g = 0; g < NG; ++g) { uint4 w[32][CHUNKS]; for (int L = 0; L < 32; ++L) for (int c = 0; c < CHUNKS; ++c) w[L][c] = s[chunk_index(t, g, c, L)]; float acc[SUB][32][4]; std::memset(acc, 0, sizeof(acc)); for (int u = 0; u < STEPS; ++u) { uint4 xa[32][2], xb[32][2]; for (int L = 0; L < 32; ++L) { const int gid = L >> 2, tq = L & 3, kb = g * GROUP + 16 * tq + 64 * u; for (int h = 0; h < 2; ++h) { const int r = gid + 8 * h; uint4 z = {0, 0, 0, 0}; xa[L][h] = z; xb[L][h] = z; if (r < M && (h == 0 || MT == 2)) { std::memcpy(&xa[L][h], xp + (size_t)r * SX + kb, 16); std::memcpy(&xb[L][h], xp + (size_t)r * SX + kb + 8, 16); } } } for (int j4 = 0; j4 < 4; ++j4) { uint32_t a[32][4]; for (int L = 0; L < 32; ++L) { a[L][0] = xword(xa[L][0], xb[L][0], 2 * j4); a[L][2] = xword(xa[L][0], xb[L][0], 2 * j4 + 1); a[L][1] = MT == 2 ? xword(xa[L][1], xb[L][1], 2 * j4) : 0u; a[L][3] = MT == 2 ? xword(xa[L][1], xb[L][1], 2 * j4 + 1) : 0u; } for (int i = 0; i < SUB; ++i) { const int U = unit_of(i, u); uint32_t b[32][2]; for (int L = 0; L < 32; ++L) { const uint32_t hiw = word_of(w[L][hi_chunk(U)], hi_word(U)); b[L][0] = sub160_host(magic_pair(word_of(w[L][nib_chunk(U)], nib_word(U, 2 * j4)), hiw, 2 * j4)); b[L][1] = sub160_host(magic_pair(word_of(w[L][nib_chunk(U)], nib_word(U, 2 * j4 + 1)), hiw, 2 * j4 + 1)); } warp_mma(acc[i], a, b); } } } for (int L = 0; L < 32; ++L) { const int gid = L >> 2, tq = L & 3; for (int i = 0; i < SUB; ++i) { const int col = 8 * i + 2 * tq; red[((size_t)g * MR + gid) * TILE + col] = acc[i][L][0]; red[((size_t)g * MR + gid) * TILE + col + 1] = acc[i][L][1]; if (MT == 2) { red[((size_t)g * MR + gid + 8) * TILE + col] = acc[i][L][2]; red[((size_t)g * MR + gid + 8) * TILE + col + 1] = acc[i][L][3]; } } } } int bad_s = 0; for (int m = 0; m < M; ++m) { float hm = -INFINITY, lm = -INFINITY; for (int c = 0; c < TILE; ++c) { const int64_t n = t * TILE + c; float part[NG], scv[NG], rr[NG], xgv[NG]; for (int g = 0; g < NG; ++g) { part[g] = red[((size_t)g * MR + m) * TILE + c]; scv[g] = h2f(scp[n * NG + g]); rr[g] = h2f(rp[n * NG + g]); xgv[g] = xgp[m * NG + g]; } const Epi r = epilogue(part, scv, xgv, rr, xnp[m], nvp[n], (float)qterm, (float)cn); if (!r.fin || !xn_in_domain(xnp[m])) bad_s = 1; if (n < nreal) { hm = std::fmax(hm, r.hi); lm = std::fmax(lm, r.lo); } if (dbg) { ds.data_ptr<float>()[m * V + n] = r.s; dlo.data_ptr<float>()[m * V + n] = r.lo; dhi.data_ptr<float>()[m * V + n] = r.hi; } } fbp[m * T1 + t] = hm; locp[m * T + t] = lm; } badp[t] = bad_s; }}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("emu_decode", &emu_decode, "n140 stream decode (kernel rule)"); m.def("emu_screen", &emu_screen, "n140 screen, host emulation");}#endif'''
_EXT = None_EMU = None
def build(verbose=False, build_dir=None, name="n140_i6"): """Compile the device extension (torch cpp_extension, sm_121a). Returns the module.""" global _EXT if _EXT is None: from torch.utils.cpp_extension import load_inline arch = os.environ.get("N140_CUDA_ARCH", "121a") kw = {} if build_dir: os.makedirs(build_dir, exist_ok=True) kw["build_directory"] = build_dir _EXT = load_inline(name, 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 build_emu(verbose=False, build_dir=None): """CPU tests: the same source through g++ (no __CUDACC__), no FP contraction (host = device epilogue bit for bit).""" global _EMU if _EMU is None: from torch.utils.cpp_extension import load_inline kw = {"build_directory": build_dir} if build_dir else {} if build_dir: os.makedirs(build_dir, exist_ok=True) _EMU = load_inline("n140_emu", cpp_sources=CUDA_SRC, verbose=verbose, with_cuda=False, extra_cflags=["-O2", "-ffp-contract=off", "-fno-fast-math"], **kw) return _EMU
# ------------------------------------------------------------------------------------------------ host: packingdef quant6(w64): """FP64 rows [n, K] -> (q int64 [n, K], s16 FP16 [n, NG], D FP64 [n, K]): n78_kern.pack(W, 6)'s arithmetic, verbatim.""" n = w64.shape[0] qmax = 31 wg = w64.view(n, NG, GROUP) amax = wg.abs().amax(-1, keepdim=True) s16 = torch.where(amax > 0, K78._up16(torch.where(amax > 0, amax / qmax, torch.ones_like(amax))), torch.zeros_like(amax, dtype=torch.float16)) s = s16.to(torch.float64) q = torch.where(s > 0, torch.clamp(torch.round(wg / torch.where(s > 0, s, torch.ones_like(s))), -qmax, qmax), torch.zeros_like(wg)) D = (q * s).view(n, KDIM) return q.view(n, KDIM).to(torch.int64), s16.view(n, NG), D
def frag_stream(q): """q int [n, K] (n % 32 == 0, values in [-31, 31]) -> uint8 B-fragment stream [n / 32 * 12 * 9 * 512].""" n = q.shape[0] T = n // TILE u = (q.to(torch.int64) + 32) # [T, i, gid, g, step, tq, j] -> [T, g, U = 4 step + i, lane = 4 gid + tq, j] u = u.view(T, 4, 8, NG, 3, 4, 16).permute(0, 3, 4, 1, 2, 5, 6).reshape(T, NG, 12, 32, 16) lo4, hi2 = u & 0xF, (u >> 4) & 0x3 nib = torch.zeros((T, NG, 12, 32, 2), dtype=torch.int64, device=q.device) for h in range(2): for p in range(4): P = 4 * h + p nib[..., h] |= (lo4[..., 2 * P] << (4 * p)) | (lo4[..., 2 * P + 1] << (16 + 4 * p)) hiw = torch.zeros((T, NG, 12, 32), dtype=torch.int64, device=q.device) for P in range(8): hiw |= (hi2[..., 2 * P] << (2 * P)) | (hi2[..., 2 * P + 1] << (16 + 2 * P)) nibc = nib.view(T, NG, 6, 2, 32, 2).permute(0, 1, 2, 4, 3, 5).reshape(T, NG, 6, 32, 4) # chunk c: units 2c, 2c + 1 hic = hiw.view(T, NG, 3, 4, 32).permute(0, 1, 2, 4, 3) # chunk 6 + c: units 4c .. 4c + 3 words = torch.cat([nibc, hic], dim=2) # [T, NG, 9, 32, 4] by = torch.stack([(words >> (8 * b)) & 0xFF for b in range(4)], dim=-1) return by.to(torch.uint8).reshape(-1)
def pack6f(W, chunk=8192, d_out=None): """W [V, K] BF16 -> dict with n78's pack(W, 6) tables (sc, R, N; same arithmetic) and the B-fragment stream qf. No planes. d_out (FP32 [V, K], optional): filled with D = q x sc (exact in FP32; + 0.0 so -0.0 reads +0.0 as the kernel's decode does).""" V, Kd = W.shape assert Kd == KDIM and V % TILE == 0 and chunk % TILE == 0 dev = W.device qf = torch.empty(V // TILE * NG * 9 * 512, dtype=torch.uint8, device=dev) sc_all = torch.empty((V, NG), dtype=torch.float16, device=dev) R_all = torch.empty((V, NG), dtype=torch.float16, device=dev) N_all = torch.empty((V,), dtype=torch.float32, device=dev) per = NG * 9 * 512 // TILE # stream bytes per vocab id for a in range(0, V, chunk): w = W[a:a + chunk].to(torch.float64) n = w.shape[0] q, s16, D = quant6(w) sc_all[a:a + n] = s16 R_all[a:a + n] = K78._up16((w - D).view(n, NG, GROUP).pow(2).sum(-1).sqrt() * (1 + 2.0 ** -40) + 1e-300) N_all[a:a + n] = K78._up32(torch.maximum(w.norm(dim=1), D.norm(dim=1)) * (1 + 2.0 ** -40) + 1e-300) qf[a * per:(a + n) * per] = frag_stream(q) if d_out is not None: d_out[a:a + n] = D.float() + 0.0 del w, q, D return {"bits": 6, "qf": qf, "sc": sc_all, "R": R_all, "N": N_all, "V": V, "K": KDIM, "NG": NG, "q": torch.zeros(16, dtype=torch.uint8, device=dev), "qb": torch.zeros(16, dtype=torch.uint8, device=dev), "bytes": qf.numel() + sc_all.numel() * 2 + R_all.numel() * 2 + N_all.numel() * 4}
# ------------------------------------------------------------------------------------------------ E3: compaction + list exact pass@triton.jitdef _compact_kernel(NEED, LIST, COUNT, T, BLOCK: tl.constexpr): """One CTA: LIST = the needed tile ids in ascending order, COUNT = their number (deterministic, no atomics).""" base = 0 for t0 in range(0, T, BLOCK): t = t0 + tl.arange(0, BLOCK) nd = (tl.load(NEED + t, t < T, other=0) != 0).to(tl.int32) pos = base + tl.cumsum(nd, axis=0) - 1 tl.store(LIST + pos, t, (nd != 0) & (t < T)) base += tl.sum(nd, axis=0) tl.store(COUNT, base)
@triton.jitdef _exact_list_kernel(X, W, Y, NEED, LIST, COUNT, M, N, K, SX, SW, SY, BN: tl.constexpr, BK: tl.constexpr, MP: tl.constexpr, TESTF32: tl.constexpr = False): """CTA p: the served _gemv_kernel body on tile LIST[p] if p < COUNT; -inf on tile p if NEED[p] == 0 (disjoint tiles).""" pid = tl.program_id(0) rows = tl.arange(0, MP) if pid < tl.load(COUNT): t = tl.load(LIST + pid) cols = t * BN + tl.arange(0, BN) acc = tl.zeros((MP, BN), tl.float32) for k0 in range(0, K, BK): ks = k0 + tl.arange(0, BK) w = tl.load( W + cols[None, :].to(tl.int64) * SW + ks[:, None], (cols[None, :] < N) & (ks[:, None] < K), other=0, ) x = tl.load( X + rows[:, None] * SX + ks[None, :], (rows[:, None] < M) & (ks[None, :] < K), other=0, ) if TESTF32: acc += tl.dot(x.to(tl.float32), w.to(tl.float32), input_precision="ieee") else: acc += tl.dot(x, w) tl.store( Y + rows[:, None] * SY + cols[None, :], acc.to(Y.dtype.element_ty), (rows[:, None] < M) & (cols[None, :] < N), ) if tl.load(NEED + pid) == 0: c0 = pid * BN + tl.arange(0, BN) tl.store(Y + rows[:, None] * SY + c0[None, :], tl.full((MP, BN), float("-inf"), tl.float32), (rows[:, None] < M) & (c0[None, :] < N))
# ------------------------------------------------------------------------------------------------ host: one certified headclass Cert6(K78.Cert): """n78's Cert with the INT6 CUDA screen (K1) and, for exact='E3', the compacted exact pass. run() is capturable. ext: the device extension (build()); on CPU (testf32) the host emulator (build_emu()) is used for K1."""
def __init__(self, W, pk6, vocab, e, M, softcap_fn, ext=None, exact="E1", testf32=False, cap=K78.CAP): super().__init__(W, pk6, vocab, e, M, softcap_fn, bn=32, exact="E1", testf32=testf32, cap=cap) assert self.NCTA == self.T self.ext = ext if ext is not None else (build_emu() if testf32 else build()) self.form = exact self.list = torch.zeros(self.T, dtype=torch.int32, device=W.device) self.count = torch.zeros(1, dtype=torch.int32, device=W.device)
def screen(self, x, qterm=1.0, dbg=False): pk = self.pk ds, dlo, dhi = self.dbg if dbg else (self.dummy, self.dummy, self.dummy) K78._xnorm_kernel[(1,)](x, self.xg, self.xn, self.M, x.stride(0), NG=NG, GROUP=GROUP, GP=256, MP=16, num_warps=4) fn = self.ext.emu_screen if self.testf32 else self.ext.screen fn(x, pk["qf"], pk["sc"], pk["R"], pk["N"], self.xg, self.xn, self.flag, self.fb, self.loc, self.bad, ds, dlo, dhi, 1 if dbg else 0, self.V, self.vocab, float(qterm), float(self.cn))
def select(self): super().select() if self.form == "E3": _compact_kernel[(1,)](self.need, self.list, self.count, self.T, BLOCK=1024, num_warps=4)
def exact_pass(self, x, out, kernel=None): if kernel is not None or self.form != "E3": return super().exact_pass(x, out, kernel) _exact_list_kernel[(self.T,)](x, self.W, out, self.need, self.list, self.count, self.M, self.V, self.K, x.stride(0), self.W.stride(0), out.stride(0), BN=32, BK=256, MP=16, TESTF32=self.testf32, num_warps=4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""n14 (inkling2-spark moe seat, 2026-11-21): cheaper SM120 MoE prefill visits, EXACT (same outputs bit for bit).Replaces Inkling2Experts._forward_sm120 for calls of >= N14_MIN_TOKENS tokens (default 512: prefill chunks; decode / verifycalls keep the image path) with the image's own steps except: q: the routed NVFP4 / MXFP8 quantizers read each token row ONCE and store it into its top_k expert-sorted rows (n14_quant.cuh, token-major), instead of re-reading the token for each of its rows (8 gathered passes over x); c: the per-token combine (the image's _routed_partial: FP32 sum in top-k order of the BF16-rounded scaled rows) stores BF16 directly (round to nearest even, as the image's .to(bfloat16) of its FP32 output), so the FP32 tensor and the copy kernel go away.N14_MOE (env): letters of the parts on ("qc" default; "" or "0" = the image path, for the control arm).N14_GRID (env, default 0 = the image grid rule, 4 x SMs): CTAs of the token-major quantizers."""import loggingimport os
import torchimport tritonimport triton.language as tl
from sglang.kernels.jit.utils import cache_once, load_jitfrom sglang.kernels.ops.moe.inkling2_moe import PDL, _nvfp4_row_scale, _row_expert
logger = logging.getLogger(__name__)MODE = os.environ.get("N14_MOE", "qc").strip()MODE = "" if MODE == "0" else MODEMIN_TOKENS = int(os.environ.get("N14_MIN_TOKENS", "512"))GRID = int(os.environ.get("N14_GRID", "0"))_INSTALLED = False
@cache_oncedef _module(width: int): return load_jit( "n14_quant", str(width), cuda_files=["inkling2/n14_quant.cuh"], cuda_wrappers=[ ("nvfp4_quantize_tokens", f"n14_quant::nvfp4_quantize_tokens<{width}>"), ("mxfp8_quantize_tokens", f"n14_quant::mxfp8_quantize_tokens<{width}>"), ], )
def _sm_count(device): return torch.cuda.get_device_properties(device).multi_processor_count
def nvfp4_token_quantize(x, src2dst, top_k, offsets, grid=None): """= experts_sm120.nvfp4_routed_quantize(x, dst2src, top_k, offsets), from the inverse permutation src2dst.""" from sglang.kernels.ops.moe import inkling2_experts_sm120 as ex
width = x.shape[1] values, scales, amax = ex._nvfp4_outputs( rows=src2dst.numel(), width=width, experts=offsets.numel() - 1, device=x.device ) if src2dst.numel(): _module(width).nvfp4_quantize_tokens( x, src2dst, values, scales, amax, offsets, top_k, _sm_count(x.device), GRID if grid is None else grid ) return values, scales, amax
def mxfp8_token_quantize(x, src2dst, top_k, offsets, grid=None): """= experts_sm120.mxfp8_routed_quantize(x, dst2src, top_k, offsets), from the inverse permutation src2dst.""" from sglang.kernels.ops.moe import inkling2_experts_sm120 as ex
rows, width = src2dst.numel(), x.shape[1] values, scales, m_padded = ex._mxfp8_outputs(rows=rows, width=width, experts=offsets.numel() - 1, device=x.device) if rows: _module(width).mxfp8_quantize_tokens( x, src2dst, values.view(torch.uint8), scales, offsets, top_k, m_padded, _sm_count(x.device), GRID if grid is None else grid, ) return values, scales.t()
@triton.jitdef _routed_partial_bf16( X, XAmax, WAmax, WDenominator, Offsets, Src2Dst, Y, N: tl.constexpr, E: tl.constexpr, TOP_K: tl.constexpr, SCALED: tl.constexpr, BLOCK: tl.constexpr, SEARCH: tl.constexpr,): # The image's _routed_partial (sglang.kernels.ops.moe.inkling2_moe) line for line, except the BF16 store. tl.extra.cuda.gdc_wait() tl.extra.cuda.gdc_launch_dependents() src = tl.program_id(0).to(tl.int64) cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) lo = tl.load(Offsets) hi = tl.load(Offsets + E) total = tl.zeros([BLOCK], dtype=tl.float32) for k in tl.static_range(TOP_K): row = tl.load(Src2Dst + src * TOP_K + k) inside = (row >= lo) & (row < hi) x = tl.load(X + row.to(tl.int64) * N + cols, (cols < N) & inside, other=0) if SCALED: x = x * _nvfp4_row_scale( XAmax, WAmax, WDenominator, _row_expert(Offsets, row, E, SEARCH), row ) total += tl.where(inside, x.to(tl.bfloat16).to(tl.float32), 0.0) tl.store(Y + src * N + cols, total.to(tl.bfloat16, fp_downcast_rounding="rtne"), cols < N)
def routed_partial_bf16(x, offsets, src2dst, top_k, *, nvfp4_scales=None, block=1024): """= routed_partial(x, offsets, src2dst, top_k, nvfp4_scales=...).to(torch.bfloat16) in one kernel.""" experts = offsets.numel() - 1 out = torch.empty((src2dst.numel() // top_k, x.shape[1]), device=x.device, dtype=torch.bfloat16) if out.numel(): x_amax, w_amax, w_denominator = nvfp4_scales or (None, None, None) _routed_partial_bf16[(out.shape[0], triton.cdiv(out.shape[1], block))]( x, x_amax, w_amax, w_denominator, offsets, src2dst, out, out.shape[1], experts, top_k, nvfp4_scales is not None, block, experts.bit_length(), launch_pdl=PDL, ) return out
def forward_sm120(self, x, weights, ids, combine, mode): """Inkling2Experts._forward_sm120 with the parts in mode ('q', 'c') replaced; the rest is the image's code.""" from sglang.kernels.ops.gemm import inkling2_grouped_sm120 as grouped_sm120 from sglang.kernels.ops.moe import inkling2_experts_sm120 as experts_sm120 from sglang.kernels.ops.moe.inkling2_moe import routed_partial from sglang.srt.models.inkling_common.inkling2_moe import RoutedOutput
tokens, top_k = ids.shape src2dst, dst2src, gammas, offsets = self._sm120_route(ids, weights) x = x.contiguous() if self._routed_kernels == torch.uint8: if "q" in mode: values, scales, amax = nvfp4_token_quantize(x, src2dst, top_k, offsets) else: values, scales, amax = experts_sm120.nvfp4_routed_quantize(x=x, dst2src=dst2src, top_k=top_k, offsets=offsets) gate_up = grouped_sm120.nvfp4_expert_matmul( values=values, scales=scales, weight=self.w13_weight, weight_scales=self.w13_scale, offsets=offsets, tokens=tokens ) values, scales, amax = experts_sm120.nvfp4_routed_swiglu_quantize( acc=gate_up, acc_amax=amax, w_amax=self.w13_amax, w_denominator=self.w13_outer_scale_denominator, gammas=gammas, offsets=offsets, gate_cap=self.gate_cap, up_cap=self.up_cap, ) down = grouped_sm120.nvfp4_expert_matmul( values=values, scales=scales, weight=self.w2_weight, weight_scales=self.w2_scale, offsets=offsets, tokens=tokens ) scales = (amax, self.w2_amax, self.w2_outer_scale_denominator) else: if "q" in mode: values, scales = mxfp8_token_quantize(x, src2dst, top_k, offsets) else: values, scales = experts_sm120.mxfp8_routed_quantize(x=x, dst2src=dst2src, top_k=top_k, offsets=offsets) gate_up = grouped_sm120.mxfp8_expert_matmul( values=values, scales=scales, weight=self.w13_weight, weight_scales=self.w13_cute_scale, offsets=offsets ) values, scales = experts_sm120.mxfp8_routed_swiglu_quantize( acc=gate_up, gammas=gammas, offsets=offsets, gate_cap=self.gate_cap, up_cap=self.up_cap ) down = grouped_sm120.mxfp8_expert_matmul( values=values, scales=scales, weight=self.w2_weight, weight_scales=self.w2_cute_scale, offsets=offsets ) scales = None if "c" in mode and x.dtype == torch.bfloat16: out = routed_partial_bf16(down, offsets, src2dst, top_k, nvfp4_scales=scales) else: out = routed_partial(down, offsets, src2dst, top_k, nvfp4_scales=scales).to(x.dtype) return out if combine else RoutedOutput(out, None, 0)
def install(): global _INSTALLED if _INSTALLED: return _INSTALLED = True if not MODE: logger.warning("n14: N14_MOE empty, image MoE path") return from sglang.srt.models.inkling_common import inkling2_moe as M
orig = M.Inkling2Experts._forward_sm120
def _forward_sm120(self, x, weights, ids, combine): if ids.shape[0] < MIN_TOKENS: return orig(self, x, weights, ids, combine) return forward_sm120(self, x, weights, ids, combine, MODE)
M.Inkling2Experts._forward_sm120 = _forward_sm120 logger.warning("n14: SM120 MoE prefill parts %r on calls >= %d tokens (grid %d)", MODE, MIN_TOKENS, GRID)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237// SPDX-License-Identifier: Apache-2.0// n14 (inkling2-spark moe seat, 2026-11-21): token-major routed NVFP4 / MXFP8 quantization for the SM120 grouped GEMMs.// The image kernels (routed_quant_sm120.cuh) walk the expert-sorted rows and re-read token dst2src[row] / top_k for each// of its top_k rows (8 gathered passes over x). Every quantity they write for a row (packed values, block scales, the// per-row amax) depends only on that token's BF16 row, so these kernels read each token row once, run the same device// helpers (part_max, block_max_reduce, quantize_part / mxfp8_half_block) and store the result into each of the token's// rows src2dst[token * top_k + k] at the image's offsets (store_part / cute_exponent_offset), zeroing each expert's// scale tail where its last row is written, as the image does. Same outputs bit for bit; same PDL behaviour as the// kernel each replaces (NVFP4: wait + trigger; MXFP8: wait only, the CuTe GEMM does not wait on its predecessor).#include <sgl_kernel/tensor.h>
#include <sgl_kernel/utils.cuh>
#include "routed_quant_sm120.cuh"#include <cstdint>#include <limits>
namespace sglang::n14_quant {
using namespace sglang::inkling2_routed_quant;using sglang::inkling2_routed_quant_sm120::cute_exponent_offset;using sglang::inkling2_routed_quant_sm120::verify_offsets;using sglang::inkling2_routed_quant_sm120::verify_rows;using sglang::inkling2_routed_quant_sm120::zero_expert_tail;
template <int K>__global__ void __launch_bounds__(split_threads(K)) 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 = split_threads(K), kSplit = split(K), E = 16 / kSplit; static_assert(K % 64 == 0 && kSplit > 1); __shared__ int32_t s_offsets[kMaxExperts + 1]; __shared__ float red[2][kThreads / 32]; device::PDLWaitPrimary<true>(); device::PDLTriggerSecondary<true>(); load_offsets(offsets, experts, s_offsets); int32_t const block = threadIdx.x / kSplit, part = threadIdx.x % kSplit; bool const active = block < K / 16; int32_t const lo = s_offsets[0], hi = s_offsets[experts]; int32_t parity = 0; for (int32_t token = blockIdx.x; token < tokens; token += gridDim.x, parity ^= 1) { float v[E];#pragma unroll for (int i = 0; i < E; ++i) v[i] = 0.0f; if (active) { __nv_bfloat16 const* src = x + int64_t(token) * K + block * 16 + part * E; if constexpr (E == 8) { uint4 raw = *reinterpret_cast<uint4 const*>(src); __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(&raw);#pragma unroll for (int i = 0; i < E; ++i) v[i] = __bfloat162float(h[i]); } else { uint2 raw = *reinterpret_cast<uint2 const*>(src); __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(&raw);#pragma unroll for (int i = 0; i < E; ++i) v[i] = __bfloat162float(h[i]); } } float block_max = part_max<E>(v); float amax = block_max_reduce<kThreads>(block_max, red[parity]); uint32_t packed; uint8_t scale; quantize_part<E>(v, amax, block_max, packed, scale); for (int32_t k = 0; k < top_k; ++k) { int32_t const row = src2dst[int64_t(token) * top_k + k]; if (row < lo || row >= hi) continue; int32_t const expert = row_expert(s_offsets, experts, row); if (active) { if (threadIdx.x == 0) amax_out[row] = amax; store_part<E>(values, x_scales, s_offsets, expert, row, block, part, K, packed, scale); } if (row == s_offsets[expert + 1] - 1) zero_expert_tail(s_offsets, expert, x_scales, (K + 63) / 64 * 4); } }}
template <int K>__global__ void __launch_bounds__(threads(K)) mxfp8_quantize_tokens_kernel( __nv_bfloat16 const* __restrict__ x, int32_t const* __restrict__ src2dst, uint8_t* values, uint8_t* exponents, int32_t const* __restrict__ offsets, int32_t tokens, int32_t experts, int32_t top_k, int32_t m_padded) { static_assert(K % 128 == 0 && K / 16 <= 1024); __shared__ int32_t s_offsets[kMaxExperts + 1]; device::PDLWaitPrimary<true>(); load_offsets(offsets, experts, s_offsets); int32_t const block = threadIdx.x; bool const active = block < K / 16; int32_t const lo = s_offsets[0], hi = s_offsets[experts]; for (int32_t token = blockIdx.x; token < tokens; token += gridDim.x) { float v[16]; if (active) { uint4 const* src = reinterpret_cast<uint4 const*>(x + int64_t(token) * K + block * 16); uint4 raw[2] = {src[0], src[1]}; __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(raw);#pragma unroll for (int i = 0; i < 16; ++i) v[i] = __bfloat162float(h[i]); } 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) { for (int32_t k = 0; k < top_k; ++k) { int32_t const row = src2dst[int64_t(token) * top_k + k]; if (row < lo || row >= hi) continue; *reinterpret_cast<uint4*>(values + int64_t(row) * K + block * 16) = packed; if (block % 2 == 0) exponents[cute_exponent_offset(row, block / 2, s_offsets, experts, m_padded)] = exponent; } } }}
inline int32_t grid_for(int32_t tokens, int64_t sm_count, int64_t grid) { int64_t const g = grid > 0 ? grid : 4 * sm_count; return static_cast<int32_t>(std::max<int64_t>(1, std::min<int64_t>(tokens, g)));}
template <int K>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 / split(K); auto tokens = host::SymbolicSize{"tokens"}; auto rows = host::SymbolicSize{"routed rows"}; auto scale_rows = host::SymbolicSize{"scale rows"}; auto device = host::SymbolicDevice{}; device.set_options<kDLCUDA>(); int32_t const experts = verify_offsets(offsets, device); host::TensorMatcher({tokens, K}) // .with_dtype<bf16_t>() .with_device(device) .ensure_alignment(kPart * 2) .verify(x); host::TensorMatcher({rows}).with_dtype<int32_t>().with_device(device).verify(src2dst); host::TensorMatcher({rows, K / 2}) // .with_dtype<uint8_t>() .with_device(device) .ensure_alignment(kPart / 2) .verify(values); host::TensorMatcher({scale_rows, K / 16}).with_dtype<uint8_t>().with_device(device).verify(x_scales); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(amax); CHECK_HOST(top_k > 0) << "top_k must be positive, 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), split_threads(K), device.unwrap()) .enable_pdl(true)( nvfp4_quantize_tokens_kernel<K>, static_cast<__nv_bfloat16 const*>(x.data_ptr()), static_cast<int32_t const*>(src2dst.data_ptr()), static_cast<uint8_t*>(values.data_ptr()), static_cast<uint8_t*>(x_scales.data_ptr()), static_cast<float*>(amax.data_ptr()), static_cast<int32_t const*>(offsets.data_ptr()), num_tokens, static_cast<int32_t>(top_k), experts);}
template <int K>void mxfp8_quantize_tokens( tvm::ffi::TensorView x, tvm::ffi::TensorView src2dst, tvm::ffi::TensorView values, tvm::ffi::TensorView exponents, tvm::ffi::TensorView offsets, int64_t top_k, int64_t m_padded, int64_t sm_count, int64_t grid) { auto tokens = host::SymbolicSize{"tokens"}; auto rows = host::SymbolicSize{"routed rows"}; auto device = host::SymbolicDevice{}; device.set_options<kDLCUDA>(); int32_t const experts = verify_offsets(offsets, device); host::TensorMatcher({tokens, K}) // .with_dtype<bf16_t>() .with_device(device) .ensure_alignment(16) .verify(x); host::TensorMatcher({rows}).with_dtype<int32_t>().with_device(device).verify(src2dst); host::TensorMatcher({rows, K}) // .with_dtype<uint8_t>() .with_device(device) .ensure_alignment(16) .verify(values); host::TensorMatcher({K / 128, m_padded}).with_dtype<int32_t>().with_device(device).verify(exponents); CHECK_HOST(top_k > 0) << "top_k must be positive, 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(m_padded >= (num_rows + 3 * int64_t{experts}) / 4 * 4 && m_padded < std::numeric_limits<int32_t>::max()) << "MXFP8 scales need 4-row aligned experts, got m_padded " << m_padded; host::LaunchKernel(grid_for(num_tokens, sm_count, grid), threads(K), device.unwrap()) .enable_pdl(true)( mxfp8_quantize_tokens_kernel<K>, static_cast<__nv_bfloat16 const*>(x.data_ptr()), static_cast<int32_t const*>(src2dst.data_ptr()), static_cast<uint8_t*>(values.data_ptr()), static_cast<uint8_t*>(exponents.data_ptr()), static_cast<int32_t const*>(offsets.data_ptr()), num_tokens, experts, static_cast<int32_t>(top_k), static_cast<int32_t>(m_padded));}
} // namespace sglang::n14_quant123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""n15 fused loop controller (stack seat, 2026-11-22): one Triton kernel for message_controllers' norm + down + mix(sglang kernels/ops/elementwise/inkling2_loop.py), meant to be BITWISE equal to the served three kernels by copying eachorder: - row RMS: per row a 1-D tensor<BLOCK = next_pow2(W)> load + tl.sum under num_warps 8, as _controller_norm (served ttgir: #blocked sizePerThread [8], warpsPerCTA [8]); rsqrt(div_rn(sum, W) + eps) with libdevice; - normed = (x * rstd).to(bf16), concatenated [dest | message] along K = 2W, never written to memory; - down: K walked in 1024-wide groups of BLOCK_K tiles, each group's tl.dot accumulation from zero, groups summed in group order (served non-split path; the split path sums the same partials in the same order); tiles past K masked to zero exactly as the served loads; - mix: hidden.to(bf16) @ gain / forget tiles (K = rank 64 from zero), out = (1 - tanh(f)) * dest + tanh(g) * message, libdevice tanh, enable_fp_fusion False.Grid (NUM, row blocks): the controllers of one row block are adjacent programs, so a stride-0 dest (local layers) isread from DRAM once and from L2 by the other two. Passes 2 and 3 re-read the row block's dest / message from L2."""import os
import tritonimport triton.language as tlfrom triton.language.extra import libdevice
@triton.jitdef _served_sumsq(ptr, ok, W: tl.constexpr): """sum(x * x) over one row of W fp32 in the served _controller_norm order, read from its PTX (image cache 63HJTHLD..., Triton 3.8): thread t = warp * 32 + lane holds x[2048 h + 8 t + 4 g + 2 f + b] (h, g, f, b in {0, 1}); its 16 squares are added as a packed f32x2 tree: over f, then g, then h, then the two lanes (b); then the lane butterfly (xor 16, 8, 4, 2, 1) and, via shared memory, the warp tree (xor 4, 2, 1). Each step below is one add over a size-2 axis, so the order does not depend on the layout this kernel gets.""" t = tl.arange(0, 256) i = tl.arange(0, 16) off = (i[None, :] // 8) * 2048 + t[:, None] * 8 + (i[None, :] % 8) v = tl.load(ptr + off, ok & (off < W), other=0) q = tl.reshape(v * v, (256, 2, 2, 2, 2)) q = tl.sum(q, axis=3) q = tl.sum(q, axis=2) q = tl.sum(q, axis=1) a = tl.sum(q, axis=1) a = tl.sum(tl.reshape(a, (8, 2, 16)), axis=1) a = tl.sum(tl.reshape(a, (8, 2, 8)), axis=1) a = tl.sum(tl.reshape(a, (8, 2, 4)), axis=1) a = tl.sum(tl.reshape(a, (8, 2, 2)), axis=1) a = tl.sum(tl.reshape(a, (8, 2, 1)), axis=1) a = tl.reshape(a, (8,)) a = tl.sum(tl.reshape(a, (2, 4)), axis=0) a = tl.sum(tl.reshape(a, (2, 2)), axis=0) return tl.sum(a, axis=0)
@triton.jitdef _fused_controller( Dest, Message, Down, Gain, Forget, Out, T, DEST_STRIDE, MESSAGE_STRIDE, eps, W: tl.constexpr, BLOCK: tl.constexpr, R: tl.constexpr, BLOCK_R: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_N: tl.constexpr, INTERP: tl.constexpr = False, SERVED_ORDER: tl.constexpr = True, NUM_STAGES: tl.constexpr = 3,): m = tl.program_id(0).to(tl.int64) row0 = tl.program_id(1) * BLOCK_M K: tl.constexpr = 2 * W GROUPS: tl.constexpr = (K + 1023) // 1024 cols = tl.arange(0, BLOCK) valid = cols < W ridx = tl.arange(0, BLOCK_M) rstd_d = tl.zeros((BLOCK_M,), tl.float32) rstd_m = tl.zeros((BLOCK_M,), tl.float32) # pass 1: row statistics, one 1-D row at a time (the served reduction shape) for r in tl.static_range(BLOCK_M): t = (row0 + r).to(tl.int64) ok = valid & (t < T) if SERVED_ORDER: # the served reduction order, layout-independent sd = _served_sumsq(Dest + m * DEST_STRIDE + t * W, t < T, W) sm = _served_sumsq(Message + m * MESSAGE_STRIDE + t * W, t < T, W) else: # failing control: this kernel's own tl.sum layout (sizePerThread 4 here vs the served 8) dest = tl.load(Dest + m * DEST_STRIDE + t * W + cols, ok, other=0) message = tl.load(Message + m * MESSAGE_STRIDE + t * W + cols, ok, other=0) sd = tl.sum(dest * dest) sm = tl.sum(message * message) if INTERP: # CPU interpreter only (no div_rn / libdevice there); GPU builds take the served ops dr = tl.rsqrt(sd / W + eps) mr = tl.rsqrt(sm / W + eps) else: dr = libdevice.rsqrt(tl.div_rn(sd, W) + eps) mr = libdevice.rsqrt(tl.div_rn(sm, W) + eps) rstd_d = tl.where(ridx == r, dr, rstd_d) rstd_m = tl.where(ridx == r, mr, rstd_m) rows = row0 + ridx row_ok = rows[:, None] < T rank = tl.arange(0, BLOCK_R) ks = tl.arange(0, BLOCK_K) Wd = Down + m * R * K # pass 2: down projection of the normalized [dest | message] rows total = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) for group in tl.static_range(GROUPS): partial = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) for tile in tl.range(0, 1024 // BLOCK_K, num_stages=NUM_STAGES): k = group * 1024 + tile * BLOCK_K + ks in_d = k[None, :] < W # branch-free (pipelinable): both tiles issue under complementary masks, one is fully masked per tile x = tl.load(Dest + m * DEST_STRIDE + rows[:, None].to(tl.int64) * W + k[None, :], row_ok & in_d, other=0) y = tl.load(Message + m * MESSAGE_STRIDE + rows[:, None].to(tl.int64) * W + (k[None, :] - W), row_ok & (k[None, :] >= W) & (k[None, :] < K), other=0) xn = tl.where(in_d, x * rstd_d[:, None], y * rstd_m[:, None]) if not INTERP: xn = xn.to(tl.bfloat16) w = tl.load(Wd + rank[None, :] * K + k[:, None], (rank[None, :] < R) & (k[:, None] < K), other=0) partial = tl.dot(xn, w, partial) if group == 0: total = partial else: total = total + partial hidden = total if not INTERP: # the CPU interpreter's bf16 dot is broken: its check runs fp32 operands hidden = total.to(tl.bfloat16) # pass 3: gain / forget and the tanh mix for start in tl.range(0, W, BLOCK_N, num_stages=NUM_STAGES): cn = start + tl.arange(0, BLOCK_N) col_ok = cn[None, :] < W weight_ok = col_ok & (rank[:, None] < R) weights = m * W * R + cn[None, :] * R + rank[:, None] offsets = rows[:, None].to(tl.int64) * W + cn[None, :] mask = row_ok & col_ok dest_t = tl.load(Dest + m * DEST_STRIDE + offsets, mask, other=0) message_t = tl.load(Message + m * MESSAGE_STRIDE + offsets, mask, other=0) gain = tl.dot(hidden, tl.load(Gain + weights, weight_ok, other=0)) forget = tl.dot(hidden, tl.load(Forget + weights, weight_ok, other=0)) if INTERP: tf = 1.0 - 2.0 / (tl.exp(2.0 * forget) + 1.0) tg = 1.0 - 2.0 / (tl.exp(2.0 * gain) + 1.0) else: tf = libdevice.tanh(forget) tg = libdevice.tanh(gain) output = (1.0 - tf) * dest_t + tg * message_t tl.store(Out + m * T * W + offsets, output, mask)
def fused_message_controllers(dest, dest_stride, message, message_stride, down, gain, forget, out, eps=1e-6, block_m=16, block_k=128, block_n=64, num_warps=8, fp_fusion=False, num_stages=2, served_order=True, loop_stages=3): """dest / message: base tensors with element strides between controllers (0 = one shared stream), as inkling2_loop._stacked returns them; out: (num, tokens, width) fp32.""" num, rank, k = down.shape tokens, width = out.shape[1], out.shape[2] grid = (num, triton.cdiv(tokens, block_m)) _fused_controller[grid]( dest, message, down, gain, forget, out, tokens, dest_stride, message_stride, eps, width, triton.next_power_of_2(width), rank, max(16, triton.next_power_of_2(rank)), block_m, block_k, block_n, os.environ.get("TRITON_INTERPRET") == "1", served_order, loop_stages, num_warps=num_warps, num_stages=num_stages, enable_fp_fusion=fp_fusion, ) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226"""n32 (inkling2-spark attn-bias seat): sliding-layer prefill rel bias computed inside the FA4 SM120 kernel, bitwise equalto the served einsum + ShearingBias + FA4 path (FlashAttentionForwardSm120RelProd, fa4_sm120/n32_fwd.py, mounted).Model side (patched inkling2_attn.py): on a sliding layer in EXTEND mode the rel bias is handed on as N32RelBias(r, module)instead of module(r) [T, H, 1024]. Here: interface._flash_attn_fwd is wrapped; an N32RelBias that reaches it on the callthis kernel covers (SM12x, paged KV page 128, varlen, window (E - 1, 0), causal, pack_gqa False, 1 split, noscore/mask mods, sinks, descales or softcap) runs the stock call with a zero-stride presheared-shape stand-in for thebias and aux_tensors = [r as int32 pairs, proj^T as int32 pairs]; make_kernel then builds the n32 class (has_bias,is_local, has_aux_tensors, no score/mask mod). Any other call gets module(r), the served bias, exactly as served.Switch: SGLANG_INKLING_N32=0 keeps the served path (same mounted files). Imported once from the patched inkling2_attn.py."""import loggingimport os
import torch
_INSTALLED = FalseENABLED = os.environ.get("SGLANG_INKLING_N32", "1") == "1"# global layers too (n13's band-split kernel fed by the n32 producer); needs a kernel file generated with N32_GLOBAL = 1GLOBAL = os.environ.get("SGLANG_INKLING_N32_GLOBAL", "0") == "1"logger = logging.getLogger(__name__)_P32 = {}_BASE = {}STATS = {"inline": 0, "materialized": 0, "built": 0}
class N32RelBias: """Stands in for the sliding-layer rel bias [T, H, E] = module(r): r [T, H, 16] (clipped, as served) + the RelLogitsProj module (proj [16, E])."""
__slots__ = ("r", "mod")
def __init__(self, r, mod): self.r = r self.mod = mod
@property def shape(self): return (self.r.shape[0], self.r.shape[1], self.mod.proj.shape[1])
def dim(self): # n218 k1: tensor-like rank, asked by knapcio's inkling_attn pass-through test (see gen_hook_k1.py) return 3
def data_ptr(self): # n218 k1: never the storage of a marker tensor (their _same_storage_rows compares pointers) return -1
@property def dtype(self): return self.r.dtype
@property def device(self): return self.r.device
@property def requires_grad(self): return False
def __getitem__(self, key): if isinstance(key, tuple): if len(key) != 1: raise TypeError("N32RelBias supports row (dim 0) indexing only") key = key[0] r = self.r[key] if r.dim() != 3: raise TypeError("N32RelBias row index must keep the token dim") return N32RelBias(r, self.mod)
def materialize(self): return self.mod(self.r)
def wants(attn, r, mode_name, padded, mxfp8): """Model-side guard (Inkling2Attention._forward, extend branch).""" return ( ENABLED and (attn.is_local or GLOBAL) and not padded and not mxfp8 and mode_name == "EXTEND" and r.dim() == 3 and r.dtype == torch.bfloat16 and r.shape[-1] == 16 and r.stride(-1) == 1 and tuple(attn.rel_logits_proj.proj.shape) == (16, 1024) and attn.rel_logits_proj.proj.dtype == torch.bfloat16 )
def _p32(proj): """proj^T as int32 pairs [E, 8], cached per layer. Never built inside a CUDA-graph capture (the transpose kernel would only be recorded, not run): returns None there and the caller serves the materialized bias instead.""" key = (id(proj), str(proj.device)) # proj is a module Parameter: one object per layer for the process v = _P32.get(key) if v is None: if torch.cuda.is_current_stream_capturing(): return None v = proj.t().contiguous().view(torch.int32) # [E, 16] BF16 -> [E, 8] int32 pairs (k = 2t, 2t + 1) v.__assumed_align__ = 16 v.__leading_dim__ = 1 _P32[key] = v return v
def _r32(r): v = r.view(torch.int32) # [T, H, 16] BF16 -> [T, H, 8] int32 pairs v.__assumed_align__ = 4 v.__leading_dim__ = 2 return v
_NONE_KW = ("qv", "score_mod", "mask_mod", "aux_tensors", "aux_scalars", "learnable_sink", "q_descale", "k_descale", "v_descale", "sfq", "sfk", "sfv", "block_sparse_tensors", "gather_kv_indices", "seqused_q", "cu_seqlens_k", "qk_sf_vec_size", "v_sf_vec_size")
def eligible(q, k, v, kw, rb): r = rb.r e = rb.mod.proj.shape[1] return ( not kw.get("rel_bias_presheared") and q is not None and q.dtype == torch.bfloat16 and q.dim() == 3 and q.shape[0] == r.shape[0] and q.shape[1] == r.shape[1] and q.shape[2] == 128 and k is not None and k.dim() == 4 and k.shape[1] == 128 and kw.get("cu_seqlens_q") is not None and kw.get("page_table") is not None and kw.get("seqused_k") is not None and ( (kw.get("window_size_left") == e - 1 and kw.get("window_size_right") == 0) # sliding layer or (GLOBAL and kw.get("window_size_left") in (None, -1) and kw.get("window_size_right") in (None, -1)) # global ) and kw.get("causal") is True and kw.get("pack_gqa") is False and kw.get("num_splits") == 1 and not kw.get("softcap") and all(kw.get(x) is None for x in _NONE_KW) and r.stride(-1) == 1 and r.stride(-2) % 2 == 0 and r.stride(0) % 2 == 0 and r.storage_offset() % 2 == 0 and q.is_cuda and _sm12(q.device) )
_CAP = {}
def _sm12(dev): v = _CAP.get(str(dev)) if v is None: v = _CAP[str(dev)] = torch.cuda.get_device_capability(dev)[0] == 12 return v
def install(): global _INSTALLED if _INSTALLED: return from sglang.kernels.ops.attention.fa4_sm120 import runtime as _rt from sglang.kernels.ops.attention.fa4_sm120.flash_fwd import FlashAttentionForwardSm120 from sglang.kernels.ops.attention.fa4_sm120 import n32_fwd as _n32 from sglang.kernels.ops.attention.fa4_sm120.n32_fwd import FlashAttentionForwardSm120RelProd
band_cls = getattr(_n32, "FlashAttentionForwardSm120BandSplitRelProd", None) assert band_cls is not None or not GLOBAL, "SGLANG_INKLING_N32_GLOBAL=1 needs n32_fwd.py generated with N32_GLOBAL = 1" from sglang.kernels.ops.attention.flash_attn.cute import interface as _itf
orig_mk = _rt.Sm120ForwardPolicy.make_kernel
def make_kernel(**kw): k = orig_mk(**kw) ok = (kw.get("has_bias") and kw.get("has_aux_tensors") and kw.get("score_mod") is None and kw.get("mask_mod") is None and not kw.get("pack_gqa") and kw.get("paged_kv") and not k._uses_split_pv_warps()) if ok and kw.get("is_local") and type(k) is FlashAttentionForwardSm120: k.__class__ = FlashAttentionForwardSm120RelProd STATS["built"] += 1 logger.warning("n32: FA4 SM120 in-kernel sliding rel-bias kernel built (tile %s x %s, bias rows %s, build %d)", k.tile_m, k.tile_n, k.bias_block_size, STATS["built"]) elif ok and GLOBAL and not kw.get("is_local") and band_cls is not None and type(k).__name__ == "FlashAttentionForwardSm120BandSplit": k.__class__ = band_cls STATS["built"] += 1 logger.warning("n32: FA4 SM120 global band-split kernel with in-kernel rel bias built (tile %s x %s, bias rows %s, build %d)", k.tile_m, k.tile_n, k.bias_block_size, STATS["built"]) return k
_rt.Sm120ForwardPolicy.make_kernel = staticmethod(make_kernel) orig_fwd = _itf._flash_attn_fwd
def _flash_attn_fwd(q, k, v, *args, **kw): rb = kw.get("rel_bias") if isinstance(rb, N32RelBias): p32 = _p32(rb.mod.proj) if not args and eligible(q, k, v, kw, rb) else None if p32 is not None: tpad = -(-q.shape[0] // 64) * 64 e_pad = rb.mod.proj.shape[1] + 256 dkey = (str(q.device), e_pad) base = _BASE.get(dkey) if base is None: # contents never read (the n32 kernel ignores the bias argument): empty is enough base = _BASE[dkey] = torch.empty(e_pad, dtype=torch.bfloat16, device=q.device) kw = dict(kw) kw["rel_bias"] = base.as_strided((tpad, q.shape[1], e_pad), (0, 0, 1)) kw["rel_bias_presheared"] = True kw["rel_bias_prep_cache"] = None kw["aux_tensors"] = [_r32(rb.r), p32] STATS["inline"] += 1 if STATS["inline"] <= 2: logger.warning("n32: in-kernel sliding rel bias, call %d tokens %d", STATS["inline"], q.shape[0]) return orig_fwd(q, k, v, *args, **kw) kw = dict(kw) kw["rel_bias"] = rb.materialize() STATS["materialized"] += 1 if STATS["materialized"] <= 4: logger.warning("n32: sliding rel bias materialized as served (ineligible call %d, tokens %d)", STATS["materialized"], q.shape[0] if q is not None else -1) return orig_fwd(q, k, v, *args, **kw)
# the stock function keeps its compile caches as attributes on itself and reads them through its module global _flash_attn_fwd.__dict__ = orig_fwd.__dict__ _itf._flash_attn_fwd = _flash_attn_fwd _INSTALLED = True logger.warning("n32: in-kernel rel-bias hook installed (enabled=%s, global=%s)", ENABLED, GLOBAL)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567# Generated by work_attnbias/gen/gen_n32.py from the image's sglang/kernels/ops/attention/fa4_sm120/flash_fwd.py (md5 f7161e38)."""n126 S4c a4 gate fix (stack seat, 2026-11-24; from n115 a4 7e0b8ca9): a4's consumer-built bias (compute_one_n_block override,the producer's bias-fill gate and the kernel-entry n115 setup) now applies to the SLIDING class only (n32_plain_bias False). Everyclass with n32_plain_bias True (n32's global FlashAttentionForwardSm120BandSplitRelProd and S3's n64a BandOnly, its subclass) tracesS3's 115d2333 code: the compute_one_n_block S3's MRO resolves (BandSplit / base), the ungated bias fill, no n115 setup. Why: S4'scheck boot hung at the first global call (n64a inherited a4's consumer while its own producer filled the bias ring).n115 V-a' (verifyship seat, gen_n115.py, from the served n32_fwd.py 115d2333): consumer warps build their own bias rows.n32 (inkling2-spark attn-bias seat): FlashAttentionForwardSm120RelProd, the image's SM120 FA4 forward kernel for thesliding-layer relative-bias prefill call with the bias producer moved in-kernel (see gen_n32.py). Outputs are meant to bebitwise equal to the served einsum + ShearingBias + FA4 path (checked on the GPU)."""from sglang.kernels.ops.attention.fa4_sm120 import flash_fwd as _base
globals().update({k: v for k, v in vars(_base).items() if not k.startswith("__")})from cutlass import BFloat16, Float32, Int32 # noqa: E402from cutlass._mlir.dialects import llvm # noqa: E402from cutlass.cutlass_dsl import dsl_user_op # noqa: E402
from sglang.kernels.ops.attention.fa4_sm120.flash_fwd import FlashAttentionForwardSm120 # noqa: E402
N32_CONTROL = 0 # 1 = deliberately wrong rounding (truncate to BF16): a failing control for the bitwise checks; never shipN32_PRODUCER = 2 # 1 = per-element generic producer, 2 = hoisted producer (same values)N115_CONTROL = 0 # 1 = truncate the bias to BF16 (round toward zero): the failing control; never shipN115_DMA = 0 # 1 = the DMA warp still fills the bias stages (served n32); 0 = V-a' (consumer warps build their own rows)N115_STRIDE2 = 88 # a2: BF16 elements per half-slab row (80 used incl. the odd-row shift)N115_STRIDE = 152 # BF16 elements per slab row (>= 16 + 128 - 1 + 1 odd-row shift; 76 words: 8 rows on 8 distinct banks)N115_VARIANT = 'a4'N32_GLOBAL = 1 # 1 = also define the global-layer class (imports n13_fwd.py, which n21-based recipes mount)
@dsl_user_opdef n32_mma_bf16_k16(a0, a1, a2, a3, b0, b1, *, loc=None, ip=None): """One mma.sync m16n8k16 (row.col, BF16 x BF16 -> fp32) with a zero accumulator; returns (d0, d1, d2, d3).""" f32 = Float32.mlir_type z = Float32(0.0).ir_value(loc=loc, ip=ip) out = llvm.inline_asm( llvm.StructType.get_literal([f32] * 4), [Int32(x).ir_value(loc=loc, ip=ip) for x in (a0, a1, a2, a3, b0, b1)] + [z, z, z, z], "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 " "{$0, $1, $2, $3}, {$4, $5, $6, $7}, {$8, $9}, {$10, $11, $12, $13};", "=f,=f,=f,=f,r,r,r,r,r,r,f,f,f,f", has_side_effects=False, is_align_stack=False, asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip, ) return [Float32(llvm.extractvalue(f32, out, [i], loc=loc, ip=ip)) for i in range(4)]
@dsl_user_opdef n32_trunc_bf16_f32(x, *, loc=None, ip=None): """Control only: x with its low 16 bits cleared (round toward zero to BF16), as fp32.""" return Float32( llvm.inline_asm( Float32.mlir_type, [Float32(x).ir_value(loc=loc, ip=ip)], "{ .reg .b32 t; mov.b32 t, $1; and.b32 t, t, 0xffff0000; mov.b32 $0, t; }", "=f,f", has_side_effects=False, is_align_stack=False, asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip, ) )
@dsl_user_opdef n115_pack_bf16x2(lo, hi, *, loc=None, ip=None): """{hi, lo} as one 32-bit word: cvt.rn.bf16x2.f32 (round to nearest even per element, as cvt.rn.bf16.f32); lo -> bits 0-15.""" return Int32( llvm.inline_asm( Int32.mlir_type, [Float32(hi).ir_value(loc=loc, ip=ip), Float32(lo).ir_value(loc=loc, ip=ip)], "cvt.rn.bf16x2.f32 $0, $1, $2;", "=r,f,f", has_side_effects=False, is_align_stack=False, asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip, ) )
class FlashAttentionForwardSm120RelProd(FlashAttentionForwardSm120): """SM120 FA4 forward, sliding-layer rel bias produced in-kernel by the DMA warp (n32)."""
n32_extent = 1024 # rel_extent (rel_extent_padded - 256) n32_plain_bias = False # stock swizzled bias tile (sliding); True for n13's unswizzled tile (global band-split) n32_chunks = 18 # 8-distance chunks per 16-row group: rows 16 + keys 128 - 1 = 143 distances
@cute.jit def n32_tile_setup( self, mR32: cute.Tensor, block_info: BlockInfo, seqlen: SeqlenInfoQK, m_block: Int32, head_idx: Int32, tidx: Int32, ): """A fragments (m16n8k16 row layout) of r for this lane: index 4 * grp + hh + 2 * kk = rows 16 grp + 8 hh + g, k pair 2 t + 8 kk; zero for rows past the sequence. Bounds: visible keys of row 16 grp + 8 hh + g are [lo, hi] = [max(n_idx_left, n_idx_right - E), n_idx_right - 1] (the shear's num_bias_vals band); -inf outside.""" lane = tidx % cute.arch.WARP_SIZE g = lane // 4 t = lane % 4 ra = cute.make_rmem_tensor((16,), Int32) lo = cute.make_rmem_tensor((8,), Int32) hi = cute.make_rmem_tensor((8,), Int32) for s in cutlass.range_constexpr(8): grp = s // 2 hh = s % 2 m_idx = m_block * self.tile_m + 16 * grp + 8 * hh + g n_idx_left, n_idx_right = block_info.get_n_idx_left_right(seqlen, m_idx) lo[s] = cutlass.max(n_idx_left, n_idx_right - self.n32_extent) hi[s] = n_idx_right - 1 row = seqlen.offset_q + m_idx for kk in cutlass.range_constexpr(2): v = Int32(0) if m_idx < seqlen.seqlen_q: v = mR32[row, head_idx, t + 4 * kk] ra[4 * grp + hh + 2 * kk] = v return ra, lo, hi
@cute.jit def n32_bias_tile( self, sB: cute.Tensor, mP32: cute.Tensor, ra: cute.Tensor, lo: cute.Tensor, hi: cute.Tensor, pmax: Int32, n_block: Int32, seqlen: SeqlenInfoQK, m_block: Int32, tidx: Int32, ): if const_expr(N32_PRODUCER == 2): self.n32_bias_tile_v2(sB, mP32, ra, hi, pmax, n_block, tidx) else: assert self.is_local and not self.n32_plain_bias, "v1 producer: sliding layers only" self.n32_bias_tile_v1(sB, mP32, ra, lo, hi, n_block, tidx)
@cute.jit def n32_bias_tile_v1( self, sB: cute.Tensor, mP32: cute.Tensor, ra: cute.Tensor, lo: cute.Tensor, hi: cute.Tensor, n_block: Int32, tidx: Int32, ): """Sheared bias tile of key block n_block into sB (bias_block_size, tile_n): sB[i, c] = BF16_RTNE(r_i . proj[:, p]) with p = hi_i - k, k = n_block * tile_n + c, if lo_i <= k <= hi_i, else -inf. T[i, j] = r_i . proj[:, D0 + j] with D0 = hi_i - i - k0 - (tile_n - 1) (row independent), and sB[i, c] = T[i, i + tile_n - 1 - c].""" lane = tidx % cute.arch.WARP_SIZE g = lane // 4 t = lane % 4 k0 = n_block * self.tile_n # hi_i - i is the same for every row: take it from this lane's first row (row g) d0 = hi[0] - g - k0 - (self.tile_n - 1) num_groups = (self.bias_block_size + 15) // 16 for grp in cutlass.range_constexpr(num_groups): for ch in cutlass.range(self.n32_chunks, unroll=1): j0 = 16 * grp + 8 * ch d = d0 + j0 + g b0 = Int32(0) b1 = Int32(0) if d >= 0 and d < self.n32_extent: b0 = mP32[d, t] b1 = mP32[d, t + 4] acc = n32_mma_bf16_k16( ra[4 * grp + 0], ra[4 * grp + 1], ra[4 * grp + 2], ra[4 * grp + 3], b0, b1 ) for hh in cutlass.range_constexpr(2): if const_expr(16 * grp + 8 * hh < self.bias_block_size): i = 16 * grp + 8 * hh + g for e in cutlass.range_constexpr(2): j = j0 + 2 * t + e c = i + (self.tile_n - 1) - j if c >= 0 and c < self.tile_n: k = k0 + c x = Float32(-Float32.inf) if k >= lo[2 * grp + hh] and k <= hi[2 * grp + hh]: x = acc[2 * hh + e] if const_expr(N32_CONTROL == 1): x = n32_trunc_bf16_f32(x) sB[i, c] = x.to(BFloat16)
@cute.jit def n32_bias_tile_v2( self, sB: cute.Tensor, mP32: cute.Tensor, ra: cute.Tensor, hi: cute.Tensor, pmax: Int32, n_block: Int32, tidx: Int32, ): """Same tile as v1 (sliding; with n32_plain_bias and causal pads for the global band-split class). Output (i, j) of chunk (grp, ch) has j = 16 grp + 8 ch + 2 t + e, proj index p = d0 + j and column c = i + tile_n - 1 - j = cb - 8 ch + 8 hh - e (cb = tile_n - 1 + g - 2 t: no grp term). Valid iff 0 <= p <= pmax (pmax = min(wl + wr, E - 1); k >= 0 always holds), the shear's band. 24 distance chunks u = 2 grp + ch carry the B fragments (d = d0 + 8 u + g). Element offset in the stage (atom 8 x 64, swizzle 3/4/3 on bytes) for this lane's rows (i & 7 == g): 512 (i >> 3) + 64 g + bbs (c & 64) + ((c & 63) ^ 8 g).""" lane = tidx % cute.arch.WARP_SIZE g = lane // 4 t = lane % 4 bbs = self.bias_block_size num_groups = (bbs + 15) // 16 nu = 2 * (num_groups - 1) + self.n32_chunks k0 = n_block * self.tile_n d0 = hi[0] - g - k0 - (self.tile_n - 1) raw = cute.make_tensor(cute.recast_ptr(sB.iterator, None), cute.make_layout(bbs * self.tile_n)) P = cute.make_tensor(mP32.iterator, cute.make_layout((self.n32_extent, 8), stride=(8, 1))) bf = cute.make_rmem_tensor((2 * nu,), Int32) for u in cutlass.range_constexpr(nu): d = cutlass.min(cutlass.max(d0 + 8 * u + g, 0), self.n32_extent - 1) bf[2 * u] = P[d, t] bf[2 * u + 1] = P[d, t + 4] if d0 >= 0 and d0 + 8 * nu - 1 <= pmax: self.n32_emit(raw, ra, bf, g, t, d0, pmax, False) else: self.n32_emit(raw, ra, bf, g, t, d0, pmax, True)
@cute.jit def n32_emit( self, raw: cute.Tensor, ra: cute.Tensor, bf: cute.Tensor, g: Int32, t: Int32, d0: Int32, pmax: Int32, check: cutlass.Constexpr[bool], ): bbs = self.bias_block_size num_groups = (bbs + 15) // 16 g8 = 8 * g rowbase = (self.tile_n if const_expr(self.n32_plain_bias) else 64) * g # shear pads: right (p < 0) -inf; left (p > pmax) -inf with a left window (sliding), 0.0 without (global, causal) left_pad = Float32(-Float32.inf) if const_expr(self.is_local) else Float32(0.0) cb = (self.tile_n - 1) + g - 2 * t pl = d0 + 2 * t for ch in cutlass.range_constexpr(self.n32_chunks): acc = [] for grp in cutlass.range_constexpr(num_groups): u = 2 * grp + ch acc.append( n32_mma_bf16_k16( ra[4 * grp + 0], ra[4 * grp + 1], ra[4 * grp + 2], ra[4 * grp + 3], bf[2 * u], bf[2 * u + 1], ) ) for hh in cutlass.range_constexpr(2): for e in cutlass.range_constexpr(2): c = cb + (8 * hh - 8 * ch - e) if const_expr(self.n32_plain_bias): col = rowbase + c # n13's unswizzled row-major tile: offset 128 i + c else: col = rowbase + ((c ^ g8) & 63) + (c & 64) * bbs edge = const_expr(ch < 2 or ch > self.n32_chunks - 3) in_tile = True if const_expr(edge): in_tile = c >= 0 and c < self.tile_n for grp in cutlass.range_constexpr(num_groups): if const_expr(16 * grp + 8 * hh < bbs): x = acc[grp][2 * hh + e] if const_expr(N32_CONTROL == 1): x = n32_trunc_bf16_f32(x) if const_expr(check): p = pl + (16 * grp + 8 * ch + e) if p < 0: x = Float32(-Float32.inf) if p > pmax: x = left_pad roff = (self.tile_n * 8 if const_expr(self.n32_plain_bias) else 512) * (2 * grp + hh) if const_expr(edge): if in_tile: raw[col + roff] = x.to(BFloat16) else: raw[col + roff] = x.to(BFloat16)
# ---- copied from the image file and patched (gen_n32.py) ---- # ---- n115 V-a' (gen_n115.py) ---- @cute.jit def n115_bias( self, acc_S: cute.Tensor, thr_mma_qk: cute.TiledMma, sBias: cute.Tensor, base_softmax_scale: Float32, apply_bias: bool, n_block: Int32, m_block: Int32, head_idx: Int32, seqlen: SeqlenInfoQK, ): """n115 V-a' (a4): this warp's 16 rows of the sheared bias, built here per 64-key half with n32 v2's values, merged as served.""" cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS = thr_mma_qk.partition_C(cS) if apply_bias: bbs = self.bias_block_size S2 = N115_STRIDE2 HALF = self.tile_n // 2 nch = (HALF + 16) // 8 nst = cute.size(sBias.shape[2]) assert ((bbs + 15) // 16) * 16 * S2 <= bbs * self.tile_n * nst, f"n115 a2 slab does not fit: bbs {bbs} nst {nst}" assert cute.size(acc_S.shape) == 64 and str(acc_S.shape).replace(" ", "") == "((2,2),1,16)", f"n115 a2: acc_S shape {acc_S.shape}" raw = cute.make_tensor(cute.recast_ptr(sBias.iterator, None), cute.make_layout(bbs * self.tile_n * nst)) lane = cute.arch.thread_idx()[0] % cute.arch.WARP_SIZE g = lane // 4 t = lane % 4 gw = tScS[0][0] // 16 base = gw * (16 * S2) mR32 = self._n115_r32 P = cute.make_tensor(self._n115_p32.iterator, cute.make_layout((self.n32_extent, 8), stride=(8, 1))) m0 = m_block * self.tile_m ra = cute.make_rmem_tensor((4,), Int32) for hh in cutlass.range_constexpr(2): m_idx = m0 + 16 * gw + 8 * hh + g for kk in cutlass.range_constexpr(2): v = Int32(0) if m_idx < seqlen.seqlen_q: v = mR32[seqlen.offset_q + m_idx, head_idx, t + 4 * kk] ra[hh + 2 * kk] = v n_idx_left, n_idx_right = self._n115_bi.get_n_idx_left_right(seqlen, m0 + g) d0 = (n_idx_right - 1) - g - n_block * self.tile_n - (self.tile_n - 1) pmax = self._n115_pmax raw32 = cute.make_tensor(cute.recast_ptr(sBias.iterator, None, Int32), cute.make_layout((bbs * self.tile_n * nst) // 2)) for hf in cutlass.range_constexpr(2): dh = d0 + 16 * gw + HALF * (1 - hf) if 16 * gw < bbs: cute.arch.sync_warp() # every lane finished reading the slab's previous contents if dh >= 0 and dh + 8 * nch - 1 <= pmax: self.n115_emit_half(raw32, ra, P, dh, pmax, base, g, t, nch, False) else: self.n115_emit_half(raw32, ra, P, dh, pmax, base, g, t, nch, True) cute.arch.sync_warp() # the half slab is complete before any lane reads it for i in cutlass.range_constexpr(32 * hf, 32 * hf + 32): row = tScS[i][0] col = tScS[i][1] acc_S[i] = acc_S[i] * base_softmax_scale if const_expr(self.bias_block_size == self.tile_m) or row < self.bias_block_size: il = row - 16 * gw acc_S[i] = acc_S[i] + raw[ base + il * S2 + (il + (HALF - 1) - (col - HALF * hf)) ].to(self.qk_acc_dtype) else: for i in cutlass.range(cute.size(acc_S.shape), unroll_full=True): acc_S[i] = acc_S[i] * base_softmax_scale
@cute.jit def n115_emit_half( self, raw32: cute.Tensor, ra: cute.Tensor, P: cute.Tensor, dh: Int32, pmax: Int32, base: Int32, g: Int32, t: Int32, nch: cutlass.Constexpr[int], check: cutlass.Constexpr[bool], ): S2 = N115_STRIDE2 bf = cute.make_rmem_tensor((2 * nch,), Int32) for ch in cutlass.range_constexpr(nch): if const_expr(check): d = cutlass.min(cutlass.max(dh + 8 * ch + g, 0), self.n32_extent - 1) else: d = dh + 8 * ch + g bf[2 * ch] = P[d, t] bf[2 * ch + 1] = P[d, t + 4] for ch in cutlass.range_constexpr(nch): acc = n32_mma_bf16_k16(ra[0], ra[1], ra[2], ra[3], bf[2 * ch], bf[2 * ch + 1]) for hh in cutlass.range_constexpr(2): x0 = acc[2 * hh] x1 = acc[2 * hh + 1] if const_expr(N115_CONTROL == 1): x0 = n32_trunc_bf16_f32(x0) x1 = n32_trunc_bf16_f32(x1) if const_expr(check): p = dh + 8 * ch + 2 * t if p < 0 or p > pmax: x0 = Float32(-Float32.inf) if p + 1 < 0 or p + 1 > pmax: x1 = Float32(-Float32.inf) raw32[(base + (g + 8 * hh) * S2 + 8 * ch + 2 * t) // 2] = n115_pack_bf16x2(x0, x1)
@cute.jit def compute_one_n_block( self, n_block: Int32, consumer_state: PipelineState, mma_params: SimpleNamespace, smem_copy_params: SimpleNamespace, softmax: Softmax, pipeline_k: PipelineAsync, pipeline_v: PipelineAsync, score_mod: Callable | None, sBias: Optional[cute.Tensor], pipeline_bias: Optional[PipelineAsync], base_softmax_scale: Optional[Float32], apply_bias: bool, batch_idx: Int32, head_idx: Int32, m_block: Int32, seqlen: SeqlenInfoQK, aux_data: AuxData = AuxData(), fastdiv_mods=None, mask_fn: Optional[Callable] = None, is_first_n_block: cutlass.Constexpr = False, check_inf: cutlass.Constexpr = True, ): acc_shape_S = mma_params.thr_mma_qk.partition_shape_C( (self.tile_m, self.tile_n) ) acc_S = cute.make_rmem_tensor(acc_shape_S, Float32) acc_S.fill(0.0) k_wait_token = pipeline_k.consumer_try_wait(consumer_state) pipeline_k.consumer_wait(consumer_state, k_wait_token) self._gemm_qk_phase_local( mma_params.thr_mma_qk, acc_S, smem_copy_params.sQ, smem_copy_params.sK[None, None, consumer_state.index], smem_copy_params.smem_thr_copy_Q, smem_copy_params.smem_thr_copy_K, ) pipeline_k.consumer_release(consumer_state)
if const_expr(self.has_bias): if const_expr(self.bias_block_size == self.tile_m): self.n115_bias( acc_S, mma_params.thr_mma_qk, sBias, base_softmax_scale, apply_bias, n_block, m_block, head_idx, seqlen, ) else: self.apply_sheared_bias( acc_S, mma_params.thr_mma_qk, sBias, pipeline_bias, consumer_state, base_softmax_scale, apply_bias, ) if const_expr(score_mod is not None): self.apply_score_mod( mma_params.thr_mma_qk, batch_idx, head_idx, m_block, acc_S, n_block, softmax_scale=( 1.0 if const_expr(self.has_bias) else softmax.softmax_scale ), seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, ) if const_expr(mask_fn is not None): mask_fn(acc_S, n_block=n_block) row_scale = softmax.online_softmax( acc_S, is_first=is_first_n_block, check_inf=check_inf ) softmax.rescale_O(mma_params.acc_O, row_scale) rP = cute.make_fragment_like(acc_S, self.dtype) rP.store(acc_S.load().to(self.dtype)) tOrP = layout_utils.reshape_acc_to_frgA(rP)
v_wait_token = pipeline_v.consumer_try_wait(consumer_state) pipeline_v.consumer_wait(consumer_state, v_wait_token) self._gemm_pv_phase_local( mma_params.thr_mma_pv, mma_params.acc_O, tOrP, smem_copy_params.sV[None, None, consumer_state.index], smem_copy_params.smem_thr_copy_V, ) pipeline_v.consumer_release(consumer_state) consumer_state.advance() return consumer_state
@cute.jit def __call__( self, mQ: cute.Tensor, mK: cute.Tensor, mV: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], softmax_scale: Float32, mCuSeqlensQ: Optional[cute.Tensor] = None, mCuSeqlensK: Optional[cute.Tensor] = None, mSeqUsedQ: Optional[cute.Tensor] = None, mSeqUsedK: Optional[cute.Tensor] = None, mPageTable: Optional[cute.Tensor] = None, window_size_left: Int32 | int | None = None, window_size_right: Int32 | int | None = None, learnable_sink: Optional[cute.Tensor] = None, blocksparse_tensors: Optional[BlockSparseTensors] = None, aux_data: AuxData = AuxData(), mBias: Optional[cute.Tensor] = None, launch_split_combine_early: Int32 = Int32(0), stream: cuda.CUstream = None, ): assert blocksparse_tensors is None, "Block sparsity is not supported on SM120" assert (mBias is not None) == self.has_bias # n32: mBias is a zero-stride stand-in (the presheared-shape argument the interface requires); the kernel reads # r (int32 pairs [T, H, 8]) and proj^T (int32 pairs [E, 8]) from aux_data and builds the sheared tile itself. assert self.has_bias and self.paged_kv and not self.pack_gqa assert not self._uses_split_pv_warps() # n32: row-independent hi - row needs n_idx_right = m_idx + 1 + delta (+ wr): local with a right window, or causal assert (self.is_local and window_size_right is not None) or (self.is_causal and not self.is_local) assert aux_data.tensors is not None and len(aux_data.tensors) == 2 n32_r32, n32_p32 = aux_data.tensors[0], aux_data.tensors[1] aux_data = AuxData() mBias = None assert mPageTable is None or self.paged_kv, ( "SM120 paged KV requires the dedicated DMA-warp specialization" ) self._check_type( *( t.element_type if t is not None else None for t in ( mQ, mK, mV, mO, mLSE, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, ) ) ) tiled_mma_qk, tiled_mma_pv = self._get_tiled_mma() self.num_qk_threads = tiled_mma_qk.size self.num_mma_threads = tiled_mma_pv.size self.num_producer_threads = self.num_threads self.num_Q_load_threads = ( self.num_qk_threads if self._uses_split_pv_warps() else self.num_threads ) self.num_epilogue_threads = ( self.num_mma_threads if self._uses_split_pv_warps() else self.num_threads ) self.use_tma_O = False self._setup_attributes() SharedStorage = self._get_shared_storage_cls()
mQ, mK, mV, mO = [assume_tensor_aligned(t) for t in (mQ, mK, mV, mO)] if const_expr(mBias is not None): assert mBias.element_type == self.dtype mBias = assume_tensor_aligned(mBias) Q_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensQ is None) else [0, 2, 1] ) KV_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensK is None) else [0, 2, 1] ) mQ = cute.make_tensor( mQ.iterator, cute.select(mQ.layout, mode=Q_layout_transpose) ) if const_expr(mBias is not None): mBias = cute.make_tensor( mBias.iterator, cute.select(mBias.layout, mode=Q_layout_transpose), ) mK, mV = [ cute.make_tensor( t.iterator, cute.select(t.layout, mode=KV_layout_transpose) ) for t in (mK, mV) ] if const_expr(mPageTable is None): V_layout_transpose = ( [1, 0, 2, 3] if const_expr(mCuSeqlensK is None) else [1, 0, 2] ) mV = cute.make_tensor( mV.iterator, cute.select(mV.layout, mode=V_layout_transpose) ) if const_expr(self.is_split_kv): num_splits = mO.shape[0] O_layout_transpose = ( [2, 4, 3, 1, 0] if const_expr(mCuSeqlensQ is None) else [1, 3, 2, 0] ) LSE_layout_transpose = ( [3, 2, 1, 0] if const_expr(mCuSeqlensQ is None) else [2, 1, 0] ) else: num_splits = Int32(1) O_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensQ is None) else [0, 2, 1] ) LSE_layout_transpose = ( [2, 1, 0] if const_expr(mCuSeqlensQ is None) else [1, 0] ) mO = cute.make_tensor( mO.iterator, cute.select(mO.layout, mode=O_layout_transpose) ) if const_expr(mLSE is not None): mLSE = cute.make_tensor( mLSE.iterator, cute.select(mLSE.layout, mode=LSE_layout_transpose) ) if const_expr(self.pack_gqa): nheads_kv = mK.shape[2] mQ = pack_gqa_layout(mQ, self.qhead_per_kvhead, nheads_kv, head_idx=2) mO = pack_gqa_layout(mO, self.qhead_per_kvhead, nheads_kv, head_idx=2) if const_expr(mLSE is not None): mLSE = pack_gqa_layout( mLSE, self.qhead_per_kvhead, nheads_kv, head_idx=1 ) if const_expr(mBias is not None): mBias = pack_gqa_layout( mBias, self.qhead_per_kvhead, nheads_kv, head_idx=2 )
if const_expr(mPageTable is None or self.paged_tma): tma_copy_op = cpasync.CopyBulkTensorTileG2SOp() mV_tma = ( mV if const_expr(mPageTable is None) else cute.make_tensor( mV.iterator, cute.select(mV.layout, mode=[1, 0, 2, 3]), ) ) tma_atom_K, tma_tensor_K = cpasync.make_tiled_tma_atom( tma_copy_op, mK, cute.select(self.sK_layout, mode=[0, 1]), (self.tile_n, self.tile_hdim), 1, ) tma_atom_V, tma_tensor_V = cpasync.make_tiled_tma_atom( tma_copy_op, mV_tma, cute.select(self.sV_layout, mode=[0, 1]), (self.tile_hdimv, self.tile_n), 1, ) self.tma_copy_bytes_K = cute.size_in_bytes( mK.element_type, cute.select(self.sK_layout, mode=[0, 1]) ) self.tma_copy_bytes_V = cute.size_in_bytes( mV_tma.element_type, cute.select(self.sV_layout, mode=[0, 1]), ) else: tma_atom_K = None tma_atom_V = None tma_tensor_K = mK tma_tensor_V = mV # n32: no bias TMA; the kernel's mBias / tma_atom_Bias slots carry r32 / p32. tma_tensor_Bias = n32_r32 tma_atom_Bias = n32_p32
is_varlen = const_expr(mCuSeqlensQ is not None or mSeqUsedQ is not None) num_batch = ( mCuSeqlensQ.shape[0] - 1 if const_expr(mCuSeqlensQ is not None) else cute.size(mQ.shape[3]) ) TileScheduler = ( Sm120UniformBatchScheduler if is_varlen and self.direct_uniform_batch else SingleTileVarlenScheduler if is_varlen else SingleTileScheduler ) tile_sched_args = TileSchedulerArguments( num_block=cute.ceil_div(cute.size(mQ.shape[0]), self.tile_m), num_head=cute.size(mQ.shape[2]), num_batch=num_batch, num_splits=num_splits, seqlen_k=0, headdim=mQ.shape[1], headdim_v=mO.shape[1], total_q=( cute.size(mQ.shape[0]) if const_expr(mCuSeqlensQ is not None) else cute.size(mQ.shape[0]) * cute.size(mQ.shape[3]) ), tile_shape_mn=(self.tile_m, self.tile_n), lpt=(self.is_causal or self.is_local) and not self.direct_uniform_batch, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), mCuSeqlensQ=mCuSeqlensQ, mSeqUsedQ=mSeqUsedQ, is_persistent=False, is_split_kv=self.is_split_kv, ) tile_sched_params = TileScheduler.to_underlying_arguments( tile_sched_args, scheduling_mode=SchedulingMode.STATIC, ) grid_dim = TileScheduler.get_grid_shape(tile_sched_params) if const_expr(self.has_bias): base_softmax_scale = softmax_scale softmax_scale_log2, softmax_scale = utils.LOG2_E, None else: base_softmax_scale = None softmax_scale_log2, softmax_scale = utils.compute_softmax_scale_log2( softmax_scale, self.score_mod ) window_size_left = ( Int32(window_size_left) if window_size_left is not None else None ) window_size_right = ( Int32(window_size_right) if window_size_right is not None else None ) fastdiv_mods = utils.compute_fastdiv_mods( mQ, mK, self.qhead_per_kvhead, self.pack_gqa, aux_data.tensors, mPageTable, )
self.kernel( mQ, tma_tensor_K, tma_tensor_V, mO, mLSE, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, tma_tensor_Bias, tma_atom_K, tma_atom_V, tma_atom_Bias, softmax_scale_log2, softmax_scale, base_softmax_scale, window_size_left, window_size_right, learnable_sink, self.sQ_layout, self.sK_layout, self.sV_layout, self.sO_layout, self.sP_layout, self.sBias_layout, self.gmem_tiled_copy_Q, self.gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, SharedStorage, tile_sched_params, TileScheduler, launch_split_combine_early, aux_data, fastdiv_mods, ).launch( grid=grid_dim, block=[self.num_threads + self._num_dma_threads(), 1, 1], smem=SharedStorage.size_in_bytes(), stream=stream, min_blocks_per_mp=1, # The immediately preceding ShearingBias grid releases this # dependent launch before all of its CTAs have retired. Bias # readers synchronize before their first TMA issue below; the # remaining kernel prologue can overlap the tail of the shear. use_pdl=False, # n32: no shear grid precedes this kernel )
@cute.kernel def kernel( self, mQ: cute.Tensor, mK: cute.Tensor, mV: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], mCuSeqlensQ: Optional[cute.Tensor], mCuSeqlensK: Optional[cute.Tensor], mSeqUsedQ: Optional[cute.Tensor], mSeqUsedK: Optional[cute.Tensor], mPageTable: Optional[cute.Tensor], mBias: Optional[cute.Tensor], tma_atom_K: Optional[cute.CopyAtom], tma_atom_V: Optional[cute.CopyAtom], tma_atom_Bias: Optional[cute.Tensor], # n32: proj^T int32 pairs [E, 8] softmax_scale_log2: Float32, softmax_scale: Optional[Float32], base_softmax_scale: Optional[Float32], window_size_left: Optional[Int32], window_size_right: Optional[Int32], learnable_sink: Optional[cute.Tensor], sQ_layout: cute.ComposedLayout, sK_layout: cute.ComposedLayout, sV_layout: cute.ComposedLayout, sO_layout: cute.ComposedLayout, sP_layout: cute.ComposedLayout | None, sBias_layout: cute.ComposedLayout | None, gmem_tiled_copy_Q: cute.TiledCopy, gmem_tiled_copy_O: cute.TiledCopy, tiled_mma_qk: cute.TiledMma, tiled_mma_pv: cute.TiledMma, SharedStorage: cutlass.Constexpr, tile_sched_params, TileScheduler: cutlass.Constexpr[Callable], launch_split_combine_early: Int32, aux_data: AuxData = AuxData(), fastdiv_mods=None, ): tidx, _, _ = cute.arch.thread_idx() warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) # n115: consumer-side bias inputs, taken at kernel entry so they dominate every consumer use if const_expr(not self.n32_plain_bias): # n126 S4c: the global classes trace S3's kernel entry self._n115_r32 = mBias self._n115_p32 = tma_atom_Bias self._n115_bi = BlockInfo( self.tile_m, self.tile_n, self.is_causal, self.is_local, self.is_split_kv, window_size_left, window_size_right, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), ) if const_expr(self.is_local): self._n115_pmax = cutlass.min( window_size_left + window_size_right, self.n32_extent - 1 ) else: self._n115_pmax = Int32(self.n32_extent - 1)
if const_expr(self.is_split_kv): if launch_split_combine_early != 0 and warp_idx == 0: cute.arch.griddepcontrol_launch_dependents()
if const_expr(mPageTable is None or self.paged_tma): if warp_idx == 0: cpasync.prefetch_descriptor(tma_atom_K) cpasync.prefetch_descriptor(tma_atom_V)
smem = cutlass.utils.SmemAllocator() storage = smem.allocate(SharedStorage) sQ = storage.sQ.get_tensor(sQ_layout.outer, swizzle=sQ_layout.inner) sK = storage.sK.get_tensor(sK_layout.outer, swizzle=sK_layout.inner) sV = storage.sV.get_tensor(sV_layout.outer, swizzle=sV_layout.inner) sO = storage.sQ.get_tensor(sO_layout.outer, swizzle=sO_layout.inner) sBias = ( storage.sBias.get_tensor(sBias_layout.outer, swizzle=sBias_layout.inner) if const_expr(self.has_bias) else None ) sP = None sRowScale = None sFinalScale = None sLSE = None if const_expr(sP_layout is not None): if const_expr(self._q_in_regs_pipeline()): sP = storage.sQ.get_tensor(sP_layout.outer, swizzle=sP_layout.inner) else: sP = storage.sP.get_tensor(sP_layout.outer, swizzle=sP_layout.inner) sSoftmaxStats = storage.softmax_stats.get_tensor( cute.make_layout( (self._num_softmax_stat_rows(), self.tile_m), stride=(self.tile_m, 1), ) ) sRowScale = sSoftmaxStats if const_expr(self._uses_n_distributed_qk()): num_qk_warps = self.num_qk_threads // cute.arch.WARP_SIZE sFinalScale = sSoftmaxStats[2 * num_qk_warps + 2, None] sLSE = sSoftmaxStats[3 * num_qk_warps + 3, None] else: sFinalScale = sSoftmaxStats[2, None] sLSE = sSoftmaxStats[3, None]
tma_group = CooperativeGroup(Agent.Thread) qk_group = CooperativeGroup( Agent.Thread, self.num_qk_threads // cute.arch.WARP_SIZE ) pv_group = CooperativeGroup( Agent.Thread, self.num_mma_threads // cute.arch.WARP_SIZE ) if const_expr(mPageTable is None or self.paged_tma): pipeline_k = PipelineTmaAsync.create( num_stages=self._num_k_stages(), producer_group=tma_group, consumer_group=qk_group, tx_count=self.tma_copy_bytes_K, barrier_storage=storage.mbar_K.data_ptr(), defer_sync=True, ) pipeline_v = PipelineTmaAsync.create( num_stages=self._num_v_stages(), producer_group=tma_group, consumer_group=pv_group, tx_count=self.tma_copy_bytes_V, barrier_storage=storage.mbar_V.data_ptr(), defer_sync=True, ) else: dma_group = CooperativeGroup(Agent.Thread, self.num_dma_threads) k_consumer_group = CooperativeGroup( Agent.Thread, ( self.num_qk_threads if self._uses_split_pv_warps() else self.num_threads ), ) v_consumer_group = CooperativeGroup( Agent.Thread, ( self.num_mma_threads if self._uses_split_pv_warps() else self.num_threads ), ) pipeline_k = pipeline_custom.PipelineCpAsync.create( num_stages=self._num_k_stages(), producer_group=dma_group, consumer_group=k_consumer_group, barrier_storage=storage.mbar_K.data_ptr(), defer_sync=True, ) pipeline_v = pipeline_custom.PipelineCpAsync.create( num_stages=self._num_v_stages(), producer_group=dma_group, consumer_group=v_consumer_group, barrier_storage=storage.mbar_V.data_ptr(), defer_sync=True, ) # n32: the DMA warp's 32 threads write the bias stage and each arrives; every QK thread waits and arrives on # release (apply_sheared_bias calls consumer_release from all of them). pipeline_bias = PipelineAsync.create( num_stages=self.num_stages, producer_group=CooperativeGroup(Agent.Thread, self.num_dma_threads), consumer_group=CooperativeGroup(Agent.Thread, self.num_qk_threads), barrier_storage=storage.mbar_Bias.data_ptr(), defer_sync=True, ) pipeline_p = None pipeline_final = None if const_expr(sP_layout is not None): pipeline_p = PipelineAsync.create( num_stages=self._num_p_stages(), producer_group=CooperativeGroup(Agent.Thread, self.num_qk_threads), consumer_group=CooperativeGroup(Agent.Thread, self.num_mma_threads), barrier_storage=storage.mbar_P.data_ptr(), defer_sync=True, name="sm120_p", ) pipeline_final = PipelineAsync.create( num_stages=1, producer_group=CooperativeGroup(Agent.Thread, self.num_qk_threads), consumer_group=CooperativeGroup(Agent.Thread, self.num_mma_threads), barrier_storage=storage.mbar_final.data_ptr(), defer_sync=True, name="sm120_final", ) tile_scheduler = TileScheduler.create(tile_sched_params) work_tile = tile_scheduler.initial_work_tile_info() if work_tile.is_valid_tile: m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx seqlen = SeqlenInfoQK.create( batch_idx=batch_idx, seqlen_q_static=( mQ.shape[0] if const_expr(not self.pack_gqa) else mQ.shape[0][1] ), seqlen_k_static=( mK.shape[0] if const_expr(mPageTable is None) else mK.shape[0] * mPageTable.shape[1] ), mCuSeqlensQ=mCuSeqlensQ, mCuSeqlensK=mCuSeqlensK, mSeqUsedQ=mSeqUsedQ, mSeqUsedK=mSeqUsedK, tile_m=self.tile_m, tile_n=self.tile_n, ) run_mainloop = True if const_expr(self.is_split_kv): block_info = BlockInfo( self.tile_m, self.tile_n, self.is_causal, self.is_local, self.is_split_kv, window_size_left, window_size_right, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), ) n_block_min, n_block_max = self._get_n_block_min_max( block_info, seqlen, m_block, split_idx, tile_scheduler.params.num_splits, ) is_empty_split = n_block_min >= n_block_max if is_empty_split: if const_expr(self._uses_split_pv_warps()): if warp_idx >= self.num_qk_threads // cute.arch.WARP_SIZE: self.epilogue_empty_split( mO, mLSE, learnable_sink, seqlen, tiled_mma_pv, tidx - self.num_qk_threads, m_block, head_idx, batch_idx, split_idx, ) else: if 0 < warp_idx <= self.num_threads // cute.arch.WARP_SIZE: self.epilogue_empty_split( mO, mLSE, learnable_sink, seqlen, tiled_mma_pv, tidx - self.num_dma_threads, m_block, head_idx, batch_idx, split_idx, ) run_mainloop = not is_empty_split
if run_mainloop: pipeline_init_arrive(cluster_shape_mn=(1, 1), is_relaxed=True) pipeline_init_wait(cluster_shape_mn=(1, 1))
if const_expr(mPageTable is not None and self._uses_split_pv_warps()): if warp_idx == 0: self.load_paged_persistent( mK, mV, mPageTable, tma_atom_K, tma_atom_V, sK, sV, pipeline_k, pipeline_v, tile_scheduler, mQ, mCuSeqlensQ, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, tidx, ) elif const_expr(self._uses_n_distributed_qk()): if warp_idx <= self.num_mma_threads // cute.arch.WARP_SIZE: self.mma_persistent( mQ, mK, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx - self.num_dma_threads, softmax_scale_log2, softmax_scale, base_softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, window_size_left, window_size_right, True, aux_data, fastdiv_mods, ) elif warp_idx == 1: self.mma_persistent( mQ, mK, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx - self.num_dma_threads, softmax_scale_log2, softmax_scale, base_softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, window_size_left, window_size_right, True, aux_data, fastdiv_mods, ) elif warp_idx <= self.num_mma_threads // cute.arch.WARP_SIZE: self.mma_persistent( mQ, mK, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx - self.num_dma_threads, softmax_scale_log2, softmax_scale, base_softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, window_size_left, window_size_right, False, aux_data, fastdiv_mods, ) elif const_expr(self._uses_split_pv_warps()): if warp_idx < self.num_qk_threads // cute.arch.WARP_SIZE: self.mma_qk_pipeline_persistent( mQ, mK, mV, sQ, sK, sV, tma_atom_K, tma_atom_V, sP, sRowScale, sFinalScale, sLSE, learnable_sink, pipeline_k, pipeline_v, pipeline_p, pipeline_final, gmem_tiled_copy_Q, tiled_mma_qk, tidx, softmax_scale_log2, softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, aux_data, fastdiv_mods, ) else: self.mma_pv_pipeline_persistent( mQ, mK, mO, mLSE, sV, sO, sP, sRowScale, sFinalScale, sLSE, pipeline_v, pipeline_p, pipeline_final, gmem_tiled_copy_O, tiled_mma_pv, tidx - self.num_qk_threads, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, ) elif warp_idx == 0: if const_expr(mPageTable is None): self.load_tma_persistent( mK, mV, sK, sV, tma_atom_K, tma_atom_V, pipeline_k, pipeline_v, tile_scheduler, mQ, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, mBias=mBias, sBias=sBias, tma_atom_Bias=tma_atom_Bias, pipeline_bias=pipeline_bias, ) else: self.load_paged_persistent( mK, mV, mPageTable, tma_atom_K, tma_atom_V, sK, sV, pipeline_k, pipeline_v, tile_scheduler, mQ, mCuSeqlensQ, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, tidx, mBias=mBias, sBias=sBias, tma_atom_Bias=tma_atom_Bias, pipeline_bias=pipeline_bias, ) elif warp_idx <= self.num_threads // cute.arch.WARP_SIZE: self.mma_persistent( mQ, mK, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx - self.num_dma_threads, softmax_scale_log2, softmax_scale, base_softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, window_size_left, window_size_right, True, aux_data, fastdiv_mods, sBias=sBias, pipeline_bias=pipeline_bias, )
@cute.jit def load_paged_persistent( self, mK: cute.Tensor, mV: cute.Tensor, mPageTable: cute.Tensor, tma_atom_K: Optional[cute.CopyAtom], tma_atom_V: Optional[cute.CopyAtom], sK: cute.Tensor, sV: cute.Tensor, pipeline_k: PipelineAsync, pipeline_v: PipelineAsync, tile_scheduler: TileSchedulerProtocol, mQ: cute.Tensor, mCuSeqlensQ: Optional[cute.Tensor], mSeqUsedQ: Optional[cute.Tensor], mSeqUsedK: Optional[cute.Tensor], window_size_left: Optional[Int32], window_size_right: Optional[Int32], tidx: Int32, mBias: Optional[cute.Tensor] = None, sBias: Optional[cute.Tensor] = None, tma_atom_Bias: Optional[cute.Tensor] = None, # n32: proj^T int32 pairs; mBias = r int32 pairs pipeline_bias: Optional[PipelineAsync] = None, ): producer_state_k = PipelineState( self._num_k_stages(), Int32(0), Int32(0), Int32(1) ) producer_state_v = PipelineState( self._num_v_stages(), Int32(0), Int32(0), Int32(1) ) block_info = BlockInfo( self.tile_m, self.tile_n, self.is_causal, self.is_local, self.is_split_kv, window_size_left, window_size_right, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), ) work_tile = tile_scheduler.initial_work_tile_info() m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx seqlen = SeqlenInfoQK.create( batch_idx=batch_idx, seqlen_q_static=( mQ.shape[0] if const_expr(not self.pack_gqa) else mQ.shape[0][1] ), seqlen_k_static=mK.shape[0] * mPageTable.shape[1], mCuSeqlensQ=mCuSeqlensQ, mCuSeqlensK=None, mSeqUsedQ=mSeqUsedQ, mSeqUsedK=mSeqUsedK, tile_m=self.tile_m, tile_n=self.tile_n, ) n_block_min, n_block_max = self._get_n_block_min_max( block_info, seqlen, m_block, split_idx, tile_scheduler.params.num_splits, ) head_idx_kv = ( head_idx if const_expr(self.pack_gqa) else head_idx // self.qhead_per_kvhead ) bias_max_idx, num_bias_loads = Int32(0), Int32(0) if const_expr(self.has_bias): bias_max_idx, num_bias_loads = self._get_bias_load_info( block_info, seqlen, m_block, n_block_min, n_block_max, ) # n32: per-lane A fragments of r for the tile's rows and the rows' visible key bounds. n32_ra, n32_lo, n32_hi = self.n32_tile_setup( mBias, block_info, seqlen, m_block, head_idx, tidx ) if const_expr(self.is_local): n32_pmax = cutlass.min( window_size_left + window_size_right, self.n32_extent - 1 ) else: n32_pmax = Int32(self.n32_extent - 1) assert not self.paged_tma # n32: page-TMA path not built if const_expr(self.paged_tma): mK_cur = mK[None, None, head_idx_kv, None] mV_cur = mV[None, None, head_idx_kv, None] gK = cute.local_tile( mK_cur, (self.tile_n, self.tile_hdim), (0, 0, None), ) gV = cute.local_tile( mV_cur, (self.tile_hdimv, self.tile_n), (0, 0, None), ) copy_K, _, _ = copy_utils.tma_get_copy_fn( tma_atom_K, 0, cute.make_layout(1), gK, sK, ) copy_V, _, _ = copy_utils.tma_get_copy_fn( tma_atom_V, 0, cute.make_layout(1), gV, sV, ) num_n_blocks = cutlass.max(n_block_max - n_block_min, 1) for n_tile in cutlass.range(num_n_blocks, unroll=1): n_block = cutlass.max(n_block_max - 1 - n_tile, n_block_min) page_idx = mPageTable[batch_idx, n_block]
if const_expr(self.has_bias): if n_tile < num_bias_loads: pipeline_bias.producer_acquire(producer_state_k) cute.copy( tma_atom_Bias, tBgBias[None, m_block, bias_max_idx - n_tile], tBsBias[None, producer_state_k.index], tma_bar_ptr=pipeline_bias.producer_get_barrier( producer_state_k ), ) pipeline_bias.producer_commit(producer_state_k) pipeline_k.producer_acquire(producer_state_k) copy_K( src_idx=page_idx, dst_idx=producer_state_k.index, tma_bar_ptr=pipeline_k.producer_get_barrier(producer_state_k), ) pipeline_k.producer_commit(producer_state_k) producer_state_k.advance()
pipeline_v.producer_acquire(producer_state_v) copy_V( src_idx=page_idx, dst_idx=producer_state_v.index, tma_bar_ptr=pipeline_v.producer_get_barrier(producer_state_v), ) pipeline_v.producer_commit(producer_state_v) producer_state_v.advance()
pipeline_k.producer_tail(producer_state_k) pipeline_v.producer_tail(producer_state_v) return
paged_kv_manager = Sm120PagedKVManager.create( mPageTable, mK, mV, FastDivmodDivisor(mK.shape[0]), batch_idx, head_idx_kv, tidx, seqlen.seqlen_k, 0, self.tile_n, self.tile_hdim, self.tile_hdimv, self.num_dma_threads, mK.element_type, ) num_n_blocks = cutlass.max(n_block_max - n_block_min, 1) for n_tile in cutlass.range(num_n_blocks, unroll=1): n_block = cutlass.max(n_block_max - 1 - n_tile, n_block_min) paged_kv_manager.load_page_table(n_block)
pipeline_k.producer_acquire(producer_state_k) paged_kv_manager.load_KV( n_block, sK[None, None, producer_state_k.index], "K", ) cute.arch.cp_async_commit_group() pipeline_k.producer_commit(producer_state_k) if const_expr(self.has_bias and (N115_DMA == 1 or self.bias_block_size != self.tile_m or self.n32_plain_bias)): # n126 S4c: global classes fill as S3 # n32: the sheared bias tile of key block n_block (the served TMA source block bias_max_idx - n_tile # holds keys n_block * tile_n + col), computed while K is in flight; same pipeline state as the TMA. if n_tile < num_bias_loads: pipeline_bias.producer_acquire(producer_state_k) self.n32_bias_tile( sBias[None, None, producer_state_k.index], tma_atom_Bias, n32_ra, n32_lo, n32_hi, n32_pmax, n_block, seqlen, m_block, tidx, ) pipeline_bias.producer_commit(producer_state_k) producer_state_k.advance()
pipeline_v.producer_acquire(producer_state_v) sV_stage = layout_utils.transpose_view( sV[None, None, producer_state_v.index] ) paged_kv_manager.load_KV(n_block, sV_stage, "V") cute.arch.cp_async_commit_group() pipeline_v.producer_commit(producer_state_v) producer_state_v.advance()
pipeline_k.producer_tail(producer_state_k) pipeline_v.producer_tail(producer_state_v)
if N32_GLOBAL: from sglang.kernels.ops.attention.fa4_sm120.n13_fwd import FlashAttentionForwardSm120BandSplit # noqa: E402
class FlashAttentionForwardSm120BandSplitRelProd(FlashAttentionForwardSm120RelProd, FlashAttentionForwardSm120BandSplit): """n13's global-layer band-split kernel (consumer mma and its unswizzled bias tile, n13_fwd.py) fed by the n32 in-kernel producer (causal pads: -inf right of the diagonal, 0.0 past the 1024-key band)."""
n32_plain_bias = True # n126 S4c: S3's consumer. a4 overrides compute_one_n_block on RelProd; S3's MRO (no override on RelProd) resolves it from # BandSplit / the base kernel. Take the raw class-dict object that S3's lookup would find, skipping RelProd, so this class and # every subclass (n64a BandOnly) trace S3's consumer. compute_one_n_block = next(k.__dict__["compute_one_n_block"] for k in FlashAttentionForwardSm120BandSplit.__mro__ if "compute_one_n_block" in k.__dict__)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""n35 / n36 (inkling2-spark decode seat, 2026-11-21): MXFP8 W8A16 weights on decode / target-verify forwards only.N35_W8 (env, comma list): attn = qkvr + wo_ud of every Inkling2Attention; lm = the verify LM head. Unset or empty: off.At the first forward (eager, before any graph capture) each selected BF16 weight gets an e4m3 copy with one power-of-2 scaleper 32 K-elements (n35_w8gemv.quantize_mx8, the n33_fq 'mx8' rounding: dequantized values are bit-equal to that probe'srounded BF16 weights). During decode / verify forwards Inkling2Attention swaps its qkvr / wo_ud child modules for a W8 wrapper(n35_w8gemv.w8_gemv: the served _gemv_kernel's tile shape with dequantized tiles, so 1-source visits and wo_ud at <= 16 rowsreproduce the probe's numerics; the 3-source stacked 24-row projection was nvjet and now is this kernel); the captured verifygraphs bind the W8 kernels, while prefill (eager or graph) keeps the BF16 path, so KLD is unchanged by construction. The LMhead is swapped inside Inkling2LogitsProcessor._compute_lm_head while a decode / verify logits call is active. Rows > 128 fallback to BF16. Extra memory: FP8 copies (~0.85 GB attn, ~0.21 GB + 6 MB lm) beside the BF16 weights."""import logging, os
import torchfrom torch import nn
logger = logging.getLogger(__name__)SEL = {s.strip() for s in os.environ.get("N35_W8", "").split(",") if s.strip()}S = {"mods": [], "done": False, "lm": {}, "active": False}_INSTALLED = False
class _W8Lin(nn.Module): def __init__(self, orig, w8, e): super().__init__() self.orig = orig self.register_buffer("w8", w8, persistent=False) self.register_buffer("e", e, persistent=False)
def forward(self, x, *a, **kw): from sglang.srt.models.inkling_common.n35_w8gemv import w8_gemv rows = x.numel() // x.shape[-1] if a or kw or rows > 128 or x.dtype != torch.bfloat16: return self.orig(x, *a, **kw) return w8_gemv(x, self.w8, self.e), None
def _decode_mode(fb): m = fb.forward_mode return m.is_decode() or m.is_target_verify()
def _prepare(): from sglang.srt.models.inkling_common.n35_w8gemv import quantize_mx8 if torch.cuda.is_current_stream_capturing(): raise RuntimeError("n35_w8: first forward inside graph capture") tot = 0 if "attn" in SEL: for m in S["mods"]: for name in ("qkvr", "wo_ud"): orig = m._modules[name] if getattr(orig, "bias", None) is not None and bool(orig.bias.abs().max() > 0): raise RuntimeError(f"n35_w8: {name} has a nonzero bias") w8, e = quantize_mx8(orig.weight.data) m.__dict__[f"_n35_{name}"] = (orig, _W8Lin(orig, w8, e)) tot += w8.numel() + e.numel() if "lm" in SEL: _patch_lm() S["done"] = True logger.warning("n35_w8 %s: %d attention modules, FP8 copies %.3f GB", sorted(SEL), len(S["mods"]), tot / 1e9)
def _patch_lm(): """Patched at the first forward: inkling2.py is still importing when inkling2_attn.py runs install().""" from sglang.srt.models import inkling2 as I from sglang.srt.models.inkling_common.n35_w8gemv import quantize_mx8, w8_gemv lp = I.Inkling2LogitsProcessor orig_fwd, orig_head = lp.forward, lp._compute_lm_head
def forward(self, input_ids, hidden_states, lm_head, logits_metadata, *a, **kw): if hasattr(logits_metadata, "forward_mode") and _decode_mode(logits_metadata): key = id(lm_head) if key not in S["lm"]: if torch.cuda.is_current_stream_capturing(): raise RuntimeError("n35_w8: LM head first seen inside graph capture") S["lm"][key] = quantize_mx8(lm_head.weight.data) logger.warning("n35_w8: LM head FP8 copy %s", tuple(lm_head.weight.shape)) S["active"] = key try: return orig_fwd(self, input_ids, hidden_states, lm_head, logits_metadata, *a, **kw) finally: S["active"] = False return orig_fwd(self, input_ids, hidden_states, lm_head, logits_metadata, *a, **kw)
def compute_lm_head(self, hidden_states, lm_head, embedding_bias=None, *, out=None): key = S["active"] rows = hidden_states.numel() // hidden_states.shape[-1] if key is False or key != id(lm_head) or embedding_bias is not None or rows > 128 or hidden_states.dtype != torch.bfloat16: return orig_head(self, hidden_states, lm_head, embedding_bias, out=out) w8, e = S["lm"][key] dt = torch.float32 if (self.use_fp32_lm_head or getattr(self, "use_fp32_lm_head_output", False)) else hidden_states.dtype if out is None or out.dtype != dt or tuple(out.shape) != (rows, w8.shape[0]): out = torch.empty((rows, w8.shape[0]), device=hidden_states.device, dtype=dt) logits = w8_gemv(hidden_states.reshape(rows, -1), w8, e, out=out) if self.shard_softcap: # as Inkling2LogitsProcessor._compute_lm_head I.fused_softcap(logits, self.shard_softcap) return logits
lp.forward, lp._compute_lm_head = forward, compute_lm_head logger.warning("n35_w8: LM head patch installed")
def install(): global _INSTALLED if _INSTALLED or not SEL: return from sglang.srt.models.inkling_common import inkling2_attn as A cls = A.Inkling2Attention orig_init, orig_fwd = cls.__init__, cls._forward
def init(self, *a, **kw): orig_init(self, *a, **kw) S["mods"].append(self)
def fwd(self, hidden_states, positions, forward_batch, *, attn, attn_padded): if not S["done"]: _prepare() if "attn" not in SEL or not _decode_mode(forward_batch): return orig_fwd(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) (q0, q1), (w0, w1) = self._n35_qkvr, self._n35_wo_ud self._modules["qkvr"], self._modules["wo_ud"] = q1, w1 try: return orig_fwd(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) finally: self._modules["qkvr"], self._modules["wo_ud"] = q0, w0
cls.__init__, cls._forward = init, fwd _INSTALLED = True logger.warning("n35_w8 installed: %s", sorted(SEL))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""n33 W8A16 GEMV (inkling2-spark decode seat, 2026-11-21): y[M, N] = x[M, K] @ dequant(w8[N, K])^T, BF16 activations, MXFP8-styleweights: e4m3 values with one power-of-2 scale per 32 consecutive K elements of a row (stored as int8 exponents e, scale 2^e).q * 2^e is exact in BF16, so each dequantized tile equals the fake-quant probe's rounded BF16 weight bit for bit; the dot runsin BF16 on tensor cores with FP32 accumulation, in the served _gemv_kernel's shape (BN 32 columns per program, BK 256,MP rows padded to 16 / 32 / 64 / 128; BK 128 above 32 rows), so only the weight bytes change: 1.03 B per weight instead of 2.quantize_mx8(w) -> (w8, e) builds the operands from a BF16 [N, K] weight (K % 32 == 0) with the n33_fq rounding."""import torchimport tritonimport triton.language as tl
BN, BK, BLK = 32, 256, 32
@triton.jitdef _w8_gemv_kernel(X, W, E, Y, M, N, K, SX, SW, SE, SY, BN: tl.constexpr, BK: tl.constexpr, MP: tl.constexpr, BLK: tl.constexpr, F32: tl.constexpr = False): pid = tl.program_id(0) cols = pid * BN + tl.arange(0, BN) rows = tl.arange(0, MP) acc = tl.zeros((MP, BN), tl.float32) for k0 in range(0, K, BK): ks = k0 + tl.arange(0, BK) w = tl.load(W + cols[None, :].to(tl.int64) * SW + ks[:, None], (cols[None, :] < N) & (ks[:, None] < K), other=0.0) kb = k0 // BLK + tl.arange(0, BK // BLK) e = tl.load(E + cols[None, :].to(tl.int64) * SE + kb[:, None], (cols[None, :] < N) & (kb[:, None] < K // BLK), other=0) s = tl.exp2(e.to(tl.float32)) # (BK/BLK, BN), exact powers of two wf = tl.reshape(w.to(tl.float32), (BK // BLK, BLK, BN)) * tl.reshape(s, (BK // BLK, 1, BN)) wb = tl.reshape(wf, (BK, BN)) if not F32: # F32: CPU-interpreter test path only (its bf16 tl.dot is broken) wb = wb.to(tl.bfloat16) x = tl.load(X + rows[:, None] * SX + ks[None, :], (rows[:, None] < M) & (ks[None, :] < K), other=0.0) acc += tl.dot(x, wb) tl.store(Y + rows[:, None] * SY + cols[None, :], acc.to(Y.dtype.element_ty), (rows[:, None] < M) & (cols[None, :] < N))
def quantize_mx8(w: torch.Tensor): n, k = w.shape assert k % BLK == 0 x = w.float().view(n, k // BLK, BLK) amax = x.abs().amax(-1, keepdim=True).clamp_min(2.0 ** -120) e = torch.floor(torch.log2(amax)) - 8 q = (x / torch.exp2(e)).clamp(-448.0, 448.0).to(torch.float8_e4m3fn) return q.view(n, k).contiguous(), e.view(n, k // BLK).to(torch.int8).contiguous()
def dequant_mx8(w8, e): n, k = w8.shape return (w8.float().view(n, k // BLK, BLK) * torch.exp2(e.float()).view(n, k // BLK, 1)).view(n, k).to(torch.bfloat16)
def w8_gemv(x: torch.Tensor, w8: torch.Tensor, e: torch.Tensor, out: torch.Tensor | None = None, _f32: bool = False) -> torch.Tensor: lead = x.shape[:-1] x2 = x.reshape(-1, x.shape[-1]) m, k = x2.shape n = w8.shape[0] assert m <= 128 and k == w8.shape[1] and k % BK == 0, (m, k, w8.shape) mp = 16 if m <= 16 else 32 if m <= 32 else 64 if m <= 64 else 128 bk = BK if mp <= 32 else 128 # bound the x tile for 64 / 128 rows (only the K chunking of the FP32 sum changes) if out is None: out = torch.empty((m, n), device=x.device, dtype=x.dtype) if m: _w8_gemv_kernel[(triton.cdiv(n, BN),)](x2, w8, e, out, m, n, k, x2.stride(0), w8.stride(0), e.stride(0), out.stride(0), BN=BN, BK=bk, MP=mp, BLK=BLK, F32=_f32, num_warps=4) return out.view(*lead, n)12345678910111213141516171819202122232425262728"""n37 (inkling2-spark decode seat, 2026-11-21): NVFP4 grouped-GEMM tile config for decode / verify sizes on GB10.sglang.kernels.ops.gemm.inkling2_grouped_sm120._tiles serves <= 128 tokens with (swap_ab, tile_n 32, tile_k 128), measured onRTX 5090. On GB10 (n33 microbench, 300 real bs-1 verify routings, cold L2) tile_k 256 is 6.0 pct faster on w13 and 2.5 pcton w2 and BITWISE EQUAL to the served config on every routing (the tile shape does not change the per-element K order).This hook replaces _tiles for tokens <= 128 only; larger calls keep the image's table. N37_TILE_K (env, default 256; 128 =the image config, for a control)."""import logging, os
logger = logging.getLogger(__name__)TILE_K = int(os.environ.get("N37_TILE_K", "256"))_INSTALLED = False
def install(): global _INSTALLED if _INSTALLED: return from sglang.kernels.ops.gemm import inkling2_grouped_sm120 as G orig = G._tiles
def _tiles(tokens, width): if tokens <= 128: return True, 32, TILE_K return orig(tokens, width)
G._tiles = _tiles _INSTALLED = True logger.warning("n37: NVFP4 grouped GEMM decode tiles (swap_ab, 32, %d) for <= 128 tokens", TILE_K)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""n50 form b (stack seat, 2026-11-22; build 6 = build 5 939f1f3f with the bank-stat tile sized to the served thread count: 128lanes for 96 threads (3 queries), 64 for 64 (1 query: build 5 masked half of 128). Build 5 = n15_fused.py build 4 380adeee + themessage-bank AttnRes fused in): one Tritonkernel for LoopMessageBank.mix on a 2-source bank = attn_res(blocks, None, queries, normalize_values=True) + message_controllers.The messages are never written: each program recomputes its controller's message rows from the two BF16 bank sources, copyingthe image AttnResFwdKernel order (kernels/ops/attention/inkling2_attn_res.py, PTX + SASS read from the image compile): - per source: thread t of NT (96 for 3 queries, 64 for 1) holds x[4 NT c + 4 t + v], c < NC (6 / 9), v < 4, and runs one fma.rn chain over (c, v) for sum(x * x) and one for sum(x * q); warp butterfly xor 16, 8, 4, 2, 1; warps added in order from 0.0; - rstd = rsqrt.approx(fma.rn(sumsq, f32(1/2304), eps)); max over sources of round(dot * rstd) from -inf; e = expf(fma(dot, rstd, -max)) (ptxas contracts the served mul + sub); sum = (0 + e0) + e1; inv = rcp.rn(sum); p = e * rstd (mul.rn); - message = mul.rn(fma.rn(p1, x1, fma.rn(p0, x0, 0)), inv).Then the build 4 controller, with every Message read replaced by that recompute. Build 4 docstring:n15 fused loop controller (stack seat, 2026-11-22): one Triton kernel for message_controllers' norm + down + mix(sglang kernels/ops/elementwise/inkling2_loop.py), meant to be BITWISE equal to the served three kernels by copying eachorder: - row RMS: per row a 1-D tensor<BLOCK = next_pow2(W)> load + tl.sum under num_warps 8, as _controller_norm (served ttgir: #blocked sizePerThread [8], warpsPerCTA [8]); rsqrt(div_rn(sum, W) + eps) with libdevice; - normed = (x * rstd).to(bf16), concatenated [dest | message] along K = 2W, never written to memory; - down: K walked in 1024-wide groups of BLOCK_K tiles, each group's tl.dot accumulation from zero, groups summed in group order (served non-split path; the split path sums the same partials in the same order); tiles past K masked to zero exactly as the served loads; - mix: hidden.to(bf16) @ gain / forget tiles (K = rank 64 from zero), out = (1 - tanh(f)) * dest + tanh(g) * message, libdevice tanh, enable_fp_fusion False.Grid (NUM, row blocks): the controllers of one row block are adjacent programs, so a stride-0 dest (local layers) isread from DRAM once and from L2 by the other two. Passes 2 and 3 re-read the row block's dest / message from L2."""import os
import tritonimport triton.language as tlfrom triton.language.extra import libdevice
@triton.jitdef _tree_sumsq(v): """the served _controller_norm order on a (256, 16) tile laid out as in _served_sumsq (see build 4).""" q = tl.reshape(v * v, (256, 2, 2, 2, 2)) q = tl.sum(q, axis=3) q = tl.sum(q, axis=2) q = tl.sum(q, axis=1) a = tl.sum(q, axis=1) a = tl.sum(tl.reshape(a, (8, 2, 16)), axis=1) a = tl.sum(tl.reshape(a, (8, 2, 8)), axis=1) a = tl.sum(tl.reshape(a, (8, 2, 4)), axis=1) a = tl.sum(tl.reshape(a, (8, 2, 2)), axis=1) a = tl.sum(tl.reshape(a, (8, 2, 1)), axis=1) a = tl.reshape(a, (8,)) a = tl.sum(tl.reshape(a, (2, 4)), axis=0) a = tl.sum(tl.reshape(a, (2, 2)), axis=0) return tl.sum(a, axis=0)
@triton.jitdef _served_off(W: tl.constexpr): t = tl.arange(0, 256) i = tl.arange(0, 16) return (i[None, :] // 8) * 2048 + t[:, None] * 8 + (i[None, :] % 8)
@triton.jitdef _msg(X0, X1, off, ok, p0, p1, inv, INTERP: tl.constexpr): """message values at element offsets off of one row (or tile): mul.rn(fma.rn(p1, x1, fma.rn(p0, x0, 0)), inv).""" x0 = tl.load(X0 + off, ok, other=0).to(tl.float32) x1 = tl.load(X1 + off, ok, other=0).to(tl.float32) if INTERP: return (p1 * x1 + (p0 * x0 + 0.0)) * inv return tl.fma(p1, x1, tl.fma(p0, x0, 0.0)) * inv
@triton.jitdef _warp_tree(a, BLOCK_M: tl.constexpr, NW4: tl.constexpr): """(BLOCK_M, 32 NW4) per-thread partials -> (BLOCK_M, NW4) warp sums by the butterfly xor 16, 8, 4, 2, 1 (lane 0's value).""" a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 16)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 8)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 4)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 2)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 1)), axis=2) return tl.reshape(a, (BLOCK_M, NW4))
@triton.jitdef _warps_in_order(a, BLOCK_M: tl.constexpr, NW: tl.constexpr, NW4: tl.constexpr, WARP_REV: tl.constexpr = False): """(BLOCK_M, NW4) warp sums -> ((0 + w0) + w1) [+ w2], extracted by splits (no arithmetic). WARP_REV (failing control only): the warps added in reverse order.""" if NW4 == 4: lo, hi = tl.split(tl.reshape(a, (BLOCK_M, 2, 2))) # lo = (w0, w2), hi = (w1, w3) w0, w2 = tl.split(lo) w1, w3 = tl.split(hi) if WARP_REV: if NW == 3: s = ((0.0 + w2) + w1) + w0 else: s = (0.0 + w1) + w0 else: s = (0.0 + w0) + w1 if NW == 3: s = s + w2 else: w0, w1 = tl.split(a) if WARP_REV: s = (0.0 + w1) + w0 else: s = (0.0 + w0) + w1 return s
@triton.jitdef _bank_stats(X0, X1, Q, rows, row_ok, d_rcp, eps, W: tl.constexpr, BLOCK_M: tl.constexpr, NT: tl.constexpr, NC: tl.constexpr, NW: tl.constexpr, NTP: tl.constexpr, INTERP: tl.constexpr, SERVED_ORDER: tl.constexpr, WARP_REV: tl.constexpr = False, CHAIN_REV: tl.constexpr = False): """AttnResFwdKernel's per-row statistics for one query: returns (p0, p1, inv) per row, as (BLOCK_M,) fp32.""" t = tl.arange(0, NTP) t_ok = t < NT s0 = tl.zeros((BLOCK_M, NTP), tl.float32) s1 = tl.zeros((BLOCK_M, NTP), tl.float32) d0 = tl.zeros((BLOCK_M, NTP), tl.float32) d1 = tl.zeros((BLOCK_M, NTP), tl.float32) base = rows[:, None].to(tl.int64) * W mask = row_ok & t_ok[None, :] for cc in tl.static_range(NC): for vv in tl.static_range(4): if CHAIN_REV: # failing control only: the per-thread fma chain walked backwards c = NC - 1 - cc v = 3 - vv else: c = cc v = vv e = 4 * NT * c + 4 * t + v q = tl.load(Q + e, t_ok, other=0) x0 = tl.load(X0 + base + e[None, :], mask, other=0).to(tl.float32) x1 = tl.load(X1 + base + e[None, :], mask, other=0).to(tl.float32) if INTERP: s0 = x0 * x0 + s0 d0 = x0 * q[None, :] + d0 s1 = x1 * x1 + s1 d1 = x1 * q[None, :] + d1 else: s0 = tl.fma(x0, x0, s0) d0 = tl.fma(x0, q[None, :], d0) s1 = tl.fma(x1, x1, s1) d1 = tl.fma(x1, q[None, :], d1) if SERVED_ORDER: ss0 = _warps_in_order(_warp_tree(s0, BLOCK_M, NTP // 32), BLOCK_M, NW, NTP // 32, WARP_REV) ss1 = _warps_in_order(_warp_tree(s1, BLOCK_M, NTP // 32), BLOCK_M, NW, NTP // 32, WARP_REV) dd0 = _warps_in_order(_warp_tree(d0, BLOCK_M, NTP // 32), BLOCK_M, NW, NTP // 32, WARP_REV) dd1 = _warps_in_order(_warp_tree(d1, BLOCK_M, NTP // 32), BLOCK_M, NW, NTP // 32, WARP_REV) else: # failing control: one plain tl.sum per row ss0 = tl.sum(s0, axis=1) ss1 = tl.sum(s1, axis=1) dd0 = tl.sum(d0, axis=1) dd1 = tl.sum(d1, axis=1) if INTERP: r0 = tl.rsqrt(ss0 * d_rcp + eps) r1 = tl.rsqrt(ss1 * d_rcp + eps) l0 = dd0 * r0 l1 = dd1 * r1 mx = tl.maximum(tl.maximum(tl.full((BLOCK_M,), float("-inf"), tl.float32), l0), l1) e0 = tl.exp(dd0 * r0 - mx) e1 = tl.exp(dd1 * r1 - mx) inv = 1.0 / ((0.0 + e0) + e1) else: r0 = libdevice.rsqrt(tl.fma(ss0, d_rcp, eps)) r1 = libdevice.rsqrt(tl.fma(ss1, d_rcp, eps)) l0 = dd0 * r0 l1 = dd1 * r1 mx = tl.maximum(tl.maximum(tl.full((BLOCK_M,), float("-inf"), tl.float32), l0), l1) e0 = libdevice.exp(tl.fma(dd0, r0, -mx)) e1 = libdevice.exp(tl.fma(dd1, r1, -mx)) inv = tl.div_rn(tl.full((BLOCK_M,), 1.0, tl.float32), (0.0 + e0) + e1) return e0 * r0, e1 * r1, inv
@triton.jitdef _row(v, ridx, r): """row r's value of a (BLOCK_M,) vector (one nonzero term: exact).""" return tl.sum(tl.where(ridx == r, v, 0.0), axis=0)
@triton.jitdef _fused_bank_controller( Dest, X0, X1, Query, Down, Gain, Forget, Out, T, DEST_STRIDE, eps, bank_eps, d_rcp, W: tl.constexpr, BLOCK: tl.constexpr, R: tl.constexpr, BLOCK_R: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_N: tl.constexpr, NT: tl.constexpr, NC: tl.constexpr, NW: tl.constexpr, NTP: tl.constexpr, INTERP: tl.constexpr = False, SERVED_ORDER: tl.constexpr = True, NUM_STAGES: tl.constexpr = 3,): m = tl.program_id(0).to(tl.int64) row0 = tl.program_id(1) * BLOCK_M K: tl.constexpr = 2 * W GROUPS: tl.constexpr = (K + 1023) // 1024 cols = tl.arange(0, BLOCK) valid = cols < W ridx = tl.arange(0, BLOCK_M) rows = row0 + ridx row_ok = rows[:, None] < T # pass 0: the bank AttnRes statistics of this controller's query (m) on the row block p0, p1, inv = _bank_stats(X0, X1, Query + m * W, rows, row_ok, d_rcp, bank_eps, W, BLOCK_M, NT, NC, NW, NTP, INTERP, SERVED_ORDER) rstd_d = tl.zeros((BLOCK_M,), tl.float32) rstd_m = tl.zeros((BLOCK_M,), tl.float32) off = _served_off(W) # pass 1: row statistics of dest and of the (recomputed) message, one 1-D row at a time (the served reduction shape) for r in tl.static_range(BLOCK_M): t = (row0 + r).to(tl.int64) ok = (t < T) & (off < W) if SERVED_ORDER: sd = _tree_sumsq(tl.load(Dest + m * DEST_STRIDE + t * W + off, ok, other=0)) sm = _tree_sumsq(_msg(X0 + t * W, X1 + t * W, off, ok, _row(p0, ridx, r), _row(p1, ridx, r), _row(inv, ridx, r), INTERP)) else: dest = tl.load(Dest + m * DEST_STRIDE + t * W + cols, valid & (t < T), other=0) message = _msg(X0 + t * W, X1 + t * W, cols, valid & (t < T), _row(p0, ridx, r), _row(p1, ridx, r), _row(inv, ridx, r), INTERP) sd = tl.sum(dest * dest) sm = tl.sum(message * message) if INTERP: dr = tl.rsqrt(sd / W + eps) mr = tl.rsqrt(sm / W + eps) else: dr = libdevice.rsqrt(tl.div_rn(sd, W) + eps) mr = libdevice.rsqrt(tl.div_rn(sm, W) + eps) rstd_d = tl.where(ridx == r, dr, rstd_d) rstd_m = tl.where(ridx == r, mr, rstd_m) rank = tl.arange(0, BLOCK_R) ks = tl.arange(0, BLOCK_K) Wd = Down + m * R * K rbase = rows[:, None].to(tl.int64) * W # pass 2: down projection of the normalized [dest | message] rows total = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) for group in tl.static_range(GROUPS): partial = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) for tile in tl.range(0, 1024 // BLOCK_K, num_stages=NUM_STAGES): k = group * 1024 + tile * BLOCK_K + ks in_d = k[None, :] < W x = tl.load(Dest + m * DEST_STRIDE + rbase + k[None, :], row_ok & in_d, other=0) y = _msg(X0 + rbase, X1 + rbase, k[None, :] - W, row_ok & (k[None, :] >= W) & (k[None, :] < K), p0[:, None], p1[:, None], inv[:, None], INTERP) xn = tl.where(in_d, x * rstd_d[:, None], y * rstd_m[:, None]) if not INTERP: xn = xn.to(tl.bfloat16) w = tl.load(Wd + rank[None, :] * K + k[:, None], (rank[None, :] < R) & (k[:, None] < K), other=0) partial = tl.dot(xn, w, partial) if group == 0: total = partial else: total = total + partial hidden = total if not INTERP: hidden = total.to(tl.bfloat16) # pass 3: gain / forget and the tanh mix for start in tl.range(0, W, BLOCK_N, num_stages=NUM_STAGES): cn = start + tl.arange(0, BLOCK_N) col_ok = cn[None, :] < W weight_ok = col_ok & (rank[:, None] < R) weights = m * W * R + cn[None, :] * R + rank[:, None] offsets = rbase + cn[None, :] mask = row_ok & col_ok dest_t = tl.load(Dest + m * DEST_STRIDE + offsets, mask, other=0) message_t = _msg(X0 + rbase, X1 + rbase, cn[None, :], mask, p0[:, None], p1[:, None], inv[:, None], INTERP) gain = tl.dot(hidden, tl.load(Gain + weights, weight_ok, other=0)) forget = tl.dot(hidden, tl.load(Forget + weights, weight_ok, other=0)) if INTERP: tf = 1.0 - 2.0 / (tl.exp(2.0 * forget) + 1.0) tg = 1.0 - 2.0 / (tl.exp(2.0 * gain) + 1.0) else: tf = libdevice.tanh(forget) tg = libdevice.tanh(gain) output = (1.0 - tf) * dest_t + tg * message_t tl.store(Out + m * T * W + offsets, output, mask)
_BANK_CFG = {3: (96, 6, 3, 128), 1: (64, 9, 2, 64)} # N_Q -> (AttnRes compute threads, vec chunks, warps, stat tile lanes) at D 2304
def fused_bank_controllers(dest, dest_stride, x0, x1, queries, down, gain, forget, out, eps=1e-6, bank_eps=1e-6, block_m=16, block_k=128, block_n=64, num_warps=8, fp_fusion=False, num_stages=2, served_order=True, loop_stages=3): """dest: base tensor with element stride between controllers (0 = one shared stream), as inkling2_loop._stacked returns; x0 / x1: the two BF16 bank sources (T, W) contiguous; queries: (num, W) fp32 scaled queries; out: (num, T, W) fp32.""" num, rank, k = down.shape tokens, width = out.shape[1], out.shape[2] assert width == 2304 and num in _BANK_CFG and queries.shape == (num, width) nt, nc, nw, ntp = _BANK_CFG[num] assert 4 * nt * nc == width grid = (num, triton.cdiv(tokens, block_m)) _fused_bank_controller[grid]( dest, x0, x1, queries, down, gain, forget, out, tokens, dest_stride, eps, bank_eps, 1.0 / width, width, triton.next_power_of_2(width), rank, max(16, triton.next_power_of_2(rank)), block_m, block_k, block_n, nt, nc, nw, ntp, os.environ.get("TRITON_INTERPRET") == "1", served_order, loop_stages, num_warps=num_warps, num_stages=num_stages, enable_fp_fusion=fp_fusion, ) return out
@triton.jitdef _bank_messages(X0, X1, Query, Out, T, bank_eps, d_rcp, W: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, NT: tl.constexpr, NC: tl.constexpr, NW: tl.constexpr, NTP: tl.constexpr, INTERP: tl.constexpr = False, SERVED_ORDER: tl.constexpr = True, WARP_REV: tl.constexpr = False, CHAIN_REV: tl.constexpr = False): """debug / check kernel: the recomputed messages (num, T, W) fp32, to compare with attn_res bitwise.""" m = tl.program_id(0).to(tl.int64) rows = tl.program_id(1) * BLOCK_M + tl.arange(0, BLOCK_M) row_ok = rows[:, None] < T p0, p1, inv = _bank_stats(X0, X1, Query + m * W, rows, row_ok, d_rcp, bank_eps, W, BLOCK_M, NT, NC, NW, NTP, INTERP, SERVED_ORDER, WARP_REV, CHAIN_REV) rbase = rows[:, None].to(tl.int64) * W for start in tl.range(0, W, BLOCK_N): cn = start + tl.arange(0, BLOCK_N) mask = row_ok & (cn[None, :] < W) tl.store(Out + m * T * W + rbase + cn[None, :], _msg(X0 + rbase, X1 + rbase, cn[None, :], mask, p0[:, None], p1[:, None], inv[:, None], INTERP), mask)
def bank_messages(x0, x1, queries, out, bank_eps=1e-6, block_m=16, block_n=128, num_warps=8, fp_fusion=False, served_order=True, warp_rev=False, chain_rev=False): num, tokens, width = out.shape nt, nc, nw, ntp = _BANK_CFG[num] _bank_messages[(num, triton.cdiv(tokens, block_m))](x0, x1, queries, out, tokens, bank_eps, 1.0 / width, width, block_m, block_n, nt, nc, nw, ntp, os.environ.get("TRITON_INTERPRET") == "1", served_order, warp_rev, chain_rev, num_warps=num_warps, enable_fp_fusion=fp_fusion) return out12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886// 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 <sgl_kernel/tensor.h>
#include <sgl_kernel/utils.cuh>
#include <cuda_bf16.h>
#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 <cstdint>
namespace sglang::n52_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 <int N2>__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<uint4 const*>(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 <int N2>__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<N2>(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 <int N2>__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<uint32_t*>(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 <int N2 = 2304>__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<N2>(p, e, r0, r1, tid, pass, discard); if (pass && r1 == p.offsets[e + 1]) band_tail<N2>(p, e, tid); } } if (tid == 0) p.counters[band] = 0;}
} // namespace sglang::n52_band
namespace cutlass::gemm::kernel {
// ---- N52Kernel: cutlass/gemm/kernel/sm90_gemm_array_tma_warpspecialized_cooperative.hpp (md5 3b39c38d712b5f27af49baea07e8c8b4) with the n52 edits ----using sglang::n52_band::BandParams;using sglang::n52_band::n52_band_hook;
template < class ProblemShape_, class CollectiveMainloop_, class CollectiveEpilogue_, class TileScheduler_>class N52Kernel{ // Get the type of the scheduler response. template<typename TileScheduler, typename = void> struct TileSchedulerResponseGetter { using Type = typename TileScheduler::CLCResponse; };
template<typename TileScheduler> struct TileSchedulerResponseGetter<TileScheduler, void_t<typename TileScheduler::SchedulerResponse>> { 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 <M,N,K> or <M,N,K,L>");
static_assert(cute::is_base_of_v<KernelPtrArrayTmaWarpSpecializedCooperative, typename CollectiveMainloop_::DispatchPolicy::Schedule>);
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<InternalStrideA, StrideA>; static constexpr uint32_t MinTensorMapWorkspaceAlignment = 64;
static_assert( cute::is_void_v<TileScheduler_> or ( IsGroupedGemmKernel and cute::is_any_of_v<TileScheduler_, GroupScheduler> ), "Ptr-Array Cooperative and Grouped Gemm Cooperative kernel only supports the default scheduler.");
using SchedulerTag = cute::conditional_t< cute::is_void_v<TileScheduler_>, 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<cute::is_same_v<SchedulerTag, void>, void, ProblemShape> // Use void for default scheduler. >::Scheduler;
using TileSchedulerArguments = typename TileScheduler::Arguments; using TileSchedulerParams = typename TileScheduler::Params; using TileSchedulerResponse = typename TileSchedulerResponseGetter<TileScheduler>::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<typename CollectiveMainloop::DispatchPolicy>;
/// 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 <typename T> struct IsSm120BlockScaled : cute::false_type {};
template <int Stages, int SchedStages, class ClusterShape, class KernelSchedule> struct IsSm120BlockScaled<MainloopSm120ArrayTmaWarpSpecializedBlockScaled<Stages, SchedStages, ClusterShape, KernelSchedule>> : cute::true_type {};
static constexpr bool IsLowRegisterPressure = IsSm120BlockScaled<DispatchPolicy>::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<typename DispatchPolicy::ArchTag, arch::Sm120>;
// 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<uint8_t*>(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<typename ProblemShape::UnderlyingProblemShape, ElementAccumulator>( 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<typename ProblemShape::UnderlyingProblemShape, ElementAccumulator>( 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<uint8_t*>(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<typename ProblemShape::UnderlyingProblemShape, ElementAccumulator>( 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<typename ProblemShape::UnderlyingProblemShape, ElementAccumulator>( 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<typename CollectiveEpilogue::DispatchPolicy>) { 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<SharedStorage*>(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<SchedulerTag, GroupScheduler>) { 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<TileSchedulerPipeline>(); PipelineState mainloop_pipe_producer_state = cutlass::make_producer_start_state<MainloopPipeline>(); PipelineState epi_load_pipe_producer_state = cutlass::make_producer_start_state<EpiLoadPipeline>(); PipelineState epi_store_pipe_producer_state = cutlass::make_producer_start_state<EpiStorePipeline>();
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<SchedulerTag, GroupScheduler>) { 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<decltype(load_inputs)> >= 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<LoadRegisterRequirement>(); }
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<SchedulerTag, GroupScheduler>) { 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<IsEpiLoad>( 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<IsEpiLoad>(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<IsEpiLoad>(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<IsEpiLoad>( 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<IsEpiLoad>(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<MmaRegisterRequirement>(); }
// 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<IsEpiLoad>( 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<IsEpiLoad>(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<IsEpiLoad>(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<IsEpiLoad>( 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<IsEpiLoad>(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::n52_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<ElementA>::value;constexpr int AlignmentB = 128 / cutlass::sizeof_bits<ElementB>::value;constexpr int AlignmentD = 128 / cutlass::sizeof_bits<ElementD>::value;using ElementAccumulator = float;using ElementCompute = float;using ElementAMainloop = cutlass::nv_float4_t<ElementA>;using ElementBMainloop = cutlass::nv_float4_t<ElementB>;using ProblemShape = cutlass::gemm::GroupProblemShape<Shape<int, int, int>>;using LayoutA = cutlass::layout::RowMajor;using LayoutB = cutlass::layout::ColumnMajor;using LayoutD = cutlass::layout::RowMajor;using ClusterShape = Shape<_1, _1, _1>;using ThreadBlockShape = Shape<_128, _128, _256>;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, cutlass::epilogue::collective::EpilogueScheduleAuto>::CollectiveOp;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<static_cast<int>(sizeof(typename CollectiveEpilogue::SharedStorage))>, 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; N52Kernel is a copy of that kernel");using GemmKernel = cutlass::gemm::kernel::N52Kernel<ProblemShape, CollectiveMainloop, CollectiveEpilogue, void>;using Gemm = cutlass::gemm::device::GemmUniversalAdapter<GemmKernel>;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 <class T>__host__ __device__ __forceinline__ T* inc_ptr(T* ptr, size_t offset) { constexpr int adjustment = (cutlass::sizeof_bits<T>::value < 8) ? (8 / cutlass::sizeof_bits<T>::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<size_t>(ScaleGranularity) * 4; size_t sf_n = (static_cast<size_t>(n) + alignment_swizzled_mn - 1) / alignment_swizzled_mn * alignment_swizzled_mn; size_t swizzled_k = (static_cast<size_t>(k) + alignment_swizzled_k - 1) / alignment_swizzled_k * alignment_swizzled_k; size_t sf_k = swizzled_k / static_cast<size_t>(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<size_t>(m_offset_next) - static_cast<size_t>(m_offset); size_t sf_m_offset = (static_cast<size_t>(m_offset) + static_cast<size_t>(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<size_t>(m_offset) * static_cast<size_t>(k)); B_ptr[i] = inc_ptr(B, static_cast<size_t>(i) * static_cast<size_t>(n) * static_cast<size_t>(k)); D_ptr[i] = D + static_cast<size_t>(m_offset) * static_cast<size_t>(n); layout_SFA[i] = ScaleConfig::tile_atom_to_shape_SFA( make_shape(static_cast<int>(m), static_cast<int>(sf_n), static_cast<int>(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<int>(m), static_cast<int>(sf_n), static_cast<int>(swizzled_k), 1)); SFB_ptr[i] = inc_ptr(SFB, static_cast<size_t>(i) * sf_n * sf_k);}
inline size_t align16(size_t x) { return (x + 15) / 16 * 16;}
// 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<kDLCUDA>(); 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<uint8_t>().with_device(device).verify(values); host::TensorMatcher({experts, n, kp}).with_dtype<uint8_t>().with_device(device).verify(weight); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(acc_amax).verify(gammas).verify(out_amax); host::TensorMatcher({experts}).with_dtype<fp32_t>().with_device(device).verify(w_amax); host::TensorMatcher({1}).with_dtype<fp32_t>().with_device(device).verify(w_den); host::TensorMatcher({rows, n}).with_dtype<bf16_t>().with_device(device).verify(d); int const num_groups = static_cast<int>(experts.unwrap()); int const N = static_cast<int>(n.unwrap()), K = static_cast<int>(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<uint8_t*>(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<UnderlyingProblemShape*>(take(num_groups * sizeof(UnderlyingProblemShape))); auto A_ptr = static_cast<ElementA const**>(take(num_groups * sizeof(void*))); auto B_ptr = static_cast<ElementB const**>(take(num_groups * sizeof(void*))); auto D_ptr = static_cast<ElementD**>(take(num_groups * sizeof(void*))); auto SFA_ptr = static_cast<ElementSF const**>(take(num_groups * sizeof(void*))); auto SFB_ptr = static_cast<ElementSF const**>(take(num_groups * sizeof(void*))); auto stride_A = static_cast<StrideA*>(take(num_groups * sizeof(StrideA))); auto stride_B = static_cast<StrideB*>(take(num_groups * sizeof(StrideB))); auto stride_D = static_cast<StrideD*>(take(num_groups * sizeof(StrideD))); auto layout_SFA = static_cast<LayoutSFA*>(take(num_groups * sizeof(LayoutSFA))); auto layout_SFB = static_cast<LayoutSFB*>(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<ElementA*>(values.data_ptr()), static_cast<ElementB*>(weight.data_ptr()), static_cast<ElementSF*>(scales.data_ptr()), static_cast<ElementSF*>(weight_scales.data_ptr()), static_cast<ElementD*>(d.data_ptr()), static_cast<int const*>(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<int>(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<int>(mode); b.counters = static_cast<int*>(counters.data_ptr()); b.d = static_cast<__nv_bfloat16 const*>(d.data_ptr()); b.n = N; b.offsets = static_cast<int const*>(m_indptr.data_ptr()); b.acc_amax = static_cast<float const*>(acc_amax.data_ptr()); b.w_amax = static_cast<float const*>(w_amax.data_ptr()); b.w_den = static_cast<float const*>(w_den.data_ptr()); b.gammas = static_cast<float const*>(gammas.data_ptr()); b.values = static_cast<uint8_t*>(out_values.data_ptr()); b.x_scales = static_cast<uint8_t*>(out_scales.data_ptr()); b.amax_out = static_cast<float*>(out_amax.data_ptr()); b.gate_cap = static_cast<float>(gate_cap); b.up_cap = static_cast<float>(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";}
// ---------------------------------------------------------------------------------------------------------------------------// 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<size_t>(ScaleGranularity) * 4; size_t sf_n = (static_cast<size_t>(n) + alignment_swizzled_mn - 1) / alignment_swizzled_mn * alignment_swizzled_mn; size_t swizzled_k = (static_cast<size_t>(k) + alignment_swizzled_k - 1) / alignment_swizzled_k * alignment_swizzled_k; size_t sf_k = swizzled_k / static_cast<size_t>(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<size_t>(m_offset) + static_cast<size_t>(i) * (alignment_swizzled_mn - 1)) / alignment_swizzled_mn * alignment_swizzled_mn + static_cast<size_t>(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<size_t>(row0) * static_cast<size_t>(k)); B_ptr[t] = inc_ptr(B, static_cast<size_t>(i) * static_cast<size_t>(n) * static_cast<size_t>(k)); D_ptr[t] = D + static_cast<size_t>(row0) * static_cast<size_t>(n); layout_SFA[t] = ScaleConfig::tile_atom_to_shape_SFA( make_shape(static_cast<int>(m), static_cast<int>(sf_n), static_cast<int>(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<int>(m), static_cast<int>(sf_n), static_cast<int>(swizzled_k), 1)); SFB_ptr[t] = inc_ptr(SFB, static_cast<size_t>(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 <int N2>__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<N2>(p, e, row, lane, pass, discard); if (pass && local == cnt - 1) band_tail<N2>(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) { auto device = host::SymbolicDevice{}; device.set_options<kDLCUDA>(); 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<uint8_t>().with_device(device).verify(values); host::TensorMatcher({experts, n, kp}).with_dtype<uint8_t>().with_device(device).verify(weight); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(acc_amax).verify(gammas).verify(out_amax); host::TensorMatcher({experts}).with_dtype<fp32_t>().with_device(device).verify(w_amax); host::TensorMatcher({1}).with_dtype<fp32_t>().with_device(device).verify(w_den); host::TensorMatcher({rows, n}).with_dtype<bf16_t>().with_device(device).verify(d); int const G = static_cast<int>(experts.unwrap()); int const N = static_cast<int>(n.unwrap()), K = static_cast<int>(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"; int const bands = static_cast<int>((R + 127 * int64_t(G)) / 128 + 1); int const nchunks = static_cast<int>((bands + tb - 1) / tb); cudaStream_t stream = host::LaunchKernel::resolve_device(device.unwrap());
uint8_t* ib = static_cast<uint8_t*>(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<UnderlyingProblemShape*>(take(NC * sizeof(UnderlyingProblemShape))); auto A_ptr = static_cast<ElementA const**>(take(NC * sizeof(void*))); auto B_ptr = static_cast<ElementB const**>(take(NC * sizeof(void*))); auto D_ptr = static_cast<ElementD**>(take(NC * sizeof(void*))); auto SFA_ptr = static_cast<ElementSF const**>(take(NC * sizeof(void*))); auto SFB_ptr = static_cast<ElementSF const**>(take(NC * sizeof(void*))); auto stride_A = static_cast<StrideA*>(take(NC * sizeof(StrideA))); auto stride_B = static_cast<StrideB*>(take(NC * sizeof(StrideB))); auto stride_D = static_cast<StrideD*>(take(NC * sizeof(StrideD))); auto layout_SFA = static_cast<LayoutSFA*>(take(NC * sizeof(LayoutSFA))); auto layout_SFB = static_cast<LayoutSFB*>(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<unsigned>((NC + 255) / 256); config.blockDim = 256; config.stream = stream; config.numAttrs = 1; config.attrs = attrs; cudaError_t st = cudaLaunchKernelEx( &config, chunk_args, static_cast<ElementA*>(values.data_ptr()), static_cast<ElementB*>(weight.data_ptr()), static_cast<ElementSF*>(scales.data_ptr()), static_cast<ElementSF*>(weight_scales.data_ptr()), static_cast<ElementD*>(d.data_ptr()), static_cast<int const*>(m_indptr.data_ptr()), N, K, G, nchunks, static_cast<int>(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<int>(mode); b.counters = nullptr; b.d = static_cast<__nv_bfloat16 const*>(d.data_ptr()); b.n = N; b.offsets = static_cast<int const*>(m_indptr.data_ptr()); b.acc_amax = static_cast<float const*>(acc_amax.data_ptr()); b.w_amax = static_cast<float const*>(w_amax.data_ptr()); b.w_den = static_cast<float const*>(w_den.data_ptr()); b.gammas = static_cast<float const*>(gammas.data_ptr()); b.values = static_cast<uint8_t*>(out_values.data_ptr()); b.x_scales = static_cast<uint8_t*>(out_scales.data_ptr()); b.amax_out = static_cast<float*>(out_amax.data_ptr()); b.gate_cap = static_cast<float>(gate_cap); b.up_cap = static_cast<float>(up_cap);
cutlass::KernelHardwareInfo hw_info; hw_info.device_id = device.unwrap().device_id; hw_info.sm_count = static_cast<int>(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; arguments.band.mode = -1; // F2: no in-kernel hook 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<unsigned>(tb * 8); pc.blockDim = 256; pc.stream = stream; pc.numAttrs = 1; pc.attrs = attrs; st = cudaLaunchKernelEx(&pc, chunk_pass<2304>, b, G, c, static_cast<int>(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<N> (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 <int N>__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<true>(); device::PDLTriggerSecondary<true>(); load_offsets(offsets, experts, s_offsets); int32_t const block = threadIdx.x / kSplit, part = threadIdx.x % kSplit; bool const active = block < 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<uint4 const*>(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<E>(v); float amax = block_max_reduce<kThreads>(block_max, red[parity]); uint32_t packed; uint8_t scale_bits; quantize_part<E>(v, amax, block_max, packed, scale_bits); if (active) { if (threadIdx.x == 0) amax_out[row] = amax; store_part<E>(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<kDLCUDA>(); int32_t const experts = sglang::inkling2_routed_quant_sm120::verify_offsets(offsets, device); host::TensorMatcher({rows, 2 * N}).with_dtype<bf16_t>().with_device(device).ensure_alignment(16).verify(acc); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(acc_amax).verify(gammas).verify(amax); host::TensorMatcher({int64_t{experts}}).with_dtype<fp32_t>().with_device(device).verify(w_amax); host::TensorMatcher({1}).with_dtype<fp32_t>().with_device(device).verify(w_denominator); host::TensorMatcher({rows, N / 2}).with_dtype<uint8_t>().with_device(device).ensure_alignment(kPart / 2).verify(values); host::TensorMatcher({scale_rows, N / 16}).with_dtype<uint8_t>().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<int32_t>(sm_count)), split_threads(N), device.unwrap()) .enable_pdl(true)( swiglu_quantize_l5<N>, static_cast<__nv_bfloat16 const*>(acc.data_ptr()), static_cast<float const*>(acc_amax.data_ptr()), static_cast<float const*>(w_amax.data_ptr()), static_cast<float const*>(w_denominator.data_ptr()), static_cast<float const*>(gammas.data_ptr()), static_cast<uint8_t*>(values.data_ptr()), static_cast<uint8_t*>(x_scales.data_ptr()), static_cast<float*>(amax.data_ptr()), static_cast<int32_t const*>(offsets.data_ptr()), experts, static_cast<float>(gate_cap), static_cast<float>(up_cap));}
} // namespace sglang::n52_band123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""n52 F1 (inkling2-spark moe seat, 2026-11-23): SM120 MoE prefill NVFP4 visits with the swiglu + NVFP4 quantization doneinside the gate_up grouped GEMM, per 128-row band, from L2 (n52_band.cuh), EXACT (same outputs bit for bit as S3's visit).
S3's visit (n14 qc, n14_moe.py f9435cd7) is: token-major quantize-once -> FlashInfer gate_up GEMM (BF16 D, 302 MB at 8K)-> the image's nvfp4_swiglu_quantize_routed (reads D back) -> down GEMM -> BF16-direct combine. n52 replaces the middle twoon calls whose gate_up runs the served (swap_ab False, 128, 256) config (> 3,072 tokens at width 2,304): the same GEMM(same CUTLASS types, mainloop and TMA epilogue, so D is the served D) in a kernel copy whose CTAs, after each tile'sepilogue, count the tiles of the tile's 128-row band; the CTA that completes a band runs the image's swiglu + NVFP4arithmetic over the band's rows reading D from L2 and discards the band's D lines from L2 (no DRAM write-back).Everything else (routing, quantize-once, down GEMM, combine, the MXFP8 layers, calls of < 3,073 tokens) is S3's code.
Knobs (env): N52_BAND 2 (pass + discard, the form) | 3 (pass, no discard) | 0 / empty = S3's path. N52_RASTER 1 (tileraster AlongN: a band's 18 tiles run back to back) | 0 (AlongM, the served default). N52_MIN_TOKENS (default 3073).N52_LEAN 1 = build 2: the band pass's two IEEE divides replaced by gate * 0.25 and a mul + 2 fma for up / 25, proven equalon every finite BF16 input (cpu/div25_proof.py); non-finite inputs keep the divide. Separate JIT unit (-DN52_LEAN=1).Graph capture: allocations are torch.empty / torch.zeros per call (graph pool; the counters' memset is a graph node), thelaunch shape depends on the token count only, PDL as served.mb1 (11-24): F1 KILLED on its measured cost (the in-GEMM pass is latency-starved: +15-23 ms per visit). mb2 adds: F2 = gate_up_chunks: the same GEMM (hook off) launched per chunk of TB 128-row bands, each followed by a standalone pass kernel at full occupancy reading D from L2 and discarding it (N52_FORM f2, N52_TB, N52_LEAN, N52_RASTER); L5 = the served GEMM + swiglu_quant_l5, the image's swiglu-quant kernel line for line with the proven divide rewrite (N52_FORM l5, N52_LEAN 1); with N52_LEAN 0 the same entry is C5, a verbatim copy of the image kernel (the copy null).N52_FORM (env, default f1 = the mb1 path when N52_BAND is 2 / 3)."""import loggingimport os
import torch
from sglang.kernels.jit.utils import cache_once, load_jit
logger = logging.getLogger(__name__)_B = os.environ.get("N52_BAND", "2").strip()BAND = int(_B) if _B not in ("", "0") else 0RASTER = int(os.environ.get("N52_RASTER", "1"))MIN_TOKENS = int(os.environ.get("N52_MIN_TOKENS", "3073"))LEAN = int(os.environ.get("N52_LEAN", "0"))FORM = os.environ.get("N52_FORM", "f1").strip()TB = int(os.environ.get("N52_TB", "16"))_INSTALLED = False_SM = {}
@cache_oncedef _module(lean: int = 0): import flashinfer
data = os.path.join(os.path.dirname(flashinfer.__file__), "data") return load_jit( "n52_band", str(int(lean)), cuda_files=["inkling2/n52_band.cuh"], cuda_wrappers=[("gate_up_band", "n52_band::gate_up_band"), ("gate_up_chunks", "n52_band::gate_up_chunks"), ("swiglu_quant_l5", "n52_band::swiglu_quant_l5")], 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)}"], )
def _sm_count(device): k = device.index if device.index is not None else torch.cuda.current_device() if k not in _SM: _SM[k] = torch.cuda.get_device_properties(k).multi_processor_count return _SM[k]
def gate_up_band(layer, values, scales, amax, gammas, offsets, mode=None, raster=None, d=None, lean=None): """= image nvfp4_routed_swiglu_quantize(nvfp4_expert_matmul(values, scales, w13, ...), amax, ...) in one GEMM launch. mode: 2 pass + discard, 3 pass only; timing twins: -1 no hook, 0 signal only, 1 discard only (outputs not written).""" 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 = LEAN if lean is None else int(lean) if lean and (float(layer.gate_cap), float(layer.up_cap)) != (4.0, 25.0): raise ValueError("n52 lean build is compiled for MLP softcaps (4, 25)") qv, qs, qa = ex._nvfp4_outputs(rows=rows, width=n // 2, experts=experts, device=values.device) if rows: dev = values.device if d is None: d = torch.empty((rows, n), dtype=torch.bfloat16, device=dev) counters = torch.zeros((rows + 127 * experts) // 128 + 1, dtype=torch.int32, device=dev) iw = torch.empty(1 << 20, dtype=torch.uint8, device=dev) fw = torch.empty(4 << 20, dtype=torch.uint8, device=dev) _module(lean).gate_up_band( 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, counters, iw, fw, float(layer.gate_cap), float(layer.up_cap), BAND if mode is None else mode, RASTER if raster is None else raster, _sm_count(dev), ) return qv, qs, qa
def _lean_ok(layer, lean): if lean and (float(layer.gate_cap), float(layer.up_cap)) != (4.0, 25.0): raise ValueError("n52 lean build is compiled for MLP softcaps (4, 25)")
def gate_up_chunks(layer, values, scales, amax, gammas, offsets, mode=2, raster=0, tb=None, lean=None): """F2: = image nvfp4_routed_swiglu_quantize(nvfp4_expert_matmul(...)) by chunked GEMM launches + an L2 pass per chunk.""" 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 = LEAN if lean is None else int(lean) _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) _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), int(raster), int(TB if tb is None else tb), _sm_count(dev), ) return qv, qs, qa
def swiglu_l5(layer, gate_up, amax, gammas, offsets, lean=None): """L5 (lean 1) / C5 (lean 0): = image nvfp4_routed_swiglu_quantize(gate_up, amax, ...) by the n52 copy of its kernel.""" from sglang.kernels.ops.moe import inkling2_experts_sm120 as ex
lean = LEAN if lean is None else int(lean) _lean_ok(layer, lean) rows, width = gate_up.shape[0], gate_up.shape[1] // 2 qv, qs, qa = ex._nvfp4_outputs(rows=rows, width=width, experts=offsets.numel() - 1, device=gate_up.device) if rows: _module(lean).swiglu_quant_l5( gate_up, amax, layer.w13_amax, layer.w13_outer_scale_denominator, gammas, qv, qs, qa, offsets, float(layer.gate_cap), float(layer.up_cap), _sm_count(gate_up.device), ) return qv, qs, qa
def uses_band(layer, tokens): from sglang.kernels.ops.gemm import inkling2_grouped_sm120 as grouped_sm120
return ( BAND in (2, 3) and tokens >= MIN_TOKENS and layer._routed_kernels == torch.uint8 and layer.w13_weight.shape[1] == 2304 and grouped_sm120._tiles(tokens=tokens, width=layer.w13_weight.shape[2] * 2) == (False, 128, 256) )
def forward_sm120(self, x, weights, ids, combine, mode=None, raster=None, lean=None, form=None, tb=None): """S3's n14 forward_sm120(mode 'qc') on an NVFP4 layer with the gate_up GEMM + swiglu-quant replaced by the n52 form (f1 gate_up_band, f2 gate_up_chunks, l5 the served GEMM + swiglu_l5).""" from sglang.kernels.ops.gemm import inkling2_grouped_sm120 as grouped_sm120 from sglang.srt.models.inkling_common import n14_moe as N14 from sglang.srt.models.inkling_common.inkling2_moe import RoutedOutput
tokens, top_k = ids.shape src2dst, dst2src, gammas, offsets = self._sm120_route(ids, weights) x = x.contiguous() values, scales, amax = N14.nvfp4_token_quantize(x, src2dst, top_k, offsets) form = FORM if form is None else form if form == "f2": values, scales, amax = gate_up_chunks(self, values, scales, amax, gammas, offsets, mode=2 if mode is None else mode, raster=0 if raster is None else raster, tb=tb, lean=lean) elif form == "l5": gate_up = grouped_sm120.nvfp4_expert_matmul(values=values, scales=scales, weight=self.w13_weight, weight_scales=self.w13_scale, offsets=offsets, tokens=tokens) values, scales, amax = swiglu_l5(self, gate_up, amax, gammas, offsets, lean=lean) else: values, scales, amax = gate_up_band(self, values, scales, amax, gammas, offsets, mode=mode, raster=raster, lean=lean) down = grouped_sm120.nvfp4_expert_matmul( values=values, scales=scales, weight=self.w2_weight, weight_scales=self.w2_scale, offsets=offsets, tokens=tokens ) out = N14.routed_partial_bf16( down, offsets, src2dst, top_k, nvfp4_scales=(amax, self.w2_amax, self.w2_outer_scale_denominator) ) return out if combine else RoutedOutput(out, None, 0)
def install(): """Chain after n14's install (S3's inkling2_attn.py calls n14_moe.install() first): NVFP4 calls the band form takes go to forward_sm120 above (n14 qc + the band GEMM); every other call goes to the method n14 installed.""" global _INSTALLED if _INSTALLED: return _INSTALLED = True if BAND not in (2, 3): logger.warning("n52: N52_BAND %r, S3 MoE path", _B) return from sglang.srt.models.inkling_common import inkling2_moe as M
prev = M.Inkling2Experts._forward_sm120
def _forward_sm120(self, x, weights, ids, combine): if x.dtype == torch.bfloat16 and uses_band(self, ids.shape[0]): return forward_sm120(self, x, weights, ids, combine) return prev(self, x, weights, ids, combine)
M.Inkling2Experts._forward_sm120 = _forward_sm120 logger.warning("n52: band gate_up on NVFP4 calls >= %d tokens (band %d, raster %s, lean %d)", MIN_TOKENS, BAND, "N" if RASTER else "M", LEAN)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233"""n64 (inkling2-spark attn seat): global-layer prefill attention as two kernels, bitwise equal to n54's served kernel. kernel A = FlashAttentionForwardSm120BandOnly (fa4_sm120/n64a_fwd.py): n54's band-split kernel (n32 producer + n13 consumer) on the first / causal-mask / bias-band key blocks, storing each thread's raw state (fragment order); kernel B = FlashAttentionForwardSm120W8Far (fa4_sm120/n64b_fwd.py): 8 consumer warps (2 per SM sub-partition, setmaxnreg) continuing that state over the far blocks with n54's far-loop arithmetic, then the served finalize + epilogue.Installed AFTER n32_attn_local (its wrapper stays the entry point for every other call). A global-layer call that n32 wouldrun in-kernel (N32RelBias, window (-1, -1), n32.eligible) goes through A then B when SGLANG_INKLING_N64=1 and the KV spanbound (page_table width x page size) is >= SGLANG_INKLING_N64_MIN_K; anything else is passed on unchanged.Workspace: stO fp32 (H, Tpad * 128) + stS fp32 (H, Tpad * 16), Tpad = tokens + 128 x sequences, allocated eagerly andreused; a call that needs more, or arrives inside a CUDA-graph capture without a big enough buffer, takes n54's path."""import loggingimport os
import torch
logger = logging.getLogger(__name__)MODE = os.environ.get("SGLANG_INKLING_N64", "0") # "0" n54's path, "1" the pair, "check" = check boot (below)ENABLED = MODE in ("1", "check")# check (n64-p1 check boot, the n50 pattern): every eligible global call runs n54's served path into scratch, the pair into the# caller's out (RETURNED, so the boot's logprobs / KLD / smoke read the pair's numerics) and a failing control (kernel B with# the unbiased folded scale, its own compile key via a third dummy aux tensor) into scratch, and adds into a device counter:# [0] pair out words != served (both-NaN excluded), [1] calls, [2] out words compared, [3] control out words != served,# [4] pair LSE words != served, [5] real tokens, [6] control LSE words != served, [7] PADDED-row out words that differ# (reported only; real-row counters [0] [2] [3] [4] [6] mask rows >= cu_seqlens_q[-1]). Graph replays count too# (the counting ops are captured); the counter is copied to pinned host memory by a one-program Triton kernel each call and a# daemon thread prints "N64CHECK ..." to stderr every 10 s when it changed.MIN_K = int(os.environ.get("SGLANG_INKLING_N64_MIN_K", "0"))MAX_ROWS = int(os.environ.get("SGLANG_INKLING_N64_MAX_ROWS", "16384")) # Tpad cap of the preallocated workspacePREALLOC_HEADS = int(os.environ.get("SGLANG_INKLING_N64_PREALLOC_HEADS", "0")) # served: 24 (q heads per rank)PHASE = [None] # None | "A" | "B": set around the two interface calls, read by the make_kernel / thread-count hooksSTATS = {"pair": 0, "passed": 0, "built_a": 0, "built_b": 0, "too_big": 0}_WS = {}_INSTALLED = False_CHK = {}
import triton # noqa: E402import triton.language as tl # noqa: E402
@triton.jitdef _n64_publish(Src, Dst, N: tl.constexpr): # check mode: copy the device counter into pinned host memory (graph replays included), as n50's _n50_publish i = tl.arange(0, N) tl.store(Dst + i, tl.load(Src + i))
def _check_init(device): import sys import threading import time
_CHK["pub"] = _n64_publish _CHK["count"] = torch.zeros(8, dtype=torch.int64, device=device) _CHK["host"] = torch.zeros(8, dtype=torch.int64, pin_memory=True) _CHK["dummy"] = torch.zeros(4, dtype=torch.int32, device=device) _CHK["dummy"].__assumed_align__ = 16 _CHK["dummy"].__leading_dim__ = 0 print(f"N64CHECK init capturing={torch.cuda.is_current_stream_capturing()} pid={os.getpid()}", file=sys.stderr, flush=True)
def line(c): return (f"N64CHECK words={c[0]} calls={c[1]} compared={c[2]} ctl_words={c[3]} lse_words={c[4]} tokens={c[5]}" f" ctl_lse_words={c[6]} pad_words={c[7]} t={time.strftime('%H:%M:%S', time.gmtime())}")
_CHK["line"] = line
def report(): last = None while True: time.sleep(10) c = _CHK["host"].tolist() if c != last: print(line(c), file=sys.stderr, flush=True) last = c
threading.Thread(target=report, daemon=True, name="n64check").start()
def _words_ne(a, b): return (a.contiguous().view(torch.int32) != b.contiguous().view(torch.int32)).sum()
def _workspace(h, rows, device): key = (str(device), h) ws = _WS.get(key) if ws is None or ws[0] < rows: if torch.cuda.is_current_stream_capturing() or rows > MAX_ROWS: return None cap = max(rows, MAX_ROWS) st_o = torch.empty(h, cap * 128, dtype=torch.float32, device=device) st_s = torch.empty(h, cap * 16, dtype=torch.float32, device=device) ws = _WS[key] = (cap, st_o, st_s) st_o, st_s = ws[1], ws[2] for t in (st_o, st_s): t.__assumed_align__ = 16 t.__leading_dim__ = 1 return st_o, st_s
def install(): global _INSTALLED if _INSTALLED: return from sglang.kernels.ops.attention.fa4_sm120 import runtime as _rt from sglang.kernels.ops.attention.fa4_sm120 import flash_fwd as _ff from sglang.kernels.ops.attention.fa4_sm120.n64a_fwd import FlashAttentionForwardSm120BandOnly from sglang.kernels.ops.attention.fa4_sm120.n64b_fwd import FlashAttentionForwardSm120W8Far from sglang.kernels.ops.attention.flash_attn.cute import interface as _itf from sglang.srt.models.inkling_common import n32_attn_local as _h32
prev_mk = _rt.Sm120ForwardPolicy.make_kernel
def make_kernel(**kw): k = prev_mk(**kw) if PHASE[0] == "A" and type(k).__name__ == "FlashAttentionForwardSm120BandSplitRelProd": k.__class__ = FlashAttentionForwardSm120BandOnly STATS["built_a"] += 1 logger.warning("n64: kernel A (band part + state store) built, tile %s x %s", k.tile_m, k.tile_n) elif (PHASE[0] in ("B", "Bctl") and type(k) is _ff.FlashAttentionForwardSm120 and not k.has_bias and (k.tile_m, k.tile_n, k.num_threads) == (128, 128, 256)): k.__class__ = FlashAttentionForwardSm120W8Far STATS["built_b"] += 1 logger.warning("n64: kernel B (W8 far part, 8 consumer warps) built") return k
_rt.Sm120ForwardPolicy.make_kernel = staticmethod(make_kernel) prev_nt = _ff.FlashAttentionForwardSm120.get_fwd_num_threads
def get_fwd_num_threads(head_dim, head_dim_v, tile_m, tile_n, paged_kv=False): if PHASE[0] in ("B", "Bctl") and (head_dim, head_dim_v, tile_m, tile_n) == (128, 128, 128, 128): return 256 return prev_nt(head_dim, head_dim_v, tile_m, tile_n, paged_kv=paged_kv)
_ff.FlashAttentionForwardSm120.get_fwd_num_threads = staticmethod(get_fwd_num_threads) prev_fwd = _itf._flash_attn_fwd
def _flash_attn_fwd(q, k, v, *args, **kw): rb = kw.get("rel_bias") if (ENABLED and not args and isinstance(rb, _h32.N32RelBias) and _h32.GLOBAL and kw.get("window_size_left") in (None, -1) and kw.get("window_size_right") in (None, -1) and _h32.eligible(q, k, v, kw, rb) and k.shape[1] * kw["page_table"].shape[1] >= MIN_K): p32 = _h32._p32(rb.mod.proj) nseq = kw["cu_seqlens_q"].shape[0] - 1 ws = _workspace(q.shape[1], q.shape[0] + 128 * nseq, q.device) if p32 is not None else None if ws is not None: st_o, st_s = ws tpad = -(-q.shape[0] // 64) * 64 e_pad = rb.mod.proj.shape[1] + 256 dkey = (str(q.device), e_pad) base = _h32._BASE.get(dkey) if base is None: base = _h32._BASE[dkey] = torch.empty(e_pad, dtype=torch.bfloat16, device=q.device) kw_a = dict(kw) kw_a["rel_bias"] = base.as_strided((tpad, q.shape[1], e_pad), (0, 0, 1)) kw_a["rel_bias_presheared"] = True kw_a["rel_bias_prep_cache"] = None kw_a["aux_tensors"] = [_h32._r32(rb.r), p32, st_o, st_s] kw_b = {x: y for x, y in kw.items() if x not in ("rel_bias", "rel_bias_presheared", "rel_bias_prep_cache")} kw_b["tile_mn"] = (128, 128) kw_b["aux_tensors"] = [st_o, st_s] STATS["pair"] += 1 if STATS["pair"] <= 2: logger.warning("n64: global call %d through kernels A + B, tokens %d", STATS["pair"], q.shape[0]) if MODE == "check": if not _CHK: _check_init(q.device) kw_ref = dict(kw) kw_ref["out"] = torch.empty_like(kw["out"]) if kw.get("out") is not None else None if kw.get("lse") is not None: # never share a caller lse buffer with the reference or the control kw_ref["lse"] = torch.empty_like(kw["lse"]) ref = prev_fwd(q, k, v, **kw_ref) # n54's served path (n32 wrapper), scratch out PHASE[0] = "A" try: prev_fwd(q, k, v, **kw_a) finally: PHASE[0] = None PHASE[0] = "B" try: res = prev_fwd(q, k, v, **kw_b) finally: PHASE[0] = None if MODE == "check": from sglang.kernels.ops.attention.fa4_sm120 import n64b_fwd as _nb
kw_c = dict(kw_b) kw_c["out"] = torch.empty_like(kw["out"]) if kw.get("out") is not None else None if kw.get("lse") is not None: kw_c["lse"] = torch.empty_like(kw["lse"]) kw_c["aux_tensors"] = [st_o, st_s, _CHK["dummy"]] PHASE[0] = "Bctl" _nb.N64_FAR = False # read at trace time only: the control compiles under its own key (3 aux tensors) try: ctl = prev_fwd(q, k, v, **kw_c) finally: PHASE[0] = None _nb.N64_FAR = True c = _CHK["count"] o, ro, co = res[0], ref[0], ctl[0] # real rows only: graph-bucket padding rows (>= cu_seqlens_q[-1]) are written by neither kernel, so the # caller's buffer and a fresh scratch differ there (check boot 1: every mismatch was such a row) real = torch.arange(o.shape[0], device=o.device) < kw["cu_seqlens_q"][-1] rmask = real.view(-1, *([1] * (o.dim() - 1))) both = torch.isnan(o) & torch.isnan(ro) ne = (o.view(torch.int32) != ro.view(torch.int32)) & ~both c[0] += (ne & rmask).sum() c[1] += 1 c[2] += (rmask.expand_as(o)).sum() c[3] += ((co.view(torch.int32) != ro.view(torch.int32)) & rmask).sum() if res[1] is not None and ref[1] is not None: lmask = real.view(1, -1) if res[1].shape[-1] == o.shape[0] else real.view(-1, 1) c[4] += ((res[1].view(torch.int32) != ref[1].view(torch.int32)) & lmask).sum() c[6] += ((ctl[1].view(torch.int32) != ref[1].view(torch.int32)) & lmask).sum() c[5] += real.sum() c[7] += (ne & ~rmask).sum() # padded-row out words that differ (reported, not a bar) _CHK["pub"][(1,)](c, _CHK["host"], 8) return res STATS["too_big"] += 1 if STATS["too_big"] <= 4: logger.warning("n64: global call kept n54's path (workspace %s, capturing %s, tokens %d)", "none" if ws is None else "ok", torch.cuda.is_current_stream_capturing(), q.shape[0]) STATS["passed"] += 1 return prev_fwd(q, k, v, *args, **kw)
_flash_attn_fwd.__dict__ = prev_fwd.__dict__ _itf._flash_attn_fwd = _flash_attn_fwd _INSTALLED = True if ENABLED and PREALLOC_HEADS > 0 and torch.cuda.is_available(): # served: allocate before any CUDA-graph capture (prefill chunks <= 8K tokens replay captured graphs, and a capture # never allocates the workspace), so captured chunks run the pair ws = _workspace(PREALLOC_HEADS, MAX_ROWS, torch.device("cuda", torch.cuda.current_device())) logger.warning("n64: workspace preallocated (%d heads x %d rows: %.0f MB)", PREALLOC_HEADS, MAX_ROWS, 0 if ws is None else (ws[0].numel() + ws[1].numel()) * 4 / 2**20) logger.warning("n64: two-kernel global attention hook installed (mode=%s, min_k=%d)", MODE, MIN_K)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138# Generated by work_attn/gen/gen_n64a.py from n54's fa4_sm120/n32_fwd.py (md5 115d2333) and n13_fwd.py (md5 18257a9c)."""Generate n64a_fwd.py (fa4_sm120/n64a_fwd.py) = n64 exact far form, KERNEL A, from n54's served global-layer kernel files:n32_fwd.py (md5 115d2333, FlashAttentionForwardSm120BandSplitRelProd: n32 in-kernel bias producer) and n13_fwd.py (md518257a9c, n13's band-split consumer mma).
FlashAttentionForwardSm120BandOnly: n54's global-layer prefill kernel (64-row CTAs, 4 consumer warps + the n32 producerwarp) running the first, causal-mask and bias-band key blocks exactly as served, then, instead of n13's far loop and thefinalize / epilogue, storing each consumer thread's raw state for kernel B (n64b_fwd.py) in fragment order:stO (H, Tpad * 128): lane l of the 16-row group starting at padded row grow = offset_q + 128 x batch + 64 m_block + 16 wholds its 64 acc_O values at grow * 128 + 64 l; stS (H, Tpad * 16): (row_max[0..1], lane-partial row_sum[0..1]) atgrow * 16 + 4 l and n_far_top at grow * 16 + 128. The out / LSE tensors are written by kernel B only.Patches (asserted string replacements): __call__ (n32's: 4 aux tensors, keeps [stO, stS] in aux_data), load_paged_persistent(n32's: loads only blocks n_block_max - 1 .. n_far_top, the consumer's count), mma (n13's: no far loop, state storeinstead of finalize + epilogue)."""from sglang.kernels.ops.attention.fa4_sm120 import n13_fwd as _n13from sglang.kernels.ops.attention.fa4_sm120 import n32_fwd as _n32globals().update({k: v for k, v in vars(_n13).items() if not k.startswith("__")})globals().update({k: v for k, v in vars(_n32).items() if not k.startswith("__")})from sglang.kernels.ops.attention.fa4_sm120.n32_fwd import FlashAttentionForwardSm120BandSplitRelProd # noqa: E402import operator # noqa: E402
N64A_CTL = 0 # 1 = failing control for the bitwise checks (quad-reduced row sums stored); never ship
class FlashAttentionForwardSm120BandOnly(FlashAttentionForwardSm120BandSplitRelProd): """n64 kernel A: n54's global-layer kernel without the far blocks; stores the raw state for kernel B."""
@cute.jit def n64_far_top(self, block_info, seqlen, m_block, n_block_min, n_block_max, num_bias_loads): """n13's n_far_top (first block n_block_max - 1, then the causal-mask loop, then the band loop down to n_far_top).""" n_block_upper = cutlass.max(n_block_max - 1, 0) if const_expr(self.is_causal or self.is_local): n_block_upper = cutlass.min( n_block_upper, block_info.get_n_block_min_causal_local_mask(seqlen, m_block, n_block_min) ) return cutlass.max( cutlass.min(n_block_upper, n_block_max - num_bias_loads), block_info.get_n_block_min_before_local_mask(seqlen, m_block, n_block_min), )
# ---- copied from n54's n32_fwd.py / n13_fwd.py and patched (gen_n64a.py) ---- @cute.jit def __call__( self, mQ: cute.Tensor, mK: cute.Tensor, mV: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], softmax_scale: Float32, mCuSeqlensQ: Optional[cute.Tensor] = None, mCuSeqlensK: Optional[cute.Tensor] = None, mSeqUsedQ: Optional[cute.Tensor] = None, mSeqUsedK: Optional[cute.Tensor] = None, mPageTable: Optional[cute.Tensor] = None, window_size_left: Int32 | int | None = None, window_size_right: Int32 | int | None = None, learnable_sink: Optional[cute.Tensor] = None, blocksparse_tensors: Optional[BlockSparseTensors] = None, aux_data: AuxData = AuxData(), mBias: Optional[cute.Tensor] = None, launch_split_combine_early: Int32 = Int32(0), stream: cuda.CUstream = None, ): assert blocksparse_tensors is None, "Block sparsity is not supported on SM120" assert (mBias is not None) == self.has_bias # n32: mBias is a zero-stride stand-in (the presheared-shape argument the interface requires); the kernel reads # r (int32 pairs [T, H, 8]) and proj^T (int32 pairs [E, 8]) from aux_data and builds the sheared tile itself. assert self.has_bias and self.paged_kv and not self.pack_gqa assert not self._uses_split_pv_warps() # n32: row-independent hi - row needs n_idx_right = m_idx + 1 + delta (+ wr): local with a right window, or causal assert (self.is_local and window_size_right is not None) or (self.is_causal and not self.is_local) # n64 kernel A: aux tensors = [r32, proj^T, stO, stS]; the state tensors stay in aux_data for mma assert aux_data.tensors is not None and len(aux_data.tensors) == 4 n32_r32, n32_p32 = aux_data.tensors[0], aux_data.tensors[1] aux_data = AuxData(tuple(aux_data.tensors[2:])) mBias = None assert mPageTable is None or self.paged_kv, ( "SM120 paged KV requires the dedicated DMA-warp specialization" ) self._check_type( *( t.element_type if t is not None else None for t in ( mQ, mK, mV, mO, mLSE, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, ) ) ) tiled_mma_qk, tiled_mma_pv = self._get_tiled_mma() self.num_qk_threads = tiled_mma_qk.size self.num_mma_threads = tiled_mma_pv.size self.num_producer_threads = self.num_threads self.num_Q_load_threads = ( self.num_qk_threads if self._uses_split_pv_warps() else self.num_threads ) self.num_epilogue_threads = ( self.num_mma_threads if self._uses_split_pv_warps() else self.num_threads ) self.use_tma_O = False self._setup_attributes() SharedStorage = self._get_shared_storage_cls()
mQ, mK, mV, mO = [assume_tensor_aligned(t) for t in (mQ, mK, mV, mO)] if const_expr(mBias is not None): assert mBias.element_type == self.dtype mBias = assume_tensor_aligned(mBias) Q_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensQ is None) else [0, 2, 1] ) KV_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensK is None) else [0, 2, 1] ) mQ = cute.make_tensor( mQ.iterator, cute.select(mQ.layout, mode=Q_layout_transpose) ) if const_expr(mBias is not None): mBias = cute.make_tensor( mBias.iterator, cute.select(mBias.layout, mode=Q_layout_transpose), ) mK, mV = [ cute.make_tensor( t.iterator, cute.select(t.layout, mode=KV_layout_transpose) ) for t in (mK, mV) ] if const_expr(mPageTable is None): V_layout_transpose = ( [1, 0, 2, 3] if const_expr(mCuSeqlensK is None) else [1, 0, 2] ) mV = cute.make_tensor( mV.iterator, cute.select(mV.layout, mode=V_layout_transpose) ) if const_expr(self.is_split_kv): num_splits = mO.shape[0] O_layout_transpose = ( [2, 4, 3, 1, 0] if const_expr(mCuSeqlensQ is None) else [1, 3, 2, 0] ) LSE_layout_transpose = ( [3, 2, 1, 0] if const_expr(mCuSeqlensQ is None) else [2, 1, 0] ) else: num_splits = Int32(1) O_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensQ is None) else [0, 2, 1] ) LSE_layout_transpose = ( [2, 1, 0] if const_expr(mCuSeqlensQ is None) else [1, 0] ) mO = cute.make_tensor( mO.iterator, cute.select(mO.layout, mode=O_layout_transpose) ) if const_expr(mLSE is not None): mLSE = cute.make_tensor( mLSE.iterator, cute.select(mLSE.layout, mode=LSE_layout_transpose) ) if const_expr(self.pack_gqa): nheads_kv = mK.shape[2] mQ = pack_gqa_layout(mQ, self.qhead_per_kvhead, nheads_kv, head_idx=2) mO = pack_gqa_layout(mO, self.qhead_per_kvhead, nheads_kv, head_idx=2) if const_expr(mLSE is not None): mLSE = pack_gqa_layout( mLSE, self.qhead_per_kvhead, nheads_kv, head_idx=1 ) if const_expr(mBias is not None): mBias = pack_gqa_layout( mBias, self.qhead_per_kvhead, nheads_kv, head_idx=2 )
if const_expr(mPageTable is None or self.paged_tma): tma_copy_op = cpasync.CopyBulkTensorTileG2SOp() mV_tma = ( mV if const_expr(mPageTable is None) else cute.make_tensor( mV.iterator, cute.select(mV.layout, mode=[1, 0, 2, 3]), ) ) tma_atom_K, tma_tensor_K = cpasync.make_tiled_tma_atom( tma_copy_op, mK, cute.select(self.sK_layout, mode=[0, 1]), (self.tile_n, self.tile_hdim), 1, ) tma_atom_V, tma_tensor_V = cpasync.make_tiled_tma_atom( tma_copy_op, mV_tma, cute.select(self.sV_layout, mode=[0, 1]), (self.tile_hdimv, self.tile_n), 1, ) self.tma_copy_bytes_K = cute.size_in_bytes( mK.element_type, cute.select(self.sK_layout, mode=[0, 1]) ) self.tma_copy_bytes_V = cute.size_in_bytes( mV_tma.element_type, cute.select(self.sV_layout, mode=[0, 1]), ) else: tma_atom_K = None tma_atom_V = None tma_tensor_K = mK tma_tensor_V = mV # n32: no bias TMA; the kernel's mBias / tma_atom_Bias slots carry r32 / p32. tma_tensor_Bias = n32_r32 tma_atom_Bias = n32_p32
is_varlen = const_expr(mCuSeqlensQ is not None or mSeqUsedQ is not None) num_batch = ( mCuSeqlensQ.shape[0] - 1 if const_expr(mCuSeqlensQ is not None) else cute.size(mQ.shape[3]) ) TileScheduler = ( Sm120UniformBatchScheduler if is_varlen and self.direct_uniform_batch else SingleTileVarlenScheduler if is_varlen else SingleTileScheduler ) tile_sched_args = TileSchedulerArguments( num_block=cute.ceil_div(cute.size(mQ.shape[0]), self.tile_m), num_head=cute.size(mQ.shape[2]), num_batch=num_batch, num_splits=num_splits, seqlen_k=0, headdim=mQ.shape[1], headdim_v=mO.shape[1], total_q=( cute.size(mQ.shape[0]) if const_expr(mCuSeqlensQ is not None) else cute.size(mQ.shape[0]) * cute.size(mQ.shape[3]) ), tile_shape_mn=(self.tile_m, self.tile_n), lpt=(self.is_causal or self.is_local) and not self.direct_uniform_batch, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), mCuSeqlensQ=mCuSeqlensQ, mSeqUsedQ=mSeqUsedQ, is_persistent=False, is_split_kv=self.is_split_kv, ) tile_sched_params = TileScheduler.to_underlying_arguments( tile_sched_args, scheduling_mode=SchedulingMode.STATIC, ) grid_dim = TileScheduler.get_grid_shape(tile_sched_params) if const_expr(self.has_bias): base_softmax_scale = softmax_scale softmax_scale_log2, softmax_scale = utils.LOG2_E, None else: base_softmax_scale = None softmax_scale_log2, softmax_scale = utils.compute_softmax_scale_log2( softmax_scale, self.score_mod ) window_size_left = ( Int32(window_size_left) if window_size_left is not None else None ) window_size_right = ( Int32(window_size_right) if window_size_right is not None else None ) fastdiv_mods = utils.compute_fastdiv_mods( mQ, mK, self.qhead_per_kvhead, self.pack_gqa, aux_data.tensors, mPageTable, )
self.kernel( mQ, tma_tensor_K, tma_tensor_V, mO, mLSE, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, tma_tensor_Bias, tma_atom_K, tma_atom_V, tma_atom_Bias, softmax_scale_log2, softmax_scale, base_softmax_scale, window_size_left, window_size_right, learnable_sink, self.sQ_layout, self.sK_layout, self.sV_layout, self.sO_layout, self.sP_layout, self.sBias_layout, self.gmem_tiled_copy_Q, self.gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, SharedStorage, tile_sched_params, TileScheduler, launch_split_combine_early, aux_data, fastdiv_mods, ).launch( grid=grid_dim, block=[self.num_threads + self._num_dma_threads(), 1, 1], smem=SharedStorage.size_in_bytes(), stream=stream, min_blocks_per_mp=1, # The immediately preceding ShearingBias grid releases this # dependent launch before all of its CTAs have retired. Bias # readers synchronize before their first TMA issue below; the # remaining kernel prologue can overlap the tail of the shear. use_pdl=False, # n32: no shear grid precedes this kernel )
@cute.jit def load_paged_persistent( self, mK: cute.Tensor, mV: cute.Tensor, mPageTable: cute.Tensor, tma_atom_K: Optional[cute.CopyAtom], tma_atom_V: Optional[cute.CopyAtom], sK: cute.Tensor, sV: cute.Tensor, pipeline_k: PipelineAsync, pipeline_v: PipelineAsync, tile_scheduler: TileSchedulerProtocol, mQ: cute.Tensor, mCuSeqlensQ: Optional[cute.Tensor], mSeqUsedQ: Optional[cute.Tensor], mSeqUsedK: Optional[cute.Tensor], window_size_left: Optional[Int32], window_size_right: Optional[Int32], tidx: Int32, mBias: Optional[cute.Tensor] = None, sBias: Optional[cute.Tensor] = None, tma_atom_Bias: Optional[cute.Tensor] = None, # n32: proj^T int32 pairs; mBias = r int32 pairs pipeline_bias: Optional[PipelineAsync] = None, ): producer_state_k = PipelineState( self._num_k_stages(), Int32(0), Int32(0), Int32(1) ) producer_state_v = PipelineState( self._num_v_stages(), Int32(0), Int32(0), Int32(1) ) block_info = BlockInfo( self.tile_m, self.tile_n, self.is_causal, self.is_local, self.is_split_kv, window_size_left, window_size_right, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), ) work_tile = tile_scheduler.initial_work_tile_info() m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx seqlen = SeqlenInfoQK.create( batch_idx=batch_idx, seqlen_q_static=( mQ.shape[0] if const_expr(not self.pack_gqa) else mQ.shape[0][1] ), seqlen_k_static=mK.shape[0] * mPageTable.shape[1], mCuSeqlensQ=mCuSeqlensQ, mCuSeqlensK=None, mSeqUsedQ=mSeqUsedQ, mSeqUsedK=mSeqUsedK, tile_m=self.tile_m, tile_n=self.tile_n, ) n_block_min, n_block_max = self._get_n_block_min_max( block_info, seqlen, m_block, split_idx, tile_scheduler.params.num_splits, ) head_idx_kv = ( head_idx if const_expr(self.pack_gqa) else head_idx // self.qhead_per_kvhead ) bias_max_idx, num_bias_loads = Int32(0), Int32(0) if const_expr(self.has_bias): bias_max_idx, num_bias_loads = self._get_bias_load_info( block_info, seqlen, m_block, n_block_min, n_block_max, ) # n32: per-lane A fragments of r for the tile's rows and the rows' visible key bounds. n32_ra, n32_lo, n32_hi = self.n32_tile_setup( mBias, block_info, seqlen, m_block, head_idx, tidx ) if const_expr(self.is_local): n32_pmax = cutlass.min( window_size_left + window_size_right, self.n32_extent - 1 ) else: n32_pmax = Int32(self.n32_extent - 1) assert not self.paged_tma # n32: page-TMA path not built if const_expr(self.paged_tma): mK_cur = mK[None, None, head_idx_kv, None] mV_cur = mV[None, None, head_idx_kv, None] gK = cute.local_tile( mK_cur, (self.tile_n, self.tile_hdim), (0, 0, None), ) gV = cute.local_tile( mV_cur, (self.tile_hdimv, self.tile_n), (0, 0, None), ) copy_K, _, _ = copy_utils.tma_get_copy_fn( tma_atom_K, 0, cute.make_layout(1), gK, sK, ) copy_V, _, _ = copy_utils.tma_get_copy_fn( tma_atom_V, 0, cute.make_layout(1), gV, sV, ) num_n_blocks = cutlass.max(n_block_max - n_block_min, 1) for n_tile in cutlass.range(num_n_blocks, unroll=1): n_block = cutlass.max(n_block_max - 1 - n_tile, n_block_min) page_idx = mPageTable[batch_idx, n_block]
if const_expr(self.has_bias): if n_tile < num_bias_loads: pipeline_bias.producer_acquire(producer_state_k) cute.copy( tma_atom_Bias, tBgBias[None, m_block, bias_max_idx - n_tile], tBsBias[None, producer_state_k.index], tma_bar_ptr=pipeline_bias.producer_get_barrier( producer_state_k ), ) pipeline_bias.producer_commit(producer_state_k) pipeline_k.producer_acquire(producer_state_k) copy_K( src_idx=page_idx, dst_idx=producer_state_k.index, tma_bar_ptr=pipeline_k.producer_get_barrier(producer_state_k), ) pipeline_k.producer_commit(producer_state_k) producer_state_k.advance()
pipeline_v.producer_acquire(producer_state_v) copy_V( src_idx=page_idx, dst_idx=producer_state_v.index, tma_bar_ptr=pipeline_v.producer_get_barrier(producer_state_v), ) pipeline_v.producer_commit(producer_state_v) producer_state_v.advance()
pipeline_k.producer_tail(producer_state_k) pipeline_v.producer_tail(producer_state_v) return
paged_kv_manager = Sm120PagedKVManager.create( mPageTable, mK, mV, FastDivmodDivisor(mK.shape[0]), batch_idx, head_idx_kv, tidx, seqlen.seqlen_k, 0, self.tile_n, self.tile_hdim, self.tile_hdimv, self.num_dma_threads, mK.element_type, ) # n64 kernel A: only the first / causal-mask / bias-band blocks (the consumer's count); far blocks are kernel B's num_n_blocks = cutlass.max( n_block_max - self.n64_far_top(block_info, seqlen, m_block, n_block_min, n_block_max, num_bias_loads), 1 ) for n_tile in cutlass.range(num_n_blocks, unroll=1): n_block = cutlass.max(n_block_max - 1 - n_tile, n_block_min) paged_kv_manager.load_page_table(n_block)
pipeline_k.producer_acquire(producer_state_k) paged_kv_manager.load_KV( n_block, sK[None, None, producer_state_k.index], "K", ) cute.arch.cp_async_commit_group() pipeline_k.producer_commit(producer_state_k) if const_expr(self.has_bias): # n32: the sheared bias tile of key block n_block (the served TMA source block bias_max_idx - n_tile # holds keys n_block * tile_n + col), computed while K is in flight; same pipeline state as the TMA. if n_tile < num_bias_loads: pipeline_bias.producer_acquire(producer_state_k) self.n32_bias_tile( sBias[None, None, producer_state_k.index], tma_atom_Bias, n32_ra, n32_lo, n32_hi, n32_pmax, n_block, seqlen, m_block, tidx, ) pipeline_bias.producer_commit(producer_state_k) producer_state_k.advance()
pipeline_v.producer_acquire(producer_state_v) sV_stage = layout_utils.transpose_view( sV[None, None, producer_state_v.index] ) paged_kv_manager.load_KV(n_block, sV_stage, "V") cute.arch.cp_async_commit_group() pipeline_v.producer_commit(producer_state_v) producer_state_v.advance()
pipeline_k.producer_tail(producer_state_k) pipeline_v.producer_tail(producer_state_v)
@cute.jit def mma( self, mQ: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], sQ: cute.Tensor, sK: cute.Tensor, sV: cute.Tensor, sO: cute.Tensor, sP: Optional[cute.Tensor], sRowScale: Optional[cute.Tensor], sLSE: Optional[cute.Tensor], learnable_sink: Optional[cute.Tensor], pipeline_k: PipelineAsync, pipeline_v: PipelineAsync, gmem_tiled_copy_Q: cute.TiledCopy, gmem_tiled_copy_O: cute.TiledCopy, tiled_mma_qk: cute.TiledMma, tiled_mma_pv: cute.TiledMma, tidx: Int32, softmax_scale_log2: Float32, softmax_scale: Optional[Float32], consumer_state: PipelineState, block_info: BlockInfo, seqlen: SeqlenInfoQK, n_block_min: Int32, n_block_max: Int32, m_block: Int32, head_idx: Int32, batch_idx: Int32, split_idx: Int32, is_qk_owner: cutlass.Constexpr[bool], aux_data: AuxData = AuxData(), fastdiv_mods=None, sBias: Optional[cute.Tensor] = None, pipeline_bias: Optional[PipelineAsync] = None, base_softmax_scale: Optional[Float32] = None, ): mQ_cur = seqlen.offset_batch_Q(mQ, batch_idx, dim=3)[None, None, head_idx] if const_expr(not self.pack_gqa): gQ = cute.local_tile(mQ_cur, (self.tile_m, self.tile_hdim), (m_block, 0)) num_bias_loads = Int32(0) if const_expr(self.has_bias): _, num_bias_loads = self._get_bias_load_info( block_info, seqlen, m_block, n_block_min, n_block_max, )
split_pv_warps = self._uses_split_pv_warps() thr_mma_pv = tiled_mma_pv.get_slice(tidx) acc_shape_O = thr_mma_pv.partition_shape_C((self.tile_m, self.tile_hdimv)) acc_O = cute.make_rmem_tensor(acc_shape_O, Float32) acc_O.fill(0.0)
smem_copy_atom_QK = cute.make_copy_atom( warp.LdMatrix8x8x16bOp(transpose=False, num_matrices=4), self.dtype ) smem_copy_atom_V = cute.make_copy_atom( warp.LdMatrix8x8x16bOp(transpose=True, num_matrices=4), self.dtype ) smem_thr_copy_V = utils.make_tiled_copy_B( smem_copy_atom_V, tiled_mma_pv ).get_slice(tidx) if const_expr(split_pv_warps): tOrV = thr_mma_pv.make_fragment_B(thr_mma_pv.partition_B(sV[None, None, 0])) tOsV = smem_thr_copy_V.partition_S(sV) smem_thr_copy_P = utils.make_tiled_copy_A( smem_copy_atom_QK, tiled_mma_pv ).get_slice(tidx) tPsP = smem_thr_copy_P.partition_S(sP) tOrP = thr_mma_pv.make_fragment_A(thr_mma_pv.partition_A(sP[None, None, 0])) if const_expr(not split_pv_warps or is_qk_owner): thr_mma_qk = tiled_mma_qk.get_slice(tidx) smem_thr_copy_Q = utils.make_tiled_copy_A( smem_copy_atom_QK, tiled_mma_qk ).get_slice(tidx) smem_thr_copy_K = utils.make_tiled_copy_B( smem_copy_atom_QK, tiled_mma_qk ).get_slice(tidx) if const_expr(split_pv_warps): tSrQ = thr_mma_qk.make_fragment_A(thr_mma_qk.partition_A(sQ)) tSrK = thr_mma_qk.make_fragment_B( thr_mma_qk.partition_B(sK[None, None, 0]) ) tSsQ = smem_thr_copy_Q.partition_S(sQ) tSsK = smem_thr_copy_K.partition_S(sK) smem_store_atom_P = utils.get_smem_store_atom( 120, self.dtype, ) smem_thr_store_P = cute.make_tiled_copy_C( smem_store_atom_P, tiled_mma_qk ).get_slice(tidx) tPsP_store = smem_thr_store_P.partition_D(sP)
if const_expr(not split_pv_warps or is_qk_owner): gmem_thr_copy_Q = gmem_tiled_copy_Q.get_slice(tidx) if const_expr(not self.pack_gqa): self.load_Q( gmem_thr_copy_Q, gQ, sQ, m_block, seqlen=seqlen.seqlen_q, headdim=mQ.shape[1], ) else: PackGQA( self.tile_m, self.tile_hdim, self.check_hdim_oob, self.qhead_per_kvhead, ).load_Q( mQ_cur, sQ, gmem_tiled_copy_Q, tidx, m_block, seqlen.seqlen_q, ) cute.arch.cp_async_commit_group() cute.arch.cp_async_wait_group(0) cute.arch.barrier( barrier_id=1, number_of_threads=self.num_Q_load_threads, )
if const_expr(not split_pv_warps or is_qk_owner): if const_expr(self._uses_n_distributed_qk()): softmax = None mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, tSrQ=tSrQ, tSrK=tSrK, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, tidx=tidx, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, tOsV=tOsV, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, smem_thr_store_P=( smem_thr_store_P if const_expr(self.split_qk_n) else None ), tPsP_store=(tPsP_store if const_expr(self.split_qk_n) else None), sQ=sQ, sK=sK, sP=sP, sRowScale=sRowScale, sLSE=sLSE, softmax_scale_log2=softmax_scale_log2, softmax_scale=softmax_scale, ) if const_expr(self.split_qk_n): mask = AttentionMask( self.tile_m, self.tile_n, seqlen, block_info.window_size_left, block_info.window_size_right, (self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1), enable_r2p_optimization=False, ) mask_fn = partial( mask.apply_mask, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, thr_mma=thr_mma_qk, mask_causal=self.is_causal, mask_local=self.is_local, aux_data=aux_data, fastdiv_mods=( fastdiv_mods if const_expr(self.mask_mod is not None) else None ), ) else: mask_fn = None else: softmax = Softmax.create( softmax_scale_log2, num_rows=acc_O.shape[0][0] * acc_O.shape[1], softmax_scale=softmax_scale, ) softmax.reset() if const_expr(split_pv_warps): mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, tSrQ=tSrQ, tSrK=tSrK, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, tSsQ=tSsQ, tSsK=tSsK, tOsV=tOsV, smem_thr_store_P=smem_thr_store_P, tPsP_store=tPsP_store, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, sRowScale=sRowScale, sLSE=sLSE, ) else: mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, acc_O=acc_O, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, sQ=sQ, sK=sK, sV=sV, ) mask = AttentionMask( self.tile_m, self.tile_n, seqlen, block_info.window_size_left, block_info.window_size_right, self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1, ) mask_fn = partial( mask.apply_mask, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, thr_mma=thr_mma_qk, mask_causal=self.is_causal, mask_local=self.is_local, aux_data=aux_data, fastdiv_mods=( fastdiv_mods if const_expr(self.mask_mod is not None) else None ), ) else: softmax = None mma_params = SimpleNamespace( thr_mma_pv=thr_mma_pv, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, ) smem_copy_params = SimpleNamespace( smem_thr_copy_V=smem_thr_copy_V, tOsV=tOsV, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, sRowScale=sRowScale, sLSE=sLSE, ) mask_fn = None if const_expr(split_pv_warps and not self._uses_n_distributed_qk()): compute_one_n_block = ( self.compute_one_n_block_split_pv_owner if const_expr(is_qk_owner) else self.compute_one_n_block_split_pv_helper ) elif const_expr(not self._uses_n_distributed_qk()): compute_one_n_block = self.compute_one_n_block if const_expr(not split_pv_warps or is_qk_owner): mask_fn_seqlen = partial(mask_fn, mask_mod=self.mask_mod, mask_seqlen=True) mask_fn_no_seqlen = partial( mask_fn, mask_mod=self.mask_mod, mask_seqlen=False ) else: mask_fn_seqlen = None mask_fn_no_seqlen = None n_block = cutlass.max(n_block_max - 1, 0) if const_expr(self._uses_n_distributed_qk()): consumer_state = self.compute_one_n_block_split_pv_distributed_qk( n_block, consumer_state, mma_params, smem_copy_params, None, pipeline_k, pipeline_v, score_mod=self.score_mod, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_seqlen, is_first_n_block=True, is_last_n_block=n_block == n_block_min, learnable_sink=learnable_sink, split_idx=split_idx, ) for n_tile in cutlass.range(n_block - n_block_min, unroll=1): consumer_state = self.compute_one_n_block_split_pv_distributed_qk( n_block - n_tile - 1, consumer_state, mma_params, smem_copy_params, None, pipeline_k, pipeline_v, score_mod=self.score_mod, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, is_last_n_block=n_block - n_tile - 1 == n_block_min, learnable_sink=learnable_sink, split_idx=split_idx, ) else: consumer_state = compute_one_n_block( n_block, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=n_block >= n_block_max - num_bias_loads, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_seqlen, is_first_n_block=True, ) n_block_upper = n_block if const_expr(self.is_causal or self.is_local): n_block_min_causal_local_mask = ( block_info.get_n_block_min_causal_local_mask( seqlen, m_block, n_block_min ) ) for n_tile in cutlass.range( n_block_max - 1 - n_block_min_causal_local_mask, unroll=1 ): n_block = n_block_max - 2 - n_tile consumer_state = compute_one_n_block( n_block, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=n_block >= n_block_max - num_bias_loads, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_seqlen, ) n_block_upper = cutlass.min( n_block_upper, n_block_min_causal_local_mask ) n_block_min_before_local_mask = ( block_info.get_n_block_min_before_local_mask( seqlen, m_block, n_block_min ) ) if const_expr(self.has_bias): # n13: blocks [n_far_top, n_block_upper) are inside the bias band (apply_bias True for every one of # them in the served loop), blocks below n_far_top are outside it (apply_bias False). Same blocks, # same order, same arithmetic; the bias branch is resolved at compile time in each loop. n_far_top = cutlass.max( cutlass.min(n_block_upper, n_block_max - num_bias_loads), n_block_min_before_local_mask, ) for n_tile in cutlass.range(n_block_upper - n_far_top, unroll=1): consumer_state = compute_one_n_block( n_block_upper - n_tile - 1, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=True, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, ) # n64 kernel A: n13's far loop is kernel B's (n64b_fwd.py) else: for n_tile in cutlass.range( n_block_upper - n_block_min_before_local_mask, unroll=1 ): consumer_state = compute_one_n_block( n_block_upper - n_tile - 1, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=(n_block_upper - n_tile - 1 >= n_block_max - num_bias_loads), batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, ) if const_expr(self.is_local and block_info.window_size_left is not None): n_block_upper = cutlass.min( n_block_upper, n_block_min_before_local_mask ) for n_tile in cutlass.range(n_block_upper - n_block_min, unroll=1): consumer_state = compute_one_n_block( n_block_upper - n_tile - 1, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=( n_block_upper - n_tile - 1 >= n_block_max - num_bias_loads ), batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, )
if const_expr(self._uses_n_distributed_qk()): cO = cute.make_identity_tensor((self.tile_m, self.tile_hdimv)) tOcO_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_pv.partition_C(cO) ) num_rows_pv = acc_O.shape[0][0] * acc_O.shape[1] row_scale_pv = cute.make_rmem_tensor(num_rows_pv, Float32) lse = cute.make_rmem_tensor(num_rows_pv, Float32) for r in cutlass.range(cute.size(row_scale_pv), unroll_full=True): row = tOcO_mn_finalize[r, 0][0] row_scale_pv[r] = sRowScale[0, row] lse[r] = sLSE[row] self._rescale_O(acc_O, row_scale_pv) elif const_expr(split_pv_warps): if const_expr(is_qk_owner): sink_val = None if const_expr(learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = Float32(learnable_sink[head_idx]) else: sink_val = cute.make_rmem_tensor_like(softmax.row_max, Float32) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) for r in cutlass.range(cute.size(sink_val), unroll_full=True): row = m_block * self.tile_m + tScS_mn_finalize[r][0] q_head_idx = ( row % self.qhead_per_kvhead + head_idx * self.qhead_per_kvhead ) sink_val[r] = Float32(learnable_sink[q_head_idx]) if const_expr(self.is_split_kv and learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = sink_val if split_idx == 0 else -Float32.inf elif split_idx != 0: sink_val.fill(-Float32.inf) row_scale_qk = softmax.finalize(sink_val=sink_val) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) if tScS_mn_finalize[0][1] == 0: for r in cutlass.range(cute.size(row_scale_qk), unroll_full=True): row = tScS_mn_finalize[r][0] sRowScale[2, row] = row_scale_qk[r] sLSE[row] = softmax.row_sum[r] cute.arch.fence_view_async_shared() cute.arch.barrier( barrier_id=int(NamedBarrierFwd.PFull), number_of_threads=self.num_mma_threads, ) cO = cute.make_identity_tensor((self.tile_m, self.tile_hdimv)) tOcO_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_pv.partition_C(cO) ) num_rows_pv = acc_O.shape[0][0] * acc_O.shape[1] row_scale_pv = cute.make_rmem_tensor(num_rows_pv, Float32) lse = cute.make_rmem_tensor(num_rows_pv, Float32) for r in cutlass.range(cute.size(row_scale_pv), unroll_full=True): row = tOcO_mn_finalize[r, 0][0] row_scale_pv[r] = sRowScale[2, row] lse[r] = sLSE[row] self._rescale_O(acc_O, row_scale_pv) else: sink_val = None if const_expr(learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = Float32(learnable_sink[head_idx]) else: sink_val = cute.make_rmem_tensor_like(softmax.row_max, Float32) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) for r in cutlass.range(cute.size(sink_val), unroll_full=True): row = m_block * self.tile_m + tScS_mn_finalize[r][0] q_head_idx = ( row % self.qhead_per_kvhead + head_idx * self.qhead_per_kvhead ) sink_val[r] = Float32(learnable_sink[q_head_idx]) if const_expr(self.is_split_kv and learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = sink_val if split_idx == 0 else -Float32.inf elif split_idx != 0: sink_val.fill(-Float32.inf) # n64 kernel A: no finalize / epilogue; store the raw per-thread state for kernel B (fragment order) stO = aux_data.tensors[0] stS = aux_data.tensors[1] lane = tidx % cute.arch.WARP_SIZE wrow = (tidx // cute.arch.WARP_SIZE) * 16 grow = seqlen.offset_q + 128 * batch_idx + m_block * self.tile_m + wrow fO = cute.make_tensor(utils.elem_pointer(stO, (head_idx, grow * self.tile_hdimv + lane * cute.size(acc_O))), cute.make_layout(cute.size(acc_O))) for i in cutlass.range(cute.size(acc_O), unroll_full=True): fO[i] = acc_O[i] fS = cute.make_tensor(utils.elem_pointer(stS, (head_idx, grow * 16 + lane * 4)), cute.make_layout(4)) nrow = cute.size(softmax.row_max) if const_expr(N64A_CTL == 1): # FAILING CONTROL (mb only): store quad-reduced row sums instead of the lane partials (must differ) softmax.row_sum.store(utils.warp_reduce(softmax.row_sum.load(), operator.add, width=4)) for r in cutlass.range(nrow, unroll_full=True): fS[r] = softmax.row_max[r] fS[nrow + r] = softmax.row_sum[r] if lane == 0: stS[head_idx, grow * 16 + 128] = Float32(n_far_top) return consumer_state1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597# Generated by work_attn/gen/gen_n64b.py from the image's sglang/kernels/ops/attention/fa4_sm120/flash_fwd.py (md5 f7161e38)."""Generate n64b_fwd.py (fa4_sm120/n64b_fwd.py) = n64 exact far form, KERNEL B, from the image's flash_fwd.py (md5 f7161e38).
FlashAttentionForwardSm120W8Far: the W8 layout of gen_n64.py (tile (128,128), consumers = warps 4-11 at N64_REG_C undersetmaxnreg, producer warpgroup 0-3 at N64_REG_P, warp 0 = the image's paged cp.async loader) running only the FAR key blocksof a global-layer prefill visit, continuing the per-thread state that kernel A (n64a_fwd.py, n54's band-split kernel withthe far loop removed) stored, with n54's far-loop arithmetic: * __call__: the has_bias scale pair (base_softmax_scale = softmax_scale, softmax_scale_log2 = LOG2_E) without bias tiles; * compute_one_n_block: acc_S *= base_softmax_scale (apply_sheared_bias with apply_bias False), then the image softmax / PV; * mma: after Softmax.create / reset, acc_O, row_max and the per-lane partial row_sum are loaded from aux tensors [stO fp32 (H, Tpad * 128), stS fp32 (H, Tpad * 16), fragment order per 16-row group: see the mma comment; Tpad = T + 128 x batch]; blocks from the causal top down to the half's n_far_top are consumed without compute (wait + release), the far blocks n_far_top - 1 .. n_block_min run with the served mask call (no-op there); finalize + epilogue are the image's."""from sglang.kernels.ops.attention.fa4_sm120 import flash_fwd as _baseglobals().update({k: v for k, v in vars(_base).items() if not k.startswith("__")})from sglang.kernels.ops.attention.fa4_sm120.flash_fwd import FlashAttentionForwardSm120 # noqa: E402
N64_REG_P = 40 # producer warpgroup registers per thread after setmaxnregN64_REG_C = 232 # consumer warpgroup registers per thread after setmaxnregN64_CONSUMER_WARP0 = 4 # consumers are warps 4-11 (two whole warpgroups)N64_FAR = True # kernel B: n54's far-loop arithmetic (FMUL by the softmax scale, exp2 with LOG2_E)
class FlashAttentionForwardSm120W8Far(FlashAttentionForwardSm120): """n64 kernel B: W8 layout, far blocks only, continuing kernel A's per-thread state with n54's far-loop math."""
def _num_dma_threads(self) -> int: assert self.num_threads == 256 and not self._uses_split_pv_warps() and not self.has_bias return N64_CONSUMER_WARP0 * 32
# ---- copied from the image file and patched (gen_n64b.py) ---- @cute.jit def __call__( self, mQ: cute.Tensor, mK: cute.Tensor, mV: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], softmax_scale: Float32, mCuSeqlensQ: Optional[cute.Tensor] = None, mCuSeqlensK: Optional[cute.Tensor] = None, mSeqUsedQ: Optional[cute.Tensor] = None, mSeqUsedK: Optional[cute.Tensor] = None, mPageTable: Optional[cute.Tensor] = None, window_size_left: Int32 | int | None = None, window_size_right: Int32 | int | None = None, learnable_sink: Optional[cute.Tensor] = None, blocksparse_tensors: Optional[BlockSparseTensors] = None, aux_data: AuxData = AuxData(), mBias: Optional[cute.Tensor] = None, launch_split_combine_early: Int32 = Int32(0), stream: cuda.CUstream = None, ): assert blocksparse_tensors is None, "Block sparsity is not supported on SM120" assert (mBias is not None) == self.has_bias assert mPageTable is None or self.paged_kv, ( "SM120 paged KV requires the dedicated DMA-warp specialization" ) self._check_type( *( t.element_type if t is not None else None for t in ( mQ, mK, mV, mO, mLSE, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, ) ) ) tiled_mma_qk, tiled_mma_pv = self._get_tiled_mma() self.num_qk_threads = tiled_mma_qk.size self.num_mma_threads = tiled_mma_pv.size self.num_producer_threads = self.num_threads self.num_Q_load_threads = ( self.num_qk_threads if self._uses_split_pv_warps() else self.num_threads ) self.num_epilogue_threads = ( self.num_mma_threads if self._uses_split_pv_warps() else self.num_threads ) self.use_tma_O = False self._setup_attributes() SharedStorage = self._get_shared_storage_cls()
mQ, mK, mV, mO = [assume_tensor_aligned(t) for t in (mQ, mK, mV, mO)] if const_expr(mBias is not None): assert mBias.element_type == self.dtype mBias = assume_tensor_aligned(mBias) Q_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensQ is None) else [0, 2, 1] ) KV_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensK is None) else [0, 2, 1] ) mQ = cute.make_tensor( mQ.iterator, cute.select(mQ.layout, mode=Q_layout_transpose) ) if const_expr(mBias is not None): mBias = cute.make_tensor( mBias.iterator, cute.select(mBias.layout, mode=Q_layout_transpose), ) mK, mV = [ cute.make_tensor( t.iterator, cute.select(t.layout, mode=KV_layout_transpose) ) for t in (mK, mV) ] if const_expr(mPageTable is None): V_layout_transpose = ( [1, 0, 2, 3] if const_expr(mCuSeqlensK is None) else [1, 0, 2] ) mV = cute.make_tensor( mV.iterator, cute.select(mV.layout, mode=V_layout_transpose) ) if const_expr(self.is_split_kv): num_splits = mO.shape[0] O_layout_transpose = ( [2, 4, 3, 1, 0] if const_expr(mCuSeqlensQ is None) else [1, 3, 2, 0] ) LSE_layout_transpose = ( [3, 2, 1, 0] if const_expr(mCuSeqlensQ is None) else [2, 1, 0] ) else: num_splits = Int32(1) O_layout_transpose = ( [1, 3, 2, 0] if const_expr(mCuSeqlensQ is None) else [0, 2, 1] ) LSE_layout_transpose = ( [2, 1, 0] if const_expr(mCuSeqlensQ is None) else [1, 0] ) mO = cute.make_tensor( mO.iterator, cute.select(mO.layout, mode=O_layout_transpose) ) if const_expr(mLSE is not None): mLSE = cute.make_tensor( mLSE.iterator, cute.select(mLSE.layout, mode=LSE_layout_transpose) ) if const_expr(self.pack_gqa): nheads_kv = mK.shape[2] mQ = pack_gqa_layout(mQ, self.qhead_per_kvhead, nheads_kv, head_idx=2) mO = pack_gqa_layout(mO, self.qhead_per_kvhead, nheads_kv, head_idx=2) if const_expr(mLSE is not None): mLSE = pack_gqa_layout( mLSE, self.qhead_per_kvhead, nheads_kv, head_idx=1 ) if const_expr(mBias is not None): mBias = pack_gqa_layout( mBias, self.qhead_per_kvhead, nheads_kv, head_idx=2 )
if const_expr(mPageTable is None or self.paged_tma): tma_copy_op = cpasync.CopyBulkTensorTileG2SOp() mV_tma = ( mV if const_expr(mPageTable is None) else cute.make_tensor( mV.iterator, cute.select(mV.layout, mode=[1, 0, 2, 3]), ) ) tma_atom_K, tma_tensor_K = cpasync.make_tiled_tma_atom( tma_copy_op, mK, cute.select(self.sK_layout, mode=[0, 1]), (self.tile_n, self.tile_hdim), 1, ) tma_atom_V, tma_tensor_V = cpasync.make_tiled_tma_atom( tma_copy_op, mV_tma, cute.select(self.sV_layout, mode=[0, 1]), (self.tile_hdimv, self.tile_n), 1, ) self.tma_copy_bytes_K = cute.size_in_bytes( mK.element_type, cute.select(self.sK_layout, mode=[0, 1]) ) self.tma_copy_bytes_V = cute.size_in_bytes( mV_tma.element_type, cute.select(self.sV_layout, mode=[0, 1]), ) else: tma_atom_K = None tma_atom_V = None tma_tensor_K = mK tma_tensor_V = mV if const_expr(self.has_bias): tma_atom_Bias, tma_tensor_Bias = cpasync.make_tiled_tma_atom( cpasync.CopyBulkTensorTileG2SOp(), mBias, cute.select(self.sBias_layout, mode=[0, 1]), (self.bias_block_size, self.tile_n), 1, ) self.tma_copy_bytes_Bias = cute.size_in_bytes( mBias.element_type, cute.select(self.sBias_layout, mode=[0, 1]), ) else: tma_atom_Bias = None tma_tensor_Bias = mBias
is_varlen = const_expr(mCuSeqlensQ is not None or mSeqUsedQ is not None) num_batch = ( mCuSeqlensQ.shape[0] - 1 if const_expr(mCuSeqlensQ is not None) else cute.size(mQ.shape[3]) ) TileScheduler = ( Sm120UniformBatchScheduler if is_varlen and self.direct_uniform_batch else SingleTileVarlenScheduler if is_varlen else SingleTileScheduler ) tile_sched_args = TileSchedulerArguments( num_block=cute.ceil_div(cute.size(mQ.shape[0]), self.tile_m), num_head=cute.size(mQ.shape[2]), num_batch=num_batch, num_splits=num_splits, seqlen_k=0, headdim=mQ.shape[1], headdim_v=mO.shape[1], total_q=( cute.size(mQ.shape[0]) if const_expr(mCuSeqlensQ is not None) else cute.size(mQ.shape[0]) * cute.size(mQ.shape[3]) ), tile_shape_mn=(self.tile_m, self.tile_n), lpt=(self.is_causal or self.is_local) and not self.direct_uniform_batch, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), mCuSeqlensQ=mCuSeqlensQ, mSeqUsedQ=mSeqUsedQ, is_persistent=False, is_split_kv=self.is_split_kv, ) tile_sched_params = TileScheduler.to_underlying_arguments( tile_sched_args, scheduling_mode=SchedulingMode.STATIC, ) grid_dim = TileScheduler.get_grid_shape(tile_sched_params) if const_expr(self.has_bias or N64_FAR): # n64 kernel B: n54's far-loop scale pair (FMUL by scale, exp2 with LOG2_E) base_softmax_scale = softmax_scale softmax_scale_log2, softmax_scale = utils.LOG2_E, None else: base_softmax_scale = None softmax_scale_log2, softmax_scale = utils.compute_softmax_scale_log2( softmax_scale, self.score_mod ) window_size_left = ( Int32(window_size_left) if window_size_left is not None else None ) window_size_right = ( Int32(window_size_right) if window_size_right is not None else None ) fastdiv_mods = utils.compute_fastdiv_mods( mQ, mK, self.qhead_per_kvhead, self.pack_gqa, aux_data.tensors, mPageTable, )
self.kernel( mQ, tma_tensor_K, tma_tensor_V, mO, mLSE, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, tma_tensor_Bias, tma_atom_K, tma_atom_V, tma_atom_Bias, softmax_scale_log2, softmax_scale, base_softmax_scale, window_size_left, window_size_right, learnable_sink, self.sQ_layout, self.sK_layout, self.sV_layout, self.sO_layout, self.sP_layout, self.sBias_layout, self.gmem_tiled_copy_Q, self.gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, SharedStorage, tile_sched_params, TileScheduler, launch_split_combine_early, aux_data, fastdiv_mods, ).launch( grid=grid_dim, block=[self.num_threads + self._num_dma_threads(), 1, 1], smem=SharedStorage.size_in_bytes(), stream=stream, min_blocks_per_mp=1, # The immediately preceding ShearingBias grid releases this # dependent launch before all of its CTAs have retired. Bias # readers synchronize before their first TMA issue below; the # remaining kernel prologue can overlap the tail of the shear. use_pdl=self.has_bias, )
@cute.kernel def kernel( self, mQ: cute.Tensor, mK: cute.Tensor, mV: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], mCuSeqlensQ: Optional[cute.Tensor], mCuSeqlensK: Optional[cute.Tensor], mSeqUsedQ: Optional[cute.Tensor], mSeqUsedK: Optional[cute.Tensor], mPageTable: Optional[cute.Tensor], mBias: Optional[cute.Tensor], tma_atom_K: Optional[cute.CopyAtom], tma_atom_V: Optional[cute.CopyAtom], tma_atom_Bias: Optional[cute.CopyAtom], softmax_scale_log2: Float32, softmax_scale: Optional[Float32], base_softmax_scale: Optional[Float32], window_size_left: Optional[Int32], window_size_right: Optional[Int32], learnable_sink: Optional[cute.Tensor], sQ_layout: cute.ComposedLayout, sK_layout: cute.ComposedLayout, sV_layout: cute.ComposedLayout, sO_layout: cute.ComposedLayout, sP_layout: cute.ComposedLayout | None, sBias_layout: cute.ComposedLayout | None, gmem_tiled_copy_Q: cute.TiledCopy, gmem_tiled_copy_O: cute.TiledCopy, tiled_mma_qk: cute.TiledMma, tiled_mma_pv: cute.TiledMma, SharedStorage: cutlass.Constexpr, tile_sched_params, TileScheduler: cutlass.Constexpr[Callable], launch_split_combine_early: Int32, aux_data: AuxData = AuxData(), fastdiv_mods=None, ): tidx, _, _ = cute.arch.thread_idx() warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
if const_expr(self.is_split_kv): if launch_split_combine_early != 0 and warp_idx == 0: cute.arch.griddepcontrol_launch_dependents()
if const_expr(mPageTable is None or self.paged_tma): if warp_idx == 0: cpasync.prefetch_descriptor(tma_atom_K) cpasync.prefetch_descriptor(tma_atom_V) if const_expr(self.has_bias): if warp_idx == 0: cpasync.prefetch_descriptor(tma_atom_Bias)
smem = cutlass.utils.SmemAllocator() storage = smem.allocate(SharedStorage) sQ = storage.sQ.get_tensor(sQ_layout.outer, swizzle=sQ_layout.inner) sK = storage.sK.get_tensor(sK_layout.outer, swizzle=sK_layout.inner) sV = storage.sV.get_tensor(sV_layout.outer, swizzle=sV_layout.inner) sO = storage.sQ.get_tensor(sO_layout.outer, swizzle=sO_layout.inner) sBias = ( storage.sBias.get_tensor(sBias_layout.outer, swizzle=sBias_layout.inner) if const_expr(self.has_bias) else None ) sP = None sRowScale = None sFinalScale = None sLSE = None if const_expr(sP_layout is not None): if const_expr(self._q_in_regs_pipeline()): sP = storage.sQ.get_tensor(sP_layout.outer, swizzle=sP_layout.inner) else: sP = storage.sP.get_tensor(sP_layout.outer, swizzle=sP_layout.inner) sSoftmaxStats = storage.softmax_stats.get_tensor( cute.make_layout( (self._num_softmax_stat_rows(), self.tile_m), stride=(self.tile_m, 1), ) ) sRowScale = sSoftmaxStats if const_expr(self._uses_n_distributed_qk()): num_qk_warps = self.num_qk_threads // cute.arch.WARP_SIZE sFinalScale = sSoftmaxStats[2 * num_qk_warps + 2, None] sLSE = sSoftmaxStats[3 * num_qk_warps + 3, None] else: sFinalScale = sSoftmaxStats[2, None] sLSE = sSoftmaxStats[3, None]
tma_group = CooperativeGroup(Agent.Thread) qk_group = CooperativeGroup( Agent.Thread, self.num_qk_threads // cute.arch.WARP_SIZE ) pv_group = CooperativeGroup( Agent.Thread, self.num_mma_threads // cute.arch.WARP_SIZE ) if const_expr(mPageTable is None or self.paged_tma): pipeline_k = PipelineTmaAsync.create( num_stages=self._num_k_stages(), producer_group=tma_group, consumer_group=qk_group, tx_count=self.tma_copy_bytes_K, barrier_storage=storage.mbar_K.data_ptr(), defer_sync=True, ) pipeline_v = PipelineTmaAsync.create( num_stages=self._num_v_stages(), producer_group=tma_group, consumer_group=pv_group, tx_count=self.tma_copy_bytes_V, barrier_storage=storage.mbar_V.data_ptr(), defer_sync=True, ) else: dma_group = CooperativeGroup(Agent.Thread, self.num_dma_threads) k_consumer_group = CooperativeGroup( Agent.Thread, ( self.num_qk_threads if self._uses_split_pv_warps() else self.num_threads ), ) v_consumer_group = CooperativeGroup( Agent.Thread, ( self.num_mma_threads if self._uses_split_pv_warps() else self.num_threads ), ) pipeline_k = pipeline_custom.PipelineCpAsync.create( num_stages=self._num_k_stages(), producer_group=dma_group, consumer_group=k_consumer_group, barrier_storage=storage.mbar_K.data_ptr(), defer_sync=True, ) pipeline_v = pipeline_custom.PipelineCpAsync.create( num_stages=self._num_v_stages(), producer_group=dma_group, consumer_group=v_consumer_group, barrier_storage=storage.mbar_V.data_ptr(), defer_sync=True, ) pipeline_bias = ( PipelineTmaAsync.create( num_stages=self.num_stages, producer_group=tma_group, consumer_group=qk_group, tx_count=self.tma_copy_bytes_Bias, barrier_storage=storage.mbar_Bias.data_ptr(), defer_sync=True, ) if const_expr(self.has_bias) else None ) pipeline_p = None pipeline_final = None if const_expr(sP_layout is not None): pipeline_p = PipelineAsync.create( num_stages=self._num_p_stages(), producer_group=CooperativeGroup(Agent.Thread, self.num_qk_threads), consumer_group=CooperativeGroup(Agent.Thread, self.num_mma_threads), barrier_storage=storage.mbar_P.data_ptr(), defer_sync=True, name="sm120_p", ) pipeline_final = PipelineAsync.create( num_stages=1, producer_group=CooperativeGroup(Agent.Thread, self.num_qk_threads), consumer_group=CooperativeGroup(Agent.Thread, self.num_mma_threads), barrier_storage=storage.mbar_final.data_ptr(), defer_sync=True, name="sm120_final", ) tile_scheduler = TileScheduler.create(tile_sched_params) work_tile = tile_scheduler.initial_work_tile_info() if work_tile.is_valid_tile: m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx seqlen = SeqlenInfoQK.create( batch_idx=batch_idx, seqlen_q_static=( mQ.shape[0] if const_expr(not self.pack_gqa) else mQ.shape[0][1] ), seqlen_k_static=( mK.shape[0] if const_expr(mPageTable is None) else mK.shape[0] * mPageTable.shape[1] ), mCuSeqlensQ=mCuSeqlensQ, mCuSeqlensK=mCuSeqlensK, mSeqUsedQ=mSeqUsedQ, mSeqUsedK=mSeqUsedK, tile_m=self.tile_m, tile_n=self.tile_n, ) run_mainloop = True if const_expr(self.is_split_kv): block_info = BlockInfo( self.tile_m, self.tile_n, self.is_causal, self.is_local, self.is_split_kv, window_size_left, window_size_right, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), ) n_block_min, n_block_max = self._get_n_block_min_max( block_info, seqlen, m_block, split_idx, tile_scheduler.params.num_splits, ) is_empty_split = n_block_min >= n_block_max if is_empty_split: if const_expr(self._uses_split_pv_warps()): if warp_idx >= self.num_qk_threads // cute.arch.WARP_SIZE: self.epilogue_empty_split( mO, mLSE, learnable_sink, seqlen, tiled_mma_pv, tidx - self.num_qk_threads, m_block, head_idx, batch_idx, split_idx, ) else: if warp_idx >= N64_CONSUMER_WARP0: self.epilogue_empty_split( mO, mLSE, learnable_sink, seqlen, tiled_mma_pv, tidx - N64_CONSUMER_WARP0 * cute.arch.WARP_SIZE, m_block, head_idx, batch_idx, split_idx, ) run_mainloop = not is_empty_split
if run_mainloop: pipeline_init_arrive(cluster_shape_mn=(1, 1), is_relaxed=True) pipeline_init_wait(cluster_shape_mn=(1, 1))
if const_expr(mPageTable is not None and self._uses_split_pv_warps()): if warp_idx == 0: self.load_paged_persistent( mK, mV, mPageTable, tma_atom_K, tma_atom_V, sK, sV, pipeline_k, pipeline_v, tile_scheduler, mQ, mCuSeqlensQ, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, tidx, ) elif const_expr(self._uses_n_distributed_qk()): if warp_idx <= self.num_mma_threads // cute.arch.WARP_SIZE: self.mma_persistent( mQ, mK, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx - self.num_dma_threads, softmax_scale_log2, softmax_scale, base_softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, window_size_left, window_size_right, True, aux_data, fastdiv_mods, ) elif warp_idx == 1: self.mma_persistent( mQ, mK, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx - self.num_dma_threads, softmax_scale_log2, softmax_scale, base_softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, window_size_left, window_size_right, True, aux_data, fastdiv_mods, ) elif warp_idx <= self.num_mma_threads // cute.arch.WARP_SIZE: self.mma_persistent( mQ, mK, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx - self.num_dma_threads, softmax_scale_log2, softmax_scale, base_softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, window_size_left, window_size_right, False, aux_data, fastdiv_mods, ) elif const_expr(self._uses_split_pv_warps()): if warp_idx < self.num_qk_threads // cute.arch.WARP_SIZE: self.mma_qk_pipeline_persistent( mQ, mK, mV, sQ, sK, sV, tma_atom_K, tma_atom_V, sP, sRowScale, sFinalScale, sLSE, learnable_sink, pipeline_k, pipeline_v, pipeline_p, pipeline_final, gmem_tiled_copy_Q, tiled_mma_qk, tidx, softmax_scale_log2, softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, aux_data, fastdiv_mods, ) else: self.mma_pv_pipeline_persistent( mQ, mK, mO, mLSE, sV, sO, sP, sRowScale, sFinalScale, sLSE, pipeline_v, pipeline_p, pipeline_final, gmem_tiled_copy_O, tiled_mma_pv, tidx - self.num_qk_threads, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, ) elif warp_idx < N64_CONSUMER_WARP0: cute.arch.setmaxregister_decrease(N64_REG_P) # n64: producer warpgroup if warp_idx == 0: if const_expr(mPageTable is None): self.load_tma_persistent( mK, mV, sK, sV, tma_atom_K, tma_atom_V, pipeline_k, pipeline_v, tile_scheduler, mQ, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, mBias=mBias, sBias=sBias, tma_atom_Bias=tma_atom_Bias, pipeline_bias=pipeline_bias, ) else: self.load_paged_persistent( mK, mV, mPageTable, tma_atom_K, tma_atom_V, sK, sV, pipeline_k, pipeline_v, tile_scheduler, mQ, mCuSeqlensQ, mSeqUsedQ, mSeqUsedK, window_size_left, window_size_right, tidx, mBias=mBias, sBias=sBias, tma_atom_Bias=tma_atom_Bias, pipeline_bias=pipeline_bias, ) else: cute.arch.setmaxregister_increase(N64_REG_C) # n64: consumer warpgroups self.mma_persistent( mQ, mK, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx - N64_CONSUMER_WARP0 * cute.arch.WARP_SIZE, softmax_scale_log2, softmax_scale, base_softmax_scale, tile_scheduler, mCuSeqlensQ, mCuSeqlensK, mSeqUsedQ, mSeqUsedK, mPageTable, window_size_left, window_size_right, True, aux_data, fastdiv_mods, sBias=sBias, pipeline_bias=pipeline_bias, )
@cute.jit def mma_persistent( self, mQ: cute.Tensor, mK: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], sQ: cute.Tensor, sK: cute.Tensor, sV: cute.Tensor, sO: cute.Tensor, sP: Optional[cute.Tensor], sRowScale: Optional[cute.Tensor], sLSE: Optional[cute.Tensor], learnable_sink: Optional[cute.Tensor], pipeline_k: PipelineAsync, pipeline_v: PipelineAsync, gmem_tiled_copy_Q: cute.TiledCopy, gmem_tiled_copy_O: cute.TiledCopy, tiled_mma_qk: cute.TiledMma, tiled_mma_pv: cute.TiledMma, tidx: Int32, softmax_scale_log2: Float32, softmax_scale: Optional[Float32], base_softmax_scale: Optional[Float32], tile_scheduler: TileSchedulerProtocol, mCuSeqlensQ: Optional[cute.Tensor], mCuSeqlensK: Optional[cute.Tensor], mSeqUsedQ: Optional[cute.Tensor], mSeqUsedK: Optional[cute.Tensor], mPageTable: Optional[cute.Tensor], window_size_left: Optional[Int32], window_size_right: Optional[Int32], is_qk_owner: cutlass.Constexpr[bool], aux_data: AuxData = AuxData(), fastdiv_mods=None, sBias: Optional[cute.Tensor] = None, pipeline_bias: Optional[PipelineAsync] = None, ): consumer_state = PipelineState(self.num_stages, Int32(0), Int32(0), Int32(0)) block_info = BlockInfo( self.tile_m, self.tile_n, self.is_causal, self.is_local, self.is_split_kv, window_size_left, window_size_right, qhead_per_kvhead_packgqa=( self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1 ), ) work_tile = tile_scheduler.initial_work_tile_info() m_block, head_idx, batch_idx, split_idx = work_tile.tile_idx seqlen = SeqlenInfoQK.create( batch_idx=batch_idx, seqlen_q_static=( mQ.shape[0] if const_expr(not self.pack_gqa) else mQ.shape[0][1] ), seqlen_k_static=( mK.shape[0] if const_expr(mPageTable is None) else mK.shape[0] * mPageTable.shape[1] ), mCuSeqlensQ=mCuSeqlensQ, mCuSeqlensK=mCuSeqlensK, mSeqUsedQ=mSeqUsedQ, mSeqUsedK=mSeqUsedK, tile_m=self.tile_m, tile_n=self.tile_n, ) n_block_min, n_block_max = self._get_n_block_min_max( block_info, seqlen, m_block, split_idx, tile_scheduler.params.num_splits, ) mma_fn = partial( self.mma, mQ, mO, mLSE, sQ, sK, sV, sO, sP, sRowScale, sLSE, learnable_sink, pipeline_k, pipeline_v, gmem_tiled_copy_Q, gmem_tiled_copy_O, tiled_mma_qk, tiled_mma_pv, tidx, softmax_scale_log2, softmax_scale, consumer_state, block_info, seqlen, n_block_min, n_block_max, m_block, head_idx, batch_idx, split_idx, is_qk_owner, aux_data, fastdiv_mods, ) if const_expr(self.has_bias): mma_fn( base_softmax_scale=base_softmax_scale, sBias=sBias, pipeline_bias=pipeline_bias, ) elif const_expr(N64_FAR): mma_fn(base_softmax_scale=base_softmax_scale) # n64 kernel B: the far-loop FMUL scale else: mma_fn()
@cute.jit def mma( self, mQ: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], sQ: cute.Tensor, sK: cute.Tensor, sV: cute.Tensor, sO: cute.Tensor, sP: Optional[cute.Tensor], sRowScale: Optional[cute.Tensor], sLSE: Optional[cute.Tensor], learnable_sink: Optional[cute.Tensor], pipeline_k: PipelineAsync, pipeline_v: PipelineAsync, gmem_tiled_copy_Q: cute.TiledCopy, gmem_tiled_copy_O: cute.TiledCopy, tiled_mma_qk: cute.TiledMma, tiled_mma_pv: cute.TiledMma, tidx: Int32, softmax_scale_log2: Float32, softmax_scale: Optional[Float32], consumer_state: PipelineState, block_info: BlockInfo, seqlen: SeqlenInfoQK, n_block_min: Int32, n_block_max: Int32, m_block: Int32, head_idx: Int32, batch_idx: Int32, split_idx: Int32, is_qk_owner: cutlass.Constexpr[bool], aux_data: AuxData = AuxData(), fastdiv_mods=None, sBias: Optional[cute.Tensor] = None, pipeline_bias: Optional[PipelineAsync] = None, base_softmax_scale: Optional[Float32] = None, ): mQ_cur = seqlen.offset_batch_Q(mQ, batch_idx, dim=3)[None, None, head_idx] if const_expr(not self.pack_gqa): gQ = cute.local_tile(mQ_cur, (self.tile_m, self.tile_hdim), (m_block, 0)) num_bias_loads = Int32(0) if const_expr(self.has_bias): _, num_bias_loads = self._get_bias_load_info( block_info, seqlen, m_block, n_block_min, n_block_max, )
split_pv_warps = self._uses_split_pv_warps() thr_mma_pv = tiled_mma_pv.get_slice(tidx) acc_shape_O = thr_mma_pv.partition_shape_C((self.tile_m, self.tile_hdimv)) acc_O = cute.make_rmem_tensor(acc_shape_O, Float32) acc_O.fill(0.0)
smem_copy_atom_QK = cute.make_copy_atom( warp.LdMatrix8x8x16bOp(transpose=False, num_matrices=4), self.dtype ) smem_copy_atom_V = cute.make_copy_atom( warp.LdMatrix8x8x16bOp(transpose=True, num_matrices=4), self.dtype ) smem_thr_copy_V = utils.make_tiled_copy_B( smem_copy_atom_V, tiled_mma_pv ).get_slice(tidx) if const_expr(split_pv_warps): tOrV = thr_mma_pv.make_fragment_B(thr_mma_pv.partition_B(sV[None, None, 0])) tOsV = smem_thr_copy_V.partition_S(sV) smem_thr_copy_P = utils.make_tiled_copy_A( smem_copy_atom_QK, tiled_mma_pv ).get_slice(tidx) tPsP = smem_thr_copy_P.partition_S(sP) tOrP = thr_mma_pv.make_fragment_A(thr_mma_pv.partition_A(sP[None, None, 0])) if const_expr(not split_pv_warps or is_qk_owner): thr_mma_qk = tiled_mma_qk.get_slice(tidx) smem_thr_copy_Q = utils.make_tiled_copy_A( smem_copy_atom_QK, tiled_mma_qk ).get_slice(tidx) smem_thr_copy_K = utils.make_tiled_copy_B( smem_copy_atom_QK, tiled_mma_qk ).get_slice(tidx) if const_expr(split_pv_warps): tSrQ = thr_mma_qk.make_fragment_A(thr_mma_qk.partition_A(sQ)) tSrK = thr_mma_qk.make_fragment_B( thr_mma_qk.partition_B(sK[None, None, 0]) ) tSsQ = smem_thr_copy_Q.partition_S(sQ) tSsK = smem_thr_copy_K.partition_S(sK) smem_store_atom_P = utils.get_smem_store_atom( 120, self.dtype, ) smem_thr_store_P = cute.make_tiled_copy_C( smem_store_atom_P, tiled_mma_qk ).get_slice(tidx) tPsP_store = smem_thr_store_P.partition_D(sP)
if const_expr(not split_pv_warps or is_qk_owner): gmem_thr_copy_Q = gmem_tiled_copy_Q.get_slice(tidx) if const_expr(not self.pack_gqa): self.load_Q( gmem_thr_copy_Q, gQ, sQ, m_block, seqlen=seqlen.seqlen_q, headdim=mQ.shape[1], ) else: PackGQA( self.tile_m, self.tile_hdim, self.check_hdim_oob, self.qhead_per_kvhead, ).load_Q( mQ_cur, sQ, gmem_tiled_copy_Q, tidx, m_block, seqlen.seqlen_q, ) cute.arch.cp_async_commit_group() cute.arch.cp_async_wait_group(0) cute.arch.barrier( barrier_id=1, number_of_threads=self.num_Q_load_threads, )
if const_expr(not split_pv_warps or is_qk_owner): if const_expr(self._uses_n_distributed_qk()): softmax = None mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, tSrQ=tSrQ, tSrK=tSrK, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, tidx=tidx, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, tOsV=tOsV, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, smem_thr_store_P=( smem_thr_store_P if const_expr(self.split_qk_n) else None ), tPsP_store=(tPsP_store if const_expr(self.split_qk_n) else None), sQ=sQ, sK=sK, sP=sP, sRowScale=sRowScale, sLSE=sLSE, softmax_scale_log2=softmax_scale_log2, softmax_scale=softmax_scale, ) if const_expr(self.split_qk_n): mask = AttentionMask( self.tile_m, self.tile_n, seqlen, block_info.window_size_left, block_info.window_size_right, (self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1), enable_r2p_optimization=False, ) mask_fn = partial( mask.apply_mask, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, thr_mma=thr_mma_qk, mask_causal=self.is_causal, mask_local=self.is_local, aux_data=aux_data, fastdiv_mods=( fastdiv_mods if const_expr(self.mask_mod is not None) else None ), ) else: mask_fn = None else: softmax = Softmax.create( softmax_scale_log2, num_rows=acc_O.shape[0][0] * acc_O.shape[1], softmax_scale=softmax_scale, ) softmax.reset() if const_expr(split_pv_warps): mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, tSrQ=tSrQ, tSrK=tSrK, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, tSsQ=tSsQ, tSsK=tSsK, tOsV=tOsV, smem_thr_store_P=smem_thr_store_P, tPsP_store=tPsP_store, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, sRowScale=sRowScale, sLSE=sLSE, ) else: mma_params = SimpleNamespace( thr_mma_qk=thr_mma_qk, thr_mma_pv=thr_mma_pv, acc_O=acc_O, ) smem_copy_params = SimpleNamespace( smem_thr_copy_Q=smem_thr_copy_Q, smem_thr_copy_K=smem_thr_copy_K, smem_thr_copy_V=smem_thr_copy_V, sQ=sQ, sK=sK, sV=sV, ) mask = AttentionMask( self.tile_m, self.tile_n, seqlen, block_info.window_size_left, block_info.window_size_right, self.qhead_per_kvhead if const_expr(self.pack_gqa) else 1, ) mask_fn = partial( mask.apply_mask, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, thr_mma=thr_mma_qk, mask_causal=self.is_causal, mask_local=self.is_local, aux_data=aux_data, fastdiv_mods=( fastdiv_mods if const_expr(self.mask_mod is not None) else None ), ) else: softmax = None mma_params = SimpleNamespace( thr_mma_pv=thr_mma_pv, tOrV=tOrV, acc_O=acc_O, tOrP=tOrP, ) smem_copy_params = SimpleNamespace( smem_thr_copy_V=smem_thr_copy_V, tOsV=tOsV, smem_thr_copy_P=smem_thr_copy_P, tPsP=tPsP, sRowScale=sRowScale, sLSE=sLSE, ) mask_fn = None if const_expr(split_pv_warps and not self._uses_n_distributed_qk()): compute_one_n_block = ( self.compute_one_n_block_split_pv_owner if const_expr(is_qk_owner) else self.compute_one_n_block_split_pv_helper ) elif const_expr(not self._uses_n_distributed_qk()): compute_one_n_block = self.compute_one_n_block if const_expr(not split_pv_warps or is_qk_owner): mask_fn_seqlen = partial(mask_fn, mask_mod=self.mask_mod, mask_seqlen=True) mask_fn_no_seqlen = partial( mask_fn, mask_mod=self.mask_mod, mask_seqlen=False ) else: mask_fn_seqlen = None mask_fn_no_seqlen = None n_block = cutlass.max(n_block_max - 1, 0) if const_expr(self._uses_n_distributed_qk()): consumer_state = self.compute_one_n_block_split_pv_distributed_qk( n_block, consumer_state, mma_params, smem_copy_params, None, pipeline_k, pipeline_v, score_mod=self.score_mod, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_seqlen, is_first_n_block=True, is_last_n_block=n_block == n_block_min, learnable_sink=learnable_sink, split_idx=split_idx, ) for n_tile in cutlass.range(n_block - n_block_min, unroll=1): consumer_state = self.compute_one_n_block_split_pv_distributed_qk( n_block - n_tile - 1, consumer_state, mma_params, smem_copy_params, None, pipeline_k, pipeline_v, score_mod=self.score_mod, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, is_last_n_block=n_block - n_tile - 1 == n_block_min, learnable_sink=learnable_sink, split_idx=split_idx, ) else: # n64 kernel B: restore kernel A's per-thread state (fp32 bit copies), consume the band blocks without # compute, then the far blocks n_far_top - 1 .. n_block_min exactly as n54's far loop. # state in FRAGMENT order (kernel A writes the same): the 16-row group of consumer warp w starts at padded row # grow = offset_q + 128 * batch + tile row 16 w; stO (H, Tpad * 128): lane l's 64 acc_O values at grow * 128 + # 64 l; stS (H, Tpad * 16): lane l's (row_max[0], row_max[1], row_sum[0], row_sum[1]) at grow * 16 + 4 l and the # 64-row block's n_far_top at grow * 16 + 128. One base address per thread, no per-element coordinates. stO = aux_data.tensors[0] stS = aux_data.tensors[1] lane = tidx % cute.arch.WARP_SIZE wrow = (tidx // cute.arch.WARP_SIZE) * 16 grow = seqlen.offset_q + 128 * batch_idx + m_block * self.tile_m + wrow fO = cute.make_tensor(utils.elem_pointer(stO, (head_idx, grow * self.tile_hdimv + lane * cute.size(acc_O))), cute.make_layout(cute.size(acc_O))) for i in cutlass.range(cute.size(acc_O), unroll_full=True): acc_O[i] = fO[i] fS = cute.make_tensor(utils.elem_pointer(stS, (head_idx, grow * 16 + lane * 4)), cute.make_layout(4)) nrow = cute.size(softmax.row_max) for r in cutlass.range(nrow, unroll_full=True): softmax.row_max[r] = fS[r] softmax.row_sum[r] = fS[nrow + r] # kernel A ran this warp's 64-row half iff the half's first row is in the sequence; else consume every block n_far_top = n_block_max if m_block * self.tile_m + (wrow // 64) * 64 < seqlen.seqlen_q: n_far_top = cutlass.min(cutlass.max(Int32(stS[head_idx, grow * 16 + 128]), n_block_min), n_block_max) for n_tile in cutlass.range(n_block_max - n_far_top, unroll=1): k_wait_token = pipeline_k.consumer_try_wait(consumer_state) pipeline_k.consumer_wait(consumer_state, k_wait_token) pipeline_k.consumer_release(consumer_state) v_wait_token = pipeline_v.consumer_try_wait(consumer_state) pipeline_v.consumer_wait(consumer_state, v_wait_token) pipeline_v.consumer_release(consumer_state) consumer_state.advance() # the first far block is peeled (as the image peels its first block): without it ptxas spills part of acc_O in # the loop at 232 registers (CPU: LDL 46 per block vs 0 peeled) if n_far_top > n_block_min: consumer_state = compute_one_n_block( n_far_top - 1, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=False, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, ) for n_tile in cutlass.range(n_far_top - 1 - n_block_min, unroll=1): consumer_state = compute_one_n_block( n_far_top - n_tile - 2, consumer_state, mma_params, smem_copy_params, softmax, pipeline_k, pipeline_v, score_mod=self.score_mod, sBias=sBias, pipeline_bias=pipeline_bias, base_softmax_scale=base_softmax_scale, apply_bias=False, batch_idx=batch_idx, head_idx=head_idx, m_block=m_block, seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, mask_fn=mask_fn_no_seqlen, )
if const_expr(self._uses_n_distributed_qk()): cO = cute.make_identity_tensor((self.tile_m, self.tile_hdimv)) tOcO_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_pv.partition_C(cO) ) num_rows_pv = acc_O.shape[0][0] * acc_O.shape[1] row_scale_pv = cute.make_rmem_tensor(num_rows_pv, Float32) lse = cute.make_rmem_tensor(num_rows_pv, Float32) for r in cutlass.range(cute.size(row_scale_pv), unroll_full=True): row = tOcO_mn_finalize[r, 0][0] row_scale_pv[r] = sRowScale[0, row] lse[r] = sLSE[row] self._rescale_O(acc_O, row_scale_pv) elif const_expr(split_pv_warps): if const_expr(is_qk_owner): sink_val = None if const_expr(learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = Float32(learnable_sink[head_idx]) else: sink_val = cute.make_rmem_tensor_like(softmax.row_max, Float32) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) for r in cutlass.range(cute.size(sink_val), unroll_full=True): row = m_block * self.tile_m + tScS_mn_finalize[r][0] q_head_idx = ( row % self.qhead_per_kvhead + head_idx * self.qhead_per_kvhead ) sink_val[r] = Float32(learnable_sink[q_head_idx]) if const_expr(self.is_split_kv and learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = sink_val if split_idx == 0 else -Float32.inf elif split_idx != 0: sink_val.fill(-Float32.inf) row_scale_qk = softmax.finalize(sink_val=sink_val) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) if tScS_mn_finalize[0][1] == 0: for r in cutlass.range(cute.size(row_scale_qk), unroll_full=True): row = tScS_mn_finalize[r][0] sRowScale[2, row] = row_scale_qk[r] sLSE[row] = softmax.row_sum[r] cute.arch.fence_view_async_shared() cute.arch.barrier( barrier_id=int(NamedBarrierFwd.PFull), number_of_threads=self.num_mma_threads, ) cO = cute.make_identity_tensor((self.tile_m, self.tile_hdimv)) tOcO_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_pv.partition_C(cO) ) num_rows_pv = acc_O.shape[0][0] * acc_O.shape[1] row_scale_pv = cute.make_rmem_tensor(num_rows_pv, Float32) lse = cute.make_rmem_tensor(num_rows_pv, Float32) for r in cutlass.range(cute.size(row_scale_pv), unroll_full=True): row = tOcO_mn_finalize[r, 0][0] row_scale_pv[r] = sRowScale[2, row] lse[r] = sLSE[row] self._rescale_O(acc_O, row_scale_pv) else: sink_val = None if const_expr(learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = Float32(learnable_sink[head_idx]) else: sink_val = cute.make_rmem_tensor_like(softmax.row_max, Float32) cS = cute.make_identity_tensor((self.tile_m, self.tile_n)) tScS_mn_finalize = layout_utils.reshape_acc_to_mn( thr_mma_qk.partition_C(cS) ) for r in cutlass.range(cute.size(sink_val), unroll_full=True): row = m_block * self.tile_m + tScS_mn_finalize[r][0] q_head_idx = ( row % self.qhead_per_kvhead + head_idx * self.qhead_per_kvhead ) sink_val[r] = Float32(learnable_sink[q_head_idx]) if const_expr(self.is_split_kv and learnable_sink is not None): if const_expr(not self.pack_gqa): sink_val = sink_val if split_idx == 0 else -Float32.inf elif split_idx != 0: sink_val.fill(-Float32.inf) row_scale = softmax.finalize(sink_val=sink_val) softmax.rescale_O(acc_O, row_scale) lse = softmax.row_sum
self.epilogue( acc_O, lse, mO, mLSE, sO, seqlen, gmem_tiled_copy_O, None, tiled_mma_pv, tidx, m_block, head_idx, batch_idx, split_idx, ) return consumer_state
@cute.jit def compute_one_n_block( self, n_block: Int32, consumer_state: PipelineState, mma_params: SimpleNamespace, smem_copy_params: SimpleNamespace, softmax: Softmax, pipeline_k: PipelineAsync, pipeline_v: PipelineAsync, score_mod: Callable | None, sBias: Optional[cute.Tensor], pipeline_bias: Optional[PipelineAsync], base_softmax_scale: Optional[Float32], apply_bias: bool, batch_idx: Int32, head_idx: Int32, m_block: Int32, seqlen: SeqlenInfoQK, aux_data: AuxData = AuxData(), fastdiv_mods=None, mask_fn: Optional[Callable] = None, is_first_n_block: cutlass.Constexpr = False, check_inf: cutlass.Constexpr = True, ): acc_shape_S = mma_params.thr_mma_qk.partition_shape_C( (self.tile_m, self.tile_n) ) acc_S = cute.make_rmem_tensor(acc_shape_S, Float32) acc_S.fill(0.0) k_wait_token = pipeline_k.consumer_try_wait(consumer_state) pipeline_k.consumer_wait(consumer_state, k_wait_token) self._gemm_qk_phase_local( mma_params.thr_mma_qk, acc_S, smem_copy_params.sQ, smem_copy_params.sK[None, None, consumer_state.index], smem_copy_params.smem_thr_copy_Q, smem_copy_params.smem_thr_copy_K, ) pipeline_k.consumer_release(consumer_state)
if const_expr(self.has_bias): self.apply_sheared_bias( acc_S, mma_params.thr_mma_qk, sBias, pipeline_bias, consumer_state, base_softmax_scale, apply_bias, ) elif const_expr(N64_FAR): # n64 kernel B: apply_sheared_bias(apply_bias=False) of n54's far loop, verbatim for i in cutlass.range(cute.size(acc_S.shape), unroll_full=True): acc_S[i] = acc_S[i] * base_softmax_scale if const_expr(score_mod is not None): self.apply_score_mod( mma_params.thr_mma_qk, batch_idx, head_idx, m_block, acc_S, n_block, softmax_scale=( 1.0 if const_expr(self.has_bias) else softmax.softmax_scale ), seqlen=seqlen, aux_data=aux_data, fastdiv_mods=fastdiv_mods, ) if const_expr(mask_fn is not None): mask_fn(acc_S, n_block=n_block) row_scale = softmax.online_softmax( acc_S, is_first=is_first_n_block, check_inf=check_inf ) softmax.rescale_O(mma_params.acc_O, row_scale) rP = cute.make_fragment_like(acc_S, self.dtype) rP.store(acc_S.load().to(self.dtype)) tOrP = layout_utils.reshape_acc_to_frgA(rP)
v_wait_token = pipeline_v.consumer_try_wait(consumer_state) pipeline_v.consumer_wait(consumer_state, v_wait_token) self._gemm_pv_phase_local( mma_params.thr_mma_pv, mma_params.acc_O, tOrP, smem_copy_params.sV[None, None, consumer_state.index], smem_copy_params.smem_thr_copy_V, ) pipeline_v.consumer_release(consumer_state) consumer_state.advance() return consumer_state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369"""n66 build file n66fb.py (ctrl seat, 2026-11-24; = forms/fb.py f7130ab6 + BANK / Message / TREE_REV). BANK True = form FB, BANK False = form C2(the same controller with the FP32 messages read from memory, i.e. message_controllers alone). Form FB: LoopMessageBank.mix on a 2-source bank in ONE Triton kernel per visit, one program perBLOCK_M-row block for ALL of the visit's controllers (3 on the attention side, 1 on the MLP side). Meant to be BITWISE equal toS3's served pair attn_res(bank, None, queries, normalize_values=True) + message_controllers (n50 build 4 = the served 3 kernels),by copying each served order (the helpers are form b build 6's, n50b_fused.py 3df3c785, bitwise in mb8-mb11 with powered controls): - bank stats (image AttnResFwdKernel order): per source, thread t of NT (96 for 3 queries, 64 for 1) holds x[4 NT c + 4 t + v], one fma.rn chain over (c, v) for sum(x * x) (shared by the queries, as in the CuTe kernel) and one per query for sum(x * q); lane butterfly xor 16..1; warps added in order from 0.0; rstd = rsqrt(fma(sumsq, 1/2304, eps)); softmax over the 2 sources; message = mul(fma(p1, x1, fma(p0, x0, 0)), inv) recomputed wherever a message value is needed (never written); - dest / message row RMS: the served _controller_norm order (packed f32x2 tree over f, g, h, b; lane butterfly; warp tree xor 4, 2, 1), computed for RB rows at a time (each size-2 sum is one add, so the order does not depend on the layout); - down: 1024-wide K groups from zero, BLOCK_K tiles in k order (dest tiles then message tiles inside a group), groups summed in order; tiles past K masked to zero as served; on local layers the dest half's normalized tile is shared by the 3 controllers; - mix: bf16 hidden @ gain / forget (K 64 from zero), (1 - tanh(f)) * dest + tanh(g) * message, libdevice tanh, no fp fusion.What it removes vs S3 (per 8K chunk, trace map): the bank AttnRes kernels (messages FP32 written 7.25 GB and read back 7.25 GB),the per-controller recompute that sank n50 form b build 5 (+37 ms: bank stats and dest reads once per controller program), and therow-at-a-time stats pass. Controls (failing on purpose): CHAIN_REV (bank per-thread chain walked backwards), FP_FUSION (launch)."""import os
import tritonimport triton.language as tlfrom triton.language.extra import libdevice
_BANK_CFG = {3: (96, 6, 3, 128), 1: (64, 9, 2, 64)} # queries -> (AttnRes compute threads, vec chunks, warps, stat tile lanes) at D 2304
@triton.jitdef _tree3(v, RB: tl.constexpr, TREE_REV: tl.constexpr = False): """served _controller_norm order on an (RB, 256, 16) tile (element 2048 h + 8 t + 4 g + 2 f + b at [., t, 8 h + 4 g + 2 f + b]). TREE_REV (failing control only): the in-thread tree pairs b first (then f, g, h) instead of f, g, h, b.""" q = tl.reshape(v * v, (RB, 256, 2, 2, 2, 2)) if TREE_REV: q = tl.sum(q, axis=5) q = tl.sum(q, axis=4) q = tl.sum(q, axis=3) a = tl.sum(q, axis=2) else: q = tl.sum(q, axis=4) q = tl.sum(q, axis=3) q = tl.sum(q, axis=2) a = tl.sum(q, axis=2) a = tl.sum(tl.reshape(a, (RB, 8, 2, 16)), axis=2) a = tl.sum(tl.reshape(a, (RB, 8, 2, 8)), axis=2) a = tl.sum(tl.reshape(a, (RB, 8, 2, 4)), axis=2) a = tl.sum(tl.reshape(a, (RB, 8, 2, 2)), axis=2) a = tl.sum(tl.reshape(a, (RB, 8, 2, 1)), axis=2) a = tl.reshape(a, (RB, 8)) a = tl.sum(tl.reshape(a, (RB, 2, 4)), axis=1) a = tl.sum(tl.reshape(a, (RB, 2, 2)), axis=1) return tl.sum(a, axis=1)
@triton.jitdef _warp_tree(a, BLOCK_M: tl.constexpr, NW4: tl.constexpr): a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 16)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 8)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 4)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 2)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 1)), axis=2) return tl.reshape(a, (BLOCK_M, NW4))
@triton.jitdef _warps_in_order(a, BLOCK_M: tl.constexpr, NW: tl.constexpr, NW4: tl.constexpr): """(BLOCK_M, NW4) warp sums -> ((0 + w0) + w1) [+ w2].""" if NW4 == 4: lo, hi = tl.split(tl.reshape(a, (BLOCK_M, 2, 2))) w0, w2 = tl.split(lo) w1, w3 = tl.split(hi) s = (0.0 + w0) + w1 if NW == 3: s = s + w2 else: w0, w1 = tl.split(a) s = (0.0 + w0) + w1 return s
@triton.jitdef _red(a, BLOCK_M: tl.constexpr, NW: tl.constexpr, NTP: tl.constexpr): return _warps_in_order(_warp_tree(a, BLOCK_M, NTP // 32), BLOCK_M, NW, NTP // 32)
@triton.jitdef _probs(ss0, ss1, dd0, dd1, d_rcp, eps, BLOCK_M: tl.constexpr): r0 = libdevice.rsqrt(tl.fma(ss0, d_rcp, eps)) r1 = libdevice.rsqrt(tl.fma(ss1, d_rcp, eps)) l0 = dd0 * r0 l1 = dd1 * r1 mx = tl.maximum(tl.maximum(tl.full((BLOCK_M,), float("-inf"), tl.float32), l0), l1) e0 = libdevice.exp(tl.fma(dd0, r0, -mx)) e1 = libdevice.exp(tl.fma(dd1, r1, -mx)) inv = tl.div_rn(tl.full((BLOCK_M,), 1.0, tl.float32), (0.0 + e0) + e1) return e0 * r0, e1 * r1, inv
@triton.jitdef _msg(x0, x1, p0, p1, inv): return tl.fma(p1, x1, tl.fma(p0, x0, 0.0)) * inv
@triton.jitdef _pick(v, s, BLOCK_M: tl.constexpr, RB: tl.constexpr): """rows [s RB, (s + 1) RB) of a (BLOCK_M,) vector (one nonzero term per output: exact for the positive stats used here).""" v2 = tl.reshape(v, (BLOCK_M // RB, RB)) sel = (tl.arange(0, BLOCK_M // RB) == s)[:, None] return tl.sum(tl.where(sel, v2, 0.0), axis=0)
@triton.jitdef _put(full, part, s, BLOCK_M: tl.constexpr, RB: tl.constexpr): f2 = tl.reshape(full, (BLOCK_M // RB, RB)) sel = (tl.arange(0, BLOCK_M // RB) == s)[:, None] return tl.reshape(tl.where(sel, part[None, :], f2), (BLOCK_M,))
@triton.jitdef _fb_kernel( Dest, X0, X1, Query, Message, Down, Gain, Forget, Out, T, DEST_STRIDE, MESSAGE_STRIDE, eps, bank_eps, d_rcp, W: tl.constexpr, R: tl.constexpr, BLOCK_R: tl.constexpr, NQ: tl.constexpr, SHARED: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_N: tl.constexpr, RB: tl.constexpr, NT: tl.constexpr, NC: tl.constexpr, NW: tl.constexpr, NTP: tl.constexpr, CHAIN_REV: tl.constexpr = False, NUM_STAGES: tl.constexpr = 2, BANK: tl.constexpr = True, TREE_REV: tl.constexpr = False,): row0 = tl.program_id(0) * BLOCK_M K: tl.constexpr = 2 * W GROUPS: tl.constexpr = (K + 1023) // 1024 ridx = tl.arange(0, BLOCK_M) rows = row0 + ridx row_ok = rows[:, None] < T rbase = rows[:, None].to(tl.int64) * W # ---- pass 0: bank AttnRes statistics, all queries at once (sumsq chains shared) ---- (BANK only) pa0 = tl.zeros((BLOCK_M,), tl.float32) pa1 = pa0 ia = pa0 pb0 = pa0 pb1 = pa0 ib = pa0 pc0 = pa0 pc1 = pa0 ic = pa0 if BANK: t = tl.arange(0, NTP) t_ok = t < NT s0 = tl.zeros((BLOCK_M, NTP), tl.float32) s1 = tl.zeros((BLOCK_M, NTP), tl.float32) a0 = tl.zeros((BLOCK_M, NTP), tl.float32) a1 = tl.zeros((BLOCK_M, NTP), tl.float32) b0 = tl.zeros((BLOCK_M, NTP), tl.float32) b1 = tl.zeros((BLOCK_M, NTP), tl.float32) c0 = tl.zeros((BLOCK_M, NTP), tl.float32) c1 = tl.zeros((BLOCK_M, NTP), tl.float32) smask = row_ok & t_ok[None, :] for cc in range(NC): # dynamic loop (compile time); same chain order for vv in tl.static_range(4): if CHAIN_REV: c = NC - 1 - cc v = 3 - vv else: c = cc v = vv e = 4 * NT * c + 4 * t + v x0 = tl.load(X0 + rbase + e[None, :], smask, other=0).to(tl.float32) x1 = tl.load(X1 + rbase + e[None, :], smask, other=0).to(tl.float32) s0 = tl.fma(x0, x0, s0) s1 = tl.fma(x1, x1, s1) qa = tl.load(Query + e, t_ok, other=0) a0 = tl.fma(x0, qa[None, :], a0) a1 = tl.fma(x1, qa[None, :], a1) if NQ == 3: qb = tl.load(Query + W + e, t_ok, other=0) qc = tl.load(Query + 2 * W + e, t_ok, other=0) b0 = tl.fma(x0, qb[None, :], b0) b1 = tl.fma(x1, qb[None, :], b1) c0 = tl.fma(x0, qc[None, :], c0) c1 = tl.fma(x1, qc[None, :], c1) ss0 = _red(s0, BLOCK_M, NW, NTP) ss1 = _red(s1, BLOCK_M, NW, NTP) pa0, pa1, ia = _probs(ss0, ss1, _red(a0, BLOCK_M, NW, NTP), _red(a1, BLOCK_M, NW, NTP), d_rcp, bank_eps, BLOCK_M) pb0 = pa0 pb1 = pa1 ib = ia pc0 = pa0 pc1 = pa1 ic = ia if NQ == 3: pb0, pb1, ib = _probs(ss0, ss1, _red(b0, BLOCK_M, NW, NTP), _red(b1, BLOCK_M, NW, NTP), d_rcp, bank_eps, BLOCK_M) pc0, pc1, ic = _probs(ss0, ss1, _red(c0, BLOCK_M, NW, NTP), _red(c1, BLOCK_M, NW, NTP), d_rcp, bank_eps, BLOCK_M) # ---- pass 1: dest / message row RMS in the served order, RB rows at a time ---- tt = tl.arange(0, 256) ii = tl.arange(0, 16) off = (ii[None, :] // 8) * 2048 + tt[:, None] * 8 + (ii[None, :] % 8) # (256, 16) rj = tl.arange(0, RB) rd_a = tl.zeros((BLOCK_M,), tl.float32) rd_b = tl.zeros((BLOCK_M,), tl.float32) rd_c = tl.zeros((BLOCK_M,), tl.float32) rm_a = tl.zeros((BLOCK_M,), tl.float32) rm_b = tl.zeros((BLOCK_M,), tl.float32) rm_c = tl.zeros((BLOCK_M,), tl.float32) for s in range(BLOCK_M // RB): # dynamic loop (compile time); rows are independent r3 = (row0 + s * RB + rj) ok3 = (r3 < T)[:, None, None] & (off < W)[None, :, :] o3 = r3.to(tl.int64)[:, None, None] * W + off[None, :, :] if BANK: z0 = tl.load(X0 + o3, ok3, other=0).to(tl.float32) z1 = tl.load(X1 + o3, ok3, other=0).to(tl.float32) za = tl.load(Dest + o3, ok3, other=0) rd_a = _put(rd_a, libdevice.rsqrt(tl.div_rn(_tree3(za, RB, TREE_REV), W) + eps), s, BLOCK_M, RB) if BANK: na = _msg(z0, z1, _pick(pa0, s, BLOCK_M, RB)[:, None, None], _pick(pa1, s, BLOCK_M, RB)[:, None, None], _pick(ia, s, BLOCK_M, RB)[:, None, None]) else: na = tl.load(Message + o3, ok3, other=0) rm_a = _put(rm_a, libdevice.rsqrt(tl.div_rn(_tree3(na, RB, TREE_REV), W) + eps), s, BLOCK_M, RB) if NQ == 3: if not SHARED: zb = tl.load(Dest + DEST_STRIDE + o3, ok3, other=0) zc = tl.load(Dest + 2 * DEST_STRIDE + o3, ok3, other=0) rd_b = _put(rd_b, libdevice.rsqrt(tl.div_rn(_tree3(zb, RB, TREE_REV), W) + eps), s, BLOCK_M, RB) rd_c = _put(rd_c, libdevice.rsqrt(tl.div_rn(_tree3(zc, RB, TREE_REV), W) + eps), s, BLOCK_M, RB) if BANK: nb = _msg(z0, z1, _pick(pb0, s, BLOCK_M, RB)[:, None, None], _pick(pb1, s, BLOCK_M, RB)[:, None, None], _pick(ib, s, BLOCK_M, RB)[:, None, None]) nc_ = _msg(z0, z1, _pick(pc0, s, BLOCK_M, RB)[:, None, None], _pick(pc1, s, BLOCK_M, RB)[:, None, None], _pick(ic, s, BLOCK_M, RB)[:, None, None]) else: nb = tl.load(Message + MESSAGE_STRIDE + o3, ok3, other=0) nc_ = tl.load(Message + 2 * MESSAGE_STRIDE + o3, ok3, other=0) rm_b = _put(rm_b, libdevice.rsqrt(tl.div_rn(_tree3(nb, RB, TREE_REV), W) + eps), s, BLOCK_M, RB) rm_c = _put(rm_c, libdevice.rsqrt(tl.div_rn(_tree3(nc_, RB, TREE_REV), W) + eps), s, BLOCK_M, RB) if SHARED: rd_b = rd_a rd_c = rd_a # ---- pass 2: down projection, dest tiles then message tiles in k order inside each 1024-wide group ---- rank = tl.arange(0, BLOCK_R) ks = tl.arange(0, BLOCK_K) wk = rank[None, :] < R ha = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) hb = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) hc = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) for group in tl.static_range(GROUPS): G0 = group * 1024 ND = (1024 if W - G0 >= 1024 else (W - G0 if W > G0 else 0)) // BLOCK_K # dest tiles of this group (compile time) qa_ = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) qb_ = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) qc_ = tl.zeros((BLOCK_M, BLOCK_R), tl.float32) for tile in tl.range(0, ND, num_stages=NUM_STAGES): k = G0 + tile * BLOCK_K + ks xa = tl.load(Dest + rbase + k[None, :], row_ok, other=0) wa = tl.load(Down + rank[None, :] * K + k[:, None], wk, other=0) qa_ = tl.dot((xa * rd_a[:, None]).to(tl.bfloat16), wa, qa_) if NQ == 3: wb = tl.load(Down + R * K + rank[None, :] * K + k[:, None], wk, other=0) wc = tl.load(Down + 2 * R * K + rank[None, :] * K + k[:, None], wk, other=0) if SHARED: qb_ = tl.dot((xa * rd_b[:, None]).to(tl.bfloat16), wb, qb_) qc_ = tl.dot((xa * rd_c[:, None]).to(tl.bfloat16), wc, qc_) else: xb = tl.load(Dest + DEST_STRIDE + rbase + k[None, :], row_ok, other=0) xc = tl.load(Dest + 2 * DEST_STRIDE + rbase + k[None, :], row_ok, other=0) qb_ = tl.dot((xb * rd_b[:, None]).to(tl.bfloat16), wb, qb_) qc_ = tl.dot((xc * rd_c[:, None]).to(tl.bfloat16), wc, qc_) for tile in tl.range(ND, 1024 // BLOCK_K, num_stages=NUM_STAGES): k = G0 + tile * BLOCK_K + ks kin = (k[None, :] >= W) & (k[None, :] < K) mofs = rbase + (k[None, :] - W) if BANK: y0 = tl.load(X0 + mofs, row_ok & kin, other=0).to(tl.float32) y1 = tl.load(X1 + mofs, row_ok & kin, other=0).to(tl.float32) ma = _msg(y0, y1, pa0[:, None], pa1[:, None], ia[:, None]) else: ma = tl.load(Message + mofs, row_ok & kin, other=0) kw = wk & (k[:, None] < K) wa = tl.load(Down + rank[None, :] * K + k[:, None], kw, other=0) qa_ = tl.dot((ma * rm_a[:, None]).to(tl.bfloat16), wa, qa_) if NQ == 3: if BANK: mb = _msg(y0, y1, pb0[:, None], pb1[:, None], ib[:, None]) mc = _msg(y0, y1, pc0[:, None], pc1[:, None], ic[:, None]) else: mb = tl.load(Message + MESSAGE_STRIDE + mofs, row_ok & kin, other=0) mc = tl.load(Message + 2 * MESSAGE_STRIDE + mofs, row_ok & kin, other=0) wb = tl.load(Down + R * K + rank[None, :] * K + k[:, None], kw, other=0) wc = tl.load(Down + 2 * R * K + rank[None, :] * K + k[:, None], kw, other=0) qb_ = tl.dot((mb * rm_b[:, None]).to(tl.bfloat16), wb, qb_) qc_ = tl.dot((mc * rm_c[:, None]).to(tl.bfloat16), wc, qc_) if group == 0: ha = qa_ hb = qb_ hc = qc_ else: ha = ha + qa_ hb = hb + qb_ hc = hc + qc_ ha = ha.to(tl.bfloat16) hb = hb.to(tl.bfloat16) hc = hc.to(tl.bfloat16) # ---- pass 3: gain / forget and the tanh mix; dest and bank tiles loaded once for all controllers ---- for start in tl.range(0, W, BLOCK_N, num_stages=NUM_STAGES): cn = start + tl.arange(0, BLOCK_N) col_ok = cn[None, :] < W mask = row_ok & col_ok wofs = cn[None, :] * R + rank[:, None] wok = col_ok & (rank[:, None] < R) offs = rbase + cn[None, :] if BANK: y0 = tl.load(X0 + offs, mask, other=0).to(tl.float32) y1 = tl.load(X1 + offs, mask, other=0).to(tl.float32) ma = _msg(y0, y1, pa0[:, None], pa1[:, None], ia[:, None]) else: ma = tl.load(Message + offs, mask, other=0) da = tl.load(Dest + offs, mask, other=0) g = tl.dot(ha, tl.load(Gain + wofs, wok, other=0)) f = tl.dot(ha, tl.load(Forget + wofs, wok, other=0)) out = (1.0 - libdevice.tanh(f)) * da + libdevice.tanh(g) * ma tl.store(Out + offs, out, mask) if NQ == 3: if SHARED: db = da dc = da else: db = tl.load(Dest + DEST_STRIDE + offs, mask, other=0) dc = tl.load(Dest + 2 * DEST_STRIDE + offs, mask, other=0) g = tl.dot(hb, tl.load(Gain + W * R + wofs, wok, other=0)) f = tl.dot(hb, tl.load(Forget + W * R + wofs, wok, other=0)) if BANK: mb = _msg(y0, y1, pb0[:, None], pb1[:, None], ib[:, None]) else: mb = tl.load(Message + MESSAGE_STRIDE + offs, mask, other=0) out = (1.0 - libdevice.tanh(f)) * db + libdevice.tanh(g) * mb tl.store(Out + T * W + offs, out, mask) g = tl.dot(hc, tl.load(Gain + 2 * W * R + wofs, wok, other=0)) f = tl.dot(hc, tl.load(Forget + 2 * W * R + wofs, wok, other=0)) if BANK: mc = _msg(y0, y1, pc0[:, None], pc1[:, None], ic[:, None]) else: mc = tl.load(Message + 2 * MESSAGE_STRIDE + offs, mask, other=0) out = (1.0 - libdevice.tanh(f)) * dc + libdevice.tanh(g) * mc tl.store(Out + 2 * T * W + offs, out, mask)
def fb_controllers(dest, dest_stride, x0, x1, queries, down, gain, forget, out, eps=1e-6, bank_eps=1e-6, block_m=16, block_k=64, block_n=64, rb=1, num_warps=8, num_stages=2, fp_fusion=False, chain_rev=False, message=None, message_stride=0, tree_rev=False, maxnreg=None): """dest: base tensor + element stride between controllers (0 = one shared stream), as inkling2_loop._stacked returns; x0 / x1: the two BF16 bank sources (T, W) (form FB, message None) or message + message_stride: the FP32 messages as _stacked returns them (form C2: the bank AttnRes ran); queries: (num, W) fp32 scaled loop queries (FB only); down (num, R, 2W), gain / forget (num, W, R) bf16; out: (num, T, W) fp32 contiguous. Returns out (the launch handle in fb_controllers.last).""" num, rank, k = down.shape tokens, width = out.shape[1], out.shape[2] bank = message is None assert width == 2304 and num in _BANK_CFG and k == 2 * width and out.is_contiguous() assert down.is_contiguous() and gain.is_contiguous() and forget.is_contiguous() if bank: assert queries.shape == (num, width) and queries.is_contiguous() and x0.is_contiguous() and x1.is_contiguous() else: x0 = x1 = queries = message assert 256 % block_k == 0 and block_m % rb == 0 nt, nc, nw, ntp = _BANK_CFG[num] shared = num == 1 or dest_stride == 0 grid = (triton.cdiv(tokens, block_m),) fb_controllers.last = _fb_kernel[grid]( dest, x0, x1, queries, message if message is not None else dest, down, gain, forget, out, tokens, dest_stride, message_stride, eps, bank_eps, 1.0 / width, width, rank, max(16, triton.next_power_of_2(rank)), num, shared, block_m, block_k, block_n, rb, nt, nc, nw, ntp, chain_rev, num_stages, bank, tree_rev, num_warps=num_warps, num_stages=num_stages, enable_fp_fusion=fp_fusion, **({"maxnreg": maxnreg} if maxnreg else {}), # ptxas register cap only (allocation, not arithmetic) ) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257"""n71 G2 resnorm (stack seat, 2026-11-22; GENERATED by make_g2.py, do not edit by hand): the servedattn_res(..., normalize_values=True) [kernels/ops/attention/inkling2_attn_res.py AttnResFwdKernel] + the RMSNorm it feeds[kernels/ops/layernorm/inkling2_rms_norm.py RMSNormFwd] in one kernel, never writing the FP32 AttnRes output. Orders: theAttnRes statistics, softmax and output chain as n50b build 6 read them from the image PTX / SASS (bitwise in mb9-mb11),generalized to N sources and the partial addend (add.rn on the last source, as compute_qk / compute_pv); the norm asn71_loopnorm.py (G3). Controls: NORM_ORDER 1 (norm groups reversed), PV_REV (output chain over sources reversed)."""import os
import torchimport tritonimport triton.language as tlfrom triton.language.extra import libdevice
@triton.jitdef _warp_tree(a, BLOCK_M: tl.constexpr, NW4: tl.constexpr): """(BLOCK_M, 32 NW4) per-thread partials -> (BLOCK_M, NW4) warp sums by the butterfly xor 16, 8, 4, 2, 1 (lane 0's value).""" a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 16)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 8)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 4)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 2)), axis=2) a = tl.sum(tl.reshape(a, (BLOCK_M, NW4, 2, 1)), axis=2) return tl.reshape(a, (BLOCK_M, NW4))
@triton.jitdef _warps_in_order(a, BLOCK_M: tl.constexpr, NW: tl.constexpr, NW4: tl.constexpr, WARP_REV: tl.constexpr = False): """(BLOCK_M, NW4) warp sums -> ((0 + w0) + w1) [+ w2], extracted by splits (no arithmetic). WARP_REV (failing control only): the warps added in reverse order.""" if NW4 == 4: lo, hi = tl.split(tl.reshape(a, (BLOCK_M, 2, 2))) # lo = (w0, w2), hi = (w1, w3) w0, w2 = tl.split(lo) w1, w3 = tl.split(hi) if WARP_REV: if NW == 3: s = ((0.0 + w2) + w1) + w0 else: s = (0.0 + w1) + w0 else: s = (0.0 + w0) + w1 if NW == 3: s = s + w2 else: w0, w1 = tl.split(a) if WARP_REV: s = (0.0 + w1) + w0 else: s = (0.0 + w0) + w1 return s
@triton.jitdef _lane_chain(acc, x, BLOCK_M: tl.constexpr, NORM_ORDER: tl.constexpr): """Add one 64-column tile (half of a 128-column group j: 16 lanes) of the row's squares into acc[BLOCK_M, 16 lanes] in the served order: column 128 j + 64 h + 4 l + v -> lane 16 h + l, v = 0, 1, 2, 3 in order (fma), as the served thread's in-register chain.""" x4 = tl.reshape(x, (BLOCK_M, 16, 2, 2)) # [r, l, i, k], v = 2 i + k a, b = tl.split(x4) # a: v in (0, 2), b: v in (1, 3), indexed by i x0, x2 = tl.split(a) x1, x3 = tl.split(b) if NORM_ORDER == 2: # control: no contraction acc = acc + x0 * x0 acc = acc + x1 * x1 acc = acc + x2 * x2 acc = acc + x3 * x3 else: acc = tl.fma(x0, x0, acc) acc = tl.fma(x1, x1, acc) acc = tl.fma(x2, x2, acc) acc = tl.fma(x3, x3, acc) return acc
@triton.jitdef _lane_tree(acc_lo, acc_hi, BLOCK_M: tl.constexpr): """The served lane butterfly xor 16, 8, 4, 2, 1: xor 16 = lane l + lane l + 16 = acc_lo + acc_hi, then each step is one add over a size-2 axis (commutative, so the order does not depend on the layout this kernel gets).""" s = acc_lo + acc_hi s = tl.sum(tl.reshape(s, (BLOCK_M, 2, 8)), axis=1) s = tl.sum(tl.reshape(s, (BLOCK_M, 2, 4)), axis=1) s = tl.sum(tl.reshape(s, (BLOCK_M, 2, 2)), axis=1) s = tl.sum(tl.reshape(s, (BLOCK_M, 2, 1)), axis=1) return tl.reshape(s, (BLOCK_M,))
@triton.jitdef _src(X0, X1, X2, X3, X4, n: tl.constexpr): if n == 0: return X0 elif n == 1: return X1 elif n == 2: return X2 elif n == 3: return X3 else: return X4
@triton.jitdef _pick3(a, idx, n: tl.constexpr): """slot n of the last axis of a 3-D tensor (one nonzero term plus zeros: the value itself).""" return tl.sum(tl.where(idx == n, a, 0.0), axis=2)
@triton.jitdef _pick2(a, idx, n: tl.constexpr): """slot n of the last axis of a 2-D tensor.""" return tl.sum(tl.where(idx == n, a, 0.0), axis=1)
@triton.jitdef _load_src(X0, X1, X2, X3, X4, Addend, base, e, mask, n: tl.constexpr, N: tl.constexpr, HAS_ADDEND: tl.constexpr): """source n at element offsets e (FP32); the last source carries the partial addend: x = add.rn(x, addend).""" x = tl.load(_src(X0, X1, X2, X3, X4, n) + base + e, mask, other=0).to(tl.float32) if HAS_ADDEND: if n == N - 1: x = x + tl.load(Addend + base + e, mask, other=0).to(tl.float32) return x
@triton.jitdef _mix_tile(X0, X1, X2, X3, X4, Addend, P, inv, nidx, base, cols, mask, N: tl.constexpr, HAS_ADDEND: tl.constexpr, BLOCK_M: tl.constexpr, QP: tl.constexpr, BLOCK_N: tl.constexpr, INTERP: tl.constexpr, PV_REV: tl.constexpr): """AttnRes output on a (BLOCK_M, QP, BLOCK_N) tile: mul.rn(fma.rn chain over sources n of (p_n, x_n) from 0, inv), the served compute_pv order (PV_REV: failing control, sources walked backwards).""" acc = tl.zeros((BLOCK_M, QP, BLOCK_N), tl.float32) for nn in tl.static_range(N): n = nn + PV_REV * (N - 1 - 2 * nn) # PV_REV (control): N - 1 - nn x = _load_src(X0, X1, X2, X3, X4, Addend, base, cols[None, :], mask, n, N, HAS_ADDEND) p = _pick3(P, nidx[None, None, :], n) if INTERP: acc = p[:, :, None] * x[:, None, :] + acc else: acc = tl.fma(p[:, :, None], x[:, None, :], acc) return acc * inv[:, :, None]
@triton.jitdef _resnorm_kernel( X0, X1, X2, X3, X4, Addend, Query, NormW, Y, T, d_rcp, eps, norm_eps, NORMW_STRIDE, W: tl.constexpr, N: tl.constexpr, HAS_ADDEND: tl.constexpr, Q: tl.constexpr, QP: tl.constexpr, NP: tl.constexpr, NT: tl.constexpr, NC: tl.constexpr, NW: tl.constexpr, NTP: tl.constexpr, BLOCK_M: tl.constexpr, INTERP: tl.constexpr = False, NORM_ORDER: tl.constexpr = 0, PV_REV: tl.constexpr = False, STORE_MIX: tl.constexpr = False,): tl.static_assert(W % 128 == 0, "W must be a whole number of 128-column groups") tl.static_assert(4 * NT * NC == W, "served AttnRes layout: thread t of NT holds x[4 NT c + 4 t + v]") row0 = tl.program_id(0) * BLOCK_M ridx = tl.arange(0, BLOCK_M) rows = row0 + ridx row_ok = rows[:, None] < T base = rows[:, None].to(tl.int64) * W t = tl.arange(0, NTP) t_ok = t < NT qi = tl.arange(0, QP) q_ok = qi < Q nidx = tl.arange(0, NP) # pass A: the served AttnResFwdKernel statistics per source (n50b's order, generalized to N sources + the addend) DD = tl.zeros((BLOCK_M, QP, NP), tl.float32) RR = tl.zeros((BLOCK_M, NP), tl.float32) for n in tl.static_range(N): s = tl.zeros((BLOCK_M, NTP), tl.float32) d = tl.zeros((BLOCK_M, QP, NTP), tl.float32) for c in tl.static_range(NC): for v in tl.static_range(4): e = 4 * NT * c + 4 * t + v x = _load_src(X0, X1, X2, X3, X4, Addend, base, e[None, :], row_ok & t_ok[None, :], n, N, HAS_ADDEND) qv = tl.load(Query + qi[:, None] * W + e[None, :], q_ok[:, None] & t_ok[None, :], other=0) if INTERP: s = x * x + s d = x[:, None, :] * qv[None, :, :] + d else: s = tl.fma(x, x, s) d = tl.fma(x[:, None, :], qv[None, :, :], d) ss = _warps_in_order(_warp_tree(s, BLOCK_M, NTP // 32), BLOCK_M, NW, NTP // 32) dd = tl.reshape(_warps_in_order(_warp_tree(tl.reshape(d, (BLOCK_M * QP, NTP)), BLOCK_M * QP, NTP // 32), BLOCK_M * QP, NW, NTP // 32), (BLOCK_M, QP)) if INTERP: r = tl.rsqrt(ss * d_rcp + eps) else: r = libdevice.rsqrt(tl.fma(ss, d_rcp, eps)) RR = tl.where(nidx[None, :] == n, r[:, None], RR) DD = tl.where(nidx[None, None, :] == n, dd[:, :, None], DD) # softmax over the sources in order (one thread per query in the served kernel) mx = tl.full((BLOCK_M, QP), float("-inf"), tl.float32) for n in tl.static_range(N): mx = tl.maximum(mx, _pick3(DD, nidx[None, None, :], n) * _pick2(RR, nidx[None, :], n)[:, None]) ssum = tl.zeros((BLOCK_M, QP), tl.float32) P = tl.zeros((BLOCK_M, QP, NP), tl.float32) for n in tl.static_range(N): dn = _pick3(DD, nidx[None, None, :], n) rn = _pick2(RR, nidx[None, :], n)[:, None] if INTERP: ex = tl.exp(dn * rn - mx) else: ex = libdevice.exp(tl.fma(dn, rn, -mx)) ssum = ssum + ex P = tl.where(nidx[None, None, :] == n, (ex * rn)[:, :, None], P) if INTERP: inv = 1.0 / ssum else: inv = tl.div_rn(tl.full((BLOCK_M, QP), 1.0, tl.float32), ssum) mask3 = row_ok[:, :, None] & q_ok[None, :, None] # pass B: the output tile by tile, squares into the served RMSNorm order (64-column halves: lanes 16 h .. 16 h + 15) acc_lo = tl.zeros((BLOCK_M * QP, 16), tl.float32) acc_hi = tl.zeros((BLOCK_M * QP, 16), tl.float32) for jj in tl.range(0, W // 128): if NORM_ORDER == 1: # control: groups j descending j = W // 128 - 1 - jj else: j = jj for h in tl.static_range(2): cols = 128 * j + 64 * h + tl.arange(0, 64) out = _mix_tile(X0, X1, X2, X3, X4, Addend, P, inv, nidx, base, cols, row_ok, N, HAS_ADDEND, BLOCK_M, QP, 64, INTERP, PV_REV) if h == 0: acc_lo = _lane_chain(acc_lo, tl.reshape(out, (BLOCK_M * QP, 64)), BLOCK_M * QP, NORM_ORDER) else: acc_hi = _lane_chain(acc_hi, tl.reshape(out, (BLOCK_M * QP, 64)), BLOCK_M * QP, NORM_ORDER) sumsq = tl.reshape(_lane_tree(acc_lo, acc_hi, BLOCK_M * QP), (BLOCK_M, QP)) if INTERP: rstd = 1.0 / tl.sqrt(sumsq / W + norm_eps) else: rstd = libdevice.rsqrt(tl.div_rn(sumsq, W) + norm_eps) # pass C: the output recomputed, normalized, stored (STORE_MIX debug: the FP32 AttnRes output itself) for j in tl.range(0, W // 64): cols = 64 * j + tl.arange(0, 64) out = _mix_tile(X0, X1, X2, X3, X4, Addend, P, inv, nidx, base, cols, row_ok, N, HAS_ADDEND, BLOCK_M, QP, 64, INTERP, PV_REV) offs = qi[None, :, None].to(tl.int64) * T * W + base[:, :, None] + cols[None, None, :] if STORE_MIX: tl.store(Y + offs, out, mask3) else: w = tl.load(NormW + qi[:, None] * NORMW_STRIDE + cols[None, :], q_ok[:, None], other=0).to(tl.float32) y = (out * rstd[:, :, None]) * w[None, :, :] tl.store(Y + offs, y.to(Y.dtype.element_ty), mask3)
_LAYOUT = {1: (64, 9, 2, 64), 3: (96, 6, 3, 128)} # served AttnRes config for W 2304: (threads, chunks, warps, padded threads)
def resnorm(sources, addend, queries, norm_w, y, eps=1e-6, norm_eps=1e-6, block_m=4, num_warps=4, norm_order=0, pv_rev=False, store_mix=False): """sources: [*blocks, partial] BF16 [T, W] (2..5), addend: BF16 [T, W] or None (added to the last source), queries: the scaled FP32 queries [Q, W], norm_w: [W] (shared) or [Q, W] (q / k / v norms), y: [Q, T, W] (BF16; FP32 for debug).""" T, W = sources[0].shape N, Q = len(sources), queries.shape[0] assert 2 <= N <= 5 and Q in _LAYOUT and W == 2304 nt, nc, nw, ntp = _LAYOUT[Q] xs = list(sources) + [sources[0]] * (5 - N) nws = 0 if norm_w.dim() == 1 else norm_w.stride(0) _resnorm_kernel[(triton.cdiv(T, block_m),)]( *xs, addend if addend is not None else sources[0], queries, norm_w, y, T, float(torch.tensor(1.0 / W, dtype=torch.float32)), eps, norm_eps, nws, W, N, addend is not None, Q, 4 if Q > 1 else 1, 8, nt, nc, nw, ntp, block_m, os.environ.get("TRITON_INTERPRET") == "1", norm_order, pv_rev, store_mix, num_warps=num_warps, enable_fp_fusion=False, ) return y123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""n71 G1 sconvres (stack seat, 2026-11-22; GENERATED by make_g1.py from the image's inkling2_sconv.py f65e8906, do not editby hand): the MLP short convolution of an extend batch (served tiled kernel, rows >= PREFILL_MIN_ROWS 2048, static weights,residual) fused with the layer's residual update (residual_add or the block-boundary add), so the BF16 conv output is neverwritten and read back (saves 2 B per element of [rows, 2304] per visit). Bit-identical by construction: the conv code is theimage kernel's text, its accumulator is rounded to BF16 exactly where the served store rounds it, and the residual sum keepsresidual_add's FP32 order from zeros. The sconv cache prepare / update calls around it stay the served ones.ROUND_CONV False = the failing control (FP32 conv added without its BF16 rounding)."""import torchimport tritonimport triton.language as tl
PREFILL_MIN_ROWS = 2048
@triton.jitdef _sconv_residual_kernel( X, Weight, Dynamic, Cache, Indices, Mask, Cu, Seq, Y, Attn, Partial, 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, HEAD_DIM: tl.constexpr, DYNAMIC: tl.constexpr, RESIDUAL: tl.constexpr, SCALE: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, USE_PDL: tl.constexpr = False, HAS_PARTIAL: tl.constexpr = True, ROUND_CONV: tl.constexpr = True,): """n71 G1: the image _sconv_prefill_kernel (verbatim above the store) + the residual update in the served order.""" if USE_PDL: tl.extra.cuda.gdc_wait() tl.extra.cuda.gdc_launch_dependents() 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 = tap if DYNAMIC else 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) if DYNAMIC: dyn = tl.load( Dynamic + rows[:, None] * (D // HEAD_DIM) * W + (col // HEAD_DIM)[None, :] * W + lag, valid, other=0, ).to(tl.float32) weight = tl.load(Weight + lag * SW0 + col * SW1, col < D, other=0).to( tl.float32 ) weight = weight[None, :] + dyn else: weight = ( tl.load(Weight + col * SW0 + tap * SW1, col < D, other=0) .to(X.dtype.element_ty) .to(tl.float32) )[None, :] if DYNAMIC and tap == 0: acc = value * weight else: acc = tl.fma(value, weight, acc) if RESIDUAL: acc = acc + current acc = acc * SCALE
if ROUND_CONV: conv = acc.to(tl.bfloat16).to(tl.float32) # the served BF16 output of the conv, read back by residual_add / torch add else: conv = acc # control: no BF16 rounding of the conv attn = tl.load(Attn + rows[:, None] * D + col[None, :], valid, other=0).to(tl.float32) if HAS_PARTIAL: # residual_add(partial, attention, conv): FP32 from zeros, argument order total = tl.zeros((BM, BN), tl.float32) total += tl.load(Partial + rows[:, None] * D + col[None, :], valid, other=0).to(tl.float32) total += attn total += conv else: # block boundary: attention + conv (torch BF16 add) total = attn + conv tl.store(Y + rows[:, None] * D + col[None, :], total, valid)
def sconv_residual(x, weight, cache, metadata, attention, partial=None, *, round_conv=True, use_pdl=False): """Served-equivalent of short_convolution(x, weight, cache, metadata) (extend, static weights, residual, rows >= 2048) followed by residual_add(partial, attention, conv) (or attention + conv when partial is None). Returns the new partial.""" assert x.shape[0] >= PREFILL_MIN_ROWS and x.stride(-1) == 1 and attention.shape == x.shape width = weight.shape[1] scale = (width + 1) ** -0.5 out = torch.empty_like(attention if partial is None else partial) _sconv_residual_kernel[(triton.cdiv(x.shape[0], 16), triton.cdiv(x.shape[1], 128))]( x, weight, None, cache, metadata["safe_idx"], metadata["cache_mask"], metadata["cu"], metadata["si"], out, attention.contiguous(), partial.contiguous() if partial is not None else None, x.shape[0], x.stride(0), *weight.stride(), *cache.stride(), x.shape[1], width, x.shape[1], False, True, scale, 16, 128, HAS_PARTIAL=partial is not None, ROUND_CONV=round_conv, enable_fp_fusion=False, **({"USE_PDL": True, "launch_pdl": True} if use_pdl else {}), ) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""n75 c12 (inkling2-spark packed seat, 2026-11-22): exact 12-bit packed BF16 weights for the served small-M GEMV.
Format (ported from the OKC bf16 board champion's sm_c12 format, problems/bf16/champion.py sm_c12_bytes l.663 /sm_c12_unpack l.686 / sm_pack_format l.709: low byte + sign + a 3-bit code of the upper seven exponent bits in a window): v = BF16 bits; lo = v & 0xFF (exponent LSB + 7 mantissa bits); s = v >> 15; eh = (v >> 8) & 0x7F (upper 7 exponent bits). nib = s << 3 | d with d = eh - base[n] when 0 <= d < 7, else d = 7 (ESC). base is per W row (GRAN 'row') or one value for the matrix (GRAN 'matrix'); it maximises the count of eh in [base, base + 7). LO [N, K] uint8 = lo. CD [N, K/2] uint8: inside each 256-wide K tile t, byte (n, 128 t + j) = nib(n, 256 t + j) | nib(n, 256 t + 128 + j) << 4, so the low nibbles code the tile's first K half and the high nibbles its second half. 1.5 bytes per weight + 1 byte per row. Differences from the board: (1) the window has 7 slots, not 8: code 7 marks an escape IN BAND; (2) an escape is not repaired from an escape list: the kernel reads that element from the resident BF16 original (the served path keeps it for prefill) with a masked load, so the tile fed to the dot is the original BF16 tile bit for bit; (3) base per row by default. pack_c12 checks the round trip bitwise (bits_equal(unpack_c12(pack), w)) and returns None if it fails (the caller then keeps the served path).
Kernel: the served sglang kernels/ops/gemm/sm12x_bf16_gemv.py _gemv_kernel (md5 7c173a3f) shape exactly: BN 32 columns perprogram, BK 256, x rows padded to MP 16, num_warps 4, FP32 accumulation in ONE in-place mma chain over K (Triton 3.7.1 ttgir:#mma v2 warpsPerCTA [1, 4], tt.dot(x, w, acc)); here each 256 tile is two chained dots of K 128 (the same 16 m16n8k16 stepsin the same K order on the same accumulator), so outputs equal the served kernel's bit for bit when the decoded tile equalsthe BF16 tile. BF16 out is RTNE of the FP32 sum (acc.to(bf16)); FP32 out stores the sum.Test paths (CPU interpreter only): DEC=1 stores the decoded tile bits instead of the GEMV; F32=1 runs the dot in FP32 'ieee'(the interpreter's BF16 dot is broken; work_decode memory note)."""import torchimport tritonimport triton.language as tl
BN, BK = 32, 256HK = BK // 2WIN = 7 # in-window code values 0..6; 7 = escapeESC = 7
@triton.jitdef _c12_gemv_kernel(X, W, LO, CD, BASE, Y, M, N, K, SX, SW, SY, BN: tl.constexpr, BK: tl.constexpr, MP: tl.constexpr, DEC: tl.constexpr, F32: tl.constexpr, CTRL: tl.constexpr = 0, DIAG: tl.constexpr = 0): HK: tl.constexpr = BK // 2 pid = tl.program_id(0) cols = pid * BN + tl.arange(0, BN) rows = tl.arange(0, MP) cm = cols[None, :] < N c64 = cols[None, :].to(tl.int64) base = tl.load(BASE + cols, cols < N, other=0).to(tl.int32)[None, :] kh = tl.arange(0, HK) acc = tl.zeros((MP, BN), tl.float32) acc2 = tl.zeros((MP, BN), tl.float32) # CTRL=1 only (failing control: second K halves on their own chain) for k0 in range(0, K, BK): ka = k0 + kh kb = ka + HK cd = tl.load(CD + c64 * (K // 2) + (k0 // 2 + kh)[:, None], cm, other=0).to(tl.int32) lo_a = tl.load(LO + c64 * K + ka[:, None], cm, other=0).to(tl.int32) lo_b = tl.load(LO + c64 * K + kb[:, None], cm, other=0).to(tl.int32) na = cd & 15 nb = cd >> 4 ea = (na & 7) == 7 eb = (nb & 7) == 7 ba = (((na >> 3) << 15) | ((base + (na & 7)) << 8) | lo_a).to(tl.uint16).to(tl.bfloat16, bitcast=True) bb = (((nb >> 3) << 15) | ((base + (nb & 7)) << 8) | lo_b).to(tl.uint16).to(tl.bfloat16, bitcast=True) if DIAG == 1: # timing only: no escape loads (escaped elements decode wrong) wa = ba wb = bb elif DIAG == 2: # timing / structure only: the raw BF16 tile, no packed bytes used (must equal the served output) wa = tl.load(W + c64 * SW + ka[:, None], cm, other=0.0) wb = tl.load(W + c64 * SW + kb[:, None], cm, other=0.0) else: oa = tl.load(W + c64 * SW + ka[:, None], ea & cm, other=0.0) ob = tl.load(W + c64 * SW + kb[:, None], eb & cm, other=0.0) wa = tl.where(ea, oa, ba) wb = tl.where(eb, ob, bb) if DEC: tl.store(Y + c64 * K + ka[:, None], wa.to(tl.int16, bitcast=True), cm) tl.store(Y + c64 * K + kb[:, None], wb.to(tl.int16, bitcast=True), cm) else: xa = tl.load(X + rows[:, None] * SX + ka[None, :], rows[:, None] < M, other=0.0) xb = tl.load(X + rows[:, None] * SX + kb[None, :], rows[:, None] < M, other=0.0) if F32: acc = tl.dot(xa.to(tl.float32), wa.to(tl.float32), acc, input_precision="ieee") acc = tl.dot(xb.to(tl.float32), wb.to(tl.float32), acc, input_precision="ieee") elif CTRL: acc = tl.dot(xa, wa, acc) acc2 = tl.dot(xb, wb, acc2) else: acc = tl.dot(xa, wa, acc) acc = tl.dot(xb, wb, acc) if CTRL: acc = acc + acc2 if not DEC: tl.store(Y + rows[:, None] * SY + cols[None, :], acc.to(Y.dtype.element_ty), (rows[:, None] < M) & cm)
def _hist_bases(eh: torch.Tensor) -> torch.Tensor: """Per-row window base maximising the count of eh in [base, base + WIN); eh [rows, K] int64 in 0..127.""" h = torch.zeros(eh.shape[0], 128, dtype=torch.int32, device=eh.device) h.scatter_add_(1, eh, torch.ones_like(eh, dtype=torch.int32)) c = torch.nn.functional.pad(h.cumsum(1), (1, 0)) # c[:, i] = count of eh < i return (c[:, WIN:] - c[:, :-WIN]).argmax(1) # [rows] in 0..128 - WIN
def _matrix_base(w: torch.Tensor, rows: int) -> int: h = torch.zeros(128, dtype=torch.int64, device=w.device) for r0 in range(0, w.shape[0], rows): h += torch.bincount(((w[r0:r0 + rows].view(torch.int16).to(torch.int32) >> 8) & 0x7F).flatten(), minlength=128) h = h.cpu() return int(torch.stack([h[b:b + WIN].sum() for b in range(128 - WIN + 1)]).argmax())
def pack_c12(w: torch.Tensor, gran: str = "row", check: bool = True, rows: int = 8192): """w [N, K] BF16 (K % 256 == 0, unit column stride) -> dict(lo, cd, base, n_esc, ...) or None if the bitwise round trip fails. Works in row chunks of `rows` (temporaries ~ rows x K x 8 B), so packing a 926 MB LM head stays small.""" assert w.dtype == torch.bfloat16 and w.dim() == 2 and w.shape[1] % BK == 0 and w.stride(1) == 1, (w.dtype, w.shape) n, k = w.shape dev = w.device lo = torch.empty((n, k), dtype=torch.uint8, device=dev) cd = torch.empty((n, k // 2), dtype=torch.uint8, device=dev) base = torch.empty((n,), dtype=torch.uint8, device=dev) mb = _matrix_base(w, rows) if gran == "matrix" else None n_esc = 0 for r0 in range(0, n, rows): r1 = min(n, r0 + rows) v = w[r0:r1].view(torch.int16).to(torch.int32) & 0xFFFF eh = (v >> 8) & 0x7F b = _hist_bases(eh.long()) if mb is None else torch.full((r1 - r0,), mb, dtype=torch.int64, device=dev) d = eh - b[:, None].to(torch.int32) inw = (d >= 0) & (d < WIN) nib = ((v >> 15) << 3) | torch.where(inw, d, torch.full_like(d, ESC)) nt = nib.view(r1 - r0, k // BK, 2, HK) cd[r0:r1] = (nt[:, :, 0] | (nt[:, :, 1] << 4)).reshape(r1 - r0, k // 2).to(torch.uint8) lo[r0:r1] = (v & 0xFF).to(torch.uint8) base[r0:r1] = b.to(torch.uint8) n_esc += int((~inw).sum()) del v, eh, d, inw, nib, nt pk = {"lo": lo, "cd": cd, "base": base, "n_esc": n_esc, "shape": (n, k), "gran": gran} if check and not check_c12(pk, w, rows): return None return pk
def bits_equal(a: torch.Tensor, b: torch.Tensor) -> bool: """Bitwise equality of two BF16 tensors (torch.equal on the float view fails on NaN).""" return a.shape == b.shape and torch.equal(a.contiguous().view(torch.int16), b.contiguous().view(torch.int16))
def unpack_c12(pk, w_orig: torch.Tensor, r0: int = 0, r1: int | None = None) -> torch.Tensor: """Reference decode (torch) of rows [r0, r1): in-window elements from the 12-bit fields, escapes from the resident original.""" n, k = pk["shape"] r1 = n if r1 is None else r1 cd = pk["cd"][r0:r1].to(torch.int32).view(r1 - r0, k // BK, 1, HK) nib = torch.cat([cd & 15, cd >> 4], dim=2).view(r1 - r0, k) bits = ((nib >> 3) << 15) | ((pk["base"][r0:r1].to(torch.int32)[:, None] + (nib & 7)) << 8) | pk["lo"][r0:r1].to(torch.int32) bits = torch.where((nib & 7) == ESC, w_orig[r0:r1].view(torch.int16).to(torch.int32) & 0xFFFF, bits) return bits.to(torch.int16).view(torch.bfloat16) # int32 -> int16 keeps the low 16 bits
def check_c12(pk, w: torch.Tensor, rows: int = 8192) -> bool: """Bitwise round trip unpack_c12(pack) == w, in row chunks.""" n, k = pk["shape"] if tuple(w.shape) != (n, k): return False return all(bits_equal(unpack_c12(pk, w, r0, min(n, r0 + rows)), w[r0:r0 + rows]) for r0 in range(0, n, rows))
def packed_bytes(pk) -> int: return pk["lo"].numel() + pk["cd"].numel() + pk["base"].numel()
CFG = (32, 4, 3) # (BN, num_warps, num_stages); any BN / warps / stages keep the per-element chain (k16 steps in K order)
def c12_gemv(x: torch.Tensor, w: torch.Tensor, pk, out_dtype=None, out=None, cfg=None, _dec=False, _f32=False, _ctrl=0, _diag=0, mp=None): """x[..., K] @ w[N, K]^T from the packed copy (w = the resident original: escapes only), FP32 accumulation in the served _gemv_kernel's order; out_dtype BF16 by default or into out ([M, N] view with unit column stride). No bias.""" n, k = pk["shape"] assert tuple(w.shape) == (n, k) and w.stride(1) == 1 and x.shape[-1] == k lead = x.shape[:-1] x2 = x.reshape(-1, k) m = x2.shape[0] if _dec: out = torch.empty((n, k), device=w.device, dtype=torch.int16) elif out is None: out = torch.empty((m, n), device=x.device, dtype=out_dtype or x.dtype) if m or _dec: bn, nw, ns = cfg or CFG mp = mp or (16 if m <= 16 else 32 if m <= 32 else 64) # rows padded to MP (the served route: always 16, m <= 16) assert m <= mp, (m, mp) _c12_gemv_kernel[(triton.cdiv(n, bn),)]( x2, w, pk["lo"], pk["cd"], pk["base"], out, m, n, k, x2.stride(0), w.stride(0), out.stride(0), BN=bn, BK=BK, MP=mp, DEC=_dec, F32=_f32, CTRL=_ctrl, DIAG=_diag, num_warps=nw, num_stages=ns) return out if _dec else out.view(*lead, n)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365"""n75 build 2 (inkling2-spark packed seat, 2026-11-22) + n137 build 2 (stack seat, 2026-11-24: c12m3_kernel / c12m3_gemv, the stacked 3-source qkvr visit in one launch; c12m_kernel and c12m_gemv unchanged): the same exact 12-bit format as n75_c12 (low byte + sign + 3-bit code ofthe upper 7 exponent bits in a per-row 7-slot window, code 7 = escape read from the resident BF16 original), streamed by a CUDAkernel in mma.sync B-fragment order. The FP32 order is the served Triton _gemv_kernel's: per output ONE in-placemma.sync.m16n8k16.row.col.f32.bf16.bf16.f32 chain over K in 16-wide steps, A = x rows (rows >= M are zero, as the served maskedload), B = the W tile; only the operand delivery differs, so outputs equal the served kernel's bit for bit.
Stream layout (pack_frag): warp tile t = 8 output columns, unit u = 8 k16 steps (128 k). Lane l owns column n = 8 t + l / 4 and,per step j, the B fragment b0 = W[n][16 s + 2 (l % 4) + {0, 1}], b1 = W[n][16 s + 8 + 2 (l % 4) + {0, 1}] (s = 8 u + j). Per(t, u): 3 segments x 32 lanes x 16 B: seg 0 / 1 = the lane's 32 low bytes (value 4 j + 2 r + h), seg 2 = 16 code bytes, byte4 q + i = nib(step 2 q, value i) | nib(step 2 q + 1, value i) << 4. 1.5 B per weight + 1 B per row (the same base array).Kernel: persistent CTAs of NW warps; x staged once per CTA in shared memory in A-fragment order; per unit one 3 x 16 B load perlane (prefetched one unit ahead), SWAR decode ((c & 0x07070707) + base * 0x01010101) | ((c << 4) & 0x80808080) and two__byte_perm per step; an escape (any code byte == 7) takes a branch that reads the original element. M <= 16, K % 128 == 0,N % 8 == 0; BF16 out = RTNE of the FP32 sum (cvt.rn), FP32 out = the sum."""import osimport torch
U = 8 # k16 steps per unit
CUDA_SRC = r'''#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <cuda_bf16.h>#include <stdint.h>
__device__ __forceinline__ void mma16816(float (&c)[4], uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t b0, uint32_t b1) { asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n" : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));}
// MT 1: rows 0-7 (a1 = a3 = 0); MT 2: rows 0-15. F32: FP32 out, else BF16 (RTNE).template <int NW, int MT, bool F32>__global__ void __launch_bounds__(NW * 32) c12m_kernel(const uint4* __restrict__ wp, const uint8_t* __restrict__ basep, const uint16_t* __restrict__ W, const uint16_t* __restrict__ x, void* __restrict__ outp, int M, int N, int K, int SX, int SW, int SY) { extern __shared__ uint4 xs[]; // [steps][32 lanes]: MT 1 -> uint2 (a0, a2), MT 2 -> uint4 (a0, a1, a2, a3) const int steps = K >> 4, NU = steps / 8, ntiles = N >> 3; uint2* xs2 = reinterpret_cast<uint2*>(xs); for (int i = threadIdx.x; i < steps * 32; i += NW * 32) { const int s = i >> 5, l = i & 31, r = l >> 2, kq = s * 16 + (l & 3) * 2; uint32_t a0 = 0, a1 = 0, a2 = 0, a3 = 0; if (r < M) { a0 = *reinterpret_cast<const uint32_t*>(x + (size_t)r * SX + kq); a2 = *reinterpret_cast<const uint32_t*>(x + (size_t)r * SX + kq + 8); } if (MT == 2 && r + 8 < M) { a1 = *reinterpret_cast<const uint32_t*>(x + (size_t)(r + 8) * SX + kq); a3 = *reinterpret_cast<const uint32_t*>(x + (size_t)(r + 8) * SX + kq + 8); } if (MT == 1) xs2[i] = make_uint2(a0, a2); else xs[i] = make_uint4(a0, a1, a2, a3); } __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, stride = gridDim.x * NW; int t = blockIdx.x * NW + warp; if (t >= ntiles) return; const int mytiles = (ntiles - 1 - t) / stride + 1, total = mytiles * NU; // flat loop over this warp's (tile, unit) pairs, one unit prefetched ahead const uint4* p = wp + (size_t)t * NU * 96 + lane; uint4 c0 = __ldg(p), c1 = __ldg(p + 32), c2 = __ldg(p + 64); float acc[4] = {0.f, 0.f, 0.f, 0.f}; int u = 0; int n = t * 8 + (lane >> 2); uint32_t base4 = (uint32_t)basep[n] * 0x01010101u; const uint16_t* wrow = W + (size_t)n * SW; for (int g = 0; g < total; ++g) { uint4 d0, d1, d2; const bool more = g + 1 < total; if (more) { const int tn = (u + 1 == NU) ? t + stride : t, un = (u + 1 == NU) ? 0 : u + 1; const uint4* q = wp + ((size_t)tn * NU + un) * 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; 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[s * 32 + lane]; mma16816(acc, a.x, 0u, a.y, 0u, b0, b1); } else { const uint4 a = xs[s * 32 + lane]; mma16816(acc, a.x, a.y, a.z, a.w, b0, b1); } } if (++u == NU) { // tile done: 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 (F32) { float* o = reinterpret_cast<float*>(outp); if (r < M) *reinterpret_cast<float2*>(o + (size_t)r * SY + col) = make_float2(acc[0], acc[1]); if (MT == 2 && r + 8 < M) *reinterpret_cast<float2*>(o + (size_t)(r + 8) * SY + col) = make_float2(acc[2], acc[3]); } else { __nv_bfloat16* o = reinterpret_cast<__nv_bfloat16*>(outp); 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]); } acc[0] = acc[1] = acc[2] = acc[3] = 0.f; u = 0; t += stride; if (t < ntiles) { n = t * 8 + (lane >> 2); base4 = (uint32_t)basep[n] * 0x01010101u; wrow = W + (size_t)n * SW; } } if (more) { c0 = d0; c1 = d1; c2 = d2; } }}
// n137 build 2: c12m_kernel for the stacked 3-source qkvr visit in ONE launch. Identical per-element code; the CTA's 128-row range (grid =// one tile per warp, the host refuses otherwise) picks its x source (rows [0, b1) and [b3, N): x0; [b1, b2): x1; [b2, b3): x2) and its output// block (src * blk elements: the [3M, N] buffer of the stock chunk(3) layout). Bounds are multiples of NW * 8 rows (host-checked).// MT 1: rows 0-7 (a1 = a3 = 0); MT 2: rows 0-15. F32: FP32 out, else BF16 (RTNE).template <int NW, int MT, bool F32>__global__ void __launch_bounds__(NW * 32) c12m3_kernel(const uint4* __restrict__ wp, const uint8_t* __restrict__ basep, const uint16_t* __restrict__ W, const uint16_t* __restrict__ x0, const uint16_t* __restrict__ x1, const uint16_t* __restrict__ x2, void* __restrict__ outp, int M, int N, int K, int SX, int SW, int SY, int b1, int b2, int b3, long long blk) { const int row0 = blockIdx.x * NW * 8; const int src = (row0 < b1 || row0 >= b3) ? 0 : (row0 < b2 ? 1 : 2); const uint16_t* __restrict__ x = src == 0 ? x0 : (src == 1 ? x1 : x2); const long long ob = (long long)src * blk; extern __shared__ uint4 xs[]; // [steps][32 lanes]: MT 1 -> uint2 (a0, a2), MT 2 -> uint4 (a0, a1, a2, a3) const int steps = K >> 4, NU = steps / 8, ntiles = N >> 3; uint2* xs2 = reinterpret_cast<uint2*>(xs); for (int i = threadIdx.x; i < steps * 32; i += NW * 32) { const int s = i >> 5, l = i & 31, r = l >> 2, kq = s * 16 + (l & 3) * 2; uint32_t a0 = 0, a1 = 0, a2 = 0, a3 = 0; if (r < M) { a0 = *reinterpret_cast<const uint32_t*>(x + (size_t)r * SX + kq); a2 = *reinterpret_cast<const uint32_t*>(x + (size_t)r * SX + kq + 8); } if (MT == 2 && r + 8 < M) { a1 = *reinterpret_cast<const uint32_t*>(x + (size_t)(r + 8) * SX + kq); a3 = *reinterpret_cast<const uint32_t*>(x + (size_t)(r + 8) * SX + kq + 8); } if (MT == 1) xs2[i] = make_uint2(a0, a2); else xs[i] = make_uint4(a0, a1, a2, a3); } __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, stride = gridDim.x * NW; int t = blockIdx.x * NW + warp; if (t >= ntiles) return; const int mytiles = (ntiles - 1 - t) / stride + 1, total = mytiles * NU; // flat loop over this warp's (tile, unit) pairs, one unit prefetched ahead const uint4* p = wp + (size_t)t * NU * 96 + lane; uint4 c0 = __ldg(p), c1 = __ldg(p + 32), c2 = __ldg(p + 64); float acc[4] = {0.f, 0.f, 0.f, 0.f}; int u = 0; int n = t * 8 + (lane >> 2); uint32_t base4 = (uint32_t)basep[n] * 0x01010101u; const uint16_t* wrow = W + (size_t)n * SW; for (int g = 0; g < total; ++g) { uint4 d0, d1, d2; const bool more = g + 1 < total; if (more) { const int tn = (u + 1 == NU) ? t + stride : t, un = (u + 1 == NU) ? 0 : u + 1; const uint4* q = wp + ((size_t)tn * NU + un) * 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; 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[s * 32 + lane]; mma16816(acc, a.x, 0u, a.y, 0u, b0, b1); } else { const uint4 a = xs[s * 32 + lane]; mma16816(acc, a.x, a.y, a.z, a.w, b0, b1); } } if (++u == NU) { // tile done: 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 (F32) { float* o = reinterpret_cast<float*>(outp) + ob; if (r < M) *reinterpret_cast<float2*>(o + (size_t)r * SY + col) = make_float2(acc[0], acc[1]); if (MT == 2 && r + 8 < M) *reinterpret_cast<float2*>(o + (size_t)(r + 8) * SY + col) = make_float2(acc[2], acc[3]); } else { __nv_bfloat16* o = reinterpret_cast<__nv_bfloat16*>(outp) + ob; 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]); } acc[0] = acc[1] = acc[2] = acc[3] = 0.f; u = 0; t += stride; if (t < ntiles) { n = t * 8 + (lane >> 2); base4 = (uint32_t)basep[n] * 0x01010101u; wrow = W + (size_t)n * SW; } } if (more) { c0 = d0; c1 = d1; c2 = d2; } }}
template <int NW, int MT, bool F32>static void launch(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 grid) { const int smem = (int)(K / 16) * 32 * (MT == 1 ? 8 : 16); auto kern = c12m_kernel<NW, MT, F32>; static int set = 0; if (set < smem) { C10_CUDA_CHECK(cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem)); set = smem; } if (grid <= 0) { int occ = 0, dev = 0, sms = 0; C10_CUDA_CHECK(cudaGetDevice(&dev)); C10_CUDA_CHECK(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev)); C10_CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, kern, NW * 32, smem)); const int64_t need = (N / 8 + NW - 1) / NW; grid = std::min<int64_t>(need, (int64_t)std::max(occ, 1) * sms); } kern<<<(int)grid, NW * 32, smem, at::cuda::getCurrentCUDAStream()>>>( reinterpret_cast<const uint4*>(wp.data_ptr()), base.data_ptr<uint8_t>(), reinterpret_cast<const uint16_t*>(W.data_ptr()), reinterpret_cast<const uint16_t*>(x.data_ptr()), out.data_ptr(), (int)M, (int)N, (int)K, (int)SX, (int)W.stride(0), (int)SY); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void c12m(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 grid) { const int64_t N = W.size(0), K = W.size(1); const bool f32 = out.scalar_type() == at::kFloat; const int mt = M <= 8 ? 1 : 2;#define C12M_CASE(NWV, MTV, F) if (nw == NWV && mt == MTV && f32 == F) return launch<NWV, MTV, F>(wp, base, W, x, out, M, N, K, SX, SY, grid); C12M_CASE(4, 1, false) C12M_CASE(4, 1, true) C12M_CASE(4, 2, false) C12M_CASE(4, 2, true) C12M_CASE(8, 1, false) C12M_CASE(8, 1, true) C12M_CASE(8, 2, false) C12M_CASE(8, 2, true) C12M_CASE(16, 1, false) C12M_CASE(16, 1, true) C12M_CASE(16, 2, false) C12M_CASE(16, 2, true) TORCH_CHECK(false, "c12m: unsupported nw ", nw);}
template <int NW, int MT, bool F32>static void launch3(const at::Tensor& wp, const at::Tensor& base, const at::Tensor& W, const at::Tensor& x0, const at::Tensor& x1, const at::Tensor& x2, at::Tensor& out, int64_t M, int64_t N, int64_t K, int64_t SX, int64_t SY, int64_t b1, int64_t b2, int64_t b3) { const int smem = (int)(K / 16) * 32 * (MT == 1 ? 8 : 16); auto kern = c12m3_kernel<NW, MT, F32>; static int set = 0; if (set < smem) { C10_CUDA_CHECK(cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem)); set = smem; } 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; TORCH_CHECK(need <= (int64_t)std::max(occ, 1) * sms, "c12m3: one tile per warp needs ", need, " CTAs, residency ", occ * sms); TORCH_CHECK(b1 % (NW * 8) == 0 && b2 % (NW * 8) == 0 && b3 % (NW * 8) == 0 && b1 <= b2 && b2 <= b3 && b3 <= N, "c12m3: bounds not CTA-aligned"); kern<<<(int)need, NW * 32, smem, at::cuda::getCurrentCUDAStream()>>>( reinterpret_cast<const uint4*>(wp.data_ptr()), base.data_ptr<uint8_t>(), reinterpret_cast<const uint16_t*>(W.data_ptr()), reinterpret_cast<const uint16_t*>(x0.data_ptr()), reinterpret_cast<const uint16_t*>(x1.data_ptr()), reinterpret_cast<const uint16_t*>(x2.data_ptr()), out.data_ptr(), (int)M, (int)N, (int)K, (int)SX, (int)W.stride(0), (int)SY, (int)b1, (int)b2, (int)b3, (long long)(M * SY)); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void c12m3(at::Tensor wp, at::Tensor base, at::Tensor W, at::Tensor x0, at::Tensor x1, at::Tensor x2, at::Tensor out, int64_t M, int64_t SX, int64_t SY, int64_t nw, int64_t b1, int64_t b2, int64_t b3) { const int64_t N = W.size(0), K = W.size(1); const bool f32 = out.scalar_type() == at::kFloat; const int mt = M <= 8 ? 1 : 2;#define C12M3_CASE(NWV, MTV, F) if (nw == NWV && mt == MTV && f32 == F) return launch3<NWV, MTV, F>(wp, base, W, x0, x1, x2, out, M, N, K, SX, SY, b1, b2, b3); C12M3_CASE(4, 1, false) C12M3_CASE(4, 2, false) C12M3_CASE(8, 1, false) C12M3_CASE(8, 2, false) C12M3_CASE(16, 1, false) C12M3_CASE(16, 2, false) TORCH_CHECK(false, "c12m3: unsupported nw ", nw, " or FP32 out");}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("c12m", &c12m); m.def("c12m3", &c12m3); }'''
_EXT = None
def build(verbose=False, build_dir=None): """Compile the extension (torch cpp_extension, sm_121a). Returns the module.""" global _EXT if _EXT is None: from torch.utils.cpp_extension import load_inline arch = os.environ.get("N75_CUDA_ARCH", "121a") kw = {} if build_dir: os.makedirs(build_dir, exist_ok=True) kw["build_directory"] = build_dir _EXT = load_inline("n75_c12m3", 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 pack_frag(pk, rows: int = 2048) -> torch.Tensor: """Fragment-order stream [T, NU, 3, 32, 16] uint8 from an n75_c12 pack (lo [N, K], cd [N, K/2] in 256-tile half layout).""" BK, HK = 256, 128 # n75_c12's CD tile layout (no import: the module path differs between the kit and the server) n, k = pk["shape"] assert n % 8 == 0 and k % 128 == 0 and k % BK == 0, (n, k) T, NU = n // 8, k // 128 out = torch.empty((T, NU, 3, 32, 16), dtype=torch.uint8, device=pk["lo"].device) for r0 in range(0, n, rows): r1 = min(n, r0 + rows); t0, t1 = r0 // 8, r1 // 8 lo = pk["lo"][r0:r1] cd = pk["cd"][r0:r1].view(r1 - r0, k // BK, 1, HK) nib = torch.cat([cd & 15, cd >> 4], dim=2).view(r1 - r0, k) # [T, nl, NU, j, r, q, h] -> [T, NU, nl, q, j, r, h]: lane = 4 nl + q, value = 4 j + 2 r + h lp = lo.view(t1 - t0, 8, NU, 8, 2, 4, 2).permute(0, 2, 1, 5, 3, 4, 6).reshape(t1 - t0, NU, 32, 32) np_ = nib.view(t1 - t0, 8, NU, 8, 2, 4, 2).permute(0, 2, 1, 5, 3, 4, 6).reshape(t1 - t0, NU, 32, 8, 4) code = (np_[:, :, :, 0::2, :] | (np_[:, :, :, 1::2, :] << 4)).reshape(t1 - t0, NU, 32, 16) out[t0:t1] = torch.stack([lp[..., :16], lp[..., 16:], code], dim=2) return out
SMEM_MAX = 101376 # per-block dynamic shared memory on sm_120 / sm_121 (99 KB)
def fits(k, m): """Whether build 2's shared x stage (K / 16 steps x 32 lanes x 8 B, 16 B above 8 rows) fits one block.""" return m <= 16 and (k // 16) * 32 * (8 if m <= 8 else 16) <= SMEM_MAX
def operands_ok(x2, out, k, m): """Build 2 reads x as 4-byte pairs and stores 2-element pairs: aligned, even-strided operands only.""" if not (fits(k, m) and x2.stride(1) == 1 and x2.stride(0) % 2 == 0 and x2.data_ptr() % 4 == 0): return False if out is None: return True return out.stride(-1) == 1 and (out.dim() < 2 or out.stride(0) % 2 == 0) and out.data_ptr() % (2 * out.element_size()) == 0
def c12m_gemv(x, w, pk, frag, out_dtype=None, out=None, nw=8, grid=0): """x[..., K] @ w[N, K]^T from the fragment stream (w = the resident original, escapes only); M <= 16.""" n, k = pk["shape"] lead = x.shape[:-1] x2 = x.reshape(-1, k) m = x2.shape[0] if not operands_ok(x2, out, k, m): raise ValueError(f"c12m_gemv: unsupported operands (m {m}, k {k}, x stride {x2.stride()}, out " f"{None if out is None else (out.stride(), out.data_ptr() % 16)})") if out is None: out = torch.empty((m, n), device=x.device, dtype=out_dtype or x.dtype) if m: build().c12m(frag, pk["base"], w, x2, out, m, x2.stride(0), out.stride(0), nw, grid) return out.view(*lead, n)
def c12m3_gemv(x0, x1, x2, w, pk, frag, buf, bounds, nw=16): """n137 build 2: the stacked 3-source qkvr visit in one launch. x0 / x1 / x2 [M, K] (q / k / v sources), buf [3M, N] (the stock chunk(3) layout): rows [0, b1) and [b3, N) of source 0 go to buf[0:M], rows [b1, b2) of source 1 to buf[M:2M], rows [b2, b3) of source 2 to buf[2M:3M]; every element = c12m_gemv's (the same per-element chain). Raises ValueError on operands it does not take (caller falls back).""" n, k = pk["shape"] m = x0.shape[0] b1, b2, b3 = bounds if not (x0.dim() == x1.dim() == x2.dim() == 2 and x0.shape == x1.shape == x2.shape and x0.shape[1] == k and x0.stride() == x1.stride() == x2.stride() and all(operands_ok(t, None, k, m) for t in (x0, x1, x2))): raise ValueError("c12m3_gemv: sources") if not (buf.dim() == 2 and tuple(buf.shape) == (3 * m, n) and buf.is_contiguous() and buf.dtype == x0.dtype and operands_ok(x0, buf, k, m)): raise ValueError("c12m3_gemv: buffer") if not (0 < m <= 16 and all(b % (nw * 8) == 0 for b in bounds) and b1 <= b2 <= b3 <= n): raise ValueError("c12m3_gemv: shape / bounds") build().c12m3(frag, pk["base"], w, x0, x1, x2, buf, m, x0.stride(0), buf.stride(0), nw, b1, b2, b3) return buf
def unpack_frag_reference(frag, pk): """CPU / torch inverse of pack_frag on the low bytes and codes (test only): returns (lo, nib) [N, K].""" n, k = pk["shape"] T, NU = n // 8, k // 128 lp = torch.cat([frag[:, :, 0], frag[:, :, 1]], dim=-1) # [T, NU, 32, 32] lo = lp.view(T, NU, 8, 4, 8, 2, 2).permute(0, 2, 1, 4, 5, 3, 6).reshape(n, k) c = frag[:, :, 2].view(T, NU, 32, 4, 4) nb = torch.stack([c & 15, c >> 4], dim=4).view(T, NU, 32, 8, 4) # [.., q, (lo/hi -> j = 2q + w), i] nib = nb.view(T, NU, 8, 4, 8, 2, 2).permute(0, 2, 1, 4, 5, 3, 6).reshape(n, k) return lo, nib123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343"""n75 (inkling2-spark packed seat, 2026-11-22): exact 12-bit packed BF16 weights on the served small-M GEMV route.[n137 build 2, stack seat 2026-11-24: N75_STACK_FUSED=1 (with N75_C12 attn,stack) runs each stacked 3-source qkvr visit of <= 16 rows persource as ONE n75_cuda.c12m3_gemv launch (each 128-row CTA reads its own source; the same per-element chain); any operand it does not takefalls back to the per-slice loop below (counted as an n75 miss); unset = this file's 088711f7 behaviour.]
N75_C12 (env, comma list; empty or unset = off, nothing patched): attn = qkvr + wo_ud of every Inkling2Attention, lm = thetarget LM head, stack (with attn) = the stacked 3-source qkvr call at <= 16 rows per source runs per source on the packed rows itkeeps (q / r / gate / sinks rows for the q source, k rows for k, v rows for v) into a [3M, N] buffer whose returned views arethe stock chunk(3) / split views: exact ONLY IF the stock stacked F.linear at 3M rows equals the per-source Triton chain (mb1STOCK rows), so it is a separate switch. N75_C12_CFG = "BN,warps,stages" or per class "qkvr=BN/warps/stages,..." (default n75_c12.CFG). N75_C12_CHECK = 1: check mode (below).
What changes: sglang.srt.layers.quantization.unquant._sm12x_bf16_gemv (the module global that UnquantizedLinearMethod.apply /apply_into and sm12x_fp32_lm_head call for BF16 operands of <= 16 rows, N >= 2048, set by initialize_bf16_gemm_config in thescheduler before the model loads) is wrapped: when the weight is one of the packed ones (same storage pointer, shape andstride as when packed) and there is no bias, the call runs n75_c12.c12_gemv on the 12-bit copy, which reproduces the servedTriton _gemv_kernel's FP32 chain (one in-place m16n8k16 chain over K) on the same BF16 values bit for bit; every other calltakes the served kernel unchanged. Calls that never reach that route (prefill GEMMs, the stacked 24-row qkvr, > 16 rows, the1-row b12x LM head) are untouched. Packing (and its bitwise round-trip check, n75_c12.pack_c12) runs at the firstDECODE / TARGET-VERIFY Inkling2Attention forward outside graph capture (a graph warmup: full_cuda_graph_backend runs two eagerwarmups per shape after the KV pool exists), not at the first forward of any mode: n35's copies made at the first forwardshrank the pool (D1b 556,416 vs n54 563,328 tokens), so that forward precedes pool sizing. The LM head is packed at the firstlogits call after that. The BF16 originals stay (prefill and escapes read them). A weight that fails the round trip keeps the served path (logged).Reach: every wrapped call is counted per class in Python (capture and eager), printed as 'N75REACH ...' lines.Check mode (N75_C12_CHECK=1): each packed call also runs the served kernel and the split-chain control (n75_c12 CTRL=1, aneighbouring order that must differ), RETURNS THE PACKED OUTPUT, and adds into a device counter [0] packed words != served(both-NaN excluded), [1] calls, [2] words compared, [3] control words != served, [4] both-NaN words, [5] rows; the counter iscopied into pinned host memory by a one-program Triton kernel per call (graph replays too) and a daemon thread prints'N75CHECK ...' when it changes (n50's check-mode pattern, work_stack/n54/patch/inkling2_loop.py)."""import logging, os, sys, threading, time
import torchimport tritonimport triton.language as tl
logger = logging.getLogger(__name__)SEL = {s.strip() for s in os.environ.get("N75_C12", "").split(",") if s.strip()}CHECK = os.environ.get("N75_C12_CHECK", "0") == "1"STACK_FUSED = os.environ.get("N75_STACK_FUSED", "") == "1" # n137 build 2 (stack seat, 2026-11-24): one 3-source launch per stacked visitdef _cfgs(): """N75_C12_CFG: 'BN,warps,stages' for every class, or per class 'qkvr=32/4/2,wo_ud=16/2/2,lm_head=64/8/2'; unset = n75_c12.CFG. Any config keeps the served per-element chain, so mixing configs by class keeps the outputs exact.""" raw = os.environ.get("N75_C12_CFG", "").strip() out = {c: None for c in ("qkvr", "wo_ud", "lm_head")} if not raw: return out if "=" not in raw: t = tuple(int(v) for v in raw.split(",")) return {c: t for c in out} for part in filter(None, (q.strip() for q in raw.split(","))): c, v = part.split("=") out[c.strip()] = tuple(int(u) for u in v.strip().split("/")) return out
CFGC = _cfgs()CFG = None # per call: CFGC[class]
def _per_class(var, default, conv): """'v' (every class) or 'qkvr=v,wo_ud=v,lm_head=v' -> {cls: v}; missing classes take default.""" raw = os.environ.get(var, "").strip() out = {c: default for c in ("qkvr", "wo_ud", "lm_head")} if raw and "=" not in raw: return {c: conv(raw) for c in out} for part in filter(None, (q.strip() for q in raw.split(","))): c, v = part.split("=") out[c.strip()] = conv(v.strip()) return out
KERN = _per_class("N75_C12_KERNEL", "triton", str) # triton = n75_c12 (build 1), cuda = n75_cuda (build 2); same output bitsCUDA_NW = _per_class("N75_C12_CUDA_NW", 8, int)S = {"mods": [], "done": False, "reg": {}, "lm_done": False, "orig": None, "reach": {}, "miss": {}}_COUNT = None_HOST = None_INSTALLED = False
@triton.jitdef _n75_publish(Src, Dst, N: tl.constexpr): i = tl.arange(0, N) tl.store(Dst + i, tl.load(Src + i))
def _line(c): return (f"N75CHECK words={c[0]} calls={c[1]} compared={c[2]} ctl_words={c[3]} nan_both={c[4]} rows={c[5]}" f" stack_words={c[6]} stack_compared={c[7]}" f" t={time.strftime('%H:%M:%S', time.gmtime())}")
def _check_init(device): global _COUNT, _HOST _COUNT = torch.zeros(8, dtype=torch.int64, device=device) _HOST = torch.zeros(8, dtype=torch.int64, pin_memory=True) print(f"N75CHECK init capturing={torch.cuda.is_current_stream_capturing()} pid={os.getpid()}", file=sys.stderr, flush=True)
def report(): last = None while True: time.sleep(10) c = _HOST.tolist() if c != last: print(_line(c), file=sys.stderr, flush=True) last = c
threading.Thread(target=report, daemon=True, name="n75check").start()
def _words(t): return t.view(torch.int32) if t.dtype == torch.float32 else t.view(torch.int16)
def _wrapped(x, weight, bias=None, out_dtype=None, out=None): from sglang.srt.models.inkling_common import n75_c12 as C e = S["reg"].get(weight.data_ptr()) if (e is None or bias is not None or e["shape"] != tuple(weight.shape) or e["stride"] != tuple(weight.stride()) or x.numel() // max(1, x.shape[-1]) > 16): if e is not None: S["miss"][e["cls"]] = S["miss"].get(e["cls"], 0) + 1 return S["orig"](x, weight, bias, out_dtype, out) S["reach"][e["cls"]] = S["reach"].get(e["cls"], 0) + 1 run = _runner(e) if not CHECK: return run(x, weight, out_dtype, out) if _COUNT is None: _check_init(x.device) ref = S["orig"](x, weight, None, out_dtype or (out.dtype if out is not None else None), None) ctl = C.c12_gemv(x, weight, e["pk"], out_dtype=ref.dtype, cfg=CFGC.get(e["cls"].split()[0]), _ctrl=1) y = run(x, weight, out_dtype, out) yw, rw, cw = _words(y.reshape(ref.shape)), _words(ref), _words(ctl.reshape(ref.shape)) rn = torch.isnan(ref) both = torch.isnan(y.reshape(ref.shape)) & rn _COUNT[0] += ((yw != rw) & ~both).sum() _COUNT[1] += 1 _COUNT[2] += ref.numel() _COUNT[3] += ((cw != rw) & ~(torch.isnan(ctl.reshape(ref.shape)) & rn)).sum() _COUNT[4] += both.sum() _COUNT[5] += ref.numel() // ref.shape[-1] _n75_publish[(1,)](_COUNT, _HOST, 8) return y
def _runner(e): """The packed GEMV for a registered weight: build 1 (Triton) or build 2 (CUDA fragment stream), same output bits.""" from sglang.srt.models.inkling_common import n75_c12 as C if e.get("frag") is not None: from sglang.srt.models.inkling_common import n75_cuda as G nw = CUDA_NW[e["cls"]] if e["cls"] in CUDA_NW else 8 def run(x, w, od, out): x2 = x.reshape(-1, x.shape[-1]) if G.operands_ok(x2, out, x2.shape[1], x2.shape[0]): return G.c12m_gemv(x, w, e["pk"], e["frag"], out_dtype=od, out=out, nw=nw) if e["pk"].get("lo") is not None: return C.c12_gemv(x, w, e["pk"], out_dtype=od, out=out, cfg=CFGC.get(e["cls"].split()[0])) S["miss"]["build 2 operands"] = S["miss"].get("build 2 operands", 0) + 1 return S["orig"](x, w, None, od, out) return run cfg = CFGC.get(e["cls"].split()[0]) return lambda x, w, od, out: C.c12_gemv(x, w, e["pk"], out_dtype=od, out=out, cfg=cfg)
def _register(cls, w): from sglang.srt.models.inkling_common import n75_c12 as C t0 = time.time() if w.dtype != torch.bfloat16 or w.dim() != 2 or w.shape[1] % C.BK or w.stride(1) != 1: logger.warning("n75: %s %s not packable (dtype %s stride %s): served path", cls, tuple(w.shape), w.dtype, w.stride()) return 0 pk = C.pack_c12(w, "row") if pk is None: logger.warning("n75: %s %s FAILED the bitwise round trip: served path", cls, tuple(w.shape)) return 0 nbytes = C.packed_bytes(pk) e = {"cls": cls, "pk": pk, "shape": tuple(w.shape), "stride": tuple(w.stride()), "frag": None} if KERN.get(cls.split()[0], "triton") == "cuda": from sglang.srt.models.inkling_common import n75_cuda as G try: if w.shape[0] % 8 or w.shape[1] % 128 or not G.fits(w.shape[1], 16): raise ValueError(f"shape {tuple(w.shape)} outside build 2") G.build() # torch extension under /root/.cache (the mounted CACHE_DIR): compiled at the first boot, reused after e["frag"] = G.pack_frag(pk) if not CHECK and G.fits(w.shape[1], 16): # Triton operands: only for check mode's control pk["lo"] = pk["cd"] = None except Exception as ex: # no nvcc / build error / shape: this class stays on build 1 (same output bits) logger.warning("n75: build 2 unavailable for %s %s (%s: %s): build 1 (Triton)", cls, tuple(w.shape), type(ex).__name__, str(ex)[:200]) e["frag"] = None S["reg"][w.data_ptr()] = e S.setdefault("esc", {}).setdefault(cls, [0, 0]) S["esc"][cls][0] += pk["n_esc"]; S["esc"][cls][1] += w.numel() S.setdefault("ptime", 0.0) S["ptime"] += time.time() - t0 return nbytes
def _prepare(): if torch.cuda.is_current_stream_capturing(): logger.warning("n75: first forward inside graph capture: packed path OFF (served kernels only)") S["done"] = True return from sglang.srt.layers.quantization import unquant as U if U._sm12x_bf16_gemv is None: logger.warning("n75: unquant._sm12x_bf16_gemv is None (not the SM12x auto backend): packed path OFF") S["done"] = True return tot = 0 if "attn" in SEL: for m in S["mods"]: for name in ("qkvr", "wo_ud"): lin = m._modules[name] if getattr(lin, "bias", None) is not None: logger.warning("n75: %s has a bias: served path", name) continue tot += _register(name, lin.weight.data) if "lm" in SEL: _patch_lm() torch.cuda.synchronize() S["orig"] = U._sm12x_bf16_gemv U._sm12x_bf16_gemv = _wrapped S["done"] = True _start_reach_log() esc = {c: f"{e[0] / e[1] * 1e4:.2f}/1e4" for c, e in S.get("esc", {}).items()} logger.warning("n75 packed: %d attention modules, %d weights, %.1f MB packed (escapes %s), pack+check %.1f s, cfg %s, " "kernel %s cuda nw %s, check %s", len(S["mods"]), len(S["reg"]), tot / 1e6, esc, S.get("ptime", 0.0), CFGC, KERN, CUDA_NW, CHECK)
def _patch_lm(): """The LM head weight is packed at the first logits call outside capture (inkling2.py is still importing when this file's install() runs, as n35 found); the call itself then takes the wrapped route.""" from sglang.srt.models import inkling2 as I lp = I.Inkling2LogitsProcessor orig_head = lp._compute_lm_head
def compute_lm_head(self, hidden_states, lm_head, embedding_bias=None, *, out=None): if not S["lm_done"] and S["done"] and not torch.cuda.is_current_stream_capturing(): S["lm_done"] = True b = _register("lm_head", lm_head.weight.data) torch.cuda.synchronize() logger.warning("n75: LM head packed %s, %.1f MB", tuple(lm_head.weight.shape), b / 1e6) elif not S["lm_done"] and S["done"]: S["miss"]["lm_head first seen in capture"] = S["miss"].get("lm_head first seen in capture", 0) + 1 return orig_head(self, hidden_states, lm_head, embedding_bias, out=out)
lp._compute_lm_head = compute_lm_head logger.warning("n75: LM head hook installed")
def _start_reach_log(): def report(): last = None while True: time.sleep(15) c = (dict(S["reach"]), dict(S["miss"])) if c != last: print(f"N75REACH calls {c[0]} misses {c[1]} t={time.strftime('%H:%M:%S', time.gmtime())}", file=sys.stderr, flush=True) last = c
threading.Thread(target=report, daemon=True, name="n75reach").start()
def _install_stack(cls): orig_ps = cls._project_sources
def ps(self, sources): e = S["reg"].get(self.qkvr.weight.data_ptr()) if S["done"] else None x = sources.q if (e is None or len({id(sources.q), id(sources.k), id(sources.v)}) != 3 or x.dim() != 2 or x.shape[0] > 16 or not (sources.k.shape == sources.v.shape == x.shape)): return orig_ps(self, sources) from sglang.srt.models.inkling_common import n75_c12 as C w = self.qkvr.weight sq, sk, sv, sr, sg, ss = self.split_sizes[:6] o_k, o_v, o_r = sq, sq + sk, sq + sk + sv end = o_r + sr + sg + ss n = w.shape[0] if end != n or e["shape"] != tuple(w.shape): return orig_ps(self, sources) m = x.shape[0] buf = torch.empty((3 * m, n), dtype=x.dtype, device=x.device) pk = e["pk"] if STACK_FUSED and e["frag"] is not None: # n137 build 2: the whole visit in one 3-source launch (same per-element chain) from sglang.srt.models.inkling_common import n75_cuda as G try: G.c12m3_gemv(sources.q, sources.k, sources.v, w, pk, e["frag"], buf, (o_k, o_v, o_r), nw=CUDA_NW.get("qkvr", 16)) S["reach"]["qkvr stack"] = S["reach"].get("qkvr stack", 0) + 1 S["reach"]["qkvr stack fused"] = S["reach"].get("qkvr stack fused", 0) + 1 q_proj, k_proj, v_proj = (p.split(self.split_sizes, dim=-1)[:6] for p in buf.chunk(3)) q, _, _, r, gate, sinks = q_proj return (q, k_proj[1], v_proj[2], r, gate, sinks) except (ValueError, RuntimeError) as ex: S["miss"][f"stack fused: {type(ex).__name__}"] = S["miss"].get(f"stack fused: {type(ex).__name__}", 0) + 1 for src, rb, (r0, r1) in ((sources.q, 0, (0, o_k)), (sources.q, 0, (o_r, end)), (sources.k, 1, (o_k, o_v)), (sources.v, 2, (o_v, o_r))): sl = {"lo": None if pk["lo"] is None else pk["lo"][r0:r1], "cd": None if pk["cd"] is None else pk["cd"][r0:r1], "base": pk["base"][r0:r1], "shape": (r1 - r0, w.shape[1]), "n_esc": 0} dst = buf[rb * m:(rb + 1) * m, r0:r1] if e["frag"] is not None and r0 % 8 == 0 and r1 % 8 == 0: _runner({"cls": "qkvr", "pk": sl, "frag": e["frag"][r0 // 8:r1 // 8]})(src, w[r0:r1], None, dst) elif sl["lo"] is not None: C.c12_gemv(src, w[r0:r1], sl, out=dst, cfg=CFGC.get("qkvr")) else: return orig_ps(self, sources) S["reach"]["qkvr stack"] = S["reach"].get("qkvr stack", 0) + 1 q_proj, k_proj, v_proj = (p.split(self.split_sizes, dim=-1)[:6] for p in buf.chunk(3)) q, _, _, r, gate, sinks = q_proj mine = (q, k_proj[1], v_proj[2], r, gate, sinks) if CHECK: # counter [6] stacked-path words != the stock stacked path, [7] words compared if _COUNT is None: _check_init(x.device) ref = orig_ps(self, sources) for a, b in zip(mine, ref): _COUNT[6] += (_words(a) != _words(b)).sum() _COUNT[7] += a.numel() _n75_publish[(1,)](_COUNT, _HOST, 8) return mine
cls._project_sources = ps logger.warning("n75: stacked 3-source qkvr per source on the packed rows (switch 'stack')")
def install(): global _INSTALLED if _INSTALLED or not SEL: return from sglang.srt.models.inkling_common import inkling2_attn as A cls = A.Inkling2Attention orig_init, orig_fwd = cls.__init__, cls._forward
def init(self, *a, **kw): orig_init(self, *a, **kw) S["mods"].append(self)
def fwd(self, *a, **kw): if not S["done"]: fb = kw.get("forward_batch", a[2] if len(a) > 2 else None) m = getattr(fb, "forward_mode", None) if m is not None and (m.is_decode() or m.is_target_verify()): _prepare() return orig_fwd(self, *a, **kw)
cls.__init__, cls._forward = init, fwd if "stack" in SEL and "attn" in SEL: _install_stack(cls) _INSTALLED = True logger.warning("n75 installed: %s check %s", sorted(SEL), CHECK)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312"""n78 SERVER FORM: certified greedy LM head, S8 (inkling2-spark packed seat, 2026-11-23); + the n140 INT6 screen behind N140_I6(decode seat, 2026-11-24: see the N140 knobs below; the n78 text that follows describes the S8 form, which N140_I6 unset keeps). Mounted beside the image'smodels/inkling_common modules with n78_kern.py; one install line in patch/inkling2_attn.py. With N78_CERT unset or not '1'install() returns at once and the served path is n54's exactly.
WHAT CHANGES. Only target-verify LM-head calls of 8 rows (bs 1; 16 rows = bs 2 stays served until it has its own bitwise read) whose operands are exactly the served sm12x FP32case (BF16 [M, 2304] x, the model's own lm_head weight, an FP32 [M, padded] contiguous out buffer, no bias) runn78_kern.Cert.run (INT8 screen, bound, tile select, served-body exact pass) in place of the sm12x GEMV. Everything after it isthe served code, unchanged: the softcap in place, the padded-id mask, the folded epilogue's argmax. Every other call (prefill,decode, draft, > 16 rows, any shape or dtype off the case) takes the original _compute_lm_head.
EXACTNESS. On a certified step the buffer holds the served FP32 logits bitwise on every tile that can hold the row maximum and-inf elsewhere, so the first-max token is the served one (results.md 'RULE n78 mb' + amendments 1-2, 'n78 mb78' rows).THE FULL HEAD WHENEVER THE CERTIFICATE IS NOT MET: - a device FLAG word, 0 by default: 0 = the exact pass computes every tile with the served body (bitwise the served head) and the screen exits. TargetVerifyExecutor.run_non_compact sets it to 1 only for a step that is all greedy AND verify_logits_adjustments_are_noop AND not return_logprob AND no grammar AND no watermark candidates, and sets it back to 0 when the call returns (fail closed: run_compact, eager paths that bypass run_non_compact and capture never see 1); - in the kernels: a non-finite screen value or bound, or f(max lo) - e <= -cap, computes every tile; - install refuses (served path) if a debug / recording switch that reads full verify logits on greedy steps is set (BLOCKERS).e = 2 x the exhaustively measured monotonicity defect of the image's softcap kernel (mb78: 1.9073486328125e-06); any e >= thetrue defect is sound. N78_E overrides (a larger value only widens the tile set).
N78_CHECK=1 (check boot only, never a timed candidate): inside the same graph the served GEMV is also run into a second bufferand softcapped, and device counters accumulate: calls, rows whose certified first-max differs from the served one (must stay 0),computed tiles, and a CONTROL (the whole bound scaled to 0, same kernels) whose mismatching rows must be > 0 over a replay.Lines: N78CERT (state, once), N78REACH (host: flag-1 / flag-0 steps by bs, routed / unrouted head calls), N78CHECK (device)."""import json, logging, os, sys, threading, time
import torch
logger = logging.getLogger(__name__)ON = os.environ.get("N78_CERT", "") == "1"CHECK = os.environ.get("N78_CHECK", "") == "1"E = float(os.environ.get("N78_E", "3.814697265625e-06"))BN = int(os.environ.get("N78_BN", "128"))ROWS = tuple(int(v) for v in os.environ.get("N78_ROWS", "8").split(",")) # 16 rows (bs 2) has NO exactness read yet: offREPORT_S = float(os.environ.get("N78_REPORT_S", "30"))TEST_CPU = os.environ.get("N78_TEST_CPU", "") == "1" # CPU pre-flight only (interpreter, FP32 test dot)# n140 rider (decode seat, 2026-11-24): N140_I6=1 replaces ONLY the screen (K1) by the INT6 CUDA screen of n140_kern.py (n78's own# pack(W, 6) tables, B-fragment stream, 357.8 MB instead of S8's 473.6 MB; S8's pack is then not built); N140_EXACT E1 (default:# n78's exact pass) | E3 (needed tiles first, same served body). Unset: this file is n78's served path exactly.I6 = os.environ.get("N140_I6", "") == "1"I6_EXACT = os.environ.get("N140_EXACT", "E1")VERIFY_MOD = "sglang.srt.speculative.dspark_components.dspark_verify"BLOCKERS = ("SGLANG_DSPARK_DEBUG_DUMP", "SGLANG_DSPARK_ENABLE_SPS_RECORD", "SGLANG_DSPARK_BLOCK_ACCEPT_ESTIMATE_PATH", "SGLANG_DSPARK_STS_COLLECT_PATH", "SGLANG_DSPARK_DEBUG_CONFIDENCE_METRICS", "SGLANG_DSPARK_LOG_SPS_PRED_INTERVAL", "SGLANG_DSPARK_BLOCK_ACCEPT_ONLINE_INTERVAL", "SGLANG_SIMULATE_ACC_LEN", "SGLANG_SIMULATE_ACC_TOKEN_MODE", "SGLANG_SIMULATE_ACC_METHOD", "SGLANG_SIMULATE_ACC_GREEDY", "SGLANG_DSPARK_SIMULATE_FOLD")S = {"certs": {}, "W": None, "flag": None, "ready": False, "failed": None, "reach": {}, "lp_done": False, "spec_done": False, "tls": threading.local(), "chk": None, "threads": []}_INSTALLED = False_LOCK = threading.Lock()
def _count(k, n=1): with _LOCK: S["reach"][k] = S["reach"].get(k, 0) + n
def _capturing(): return torch.cuda.is_available() and torch.cuda.is_current_stream_capturing()
def _prepare(lp, x, lm_head): """Outside capture, at the first decode / target-verify logits call (after the KV pool is sized): pack the head, build one Cert per row count, compile every kernel on warm buffers. Any failure leaves the served path (S['failed']).""" from sglang.srt.models.inkling_common import n78_kern as K if TEST_CPU: softcap = lambda t, cap: t.copy_(torch.tanh(t / torch.tensor(cap, dtype=torch.float32)) * torch.tensor(cap, dtype=torch.float32)) served = None else: from sglang.kernels.ops.activation.softcap import softcap_inplace_logits as softcap from sglang.kernels.ops.gemm.sm12x_bf16_gemv import sm12x_bf16_gemv as served W = lm_head.weight V, KK = W.shape vocab, cap = int(lp.config.vocab_size), float(lp.shard_softcap) if not (W.dtype == torch.bfloat16 and W.is_contiguous() and V % 32 == 0 and KK % 192 == 0 and KK % 256 == 0 and 0 < vocab <= V and cap > 0): raise RuntimeError("head off the certified case") t = time.time() if I6: from sglang.srt.models.inkling_common import n140_kern as N6 if I6_EXACT not in ("E1", "E3"): raise RuntimeError(f"N140_EXACT {I6_EXACT}") ext6 = N6.build_emu() if TEST_CPU else N6.build() pk = N6.pack6f(W) mk = lambda M: N6.Cert6(W, pk, vocab, E, M, softcap, ext=ext6, exact=I6_EXACT, testf32=TEST_CPU, cap=cap) else: pk = K.pack(W, 8) mk = lambda M: K.Cert(W, pk, vocab, E, M, softcap, bn=BN, exact="E1", testf32=TEST_CPU, cap=cap) flag = torch.zeros(1, dtype=torch.int32, device=W.device) certs = {} for M in ROWS: c = mk(M) c.flag = flag xw = torch.zeros((M, KK), dtype=torch.bfloat16, device=W.device) ow = torch.empty((M, V), dtype=torch.float32, device=W.device) for v in (1, 0): flag.fill_(v) c.run(xw, ow) if CHECK: c.ref = torch.empty((M, V), dtype=torch.float32, device=W.device) c.ctl = torch.empty((M, V), dtype=torch.float32, device=W.device) c.mine = torch.empty((M, V), dtype=torch.float32, device=W.device) _check(c, xw, ow, served, softcap, cap, vocab) certs[M] = c flag.fill_(0) if CHECK: S["chk"] = torch.zeros(6, dtype=torch.int64, device=W.device) # calls, flag-1 calls, mismatch rows, tiles, ctl mismatch rows, ctl tiles S.update(certs=certs, W=W, flag=flag, served=served, softcap=softcap, cap=cap, vocab=vocab, ready=True) print("N78CERT " + json.dumps({"state": "ready", "form": ("I6-" + I6_EXACT) if I6 else "S8", "bn": 32 if I6 else BN, "e": E, "rows": list(ROWS), "check": CHECK, "vocab": vocab, "padded": V, "cap": cap, "packed_mb": round(pk["bytes"] / 1e6, 1), "prepare_s": round(time.time() - t, 1)}, sort_keys=True), file=sys.stderr, flush=True)
def _check(c, x, out, served, softcap, cap, vocab, acc=None): """CHECK mode, capturable: out holds the certified head output BEFORE the softcap. Reference = the served GEMV; control = the same kernels with the whole bound scaled to 0. Counters are device adds (replayed with the graph).""" if served is None: # CPU pre-flight: the served-body kernel with every tile needed from sglang.srt.models.inkling_common import n78_kern as K full = torch.ones_like(c.need) K._exact_kernel[(c.T,)](x, c.W, c.ref, full, c.M, c.V, c.K, x.stride(0), c.W.stride(0), c.ref.stride(0), BN=32, BK=256, MP=16, TESTF32=True) else: served(x, c.W, out_dtype=torch.float32, out=c.ref) softcap(c.ref, cap) tiles = c.need.sum() mine = c.mine mine.copy_(out) softcap(mine, cap) mism = (torch.argmax(mine[:, :vocab], dim=-1) != torch.argmax(c.ref[:, :vocab], dim=-1)).sum() cn = c.cn c.cn = 0.0 try: c.screen(x, qterm=0.0) c.select() c.exact_pass(x, c.ctl) finally: c.cn = cn softcap(c.ctl, cap) cm = (torch.argmax(c.ctl[:, :vocab], dim=-1) != torch.argmax(c.ref[:, :vocab], dim=-1)).sum() if acc is not None: acc[0] += 1 acc[1] += c.flag[0] acc[2] += mism acc[3] += tiles acc[4] += cm acc[5] += c.need.sum()
def _route(lp, x, lm_head, bias, out): """The Cert for this call, or None with the reason counted (the original head then runs).""" if not getattr(S["tls"], "verify", False): return None why = None if not S["ready"]: why = "not ready" elif x.dim() != 2 or x.shape[0] not in S["certs"]: why = f"rows {tuple(x.shape)[0] if x.dim() == 2 else 'nd'}" elif bias is not None or out is None: why = "bias or no out buffer" elif not (TEST_CPU or x.is_cuda) or x.dtype != torch.bfloat16 or not x.is_contiguous() or x.shape[1] != S["W"].shape[1]: why = "x off the case" elif getattr(lm_head, "weight", None) is not S["W"]: why = "another head weight" elif out.dtype != torch.float32 or tuple(out.shape) != (x.shape[0], S["W"].shape[0]) or not out.is_contiguous() or out.device != x.device: why = "out off the case" elif not getattr(lp, "use_fp32_lm_head", False) or float(getattr(lp, "shard_softcap", 0) or 0) != S["cap"]: why = "softcap / fp32 off the case" elif I6 and (x.data_ptr() % 16 != 0 or (x.shape[0] > 1 and x.stride(0) % 8 != 0)): why = "x alignment (n140 screen needs 16-byte rows)" # the extension would refuse: take the original head instead if why is not None: _count(f"verify head unrouted: {why}") return None return S["certs"][x.shape[0]]
def _patch_lp(): if S["lp_done"]: return I = sys.modules.get("sglang.srt.models.inkling2") cls = getattr(I, "Inkling2LogitsProcessor", None) if cls is None: _count("Inkling2LogitsProcessor not found at the first attention init") return S["lp_done"] = True o_get, o_head = cls._get_logits, cls._compute_lm_head
def get_logits(self, hidden_states, lm_head, logits_metadata, *a, **kw): mode = getattr(logits_metadata, "forward_mode", None) tv = mode is not None and bool(mode.is_target_verify()) if not S["spec_done"]: _patch_spec() if not S["ready"] and S["failed"] is None and not _capturing(): dec = mode is not None and hasattr(mode, "is_decode") and bool(mode.is_decode()) if (tv or dec) and (TEST_CPU or hidden_states.is_cuda): try: _prepare(self, hidden_states, lm_head) _start_threads() except Exception as e: # serve on with the original head S["failed"] = f"{type(e).__name__}: {str(e)[:200]}" print("N78CERT " + json.dumps({"state": "failed", "why": S["failed"]}), file=sys.stderr, flush=True) S["tls"].verify = tv try: return o_get(self, hidden_states, lm_head, logits_metadata, *a, **kw) finally: S["tls"].verify = False
def compute_lm_head(self, hidden_states, lm_head, embedding_bias=None, *, out=None): c = _route(self, hidden_states, lm_head, embedding_bias, out) if c is None: return o_head(self, hidden_states, lm_head, embedding_bias, out=out) c.run(hidden_states, out) if CHECK: _check(c, hidden_states, out, S["served"], S["softcap"], S["cap"], S["vocab"], S["chk"]) S["softcap"](out, self.shard_softcap) if not _capturing(): _count(f"verify head routed rows {hidden_states.shape[0]} eager") else: _count(f"verify head routed rows {hidden_states.shape[0]} capture") return out
cls._get_logits, cls._compute_lm_head = get_logits, compute_lm_head logger.warning("n78 cert: Inkling2LogitsProcessor._get_logits / _compute_lm_head wrapped")
def flag_for(batch, sampling_info, noop): from sglang.srt.models.inkling_common import n78_kern as K return K.flag_value(all_greedy=sampling_info is None or bool(sampling_info.is_all_greedy), adjustments_noop=bool(noop(sampling_info)), return_logprob=bool(batch.return_logprob), grammar=bool(batch.has_grammar), watermark=bool(getattr(sampling_info, "has_watermark_candidates", False)))
def _patch_spec(): V = sys.modules.get(VERIFY_MOD) if V is None or S["spec_done"]: return S["spec_done"] = True TE, noop = V.TargetVerifyExecutor, V.verify_logits_adjustments_are_noop o_rnc = TE.run_non_compact
def rnc(self, *a, **kw): fl = S["flag"] v = 0 if fl is not None and not _capturing(): try: b = kw["batch"] v = flag_for(b, kw["sampling_info"], noop) _count(f"step bs {len(b.reqs)} flag {v}") except Exception as e: # unknown step kind: the full head v = 0 _count(f"flag error {type(e).__name__}") if v: fl.fill_(1) try: return o_rnc(self, *a, **kw) finally: if v: fl.fill_(0)
TE.run_non_compact = rnc logger.warning("n78 cert: TargetVerifyExecutor.run_non_compact wrapped (flag word)")
def _reporter(): last = None while True: time.sleep(REPORT_S) try: with _LOCK: r = dict(S["reach"]) chk = S["chk"].tolist() if S["chk"] is not None else None cur = (r, chk) if cur != last: t = time.strftime("%H:%M:%S", time.gmtime()) print(f"N78REACH {json.dumps(r, sort_keys=True)} t={t}", file=sys.stderr, flush=True) if chk is not None: print("N78CHECK " + json.dumps({"calls": chk[0], "flag1_calls": chk[1], "mismatch_rows": chk[2], "tiles": chk[3], "control_mismatch_rows": chk[4], "control_tiles": chk[5]}, sort_keys=True) + f" t={t}", file=sys.stderr, flush=True) last = cur except Exception as e: _count(f"reporter {type(e).__name__}")
def _start_threads(): if S["threads"] or TEST_CPU: return t = threading.Thread(target=_reporter, daemon=True, name="n78report") t.start() S["threads"].append(t)
def install(): global _INSTALLED if _INSTALLED or not ON: return bl = [k for k in BLOCKERS if os.environ.get(k, "") not in ("", "0", "false", "False")] if bl: print("N78CERT " + json.dumps({"state": "refused", "blockers": bl}), file=sys.stderr, flush=True) return from sglang.srt.models.inkling_common import inkling2_attn as A cls = A.Inkling2Attention orig_init = cls.__init__
def init(self, *a, **kw): orig_init(self, *a, **kw) if not S["lp_done"]: _patch_lp()
cls.__init__ = init _INSTALLED = True logger.warning("n78 cert installed: %s bn %d e %.3e check %s", ("I6-" + I6_EXACT) if I6 else "S8", 32 if I6 else BN, E, CHECK)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417"""n78 certified greedy LM head: GPU kernels + host packers (packed seat, 2026-11-23; kit for 'RULE n78 mb', kit-only amendment).
One certified head call (x [M <= 16, 2304] BF16, the served head W [201,024, 2304] BF16) = six launches, all graph-safe (fixed grids): K0 _xnorm_kernel per-row group norms ||x_g|| (12 groups of 192) and ||x||, rounded up (x 1 + 2^-10). K1 _screen_kernel S = <D_v, x> from a packed quantized head (BITS 8 / 6 / 4, FP16 scale per (row, 192-group)); bound B = (qterm * sum_g ||x_g|| R_vg + CN N_v ||x||) (1 + 2^-18), slop = (|S| + B) 2^-20 + 1e-30, lo = S - B - slop, hi = S + B + slop; writes per (row, 32-id tile) the max of hi over REAL ids into FB[r, t], per (row, CTA) the max of lo over real ids into LOC, and a per-CTA non-finite flag. dbg != 0 also writes S, lo, hi per id (mb78 bar checks only). K2 _reduce_kernel per row r < M: max over CTAs of LOC -> FB[r, T]; any non-finite -> OKW[r] = 0. (served) the image's softcap_inplace_logits(FB, cap) in place: f is the served softcap kernel itself. K3 _select_kernel NEED[t] = 1 iff flag == 0, or not certifiable (a non-finite S / B, or f(max lo) - e <= -cap or non-finite), or some row r < M has f(H_rt) + 3e >= f(max_v lo_rv). K4 _exact_kernel the served sm12x _gemv_kernel body (BN 32, BK 256, MP 16, same loop) for tiles with NEED, -inf elsewhere (E1: branch; _exact_masked_kernel E2: the served loop with need-masked weight loads).Then the served softcap, padded mask and argmax run unchanged.
Certificate (tile-max form of 'RULE n78 mb'): the rule's per-id test is 'f(hi_v) + 2e >= m, m = max_v f(lo_v)'. This kittests per 32-id tile with H_rt = max of hi over the tile's real ids and m'_r = f(max_v lo_rv) (one f per row and tile): sound for any e: with u = argmax lo, m' = f(lo_u) <= f(L_u) + e <= Y + e (lo_u <= L_u, e = max_{a<=b} f(a) - f(b)); for every served maximiser j in tile t: f(H_rt) >= f(hi_j) - e >= f(L_j) - 2e = Y - 2e >= m' - 3e, so t is computed exactly; non-computed tiles read f(-inf) = -cap < m' - e <= Y (guard), so the lowest index holding Y is the served token. At e = 0 (f non-decreasing) max f(lo) = f(max lo) and max_v f(hi_v) = f(max_v hi_v), so the tile decisions equal the per-id rule's exactly; at e > 0 the tile set is a superset (tests/test_kern_cpu.py T3).CPU test path: TESTF32 (constexpr) replaces only the dot (FP32 operands, input_precision 'ieee'); the unpack is the same code."""import math
import torchimport tritonimport triton.language as tl
TILE = 32 # the served kernel's BN: one exact tile = 32 vocab idsGROUP = 192 # quantization group along KCAP = 30.0SBK = 64 # screen K block (3 per group)
def c_acc(k): """MMA-chain accumulation model per unit of ||x|| ||w|| (knapcio's form; mb78 bar (1) tests it on every row and id).""" return (k / 16 * 17 + 32) * 2.0 ** -23
def flag_value(all_greedy, adjustments_noop, return_logprob, grammar, watermark): """Server-form flag per <= 16-row verify step: 1 = certified head allowed, 0 = the full head (exact everywhere).""" return int(bool(all_greedy) and bool(adjustments_noop) and not return_logprob and not grammar and not watermark)
# ------------------------------------------------------------------------------------------------ K4: exact passes@triton.jitdef _exact_kernel(X, W, Y, NEED, M, N, K, SX, SW, SY, BN: tl.constexpr, BK: tl.constexpr, MP: tl.constexpr, TESTF32: tl.constexpr = False): pid = tl.program_id(0) cols = pid * BN + tl.arange(0, BN) rows = tl.arange(0, MP) if tl.load(NEED + pid) != 0: acc = tl.zeros((MP, BN), tl.float32) for k0 in range(0, K, BK): ks = k0 + tl.arange(0, BK) w = tl.load( W + cols[None, :].to(tl.int64) * SW + ks[:, None], (cols[None, :] < N) & (ks[:, None] < K), other=0, ) x = tl.load( X + rows[:, None] * SX + ks[None, :], (rows[:, None] < M) & (ks[None, :] < K), other=0, ) if TESTF32: acc += tl.dot(x.to(tl.float32), w.to(tl.float32), input_precision="ieee") else: acc += tl.dot(x, w) tl.store( Y + rows[:, None] * SY + cols[None, :], acc.to(Y.dtype.element_ty), (rows[:, None] < M) & (cols[None, :] < N), ) else: tl.store(Y + rows[:, None] * SY + cols[None, :], tl.full((MP, BN), float("-inf"), tl.float32), (rows[:, None] < M) & (cols[None, :] < N))
@triton.jitdef _exact_masked_kernel(X, W, Y, NEED, M, N, K, SX, SW, SY, BN: tl.constexpr, BK: tl.constexpr, MP: tl.constexpr, TESTF32: tl.constexpr = False): pid = tl.program_id(0) cols = pid * BN + tl.arange(0, BN) rows = tl.arange(0, MP) need = tl.load(NEED + pid) != 0 acc = tl.zeros((MP, BN), tl.float32) for k0 in range(0, K, BK): ks = k0 + tl.arange(0, BK) w = tl.load( W + cols[None, :].to(tl.int64) * SW + ks[:, None], (cols[None, :] < N) & (ks[:, None] < K) & need, other=0, ) x = tl.load( X + rows[:, None] * SX + ks[None, :], (rows[:, None] < M) & (ks[None, :] < K), other=0, ) if TESTF32: acc += tl.dot(x.to(tl.float32), w.to(tl.float32), input_precision="ieee") else: acc += tl.dot(x, w) acc = tl.where(need, acc, float("-inf")) tl.store( Y + rows[:, None] * SY + cols[None, :], acc.to(Y.dtype.element_ty), (rows[:, None] < M) & (cols[None, :] < N), )
@triton.jitdef _exact_rev_kernel(X, W, Y, NEED, M, N, K, SX, SW, SY, BN: tl.constexpr, BK: tl.constexpr, MP: tl.constexpr, TESTF32: tl.constexpr = False): """CONTROL (c): E1 with its K chunks in reversed order; must differ from the served head.""" pid = tl.program_id(0) cols = pid * BN + tl.arange(0, BN) rows = tl.arange(0, MP) if tl.load(NEED + pid) != 0: acc = tl.zeros((MP, BN), tl.float32) for i0 in range(0, K, BK): k0 = K - BK - i0 ks = k0 + tl.arange(0, BK) w = tl.load(W + cols[None, :].to(tl.int64) * SW + ks[:, None], (cols[None, :] < N) & (ks[:, None] < K), other=0) x = tl.load(X + rows[:, None] * SX + ks[None, :], (rows[:, None] < M) & (ks[None, :] < K), other=0) if TESTF32: acc += tl.dot(x.to(tl.float32), w.to(tl.float32), input_precision="ieee") else: acc += tl.dot(x, w) tl.store(Y + rows[:, None] * SY + cols[None, :], acc, (rows[:, None] < M) & (cols[None, :] < N)) else: tl.store(Y + rows[:, None] * SY + cols[None, :], tl.full((MP, BN), float("-inf"), tl.float32), (rows[:, None] < M) & (cols[None, :] < N))
# ------------------------------------------------------------------------------------------------ K0: x norms@triton.jitdef _xnorm_kernel(X, XG, XN, M, SX, NG: tl.constexpr, GROUP: tl.constexpr, GP: tl.constexpr, MP: tl.constexpr): rows = tl.arange(0, MP) j = tl.arange(0, GP) tot = tl.zeros((MP,), tl.float32) for g in tl.static_range(NG): x = tl.load(X + rows[:, None] * SX + g * GROUP + j[None, :], (rows[:, None] < M) & (j[None, :] < GROUP), other=0) x = x.to(tl.float32) ss = tl.sum(x * x, axis=1) tl.store(XG + rows * NG + g, tl.sqrt_rn(ss) * (1.0 + 2.0 ** -10)) tot += ss tl.store(XN + rows, tl.sqrt_rn(tot) * (1.0 + 2.0 ** -10))
# ------------------------------------------------------------------------------------------------ K1: screens@triton.jitdef _wsub(a0, a1, bb, s: tl.constexpr, BITS: tl.constexpr): """Decode sub-block s (16 K x BN ids) of a 64-K block: 4-bit plane a0 / a1 (+ 2-bit plane bb for BITS 6) -> FP32 ints.""" if s % 2 == 0: a = a0 else: a = a1 nib = (a >> (4 * (s // 2))) & 0xF if BITS == 6: v = nib | (((bb >> (2 * s)) & 0x3) << 4) w = v.to(tl.float32) - 32.0 else: w = nib.to(tl.float32) - 8.0 return w
@triton.jitdef _screen_kernel(X, Q, QB, SC, R, NV, XG, XN, FLAG, FB, LOC, BAD, DS, DLO, DHI, M, N, NREAL, SX, SQ, SQB, T1, NCTA, qterm, cn, dbg, BITS: tl.constexpr, BN: tl.constexpr, MP: tl.constexpr, NG: tl.constexpr, GROUP: tl.constexpr, TESTF32: tl.constexpr = False): pid = tl.program_id(0) if tl.load(FLAG) != 0: cols = pid * BN + tl.arange(0, BN) rows = tl.arange(0, MP) cm = cols < N acc = tl.zeros((MP, BN), tl.float32) bq = tl.zeros((MP, BN), tl.float32) for g in range(NG): part = tl.zeros((MP, BN), tl.float32) for jb in tl.static_range(GROUP // 64): kb = g * GROUP + jb * 64 if BITS == 8: kk = kb + tl.arange(0, 64) q = tl.load(Q + cols[None, :].to(tl.int64) * SQ + kk[:, None], cm[None, :], other=0) xk = tl.load(X + rows[:, None] * SX + kk[None, :], rows[:, None] < M, other=0) if TESTF32: part += tl.dot(xk.to(tl.float32), q.to(tl.float32), input_precision="ieee") else: part += tl.dot(xk, q.to(tl.float32).to(tl.bfloat16)) else: j16 = tl.arange(0, 16) base = Q + cols[None, :].to(tl.int64) * SQ + kb // 2 a0 = tl.load(base + j16[:, None], cm[None, :], other=0) a1 = tl.load(base + 16 + j16[:, None], cm[None, :], other=0) if BITS == 6: bb = tl.load(QB + cols[None, :].to(tl.int64) * SQB + kb // 4 + j16[:, None], cm[None, :], other=0) else: bb = a0 for s in tl.static_range(4): w = _wsub(a0, a1, bb, s, BITS) xk = tl.load(X + rows[:, None] * SX + kb + 16 * s + j16[None, :], rows[:, None] < M, other=0) if TESTF32: part += tl.dot(xk.to(tl.float32), w, input_precision="ieee") else: part += tl.dot(xk, w.to(tl.bfloat16)) sc = tl.load(SC + cols * NG + g, cm, other=0).to(tl.float32) acc += part * sc[None, :] rg = tl.load(R + cols * NG + g, cm, other=0).to(tl.float32) xg = tl.load(XG + rows * NG + g) bq += xg[:, None] * rg[None, :] nv = tl.load(NV + cols, cm, other=0) xn = tl.load(XN + rows) b = (qterm * bq + cn * (xn[:, None] * nv[None, :])) * (1.0 + 2.0 ** -18) slop = (tl.abs(acc) + b) * (2.0 ** -20) + 1e-30 lo = acc - b - slop hi = acc + b + slop valid = (rows[:, None] < M) & cm[None, :] fin = (acc == acc) & (tl.abs(acc) < float("inf")) & (b == b) & (tl.abs(b) < float("inf")) bad = tl.max(tl.max(tl.where(valid, tl.where(fin, 0, 1), 0), axis=1), axis=0) tl.store(BAD + pid, bad) real = (rows[:, None] < M) & (cols[None, :] < NREAL) hm = tl.where(real, hi, float("-inf")) lm = tl.where(real, lo, float("-inf")) ht = tl.max(tl.reshape(hm, (MP, BN // 32, 32)), axis=2) tt = pid * (BN // 32) + tl.arange(0, BN // 32) tl.store(FB + rows[:, None] * T1 + tt[None, :], ht, (rows[:, None] < M) & (tt[None, :] < T1 - 1)) tl.store(LOC + rows * NCTA + pid, tl.max(lm, axis=1), rows < M) if dbg != 0: o = rows[:, None] * N + cols[None, :] tl.store(DS + o, acc, valid) tl.store(DLO + o, lo, valid) tl.store(DHI + o, hi, valid)
# ------------------------------------------------------------------------------------------------ K2 / K3@triton.jitdef _reduce_kernel(LOC, BAD, FB, OKW, FLAG, NCTA, T, T1, BLOCK: tl.constexpr): r = tl.program_id(0) if tl.load(FLAG) != 0: m = tl.full((BLOCK,), float("-inf"), tl.float32) bad = tl.zeros((BLOCK,), tl.int32) for c0 in range(0, NCTA, BLOCK): o = c0 + tl.arange(0, BLOCK) v = tl.load(LOC + r * NCTA + o, o < NCTA, other=float("-inf")) m = tl.maximum(m, v) bad = tl.maximum(bad, tl.load(BAD + o, o < NCTA, other=0)) bad = tl.maximum(bad, tl.where(v == v, 0, 1)) tl.store(FB + r * T1 + T, tl.max(m, axis=0)) tl.store(OKW + r, 1 - tl.max(bad, axis=0))
@triton.jitdef _select_kernel(FB, OKW, FLAG, NEED, M, T, T1, e1, e3, cap, BLOCK: tl.constexpr, MP: tl.constexpr): pid = tl.program_id(0) t = pid * BLOCK + tl.arange(0, BLOCK) tm = t < T rows = tl.arange(0, MP) rm = rows < M fm = tl.load(FB + rows * T1 + T, rm, other=0.0) okw = tl.load(OKW + rows, rm, other=1) good = tl.where(rm, ((okw != 0) & (fm - e1 > -cap) & (tl.abs(fm) < float("inf"))).to(tl.int32), 1) ok = (tl.min(good, axis=0) == 1) & (tl.load(FLAG) != 0) fh = tl.load(FB + rows[:, None] * T1 + t[None, :], rm[:, None] & tm[None, :], other=float("-inf")) cand = tl.max(tl.where(rm[:, None] & (fh + e3 >= fm[:, None]), 1, 0), axis=0) need = tl.where(ok, cand, 1) tl.store(NEED + t, need, tm)
# ------------------------------------------------------------------------------------------------ host: packingdef _up16(target): """FP64 (> 0) -> FP16 rounded toward +inf (finite inputs; one bit step on the positive range).""" h = target.to(torch.float16) b = h.view(torch.int16) b = torch.where(h.to(torch.float64) < target, b + 1, b) return b.view(torch.float16)
def _up32(target): f = target.to(torch.float32) return torch.where(f.to(torch.float64) < target, torch.nextafter(f, torch.full_like(f, math.inf)), f)
def pack(W, bits, group=GROUP, chunk=8192): """W [V, K] BF16 (any device) -> dict: q (BITS 8: int8 [V, K]; 6 / 4: uint8 nibble plane [V, K / 2]), qb (BITS 6: uint8 2-bit plane [V, K / 4], else a 1-byte stub), sc FP16 [V, NG] (scale, rounded up), R FP16 [V, NG] (||W_g - D_g||, up), N FP32 [V] (max(||W_v||, ||D_v||), up). D = q * sc exactly (FP64); decode(pk) gives it.""" V, K = W.shape NG = K // group qmax = 2 ** (bits - 1) - 1 dev = W.device if bits == 8: q_all = torch.empty((V, K), dtype=torch.int8, device=dev) else: q_all = torch.empty((V, K // 2), dtype=torch.uint8, device=dev) qb_all = torch.empty((V, K // 4), dtype=torch.uint8, device=dev) if bits == 6 else torch.zeros(16, dtype=torch.uint8, device=dev) sc_all = torch.empty((V, NG), dtype=torch.float16, device=dev) R_all = torch.empty((V, NG), dtype=torch.float16, device=dev) N_all = torch.empty((V,), dtype=torch.float32, device=dev) for a in range(0, V, chunk): w = W[a:a + chunk].to(torch.float64) n = w.shape[0] wg = w.view(n, NG, group) amax = wg.abs().amax(-1, keepdim=True) s16 = torch.where(amax > 0, _up16(torch.where(amax > 0, amax / qmax, torch.ones_like(amax))), torch.zeros_like(amax, dtype=torch.float16)) s = s16.to(torch.float64) q = torch.where(s > 0, torch.clamp(torch.round(wg / torch.where(s > 0, s, torch.ones_like(s))), -qmax, qmax), torch.zeros_like(wg)) D = (q * s).view(n, K) sc_all[a:a + n] = s16.view(n, NG) R_all[a:a + n] = _up16((w - D).view(n, NG, group).pow(2).sum(-1).sqrt() * (1 + 2.0 ** -40) + 1e-300) N_all[a:a + n] = _up32(torch.maximum(w.norm(dim=1), D.norm(dim=1)) * (1 + 2.0 ** -40) + 1e-300) qi = q.view(n, K).to(torch.int32) if bits == 8: q_all[a:a + n] = qi.to(torch.int8) continue f = (qi + (qmax + 1)).view(n, K // 64, 4, 16) # field in [1, 2 qmax + 1]; (s, j) = k - kb = 16 s + j lo4 = f & 0xF b0 = lo4[:, :, 0] | (lo4[:, :, 2] << 4) b1 = lo4[:, :, 1] | (lo4[:, :, 3] << 4) q_all[a:a + n] = torch.stack([b0, b1], dim=2).reshape(n, K // 2).to(torch.uint8) if bits == 6: h2 = (f >> 4) & 0x3 qb_all[a:a + n] = (h2[:, :, 0] | (h2[:, :, 1] << 2) | (h2[:, :, 2] << 4) | (h2[:, :, 3] << 6)).reshape(n, K // 4).to(torch.uint8) return {"bits": bits, "q": q_all, "qb": qb_all, "sc": sc_all, "R": R_all, "N": N_all, "V": V, "K": K, "NG": NG, "bytes": q_all.numel() * q_all.element_size() + (qb_all.numel() if bits == 6 else 0) + sc_all.numel() * 2 + R_all.numel() * 2 + N_all.numel() * 4}
def decode(pk, rows=slice(None)): """Host reference decoder: D [n, K] FP64 for the given vocab rows (independent of the kernel's decode).""" bits, K, NG = pk["bits"], pk["K"], pk["NG"] qmax = 2 ** (bits - 1) - 1 if bits == 8: q = pk["q"][rows].to(torch.int64) else: by = pk["q"][rows].to(torch.int64) n = by.shape[0] by = by.view(n, K // 64, 2, 16) lo = torch.stack([by[:, :, 0] & 0xF, by[:, :, 1] & 0xF, by[:, :, 0] >> 4, by[:, :, 1] >> 4], dim=2) # [n, K/64, 4, 16] if bits == 6: hb = pk["qb"][rows].to(torch.int64).view(n, K // 64, 16) hi = torch.stack([(hb >> (2 * s)) & 0x3 for s in range(4)], dim=2) f = lo | (hi << 4) else: f = lo q = (f - (qmax + 1)).reshape(n, K) s = pk["sc"][rows].to(torch.float64).repeat_interleave(GROUP, dim=1) return q.to(torch.float64) * s
# ------------------------------------------------------------------------------------------------ host: one headclass Cert: """Buffers + launches of one certified head for a fixed (form, M, x buffer, out buffer). run() is capturable."""
def __init__(self, W, pk, vocab, e, M, softcap_fn, bn=64, nw=4, ns=None, exact="E1", testf32=False, cap=CAP): dev = W.device V, K = W.shape assert V % TILE == 0 and K % GROUP == 0 and K % 256 == 0 and M <= 16 and bn % 32 == 0 self.W, self.pk, self.vocab, self.M, self.K, self.V = W, pk, vocab, M, K, V self.T = V // TILE self.T1 = self.T + 1 self.bn, self.nw, self.ns, self.exact, self.testf32, self.cap = bn, nw, ns, exact, testf32, cap self.NCTA = triton.cdiv(V, bn) self.e = float(e) # FP32 evaluation margin of 'fh + 3e >= fm' and 'fm - e > -cap' when e > 0 (|f| <= cap < 32: ulp <= 2^-19) self.e1 = self.e + (2.0 ** -18 if self.e > 0 else 0.0) self.e3 = 3.0 * self.e + (2.0 ** -18 if self.e > 0 else 0.0) self.cn = 2.0 * c_acc(K) self.softcap_fn = softcap_fn z = lambda *s, dt=torch.float32: torch.zeros(s, dtype=dt, device=dev) self.xg, self.xn = z(16, pk["NG"]), z(16) self.loc, self.bad = z(16, self.NCTA), z(self.NCTA, dt=torch.int32) self.fb, self.okw = z(16, self.T1), z(16, dt=torch.int32) self.need = torch.ones(self.T, dtype=torch.int32, device=dev) self.flag = torch.ones(1, dtype=torch.int32, device=dev) self.dummy = z(1) self.dbg = None
def debug_buffers(self): dev = self.W.device self.dbg = tuple(torch.empty((self.M, self.V), dtype=torch.float32, device=dev) for _ in range(3)) # S, lo, hi return self.dbg
def screen(self, x, qterm=1.0, dbg=False): pk = self.pk ds, dlo, dhi = self.dbg if dbg else (self.dummy, self.dummy, self.dummy) kw = {"num_warps": self.nw} if self.ns is not None: kw["num_stages"] = self.ns _xnorm_kernel[(1,)](x, self.xg, self.xn, self.M, x.stride(0), NG=pk["NG"], GROUP=GROUP, GP=256, MP=16, num_warps=4) _screen_kernel[(self.NCTA,)](x, pk["q"], pk["qb"], pk["sc"], pk["R"], pk["N"], self.xg, self.xn, self.flag, self.fb, self.loc, self.bad, ds, dlo, dhi, self.M, self.V, self.vocab, x.stride(0), pk["q"].stride(0), pk["qb"].stride(0) if pk["bits"] == 6 else 0, self.T1, self.NCTA, float(qterm), self.cn, 1 if dbg else 0, BITS=pk["bits"], BN=self.bn, MP=16, NG=pk["NG"], GROUP=GROUP, TESTF32=self.testf32, **kw)
def select(self): _reduce_kernel[(self.M,)](self.loc, self.bad, self.fb, self.okw, self.flag, self.NCTA, self.T, self.T1, BLOCK=1024, num_warps=4) self.softcap_fn(self.fb, self.cap) _select_kernel[(triton.cdiv(self.T, 1024),)](self.fb, self.okw, self.flag, self.need, self.M, self.T, self.T1, self.e1, self.e3, self.cap, BLOCK=1024, MP=16, num_warps=4)
def exact_pass(self, x, out, kernel=None): k = kernel or (_exact_kernel if self.exact == "E1" else _exact_masked_kernel) k[(self.T,)](x, self.W, out, self.need, self.M, self.V, self.K, x.stride(0), self.W.stride(0), out.stride(0), BN=32, BK=256, MP=16, TESTF32=self.testf32, num_warps=4)
def run(self, x, out, qterm=1.0, dbg=False): self.screen(x, qterm, dbg) self.select() self.exact_pass(x, out) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""n80_cuda.py (inkling2-spark decode seat, tree n80, 2026-11-24): K-chunked variant of n75 build 2 for drafter linears whose K istoo large for build 2's one shared x stage (DSpark drafter down_proj: K 9216 needs 147 KB at M <= 8). Same 12-bit fragment stream(n75_cuda.pack_frag of an n75_c12.pack_c12 "row" pack), same decode / escape / store code (copied verbatim from c12m_kernel),same per-element FP32 order (one in-order mma.sync chain over K per output tile) -> bit-identical to c12m and to the servedsm12x_bf16_gemv. x is restaged per chunk of CH k16 steps between CTA barriers; every warp walks the same rounds and chunks.Generated (inline script, decode seat) from work_stack/n137/b2/n75_cuda.py 0ab557d0 (the packed seat's build 2 + the stack seat's n137)."""import osimport torch
SMEM_MAX = 101376CUDA_SRC = r'''#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <cuda_bf16.h>#include <stdint.h>
__device__ __forceinline__ void mma16816(float (&c)[4], uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t b0, uint32_t b1) { asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n" : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));}
// n80 c12mk: n75 build 2's c12m_kernel with x staged in K chunks of CH k16 steps (CH % 8 == 0) instead of whole, for K too large for// one shared x stage (the drafter's down_proj, K 9216). Every warp walks the same rounds (one tile per warp per round) and chunks// between CTA barriers; per tile the accumulator runs ONE in-order mma.sync chain over K exactly as c12m_kernel (and the served// Triton _gemv_kernel), so outputs are bit-identical. Decode / escape / store code is c12m_kernel's, copied by gen. BF16 out only.template <int NW, int MT>__global__ void __launch_bounds__(NW * 32) c12mk_kernel(const uint4* __restrict__ wp, const uint8_t* __restrict__ basep, const uint16_t* __restrict__ W, const uint16_t* __restrict__ x, __nv_bfloat16* __restrict__ o, int M, int N, int K, int SX, int SW, int SY, int CH) { extern __shared__ uint4 xs[]; uint2* xs2 = reinterpret_cast<uint2*>(xs); const int steps = K >> 4, NU = steps / 8, ntiles = N >> 3; const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, stride = gridDim.x * NW; const int rounds = (ntiles + stride - 1) / stride; for (int rd = 0; rd < rounds; ++rd) { const int t = blockIdx.x * NW + warp + rd * stride; const bool valid = t < ntiles; float acc[4] = {0.f, 0.f, 0.f, 0.f}; const int n = valid ? t * 8 + (lane >> 2) : 0; const uint32_t base4 = valid ? (uint32_t)basep[n] * 0x01010101u : 0u; const uint16_t* wrow = W + (size_t)n * SW; for (int s0 = 0; s0 < steps; s0 += CH) { const int s1 = min(steps, s0 + CH); __syncthreads(); // every warp finished reading the previous chunk for (int i = threadIdx.x; i < (s1 - s0) * 32; i += NW * 32) { const int s = s0 + (i >> 5), l = i & 31, r = l >> 2, kq = s * 16 + (l & 3) * 2; uint32_t a0 = 0, a1 = 0, a2 = 0, a3 = 0; if (r < M) { a0 = *reinterpret_cast<const uint32_t*>(x + (size_t)r * SX + kq); a2 = *reinterpret_cast<const uint32_t*>(x + (size_t)r * SX + kq + 8); } if (MT == 2 && r + 8 < M) { a1 = *reinterpret_cast<const uint32_t*>(x + (size_t)(r + 8) * SX + kq); a3 = *reinterpret_cast<const uint32_t*>(x + (size_t)(r + 8) * SX + kq + 8); } if (MT == 1) xs2[i] = make_uint2(a0, a2); else xs[i] = make_uint4(a0, a1, a2, a3); } __syncthreads(); if (valid) { const int u0 = s0 >> 3, u1 = s1 >> 3; const uint4* p = wp + ((size_t)t * NU + u0) * 96 + lane; uint4 c0 = __ldg(p), c1 = __ldg(p + 32), c2 = __ldg(p + 64); for (int u = u0; u < u1; ++u) { uint4 d0, d1, d2; const bool more = u + 1 < u1; if (more) { const uint4* q = wp + ((size_t)t * NU + u + 1) * 96 + lane; d0 = __ldg(q); d1 = __ldg(q + 32); d2 = __ldg(q + 64); } const uint32_t L[8] = {c0.x, c0.y, c0.z, c0.w, c1.x, c1.y, c1.z, c1.w}; const uint32_t Cw[4] = {c2.x, c2.y, c2.z, c2.w}; #pragma unroll for (int j = 0; j < 8; ++j) { const uint32_t c4 = (j & 1) ? ((Cw[j >> 1] >> 4) & 0x0F0F0F0Fu) : (Cw[j >> 1] & 0x0F0F0F0Fu); const uint32_t hi = ((c4 & 0x07070707u) + base4) | ((c4 << 4) & 0x80808080u); uint32_t b0 = __byte_perm(L[j], hi, 0x5140), b1 = __byte_perm(L[j], hi, 0x7362); const uint32_t e7 = c4 & 0x07070707u, f = e7 & (e7 >> 1) & (e7 >> 2) & 0x01010101u; const int s = u * 8 + j, sl = s - s0; if (f) { // escape: the element comes from the resident BF16 original const int kb = s * 16 + (lane & 3) * 2; #pragma unroll for (int i = 0; i < 4; ++i) { if ((f >> (8 * i)) & 1u) { const uint32_t v = wrow[kb + (i >= 2 ? 8 : 0) + (i & 1)]; if (i == 0) b0 = (b0 & 0xFFFF0000u) | v; else if (i == 1) b0 = (b0 & 0x0000FFFFu) | (v << 16); else if (i == 2) b1 = (b1 & 0xFFFF0000u) | v; else b1 = (b1 & 0x0000FFFFu) | (v << 16); } } } if (MT == 1) { const uint2 a = xs2[sl * 32 + lane]; mma16816(acc, a.x, 0u, a.y, 0u, b0, b1); } else { const uint4 a = xs[sl * 32 + lane]; mma16816(acc, a.x, a.y, a.z, a.w, b0, b1); } } if (more) { c0 = d0; c1 = d1; c2 = d2; } } } } if (valid) { // c12m_kernel's BF16 store: D[r][c] with r = lane / 4 (+ 8), c = 8 t + 2 (lane % 4) + {0, 1} const int r = lane >> 2, col = t * 8 + (lane & 3) * 2; if (r < M) *reinterpret_cast<__nv_bfloat162*>(o + (size_t)r * SY + col) = __floats2bfloat162_rn(acc[0], acc[1]); if (MT == 2 && r + 8 < M) *reinterpret_cast<__nv_bfloat162*>(o + (size_t)(r + 8) * SY + col) = __floats2bfloat162_rn(acc[2], acc[3]); } }}
template <int NW, int MT>static void launchk(const at::Tensor& wp, const at::Tensor& base, const at::Tensor& W, const at::Tensor& x, at::Tensor& out, int64_t M, int64_t N, int64_t K, int64_t SX, int64_t SY, int64_t CH, int64_t grid) { const int smem = (int)CH * 32 * (MT == 1 ? 8 : 16); auto kern = c12mk_kernel<NW, MT>; static int set = 0; if (set < smem) { C10_CUDA_CHECK(cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem)); set = smem; } if (grid <= 0) { int occ = 0, dev = 0, sms = 0; C10_CUDA_CHECK(cudaGetDevice(&dev)); C10_CUDA_CHECK(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev)); C10_CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, kern, NW * 32, smem)); const int64_t need = (N / 8 + NW - 1) / NW; grid = std::min<int64_t>(need, (int64_t)std::max(occ, 1) * sms); } kern<<<(int)grid, NW * 32, smem, at::cuda::getCurrentCUDAStream()>>>( reinterpret_cast<const uint4*>(wp.data_ptr()), base.data_ptr<uint8_t>(), reinterpret_cast<const uint16_t*>(W.data_ptr()), reinterpret_cast<const uint16_t*>(x.data_ptr()), reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), (int)M, (int)N, (int)K, (int)SX, (int)W.stride(0), (int)SY, (int)CH); C10_CUDA_KERNEL_LAUNCH_CHECK();}
void c12mk(at::Tensor wp, at::Tensor base, at::Tensor W, at::Tensor x, at::Tensor out, int64_t M, int64_t SX, int64_t SY, int64_t nw, int64_t ch, int64_t grid) { const int64_t N = W.size(0), K = W.size(1); TORCH_CHECK(out.scalar_type() == at::kBFloat16, "c12mk: BF16 out only"); TORCH_CHECK(ch > 0 && ch % 8 == 0 && K % 128 == 0 && N % 8 == 0 && M >= 1 && M <= 16, "c12mk: bad shape / chunk"); const int mt = M <= 8 ? 1 : 2;#define C12MK_CASE(NWV, MTV) if (nw == NWV && mt == MTV) return launchk<NWV, MTV>(wp, base, W, x, out, M, N, K, SX, SY, ch, grid); C12MK_CASE(4, 1) C12MK_CASE(4, 2) C12MK_CASE(8, 1) C12MK_CASE(8, 2) C12MK_CASE(16, 1) C12MK_CASE(16, 2) TORCH_CHECK(false, "c12mk: unsupported nw ", nw);}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("c12mk", &c12mk); }'''_EXT = None
def build(verbose=False, build_dir=None): global _EXT if _EXT is None: from torch.utils.cpp_extension import load_inline arch = os.environ.get("N75_CUDA_ARCH", "121a") kw = {"build_directory": build_dir} if build_dir else {} if build_dir: os.makedirs(build_dir, exist_ok=True) _EXT = load_inline("n80_c12mk", cpp_sources="", cuda_sources=CUDA_SRC, verbose=verbose, with_cuda=True, extra_cuda_cflags=["-O3", f"-gencode=arch=compute_{arch},code=sm_{arch}", "-Xptxas=-v"], **kw) return _EXT
def max_ch(m): """Largest chunk (k16 steps, multiple of 8) whose x stage fits one block.""" per = 32 * (8 if m <= 8 else 16) return (SMEM_MAX // per) // 8 * 8
def c12mk_gemv(x, w, pk, frag, out=None, nw=8, ch=0, grid=0): """x[..., K] @ w[N, K]^T (BF16 out) from the fragment stream, x staged in chunks of ch k16 steps (0 = the largest that fits).""" n, k = pk["shape"] lead = x.shape[:-1] x2 = x.reshape(-1, k) m = x2.shape[0] if not (1 <= m <= 16 and x2.dtype == torch.bfloat16 and x2.stride(1) == 1 and x2.stride(0) % 2 == 0 and x2.data_ptr() % 4 == 0): raise ValueError(f"c12mk_gemv: unsupported operands (m {m}, k {k}, x stride {x2.stride()})") ch = ch or max_ch(m) ch = min(ch, (k // 16 + 7) // 8 * 8) if out is None: out = torch.empty((m, n), device=x.device, dtype=torch.bfloat16) elif not (out.dtype == torch.bfloat16 and out.stride(-1) == 1 and (out.dim() < 2 or out.stride(0) % 2 == 0) and out.data_ptr() % 4 == 0): raise ValueError("c12mk_gemv: unsupported out") build().c12mk(frag, pk["base"], w, x2, out, m, x2.stride(0), out.stride(0) if out.dim() > 1 else n, nw, ch, grid) return out.view(*lead, n)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""n80 rider (inkling2-spark decode seat, 2026-11-24; DRAFT, not run on the image): exact 12-bit packed DSpark drafter linears onn75's packed registry (S6: n75_install.py df7cb3e4, n75_cuda.py 0ab557d0, n75_c12.py bb969a78) and the served <= 16-rowsm12x_bf16_gemv route. Bitwise to the served drafter GEMV, so draft tokens, acceptance and outputs are unchanged.
Knobs (env): N80_DRAFT ('' or unset = off, nothing patched; A = n75 build 2 on the drafter linears whose K fits its one shared xstage; B = A + n80_cuda.c12mk on the others, i.e. down_proj K 9216), N80_NW (c12m warps for drafter classes, default 16),N80_MK_NW (c12mk warps, default 8), N80_SKIP (comma list of linears left served, default kv_proj_ctx: mb1 read it +2 pctslower packed, N 2,048 being launch-bound). Needs n75 on (N75_C12 non-empty); otherwise logs and stays off.What it patches: * n75_install._prepare (n75's own one-time hook at the first target DECODE / TARGET-VERIFY forward outside capture, after the KV pool, before the draft model's graphs are captured): after the original, every DFlashDraftModel instance's BF16 linears on the route (2-D, no bias, N >= 2048, K % 256 == 0) are packed: - K that fits build 2 at 16 rows -> n75's registry as class 'draft <leaf>' with KERN 'cuda' (n75's build 2). An entry that would fall back to build 1 (Triton: NOT bitwise, n75 mb1) is removed again, so that weight stays on the served path. - (B) other K -> this module's registry, served by c12mk through one more wrapper around unquant._sm12x_bf16_gemv (the function n75 installed). Everything else falls through to it. The BF16 originals stay (escapes and > 16-row calls read them): about +297 MB (A) / +393 MB (B) device memory after the KV pool.Log prefix '[n80 pid=...]'."""import gc, logging, os
import torch
logger = logging.getLogger(__name__)FORM = os.environ.get("N80_DRAFT", "").strip().upper()NW = int(os.environ.get("N80_NW", "16"))MK_NW = int(os.environ.get("N80_MK_NW", "8"))LEAVES = ("qkv_proj", "kv_proj_ctx", "o_proj", "gate_up_proj", "down_proj")SKIP = {v.strip() for v in os.environ.get("N80_SKIP", "kv_proj_ctx").split(",") if v.strip()}_S = {"installed": False, "done": False, "mk": {}, "mk_calls": 0, "mk_miss": 0, "n75": 0, "bytes": 0}
def _log(msg, *a): logger.warning(f"[n80 pid={os.getpid()}] " + msg, *a)
def _mods(): from sglang.srt.models.inkling_common import n75_c12 as C, n75_cuda as G, n75_install as N try: from sglang.srt.models.inkling_common import n80_cuda as K except ImportError: import n80_cuda as K return C, G, N, K
def _find_drafters(cls): """Every instance of cls alive in this process, also when SGLang's graph-capture setup has run gc.freeze() (base_cuda_graph_runner): frozen objects leave the normal generations, so gc.get_objects() alone returns none of them (stack seat, 2026-11-24: the first composed boot of form B packed 0 drafters for this reason). unfreeze moves them back to the oldest generation, freeze restores the state afterwards; no collection runs (gc stays as it was). type(o).__mro__ is used instead of isinstance: no __class__ lookups on weakref proxies or other objects with hooked __class__.""" frozen = gc.get_freeze_count() > 0 if frozen: gc.unfreeze() try: return [o for o in gc.get_objects() if cls in type(o).__mro__] finally: if frozen: gc.freeze()
def _register_drafter(): C, G, N, K = _mods() if N.S.get("orig") is None: _log("n75's wrapper is not installed (n75 prepared off): n80 off") return from sglang.srt.layers.linear import LinearBase from sglang.srt.models.dflash import DFlashDraftModel drafts = _find_drafters(DFlashDraftModel) if not drafts: _log("no DFlashDraftModel instance found (freeze count %d): n80 packs nothing, served path", gc.get_freeze_count()) N.KERN["draft"] = "cuda" for d in drafts: for name, m in d.named_modules(): leaf = name.split(".")[-1] w, b = getattr(m, "weight", None), getattr(m, "bias", None) if (not isinstance(m, LinearBase) or leaf not in LEAVES or leaf in SKIP or b is not None or not isinstance(w, torch.Tensor) or w.dtype != torch.bfloat16 or w.dim() != 2 or w.shape[0] < 2048 or w.shape[1] % 256 or w.stride(1) != 1): continue if G.fits(w.shape[1], 16): nb = N._register("draft " + leaf, w.data) e = N.S["reg"].get(w.data_ptr()) if e is None or e.get("frag") is None: # build 1 is not bitwise: keep the served path for this weight N.S["reg"].pop(w.data_ptr(), None) _log("%s %s: no build 2 entry, served path", name, tuple(w.shape)) continue N.CUDA_NW["draft " + leaf] = NW _S["n75"] += 1; _S["bytes"] += nb elif FORM == "B": pk = C.pack_c12(w.data, "row") if pk is None: _log("%s %s FAILED the bitwise round trip: served path", name, tuple(w.shape)) continue frag = G.pack_frag(pk) pk["lo"] = pk["cd"] = None # c12mk reads the fragment stream, the base and (escapes) the original _S["mk"][w.data_ptr()] = (pk, frag, tuple(w.shape), tuple(w.stride())) _S["bytes"] += frag.numel() + pk["base"].numel() if _S["mk"]: K.build() from sglang.srt.layers.quantization import unquant as U prev = U._sm12x_bf16_gemv
def wrapped(x, weight, bias=None, out_dtype=None, out=None): e = _S["mk"].get(weight.data_ptr()) if (e is not None and bias is None and out_dtype in (None, torch.bfloat16) and x.dtype == torch.bfloat16 and e[2] == tuple(weight.shape) and e[3] == tuple(weight.stride()) and x.numel() // max(1, x.shape[-1]) <= 16): try: y = K.c12mk_gemv(x, weight, e[0], e[1], out=out, nw=MK_NW) _S["mk_calls"] += 1 return y except ValueError: _S["mk_miss"] += 1 return prev(x, weight, bias, out_dtype, out)
U._sm12x_bf16_gemv = wrapped torch.cuda.synchronize() _log("drafter linears packed: %d DFlashDraftModel, %d on n75 build 2 (nw %d), %d on c12mk (nw %d), %.1f MB, form %s", len(drafts), _S["n75"], NW, len(_S["mk"]), MK_NW, _S["bytes"] / 1e6, FORM)
def install(): if _S["installed"]: return _S["installed"] = True if FORM not in ("A", "B"): _log("N80_DRAFT %r: off, nothing patched", FORM) return from sglang.srt.models.inkling_common import n75_install as N if not N.SEL: _log("n75 is off (N75_C12 empty): n80 off") return orig_prepare = N._prepare
def _prepare(): orig_prepare() if not _S["done"]: _S["done"] = True try: _register_drafter() except Exception as e: # never kill the server: remove drafter entries, served path for k_, e_ in list(N.S["reg"].items()): if str(e_.get("cls", "")).startswith("draft "): N.S["reg"].pop(k_, None) _S["mk"].clear() _log("drafter packing failed (%r): n80 off, served path", e)
N._prepare = _prepare _log("installed: form %s (packing at n75's first-decode prepare)", FORM)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448"""n86 S1 riders (inkling2-spark stack seat, 2026-11-23): n54 + G1 + G2 (n71 riders, KEEP in mb2a-d) + the n75 build-2 rider gate.
Mounted beside the image modules at srt/models/inkling_common/n86_riders.py; install() is called from the bottom of the mountedinkling2_attn.py (after n75's install). Every knob off = the n54 code path (nothing patched).
G1 (N86_G1=1): the MLP short conv of an EXTEND batch of >= 2048 rows (the served tiled-kernel range, PREFILL_MIN_ROWS) writes the layer's residual update directly (n71_sconvres.sconv_residual 09d3d221 = the image _sconv_prefill_kernel text + residual_add's FP32 order / the block-boundary BF16 add); the sconv cache prepare and update stay the served calls, in the served order around the conv. Gates (else the served path, counted): static weights, BF16 contiguous x / attention / partial of one shape, the served cache shape.G2 (N86_G2=1): attn_res(normalize_values=True) + the RMSNorm it feeds in one kernel (n71_resnorm.resnorm d1054a4c) on the NON-LOOP visits (messages is None) of EXTEND batches of >= N86_MIN_ROWS rows: attention side (local: attn_norm; global: the q / k / v input norms into one [3, T, W] BF16 buffer) and MLP side (mlp_norm). Only the (side, sources, addend, queries) shapes in N86_G2_SHAPES run fused (default: mb2d's 16 walk shapes minus ('mlp', 5, 1, 1), which mb2d measured slower, 1.694 -> 2.574 ms); other shapes, BF16 / contiguity / pre_weight / output-dtype misses and blocks-empty visits take the served calls.n75 gate (N75_C12 set): wraps n75_install._wrapped (n75_install.py 088711f7 unchanged) before its _prepare installs it, so the packed GEMV runs only where RULE n86 S1 (i)-(ii) show coverage: build 2 (registered entry has a CUDA fragment stream), M in N86_N75_MS (default 8,16: bitwise in mb1 BITC and timed in TIMEC), weight shape in {qkvr 8600x2304, wo_ud 2304x3072, LM head 201024x2304} and class in N86_N75_CLASSES; every other call takes S['orig'] (the served kernel), counted.
FAIL CLOSED: install() checks the md5 of the nine image files the patch derives from (inkling2.py, inkling2_attn_res.py,inkling2_sconv.py, sconv.py, inkling2_norm.py and the AttnRes / sconv / RMSNorm / residual_add kernel files) and that each of thethree text edits of the served Inkling2DecoderLayer._forward matches exactly once; on any miss G1 and G2 stay off (logged).The patched _forward is the image's source with three guarded insertions, exec'd in inkling2's module globals.Reach: Python counters per path (graph capture + eager calls) printed as 'N86REACH ...' lines; graph replays are not countedhere (the check boot's profiler census counts kernels)."""import hashlib, logging, os, sys, textwrap, threading, time
import torch
logger = logging.getLogger(__name__)
G1 = os.environ.get("N86_G1", "0") == "1"G2 = os.environ.get("N86_G2", "0") == "1"MIN_ROWS = int(os.environ.get("N86_MIN_ROWS", "2048") or 2048)G1_MIN_ROWS = 2048 # the image short_convolution's PREFILL_MIN_ROWS (asserted at install against the module)_DEFAULT_G2 = ("attn:2:0:1,attn:2:0:3,attn:3:0:1,attn:3:0:3,attn:4:0:1,attn:4:0:3,attn:5:0:1,attn:5:0:3," "mlp:2:0:1,mlp:2:1:1,mlp:3:0:1,mlp:3:1:1,mlp:4:0:1,mlp:4:1:1,mlp:5:0:1")
def _shapes(raw): out = set() for part in filter(None, (p.strip() for p in raw.split(","))): side, n, ad, q = part.split(":") out.add((side, int(n), int(ad), int(q))) return out
G2_SHAPES = _shapes(os.environ.get("N86_G2_SHAPES") or _DEFAULT_G2) # empty / unset = the default listN75_MS = {int(v) for v in (os.environ.get("N86_N75_MS") or "8,16").split(",") if v.strip()}N75_CLASSES = {v.strip() for v in (os.environ.get("N86_N75_CLASSES") or "qkvr,wo_ud,lm_head").split(",") if v.strip()}N75_SHAPES = {"qkvr": (8600, 2304), "wo_ud": (2304, 3072), "lm_head": (201024, 2304)}
# md5 of the image files the patch derives from (image lmsysorg/sglang@sha256:efac853b..., checked 11-23 on the Spark)IMAGE_MD5 = { "sglang.srt.models.inkling2": "5db5443befb09e9a846d2fad560bb7cb", "sglang.srt.models.inkling_common.inkling2_attn_res": "803b43bfe76e190f0bf92c61269c2ae2", "sglang.srt.models.inkling_common.inkling2_sconv": "8ca39087d78cfacc0d580144a39c726e", "sglang.srt.models.inkling_common.sconv": "f2d226bdb97182a70b76f24bee3a9ff5", "sglang.srt.models.inkling_common.inkling2_norm": "a1aa0ab904b384f7ab6e61e1af7a3a0f", "sglang.kernels.ops.attention.inkling2_attn_res": "4da6f04bca81772dcc6109bc67fc1730", "sglang.kernels.ops.mamba.inkling2_sconv": "f65e89067b7fa7d76b9b7c3e4bacea26", "sglang.kernels.ops.layernorm.inkling2_rms_norm": "e1be9289e74eb22350b0206f4244f941", "sglang.kernels.ops.elementwise.inkling2_residual_add": "c42560e64d3629b070582e0d7c09525e",}FORWARD_MD5 = "466a152cc7f66083a999dbf15f926fb8" # dedented source of the image Inkling2DecoderLayer._forward
# ---- the three guarded insertions into the served _forward (each anchor must match exactly once) ----EDITS = ( (" attn_input = self._attention_input(\n" " state.attention_input(self.layer_id), messages\n" " )\n", " attn_input = _n86_g2_attention(self, state, forward_batch, messages)\n" " if attn_input is None:\n" " attn_input = self._attention_input(\n" " state.attention_input(self.layer_id), messages\n" " )\n"), (" mlp_input = state.mlp_input(self.layer_id, attention)\n" " if messages is not None:\n" " mlp_input = messages.mix(\n" " self.layer_id - self.config.loop_core_layers.start,\n" " (mlp_input,),\n" " self.controller_weights,\n" " \"mlp\",\n" " )[0]\n" " mlp_input = self.mlp_norm(mlp_input)\n", " mlp_input = _n86_g2_mlp(self, state, attention, forward_batch, messages)\n" " if mlp_input is None:\n" " mlp_input = state.mlp_input(self.layer_id, attention)\n" " if messages is not None:\n" " mlp_input = messages.mix(\n" " self.layer_id - self.config.loop_core_layers.start,\n" " (mlp_input,),\n" " self.controller_weights,\n" " \"mlp\",\n" " )[0]\n" " mlp_input = self.mlp_norm(mlp_input)\n"), (" mlp = self.mlp_sconv(mlp, positions, forward_batch)\n" " state.finalize_layer(self.layer_id, attention, mlp)\n", " if _n86_g1(self, state, attention, mlp, forward_batch):\n" " return\n" " mlp = self.mlp_sconv(mlp, positions, forward_batch)\n" " state.finalize_layer(self.layer_id, attention, mlp)\n"),)
R = {"g1": {}, "g2": {}, "served": {}, "n75": {}, "modes": {}}K = {"sconv_residual": None, "resnorm": None, "pdl": None, "AttentionSources": None}_NW_CACHE = {}_STATE = {"installed": False, "patched": False, "why": "not installed"}
def _bump(d, k): d[k] = d.get(k, 0) + 1
def _served(reason): _bump(R["served"], reason) return None
def _md5_file(path): with open(path, "rb") as f: return hashlib.md5(f.read()).hexdigest()
def served_forward_source(path): """The dedented source of Inkling2DecoderLayer._forward from the image file (ast segment).""" import ast src = open(path).read() for node in ast.walk(ast.parse(src)): if isinstance(node, ast.ClassDef) and node.name == "Inkling2DecoderLayer": for f in node.body: if isinstance(f, ast.FunctionDef) and f.name == "_forward": return textwrap.dedent(ast.get_source_segment(src, f, padded=True)) return None
def patched_forward_source(served): out = served if served.endswith("\n") else served + "\n" # the ast segment ends without one for old, new in EDITS: if out.count(old) != 1: raise ValueError(f"n86: edit anchor found {out.count(old)} times: {old.splitlines()[0].strip()!r}") out = out.replace(old, new) return out
def _mode_ok(forward_batch): """EXTEND batches only (the served ShortConvolution.forward's extend = not decode and not verify); draft modes excluded.""" m = forward_batch.forward_mode _bump(R["modes"], getattr(m, "name", str(m))) if m.is_decode() or m.is_target_verify() or not m.is_extend(): return False for attr in ("is_draft_extend", "is_draft_extend_v2"): f = getattr(m, attr, None) if f is not None and f(): return False return True
DEVICE_OK = lambda x: x.is_cuda # noqa: E731 (the CPU pre-flight replaces it; served kernels need CUDA tensors)
def _bf16_rows(xs, shape): return all(x.dtype == torch.bfloat16 and x.is_contiguous() and tuple(x.shape) == shape and DEVICE_OK(x) for x in xs)
def _queries(attn_res, kind, layer_idx, queries): """block_attn_res's effective queries, exactly: unsqueeze a 1-D query, the cached scaled query (view) or q.float() * W**-0.5.""" if queries.ndim == 1: queries = queries.unsqueeze(0) scaled = attn_res.scaled_query(kind, layer_idx) eff = scaled.view(queries.shape) if scaled is not None else queries.float() * (queries.shape[-1] ** -0.5) return eff.contiguous()
def _norms_ok(norms): n0 = norms[0] return all(n.pre_weight is None and n.weight is not None and n.output_dtype == torch.bfloat16 and n.eps == n0.eps and n.weight.dtype == n0.weight.dtype and n.weight.is_contiguous() and n.weight.dim() == 1 for n in norms)
def _stacked_norm_weight(norms): """[3, W] q / k / v norm weights. Cached only when built outside graph capture (a persistent allocation); inside a capture the stack is recorded into the graph (a 27 KB copy per replay).""" key = tuple((n.weight.data_ptr(), n.weight._version) for n in norms) w = _NW_CACHE.get(key) if w is not None: return w w = torch.stack([n.weight for n in norms]).contiguous() if not torch.cuda.is_current_stream_capturing(): _NW_CACHE[key] = w else: _bump(R["g2"], "nw stacked in capture") return w
def _n86_g2_attention(layer, state, forward_batch, messages): if not G2: return None if messages is not None: return _served("g2 attn: loop pass (messages)") if not state.blocks: return _served("g2 attn: blocks empty (no attn_res)") partial = state.partial if not _mode_ok(forward_batch): return _served("g2 attn: not extend") T, W = partial.shape if T < MIN_ROWS: return _served("g2 attn: rows < min") ar = state.attn_res if not ar.normalize_values: return _served("g2 attn: normalize_values False") sources = [*state.blocks, partial] local = layer.is_local Q = 1 if local else 3 key = ("attn", len(sources), 0, Q) if key not in G2_SHAPES: return _served(f"g2 shape {key} served") if not _bf16_rows(sources, (T, W)): return _served("g2 attn: dtype / layout") norms = (layer.attn_norm,) if local else (layer.q_input_norm, layer.k_input_norm, layer.v_input_norm) if not _norms_ok(norms): return _served("g2 attn: norm config") q = _queries(ar, "attn", layer.layer_id, ar.attn_query(layer.layer_id)) if tuple(q.shape) != (Q, W) or q.dtype != torch.float32: return _served("g2 attn: query shape") nw = norms[0].weight if local else _stacked_norm_weight(norms) y = partial.new_empty((Q, T, W), dtype=torch.bfloat16) K["resnorm"](sources, None, q, nw, y, 1e-6, norms[0].eps) _bump(R["g2"], key) if local: return y[0] return K["AttentionSources"](y[0], y[1], y[2])
def _n86_g2_mlp(layer, state, attention, forward_batch, messages): if not G2: return None if messages is not None: return _served("g2 mlp: loop pass (messages)") if not _mode_ok(forward_batch): return _served("g2 mlp: not extend") T, W = state.partial.shape if T < MIN_ROWS: return _served("g2 mlp: rows < min") ar = state.attn_res if not ar.normalize_values: return _served("g2 mlp: normalize_values False") if ar.is_block_boundary(layer.layer_id): # mlp_input: blocks + [partial], partial block = attention sources, addend = [*state.blocks, state.partial, attention], None else: # mlp_input: blocks, (partial, attention) = last source + addend sources, addend = [*state.blocks, state.partial], attention key = ("mlp", len(sources), int(addend is not None), 1) if key not in G2_SHAPES: return _served(f"g2 shape {key} served") if not _bf16_rows(sources + ([addend] if addend is not None else []), (T, W)): return _served("g2 mlp: dtype / layout") norm = layer.mlp_norm if not _norms_ok((norm,)): return _served("g2 mlp: norm config") q = _queries(ar, "mlp", layer.layer_id, ar.mlp_queries[layer.layer_id]) if tuple(q.shape) != (1, W) or q.dtype != torch.float32: return _served("g2 mlp: query shape") y = state.partial.new_empty((1, T, W), dtype=torch.bfloat16) K["resnorm"](sources, addend, q, norm.weight, y, 1e-6, norm.eps) _bump(R["g2"], key) return y[0]
def _n86_g1(layer, state, attention, mlp, forward_batch): if not G1: return False if not isinstance(mlp, torch.Tensor): _served("g1: routed output") return False if not _mode_ok(forward_batch): _served("g1: not extend") return False sc = layer.mlp_sconv if getattr(sc, "is_dynamic", True): _served("g1: dynamic sconv") return False T = mlp.shape[0] if T < G1_MIN_ROWS or mlp.dim() != 2: _served("g1: rows < 2048") return False boundary = state.attn_res.is_block_boundary(layer.layer_id) xs = [mlp, attention] + ([] if boundary else [state.partial]) if not _bf16_rows(xs, tuple(mlp.shape)): _served("g1: dtype / layout") return False weight = sc._weight_2d() cache = sc._sconv_cache() width = weight.shape[1] if cache.ndim != 3 or tuple(cache.shape[1:]) != (width - 1, mlp.shape[1]) or weight.dim() != 2: _served("g1: cache shape") return False meta = sc._conv_state(forward_batch) sc._prepare_extend_sconv_cache(forward_batch, cache, mlp, meta.track_conv_indices) # served order: prepare, conv, update holder = []
def update(partial): out = K["sconv_residual"](mlp, weight, cache, meta.precomputed, attention, partial, use_pdl=K["pdl"]) holder.append(out) return out
from sglang.srt.models.inkling_common.kernels.sconv import update_sconv_cache # finalize_layer_with: boundary -> blocks.append(partial), partial = update(None); else partial = update(partial) state.finalize_layer_with(layer.layer_id, update) update_sconv_cache( x=mlp, sconv_cache=cache, cache_indices=meta.cache_indices, has_initial_state=meta.has_initial_state, query_start_loc=meta.query_start_loc, ) _bump(R["g1"], "boundary" if boundary else "residual") return True
def build_forward(served_src, module_globals): """Exec the patched _forward in the inkling2 module globals (helpers injected under _n86_* names).""" module_globals["_n86_g2_attention"] = _n86_g2_attention module_globals["_n86_g2_mlp"] = _n86_g2_mlp module_globals["_n86_g1"] = _n86_g1 ns = {} exec(compile(patched_forward_source(served_src), "<n86 Inkling2DecoderLayer._forward>", "exec"), module_globals, ns) return ns["_forward"]
def _check_files(): bad = [] for mod, want in IMAGE_MD5.items(): m = sys.modules.get(mod) if m is None: __import__(mod) m = sys.modules[mod] got = _md5_file(m.__file__) if got != want: bad.append(f"{mod} {got[:8]} != {want[:8]}") return bad
def _patch_layer(): """Runs at the first Inkling2Attention construction (inkling2.py has finished importing by then).""" if _STATE["patched"] or not (G1 or G2): return _STATE["patched"] = True try: bad = _check_files() if bad: _STATE["why"] = f"image files differ: {bad}" logger.warning("n86: G1 / G2 OFF (served path): %s", _STATE["why"]) return I = sys.modules["sglang.srt.models.inkling2"] src = served_forward_source(I.__file__) if src is None or hashlib.md5(src.encode()).hexdigest() != FORWARD_MD5: _STATE["why"] = "served _forward source differs" logger.warning("n86: G1 / G2 OFF (served path): %s", _STATE["why"]) return from sglang.kernels.ops.mamba import inkling2_sconv as KS if KS.PREFILL_MIN_ROWS != G1_MIN_ROWS: _STATE["why"] = f"PREFILL_MIN_ROWS {KS.PREFILL_MIN_ROWS}" logger.warning("n86: G1 / G2 OFF: %s", _STATE["why"]) return from sglang.kernels.jit.utils import is_arch_support_pdl from sglang.srt.models.inkling_common.n71_resnorm import resnorm from sglang.srt.models.inkling_common.n71_sconvres import sconv_residual K.update(sconv_residual=sconv_residual, resnorm=resnorm, pdl=bool(is_arch_support_pdl()), AttentionSources=I.AttentionSources) I.Inkling2DecoderLayer._forward = build_forward(src, I.__dict__) _STATE["why"] = "patched" logger.warning("n86: Inkling2DecoderLayer._forward patched (G1 %s, G2 %s, min rows %d, G2 shapes %d, pdl %s)", G1, G2, MIN_ROWS, len(G2_SHAPES), K["pdl"]) except Exception as ex: # fail closed _STATE["why"] = f"{type(ex).__name__}: {str(ex)[:300]}" logger.warning("n86: G1 / G2 OFF (served path) after an install error: %s", _STATE["why"])
def _n75_gate(): """Restrict n75's wrapper (installed into unquant by n75's own _prepare) to the covered (class, shape, M) on build 2.""" from sglang.srt.models.inkling_common import n75_install as X if not X.SEL: return orig = X._wrapped
def gated(x, weight, bias=None, out_dtype=None, out=None): e = X.S["reg"].get(weight.data_ptr()) if e is not None: m = x.numel() // max(1, x.shape[-1]) cls = e["cls"] why = None if e.get("frag") is None: why = "not build 2" elif cls.startswith("draft "): # S7 (n151): n80's drafter linears ('draft <leaf>', build 2 at <= 16 rows): no class / shape / M gate; if m <= 16: # > 16 rows falls to n75's own wrapper, which returns the served kernel. Packed calls counted below. _bump(R["n75"], f"{cls} M{m} packed") return orig(x, weight, bias, out_dtype, out) elif cls not in N75_CLASSES: why = "class off" elif tuple(weight.shape) != N75_SHAPES.get(cls): why = "shape off" elif m not in N75_MS: why = f"M {m} off" if m <= 16 else None # > 16 rows: n75's own wrapper returns the served kernel if why is not None: _bump(R["n75"], f"{cls} {why}") return X.S["orig"](x, weight, bias, out_dtype, out) if m in N75_MS: _bump(R["n75"], f"{cls} M{m} packed") return orig(x, weight, bias, out_dtype, out)
X._wrapped = gated logger.warning("n86: n75 gate installed: classes %s, M %s, build 2 only", sorted(N75_CLASSES), sorted(N75_MS))
def _reporter(): def run(): last = None while True: time.sleep(15) c = repr((R["g1"], R["g2"], R["n75"], R["served"])) if c != last: print(f"N86REACH g1 {R['g1']} g2 {R['g2']} n75 {R['n75']} served {R['served']} modes {R['modes']} " f"state {_STATE['why']!r} t={time.strftime('%H:%M:%S', time.gmtime())}", file=sys.stderr, flush=True) last = c
threading.Thread(target=run, daemon=True, name="n86reach").start()
def install(): if _STATE["installed"]: return _STATE["installed"] = True if G1 or G2: from sglang.srt.models.inkling_common import inkling2_attn as A cls = A.Inkling2Attention orig_init = cls.__init__
def init(self, *a, **kw): _patch_layer() orig_init(self, *a, **kw)
cls.__init__ = init if os.environ.get("N75_C12", "").strip(): _n75_gate() if G1 or G2 or os.environ.get("N75_C12", "").strip(): _reporter() logger.warning("n86 installed: G1 %s G2 %s N75_C12 %r", G1, G2, os.environ.get("N75_C12", ""))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667import jsonimport loggingimport osfrom collections.abc import Iterable
import torchfrom torch import nn
from sglang.kernels.ops.speculative.inkling2_mtp import ( mix_rmsnorm, rnn_gates, rnn_inputs,)from sglang.srt.distributed.device_communicators.vocab_gather import ( make_vocab_gather,)from sglang.srt.layers.layernorm import RMSNormfrom sglang.srt.layers.linear import QKVParallelLinearfrom sglang.srt.layers.logits_processor import should_apply_lm_head_quant_methodfrom sglang.srt.mem_cache.memory_pool import KVWriteLoc, layer_window_locsfrom sglang.srt.mem_cache.swa_memory_pool import SWAKVPoolfrom sglang.srt.model_loader.weight_utils import default_weight_loaderfrom sglang.srt.models.dflash import DFlashDraftModelfrom sglang.srt.models.dspark import ( BaseDSparkMarkovHead, DSparkDraftModel, VocabShard, gather_and_crop_vocab, project_through_lm_head,)from sglang.srt.runtime_context import get_parallel, get_platform
logger = logging.getLogger(__name__)# n3 ds-sl (inkling2-spark dspark seat, 2026-11-20): shortlist-vocab draft head. When set, the draft's base logits and its# markov step bias are computed only over the token ids listed in this JSON file and written into full-width rows whose# other columns hold _SL_FILL (base) / 0 (bias), so every consumer downstream sees the usual [.., vocab] shapes and real# token ids. Draft-only: the target verify, and so the greedy output, is untouched; off-list tokens can only be rejected._SL_PATH = os.environ.get("SGLANG_INKLING2_DRAFT_SHORTLIST") or None_SL_FILL = -1.0e4
class Inkling2MTPHead(BaseDSparkMarkovHead): def __init__(self, vocab_size, markov_rank, hidden_size, rms_norm_eps): super().__init__() self.vocab_size = vocab_size self.hidden_size = hidden_size self.markov_rank = markov_rank self.markov_w1 = nn.Embedding(vocab_size, markov_rank) self.rnn_proj = nn.Linear(2 * markov_rank + 2 * hidden_size, 3 * markov_rank) self.hidden_out = nn.Linear(markov_rank, hidden_size) self.dflare_norm = RMSNorm(hidden_size, eps=rms_norm_eps) self._fold_weight = None self._fold_bias = None self._gather_logits = None self._get_staged_f = None self._sl_ids = None
@torch.no_grad() def attach_fold(self, weight, multiplier): assert weight.ndim == 2 and weight.shape[1] == self.hidden_size self._fold_weight = weight.new_empty((weight.shape[0], self.markov_rank)) self._fold_bias = weight.new_empty((weight.shape[0],)) self.refresh_fold(weight, multiplier)
@torch.no_grad() def refresh_fold(self, weight, multiplier): assert self._fold_weight is not None and self._fold_bias is not None assert weight.shape == (self._fold_weight.shape[0], self.hidden_size) projection = self.hidden_out.weight.double() bias = self.hidden_out.bias.double() for start in range(0, weight.shape[0], 4096): rows = slice(start, min(start + 4096, weight.shape[0])) head = weight[rows].double() folded_weight, folded_bias = head @ projection, head @ bias if multiplier: folded_weight /= multiplier folded_bias /= multiplier self._fold_weight[rows].copy_(folded_weight) self._fold_bias[rows].copy_(folded_bias) if self._sl_ids is not None: self.attach_shortlist(self._sl_ids, self._sl_width)
@torch.no_grad() def attach_shortlist(self, ids, width): self._sl_ids, self._sl_width = ids, int(width) self._sl_fw = self._fold_weight.index_select(0, ids).contiguous() self._sl_fb = self._fold_bias.index_select(0, ids).contiguous()
def get_prev_embeddings(self, token_ids): return self.markov_w1(token_ids.long())
def _rnn_step(self, state, prev_tokens, hidden, f_rnn): inputs = rnn_inputs(state, prev_tokens, self.markov_w1.weight, hidden, f_rnn) return rnn_gates(self.rnn_proj(inputs), state)
def init_state(self, hidden_states): batch_size = hidden_states.shape[0] assert self._get_staged_f is not None f_rnn = self._get_staged_f() assert f_rnn is not None and f_rnn.shape[0] >= batch_size assert f_rnn.shape[1] == self.hidden_size return ( hidden_states.new_zeros(batch_size, self.markov_rank), f_rnn[:batch_size].to(hidden_states.dtype), )
def step_bias(self, prev_tokens, *, hidden_states, state): state, f_rnn = state state, latent = self._rnn_step(state, prev_tokens, hidden_states, f_rnn) if self._sl_ids is not None: part = torch.addmm(self._sl_fb, latent.to(self._sl_fw.dtype), self._sl_fw.T) bias = part.new_zeros((part.shape[0], self._sl_width)) bias.index_copy_(1, self._sl_ids, part) return bias, (state, f_rnn) assert self._fold_weight is not None and self._fold_bias is not None assert self._gather_logits is not None bias = torch.addmm( self._fold_bias, latent.to(self._fold_weight.dtype), self._fold_weight.T ) if self.vocab_shard is None: bias = self._gather_logits(bias) return bias, (state, f_rnn)
def step_logits_dtype(self, base_dtype): return torch.promote_types(base_dtype, self._fold_weight.dtype)
class Inkling2ForConditionalGenerationMTP(DSparkDraftModel): fall_back_to_pt_during_load = False allow_patterns_overrides = ["mtp.safetensors"] safetensors_index_file = None supports_pre_gather_target_hidden_projection = False supports_fused_context_kv = False folds_static_verify_commit = True
def __init__(self, config, quant_config=None, prefix=""): if quant_config is not None: raise ValueError("Inkling2 MTP requires BF16 checkpoint weights") if config.q_bias or config.o_bias: raise ValueError( "Inkling2 MTP does not support attention projection biases" ) DFlashDraftModel.__init__( self, config, quant_config=quant_config, prefix=prefix ) hidden, eps = config.hidden_size, config.rms_norm_eps self.block_size = config.block_size self.gamma = self.block_size - 1 self.sample_from_anchor = False self.num_stages = config.num_hidden_layers self.num_context_features = len(config.target_layer_ids) self.logits_mup_width_multiplier = None self.fc = self.hidden_norm = None self.lm_head = None self.confidence_head = None self.markov_head = Inkling2MTPHead( config.padded_vocab_size, config.markov_rank, hidden, eps ) self.markov_head.step_softcap = config.final_logit_softcapping or None self.markov_head.step_vocab_limit = config.unpadded_vocab_size self.fuse_weight = nn.Parameter( torch.zeros(self.num_stages + 1, self.num_context_features), requires_grad=False, ) self.mask_embed = nn.Parameter(torch.zeros(hidden), requires_grad=False) self._fuse_alpha = None self._f_rnn_rows = None self._f_rnn_buf = None self._sl_ids = None for layer_id, layer in enumerate(self.layers): attn = layer.self_attn attn.attn.window_anchor_at_start = layer_id in config.local_layer_ids attn.attn.num_splits = ( 0 if get_platform().is_sm90 or layer_id not in config.local_layer_ids else 1 ) attn.attn.pack_gqa = True attn.kv_proj_ctx = QKVParallelLinear( hidden_size=hidden, head_size=attn.head_dim, total_num_heads=0, total_num_kv_heads=attn.total_num_kv_heads, bias=False, ) attn.k_norm_ctx = RMSNorm(attn.head_dim, eps=eps) layer.dflare_norm = RMSNorm(hidden, eps=eps)
def set_block_size(self, block_size): if block_size != self.block_size: raise ValueError("Inkling2 MTP requires the checkpoint's block size")
def attach_shared_modules(self, *, embed_tokens, lm_head): if should_apply_lm_head_quant_method(lm_head, lm_head.quant_method): raise ValueError("Inkling2 MTP requires an unquantized target LM head") self.embed_tokens, self.lm_head = embed_tokens, lm_head self.markov_head.attach_fold(lm_head.weight, self.logits_mup_width_multiplier) self.markov_head._gather_logits = self._gather_logits self.markov_head._get_staged_f = lambda: self._f_rnn_rows if _SL_PATH: self._attach_shortlist(_SL_PATH) if lm_head.tp_size > 1: group = ( get_parallel().attn_tp_group if lm_head.use_attn_tp_group else get_parallel().tp_group ) assert group.world_size == lm_head.tp_size assert ( lm_head.num_embeddings_per_partition * lm_head.tp_size == lm_head.num_embeddings_padded ) self.markov_head.vocab_size = int(lm_head.org_vocab_size) shard = lm_head.shard_indices self.markov_head.vocab_shard = VocabShard( start=int(shard.org_vocab_start_index), width=int(shard.org_vocab_end_index - shard.org_vocab_start_index), gather=make_vocab_gather( group, local_width=int(lm_head.num_embeddings_per_partition), dtype=lm_head.weight.dtype, ), )
@torch.no_grad() def _attach_shortlist(self, path): if self.lm_head.tp_size > 1: raise ValueError("SGLANG_INKLING2_DRAFT_SHORTLIST supports TP1 only") with open(path) as f: ids = sorted({int(i) for i in json.load(f)}) width = int(self.lm_head.org_vocab_size) limit = self.markov_head.step_vocab_limit or width if not ids or ids[0] < 0 or ids[-1] >= min(width, limit): raise ValueError(f"shortlist ids must lie in [0, {min(width, limit)})") weight = self.lm_head.weight sl = torch.tensor(ids, dtype=torch.long, device=weight.device) self._sl_ids, self._sl_width = sl, width self._sl_w = weight.index_select(0, sl).contiguous() self.markov_head.attach_shortlist(sl, width) logger.info( "Inkling2 MTP shortlist draft head: %d of %d tokens (%s).", len(ids), width, path )
def _gather_logits(self, logits): return gather_and_crop_vocab(logits, self.lm_head)
def compute_base_logits(self, hidden): assert self.lm_head is not None if self.logits_mup_width_multiplier: hidden = hidden / self.logits_mup_width_multiplier if self._sl_ids is not None: part = torch.matmul(hidden.to(self._sl_w.dtype), self._sl_w.T) logits = part.new_full((part.shape[0], self._sl_width), _SL_FILL) logits.index_copy_(1, self._sl_ids, part) return logits, None logits = project_through_lm_head(hidden, self.lm_head) if self.markov_head.vocab_shard is None: logits = self._gather_logits(logits) return logits, None
def forward_embed(self, input_ids): assert self.embed_tokens is not None ids = input_ids.view(-1, self.block_size) hidden = ( self.mask_embed.to(self.embed_tokens.weight.dtype) .expand(ids.shape[0], self.block_size, -1) .clone() ) hidden[:, 0, :] = self.embed_tokens(ids[:, 0]).to(hidden.dtype) return hidden.view(-1, hidden.shape[-1])
def ensure_propose_staging(self, req_pool_size): if self._f_rnn_buf is None: self._f_rnn_buf = self.mask_embed.new_zeros( req_pool_size + 1, self.config.hidden_size ) elif self._f_rnn_buf.shape[0] != req_pool_size + 1: raise ValueError( "MTP request pool changed after recurrent state allocation" )
def _mix_norm(self, targets, row, norm): assert self._fuse_alpha is not None alpha = self._fuse_alpha[row].to(targets.dtype) return mix_rmsnorm(targets, alpha, norm.weight, norm.variance_epsilon)
def compute_f_rnn(self, target_hidden_last): targets = target_hidden_last.view( target_hidden_last.shape[0], self.num_context_features, self.config.hidden_size, ) return self._mix_norm(targets, -1, self.markov_head.dflare_norm)
def store_f_rnn(self, req_pool_indices, target_hidden_rows): assert self._f_rnn_buf is not None features = self.compute_f_rnn(target_hidden_rows) self._f_rnn_buf.index_copy_( 0, req_pool_indices.view(-1).long(), features.to(self._f_rnn_buf.dtype) )
def store_verify_commit( self, *, req_pool_indices, verify_hidden, commit_lens, stride, valid=None ): bs = commit_lens.shape[0] rows = torch.arange(bs, device=verify_hidden.device) last_hidden = verify_hidden.view(bs, stride, -1)[rows, commit_lens.long() - 1] indices = req_pool_indices[:bs].view(-1).long() if valid is not None: indices = torch.where(valid, indices, self._f_rnn_buf.shape[0] - 1) self.store_f_rnn(indices, last_hidden)
@torch.no_grad() def forward(self, input_ids, positions, forward_batch, input_embeds=None, **kwargs): batch_size, remainder = divmod(input_ids.numel(), self.block_size) assert remainder == 0 assert self._f_rnn_buf is not None self._f_rnn_rows = self._f_rnn_buf.index_select( 0, forward_batch.req_pool_indices.view(-1)[:batch_size].long() ) input_embeds = self.forward_embed(input_ids) return DFlashDraftModel.forward( self, input_ids, positions, forward_batch, input_embeds=input_embeds, **kwargs, )
def project_target_hidden(self, target_hidden): raise RuntimeError( "Inkling2 MTP requires a separate target mixture for every layer" )
def write_target_hidden_kv( self, *, target_hidden, pool, positions, cache_loc, cache_loc_2d=None, commit_lens=None, target_hidden_is_projected=False, swa_loc=None, ): if target_hidden_is_projected: raise ValueError("Inkling2 MTP requires unprojected target hidden states") targets = target_hidden.view( target_hidden.shape[0], self.num_context_features, self.config.hidden_size ) if swa_loc is None and isinstance(pool, SWAKVPool): # Static verify capture can supply only full-space locations. swa_loc = pool.translate_loc_from_full_to_swa(cache_loc) for i, layer in enumerate(self.layers): attn = layer.self_attn context = self._mix_norm(targets, i, layer.dflare_norm) kv, _ = attn.kv_proj_ctx(context.to(attn.kv_proj_ctx.weight.dtype)) k, v = kv.split([attn.kv_size, attn.kv_size], dim=-1) k = attn.k_norm_ctx(k.reshape(-1, attn.head_dim)).view_as(k) k = attn.apply_k_rope(positions, k) k = k.view(-1, attn.num_kv_heads, attn.head_dim) v = v.view(-1, attn.num_kv_heads, attn.head_dim) if cache_loc_2d is not None and commit_lens is not None: pool.layer_router.layer(attn.attn.layer_id).store_prefix( attn.attn, KVWriteLoc( cache_loc_2d, window_locs=layer_window_locs( pool, attn.attn.layer_id, None if swa_loc is None else swa_loc.view_as(cache_loc_2d), ), physical=True, ), commit_lens, k, v, attn.attn.k_scale, attn.attn.v_scale, ) else: pool.layer_router.layer(attn.attn.layer_id).store( attn.attn, KVWriteLoc( cache_loc, window_locs=layer_window_locs( pool, attn.attn.layer_id, swa_loc ), physical=True, ), k, v, attn.attn.k_scale, attn.attn.v_scale, )
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: params = { name: param for name, param in self.named_parameters() if not name.startswith(("embed_tokens.", "lm_head.")) } mapping = ( (".q_proj.", ".qkv_proj.", "q"), (".k_proj.", ".qkv_proj.", "k"), (".v_proj.", ".qkv_proj.", "v"), (".k_proj_ctx.", ".kv_proj_ctx.", "k"), (".v_proj_ctx.", ".kv_proj_ctx.", "v"), (".gate_proj.", ".gate_up_proj.", 0), (".up_proj.", ".gate_up_proj.", 1), ) loaded, shards = set(), {} for checkpoint_name, weight in weights: name, shard = checkpoint_name, None for source, destination, shard_id in mapping: if source in name: name, shard = name.replace(source, destination), shard_id break if name not in params: raise ValueError( f"Unrecognized MTP checkpoint tensor: {checkpoint_name}" ) param = params[name] if weight.dtype != torch.bfloat16 or param.dtype != weight.dtype: raise ValueError( f"{checkpoint_name}: MTP requires BF16 parameters and checkpoint weights" ) loader = getattr(param, "weight_loader", default_weight_loader) if shard is None: if name in loaded: raise ValueError( f"Duplicate MTP checkpoint tensor: {checkpoint_name}" ) loader(param, weight) else: if name in loaded and name not in shards: raise ValueError( f"MTP checkpoint mixes packed and unpacked tensors: {checkpoint_name}" ) pieces = shards.setdefault(name, set()) if shard in pieces: raise ValueError( f"Duplicate MTP checkpoint tensor: {checkpoint_name}" ) loader(param, weight, shard) pieces.add(shard) loaded.add(name) missing = set(params) - loaded for name, pieces in shards.items(): expected = ( {"q", "k", "v"} if ".qkv_proj." in name else {"k", "v"} if ".kv_proj_ctx." in name else {0, 1} ) if pieces != expected: missing.add(f"{name} shards {sorted(expected - pieces)}") if missing: raise ValueError(f"Missing MTP checkpoint tensors: {sorted(missing)}") fuse_alpha = torch.softmax(self.fuse_weight.float(), dim=-1).to( self.fuse_weight.dtype ) if self._fuse_alpha is None: self._fuse_alpha = fuse_alpha else: self._fuse_alpha.copy_(fuse_alpha) return loaded
EntryClass = Inkling2ForConditionalGenerationMTP
# n38 (inkling2-spark decode seat, 2026-11-21): MXFP8 W8A16 drafter dense layers (draft-only numerics: the target verifies# every draft, so outputs stay the target's greedy tokens; acceptance may move). With N38_DRAFT_W8=1, after load_weights every# BF16 linear of this draft model (qkv_proj, kv_proj_ctx, o_proj, gate_up_proj, down_proj; K % 256 == 0, no bias) gets an# e4m3 copy with power-of-2 scales per 32 K-elements (n35_w8gemv.quantize_mx8), and UnquantizedLinearMethod.apply sends calls# of <= 128 rows on such layers to n35_w8gemv.w8_gemv (n33 microbench: drafter mlp up 185 -> 100 us, down 186 -> 106 us).# Larger calls (prompt-chunk context projections) keep the BF16 path. Off when N38_DRAFT_W8 != 1: this file = 822cddb7 then.if os.environ.get("N38_DRAFT_W8") == "1": from sglang.srt.layers.linear import LinearBase as _N38LinearBase from sglang.srt.layers.quantization import unquant as _n38_unquant
_n38_orig_load = Inkling2ForConditionalGenerationMTP.load_weights _n38_orig_apply = _n38_unquant.UnquantizedLinearMethod.apply
def _n38_load_weights(self, weights): out = _n38_orig_load(self, weights) from sglang.srt.models.inkling_common.n35_w8gemv import quantize_mx8 n = tot = 0 for _, m in self.named_modules(): w = getattr(m, "weight", None) b = getattr(m, "bias", None) if (isinstance(m, _N38LinearBase) and isinstance(w, torch.Tensor) and w.dim() == 2 and w.dtype == torch.bfloat16 and w.shape[1] % 256 == 0 and (b is None or not bool(b.abs().max() > 0))): m._n38_w8 = quantize_mx8(w.data) n += 1; tot += w.numel() logger.warning("n38: drafter W8 copies for %d linears, %.0f MB FP8", n, tot / 1e6) return out
def _n38_apply(self, layer, x, bias=None, *a, **kw): q = getattr(layer, "_n38_w8", None) if (q is not None and not a and not kw and bias is None and x.dtype == torch.bfloat16 # no device sync here (graph capture) and 0 < x.numel() // x.shape[-1] <= 128): from sglang.srt.models.inkling_common.n35_w8gemv import w8_gemv return w8_gemv(x, *q) return _n38_orig_apply(self, layer, x, bias, *a, **kw)
Inkling2ForConditionalGenerationMTP.load_weights = _n38_load_weights _n38_unquant.UnquantizedLinearMethod.apply = _n38_apply logger.warning("n38: drafter W8 dispatch installed")
# n41 (inkling2-spark decode seat, 2026-11-21): context-augmented shortlist draft head (draft-only numerics; off unless# N41_CTX_SL > 0 and the shortlist is on). Per request the prompt's own off-shortlist token ids (the N41_CTX_SL most recent# distinct ones, computed once per request on CPU from req.origin_input_ids when DSparkWorkerV2.forward_batch_generation first# sees the request in its pool slot; last 128K prompt tokens) are written to a [req_pool + 1, X] table (pinned, non_blocking); the draft forward gathers the table rows of its# requests by forward_batch.req_pool_indices (inside the draft graph), compute_base_logits adds hidden @ lm_head[E]^T for those# columns and step_bias adds the folded Markov bias for them (scatter into the full-width rows the shortlist head already builds).# Empty table slots hold the first shortlist id (its column is rewritten with a value of the same dot product). n33 probe4:# 13.9 pct of sessions-eval rejections are off-shortlist targets (5.5 pct with the full-vocab head)._N41_X = int(os.environ.get("N41_CTX_SL", "0"))if _N41_X > 0 and _SL_PATH: import numpy as _n41_np
_N41 = {"model": None, "slot_rid": {}, "mask": None, "pad": None, "n": 0, "sizes": [], "patched": False} _n41_orig_staging = Inkling2ForConditionalGenerationMTP.ensure_propose_staging _n41_orig_forward = Inkling2ForConditionalGenerationMTP.forward _n41_orig_base = Inkling2ForConditionalGenerationMTP.compute_base_logits _n41_orig_bias = Inkling2MTPHead.step_bias
def _n41_staging(self, req_pool_size): _n41_orig_staging(self, req_pool_size) if getattr(self, "_n41_tab", None) is None and self._sl_ids is not None: pad = int(self._sl_ids[0]) self._n41_tab = torch.full((req_pool_size + 1, _N41_X), pad, dtype=torch.long, device=self._sl_ids.device) # pinned staging rows, one per pool slot: the H2D copy is non_blocking (a pageable copy would stall the host until # the stream drains, up to a step per new request); a slot is refilled only after its request has finished. try: self._n41_pin = torch.full((req_pool_size + 1, _N41_X), pad, dtype=torch.long).pin_memory() if torch.cuda.is_available() else None except Exception as e: # never fail the boot: fall back to a pageable copy logger.warning("n41: pinned staging unavailable (%r): pageable copies", e); self._n41_pin = None mask = _n41_np.zeros(self._sl_width, dtype=bool); mask[self._sl_ids.cpu().numpy()] = True _N41.update(model=self, mask=mask, pad=pad) _n41_patch_worker() logger.warning("n41: context shortlist table %s (X %d)", tuple(self._n41_tab.shape), _N41_X)
def _n41_forward(self, input_ids, positions, forward_batch, input_embeds=None, **kwargs): out = _n41_orig_forward(self, input_ids, positions, forward_batch, input_embeds=input_embeds, **kwargs) tab = getattr(self, "_n41_tab", None) if tab is not None and self._f_rnn_rows is not None: bs = self._f_rnn_rows.shape[0] self._n41_rows = tab.index_select(0, forward_batch.req_pool_indices.view(-1)[:bs].long()) return out
def _n41_base(self, hidden): logits, extra = _n41_orig_base(self, hidden) rows = getattr(self, "_n41_rows", None) self.markov_head._n41_ctx = None if rows is None or self._sl_ids is None or hidden.shape[0] % rows.shape[0]: return logits, extra bs, x = rows.shape; g = hidden.shape[0] // bs h = hidden / self.logits_mup_width_multiplier if self.logits_mup_width_multiplier else hidden w = self.lm_head.weight.index_select(0, rows.view(-1)).view(bs, x, -1) part = torch.bmm(h.view(bs, g, -1).to(w.dtype), w.transpose(1, 2)) logits.view(bs, g, -1).scatter_(2, rows[:, None, :].expand(bs, g, x), part.to(logits.dtype)) mh = self.markov_head mh._n41_ctx = (rows, mh._fold_weight.index_select(0, rows.view(-1)).view(bs, x, -1), mh._fold_bias.index_select(0, rows.view(-1)).view(bs, x)) return logits, extra
def _n41_bias(self, prev_tokens, *, hidden_states, state): bias, state2 = _n41_orig_bias(self, prev_tokens, hidden_states=hidden_states, state=state) ctx = getattr(self, "_n41_ctx", None) if ctx is None or self._sl_ids is None: return bias, state2 rows, fw, fb = ctx latent = self._n41_latent if latent.shape[0] != rows.shape[0]: return bias, state2 part = torch.baddbmm(fb.unsqueeze(1), latent.to(fw.dtype).unsqueeze(1), fw.transpose(1, 2)).squeeze(1) bias.scatter_(1, rows, part.to(bias.dtype)) return bias, state2
_n41_orig_rnn = Inkling2MTPHead._rnn_step
def _n41_rnn(self, state, prev_tokens, hidden, f_rnn): state, latent = _n41_orig_rnn(self, state, prev_tokens, hidden, f_rnn) self._n41_latent = latent return state, latent
def _n41_fill(reqs): m = _N41["model"] if m is None: return import time as _n41_time _t0 = _n41_time.perf_counter(); _n0 = _N41["n"] try: _n41_fill_rows(m, reqs) finally: if _N41["n"] > _n0: _N41.setdefault("host_s", 0.0); _N41["host_s"] += _n41_time.perf_counter() - _t0
def _n41_fill_rows(m, reqs): for req in reqs: kv = getattr(req, "kv", None) slot = getattr(kv, "req_pool_idx", None) if kv is not None else getattr(req, "req_pool_idx", None) if slot is None or _N41["slot_rid"].get(slot) == req.rid: continue ids = _n41_np.asarray(req.origin_input_ids[-131072:], dtype=_n41_np.int64) # bound host work per request ids = ids[(ids >= 0) & (ids < len(_N41["mask"]))] off = ids[~_N41["mask"][ids]][::-1] uniq, first = _n41_np.unique(off, return_index=True) recent = uniq[_n41_np.argsort(first)][:_N41_X] row = _n41_np.full(_N41_X, _N41["pad"], dtype=_n41_np.int64); row[: len(recent)] = recent if m._n41_pin is not None: m._n41_pin[slot].copy_(torch.from_numpy(row)) m._n41_tab[slot].copy_(m._n41_pin[slot], non_blocking=True) else: m._n41_tab[slot].copy_(torch.from_numpy(row)) _N41["slot_rid"][slot] = req.rid; _N41["n"] += 1; _N41["sizes"].append(len(uniq)) if _N41["n"] in (1, 10, 32, 50) or _N41["n"] % 64 == 0: s = sorted(_N41["sizes"]) logger.warning("n41: %d requests filled; distinct off-shortlist context ids median %d p90 %d max %d (X %d); host fill %.1f ms per request", _N41["n"], s[len(s) // 2], s[int(0.9 * (len(s) - 1))], s[-1], _N41_X, 1000 * _N41.get("host_s", 0.0) / max(1, _N41["n"] - 1))
def _n41_patch_worker(): if _N41["patched"]: return import sys as _sys mod = _sys.modules.get("sglang.srt.speculative.dspark_components.dspark_worker_v2") cls = getattr(mod, "DSparkWorkerV2", None) if mod is not None else None if cls is None: logger.warning("n41: DSparkWorkerV2 not loaded: context table stays empty") return orig = cls.forward_batch_generation
def forward_batch_generation(self, batch, *a, **kw): try: _n41_fill(getattr(batch, "reqs", ()) or ()) except Exception as e: # never break serving: the table just stays as it is logger.warning("n41: fill failed: %r", e) return orig(self, batch, *a, **kw)
cls.forward_batch_generation = forward_batch_generation _N41["patched"] = True logger.warning("n41: DSparkWorkerV2.forward_batch_generation hook installed")
Inkling2ForConditionalGenerationMTP.ensure_propose_staging = _n41_staging Inkling2ForConditionalGenerationMTP.forward = _n41_forward Inkling2ForConditionalGenerationMTP.compute_base_logits = _n41_base Inkling2MTPHead.step_bias = _n41_bias Inkling2MTPHead._rnn_step = _n41_rnn logger.warning("n41: context-augmented shortlist installed (X %d)", _N41_X)
# n105 (inkling2-spark rnnhoist seat, 2026-11-23): exact bitwise hoisted Markov RNN projection on bs=1 draft walk# (CERT90: precompute W_f + W_h once in init_state with TwoSum-FP32 + Higham/Rump interval certificate, read only W_s# per step with inline exact stride-16 fixup on ~7 pct tripped rows; bs != 1 keeps served _rnn_step). Off unless# N105_RNNHOIST=1 (off = S3 ff39c84d verbatim). Pointer-offset walk-step recovery adapts MIT code from# knapcio/Inkling-2-Mini-1x-DGX-Spark (Copyright (c) 2026 Zbigniew Majewski, MIT License).if os.environ.get("N105_RNNHOIST") == "1": import sys as _n105_sys from sglang.srt.models.inkling_common import n105_rnnhoist as _n105_mod _n105_mod.install(_n105_sys.modules[__name__])
12345678910111213#!/usr/bin/env bash# Mix-guard (dflash; the RULE in work_dflash/PICKUP.md, SUPERVISOR 17:0xZ): a derived drafter mix loads only with BOTH its own sha256# and the sha256 of the base drafter model.safetensors it was built from pinned and matching. serve.sh runs this inside the container# before launch_server (once; never in sitecustomize, which every Python process runs). Refusal exits 78 with one fixed line.# bash mixpin.sh MIX_FILE MIX_SHA256 BASE_MODEL_FILE BASE_SHA256set -uo pipefailmix=$1; mix_sha=$2; base=$3; base_sha=$4[[ $mix_sha =~ ^[0-9a-f]{64}$ && $base_sha =~ ^[0-9a-f]{64}$ ]] || { echo "[mixpin] REFUSED: both pins must be 64-hex sha256" >&2; exit 78; }got_base=$(sha256sum < "$base" | cut -c1-64) || { echo "[mixpin] REFUSED: base drafter unreadable" >&2; exit 78; }[[ $got_base == "$base_sha" ]] || { echo "[mixpin] REFUSED: base drafter ${got_base:0:8} != pinned ${base_sha:0:8} (this mix was not built from this drafter)" >&2; exit 78; }got_mix=$(sha256sum < "$mix" | cut -c1-64) || { echo "[mixpin] REFUSED: mix unreadable" >&2; exit 78; }[[ $got_mix == "$mix_sha" ]] || { echo "[mixpin] REFUSED: mix ${got_mix:0:8} != pinned ${mix_sha:0:8}" >&2; exit 78; }echo "[mixpin] mix ${got_mix:0:8} on base drafter ${got_base:0:8}: pins match"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189#!/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.# n391-a (dflash, 2026-11-28; tree n391 / program B1) = S3b-p's serve.sh with a GENERAL DFlash2-family drafter gate: DRAFT_DIR# (required) holds config.json + model.safetensors + SHA256SUMS listing exactly its files (all checked in the container);# the stock Inkling integration script (incoai sglang_inkling_dflash2.py, sha 14223ae2) is mounted from DFLASH2_SCRIPT by sha;# SGLANG_ENABLE_DFLASH_DRAFT_KV_RING = 1 iff every config.json layer_types entry is sliding_attention (stock refuses the ring# for a mixed drafter), else 0. Nothing else changes.# n391-b form recipe (dflash; the mix-guard RULE in work_dflash/PICKUP.md) = n391-a's serve.sh + an optional DERIVED MIX: MIX_DIR (a dir# holding Inkling-2-Mini-DFlash2-mix.safetensors) loads only with MIX_SHA256 (the mix) AND MIX_BASE_SHA256 (the base drafter# model.safetensors it was built from) both pinned and matching (mixpin.sh, run here once before docker; refusal exit 78); it is then# mounted read-only at /draft-mix and INKLING_DFLASH_MIX_PATH set; MIX_DIR/BUILT_FROM (written by the rebuild)# must name MIX_BASE_SHA256 (provenance: a mix pinned beside a base it was not built from refuses). Without MIX_DIR no mix is mounted or named (= n391-a).# n2-proj1 (inkling2-spark prefill seat, 2026-11-20): the champion + per-source qkvr projection on 3-source attention visits (loop# passes 2-3 and the global layers) at >= 512 tokens. The image stacks the three sources (3T rows) through the full 8,600-column# qkvr weight and keeps a third of each output; here each source multiplies only the weight rows it uses (q/r/gate/sinks from# q's source, k from k's, v from v's), F.linear on row slices of the same weight, the same cuBLAS path. Bitwise identical# outputs (n2-probe1: logprobs and KLD equal to the digit). One file mounted over the image: ../patch/inkling2_attn.py (image# file md5 b6d57038 + a guarded branch in _project_sources, switch SGLANG_INKLING_SPLIT_PROJ). Knob added: INK_PROJ_SPLIT# (default 1; 0 = the patched file with the branch off).# n21-bs1 (inkling2-spark attn-global seat, 2026-11-21): n17-slp1 + n13-bs1's global-layer band-split FA4 SM120 prefill kernel# (FlashAttentionForwardSm120BandSplit, bitwise equal to the image kernel). Adds the same two mounted files as n13-bs1# (../patch/n13_fwd.py at fa4_sm120/n13_fwd.py, ../patch/n13_attn_global.py) and n13-bs1's patch/inkling2_attn.py# (n17-slp1's = n2-proj1's file + 2 lines installing the hook). Replaces only FlashAttentionForwardSm120.mma for# has_bias, not is_local, not pack_gqa kernels; the draft head files (serve/inkling2_mtp.py, sl.json) are n17-slp1's.# n32-ikb2 (inkling2-spark attn-bias seat, 2026-11-21): n32-ikb1 + the same in-kernel bias producer on the GLOBAL layers too:# n13's band-split kernel (its consumer mma and unswizzled bias tile, n13_fwd.py unchanged) is built as# FlashAttentionForwardSm120BandSplitRelProd (n32_fwd.py generated with N32_GLOBAL = 1), so the global einsum + ShearingBias# are not run either. This touches n13's global path (supervisor ruling 2026-11-21: n13 unseated, attn-bias owns the change).# Knob added: INK_N32_GLOBAL (default 1; 0 = sliding-only, = n32-ikb1's behaviour under this recipe's kernel file).# n32-ikb1 (inkling2-spark attn-bias seat, 2026-11-21): n21-bs1 + the sliding-layer prefill rel bias computed inside the FA4 SM120# kernel (FlashAttentionForwardSm120RelProd: the DMA warp builds each sheared bias tile with mma.sync m16n8k16 + RTNE, bitwise# equal to the served einsum + ShearingBias + FA4 path in work_attnbias mb1). Adds ../patch/n32_fwd.py at fa4_sm120/n32_fwd.py# (its own FA4 AOT fingerprint) and ../patch/n32_attn_local.py, and ../patch/inkling2_attn.py = n21's file + the guarded rel_bias# line + the hook install. Knobs added: INK_N32 (default 1; 0 = served bias path, same mounted files), ADMIN=1# (--admin-api-key API_KEY, for /start_profile), EXTRA_DOCKER (extra docker run options, e.g. -v .../prof:/prof).# n14x37 (inkling2-spark moe seat, 2026-11-22; composition owned by the moe seat per the supervisor's ruling): decode's# cands/n41-k2 recipe (n48's ikb2 attention files untouched + n35 / n37 / n38 / n41 decode files) + n14's exact SM120 MoE prefill# visit (../patch/n14_moe.py f9435cd7 + ../patch/n14_quant.cuh afdcb38b, calls >= 512 tokens; n37 only touches <= 128-token# tiles, so the two never meet). ../patch/inkling2_attn.py = n41-k2's 1579708b + the n14 install block. Knob N14_MOE (default qc;# empty = the image MoE path). Manifests: work_moe/n14x37.py (x37 knobs) and work_moe/n14n37.py (exact: n14 + n37 only).# n54 (inkling2-spark stack seat, 2026-11-22): n51's recipe (cands/n14x37 = n48 + n14 qc + n37, run with the n14n37 ENV) + n50's# exact fused loop controller: ../patch/inkling2_loop.py (image kernels/ops/elementwise/inkling2_loop.py caaaefb4 + the n50# dispatch) and ../patch/n15_fused.py (the fused kernel, build 4 380adeee), both mounted over / beside the image module.# Knobs N50 (default 1 = prefill-size calls run the fused kernel; 0 = the served kernels with the same files; check = served +# fused + a failing control, returns the fused output, mismatch counter in pinned host memory printed as N50CHECK lines) and# N50_MIN (default 1000 tokens; decode / verify sizes always take the served kernels).# n75 (inkling2-spark packed seat, 2026-11-22): n54 + exact 12-bit packed BF16 weights on the served small-M GEMV route:# ../patch/n75_install.py + ../patch/n75_c12.py mounted beside the image modules; ../patch/inkling2_attn.py = n54's 1e3a8cae + the# n75 install block. Knobs N75_C12 (attn = qkvr + wo_ud, lm = LM head; default empty = off, the n54 code path), N75_C12_CHECK# (1 = served + packed + a failing control per call, returns the packed output, N75CHECK lines), N75_C12_CFG (BN,warps,stages),# N75_C12_KERNEL (triton | cuda | per class 'qkvr=cuda,...': build 1 / build 2 (../patch/n75_cuda.py), same output bits),# N75_C12_CUDA_NW (warps per CTA of build 2, one value or per class).# n86 S1 (inkling2-spark stack seat, 2026-11-23): n54 + n71 riders G1 / G2 + the n75 build-2 rider (RULE n86 S1): ../patch/n86_riders.py,# ../patch/n71_sconvres.py (09d3d221) and ../patch/n71_resnorm.py (d1054a4c) mounted beside the image modules; ../patch/inkling2_attn.py# = n75's 8771c89c + the n86 install block. Knobs N86_G1 / N86_G2 (1 = on; default 0 = the n54 code path), N86_MIN_ROWS (G2 rows# gate, default 2048), N86_G2_SHAPES (fused G2 shapes), N86_N75_MS (packed GEMV rows, default 8,16), N86_N75_CLASSES.# n64-p1 (inkling2-spark attn seat, 2026-11-22): n54 + n64's exact two-kernel global-layer prefill attention: kernel A# (../patch/n64a_fwd.py at fa4_sm120/n64a_fwd.py: n54's band part, state store) + kernel B (../patch/n64b_fwd.py: 8 consumer# warps under setmaxnreg on the far blocks, n54's far math, served finalize) via ../patch/n64_attn_global.py (installed# after n32's hook in ../patch/inkling2_attn.py). Knobs N64 (default 1; 0 = n54's path with the same files), N64_MIN_K# (KV span bound below which a call keeps n54's path; default 0), N64_PREALLOC (heads of the install-time workspace, 24).# n78 certified greedy LM head, S8 (inkling2-spark packed seat, 2026-11-23; recipe cands/<name> = cp -a cands/n54 + these files):# n54 + ../patch/n78_head.py + ../patch/n78_kern.py mounted beside the image modules; ../patch/inkling2_attn.py = n54's 1e3a8cae# + the n78 install block. Knobs N78_CERT (1 = bs-1 / bs-2 target-verify LM-head calls on all-greedy plain steps run the INT8# screen + bound + served-body exact tiles, +474 MB; every other step and call runs the full served head; default empty = off,# n54's path exactly) and N78_CHECK (1 = CHECK BOOT ONLY: the served head also runs in-graph and N78CHECK counters are printed).# n126 S4 (inkling2-spark stack seat, 2026-11-24): S3 (cands/n86-s3) + three exact riders, each off by its knob except a4 (a file):# n115 a4 = ../patch/n32_fwd.py 7e0b8ca9 (S3's 115d2333 + the full-block consumer-built sliding bias; smaller blocks keep the served# DMA producer); n124 F2b = ../patch/n52_moe.py c614ad75 + ../patch/n52_band.cuh e855abc8 (chunked NVFP4 gate_up GEMM, TB 16 bands,# + the lean L2 swiglu-NVFP4 pass on NVFP4 MoE prefill calls >= 3,073 tokens; installed after n14 by ../patch/inkling2_attn.py =# S3's c8bd1ccc + the n52 install block) with knobs N52_BAND (2 = on, default 0 = S3's MoE path), N52_FORM (f2), N52_TB (16),# N52_LEAN (1), N52_RASTER (0; the f2 path forces AlongM); n105 build 3 = ../patch/n105_rnnhoist.py 4f3d50fa + serve/inkling2_mtp.py# f68b1967 (S3's ff39c84d + the env-gated install) with knobs N105_RNNHOIST (1 = on, default empty = S3's drafter verbatim),# N105_MODE, N105_PRE_NW, N105_STEP_NW, N105_CHECK (1 = CHECK BOOT ONLY: served RNN step + a failing control beside each hoisted step).# n419b (dflash, SUPERVISOR 07:3xZ 11-29, no-op cleanup in this NEW recipe only): the three DSpark-only envs# SGLANG_OPT_DSV41_DSPARK_{MID_FOLD,PREPARE_INPUTS_ONCE,SKIP_PREFILLED_INPUTS} are dropped; each is read only on the DSpark path# (dspark_draft_sampler.py, dspark_worker_v2.py / dspark_planner.py, decode_cuda_graph_runner.py:2083-2086 gated on is_dspark()).set -eu# n41-k2 (inkling2-spark decode seat, 2026-11-21): n39-k2 (ikb2-rebased) + n41: serve/inkling2_mtp.py = the n41 file (n17 822cddb7 + the n38 block# + the env-gated n41 context-augmented shortlist: the most recent N41_CTX_SL distinct off-shortlist prompt token ids per request# join the 32K draft shortlist; draft-only). Knob N41_CTX_SL (default 4096; 0 = n39-dec's drafter exactly).# n39-k2 (inkling2-spark decode seat, 2026-11-21): n32-ikb2 + the n39-dec decode stack, rebased for the case that ikb2 ships:# n35 (patch/n35_w8.py + patch/n35_w8gemv.py: MXFP8 W8A16 qkvr / wo_ud on decode / verify only, knob N35_W8 attn | empty),# n37 (patch/n37_tiles.py: NVFP4 grouped-GEMM decode tile_k N37_TILE_K, default 256, bitwise equal to the image config),# n38 (serve/inkling2_mtp.py = the n17 file 822cddb7 + an env-gated block: W8 drafter linears when N38_DRAFT_W8=1, default 1).# patch/inkling2_attn.py = ikb2's c1889915 + the n35 and n37 install blocks appended. Empty / 128 / 0 = ikb2 exactly.INK_N32=${INK_N32:-1}INK_N32_GLOBAL=${INK_N32_GLOBAL:-1}EXTRA_DOCKER=${EXTRA_DOCKER:-}ADMIN=${ADMIN:-0}; ADMIN_ARGS=(); [ "$ADMIN" = 1 ] && ADMIN_ARGS=(--admin-api-key "$API_KEY")# n17 (dspark seat, 2026-11-21, staged): n2-proj1 + ds-sl32. Adds the ds-sl32 shortlist-vocab DSpark draft head: serve/inkling2_mtp.py# (image md5 35e23e4a + env-gated shortlist, md5 822cddb7) and serve/sl.json (32,768 ids, md5 389d362c), mounted only with SPEC=1.HERE=$(cd "$(dirname "$0")/.." && pwd)SDIR=$(cd "$(dirname "$0")" && pwd)INK_PROJ_SPLIT=${INK_PROJ_SPLIT:-1}N14_MOE=${N14_MOE-qc}KJ=/sgl-workspace/sglang/python/sglang/kernels/jit/csrc/inkling2N75_C12=${N75_C12:-}; N75_C12_CHECK=${N75_C12_CHECK:-0}; N75_C12_CFG=${N75_C12_CFG:-}N75_C12_KERNEL=${N75_C12_KERNEL:-}; N75_C12_CUDA_NW=${N75_C12_CUDA_NW:-}N86_G1=${N86_G1:-0}; N86_G2=${N86_G2:-0}; N86_MIN_ROWS=${N86_MIN_ROWS:-2048}; N86_G2_SHAPES=${N86_G2_SHAPES:-}N86_N75_MS=${N86_N75_MS:-8,16}; N86_N75_CLASSES=${N86_N75_CLASSES:-qkvr,wo_ud,lm_head}N78_CERT=${N78_CERT:-}; N78_CHECK=${N78_CHECK:-}N35_W8=${N35_W8-attn}N37_TILE_K=${N37_TILE_K:-256}N38_DRAFT_W8=${N38_DRAFT_W8:-1}N41_CTX_SL=${N41_CTX_SL:-4096}N50=${N50:-1}; N50_MIN=${N50_MIN:-1000}N64=${N64:-1}; N64_MIN_K=${N64_MIN_K:-0}; N64_PREALLOC=${N64_PREALLOC:-24}N52_BAND=${N52_BAND:-0}; N52_FORM=${N52_FORM:-f2}; N52_TB=${N52_TB:-16}; N52_LEAN=${N52_LEAN:-1}; N52_RASTER=${N52_RASTER:-0}N105_RNNHOIST=${N105_RNNHOIST:-}; N105_MODE=${N105_MODE:-}; N105_PRE_NW=${N105_PRE_NW:-}; N105_STEP_NW=${N105_STEP_NW:-}; N105_CHECK=${N105_CHECK:-}KO=/sgl-workspace/sglang/python/sglang/kernels/ops/elementwiseMDL=/sgl-workspace/sglang/python/sglang/srt/models/inkling_common: "${NAME:?}" "${PORT:?}" "${IMAGE:?}" # standing copy: API_KEY optional (serve.sh.orig requires it)MODEL_DIR=${MODEL_DIR:-/workspace/models/Inkling-2-Mini}; MEM=${MEM:-0.45}; CTX=${CTX:-262144}SPEC=${SPEC:-1}; NUM_DRAFT=${NUM_DRAFT:-8}; CACHE_DIR=${CACHE_DIR:-/workspace/eat-inkling/cache/sglang}; SERVED=${SERVED:-inkling-2-mini}EXTRA_ARGS=${EXTRA_ARGS:-}FA=/sgl-workspace/sglang/python/sglang/kernels/ops/attention/fa4_sm120mkdir -p "$CACHE_DIR"[ "$SPEC" = dflash2 ] || { echo "n292 requires SPEC=dflash2" >&2; exit 2; }DRAFT_DIR=${DRAFT_DIR:?DRAFT_DIR: a DFlash2-family drafter dir with SHA256SUMS}DFLASH2_SCRIPT=${DFLASH2_SCRIPT:-/workspace/eat-inkling/drafters/dflash2-4f9088ea/sglang_inkling_dflash2.py}[ -f "$DRAFT_DIR/model.safetensors" ] && [ -f "$DRAFT_DIR/config.json" ] && [ -f "$DRAFT_DIR/SHA256SUMS" ] || { echo "no DFlash2-family drafter at $DRAFT_DIR" >&2; exit 1; }# n419b: plain-text docs (LICENSE, NOTICE, README.md, MD5SUMS) may sit uncovered in the drafter dir (the lane's copies list only# config.json + model.safetensors); every other file must be listed, and the listed files are sha256-checked in the container belowdocs='LICENSE|NOTICE|README\.md|MD5SUMS'listed=$(awk '{print $2}' "$DRAFT_DIR/SHA256SUMS" | grep -vxE "$docs" | sort); present=$(cd "$DRAFT_DIR" && ls -A | grep -vxE "SHA256SUMS|$docs" | sort)[ "$listed" = "$present" ] && grep -q ' config\.json$' "$DRAFT_DIR/SHA256SUMS" && grep -q ' model\.safetensors$' "$DRAFT_DIR/SHA256SUMS" || { echo "files in $DRAFT_DIR differ from its SHA256SUMS" >&2; exit 1; }printf '%s %s\n' 14223ae2f3aa1d661da67cf0143ec33070d952a6e28a119e6cec64fcc0bebe50 "$DFLASH2_SCRIPT" | sha256sum -c --quiet - || { echo "integration script $DFLASH2_SCRIPT is not 14223ae2" >&2; exit 1; }DFLASH2_SHA256=$(awk '{print $1" "$2}' "$DRAFT_DIR/SHA256SUMS")MIX_ARGS=()if [ -n "${MIX_DIR:-}" ]; then [ "$(cat "$MIX_DIR/BUILT_FROM" 2>/dev/null)" = "${MIX_BASE_SHA256:-}" ] || { echo "[mixpin] REFUSED: $MIX_DIR/BUILT_FROM does not name the pinned base drafter (provenance: written by the rebuild)" >&2; exit 78; } bash "$HERE/serve/mixpin.sh" "$MIX_DIR/Inkling-2-Mini-DFlash2-mix.safetensors" "${MIX_SHA256:-}" "$DRAFT_DIR/model.safetensors" "${MIX_BASE_SHA256:-}" || exit 78 MIX_ARGS=(-v "$MIX_DIR":/draft-mix:ro -e INKLING_DFLASH_MIX_PATH=/draft-mix/Inkling-2-Mini-DFlash2-mix.safetensors)fiRING=$(python3 -I -c 'import json, sys; t = json.load(open(sys.argv[1])).get("layer_types") or []; print(1 if t and all(x == "sliding_attention" for x in t) else 0)' "$DRAFT_DIR/config.json") || { echo "unreadable $DRAFT_DIR/config.json" >&2; exit 1; }docker rm -f "$NAME" > /dev/null 2>&1 || true# shellcheck disable=SC2086exec docker run --pull=never -d --name "$NAME" --gpus all --ipc=host --shm-size 32g \ -p ${BIND:-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 MALLOC_MMAP_THRESHOLD_=1048576 \ -e SGLANG_ENABLE_DFLASH_DRAFT_KV_RING="$RING" -e DFLASH2_SHA256="$DFLASH2_SHA256" -v "$DRAFT_DIR":/draft:ro \ -v "$DFLASH2_SCRIPT":/draft-script/sglang_inkling_dflash2.py:ro "${MIX_ARGS[@]}" \ --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; } echo "[n391-serve] DFLASH draft KV ring env $SGLANG_ENABLE_DFLASH_DRAFT_KV_RING (1 iff every draft layer is sliding_attention)" python3 -I /draft-script/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 "$API_KEY"} --weight-loader-disable-mmap --swa-full-tokens-ratio 0.037 \ --max-mamba-cache-size 512 --max-prefill-tokens 8192 $EXTRA_ARGS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189#!/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.# n391-a (dflash, 2026-11-28; tree n391 / program B1) = S3b-p's serve.sh with a GENERAL DFlash2-family drafter gate: DRAFT_DIR# (required) holds config.json + model.safetensors + SHA256SUMS listing exactly its files (all checked in the container);# the stock Inkling integration script (incoai sglang_inkling_dflash2.py, sha 14223ae2) is mounted from DFLASH2_SCRIPT by sha;# SGLANG_ENABLE_DFLASH_DRAFT_KV_RING = 1 iff every config.json layer_types entry is sliding_attention (stock refuses the ring# for a mixed drafter), else 0. Nothing else changes.# n391-b form recipe (dflash; the mix-guard RULE in work_dflash/PICKUP.md) = n391-a's serve.sh + an optional DERIVED MIX: MIX_DIR (a dir# holding Inkling-2-Mini-DFlash2-mix.safetensors) loads only with MIX_SHA256 (the mix) AND MIX_BASE_SHA256 (the base drafter# model.safetensors it was built from) both pinned and matching (mixpin.sh, run here once before docker; refusal exit 78); it is then# mounted read-only at /draft-mix and INKLING_DFLASH_MIX_PATH set; MIX_DIR/BUILT_FROM (written by the rebuild)# must name MIX_BASE_SHA256 (provenance: a mix pinned beside a base it was not built from refuses). Without MIX_DIR no mix is mounted or named (= n391-a).# n2-proj1 (inkling2-spark prefill seat, 2026-11-20): the champion + per-source qkvr projection on 3-source attention visits (loop# passes 2-3 and the global layers) at >= 512 tokens. The image stacks the three sources (3T rows) through the full 8,600-column# qkvr weight and keeps a third of each output; here each source multiplies only the weight rows it uses (q/r/gate/sinks from# q's source, k from k's, v from v's), F.linear on row slices of the same weight, the same cuBLAS path. Bitwise identical# outputs (n2-probe1: logprobs and KLD equal to the digit). One file mounted over the image: ../patch/inkling2_attn.py (image# file md5 b6d57038 + a guarded branch in _project_sources, switch SGLANG_INKLING_SPLIT_PROJ). Knob added: INK_PROJ_SPLIT# (default 1; 0 = the patched file with the branch off).# n21-bs1 (inkling2-spark attn-global seat, 2026-11-21): n17-slp1 + n13-bs1's global-layer band-split FA4 SM120 prefill kernel# (FlashAttentionForwardSm120BandSplit, bitwise equal to the image kernel). Adds the same two mounted files as n13-bs1# (../patch/n13_fwd.py at fa4_sm120/n13_fwd.py, ../patch/n13_attn_global.py) and n13-bs1's patch/inkling2_attn.py# (n17-slp1's = n2-proj1's file + 2 lines installing the hook). Replaces only FlashAttentionForwardSm120.mma for# has_bias, not is_local, not pack_gqa kernels; the draft head files (serve/inkling2_mtp.py, sl.json) are n17-slp1's.# n32-ikb2 (inkling2-spark attn-bias seat, 2026-11-21): n32-ikb1 + the same in-kernel bias producer on the GLOBAL layers too:# n13's band-split kernel (its consumer mma and unswizzled bias tile, n13_fwd.py unchanged) is built as# FlashAttentionForwardSm120BandSplitRelProd (n32_fwd.py generated with N32_GLOBAL = 1), so the global einsum + ShearingBias# are not run either. This touches n13's global path (supervisor ruling 2026-11-21: n13 unseated, attn-bias owns the change).# Knob added: INK_N32_GLOBAL (default 1; 0 = sliding-only, = n32-ikb1's behaviour under this recipe's kernel file).# n32-ikb1 (inkling2-spark attn-bias seat, 2026-11-21): n21-bs1 + the sliding-layer prefill rel bias computed inside the FA4 SM120# kernel (FlashAttentionForwardSm120RelProd: the DMA warp builds each sheared bias tile with mma.sync m16n8k16 + RTNE, bitwise# equal to the served einsum + ShearingBias + FA4 path in work_attnbias mb1). Adds ../patch/n32_fwd.py at fa4_sm120/n32_fwd.py# (its own FA4 AOT fingerprint) and ../patch/n32_attn_local.py, and ../patch/inkling2_attn.py = n21's file + the guarded rel_bias# line + the hook install. Knobs added: INK_N32 (default 1; 0 = served bias path, same mounted files), ADMIN=1# (--admin-api-key API_KEY, for /start_profile), EXTRA_DOCKER (extra docker run options, e.g. -v .../prof:/prof).# n14x37 (inkling2-spark moe seat, 2026-11-22; composition owned by the moe seat per the supervisor's ruling): decode's# cands/n41-k2 recipe (n48's ikb2 attention files untouched + n35 / n37 / n38 / n41 decode files) + n14's exact SM120 MoE prefill# visit (../patch/n14_moe.py f9435cd7 + ../patch/n14_quant.cuh afdcb38b, calls >= 512 tokens; n37 only touches <= 128-token# tiles, so the two never meet). ../patch/inkling2_attn.py = n41-k2's 1579708b + the n14 install block. Knob N14_MOE (default qc;# empty = the image MoE path). Manifests: work_moe/n14x37.py (x37 knobs) and work_moe/n14n37.py (exact: n14 + n37 only).# n54 (inkling2-spark stack seat, 2026-11-22): n51's recipe (cands/n14x37 = n48 + n14 qc + n37, run with the n14n37 ENV) + n50's# exact fused loop controller: ../patch/inkling2_loop.py (image kernels/ops/elementwise/inkling2_loop.py caaaefb4 + the n50# dispatch) and ../patch/n15_fused.py (the fused kernel, build 4 380adeee), both mounted over / beside the image module.# Knobs N50 (default 1 = prefill-size calls run the fused kernel; 0 = the served kernels with the same files; check = served +# fused + a failing control, returns the fused output, mismatch counter in pinned host memory printed as N50CHECK lines) and# N50_MIN (default 1000 tokens; decode / verify sizes always take the served kernels).# n75 (inkling2-spark packed seat, 2026-11-22): n54 + exact 12-bit packed BF16 weights on the served small-M GEMV route:# ../patch/n75_install.py + ../patch/n75_c12.py mounted beside the image modules; ../patch/inkling2_attn.py = n54's 1e3a8cae + the# n75 install block. Knobs N75_C12 (attn = qkvr + wo_ud, lm = LM head; default empty = off, the n54 code path), N75_C12_CHECK# (1 = served + packed + a failing control per call, returns the packed output, N75CHECK lines), N75_C12_CFG (BN,warps,stages),# N75_C12_KERNEL (triton | cuda | per class 'qkvr=cuda,...': build 1 / build 2 (../patch/n75_cuda.py), same output bits),# N75_C12_CUDA_NW (warps per CTA of build 2, one value or per class).# n86 S1 (inkling2-spark stack seat, 2026-11-23): n54 + n71 riders G1 / G2 + the n75 build-2 rider (RULE n86 S1): ../patch/n86_riders.py,# ../patch/n71_sconvres.py (09d3d221) and ../patch/n71_resnorm.py (d1054a4c) mounted beside the image modules; ../patch/inkling2_attn.py# = n75's 8771c89c + the n86 install block. Knobs N86_G1 / N86_G2 (1 = on; default 0 = the n54 code path), N86_MIN_ROWS (G2 rows# gate, default 2048), N86_G2_SHAPES (fused G2 shapes), N86_N75_MS (packed GEMV rows, default 8,16), N86_N75_CLASSES.# n64-p1 (inkling2-spark attn seat, 2026-11-22): n54 + n64's exact two-kernel global-layer prefill attention: kernel A# (../patch/n64a_fwd.py at fa4_sm120/n64a_fwd.py: n54's band part, state store) + kernel B (../patch/n64b_fwd.py: 8 consumer# warps under setmaxnreg on the far blocks, n54's far math, served finalize) via ../patch/n64_attn_global.py (installed# after n32's hook in ../patch/inkling2_attn.py). Knobs N64 (default 1; 0 = n54's path with the same files), N64_MIN_K# (KV span bound below which a call keeps n54's path; default 0), N64_PREALLOC (heads of the install-time workspace, 24).# n78 certified greedy LM head, S8 (inkling2-spark packed seat, 2026-11-23; recipe cands/<name> = cp -a cands/n54 + these files):# n54 + ../patch/n78_head.py + ../patch/n78_kern.py mounted beside the image modules; ../patch/inkling2_attn.py = n54's 1e3a8cae# + the n78 install block. Knobs N78_CERT (1 = bs-1 / bs-2 target-verify LM-head calls on all-greedy plain steps run the INT8# screen + bound + served-body exact tiles, +474 MB; every other step and call runs the full served head; default empty = off,# n54's path exactly) and N78_CHECK (1 = CHECK BOOT ONLY: the served head also runs in-graph and N78CHECK counters are printed).# n126 S4 (inkling2-spark stack seat, 2026-11-24): S3 (cands/n86-s3) + three exact riders, each off by its knob except a4 (a file):# n115 a4 = ../patch/n32_fwd.py 7e0b8ca9 (S3's 115d2333 + the full-block consumer-built sliding bias; smaller blocks keep the served# DMA producer); n124 F2b = ../patch/n52_moe.py c614ad75 + ../patch/n52_band.cuh e855abc8 (chunked NVFP4 gate_up GEMM, TB 16 bands,# + the lean L2 swiglu-NVFP4 pass on NVFP4 MoE prefill calls >= 3,073 tokens; installed after n14 by ../patch/inkling2_attn.py =# S3's c8bd1ccc + the n52 install block) with knobs N52_BAND (2 = on, default 0 = S3's MoE path), N52_FORM (f2), N52_TB (16),# N52_LEAN (1), N52_RASTER (0; the f2 path forces AlongM); n105 build 3 = ../patch/n105_rnnhoist.py 4f3d50fa + serve/inkling2_mtp.py# f68b1967 (S3's ff39c84d + the env-gated install) with knobs N105_RNNHOIST (1 = on, default empty = S3's drafter verbatim),# N105_MODE, N105_PRE_NW, N105_STEP_NW, N105_CHECK (1 = CHECK BOOT ONLY: served RNN step + a failing control beside each hoisted step).# n419b (dflash, SUPERVISOR 07:3xZ 11-29, no-op cleanup in this NEW recipe only): the three DSpark-only envs# SGLANG_OPT_DSV41_DSPARK_{MID_FOLD,PREPARE_INPUTS_ONCE,SKIP_PREFILLED_INPUTS} are dropped; each is read only on the DSpark path# (dspark_draft_sampler.py, dspark_worker_v2.py / dspark_planner.py, decode_cuda_graph_runner.py:2083-2086 gated on is_dspark()).set -eu# n41-k2 (inkling2-spark decode seat, 2026-11-21): n39-k2 (ikb2-rebased) + n41: serve/inkling2_mtp.py = the n41 file (n17 822cddb7 + the n38 block# + the env-gated n41 context-augmented shortlist: the most recent N41_CTX_SL distinct off-shortlist prompt token ids per request# join the 32K draft shortlist; draft-only). Knob N41_CTX_SL (default 4096; 0 = n39-dec's drafter exactly).# n39-k2 (inkling2-spark decode seat, 2026-11-21): n32-ikb2 + the n39-dec decode stack, rebased for the case that ikb2 ships:# n35 (patch/n35_w8.py + patch/n35_w8gemv.py: MXFP8 W8A16 qkvr / wo_ud on decode / verify only, knob N35_W8 attn | empty),# n37 (patch/n37_tiles.py: NVFP4 grouped-GEMM decode tile_k N37_TILE_K, default 256, bitwise equal to the image config),# n38 (serve/inkling2_mtp.py = the n17 file 822cddb7 + an env-gated block: W8 drafter linears when N38_DRAFT_W8=1, default 1).# patch/inkling2_attn.py = ikb2's c1889915 + the n35 and n37 install blocks appended. Empty / 128 / 0 = ikb2 exactly.INK_N32=${INK_N32:-1}INK_N32_GLOBAL=${INK_N32_GLOBAL:-1}EXTRA_DOCKER=${EXTRA_DOCKER:-}ADMIN=${ADMIN:-0}; ADMIN_ARGS=(); [ "$ADMIN" = 1 ] && ADMIN_ARGS=(--admin-api-key "$API_KEY")# n17 (dspark seat, 2026-11-21, staged): n2-proj1 + ds-sl32. Adds the ds-sl32 shortlist-vocab DSpark draft head: serve/inkling2_mtp.py# (image md5 35e23e4a + env-gated shortlist, md5 822cddb7) and serve/sl.json (32,768 ids, md5 389d362c), mounted only with SPEC=1.HERE=$(cd "$(dirname "$0")/.." && pwd)SDIR=$(cd "$(dirname "$0")" && pwd)INK_PROJ_SPLIT=${INK_PROJ_SPLIT:-1}N14_MOE=${N14_MOE-qc}KJ=/sgl-workspace/sglang/python/sglang/kernels/jit/csrc/inkling2N75_C12=${N75_C12:-}; N75_C12_CHECK=${N75_C12_CHECK:-0}; N75_C12_CFG=${N75_C12_CFG:-}N75_C12_KERNEL=${N75_C12_KERNEL:-}; N75_C12_CUDA_NW=${N75_C12_CUDA_NW:-}N86_G1=${N86_G1:-0}; N86_G2=${N86_G2:-0}; N86_MIN_ROWS=${N86_MIN_ROWS:-2048}; N86_G2_SHAPES=${N86_G2_SHAPES:-}N86_N75_MS=${N86_N75_MS:-8,16}; N86_N75_CLASSES=${N86_N75_CLASSES:-qkvr,wo_ud,lm_head}N78_CERT=${N78_CERT:-}; N78_CHECK=${N78_CHECK:-}N35_W8=${N35_W8-attn}N37_TILE_K=${N37_TILE_K:-256}N38_DRAFT_W8=${N38_DRAFT_W8:-1}N41_CTX_SL=${N41_CTX_SL:-4096}N50=${N50:-1}; N50_MIN=${N50_MIN:-1000}N64=${N64:-1}; N64_MIN_K=${N64_MIN_K:-0}; N64_PREALLOC=${N64_PREALLOC:-24}N52_BAND=${N52_BAND:-0}; N52_FORM=${N52_FORM:-f2}; N52_TB=${N52_TB:-16}; N52_LEAN=${N52_LEAN:-1}; N52_RASTER=${N52_RASTER:-0}N105_RNNHOIST=${N105_RNNHOIST:-}; N105_MODE=${N105_MODE:-}; N105_PRE_NW=${N105_PRE_NW:-}; N105_STEP_NW=${N105_STEP_NW:-}; N105_CHECK=${N105_CHECK:-}KO=/sgl-workspace/sglang/python/sglang/kernels/ops/elementwiseMDL=/sgl-workspace/sglang/python/sglang/srt/models/inkling_common: "${NAME:?}" "${PORT:?}" "${API_KEY:?}" "${IMAGE:?}"MODEL_DIR=${MODEL_DIR:-/workspace/models/Inkling-2-Mini}; MEM=${MEM:-0.45}; CTX=${CTX:-262144}SPEC=${SPEC:-1}; NUM_DRAFT=${NUM_DRAFT:-8}; CACHE_DIR=${CACHE_DIR:-/workspace/eat-inkling/cache/sglang}; SERVED=${SERVED:-inkling-2-mini}EXTRA_ARGS=${EXTRA_ARGS:-}FA=/sgl-workspace/sglang/python/sglang/kernels/ops/attention/fa4_sm120mkdir -p "$CACHE_DIR"[ "$SPEC" = dflash2 ] || { echo "n292 requires SPEC=dflash2" >&2; exit 2; }DRAFT_DIR=${DRAFT_DIR:?DRAFT_DIR: a DFlash2-family drafter dir with SHA256SUMS}DFLASH2_SCRIPT=${DFLASH2_SCRIPT:-/workspace/eat-inkling/drafters/dflash2-4f9088ea/sglang_inkling_dflash2.py}[ -f "$DRAFT_DIR/model.safetensors" ] && [ -f "$DRAFT_DIR/config.json" ] && [ -f "$DRAFT_DIR/SHA256SUMS" ] || { echo "no DFlash2-family drafter at $DRAFT_DIR" >&2; exit 1; }# n419b: plain-text docs (LICENSE, NOTICE, README.md, MD5SUMS) may sit uncovered in the drafter dir (the lane's copies list only# config.json + model.safetensors); every other file must be listed, and the listed files are sha256-checked in the container belowdocs='LICENSE|NOTICE|README\.md|MD5SUMS'listed=$(awk '{print $2}' "$DRAFT_DIR/SHA256SUMS" | grep -vxE "$docs" | sort); present=$(cd "$DRAFT_DIR" && ls -A | grep -vxE "SHA256SUMS|$docs" | sort)[ "$listed" = "$present" ] && grep -q ' config\.json$' "$DRAFT_DIR/SHA256SUMS" && grep -q ' model\.safetensors$' "$DRAFT_DIR/SHA256SUMS" || { echo "files in $DRAFT_DIR differ from its SHA256SUMS" >&2; exit 1; }printf '%s %s\n' 14223ae2f3aa1d661da67cf0143ec33070d952a6e28a119e6cec64fcc0bebe50 "$DFLASH2_SCRIPT" | sha256sum -c --quiet - || { echo "integration script $DFLASH2_SCRIPT is not 14223ae2" >&2; exit 1; }DFLASH2_SHA256=$(awk '{print $1" "$2}' "$DRAFT_DIR/SHA256SUMS")MIX_ARGS=()if [ -n "${MIX_DIR:-}" ]; then [ "$(cat "$MIX_DIR/BUILT_FROM" 2>/dev/null)" = "${MIX_BASE_SHA256:-}" ] || { echo "[mixpin] REFUSED: $MIX_DIR/BUILT_FROM does not name the pinned base drafter (provenance: written by the rebuild)" >&2; exit 78; } bash "$HERE/serve/mixpin.sh" "$MIX_DIR/Inkling-2-Mini-DFlash2-mix.safetensors" "${MIX_SHA256:-}" "$DRAFT_DIR/model.safetensors" "${MIX_BASE_SHA256:-}" || exit 78 MIX_ARGS=(-v "$MIX_DIR":/draft-mix:ro -e INKLING_DFLASH_MIX_PATH=/draft-mix/Inkling-2-Mini-DFlash2-mix.safetensors)fiRING=$(python3 -I -c 'import json, sys; t = json.load(open(sys.argv[1])).get("layer_types") or []; print(1 if t and all(x == "sliding_attention" for x in t) else 0)' "$DRAFT_DIR/config.json") || { echo "unreadable $DRAFT_DIR/config.json" >&2; exit 1; }docker rm -f "$NAME" > /dev/null 2>&1 || true# shellcheck disable=SC2086exec docker run --pull=never -d --name "$NAME" --gpus all --ipc=host --shm-size 32g \ -p 127.0.0.1:$PORT:30000 \ -e MAX_JOBS=4 -e HF_HUB_OFFLINE=1 -e DO_NOT_TRACK=1 -e SGLANG_DISABLE_USAGE_STATS=1 \ -v "$MODEL_DIR":/model:ro -v "$CACHE_DIR":/root/.cache \ -v "$HERE/patch/inkling2_attn.py":$MDL/inkling2_attn.py:ro -e SGLANG_INKLING_SPLIT_PROJ="$INK_PROJ_SPLIT" \ -v "$HERE/patch/n13_attn_global.py":$MDL/n13_attn_global.py:ro -v "$HERE/patch/n13_fwd.py":$FA/n13_fwd.py:ro \ -v "$HERE/patch/n75_install.py":$MDL/n75_install.py:ro -v "$HERE/patch/n75_c12.py":$MDL/n75_c12.py:ro \ -v "$HERE/patch/n75_cuda.py":$MDL/n75_cuda.py:ro -e N75_C12_KERNEL="$N75_C12_KERNEL" -e N75_C12_CUDA_NW="$N75_C12_CUDA_NW" \ -e N75_C12="$N75_C12" -e N75_C12_CHECK="$N75_C12_CHECK" -e N75_C12_CFG="$N75_C12_CFG" \ -v "$HERE/patch/n86_riders.py":$MDL/n86_riders.py:ro -v "$HERE/patch/n71_sconvres.py":$MDL/n71_sconvres.py:ro \ -v "$HERE/patch/n71_resnorm.py":$MDL/n71_resnorm.py:ro -e N86_G1="$N86_G1" -e N86_G2="$N86_G2" -e N86_MIN_ROWS="$N86_MIN_ROWS" \ -e N86_G2_SHAPES="$N86_G2_SHAPES" -e N86_N75_MS="$N86_N75_MS" -e N86_N75_CLASSES="$N86_N75_CLASSES" \ -v "$HERE/patch/n78_head.py":$MDL/n78_head.py:ro -v "$HERE/patch/n78_kern.py":$MDL/n78_kern.py:ro -e N78_CERT="$N78_CERT" -e N78_CHECK="$N78_CHECK" \ -v "$HERE/patch/n35_w8.py":$MDL/n35_w8.py:ro -v "$HERE/patch/n35_w8gemv.py":$MDL/n35_w8gemv.py:ro -e N35_W8="$N35_W8" \ -v "$HERE/patch/n14_moe.py":$MDL/n14_moe.py:ro -v "$HERE/patch/n14_quant.cuh":$KJ/n14_quant.cuh:ro -e N14_MOE="$N14_MOE" \ -v "$HERE/patch/n52_moe.py":$MDL/n52_moe.py:ro -v "$HERE/patch/n52_band.cuh":$KJ/n52_band.cuh:ro \ -e N52_BAND="$N52_BAND" -e N52_FORM="$N52_FORM" -e N52_TB="$N52_TB" -e N52_LEAN="$N52_LEAN" -e N52_RASTER="$N52_RASTER" \ -v "$HERE/patch/n105_rnnhoist.py":$MDL/n105_rnnhoist.py:ro -e N105_RNNHOIST="$N105_RNNHOIST" -e N105_MODE="$N105_MODE" \ -e N105_PRE_NW="$N105_PRE_NW" -e N105_STEP_NW="$N105_STEP_NW" -e N105_CHECK="$N105_CHECK" \ -v "$HERE/patch/n37_tiles.py":$MDL/n37_tiles.py:ro -e N37_TILE_K="$N37_TILE_K" -e N38_DRAFT_W8="$N38_DRAFT_W8" -e N41_CTX_SL="$N41_CTX_SL" \ -v "$HERE/patch/n32_attn_local.py":$MDL/n32_attn_local.py:ro -v "$HERE/patch/n32_fwd.py":$FA/n32_fwd.py:ro \ -v "$HERE/patch/inkling2_loop.py":$KO/inkling2_loop.py:ro -v "$HERE/patch/n15_fused.py":$KO/n15_fused.py:ro \ -e SGLANG_INKLING_N50="$N50" -e SGLANG_INKLING_N50_MIN_TOKENS="$N50_MIN" \ -e SGLANG_INKLING_N32="$INK_N32" -e SGLANG_INKLING_N32_GLOBAL="$INK_N32_GLOBAL" \ -v "$HERE/patch/n64a_fwd.py":$FA/n64a_fwd.py:ro -v "$HERE/patch/n64b_fwd.py":$FA/n64b_fwd.py:ro \ -v "$HERE/patch/n64_attn_global.py":$MDL/n64_attn_global.py:ro -e SGLANG_INKLING_N64="$N64" \ -e SGLANG_INKLING_N64_MIN_K="$N64_MIN_K" -e SGLANG_INKLING_N64_PREALLOC_HEADS="$N64_PREALLOC" $EXTRA_DOCKER \ -e SGLANG_OPT_INKLING2_VERIFY_REL_BIAS_KERNEL=1 \ -e MALLOC_MMAP_THRESHOLD_=1048576 \ -e SGLANG_ENABLE_DFLASH_DRAFT_KV_RING="$RING" -e DFLASH2_SHA256="$DFLASH2_SHA256" -v "$DRAFT_DIR":/draft:ro \ -v "$DFLASH2_SCRIPT":/draft-script/sglang_inkling_dflash2.py:ro "${MIX_ARGS[@]}" \ --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; } echo "[n391-serve] DFLASH draft KV ring env $SGLANG_ENABLE_DFLASH_DRAFT_KV_RING (1 iff every draft layer is sliding_attention)" python3 -I /draft-script/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_ARGS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""Minimal Inkling DFlash2 integration for the pinned official Inkling image.
No target math, sampling, or checkpoint weights are changed."""from pathlib import Pathimport hashlib, json
def apply(): import sglang root=Path(sglang.__file__).resolve().parent changes=[] pending={} originals={} def read(rel): if rel not in pending: originals[rel]=pending[rel]=(root/rel).read_text() return pending[rel] def edit(rel, old, new): s=read(rel) if new in s:return assert s.count(old)==1,(rel,s.count(old),old[:100]) pending[rel]=s.replace(old,new) def undo(rel, old, new): s=read(rel) if new in s: assert s.count(new)==1,(rel,new[:100]) pending[rel]=s.replace(new,old) # Upgrade the earlier patch without retaining draft-owned target metadata. undo('srt/speculative/dflash_utils.py', ' is_mla: bool = False\n', ' is_mla: bool = False\n capture_final_norm: bool = False\n') undo('srt/speculative/dflash_utils.py', ' if val < 0 or val >= target_num_layers:', ' if val < 0 or val > target_num_layers or (val == target_num_layers and not self.capture_final_norm):') undo('srt/speculative/dflash_utils.py', ' final_logit_softcapping=final_logit_softcapping,', ' final_logit_softcapping=final_logit_softcapping,\n' ' capture_final_norm=bool(dflash_cfg.get("capture_final_norm", False)),') alias = (' def set_dflash_layers_to_capture(self, layer_ids: list[int]) -> None:\n' ' # Both drafts use native post-residual visit features and final norm.\n' ' self.set_dspark_layers_to_capture(layer_ids)\n\n') original = ' def set_dspark_layers_to_capture(self, layer_ids: list[int]) -> None:' undo('srt/models/inkling2.py', original, alias + original) edit('srt/models/inkling2.py', original, alias + ' def get_dflash_valid_vocab_size(self) -> int:\n' ' return int(self.text_config.vocab_size)\n\n' + original) edit('srt/configs/inkling2.py', ' @property\n def num_layer_visits(self) -> int:', ' def resolve_dflash_capture_layers(self, layer_ids):\n' ' # Inkling features end with the post-final-norm state.\n' ' ids = list(layer_ids) if layer_ids is not None else []\n' ' if (not ids or ids != sorted(set(ids)) or ids[0] < 0\n' ' or ids[-1] != self.num_layer_visits):\n' ' raise ValueError("Inkling draft capture ids must be sorted, unique, "\n' ' "and end at the final-norm layer visit")\n' ' return ids\n\n' ' @property\n def num_layer_visits(self) -> int:') edit('srt/model_executor/model_runner_components/spec_aux_hidden_state.py', ' target_layer_ids = dflash_draft_config.resolve_target_layer_ids(\n' ' target_num_layers=int(target_num_layers),\n' ' draft_num_layers=int(draft_num_layers),\n' ' )', ' capture_resolver = getattr(model_config.hf_text_config,\n' ' "resolve_dflash_capture_layers", None)\n' ' if callable(capture_resolver):\n' ' target_layer_ids = capture_resolver(dflash_draft_config.target_layer_ids)\n' ' else:\n' ' target_layer_ids = dflash_draft_config.resolve_target_layer_ids(\n' ' target_num_layers=int(target_num_layers),\n' ' draft_num_layers=int(draft_num_layers),\n' ' )') edit('srt/models/dflash.py', ' target_layer_ids = draft_config.resolve_target_layer_ids(\n' ' target_num_layers=target_num_layers, draft_num_layers=num_layers\n' ' )', ' # Explicit feature ids are validated against the actual target\n' ' # by its capture adapter; here only the projection width is needed.\n' ' target_layer_ids = draft_config.target_layer_ids\n' ' if target_layer_ids is None:\n' ' target_layer_ids = draft_config.resolve_target_layer_ids(\n' ' target_num_layers=target_num_layers, draft_num_layers=num_layers\n' ' )') edit('srt/speculative/dflash_worker_v2.py', ' self.selector = self.draft_model.candidate_selector\n', ' self.selector = self.draft_model.candidate_selector\n' ' vocab_resolver = getattr(target_worker.model_runner.model,\n' ' "get_dflash_valid_vocab_size", None)\n' ' if self.selector is not None and callable(vocab_resolver):\n' ' self.draft_model.valid_vocab_size = vocab_resolver()\n') undo('srt/models/dflash.py', ' self.valid_vocab_size = None', ' self.valid_vocab_size = config.dflash_config.get("valid_vocab_size")') # The trained selector applies softcap after adding the correction. The # image predates that config field; preserve its default for other drafts. edit('srt/models/dflash.py', ' # The draft has no head of its own; the worker points this at the target\'s', ' self.selector_softcap_mode = config.dflash_config.get("selector_softcap_mode", "before_correction")\n' ' if self.selector_softcap_mode not in ("before_correction", "after_correction"):\n' ' raise ValueError(self.selector_softcap_mode)\n' ' self.candidate_selector.post_softcap = (draft_config.final_logit_softcapping\n' ' if self.selector_softcap_mode == "after_correction" else None)\n' ' self.valid_vocab_size = None\n' ' # The draft has no head of its own; the worker points this at the target\'s') edit('srt/models/dflash.py', ' if softcap is not None:\n logits.div_(softcap).tanh_().mul_(softcap)', ' if softcap is not None and self.selector_softcap_mode == "before_correction":\n logits.div_(softcap).tanh_().mul_(softcap)') edit('srt/models/dflash.py', ' return _score_edges(\n predecessor_table=self.predecessor_codebook,', ' scores = _score_edges(\n predecessor_table=self.predecessor_codebook,') edit('srt/models/dflash.py', ' top_k=self.top_k,\n )\n\n def sample_path(', ' top_k=self.top_k,\n )\n' ' cap = getattr(self, "post_softcap", None)\n' ' return cap * torch.tanh(scores / cap) if cap else scores\n\n' ' def sample_path(') # Limit the draft candidate projection to the same real vocabulary used by # the target logits processor and training (201024 is padded storage only). edit('srt/models/dflash.py', ' with_partition: bool = False,\n merged_unary_transform:', ' with_partition: bool = False,\n valid_vocab_size: Optional[int] = None,\n merged_unary_transform:') edit('srt/models/dflash.py', ' logits = _project_candidate_logits(\n hidden, lm_head, num_org=num_org, use_quant_head=use_quant_head\n )', ' if valid_vocab_size is not None:\n' ' if not tp:\n' ' raise ValueError("This Inkling benchmark integration is validated for TP1")\n' ' num_org = min(num_org, int(valid_vocab_size))\n' ' logits = _project_candidate_logits(\n hidden, lm_head, num_org=num_org, use_quant_head=use_quant_head\n )') edit('srt/models/dflash.py', ' hidden, self.lm_head, self.candidate_selector.top_k\n )\n return ids, self._transform_unary_logits(vals)', ' hidden, self.lm_head, self.candidate_selector.top_k,\n' ' valid_vocab_size=self.valid_vocab_size\n )\n return ids, self._transform_unary_logits(vals)') for rel,s in pending.items(): compile(s, str(root/rel), 'exec') for rel,s in pending.items(): before=originals[rel] if before != s: (root/rel).write_text(s) changes.append({'file':rel,'before_sha256':hashlib.sha256(before.encode()).hexdigest(), 'after_sha256':hashlib.sha256(s.encode()).hexdigest()}) return changes
if __name__=='__main__': print(json.dumps(apply(),indent=2))recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/_hook.pyAdded+78
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/build.pyAdded+113
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/csrc/bf16x_format.cuhAdded+57
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/csrc/wide_ext.cuAdded+787
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/ops.pyAdded+313
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/patches.pyAdded+397
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/tests/fake_wide_ext.pyAdded+65
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/tests/test_wide.pyAdded+508
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/third_party/pico/LICENSEAdded+21
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/tools/gpu_check_wide.pyAdded+407
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/inkling_wide/tools/gpu_integration_wide.pyAdded+201
recipe/stack/cands/n419j3-2416d17a/recipe/overlay/sitecustomize.pyAdded+98
recipe/stack/cands/n419j3-2416d17a/recipe/patch/inkling2_attn.pyAdded+780
recipe/stack/cands/n419j3-2416d17a/recipe/patch/inkling2_loop.pyAdded+280
recipe/stack/cands/n419j3-2416d17a/recipe/patch/inkling2_loop_model.pyAdded+68
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n105_rnnhoist.pyAdded+1783
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n13_attn_global.pyAdded+37
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n13_fwd.pyAdded+655
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n140_kern.pyAdded+641
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n14_moe.pyAdded+216
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n14_quant.cuhAdded+237
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n15_fused.pyAdded+147
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n32_attn_local.pyAdded+226
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n32_fwd.pyAdded+1567
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n35_w8.pyAdded+128
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n35_w8gemv.pyAdded+64
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n37_tiles.pyAdded+28
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n50b_fused.pyAdded+314
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n52_band.cuhAdded+1886
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n52_moe.pyAdded+202
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n64_attn_global.pyAdded+233
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n64a_fwd.pyAdded+1138
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n64b_fwd.pyAdded+1597
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n66fb.pyAdded+369
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n71_resnorm.pyAdded+257
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n71_sconvres.pyAdded+135
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n75_c12.pyAdded+188
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n75_cuda.pyAdded+365
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n75_install.pyAdded+343
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n78_head.pyAdded+312
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n78_kern.pyAdded+417
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n80_cuda.pyAdded+171
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n80_draft.pyAdded+147
recipe/stack/cands/n419j3-2416d17a/recipe/patch/n86_riders.pyAdded+448
recipe/stack/cands/n419j3-2416d17a/recipe/serve/inkling2_mtp.pyAdded+667
recipe/stack/cands/n419j3-2416d17a/recipe/serve/mixpin.shAdded+13
recipe/stack/cands/n419j3-2416d17a/recipe/serve/serve.shAdded+189
recipe/stack/cands/n419j3-2416d17a/recipe/serve/serve.sh.origAdded+189
recipe/stack/cands/n419j3-2416d17a/recipe/serve/sl.jsonAdded
recipe/stack/dflash2/sglang_inkling_dflash2.pyAdded+143