Inkling-2-Mini DGX Spark recipe + t5a DFlash2 drafter (package 1741ea3c) (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- recipe/stack/cands/n292-v2-v297-pk3c/recipe/serve/sl.jsonAdded
- recipe/stack/cands/n343a-s2-verify-scodes/CREDITS.mdAdded+94
- recipe/stack/cands/n343a-s2-verify-scodes/LICENSEAdded+21
- recipe/stack/cands/n343a-s2-verify-scodes/NOTICEAdded+54
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/README.mdAdded+85
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/__init__.pyAdded+288
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/_hook.pyAdded+78
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_args.hAdded+35
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_binding.cuAdded+58
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_group_gemm.cuhAdded+247
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_128_128.cuAdded+4
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_32_128.cuAdded+4
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_32_256.cuAdded+4
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_64_128.cuAdded+4
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_64_256.cuAdded+4
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_sm120_mma_array.hppAdded+1333
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/encode.pyAdded+123
- recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/kernel.pyAdded+99
- recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n320s/__init__.pyAdded+66
- recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n329/__init__.pyAdded+58
- recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n329/n329_rows.pyAdded+31
- recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n329/n329_rows_ctl.pyAdded+31
- recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n351/__init__.pyAdded+68
- recipe/stack/cands/n361-s3b-p/overlay_n320/n351_quant.cuhAdded+175
- recipe/stack/cands/n361-s3b-p/overlay_n320/sitecustomize.pyAdded+107
- recipe/stack/cands/n361-s3b-p/recipe/CREDITS.mdAdded+94
- recipe/stack/cands/n361-s3b-p/recipe/LICENSEAdded+21
- recipe/stack/cands/n361-s3b-p/recipe/NOTICEAdded+54
- recipe/stack/cands/n361-s3b-p/recipe/draft-mix/LICENSEAdded+202
- recipe/stack/cands/n361-s3b-p/recipe/draft-mix/NOTICEAdded+46
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/CREDITS.knapcio-v2.9.3.mdAdded+94
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/LICENSE.knapcio-v2.9.3Added+21
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/NOTICE.knapcio-v2.9.3Added+54
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/README.mdAdded+164
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/__init__.pyAdded+170
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/_hook.pyAdded+83
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/build.pyAdded+102
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/csrc/attn_kernel.cuhAdded+555
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/csrc/inkling_attn_ext.cuAdded+326
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/ops.pyAdded+76
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/patch.pyAdded+562
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/tests/test_install.pyAdded+54
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/tests/test_w8split_cpu.pyAdded+118
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/README.mdAdded+197
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/__init__.pyAdded+172
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/_hook.pyAdded+78
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/build.pyAdded+102
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/cert_math.pyAdded+163
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/certwide.pyAdded+140
- recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/certwide_math.pyAdded+74
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Credits
- **Thinking Machines Lab** for Inkling-2-Mini, its NVFP4 / MXFP8 checkpoint and the bundled DSpark draft model (`mtp.safetensors`) ([model card](https://huggingface.co/thinkingmachines/Inkling-2-Mini), [announcement](https://thinkingmachines.ai/news/inkling-2-mini/), Apache-2.0).- **incoai**, [Inkling-2-Mini-DFlash2](https://huggingface.co/incoai/Inkling-2-Mini-DFlash2) (Apache-2.0): the DFlash2 draft model that is this recipe's default drafter, and its SGLang compatibility patch (`sglang_inkling_dflash2.py`), both used as published at revision `4f9088ea`, fetched by `scripts/download.sh` and not distributed here. The drafter byte cuts, the DFLASH verify-width cap, the certified head on DFLASH steps and the selector fix are ours, on top of it.- **The DFlash authors** ([z-lab/dflash](https://github.com/z-lab/dflash)): block-diffusion drafting for speculative decoding, the method behind the DFlash2 drafter, and SGLang's DFLASH worker that serves it.- **SGLang** project for the Inkling-2-Mini support, the `lmsysorg/sglang:inkling-2-mini` image and the [Inkling-2-Mini cookbook](https://docs.sglang.io/cookbook/autoregressive/ThinkingMachines/Inkling-2-Mini), whose DGX Spark DSpark cell (TP1/EP1, FA4, page 128, 8 draft tokens, the four `SGLANG_OPT_*` switches, `MAX_JOBS=4`, the `inkling` / `inkling2` parsers) is the base of the default profile.- **vLLM** project for the Inkling-2-Mini support (vllm-project/vllm #69027, #69028, #69039 by Woosuk Kwon and contributors), the `vllm/vllm-openai:inkling-2-mini` image and the [vLLM recipe](https://recipes.vllm.ai/thinkingmachines/Inkling-2-Mini) behind the alternative profile.- **Tech2Wild (tonyd2wild)**, [Inkling-2-Mini-NVFP4-DGX-Spark](https://github.com/tonyd2wild/Inkling-2-Mini-NVFP4-DGX-Spark): the first single-Spark vLLM recipe for this model. Reused here: the vLLM tier settings (`--gpu-memory-utilization 0.80` at 262K context with tool calling on), the hybrid KV-pool block model and the FP8-KV long-context tier with its memory budget (74 GiB of FP8 KV at 1M), the GB10 page-cache trap, and the advice to keep MemAvailable above ~6 GiB.- **thefullctx**, [inkling-2-mini-sglang-dgx-spark](https://github.com/thefullctx/inkling-2-mini-sglang-dgx-spark) and [inkling-2-mini-vllm-dgx-spark](https://github.com/thefullctx/inkling-2-mini-vllm-dgx-spark): the first published SGLang vs vLLM head-to-head on one Spark (vLLM slightly ahead on short c1 decode, SGLang ~2x on long prefill, faster long-context decode and much lower memory use), which set the arms of our comparison.- **Thien Tran (gau-nernst)**, vLLM PR #69168 (small-M GEMMs for Inkling's looped core): the split-K router / conv-projection and controller re-tiling we screened (not adopted, flat in serving).- **sxuff**, [inkling-2-mini-spark](https://github.com/sxuff/inkling-2-mini-spark) (Apache-2.0): the vLLM + DSpark + INT8 draft recipe and benchmark used for the same-harness comparison, and the `--safetensors-load-strategy eager` result (127 -> 45 s) that prompted our one-pass checkpoint load with SGLang's own flag.- **0xSero**, [inference-optimisation skill](https://github.com/sybil-solutions/inference-optimisation-skill) (MIT): the method behind sxuff's eager-load finding.- **tie-pilot-qxw**, [dspark-markov-walk](https://github.com/tie-pilot-qxw/dspark-markov-walk) (MIT), and [vLLM PR #62958](https://github.com/vllm-project/vllm/pull/62958): the one-kernel DSpark Markov walk that inspired `rnnhoist`. Our projection split is an independent implementation.- **nick398** on the [NVIDIA developer forum thread](https://forums.developer.nvidia.com/t/inkling-2-mini/389745): the first FP8-KV serving notes for this model (vLLM `--kv-cache-dtype fp8` on an RTX 5090: about half the KV memory per token, described there as a quality trade-off).- **Andy Shu (@blaesus)**, [dsgb10](https://github.com/blaesus/dsgb10) (formerly dsgx10, MIT), as carried in [Picom-code/pico-dgx-ds4](https://github.com/Picom-code/pico-dgx-ds4) ("pico"): the exactly coded 12-bit BF16 GEMV (`bf16x` format and kernel) that `overlay/inkling_pico12/` builds and calls for the dense projections and the LM head; the sources are vendored unmodified in `overlay/inkling_pico12/third_party/pico/` with their licence.- **Andy Shu's `bf16x` reader** is also copied (MIT, with its notice) into `overlay/inkling_wide/csrc/bf16x_format.cuh`, which reads pico12's coded weights in the 17-256-row GEMM, and `overlay/inkling_cert/` compiles pico's head GEMV body from the vendored copy for the exact pass of the certified LM head.- **Tri Dao et al., FlashAttention-2** (algorithm): the online-softmax tiling of the fused relative-bias prefill attention in `overlay/inkling_attn/`.- **SGLang Inkling2 kernels**: the split-KV relative-bias verify kernel that `overlay/inkling_vattn/` routes every batch size to (and copies, with the bias computed per key tile, above 32 rows), the split-KV decode kernel that `overlay/inkling_kv12/` follows with its K / V tile loads replaced, the split softmax kernels that `VCAP_FASTPROBS` calls, the block-verification accept kernel behind `--speculative-use-block-verification`, and the fused loop-controller kernels of sgl-project/sglang PR #51926, already in the image.- **SGLang PR #51681** (DSpark Markov sampler: Philox words that rounded to u == 1) and **SGLang PR #51692** (blockwise rejection precision): their fixes are carried verbatim in `overlay/inkling_rsfix/` (`RSFIX`) until the image has them. The reject-sampler CDF fix and the DFLASH selector no-match fix in the same package are ours.- **Sun et al.**, "Block Verification Accelerates Speculative Decoding" (ICLR 2025): the block-verification algorithm that sampled requests use (`VCAP_BV`, `DFLASH_BV`). Running it under the verify cap (dead drafts as a stopped draft) and its logits-only form in the fused accept are ours.- **Xiao et al.**, StreamingLLM (2023): the attention sink kept by the optional drafter global-attention window (`dwin`, 128 sink tokens by default).- **Lossless float compression by exponent coding** (ZipNN, Hershcovitch et al., 2024; SplitZip) and **Andy Shu's exactly coded 12-bit `bf16x` format**: the inspiration for the packed 12-bit global-layer KV in `overlay/inkling_kv12/` (sign + mantissa byte, 4-bit exponent code, escapes). The KV format, packer and attention kernel are our own code; nothing is copied from these projects.- **Alexey Fateev / Project Maya**, [maya-inkling-mini](https://github.com/alesha-pro/maya-inkling-mini) (MIT): launch and "bytes in flight" notes on Inkling's small per-visit kernels that framed our L2-warming screen (not adopted, see docs/experiments.md).- **FR-Spec** (Zhao et al., ACL 2025, frequency-ranked draft vocabulary) and SGLang's EAGLE `--speculative-token-map`: the idea behind the hot-vocabulary draft. The prompt corpus that ranks the shipped list comes from allenai/WildChat-1M (ODC-BY), OpenAssistant/oasst2 (Apache-2.0), NousResearch/hermes-function-calling-v1 (Apache-2.0), bigcode/self-oss-instruct-sc2-exec-filter-50k (ODC-BY), HuggingFaceH4/ultrachat_200k (MIT), ise-uiuc/Magicoder-OSS-Instruct-75K (MIT), openai/gsm8k (MIT), databricks/databricks-dolly-15k (CC-BY-SA-3.0), EleutherAI/hendrycks_math (MIT), abisee/cnn_dailymail (Apache-2.0), CohereLabs/aya_dataset (Apache-2.0), wikimedia/wikipedia (CC-BY-SA-4.0), juletxara/mgsm (CC-BY-SA-4.0) and llm-jp/oasst2-33k-ja (Apache-2.0); only token frequencies of the model's own outputs are shipped, no prompt text.- **thefullctx**: the KV page-size 16 measurement we screened (not adopted here).- **Christopher Owen** and B12X (MXFP4-CSF): the scale-code format idea behind `overlay/inkling_scodes/` (our implementation, in a modified FlashInfer / CUTLASS mainloop).- **Christopher Owen, spark-ds41f** (Apache-2.0): the packed-BF16 vocabulary projection (b12x patch 0012) whose format we ported to Triton in a screen (not adopted, see docs/experiments.md).- **FlashInfer** (CUTLASS / CuTe DSL grouped GEMMs, the GEMVs) and **CUTLASS**: the kernels the MoE tile choice and the GPU checks run on; since v2.8.4 also the b12x MXFP8 GEMM and quantiser (`mm_mxfp8`, `mxfp8_quantize`) that run the drafter's eligible linears (mx8w), used as shipped.- **NVIDIA** for the DGX Spark platform.- **speedbench** ([knapcio/speedbench](https://github.com/knapcio/speedbench)), our own benchmark, for the headline numbers and the long-context table; its frozen prompt set also feeds the decode table.
Our own earlier recipes contributed ideas reused here: the verify cap with dead-row expert remap (DeepSeek-V4.1recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bitdraft heads (DeepSeek-V4.1), and our spark-tools and speedbench for measurement.
Every lever adopted from someone else's work gets a line here and an entry in the Credit column of the README.123456789101112131415161718192021MIT License
Copyright (c) 2026 Zbigniew Majewski
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354Inkling-2-Mini on one NVIDIA DGX Spark
Repository-authored launch scripts, benchmark scripts and documentation: MIT, see LICENSE.
Third-party code vendored in this repository:- overlay/inkling_pico12/third_party/pico/: kernels/gemv16.cu, kernels/common.cuh, kernels/dsk.h, common/check.h by Andy Shu (github.com/blaesus/dsgb10, formerly dsgx10, `ds41f-4xgx10-switchless/engine/` at commit f2117916, as carried in github.com/Picom-code/pico-dgx-ds4), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_pico12/third_party/pico/LICENSE. Unmodified except a two-line header naming the origin.- overlay/inkling_wide/csrc/bf16x_format.cuh: the `bf16x` reader (layout description, bf16x_raw_off, mad_imm, bf16x_dec, ldg_bf16x) copied from the same pico gemv16.cu (commit f2117916), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_wide/third_party/pico/LICENSE.- overlay/inkling_cert/csrc/cert_ext.cu compiles kernels/gemv16.cu from overlay/inkling_pico12/third_party/pico/ (above) into its own extension; no further copy.
- overlay/inkling_scodes/csrc/scodes_sm120_mma_array.hpp: derived from CUTLASS's SM120 block-scaled grouped-GEMM collective mainloop (NVIDIA CORPORATION & AFFILIATES, BSD-3-Clause, licence text kept in the file header), modified to expand coded scale factors; scodes_group_gemm.cuh reduces FlashInfer 0.7.4's include/flashinfer/gemm/group_gemm_nvfp4_groupwise_sm120.cuh (Apache-2.0, Copyright (c) 2026 FlashInfer team) to the configuration SGLang uses and swaps in that mainloop.- overlay/inkling_kv12/ops.py: the decode / verify attention kernels (`_kv12_partials_np`, `_kv12_partials`) follow SGLang's Inkling2 split-KV decode kernel (`_decode_partials` in sglang.kernels.ops.attention.inkling2_decode_attention_sm90, sgl-project/sglang, Apache-2.0) with the same grid, tile order and online softmax, modified to read packed 12-bit K / V tiles from a side pool.- overlay/inkling_vattn/ops.py: `_inkernel_bias_partials` is the same SGLang `_decode_partials` kernel body (sgl-project/sglang, Apache-2.0), modified to compute the relative-position bias per key tile in-kernel.- overlay/inkling_rsfix/markov.py and overlay/inkling_rsfix/blockwise.py: the changes of sgl-project/sglang pull requests #51681 (dspark markov_sample) and #51692 (dspark blockwise_rejection), applied verbatim to copies of the image's functions (sgl-project/sglang, Apache-2.0). overlay/inkling_rsfix/reject.py and selector.py are copies of SGLang's reject_sampling kernels and DFLASH selector walk (Apache-2.0), modified as described in overlay/inkling_rsfix/README.md.
Third-party model files fetched at run time, not distributed in this repository:- Inkling-2-Mini-DFlash2 (huggingface.co/incoai/Inkling-2-Mini-DFlash2) by incoai, revision 4f9088ea66c21f2b99ed657d1941c306b03e84d2: the draft model (config.json, model.safetensors) and its SGLang compatibility patch (sglang_inkling_dflash2.py). Licensed under the Apache License, Version 2.0; you may not use these files except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. scripts/download.sh fetches them unmodified at that revision; scripts/launch.sh checks their sha256 and runs the patch, unmodified, inside the serving container only. The draft method builds on DFlash (github.com/z-lab/dflash).
The serving engines run from their published container images, pinned by digest in scripts/launch.sh:- SGLang (sgl-project/sglang), lmsysorg/sglang:inkling-2-mini, Apache-2.0.- vLLM (vllm-project/vllm), vllm/vllm-openai:inkling-2-mini, Apache-2.0.bench/decode_table.py reads the prompt file of speedbench (knapcio/speedbench, MIT) from a separate checkout; theprompts themselves are not copied here.
No model weights or container images are distributed. The Inkling-2-Mini weights (thinkingmachines/Inkling-2-Mini)are Apache-2.0 from Thinking Machines Lab; read the model card for the terms that apply to anything you serve.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# inkling_scodes: scale codes for the NVFP4 routed experts (exact)
Switch: `INKLING_SCODES=1` (unset = nothing is imported). Exact: the GEMM's MMAs see bit-identical operands; theoutput equals FlashInfer's stock kernel bit for bit (tested on real weights and routing, and self-checked live).Idea and format precedent: Christopher Owen (B12X MXFP4-CSF), ported in spirit from our DeepSeek recipe's`DSV41_MOE_SCALE_CODES`; no code reused.
## What it does
NVFP4 experts (layers 0-19) carry one UE4M3 scale byte per 16 weights: 11 % of their bytes (497,664 of 4,478,976bytes per expert for w13 + w2). Each weight row is stored as a base byte plus a 5-bit code per scale (`encode.py`),packed as 5 bit-planes of 128 bytes per 128 rows x 128 K (640 bytes instead of 1024). Per expert: 497,664 -> 315,648scale bytes, i.e. **-4.06 % of the NVFP4 expert bytes** read per decode step (w13 -4.09 %, w2 -4.01 %; all 20layers: 1,274.0 -> 808.1 MB of scales, 11,466 MB of NVFP4 expert bytes).Measured on the checkpoint (all 40 tensors, `results/kbench/round2/scodes/logs/real_encode_check.log`): 11,794,049 of 11,796,480rows span <= 31 codes (base = row minimum, exact). 2,431 rows (0.02 %) span 32-50 codes: they are escape rows (basebit 7 set, codes 0..30 cover the best 31-value window, code 31 = escape); the kernel takes such an SFA word from theresident stock scales (prefetched one k tile ahead). 3,313 escape words of 318.5 M. Round trip exact on every tensor.
The kernel (`csrc/`) is FlashInfer 0.7.4's SM120 CUTLASS NVFP4 grouped GEMM (`group_gemm_nvfp4_nt_groupwise`,swap_ab=true, tile_m 128) with one collective changed (`csrc/scodes_sm120_mma_array.hpp`, a copy of CUTLASS's`sm120_blockscaled_mma_array_tma.hpp`, all edits marked `scodes`):- producer: one `cp.async.bulk` of the stage's code chunks on the stage mbarrier replaces the SFA TMA (tx bytes adjusted);- consumers: after each `consumer_wait` the 256 MMA threads expand the codes into ONE shared SFA buffer laid out exactly as the stock TMA writes it (thread t -> SFA word t of each chunk: `base*0x01010101 + sum_b spread(nibble_b) << b`), a named barrier publishes it, and the stock smem->rmem copies and MMAs run unchanged. Chunks past K (w2 with tile_k 256) are zero words, like the TMA out-of-bounds fill.Selected through a partial specialization on `TransformA == inkling_scodes::ScodesTransformA`; schedule, epilogue,argument kernel and PDL launch are the stock ones. Built by FlashInfer's own JIT (`gen_jit_spec`, same nvcc flags),cached under `~/.cache/flashinfer/0.7.4/121a/cached_ops/inkling_scodes_<hash>` (~3.5 min cold build, 5 tiles:32x128, 32x256, 64x128, 64x256, 128x128; 128x256 would need more smem than stock and stays stock).
## How it hooks SGLang (post-import, no engine file edited)
- `Inkling2Experts.swizzle_nvfp4_scales` (called by `post_load_weights`, before the KV pool is sized): afterwards the swizzled w13/w2 scales of NVFP4 SM120 experts are encoded; the codes ride on the scale Parameter (`_inkling_scodes`). Raw scales stay resident (prefill > 3072 tokens and any fallback use them): **+0.81 GB** device memory for 20 layers.- `Inkling2Experts._load_shard`: an in-place reload of a coded scale re-encodes into the same buffers (captured graphs keep valid addresses); scales that no longer fit exit 78.- `inkling2_grouped_sm120.nvfp4_expert_matmul`: coded weights run the scodes kernel at the tile `_tiles` returns (so `inkling_kernels.moe_tiles` and `inkling_moe2` keep choosing tiles); a non-swap choice at <= 3072 tokens (the shipped moe_tiles rule for w13 at 9-64 tokens) runs coded swap 32x256 (bit-identical, tested); larger non-swap calls, 128x256 and uncoded weights run stock.- Self-check: the first 3 eager calls per (n, k, tile) also run the stock function and compare bitwise (warm-up only, one host sync each); a mismatch exits 78. A configuration with no passed check runs stock during CUDA-graph capture. `INKLING_SCODES_CHECK=0` disables it.- Patch targets are checked as source strings at `install()`; a change raises `RuntimeError` (loader exits 78).
### sitecustomize snippet (any position; it wraps nvfp4_expert_matmul, not _tiles)
```python if _on("INKLING_SCODES"): # NVFP4 expert scale codes (exact) import inkling_scodes inkling_scodes.install()```
and in `scripts/launch.sh`: `-e INKLING_SCODES="${SCODES:-}"`.
## Evidence (GB10, 2026-11-22; `results/kbench/round2/scodes/`)
- Format: all 40 real NVFP4 tensors (layers 0-19) encoded and decoded exactly (`logs/real_encode_check.log`).- Bit identity (`tools/gpu_scodes.py`, `logs/gpu1.log`): real layers 0, 6, 17 (most escape rows), 19 plus "0x" (layer 0 with forced escape words in the first and last chunk of every 5th row), real routing (oracle top-8 ids) at 8 / 64 / 192 tokens x 2 steps plus a synthetic 160-rows-per-expert case, w13 and w2, all 5 tiles: 350/350 outputs bit-identical to FlashInfer's stock kernel at the same tile, every output written; 10/10 identical to the stock NON-swap 64x256 call it replaces at 9-64 tokens; CUDA graph captured on one routing and replayed on two routings: identical to stock.- Integration (`tools/gpu_integration.py`): hooks over moe_tiles + moe2 and over moe_tiles alone; eager and graph replay identical to stock at 8/64/192 tokens; corrupted codes trip the self-check (exit 78); reload re-encodes into the same buffers.- Cold-L2 microbench (median of 30, 128 MiB read flush before each call), us per call, stock -> scodes at the shipped tile 32x256 (union 37 / 97 / 126 experts):
| layer | 8 tok w13 | 8 tok w2 | 64 tok w13 | 64 tok w2 | 192 tok w13 | 192 tok w2 ||---|---|---|---|---|---|---|| 0 | 494 -> 475 | 251 -> 242 | 1291 -> 1240 | 655 -> 632 | 1706 -> 1639 | 881 -> 843 || 6 | 495 -> 476 | 251 -> 242 | 1293 -> 1245 | 654 -> 632 | 1728 -> 1650 | 887 -> 840 || 17 | 496 -> 483 | 252 -> 246 | 1298 -> 1259 | 655 -> 641 | 1709 -> 1662 | 876 -> 856 || 19 | 495 -> 477 | 250 -> 246 | 1294 -> 1245 | 665 -> 637 | 1711 -> 1648 | 874 -> 844 |
-3.5 to -4.5 % per call on low-escape layers (the byte cut is -4.1 %), -2.2 to -3 % on layer 17 (890 escape rows). Forced escapes in 20 % of rows ("0x") cost +7 %: escape words are a slow path, fine at the real 0.02 %.- Registers: 118-168 per kernel, no local memory (stock gemm_sm120: 114-168).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288"""Inkling-2-Mini NVFP4 expert scale codes on one GB10 (SGLang overlay). Exact.
INKLING_SCODES=1 (default: empty -> install() does nothing)
The NVFP4 routed experts (layers 0-19) store one UE4M3 scale byte per 16 weights (11 % of their bytes). At load,every weight row's scales are re-encoded as a row base byte + a 5-bit code per scale (encode.py; 0.39 of the scalebytes); the SM120 grouped GEMM reads the codes and expands them in shared memory into exactly the bytes the stockkernel would have loaded (csrc/scodes_sm120_mma_array.hpp), so the MMAs see bit-identical operands. -4.1 % of theNVFP4 expert bytes read per decode step.
Hooks (post-import, no engine file edited): sglang.srt.models.inkling_common.inkling2_moe.Inkling2Experts.swizzle_nvfp4_scales (post_load_weights) -> afterwards encode w13/w2 scales of NVFP4 SM120 experts; the codes ride on the scale Parameter (attribute _inkling_scodes). Tensors the 5-bit code cannot hold stay stock. Inkling2Experts._load_shard -> a reload of a coded scale re-encodes it in place (captured graphs keep their addresses); scales that no longer fit the code end the process (exit 78). sglang.kernels.ops.gemm.inkling2_grouped_sm120.nvfp4_expert_matmul -> coded weights with a swap_ab tile the scodes kernel has (tile_n 32/64/128 x tile_k 128/256, not 128x256) run it; a non-swap choice at <= 3072 tokens (shipped moe_tiles rule for w13 at 9-64 tokens) runs swap 32x256 coded (bit-identical, checked); everything else runs stock. Tiles come from the module's _tiles at call time, so inkling_kernels.moe_tiles and inkling_moe2 keep working.Self-check: the first 3 eager calls per (n, k, stock tactic, coded tile) also run the stock kernel and compare the BF16 outputs bitfor bit (one host sync each, warm-up only); a difference exits the process with code 78. During CUDA-graph capturea configuration with no passed check runs stock, so a graph never records an unchecked kernel. INKLING_SCODES_CHECK=0 skipsthe self-check (not recommended).Patch targets are checked as source strings at install() (no sglang/torch import); a changed target raisesRuntimeError (the combined loader exits 78); one found changed at import time raises PatchError (BaseException)."""
import importlib.utilimport osimport sys
STATE = {"installed": False, "encoded": [], "checked": {}, "calls": 0, "stock_calls": 0, "n343_c1_verify": False, "n343_captured": set()}SWAP_OVERRIDE_MAX_TOKENS = 3072SWAP_OVERRIDE_TILE = (32, 256)CHECKS_PER_CONFIG = 3 # eager self-checks per (n, k, tile) before the config counts as checkedMARK = "_inkling_scodes_wrapped"ATTR = "_inkling_scodes"MOE_MODULE = "sglang.srt.models.inkling_common.inkling2_moe"GEMM_MODULE = "sglang.kernels.ops.gemm.inkling2_grouped_sm120"
_SOURCE_CHECKS = ( ("kernels/ops/gemm/inkling2_grouped_sm120.py", ( "def nvfp4_expert_matmul(values, scales, weight, weight_scales, offsets, tokens):", "swap_ab, tile_n, tile_k = _tiles(tokens=tokens, width=packed_width * 2)", "weight_scales.view(torch.uint8).view(experts, n, packed_width // 8),", "group_gemm_nvfp4_nt_groupwise(", )), ("srt/models/inkling_common/inkling2_moe.py", ( "def swizzle_nvfp4_scales(self):", "def _prepare_sm120_scales(self):", "scale.data = swizzle_blockscale(scale.data).flatten(1)", "def _load_shard(self, param, loaded, dim, expert_axis=True, checkpoint_shape=None):", "def forward(self, x, forward_batch=None, combine=True):", "weight_scales=self.w13_scale,", "weight_scales=self.w2_scale,", "grouped_sm120.nvfp4_expert_matmul(", "from sglang.kernels.ops.gemm import inkling2_grouped_sm120 as grouped_sm120", )),)
class PatchError(BaseException): """A patch target changed (BaseException: SGLang's model registry swallows Exception during imports)."""
def _log(msg): sys.stderr.write(f"[inkling_scodes pid={os.getpid()}] {msg}\n") sys.stderr.flush()
def _on(value): return value.strip().lower() not in ("", "0", "off", "none", "false", "no")
def _sglang_root(): spec = importlib.util.find_spec("sglang") if spec is None or not spec.submodule_search_locations: raise RuntimeError("inkling_scodes: the sglang package is not importable") return list(spec.submodule_search_locations)[0]
def check_sources(root=None): root = root or _sglang_root() for rel, needles in _SOURCE_CHECKS: path = os.path.join(root, rel) try: with open(path, encoding="utf-8") as f: text = f.read() except OSError as exc: raise RuntimeError(f"inkling_scodes: patch target {path} is missing") from exc missing = [n for n in needles if n not in text] if missing: raise RuntimeError(f"inkling_scodes: patch target {path} lacks {missing}")
def encode_experts(experts): """Attach scale codes to the NVFP4 SM120 w13/w2 scales of one Inkling2Experts module (after swizzling).""" import torch
from . import encode
if not getattr(experts, "native_sm120", False) or getattr(experts, "_routed_kernels", None) != torch.uint8: return shapes = getattr(experts, "_nvfp4_scale_shapes", {}) for name in ("w13", "w2"): weight = getattr(experts, name + "_weight", None) scale = getattr(experts, name + "_scale", None) if weight is None or scale is None or name not in shapes or not weight.is_cuda or not weight.numel(): continue e, n, half_k = weight.shape k = half_k * 2 if tuple(scale.shape) == shapes[name]: continue # not swizzled (yet): leave stock if getattr(scale, ATTR, None) is not None: reencode(scale) # post_load_weights after a reload: keep the buffers captured graphs hold continue try: codes, bases, stride = encode.encode(torch, scale.data, n, k) except encode.ScodesError as exc: _log(f"{name} {tuple(weight.shape)} stays stock: {exc}") setattr(scale, ATTR, None) continue setattr(scale, ATTR, (codes, bases, stride, n, k)) STATE["encoded"].append((name, e, n, k, scale.numel(), codes.numel() + bases.numel())) if any(getattr(getattr(experts, nm + "_scale", None), ATTR, None) is not None for nm in ("w13", "w2")): # SGLang's direct tensor updates skip _load_shard/post_load_weights and would leave stale codes. experts._direct_weight_update_error = ( "inkling_scodes: NVFP4 expert scales are mirrored as scale codes; direct weight updates would " "leave them stale (reload through load_weights or run without INKLING_SCODES)") from . import kernel
kernel.module() # build/load the JIT module now, never during graph capture kernel.prepare(torch, scale.device)
def reencode(scale): """After an in-place reload of a coded scale: re-encode into the SAME code/base buffers (graph addresses).""" import torch
from . import encode
codes, bases, stride, n, k = getattr(scale, ATTR) try: new_codes, new_bases, new_stride = encode.encode(torch, scale.data, n, k) except encode.ScodesError as exc: # Graphs may already embed the old codes; running on would silently use stale scales. _log(f"FATAL reloaded scales cannot be coded ({exc}); restart without INKLING_SCODES") raise SystemExit(78) codes.copy_(new_codes) bases.copy_(new_bases)
def _wrap_moe(module): cls = getattr(module, "Inkling2Experts", None) if cls is None: raise PatchError("inkling_scodes: Inkling2Experts is missing") swz = getattr(cls, "swizzle_nvfp4_scales", None) load = getattr(cls, "_load_shard", None) if not callable(swz) or not callable(load): raise PatchError("inkling_scodes: Inkling2Experts.swizzle_nvfp4_scales/_load_shard missing") if getattr(swz, MARK, False): return
def swizzle_nvfp4_scales(self, *args, **kwargs): out = swz(self, *args, **kwargs) encode_experts(self) return out
def _load_shard(self, param, *args, **kwargs): out = load(self, param, *args, **kwargs) if getattr(param, ATTR, None) is not None: reencode(param) # captured graphs hold the code addresses: rewrite them in place return out
for f, inner in ((swizzle_nvfp4_scales, swz), (_load_shard, load)): f.__wrapped__ = inner setattr(f, MARK, True) cls.swizzle_nvfp4_scales = swizzle_nvfp4_scales cls._load_shard = _load_shard _wrap_verify_scope(module)
def _wrap_verify_scope(module): from functools import wraps
cls = module.Inkling2MoE forward = cls.forward
@wraps(forward) def scoped_forward(self, x, forward_batch=None, combine=True): prior = STATE["n343_c1_verify"] mode = getattr(forward_batch, "forward_mode", None) STATE["n343_c1_verify"] = ( mode is not None and mode.is_target_verify() and forward_batch.batch_size == 1 ) try: return forward(self, x, forward_batch=forward_batch, combine=combine) finally: STATE["n343_c1_verify"] = prior
cls.forward = scoped_forward
def _wrap_gemm(module): stock = getattr(module, "nvfp4_expert_matmul", None) if not callable(stock): raise PatchError("inkling_scodes: nvfp4_expert_matmul is missing") if getattr(stock, MARK, False): return if not callable(getattr(module, "_tiles", None)): raise PatchError("inkling_scodes: _tiles is missing") check = _on(os.environ.get("INKLING_SCODES_CHECK", "1"))
from . import kernel
def nvfp4_expert_matmul(values, scales, weight, weight_scales, offsets, tokens): import torch
if not STATE["n343_c1_verify"] or not (0 < tokens <= 8): return stock(values, scales, weight, weight_scales, offsets, tokens) coded = getattr(weight_scales, ATTR, None) if coded is None or not values.shape[0]: STATE["stock_calls"] += 1 return stock(values, scales, weight, weight_scales, offsets, tokens) codes, bases, stride, n, k = coded experts, wn, packed_width = weight.shape stock_tactic = module._tiles(tokens=tokens, width=packed_width * 2) swap_ab, tile_n, tile_k = stock_tactic if not swap_ab and tokens <= SWAP_OVERRIDE_MAX_TOKENS: # The coded kernel exists only with swap_ab; at decode sizes swap 32x256 is the bit-identical, faster # choice (inkling_moe2 measurements). The self-check compares against the stock non-swap call. tile_n, tile_k = SWAP_OVERRIDE_TILE elif not swap_ab: STATE["stock_calls"] += 1 return stock(values, scales, weight, weight_scales, offsets, tokens) if (tile_n, tile_k) not in kernel.TILES or (wn, packed_width * 2) != (n, k): STATE["stock_calls"] += 1 return stock(values, scales, weight, weight_scales, offsets, tokens) # Checked per (shape, stock tactic, coded tile): an override of a non-swap tactic is qualified separately. key = (n, k, tuple(stock_tactic), (tile_n, tile_k)) done = STATE["checked"].get(key, 0) ref = None if check and done < CHECKS_PER_CONFIG: if torch.cuda.is_current_stream_capturing(): if done == 0: STATE["stock_calls"] += 1 return stock(values, scales, weight, weight_scales, offsets, tokens) else: ref = stock(values, scales, weight, weight_scales, offsets, tokens) out = torch.empty((values.shape[0], n), dtype=torch.bfloat16, device=values.device) kernel.grouped_gemm(torch, values, scales, weight, weight_scales, offsets, codes, bases, stride, tile_n, tile_k, out) STATE["calls"] += 1 if key not in STATE["n343_captured"] and torch.cuda.is_current_stream_capturing(): _log(f"n343 captured c1 verify scale codes: n={n} k={k} tile {tile_n}x{tile_k}") STATE["n343_captured"].add(key) if ref is not None: if not torch.equal(ref.view(torch.int16), out.view(torch.int16)): bad = int((ref.view(torch.int16) != out.view(torch.int16)).sum()) _log(f"FATAL self-check: {bad} of {out.numel()} outputs differ from stock at rows " f"{values.shape[0]}, n/k/tile {key}") raise SystemExit(78) STATE["checked"][key] = done + 1 return out
nvfp4_expert_matmul.__wrapped__ = stock setattr(nvfp4_expert_matmul, MARK, True) module.nvfp4_expert_matmul = nvfp4_expert_matmul
def install(root=None): """Activate when INKLING_SCODES is on. Idempotent; raises RuntimeError on a changed patch target.""" if STATE["installed"]: return STATE["installed"] = True if not _on(os.environ.get("INKLING_SCODES", "")): return check_sources(root) from . import _hook
_hook.when_imported(MOE_MODULE, _wrap_moe) _hook.when_imported(GEMM_MODULE, _wrap_gemm) _log("enabled: NVFP4 expert scale codes (5-bit, row base), self-check " + ("on" if _on(os.environ.get("INKLING_SCODES_CHECK", "1")) else "OFF"))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)1234567891011121314151617181920212223242526272829303132333435// inkling_scodes: launch arguments shared by the binding and the per-tile instantiations.#pragma once
#include <cstddef>#include <cstdint>
#include <cuda_runtime.h>
namespace inkling_scodes {
struct ScodesArgs { void* int_buffer; size_t int_buffer_bytes; void* float_buffer; size_t float_buffer_bytes; void* weight; // [experts][n][k/2] packed NVFP4 (kernel A) void* act; // [cum_m][k/2] packed NVFP4 (kernel B) void* weight_scales; // stock swizzled UE4M3 weight scales (escape words read them; SFA tensormap unused) void* act_scales; // swizzled UE4M3 activation scales void* out; // [cum_m][n] BF16 int* m_indptr; // [experts + 1] uint8_t const* codes; // scale codes uint8_t const* bases; // row bases [experts][n] int64_t expert_stride; // bytes of codes per expert int n; int k; int num_groups; cudaStream_t stream; int device_id;};
template <int TileN, int TileK>cudaError_t ScodesGroupGemm(ScodesArgs const& a);
} // namespace inkling_scodes12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758// inkling_scodes: TVM-FFI entry of the scale-code NVFP4 grouped GEMM (swap_ab=true, tile_m=128, BF16 out).#include <cstdint>
#include "tvm_ffi_utils.h"
#include "scodes_args.h"
// A: activations [cum_m, k/2] u8; B: weights [E, n, k/2] u8; SFA: activation scales (swizzled, u8);// SFB: stock swizzled weight scales [E, n * k/16] u8 (escape words are read from them; validated in kernel.py);// D: [cum_m, n] bf16; m_indptr: [E + 1] int32; codes / bases: encode.py layout.void ScodesGroupGemmNVFP4(TensorView int_workspace_buffer, TensorView float_workspace_buffer, TensorView A, TensorView B, TensorView SFA, TensorView SFB, TensorView D, TensorView m_indptr, TensorView codes, TensorView bases, int64_t n, int64_t k, int64_t tile_n, int64_t tile_k, int64_t expert_stride) { int device_id = float_workspace_buffer.device().device_id; ffi::CUDADeviceGuard device_guard(device_id); auto stream = get_stream(float_workspace_buffer.device()); int num_groups = m_indptr.size(0) - 1; TVM_FFI_ICHECK(B.size(0) == num_groups) << "weights have " << B.size(0) << " experts, m_indptr " << num_groups; TVM_FFI_ICHECK(bases.numel() == static_cast<int64_t>(num_groups) * n) << "bases must be [experts, n]"; TVM_FFI_ICHECK(SFB.numel() * get_element_size(SFB) == static_cast<int64_t>(num_groups) * n * (k / 16)) << "stock weight scales must be [experts, n * k/16] bytes"; TVM_FFI_ICHECK(codes.numel() >= static_cast<int64_t>(num_groups) * expert_stride + 640) << "codes buffer too small (needs experts * expert_stride + 640 tail bytes)"; TVM_FFI_ICHECK(expert_stride == (n / 128) * (k / 128) * 640) << "bad expert_stride"; inkling_scodes::ScodesArgs a{}; a.int_buffer = int_workspace_buffer.data_ptr(); a.int_buffer_bytes = get_element_size(int_workspace_buffer) * int_workspace_buffer.size(0); a.float_buffer = float_workspace_buffer.data_ptr(); a.float_buffer_bytes = get_element_size(float_workspace_buffer) * float_workspace_buffer.size(0); a.weight = B.data_ptr(); a.act = A.data_ptr(); a.weight_scales = SFB.data_ptr(); a.act_scales = SFA.data_ptr(); a.out = D.data_ptr(); a.m_indptr = static_cast<int*>(m_indptr.data_ptr()); a.codes = static_cast<uint8_t const*>(codes.data_ptr()); a.bases = static_cast<uint8_t const*>(bases.data_ptr()); a.expert_stride = expert_stride; a.n = static_cast<int>(n); a.k = static_cast<int>(k); a.num_groups = num_groups; a.stream = stream; a.device_id = device_id; cudaError_t err = cudaErrorInvalidValue;#define INKLING_SCODES_CASE(TN, TK) \ if (tile_n == TN && tile_k == TK) err = inkling_scodes::ScodesGroupGemm<TN, TK>(a); INKLING_SCODES_CASE(32, 128) INKLING_SCODES_CASE(32, 256) INKLING_SCODES_CASE(64, 128) INKLING_SCODES_CASE(64, 256) INKLING_SCODES_CASE(128, 128)#undef INKLING_SCODES_CASE TVM_FFI_ICHECK(err == cudaSuccess) << "scodes grouped GEMM failed (tile " << tile_n << "x" << tile_k << "): " << cudaGetErrorString(err);}
TVM_FFI_DLL_EXPORT_TYPED_FUNC(scodes_group_gemm_nvfp4, ScodesGroupGemmNVFP4);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247/* * inkling_scodes: FlashInfer 0.7.4's SM120 NVFP4 grouped GEMM (include/flashinfer/gemm/ * group_gemm_nvfp4_groupwise_sm120.cuh, Apache-2.0, Copyright (c) 2026 by FlashInfer team), reduced to the * swap_ab=true, tile_m=128, BF16-output, no-alpha configuration SGLang's inkling2 SM120 path runs, with the * collective mainloop swapped for the scale-code one (scodes_sm120_mma_array.hpp). Everything else (builder * choices, schedule, epilogue, argument kernel, launch with PDL) is the stock code path. */#pragma once
#include <flashinfer/allocator.h>#include <flashinfer/cutlass_utils.cuh>
#include "scodes_args.h"#include "scodes_sm120_mma_array.hpp"
namespace inkling_scodes {
using namespace cute;
template <class T>struct WithScodes;
// Same collective as the builder's, with TransformA replaced by the tag that selects the scale-code mainloop.template <class DP, class TS, class EPA, class SPA, class EPB, class SPB, class TM, class GA, class SLA, class SCA, class TA, class GB, class SLB, class SCB, class TB>struct WithScodes<cutlass::gemm::collective::CollectiveMma<DP, TS, EPA, SPA, EPB, SPB, TM, GA, SLA, SCA, TA, GB, SLB, SCB, TB>> { static_assert(cute::is_same_v<TA, cute::identity>, "unexpected TransformA from the SM120 builder"); using type = cutlass::gemm::collective::CollectiveMma<DP, TS, EPA, SPA, EPB, SPB, TM, GA, SLA, SCA, ScodesTransformA, GB, SLB, SCB, TB>;};
template <typename T>__host__ __device__ __forceinline__ constexpr T* safe_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 branch (weights are the kernel's A operand).template <int ScaleGranularity, typename ScaleConfig, typename ElementA, typename ElementB, typename ElementSFA, typename ElementSFB, typename ElementD, typename ProblemShape, typename StrideA, typename StrideB, typename StrideD, typename LayoutSFA, typename LayoutSFB>__global__ void scodes_group_gemm_args(ElementA* A, ElementB* B, ElementSFA* SFA, ElementSFB* SFB, ElementD* D, int* m_indptr, int n, int k, int num_groups, ProblemShape* problem_sizes, const ElementA** A_ptr, const ElementB** B_ptr, const ElementSFA** SFA_ptr, const ElementSFB** 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);#if (__CUDACC_VER_MAJOR__ >= 12 && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900)) asm volatile("griddepcontrol.wait;"); asm volatile("griddepcontrol.launch_dependents;");#endif 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] = ProblemShape(n, m, k); stride_A[i] = cutlass::make_cute_packed_stride(StrideA{}, {n, k, 1}); stride_B[i] = cutlass::make_cute_packed_stride(StrideB{}, {m, k, 1}); stride_D[i] = cutlass::make_cute_packed_stride(StrideD{}, {n, m, 1}); B_ptr[i] = safe_inc_ptr(B, static_cast<size_t>(m_offset) * static_cast<size_t>(k)); A_ptr[i] = safe_inc_ptr(A, static_cast<size_t>(i) * static_cast<size_t>(n) * static_cast<size_t>(k)); D_ptr[i] = safe_inc_ptr(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>(sf_n), static_cast<int>(m), static_cast<int>(swizzled_k), 1)); // Stock weight scales: the SFA tensormap is never used for a copy; escape words are read from here. SFA_ptr[i] = safe_inc_ptr(SFA, static_cast<size_t>(i) * sf_n * sf_k); layout_SFB[i] = ScaleConfig::tile_atom_to_shape_SFB( make_shape(static_cast<int>(sf_n), static_cast<int>(m), static_cast<int>(swizzled_k), 1)); SFB_ptr[i] = safe_inc_ptr(SFB, sf_m_offset * sf_k);}
template <int TileN, int TileK>cudaError_t ScodesGroupGemm(ScodesArgs const& a) { constexpr int TileM = 128; using DTypeIn = cutlass::float_e2m1_t; using ElementA = DTypeIn; using ElementB = DTypeIn; using ElementSFA = cutlass::float_ue4m3_t; using ElementSFB = cutlass::float_ue4m3_t; using ElementD = cutlass::bfloat16_t; using ElementC = void; using LayoutC = void; 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; if (a.num_groups == 0) { return cudaSuccess; } if (a.k % std::max(AlignmentA, AlignmentB) != 0 || a.n % AlignmentD != 0 || a.k % 128 != 0 || a.n % 128 != 0) { return cudaErrorInvalidValue; } 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::ColumnMajor; // SwapAB using ClusterShape = Shape<_1, _1, _1>; using EpilogueSchedule = cutlass::epilogue::collective::EpilogueScheduleAuto; using ThreadBlockShape = Shape<Int<TileM>, Int<TileN>, Int<TileK>>; using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< cutlass::arch::Sm120, cutlass::arch::OpClassBlockScaledTensorOp, ThreadBlockShape, ClusterShape, cutlass::epilogue::collective::EpilogueTileAuto, ElementAccumulator, ElementCompute, ElementC, LayoutD*, AlignmentD, ElementD, LayoutD*, AlignmentD, EpilogueSchedule>::CollectiveOp; using MainloopSchedule = cutlass::gemm::collective::KernelScheduleAuto; using StockMainloop = 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))>, MainloopSchedule>::CollectiveOp; using CollectiveMainloop = typename WithScodes<StockMainloop>::type; static_assert(sizeof(typename CollectiveMainloop::SharedStorage) <= sizeof(typename StockMainloop::SharedStorage), "scodes mainloop must not need more shared memory than the stock one"); using GemmKernel = cutlass::gemm::kernel::GemmUniversal<ProblemShape, CollectiveMainloop, CollectiveEpilogue, void>; using Gemm = cutlass::gemm::device::GemmUniversalAdapter<GemmKernel>; 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, "NVFP4 scale granularity must be 16");
int const num_groups = a.num_groups; flashinfer::AlignedAllocator allocator(a.int_buffer, a.int_buffer_bytes); auto problem_sizes = allocator.aligned_alloc<typename ProblemShape::UnderlyingProblemShape>( num_groups * sizeof(typename ProblemShape::UnderlyingProblemShape), 16, "scodes_problem_sizes"); auto A_ptr = allocator.aligned_alloc<const typename Gemm::ElementA*>( num_groups * sizeof(const typename Gemm::ElementA*), 16, "scodes_A_ptr"); auto B_ptr = allocator.aligned_alloc<const typename Gemm::ElementB*>( num_groups * sizeof(const typename Gemm::ElementB*), 16, "scodes_B_ptr"); auto D_ptr = allocator.aligned_alloc<typename Gemm::EpilogueOutputOp::ElementOutput*>( num_groups * sizeof(typename Gemm::EpilogueOutputOp::ElementOutput*), 16, "scodes_D_ptr"); auto SFA_ptr = allocator.aligned_alloc<const ElementSFA*>(num_groups * sizeof(const ElementSFA*), 16, "scodes_SFA_ptr"); auto SFB_ptr = allocator.aligned_alloc<const ElementSFB*>(num_groups * sizeof(const ElementSFB*), 16, "scodes_SFB_ptr"); auto stride_A = allocator.aligned_alloc<StrideA>(num_groups * sizeof(StrideA), 16, "scodes_stride_A"); auto stride_B = allocator.aligned_alloc<StrideB>(num_groups * sizeof(StrideB), 16, "scodes_stride_B"); auto stride_D = allocator.aligned_alloc<StrideD>(num_groups * sizeof(StrideD), 16, "scodes_stride_D"); auto layout_SFA = allocator.aligned_alloc<LayoutSFA>(num_groups * sizeof(LayoutSFA), 16, "scodes_layout_SFA"); auto layout_SFB = allocator.aligned_alloc<LayoutSFB>(num_groups * sizeof(LayoutSFB), 16, "scodes_layout_SFB");
int num_threads = std::min(num_groups, 1024); int num_blocks = (num_groups + num_threads - 1) / num_threads; cudaLaunchConfig_t config; config.gridDim = num_blocks; config.blockDim = num_threads; config.dynamicSmemBytes = 0; config.stream = a.stream; cudaLaunchAttribute attrs[1]; attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; attrs[0].val.programmaticStreamSerializationAllowed = true; config.numAttrs = 1; config.attrs = attrs; auto prepare_args_kernel = scodes_group_gemm_args<ScaleGranularity, ScaleConfig, ElementA, ElementB, ElementSFA, ElementSFB, ElementD, typename ProblemShape::UnderlyingProblemShape, StrideA, StrideB, StrideD, LayoutSFA, LayoutSFB>; cudaError_t err = cudaLaunchKernelEx( &config, prepare_args_kernel, static_cast<ElementA*>(a.weight), static_cast<ElementB*>(a.act), static_cast<ElementSFA*>(a.weight_scales), static_cast<ElementSFB*>(a.act_scales), static_cast<ElementD*>(a.out), a.m_indptr, a.n, a.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); if (err != cudaSuccess) { return err; }
thread_local int last_device_id = -1; thread_local int sm_count = 0; if (last_device_id != a.device_id) { last_device_id = a.device_id; sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(); } cutlass::KernelHardwareInfo hw_info; hw_info.device_id = a.device_id; hw_info.sm_count = 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}; arguments.mainloop.scodes_codes = a.codes; arguments.mainloop.scodes_bases = a.bases; arguments.mainloop.scodes_expert_stride = a.expert_stride; arguments.mainloop.scodes_chunks = a.k / 128; arguments.mainloop.scodes_rows = a.n; 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}; Gemm gemm; size_t workspace_size = Gemm::get_workspace_size(arguments); flashinfer::AlignedAllocator float_allocator(a.float_buffer, a.float_buffer_bytes); auto workspace_ptr = float_allocator.aligned_alloc<void>(workspace_size, 16, "scodes_float_workspace"); if (gemm.can_implement(arguments) != cutlass::Status::kSuccess) { return cudaErrorInvalidValue; } if (gemm.initialize(arguments, workspace_ptr) != cutlass::Status::kSuccess) { return cudaErrorUnknown; } if (gemm.run(a.stream, /*cuda_adapter=*/nullptr, /*launch_with_pdl=*/true) != cutlass::Status::kSuccess) { return cudaErrorLaunchFailure; } return cudaSuccess;}
} // namespace inkling_scodes
#define INKLING_SCODES_INSTANTIATE(TN, TK) \ template cudaError_t inkling_scodes::ScodesGroupGemm<TN, TK>(inkling_scodes::ScodesArgs const&);1234// inkling_scodes: one tile configuration per translation unit (parallel JIT build).#include "scodes_group_gemm.cuh"
INKLING_SCODES_INSTANTIATE(128, 128)1234// inkling_scodes: one tile configuration per translation unit (parallel JIT build).#include "scodes_group_gemm.cuh"
INKLING_SCODES_INSTANTIATE(32, 128)1234// inkling_scodes: one tile configuration per translation unit (parallel JIT build).#include "scodes_group_gemm.cuh"
INKLING_SCODES_INSTANTIATE(32, 256)1234// inkling_scodes: one tile configuration per translation unit (parallel JIT build).#include "scodes_group_gemm.cuh"
INKLING_SCODES_INSTANTIATE(64, 128)1234// inkling_scodes: one tile configuration per translation unit (parallel JIT build).#include "scodes_group_gemm.cuh"
INKLING_SCODES_INSTANTIATE(64, 256)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333/*************************************************************************************************** * Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/
// inkling_scodes: a copy of CUTLASS's cutlass/gemm/collective/sm120_blockscaled_mma_array_tma.hpp (as shipped in// FlashInfer 0.7.4) whose A-operand block scales (SFA) are stored as scale codes. Changes, all marked "scodes":// - a partial specialization selected by TransformA == inkling_scodes::ScodesTransformA (the stock specialization// stays untouched and is still picked for every other GEMM);// - the producer bulk-copies a 640-byte code chunk per 128x128 (M x K) block instead of the 1024-byte SFA TMA box;// - the consumer warps expand the codes of each stage into ONE shared SFA buffer laid out exactly as the stock TMA// would have written it (row base + 5-bit code = the original E4M3 byte), then run the stock smem->rmem copies and// MMAs unchanged, so the MMA sees bit-identical operands.// Code chunk format (encode.py): for block (expert e, m-tile mt, k-chunk c) 5 bit-planes of 128 bytes; plane b,// nibble w (byte w/2, low nibble for even w) holds bit b of the codes of SFA word w (4 consecutive scale bytes of one// row in the CUTLASS 128x4 atom order: w = kg*128 + r32*4 + r4, row = r4*32 + r32). Row bases are one byte per row;// bit 7 marks an escape row whose code 31 means "use the stock scale word" (read from the resident stock scales).#pragma once
#include "cutlass/cutlass.h"#include "cutlass/gemm/gemm.h"#include "cutlass/pipeline/pipeline.hpp"#include "cutlass/gemm/dispatch_policy.hpp"#include "cutlass/detail/dependent_false.hpp"#include "cutlass/detail/sm100_blockscaled_layout.hpp"#include "cutlass/trace.h"#include "cutlass/numeric_types.h"
#include "cute/arch/cluster_sm90.hpp"#include "cute/arch/copy_sm90.hpp"#include "cute/atom/mma_atom.hpp"#include "cute/algorithm/functional.hpp"#include "cute/algorithm/gemm.hpp"#include "cute/numeric/arithmetic_tuple.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "cute/arch/copy_sm90_tma.hpp"#include "cutlass/arch/barrier.h"
namespace inkling_scodes {// Tag type: CollectiveMma<..., TransformA = ScodesTransformA, ...> selects the scale-code mainloop below.struct ScodesTransformA {};constexpr int kChunkBytes = 640; // 5 planes x 128 bytes per 128 rows x 128 K (= 8 scales per row)constexpr int kChunkWords = 256; // decoded SFA words (4 bytes) per chunk} // namespace inkling_scodes
namespace cutlass::gemm::collective {using namespace cute;
/////////////////////////////////////////////////////////////////////////////////////////////////
template < int Stages, int SchedulerPipelineStageCount, class ClusterShape, class KernelScheduleType, class TileShape_, class ElementPairA_, class StridePairA_, class ElementPairB_, class StridePairB_, class TiledMma_, class GmemTiledCopyPairA_, class SmemLayoutAtomsA_, class SmemCopyAtomsA_, class GmemTiledCopyPairB_, class SmemLayoutAtomsB_, class SmemCopyAtomsB_, class TransformB_>struct CollectiveMma< MainloopSm120ArrayTmaWarpSpecializedBlockScaled<Stages, SchedulerPipelineStageCount, ClusterShape, KernelScheduleType>, TileShape_, ElementPairA_, StridePairA_, ElementPairB_, StridePairB_, TiledMma_, GmemTiledCopyPairA_, SmemLayoutAtomsA_, SmemCopyAtomsA_, inkling_scodes::ScodesTransformA, // scodes: selects this specialization GmemTiledCopyPairB_, SmemLayoutAtomsB_, SmemCopyAtomsB_, TransformB_> { // // Type Aliases // using DispatchPolicy = MainloopSm120ArrayTmaWarpSpecializedBlockScaled<Stages, SchedulerPipelineStageCount, ClusterShape, KernelScheduleType>; using TileShape = TileShape_; using ElementPairA = ElementPairA_; using ElementPairB = ElementPairB_; using StridePairA = StridePairA_; using StridePairB = StridePairB_;
static_assert(cute::is_same_v<remove_cvref_t<decltype(get<1>(ElementPairA{}))>, remove_cvref_t<decltype(get<1>(ElementPairB{}))>>, "SFA and SFB data types should be the same");
using RuntimeDataTypeA = void*; using RuntimeDataTypeB = void*;
// A and B matrices using ElementA = remove_cvref_t<decltype(get<0>(ElementPairA{}))>; using StrideA = remove_cvref_t<decltype(get<0>(StridePairA{}))>; using InternalStrideA = cute::remove_pointer_t<StrideA>;
using ElementB = remove_cvref_t<decltype(get<0>(ElementPairB{}))>; using StrideB = remove_cvref_t<decltype(get<0>(StridePairB{}))>; using InternalStrideB = cute::remove_pointer_t<StrideB>;
// SFA and SFB using ElementSF = remove_cvref_t<decltype(get<1>(ElementPairA{}))>; using LayoutSFA = remove_cvref_t<decltype(get<1>(StridePairA{}))>; using LayoutSFB = remove_cvref_t<decltype(get<1>(StridePairB{}))>; using InternalLayoutSFA = cute::remove_pointer_t<LayoutSFA>; using InternalLayoutSFB = cute::remove_pointer_t<LayoutSFB>;
using ArrayElementA = ElementA; using ArrayElementB = ElementB;
using TiledMma = TiledMma_; using CtaShape_MNK = decltype(shape_div(TileShape{}, ClusterShape{})); using ElementAccumulator = typename TiledMma::ValTypeC;
static constexpr int SFVecSize = TiledMma::Traits::SFVecSize; using Sm1xxBlkScaledConfig = cutlass::detail::Sm1xxBlockScaledConfig<SFVecSize>;
// Gmem copies using GmemTiledCopyPairA = GmemTiledCopyPairA_; using GmemTiledCopyPairB = GmemTiledCopyPairB_; using GmemTiledCopyA = remove_cvref_t<decltype(get<0>(GmemTiledCopyPairA{}))>; using GmemTiledCopySFA = remove_cvref_t<decltype(get<1>(GmemTiledCopyPairA{}))>; using GmemTiledCopyB = remove_cvref_t<decltype(get<0>(GmemTiledCopyPairB{}))>; using GmemTiledCopySFB = remove_cvref_t<decltype(get<1>(GmemTiledCopyPairB{}))>;
// Smem copies using SmemLayoutAtomsA = SmemLayoutAtomsA_; using SmemLayoutAtomsB = SmemLayoutAtomsB_;
using SmemLayoutAtomA = remove_cvref_t<decltype(get<0>(SmemLayoutAtomsA{}))>; using SmemLayoutAtomSFA = remove_cvref_t<decltype(get<1>(SmemLayoutAtomsA{}))>; using SmemLayoutAtomB = remove_cvref_t<decltype(get<0>(SmemLayoutAtomsB{}))>; using SmemLayoutAtomSFB = remove_cvref_t<decltype(get<1>(SmemLayoutAtomsB{}))>;
using SmemCopyAtomsA = SmemCopyAtomsA_; using SmemCopyAtomsB = SmemCopyAtomsB_;
using SmemCopyAtomA = remove_cvref_t<decltype(get<0>(SmemCopyAtomsA{}))>; using SmemCopyAtomSFA = remove_cvref_t<decltype(get<1>(SmemCopyAtomsA{}))>;
using SmemCopyAtomB = remove_cvref_t<decltype(get<0>(SmemCopyAtomsB{}))>; using SmemCopyAtomSFB = remove_cvref_t<decltype(get<1>(SmemCopyAtomsB{}))>;
using TransformA = cute::identity; // scodes: the tag is not a transform using TransformB = TransformB_;
using ArchTag = typename DispatchPolicy::ArchTag;
static constexpr int ThreadCount = size(TiledMma{});
using MainloopPipeline = cutlass::PipelineTmaAsync<DispatchPolicy::Stages>;
using PipelineParams = typename MainloopPipeline::Params; using PipelineState = typename cutlass::PipelineState<DispatchPolicy::Stages>;
// One threads per CTA are producers (1 for operand tile) static constexpr int NumProducerThreadEvents = 1;
static_assert(rank(SmemLayoutAtomA{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); static_assert((size<0>(TileShape{}) % size<0>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtom must evenly divide tile shape."); static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtom must evenly divide tile shape.");
static_assert(rank(SmemLayoutAtomB{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); static_assert((size<1>(TileShape{}) % size<0>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtom must evenly divide tile shape."); static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtom must evenly divide tile shape.");
static_assert(not cute::is_void_v<SmemCopyAtomA>, "SM120 mainloop must specify a copy atom for A operand smem->rmem reads."); static_assert(not cute::is_void_v<SmemCopyAtomB>, "SM120 mainloop must specify a copy atom for B operand smem->rmem reads.");
// Tile along modes in a way that maximizes the TMA box size. using SmemLayoutA = decltype(tile_to_shape( SmemLayoutAtomA{}, make_shape(shape<0>(TileShape{}), shape<2>(TileShape{}), Int<DispatchPolicy::Stages>{}), conditional_t< ::cutlass::gemm::detail::is_major<0,StrideA>(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); using SmemLayoutB = decltype(tile_to_shape( SmemLayoutAtomB{}, make_shape(shape<1>(TileShape{}), shape<2>(TileShape{}), Int<DispatchPolicy::Stages>{}), conditional_t< ::cutlass::gemm::detail::is_major<0,StrideB>(), Step<_2,_1,_3>, Step<_1,_2,_3>>{}));
// SmemLayoutAtomSFA and SmemLayoutAtomSFB are for whole CTA tiles. We add the number of pipeline stages here. // The number of pipeline stages is the same as the number of pipeline stages from AB Load <-> MainLoop using SmemLayoutSFA = decltype(make_layout( append(shape(SmemLayoutAtomSFA{}), Int<DispatchPolicy::Stages>{}), append(stride(SmemLayoutAtomSFA{}), size(filter_zeros(SmemLayoutAtomSFA{}))) ));
using SmemLayoutSFB_ = decltype(make_layout( append(shape(SmemLayoutAtomSFB{}), Int<DispatchPolicy::Stages>{}), append(stride(SmemLayoutAtomSFB{}), size(filter_zeros(SmemLayoutAtomSFB{}))) ));
using TileShapeSFB = cute::conditional_t<size<1>(TileShape{}) < 128, decltype(cute::make_shape( shape<0>(TileShape{}), Int<128>{}, shape<2>(TileShape{}))), TileShape>;
using SmemLayoutSFB = cute::conditional_t<size<1>(TileShape{}) < 128, decltype(cute::logical_divide(SmemLayoutSFB_{}, select<1,2>(TileShape{}))), SmemLayoutSFB_>;
static_assert(rank(SmemLayoutA{}) == 3, "Smem layout must be rank 3."); static_assert(rank(SmemLayoutB{}) == 3, "Smem layout must be rank 3.");
static_assert(DispatchPolicy::Stages >= 2, "Specialization requires Stages set to value 2 or more."); static_assert(not cute::is_base_of<cute::GMMA::DescriptorIterator, typename TiledMma::FrgTypeA>::value && not cute::is_base_of<cute::GMMA::DescriptorIterator, typename TiledMma::FrgTypeB>::value, "MMA atom must source both A and B operands from rmem for this mainloop."); static_assert(cute::is_same_v<GmemTiledCopyA, SM90_TMA_LOAD>, "GmemTiledCopy - invalid SM90 TMA copy atom specified."); static_assert(cute::is_same_v<GmemTiledCopyB, SM90_TMA_LOAD>, "GmemTiledCopy - invalid SM90 TMA copy atom specified.");
static constexpr bool IsF8F6F4 = detail::is_sm120_f8f6f4<TiledMma, ElementA, ElementB>();
// For all other types, cast to size equivalent uint type to avoid any rounding by TMA. using TmaInternalElementA = cute::conditional_t<not IsF8F6F4, ElementA, cute::conditional_t<cute::is_same_v<ElementA, cutlass::float_e2m1_t>, cutlass::detail::float_e2m1_unpacksmem_t, cute::conditional_t<cute::is_same_v<ElementA, cutlass::float_e2m3_t>, cutlass::detail::float_e2m3_unpacksmem_t, cute::conditional_t<cute::is_same_v<ElementA, cutlass::float_e3m2_t>, cutlass::detail::float_e3m2_unpacksmem_t, uint_bit_t<sizeof_bits_v<ElementA>>>>>>;
using TmaInternalElementB = cute::conditional_t<not IsF8F6F4, ElementB, cute::conditional_t<cute::is_same_v<ElementB, cutlass::float_e2m1_t>, cutlass::detail::float_e2m1_unpacksmem_t, cute::conditional_t<cute::is_same_v<ElementB, cutlass::float_e2m3_t>, cutlass::detail::float_e2m3_unpacksmem_t, cute::conditional_t<cute::is_same_v<ElementB, cutlass::float_e3m2_t>, cutlass::detail::float_e3m2_unpacksmem_t, uint_bit_t<sizeof_bits_v<ElementB>>>>>>;
using SmemAllocTypeA = cute::conditional_t<IsF8F6F4, uint8_t, typename TiledMma::ValTypeA>; using SmemAllocTypeB = cute::conditional_t<IsF8F6F4, uint8_t, typename TiledMma::ValTypeB>;
// scodes: the A operand is the expert weight (swap_ab); one CTA tile is 128 weight rows, and every 128 K of it // carries one 640-byte code chunk instead of 1024 bytes of SFA. static_assert(size<0>(TileShape{}) == 128, "scodes: tile M must be 128 (one row block of the 128x4 SF atom)"); // 128 or 256 only: a stage then overruns K by at most one chunk, which the 640-byte tail of the codes covers. static_assert(size<2>(TileShape{}) == 128 || size<2>(TileShape{}) == 256, "scodes: tile K must be 128 or 256"); static_assert(cute::is_same_v<ElementSF, cutlass::float_ue4m3_t>, "scodes: NVFP4 (UE4M3) scales only"); static constexpr int ScodesChunksPerStage = size<2>(TileShape{}) / 128; static constexpr int ScodesStageBytes = ScodesChunksPerStage * inkling_scodes::kChunkBytes; static_assert(cosize(take<0,2>(SmemLayoutAtomSFA{})) == ScodesChunksPerStage * inkling_scodes::kChunkWords * 4, "scodes: unexpected SFA smem tile size"); static_assert(size(TiledMma{}) == inkling_scodes::kChunkWords, "scodes: the decode assigns one SFA word per chunk to each of the 256 consumer threads");
// Set the bytes transferred in this TMA transaction (may involve multiple issues) static constexpr uint32_t TmaTransactionBytesMK = static_cast<uint32_t>( ScodesStageBytes + cutlass::bits_to_bytes(size(take<0,2>(SmemLayoutA{})) * sizeof_bits<ElementA>::value));
static constexpr uint32_t TmaTransactionBytesNK = static_cast<uint32_t>( cutlass::bits_to_bytes(cosize(take<0,2>(SmemLayoutSFB{})) * cute::sizeof_bits_v<ElementSF>) + cutlass::bits_to_bytes(size(take<0,2>(SmemLayoutB{})) * sizeof_bits<ElementB>::value));
static constexpr uint32_t TmaTransactionBytes = TmaTransactionBytesMK + TmaTransactionBytesNK;
struct SharedStorage { struct TensorStorage : cute::aligned_struct<128, _0> { alignas(1024) cute::ArrayEngine<SmemAllocTypeA, cute::cosize_v<SmemLayoutA>> smem_A; alignas(1024) cute::ArrayEngine<SmemAllocTypeB, cute::cosize_v<SmemLayoutB>> smem_B; // scodes: ONE decoded SFA stage (the consumers rewrite it for every k tile), not one per pipeline stage. alignas(16) cute::ArrayEngine<ElementSF, cute::cosize_v<SmemLayoutAtomSFA>> smem_SFA; alignas(16) cute::ArrayEngine<ElementSF, cute::cosize_v<SmemLayoutSFB>> smem_SFB; // scodes: per pipeline stage the code chunks of the A tile, written by cp.async.bulk. alignas(128) cute::ArrayEngine<uint8_t, DispatchPolicy::Stages * ScodesStageBytes> smem_codes; } tensors;
struct TensorMapStorage : cute::aligned_struct<128, _0> { cute::TmaDescriptor smem_tensormap_A; cute::TmaDescriptor smem_tensormap_B; cute::TmaDescriptor smem_tensormap_SFA; cute::TmaDescriptor smem_tensormap_SFB; } tensormaps;
using PipelineStorage = typename MainloopPipeline::SharedStorage; alignas(16) PipelineStorage pipeline_storage; };
using TensorStorage = typename SharedStorage::TensorStorage; using PipelineStorage = typename SharedStorage::PipelineStorage; using TensorMapStorage = typename SharedStorage::TensorMapStorage;
static constexpr bool IsGroupedGemmKernel = !cute::is_same_v<InternalStrideA, StrideA>;
// Host side kernel arguments struct Arguments { ElementA const** ptr_A{nullptr}; StrideA dA{}; ElementB const** ptr_B{nullptr}; StrideB dB{}; ElementSF const** ptr_SFA{nullptr}; LayoutSFA layout_SFA{}; ElementSF const** ptr_SFB{nullptr}; LayoutSFB layout_SFB{}; // scodes: codes [experts][row blocks][chunks][640] (+ tail padding), bases [experts][rows] uint8_t const* scodes_codes{nullptr}; uint8_t const* scodes_bases{nullptr}; int64_t scodes_expert_stride{0}; // bytes of codes per expert = row blocks * chunks * 640 int32_t scodes_chunks{0}; // 128-K chunks per row block = K / 128 int32_t scodes_rows{0}; // weight rows per expert (A rows, a multiple of 128) };
// Device side kernel params struct Params { // Assumption: StrideA is congruent with Problem_MK using TMA_A = decltype(make_tma_copy( GmemTiledCopyA{}, make_tensor(recast_ptr<TmaInternalElementA>(nullptr), repeat_like(InternalStrideA{}, int32_t(0)), InternalStrideA{}), SmemLayoutA{}(_,_,cute::Int<0>{}), make_shape(shape<0>(TileShape{}), shape<2>(TileShape{})), _1{})); // No programmatic multicast // Assumption: StrideB is congruent with Problem_NK using TMA_B = decltype(make_tma_copy( GmemTiledCopyB{}, make_tensor(recast_ptr<TmaInternalElementB>(nullptr), repeat_like(InternalStrideB{}, int32_t(0)), InternalStrideB{}), SmemLayoutB{}(_,_,cute::Int<0>{}), make_shape(shape<1>(TileShape{}), shape<2>(TileShape{})), _1{})); // No programmatic multicast
using TMA_SFA = decltype(make_tma_copy<uint16_t>( GmemTiledCopySFA{}, make_tensor(static_cast<ElementSF const*>(nullptr), InternalLayoutSFA{}), SmemLayoutSFA{}(_,_,cute::Int<0>{}), make_shape(shape<0>(TileShape{}), shape<2>(TileShape{})), _1{})); // No programmatic multicast
using TMA_SFB = decltype(make_tma_copy<uint16_t>( GmemTiledCopySFB{}, make_tensor(static_cast<ElementSF const*>(nullptr), InternalLayoutSFB{}), SmemLayoutSFB{}(_,_,cute::Int<0>{}), make_shape(shape<1>(TileShapeSFB{}), shape<2>(TileShapeSFB{})), _1{})); // No programmatic multicast
TMA_A tma_load_a; TMA_B tma_load_b; TMA_SFA tma_load_sfa; TMA_SFB tma_load_sfb; uint32_t tma_transaction_bytes = TmaTransactionBytes; uint32_t tma_transaction_bytes_mk = TmaTransactionBytesMK; uint32_t tma_transaction_bytes_nk = TmaTransactionBytesNK; cute::TmaDescriptor* tensormaps; ElementA const** ptr_A; StrideA dA; ElementB const** ptr_B; StrideB dB; ElementSF const** ptr_SFA; LayoutSFA layout_SFA; ElementSF const** ptr_SFB; LayoutSFB layout_SFB; uint8_t const* scodes_codes; uint8_t const* scodes_bases; int64_t scodes_expert_stride; int32_t scodes_chunks; int32_t scodes_rows; };
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shapes, Arguments const& args, void* workspace) { (void) workspace; // These tensor shapes (only applicable for grouped gemm) and pointers are only used to create tensormap/tma desc. // These will be replaced with correct values before the initial tma load. auto init_M = int32_t(size<0>(TileShape{})); auto init_N = int32_t(size<1>(TileShape{})); auto init_K = int32_t(size<2>(TileShape{})); auto init_L = 1;
// Batches/Groups are managed by using appropriate pointers to input matrices TmaInternalElementA const* ptr_A_first_batch = nullptr; TmaInternalElementB const* ptr_B_first_batch = nullptr; ElementSF const* ptr_SFA_first_batch = nullptr; ElementSF const* ptr_SFB_first_batch = nullptr;
InternalStrideA stride_a; InternalStrideB stride_b; InternalLayoutSFA layout_SFA; InternalLayoutSFB layout_SFB;
if constexpr (IsGroupedGemmKernel) { // Strides for Grouped Gemm will be replaced prior to the first access regardless. stride_a = InternalStrideA{}; stride_b = InternalStrideB{}; layout_SFA = Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA(cute::make_shape(init_M, init_N, init_K, 1)); layout_SFB = Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA(cute::make_shape(init_M, init_N, init_K, 1)); } else { // Tensor shapes for Ptr-Array are initialized correctly only here. auto problem_shape_MNK = problem_shapes.get_host_problem_shape(0); init_M = get<0>(problem_shape_MNK); init_N = get<1>(problem_shape_MNK); init_K = get<2>(problem_shape_MNK);
stride_a = args.dA; stride_b = args.dB; layout_SFA = args.layout_SFA; layout_SFB = args.layout_SFB; }
Tensor tensor_a = make_tensor(ptr_A_first_batch, make_layout(make_shape(init_M,init_K,init_L), stride_a)); Tensor tensor_b = make_tensor(ptr_B_first_batch, make_layout(make_shape(init_N,init_K,init_L), stride_b)); Tensor tensor_sfa = make_tensor(ptr_SFA_first_batch, layout_SFA); Tensor tensor_sfb = make_tensor(ptr_SFB_first_batch, layout_SFB);
typename Params::TMA_A tma_load_a = make_tma_copy( GmemTiledCopyA{}, tensor_a, SmemLayoutA{}(_,_,cute::Int<0>{}), make_shape(shape<0>(TileShape{}), shape<2>(TileShape{})), _1{}); // No programmatic multicast typename Params::TMA_B tma_load_b = make_tma_copy( GmemTiledCopyB{}, tensor_b, SmemLayoutB{}(_,_,cute::Int<0>{}), make_shape(shape<1>(TileShape{}), shape<2>(TileShape{})), _1{}); // No programmatic multicast
typename Params::TMA_SFA tma_load_sfa = make_tma_copy<uint16_t>( GmemTiledCopySFA{}, tensor_sfa, SmemLayoutSFA{}(_,_,cute::Int<0>{}), make_shape(shape<0>(TileShape{}), shape<2>(TileShape{})), _1{}); // No programmatic multicast
typename Params::TMA_SFB tma_load_sfb = make_tma_copy<uint16_t>( GmemTiledCopySFB{}, tensor_sfb, SmemLayoutSFB{}(_,_,cute::Int<0>{}), make_shape(shape<1>(TileShapeSFB{}), shape<2>(TileShapeSFB{})), _1{}); // No programmatic multicast
return { tma_load_a, tma_load_b, tma_load_sfa, tma_load_sfb, TmaTransactionBytes, TmaTransactionBytesMK, TmaTransactionBytesNK, reinterpret_cast<cute::TmaDescriptor*>(workspace), reinterpret_cast<ArrayElementA const**>(args.ptr_A), args.dA, reinterpret_cast<ArrayElementB const**>(args.ptr_B), args.dB, reinterpret_cast<ElementSF const**>(args.ptr_SFA), args.layout_SFA, reinterpret_cast<ElementSF const**>(args.ptr_SFB), args.layout_SFB, args.scodes_codes, args.scodes_bases, args.scodes_expert_stride, args.scodes_chunks, args.scodes_rows }; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args, int sm_count) { constexpr uint32_t NumInputTensors = 4; constexpr size_t SizeOfCuTensorMap = sizeof(cute::TmaDescriptor); // Allocate gmem space for input tensormaps per each SM, A tensormap copies followed by B tensormap copies return (NumInputTensors * SizeOfCuTensorMap * sm_count); }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
template<class ProblemShape> CUTLASS_HOST_DEVICE static bool can_implement( ProblemShape problem_shapes, [[maybe_unused]] Arguments const& args) {
constexpr int tma_alignment_bits_A = cutlass::detail::get_input_alignment_bits<ElementA, IsF8F6F4>(); constexpr int tma_alignment_bits_B = cutlass::detail::get_input_alignment_bits<ElementB, IsF8F6F4>(); constexpr int min_tma_aligned_elements_A = tma_alignment_bits_A / cutlass::sizeof_bits<ElementA>::value; constexpr int min_tma_aligned_elements_B = tma_alignment_bits_B / cutlass::sizeof_bits<ElementB>::value;
bool implementable = true; if (problem_shapes.is_host_problem_shape_available()) { // Check alignment for all problem sizes for (int i = 0; i < problem_shapes.groups(); i++) { auto problem_shape_MNKL = append<4>(problem_shapes.get_host_problem_shape(i), 1); auto [M,N,K,L] = problem_shape_MNKL; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_A>(cute::make_shape(M,K,L), InternalStrideA{}); implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_B>(cute::make_shape(N,K,L), InternalStrideB{}); } }
if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); } // scodes: codes and bases present, 16-byte aligned codes (cp.async.bulk), whole row blocks and chunks. implementable = implementable && args.scodes_codes != nullptr && args.scodes_bases != nullptr && (reinterpret_cast<uintptr_t>(args.scodes_codes) % 16 == 0) && args.scodes_expert_stride % 16 == 0 && args.scodes_chunks > 0 && args.scodes_rows > 0 && args.scodes_rows % 128 == 0; return implementable; }
// Temporary adhoc partitioning for scaling factors. template <class SFATensor, class Atom, class TiledThr, class TiledPerm> CUTE_HOST_DEVICE constexpr auto thrfrg_SFA(SFATensor&& sfatensor, TiledMMA<Atom, TiledThr, TiledPerm>& mma) { CUTE_STATIC_ASSERT_V(rank(sfatensor) >= Int<2>{});
using AtomShape_MNK = typename Atom::Shape_MNK; using AtomLayoutSFA_TV = typename Atom::Traits::SFALayout;
auto permutation_mnk = TiledPerm{}; auto thr_layout_vmnk = mma.get_thr_layout_vmnk();
// Reorder the tensor for the TiledAtom auto t_tile = make_tile(get<0>(permutation_mnk), get<2>(permutation_mnk)); auto t_tensor = logical_divide(sfatensor, t_tile); // (PermM,PermK)
// Tile the tensor for the Atom auto a_tile = make_tile(make_layout(size<0>(AtomShape_MNK{})), make_layout(size<2>(AtomShape_MNK{}))); auto a_tensor = zipped_divide(t_tensor, a_tile); // ((AtomM,AtomK),(RestM,RestK))
// Transform the Atom mode from (M,K) to (Thr,Val) auto tv_tensor = a_tensor.compose(AtomLayoutSFA_TV{},_); // ((ThrV,FrgV),(RestM,RestK))
// Tile the tensor for the Thread auto thr_tile = make_tile(_, make_tile(make_layout(size<1>(thr_layout_vmnk)), make_layout(size<3>(thr_layout_vmnk)))); auto thr_tensor = zipped_divide(tv_tensor, thr_tile); // ((ThrV,(ThrM,ThrK)),(FrgV,(RestM,RestK)))
return thr_tensor; }
template <class SFBTensor, class Atom, class TiledThr, class TiledPerm> CUTE_HOST_DEVICE constexpr auto thrfrg_SFB(SFBTensor&& sfbtensor, TiledMMA<Atom, TiledThr, TiledPerm>& mma) { CUTE_STATIC_ASSERT_V(rank(sfbtensor) >= Int<2>{});
using AtomShape_MNK = typename Atom::Shape_MNK; using AtomLayoutSFB_TV = typename Atom::Traits::SFBLayout;
auto permutation_mnk = TiledPerm{}; auto thr_layout_vmnk = mma.get_thr_layout_vmnk();
// Reorder the tensor for the TiledAtom auto t_tile = make_tile(get<1>(permutation_mnk), get<2>(permutation_mnk)); auto t_tensor = logical_divide(sfbtensor, t_tile); // (PermN,PermK)
// Tile the tensor for the Atom auto a_tile = make_tile(make_layout(size<1>(AtomShape_MNK{})), make_layout(size<2>(AtomShape_MNK{}))); auto a_tensor = zipped_divide(t_tensor, a_tile); // ((AtomN,AtomK),(RestN,RestK))
// Transform the Atom mode from (M,K) to (Thr,Val) auto tv_tensor = a_tensor.compose(AtomLayoutSFB_TV{},_); // ((ThrV,FrgV),(RestN,RestK))
// Tile the tensor for the Thread auto thr_tile = make_tile(_, make_tile(make_layout(size<2>(thr_layout_vmnk)), make_layout(size<3>(thr_layout_vmnk)))); auto thr_tensor = zipped_divide(tv_tensor, thr_tile); // ((ThrV,(ThrN,ThrK)),(FrgV,(RestN,RestK))) return thr_tensor; }
template <class SFATensor, class ThrMma> CUTE_HOST_DEVICE constexpr auto partition_fragment_SFA(SFATensor&& sfatensor, ThrMma& thread_mma) { using ValTypeSF = typename ThrMma::Atom::Traits::ValTypeSF; auto thr_tensor = make_tensor(static_cast<SFATensor&&>(sfatensor).data(), thrfrg_SFA(sfatensor.layout(),thread_mma)); auto thr_vmnk = thread_mma.thr_vmnk_; auto thr_vmk = make_coord(get<0>(thr_vmnk), make_coord(get<1>(thr_vmnk), get<3>(thr_vmnk))); auto partition_SFA = thr_tensor(thr_vmk, make_coord(_, repeat<rank<1,1>(thr_tensor)>(_))); return make_fragment_like<ValTypeSF>(partition_SFA); }
template <class SFBTensor, class ThrMma> CUTE_HOST_DEVICE constexpr auto partition_fragment_SFB(SFBTensor&& sfbtensor, ThrMma& thread_mma) { using ValTypeSF = typename ThrMma::Atom::Traits::ValTypeSF; auto thr_tensor = make_tensor(static_cast<SFBTensor&&>(sfbtensor).data(), thrfrg_SFB(sfbtensor.layout(),thread_mma)); auto thr_vmnk = thread_mma.thr_vmnk_; auto thr_vnk = make_coord(get<0>(thr_vmnk), make_coord(get<2>(thr_vmnk), get<3>(thr_vmnk))); auto partition_SFB = thr_tensor(thr_vnk, make_coord(_, repeat<rank<1,1>(thr_tensor)>(_))); return make_fragment_like<ValTypeSF>(partition_SFB); }
template<class TiledMma> CUTE_HOST_DEVICE constexpr auto get_layoutSFA_TV(TiledMma& mma) { // (M,K) -> (M,K) auto tile_shape_mnk = tile_shape(mma); auto ref_A = make_layout(make_shape(size<0>(tile_shape_mnk), size<2>(tile_shape_mnk))); auto thr_layout_vmnk = mma.get_thr_layout_vmnk();
// (ThrV,(ThrM,ThrK)) -> (ThrV,(ThrM,ThrN,ThrK)) auto atile = make_tile(_, make_tile(make_layout(make_shape (size<1>(thr_layout_vmnk), size<2>(thr_layout_vmnk)), make_stride( Int<1>{} , Int<0>{} )), _));
// thr_idx -> (ThrV,ThrM,ThrN,ThrK) auto thridx_2_thrid = right_inverse(thr_layout_vmnk); // (thr_idx,val) -> (M,K) return thrfrg_SFA(ref_A, mma).compose(atile, _).compose(thridx_2_thrid, _); }
template<class TiledMma> CUTE_HOST_DEVICE constexpr auto get_layoutSFB_TV(TiledMma& mma) { // (N,K) -> (N,K) auto tile_shape_mnk = tile_shape(mma); auto ref_B = make_layout(make_shape(size<1>(tile_shape_mnk), size<2>(tile_shape_mnk))); auto thr_layout_vmnk = mma.get_thr_layout_vmnk();
// (ThrV,(ThrM,ThrK)) -> (ThrV,(ThrM,ThrN,ThrK)) auto btile = make_tile(_, make_tile(make_layout(make_shape (size<1>(thr_layout_vmnk), size<2>(thr_layout_vmnk)), make_stride( Int<0>{} , Int<1>{} )), _));
// thr_idx -> (ThrV,ThrM,ThrN,ThrK) auto thridx_2_thrid = right_inverse(thr_layout_vmnk); // (thr_idx,val) -> (M,K) return thrfrg_SFB(ref_B, mma).compose(btile, _).compose(thridx_2_thrid, _); }
/// Set up the data needed by this collective for load and mma. /// Returns a tuple of tensors. The collective and the kernel layer have the contract /// Returned tuple must contain at least two elements, with the first two elements being: /// gA_mkl - The tma tensor, A after a local tile so it has shape (BLK_M,BLK_K,m,k,l) /// gB_nkl - The tma tensor, B after a local tile so it has shape (BLK_N,BLK_K,n,k,l) /// The rest of the tensors can be specified as needed by this collective. template <class ProblemShape_MNKL> CUTLASS_DEVICE auto load_init(ProblemShape_MNKL const& problem_shape_MNKL, Params const& params) const { using X = Underscore; // Separate out problem shape for convenience auto [M, N, K, L] = problem_shape_MNKL; const int32_t init_L = 1;
// TMA requires special handling of strides to deal with coord codomain mapping // Represent the full tensors -- get these from TMA Tensor mA_mkl = params.tma_load_a.get_tma_tensor(make_shape(M,K,init_L)); // (m,k,l) Tensor mB_nkl = params.tma_load_b.get_tma_tensor(make_shape(N,K,init_L)); // (n,k,l)
// Represent the full tensor of Scale factors InternalLayoutSFA layout_SFA{}; InternalLayoutSFB layout_SFB{}; if constexpr (IsGroupedGemmKernel) { layout_SFA = params.layout_SFA[0]; layout_SFB = params.layout_SFB[0]; } else { layout_SFA = params.layout_SFA; layout_SFB = params.layout_SFB; }
Tensor mSFA_mkl = params.tma_load_sfa.get_tma_tensor(shape(layout_SFA)); Tensor mSFB_nkl = params.tma_load_sfb.get_tma_tensor(shape(layout_SFB));
// Make tiled views, defer the slice Tensor gA_mkl = local_tile(mA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (BLK_M,BLK_K,m,k,l) Tensor gB_nkl = local_tile(mB_nkl, TileShape{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (BLK_N,BLK_K,n,k,l)
Tensor gSFA_mkl = local_tile(mSFA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (TILE_M,TILE_K,m,k,l) Tensor gSFB_nkl = local_tile(mSFB_nkl, TileShape{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (TILE_N,TILE_K,n,k,l)
// scodes: a fifth element carries the current group (expert) for the code chunk addresses; the kernel only // reads elements 0 and 1 and hands the tuple back to load() and tensors_perform_update(). return cute::make_tuple(gA_mkl, gB_nkl, gSFA_mkl, gSFB_nkl, int32_t(0)); }
/// Perform a collective-scoped matrix multiply-accumulate /// Producer Perspective template < class TensorA, class TensorB, class TensorSFA, class TensorSFB, class TensorMapA, class TensorMapB, class TensorMapSFA, class TensorMapSFB, class KTileIterator, class BlockCoord > CUTLASS_DEVICE void load( Params const& params, MainloopPipeline pipeline, PipelineState smem_pipe_write, cute::tuple<TensorA, TensorB, TensorSFA, TensorSFB, int32_t> const& load_inputs, cute::tuple<TensorMapA, TensorMapB, TensorMapSFA, TensorMapSFB> const& input_tensormaps, BlockCoord const& blk_coord, KTileIterator k_tile_iter, int k_tile_count, int thread_idx, uint32_t block_rank_in_cluster, TensorStorage& shared_tensors) { int lane_predicate = cute::elect_one_sync();
if (lane_predicate) {
Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.begin()), SmemLayoutA{}); // (BLK_M,BLK_K,PIPE) Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.begin()), SmemLayoutB{}); // (BLK_N,BLK_K,PIPE) Tensor sSFB = make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); // (BLK_N,BLK_K,PIPE)
// // Prepare the TMA loads for A, B, SFA and SFB //
auto [gA_mkl, gB_nkl, gSFA_mkl, gSFB_nkl, scodes_group] = load_inputs;
auto block_tma_a = params.tma_load_a.get_slice(0); auto block_tma_b = params.tma_load_b.get_slice(0);
auto block_tma_sfb = params.tma_load_sfb.get_slice(0);
// Partition the inputs based on the current block coordinates. auto [m_coord, n_coord, k_coord, l_coord] = blk_coord;
auto broadcast_n = make_layout( make_shape(Int<size<1>(TileShapeSFB{}) / size<1>(TileShape{})>{}, Int<cute::numeric_limits<int>::max()>{}), make_stride(_0{}, size<1>(TileShapeSFB{}) / size<1>(TileShape{})));
Tensor gA = gA_mkl(_,_,m_coord,_,l_coord); // (BLK_M,BLK_K,k) Tensor gB = gB_nkl(_,_,n_coord,_,l_coord); // (BLK_N,BLK_K,k) Tensor gSFB = gSFB_nkl(_,_,broadcast_n(n_coord),_,l_coord); // (BLK_N,BLK_K,k)
// Partition source and destination tensors for tma copies Tensor tAgA = block_tma_a.partition_S(gA); // (TMA,TMA_M,TMA_K,k) Tensor tAsA = block_tma_a.partition_D(sA); // (TMA,TMA_M,TMA_K,PIPE)
Tensor tBgB = block_tma_b.partition_S(gB); // (TMA,TMA_N,TMA_K,k) Tensor tBsB = block_tma_b.partition_D(sB); // (TMA,TMA_N,TMA_K,PIPE)
Tensor tBgSFB = block_tma_sfb.partition_S(gSFB); // (TMA,TMA_N,TMA_K,k) Tensor tBsSFB = block_tma_sfb.partition_D(sSFB); // (TMA,TMA_N,TMA_K,PIPE)
// scodes: code chunks of this row block; chunk c of k tile kt is at (kt * ChunksPerStage + c) * 640. uint8_t const* scodes_src = params.scodes_codes + static_cast<int64_t>(scodes_group) * params.scodes_expert_stride + static_cast<int64_t>(m_coord) * params.scodes_chunks * inkling_scodes::kChunkBytes; uint8_t* scodes_dst = shared_tensors.smem_codes.begin();
// Mainloop CUTLASS_PRAGMA_NO_UNROLL for ( ; k_tile_count > 0; --k_tile_count) { // LOCK smem_pipe_write for _writing_ pipeline.producer_acquire(smem_pipe_write);
// // Copy gmem to smem for *k_tile_iter //
using BarrierType = typename MainloopPipeline::ProducerBarrierType; BarrierType* tma_barrier = pipeline.producer_get_barrier(smem_pipe_write);
int write_stage = smem_pipe_write.index(); copy(params.tma_load_a.with(get<0>(input_tensormaps),*tma_barrier), tAgA(_,_,_,*k_tile_iter), tAsA(_,_,_,write_stage)); copy(params.tma_load_b.with(get<1>(input_tensormaps),*tma_barrier), tBgB(_,_,_,*k_tile_iter), tBsB(_,_,_,write_stage));
// scodes: one bulk copy of the stage's code chunks replaces the SFA TMA load. A last k tile that runs past K // reads the next chunks (or the buffer's tail padding); the consumers zero those words like TMA OOB fill. cute::SM90_BULK_COPY_G2S::copy( scodes_src + static_cast<int64_t>(*k_tile_iter) * ScodesStageBytes, tma_barrier, scodes_dst + write_stage * ScodesStageBytes, ScodesStageBytes); copy(params.tma_load_sfb.with(get<3>(input_tensormaps),*tma_barrier), tBgSFB(_,_,_,*k_tile_iter), tBsSFB(_,_,_,write_stage));
// Advance k tile ++k_tile_iter; ++smem_pipe_write; } } __syncwarp(); }
/// Perform a Producer Epilogue to prevent early exit of blocks in a Cluster CUTLASS_DEVICE void load_tail(MainloopPipeline pipeline, PipelineState smem_pipe_write) { int lane_predicate = cute::elect_one_sync();
// Issue the epilogue waits if (lane_predicate) { /* This helps avoid early exit of blocks in Cluster * Waits for all stages to either be released (all * Consumer UNLOCKs), or if the stage was never used * then would just be acquired since the phase was * still inverted from make_producer_start_state */ pipeline.producer_tail(smem_pipe_write); } }
/// Perform a collective-scoped matrix multiply-accumulate /// Consumer Perspective template < class FrgTensorC, class BlockCoord > CUTLASS_DEVICE void mma(MainloopPipeline pipeline, PipelineState smem_pipe_read, FrgTensorC& accum, int k_tile_count, int thread_idx, TensorStorage& shared_tensors, [[maybe_unused]] Params const& params, BlockCoord const& blk_coord) { using namespace cute;
static_assert(is_rmem<FrgTensorC>::value, "C tensor must be rmem resident.");
clear(accum);
Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.begin()), SmemLayoutA{}); // (BLK_M,BLK_K,PIPE) Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.begin()), SmemLayoutB{}); // (BLK_N,BLK_K,PIPE) Tensor sSFA = make_tensor(make_smem_ptr(shared_tensors.smem_SFA.begin()), SmemLayoutSFA{}); // (BLK_M,BLK_K,PIPE) Tensor sSFB = [&]() { if constexpr (size<1>(TileShape{}) >= 128) { return make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); // (BLK_N,BLK_K,PIPE) } else { Tensor temp = make_tensor(make_smem_ptr(shared_tensors.smem_SFB.begin()), SmemLayoutSFB{}); // (BLK_SFB_N,BLK_K,PIPE) auto n = get<1>(blk_coord); return temp(make_coord(_,n % (size<1>(TileShapeSFB{}) / size<1>(TileShape{}))), _, _); } }();
// // Define C accumulators and A/B partitioning //
TiledMma tiled_mma; auto thread_mma = tiled_mma.get_thread_slice(thread_idx);
// Allocate fragments and descriptors Tensor tCrA = thread_mma.partition_fragment_A(sA(_,_,Int<0>{})); // (MMA,MMA_M,MMA_K) Tensor tCrB = thread_mma.partition_fragment_B(sB(_,_,Int<0>{})); // (MMA,MMA_N,MMA_K)
Tensor tCrSFA = partition_fragment_SFA(sSFA(_,_,Int<0>{}), thread_mma); // (MMA,MMA_M,MMA_K) Tensor tCrSFB = partition_fragment_SFB(sSFB(_,_,Int<0>{}), thread_mma); // (MMA,MMA_N,MMA_K)
// // Copy from smem to registers //
// A auto smem_tiled_copy_A = make_tiled_copy_A(SmemCopyAtomA{}, tiled_mma); auto smem_thr_copy_A = smem_tiled_copy_A.get_thread_slice(thread_idx); Tensor tCsA = smem_thr_copy_A.partition_S( as_position_independent_swizzle_tensor(sA)); // (CPY,CPY_M,CPY_K,PIPE) Tensor tCrA_copy_view = smem_thr_copy_A.retile_D(tCrA); // (CPY,CPY_M,CPY_K)
// B auto smem_tiled_copy_B = make_tiled_copy_B(SmemCopyAtomB{}, tiled_mma); auto smem_thr_copy_B = smem_tiled_copy_B.get_thread_slice(thread_idx); Tensor tCsB = smem_thr_copy_B.partition_S( as_position_independent_swizzle_tensor(sB)); // (CPY,CPY_M,CPY_K,PIPE) Tensor tCrB_copy_view = smem_thr_copy_B.retile_D(tCrB); // (CPY,CPY_M,CPY_K)
// SFA auto tile_shape_mnk = tile_shape(tiled_mma); auto smem_tiled_copy_SFA = make_tiled_copy_impl(SmemCopyAtomSFA{}, get_layoutSFA_TV(tiled_mma), make_shape(size<0>(tile_shape_mnk), size<2>(tile_shape_mnk)) ); auto smem_thr_copy_SFA = smem_tiled_copy_SFA.get_thread_slice(thread_idx); Tensor tCsSFA = smem_thr_copy_SFA.partition_S( as_position_independent_swizzle_tensor(sSFA)); // (CPY,CPY_M,CPY_K,PIPE) Tensor tCrSFA_copy_view = smem_thr_copy_SFA.retile_D(tCrSFA); // (CPY,CPY_M,CPY_K)
// SFB auto smem_tiled_copy_SFB = make_tiled_copy_impl(SmemCopyAtomSFB{}, get_layoutSFB_TV(tiled_mma), make_shape(size<1>(tile_shape_mnk), size<2>(tile_shape_mnk)) ); auto smem_thr_copy_SFB = smem_tiled_copy_SFB.get_thread_slice(thread_idx); Tensor tCsSFB = smem_thr_copy_SFB.partition_S( as_position_independent_swizzle_tensor(sSFB)); // (CPY,CPY_N,CPY_K,PIPE) Tensor tCrSFB_copy_view = smem_thr_copy_SFB.retile_D(tCrSFB); // (CPY,CPY_N,CPY_K)
CUTE_STATIC_ASSERT_V(size<1>(tCsA) == size<1>(tCrA_copy_view)); // CPY_M CUTE_STATIC_ASSERT_V(size<2>(tCsA) == size<2>(tCrA_copy_view)); // CPY_K CUTE_STATIC_ASSERT_V(size<1>(tCrA) == size<1>(accum)); // MMA_M CUTE_STATIC_ASSERT_V(size<1>(tCrB) == size<2>(accum)); // MMA_N CUTE_STATIC_ASSERT_V(size<2>(tCsA) == size<2>(tCsB)); // CPY_K CUTE_STATIC_ASSERT_V(size<3>(tCsA) == size<3>(tCsB)); // PIPE CUTE_STATIC_ASSERT_V(Int<DispatchPolicy::Stages>{} == size<2>(sA)); // PIPE CUTE_STATIC_ASSERT_V(Int<DispatchPolicy::Stages>{} == size<2>(sB)); // PIPE
CUTE_STATIC_ASSERT_V(size<1>(tCsSFA) == size<1>(tCrSFA_copy_view)); // CPY_M CUTE_STATIC_ASSERT_V(size<2>(tCsSFA) == size<2>(tCrSFA_copy_view)); // CPY_K CUTE_STATIC_ASSERT_V(size<1>(tCrSFA) == size<1>(accum)); // MMA_M CUTE_STATIC_ASSERT_V(size<1>(tCrSFB) == size<2>(accum)); // MMA_N CUTE_STATIC_ASSERT_V(size<2>(tCsSFA) == size<2>(tCsSFB)); // CPY_K CUTE_STATIC_ASSERT_V(size<3>(tCsSFA) == size<3>(tCsSFB)); // PIPE CUTE_STATIC_ASSERT_V(size<2>(sA) == size<2>(sSFA)); // PIPE CUTE_STATIC_ASSERT_V(size<2>(sB) == size<2>(sSFA)); // PIPE
// // PIPELINED MAIN LOOP //
// Size of the register pipeline auto K_BLOCK_MAX = size<2>(tCrA);
int read_stage = smem_pipe_read.index(); auto tCsA_stage = tCsA(_,_,_,read_stage); auto tCsB_stage = tCsB(_,_,_,read_stage); auto tCsSFA_stage = tCsSFA(_,_,_,0); // scodes: the single decoded SFA buffer auto tCsSFB_stage = tCsSFB(_,_,_,read_stage);
// scodes: expand the code chunks of a pipeline stage into the decoded SFA buffer. Thread t writes SFA word t of // every chunk of the stage (4 scale bytes of one weight row, row = (t % 4) * 32 + (t % 128) / 4 inside the // 128-row block); value = row base * 0x01010101 + the 5 code bits spread to the 4 bytes. Words of chunks at or // past K (scodes_chunks) are zero, matching the stock TMA's out-of-bounds fill. int const scodes_tid = thread_idx; int const scodes_row = (scodes_tid & 3) * 32 + ((scodes_tid & 127) >> 2); int32_t const scodes_group = static_cast<int32_t>(get<3>(blk_coord)); int32_t const scodes_mblk = static_cast<int32_t>(get<0>(blk_coord)); uint32_t const scodes_base_byte = static_cast<uint32_t>(__ldg( params.scodes_bases + static_cast<int64_t>(scodes_group) * params.scodes_rows + static_cast<int64_t>(scodes_mblk) * 128 + scodes_row)); uint32_t const scodes_base4 = 0x01010101u * (scodes_base_byte & 0x7Fu); // Escape rows (base bit 7 set; ~0.02 % of rows span > 31 scale codes): code 31 means "take the stock scale // word". Their stock SFA words (the resident swizzled scales, block chunk c word t at // ptr_SFA[group] + (mblk * chunks + c) * 1024 + 4 t) are loaded one k tile ahead into registers. bool const scodes_esc = (scodes_base_byte & 0x80u) != 0u; uint32_t const* scodes_raw = nullptr; if (scodes_esc) { scodes_raw = reinterpret_cast<uint32_t const*>(params.ptr_SFA[scodes_group]) + static_cast<int64_t>(scodes_mblk) * params.scodes_chunks * inkling_scodes::kChunkWords + scodes_tid; } uint32_t scodes_raw_next[ScodesChunksPerStage]; auto scodes_prefetch = [&](int k_tile_abs) { CUTLASS_PRAGMA_UNROLL for (int c = 0; c < ScodesChunksPerStage; ++c) { int const chunk = k_tile_abs * ScodesChunksPerStage + c; scodes_raw_next[c] = (scodes_esc && chunk < params.scodes_chunks) ? __ldg(scodes_raw + static_cast<int64_t>(chunk) * inkling_scodes::kChunkWords) : 0u; } }; scodes_prefetch(0); uint32_t* const scodes_sfa = reinterpret_cast<uint32_t*>(raw_pointer_cast(shared_tensors.smem_SFA.begin())); uint8_t const* const scodes_smem = shared_tensors.smem_codes.begin(); int const scodes_byte = scodes_tid >> 1; int const scodes_shift = (scodes_tid & 1) * 4; auto scodes_decode = [&](int stage, int k_tile_abs) { uint32_t raw_cur[ScodesChunksPerStage]; CUTLASS_PRAGMA_UNROLL for (int c = 0; c < ScodesChunksPerStage; ++c) { raw_cur[c] = scodes_raw_next[c]; } if (scodes_esc) { scodes_prefetch(k_tile_abs + 1); } CUTLASS_PRAGMA_UNROLL for (int c = 0; c < ScodesChunksPerStage; ++c) { uint32_t v = 0u; if (k_tile_abs * ScodesChunksPerStage + c < params.scodes_chunks) { uint8_t const* planes = scodes_smem + stage * ScodesStageBytes + c * inkling_scodes::kChunkBytes + scodes_byte; v = scodes_base4; uint32_t all_ones = 0xFu; CUTLASS_PRAGMA_UNROLL for (int b = 0; b < 5; ++b) { uint32_t nib = (static_cast<uint32_t>(planes[b * 128]) >> scodes_shift) & 0xFu; all_ones &= nib; v += ((nib * 0x00204081u) & 0x01010101u) << b; } if (scodes_esc && all_ones != 0u) { v = raw_cur[c]; // a byte of this word is an escape (code 31): the stock word is exact } } scodes_sfa[c * inkling_scodes::kChunkWords + scodes_tid] = v; } }; int scodes_k_tile = 0;
auto copy_kblock = [&](auto k_block) { // copy smem->rmem for A/B operand copy(smem_tiled_copy_A, tCsA_stage(_,_,k_block), tCrA_copy_view(_,_,k_block)); copy(smem_tiled_copy_B, tCsB_stage(_,_,k_block), tCrB_copy_view(_,_,k_block));
// Left shift A,B for FP4 using MMAOp = typename TiledMma::MMA_Op; fp4_shift_A(MMAOp{}, tCrA_copy_view(_,_,k_block)); fp4_shift_B(MMAOp{}, tCrB_copy_view(_,_,k_block));
// Copy smem->rmem for SFA/SFB operand copy(tCsSFA_stage(_,_,k_block), tCrSFA_copy_view(_,_,k_block)); copy(tCsSFB_stage(_,_,k_block), tCrSFB_copy_view(_,_,k_block)); };
auto gemm_kblock = [&](auto k_block) { // (V,M) x (V,N) => (V,M,N) cute::gemm(tiled_mma, make_zip_tensor(tCrA(_,_,k_block), tCrSFA(_,_,k_block)), make_zip_tensor(tCrB(_,_,k_block), tCrSFB(_,_,k_block)), accum); };
pipeline.consumer_wait(smem_pipe_read); // scodes: decode the first stage; every consumer thread must see the whole buffer before its smem->rmem copy. scodes_decode(read_stage, scodes_k_tile); cutlass::arch::NamedBarrier::sync( thr_size(tiled_mma), cutlass::arch::ReservedNamedBarriers::Sm120MainloopBarrier);
copy_kblock(_0{}); CUTLASS_PRAGMA_NO_UNROLL for ( ; k_tile_count > 1; --k_tile_count) { // // Compute on k_tile // for_each(make_int_sequence<K_BLOCK_MAX>{}, [&] (auto k_block) {
auto k_block_next = ((k_block + 1) == K_BLOCK_MAX) ? 0 : (k_block + 1);
if (k_block == K_BLOCK_MAX - 1) { cutlass::arch::NamedBarrier::sync( thr_size(tiled_mma), cutlass::arch::ReservedNamedBarriers::Sm120MainloopBarrier); // UNLOCK smem_pipe_read, done _computing_ on it pipeline.consumer_release(smem_pipe_read); ++smem_pipe_read; read_stage = smem_pipe_read.index(); tCsA_stage = tCsA(_,_,_,read_stage); tCsB_stage = tCsB(_,_,_,read_stage); tCsSFB_stage = tCsSFB(_,_,_,read_stage); pipeline.consumer_wait(smem_pipe_read); // scodes: every thread copied its last SFA registers of the previous stage before the barrier above, so // the decoded buffer can be rewritten now; the second barrier publishes it before the copies below. ++scodes_k_tile; scodes_decode(read_stage, scodes_k_tile); cutlass::arch::NamedBarrier::sync( thr_size(tiled_mma), cutlass::arch::ReservedNamedBarriers::Sm120MainloopBarrier); }
copy_kblock(k_block_next); gemm_kblock(k_block);
}); } // k_tile_count
// // Hoist out last k_tile // for_each(make_int_sequence<K_BLOCK_MAX>{}, [&] (auto k_block) {
auto k_block_next = ((k_block + 1) == K_BLOCK_MAX) ? 0 : (k_block + 1);
if (k_block == K_BLOCK_MAX - 1) { cutlass::arch::NamedBarrier::sync( thr_size(tiled_mma), cutlass::arch::ReservedNamedBarriers::Sm120MainloopBarrier); // UNLOCK smem_pipe_read, done _computing_ on it pipeline.consumer_release(smem_pipe_read); ++smem_pipe_read; }
if (k_block_next > 0) { copy_kblock(k_block_next); } gemm_kblock(k_block);
});}
/// Perform a Consumer Epilogue to release all buffers CUTLASS_DEVICE void mma_tail(MainloopPipeline, PipelineState, int) { }
// // Methods to perform different parts of TMA/Tensormap modifications //
CUTLASS_DEVICE auto tensormaps_init( Params const& mainloop_params, TensorMapStorage& shared_tensormaps, int32_t sm_count, int32_t sm_idx) { cute::TmaDescriptor* gmem_tensormap = reinterpret_cast<cute::TmaDescriptor*>(mainloop_params.tensormaps);
cute::TmaDescriptor* tma_desc_a = &gmem_tensormap[sm_idx]; cute::TmaDescriptor* tma_desc_b = &gmem_tensormap[sm_idx + sm_count]; cute::TmaDescriptor* tma_desc_sfa = &gmem_tensormap[sm_idx + 2 * sm_count]; cute::TmaDescriptor* tma_desc_sfb = &gmem_tensormap[sm_idx + 3 * sm_count];
if (cute::elect_one_sync()) { // Bringing tensormaps from params to smem for modification later Tensor pA_tensormap = make_tensor(mainloop_params.tma_load_a.get_tma_descriptor(), Int<1>{}, Int<1>{}); Tensor sA_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_A), Int<1>{}, Int<1>{}); Tensor pB_tensormap = make_tensor(mainloop_params.tma_load_b.get_tma_descriptor(), Int<1>{}, Int<1>{}); Tensor sB_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_B), Int<1>{}, Int<1>{});
Tensor pSFA_tensormap = make_tensor(mainloop_params.tma_load_sfa.get_tma_descriptor(), Int<1>{}, Int<1>{}); Tensor sSFA_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_SFA), Int<1>{}, Int<1>{}); Tensor pSFB_tensormap = make_tensor(mainloop_params.tma_load_sfb.get_tma_descriptor(), Int<1>{}, Int<1>{}); Tensor sSFB_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_SFB), Int<1>{}, Int<1>{});
copy(recast<uint128_t>(pA_tensormap), recast<uint128_t>(sA_tensormap)); copy(recast<uint128_t>(pB_tensormap), recast<uint128_t>(sB_tensormap)); copy(recast<uint128_t>(pSFA_tensormap), recast<uint128_t>(sSFA_tensormap)); copy(recast<uint128_t>(pSFB_tensormap), recast<uint128_t>(sSFB_tensormap)); } __syncwarp(); return cute::make_tuple(tma_desc_a, tma_desc_b, tma_desc_sfa, tma_desc_sfb); }
// Replace address for the global tensor (to be done by single thread) CUTLASS_DEVICE void tensormaps_replace_global_address( TensorMapStorage& shared_tensormaps, Params const& mainloop_params, int32_t next_batch) { // Replacing global_address for the next batch cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_A, mainloop_params.ptr_A[next_batch]); cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_B, mainloop_params.ptr_B[next_batch]);
cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_SFA, mainloop_params.ptr_SFA[next_batch]); cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_SFB, mainloop_params.ptr_SFB[next_batch]); }
// Replace dim and strides for the global tensor - used only for Grouped GEMM (to be done by single thread) template <class ProblemShape_MNKL> CUTLASS_DEVICE void tensormaps_replace_global_tensor_properties( TensorMapStorage& shared_tensormaps, Params const& mainloop_params, int32_t next_group, ProblemShape_MNKL problem_shape_mnkl) { const uint32_t M = get<0>(problem_shape_mnkl); const uint32_t N = get<1>(problem_shape_mnkl); const uint32_t K = get<2>(problem_shape_mnkl); // Replace all dims for consistency constexpr int MaxTensorRank = 5; cute::array<uint32_t, MaxTensorRank> prob_shape_A = {1,1,1,1,1}; cute::array<uint64_t, MaxTensorRank> prob_stride_A = {0,0,0,0,0}; cute::array<uint32_t, MaxTensorRank> prob_shape_SFA = {1,1,1,1,1}; cute::array<uint64_t, MaxTensorRank> prob_stride_SFA = {0,0,0,0,0}; cute::array<uint32_t, MaxTensorRank> prob_shape_B = {1,1,1,1,1}; cute::array<uint64_t, MaxTensorRank> prob_stride_B = {0,0,0,0,0}; cute::array<uint32_t, MaxTensorRank> prob_shape_SFB = {1,1,1,1,1}; cute::array<uint64_t, MaxTensorRank> prob_stride_SFB = {0,0,0,0,0};
TmaInternalElementA const* ptr_A = nullptr; Tensor tensor_a = make_tensor(ptr_A, make_shape(M,K,Int<1>{}), mainloop_params.dA[next_group]);
ElementSF const* ptr_SF = nullptr; Tensor tensor_sfa = make_tensor(ptr_SF, mainloop_params.layout_SFA[next_group]);
TmaInternalElementB const* ptr_B = nullptr; Tensor tensor_b = make_tensor(ptr_B, make_shape(N,K,Int<1>{}), mainloop_params.dB[next_group]);
Tensor tensor_sfb = make_tensor(ptr_SF, mainloop_params.layout_SFB[next_group]);
cute::detail::fill_tma_gmem_shape_stride(mainloop_params.tma_load_a, tensor_a, prob_shape_A, prob_stride_A); cute::detail::fill_tma_gmem_shape_stride(mainloop_params.tma_load_sfa, tensor_sfa, prob_shape_SFA, prob_stride_SFA); cute::detail::fill_tma_gmem_shape_stride(mainloop_params.tma_load_b, tensor_b, prob_shape_B, prob_stride_B); cute::detail::fill_tma_gmem_shape_stride(mainloop_params.tma_load_sfb, tensor_sfb, prob_shape_SFB, prob_stride_SFB); // Convert strides to byte strides for (uint64_t& stride : prob_stride_A) { stride = (stride * sizeof_bits_v<TmaInternalElementA>) / 8; } for (uint64_t& stride : prob_stride_SFA) { stride = (stride * sizeof_bits_v<ElementSF>) / 8; } for (uint64_t& stride : prob_stride_B) { stride = (stride * sizeof_bits_v<TmaInternalElementB>) / 8; } for (uint64_t& stride : prob_stride_SFB) { stride = (stride * sizeof_bits_v<ElementSF>) / 8; }
cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_A, prob_shape_A, prob_stride_A); cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_SFA, prob_shape_SFA, prob_stride_SFA); cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_B, prob_shape_B, prob_stride_B); cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_SFB, prob_shape_SFB, prob_stride_SFB); }
// The entire warp must call this function collectively (that is, the instructions are aligned) template <class TensorMapA, class TensorMapB, class TensorMapSFA, class TensorMapSFB, class ProblemShape_MNKL> CUTLASS_DEVICE void tensormaps_perform_update( TensorMapStorage& shared_tensormaps, Params const& mainloop_params, cute::tuple<TensorMapA, TensorMapB, TensorMapSFA, TensorMapSFB> const& input_tensormaps, ProblemShape_MNKL problem_shape_mnkl, int32_t next_batch) { if (cute::elect_one_sync()) { // Replacing global_address for the next batch tensormaps_replace_global_address(shared_tensormaps, mainloop_params, next_batch);
if constexpr (IsGroupedGemmKernel) { // Replacing global dims and strides for the next batch tensormaps_replace_global_tensor_properties(shared_tensormaps, mainloop_params, next_batch, problem_shape_mnkl); } } }
template <class TensorMapA, class TensorMapB, class TensorMapSFA, class TensorMapSFB> CUTLASS_DEVICE void tensormaps_cp_fence_release ( TensorMapStorage& shared_tensormaps, cute::tuple<TensorMapA, TensorMapB, TensorMapSFA, TensorMapSFB> const& input_tensormaps) { if (cute::elect_one_sync()) { cute::tma_desc_commit_group(); cute::tma_desc_wait_group(); } // Entire warp must do this (i.e. it's aligned) tma_descriptor_cp_fence_release(get<0>(input_tensormaps), shared_tensormaps.smem_tensormap_A); tma_descriptor_cp_fence_release(get<1>(input_tensormaps), shared_tensormaps.smem_tensormap_B);
tma_descriptor_cp_fence_release(get<2>(input_tensormaps), shared_tensormaps.smem_tensormap_SFA); tma_descriptor_cp_fence_release(get<3>(input_tensormaps), shared_tensormaps.smem_tensormap_SFB); }
// The entire warp must call this function collectively (that is, the instructions are aligned) template <class TensorMapA, class TensorMapB, class TensorMapSFA, class TensorMapSFB> CUTLASS_DEVICE void tensormaps_fence_acquire(cute::tuple<TensorMapA, TensorMapB, TensorMapSFA, TensorMapSFB> const& input_tensormaps) { cute::tma_descriptor_fence_acquire(get<0>(input_tensormaps)); cute::tma_descriptor_fence_acquire(get<1>(input_tensormaps)); cute::tma_descriptor_fence_acquire(get<2>(input_tensormaps)); cute::tma_descriptor_fence_acquire(get<3>(input_tensormaps)); }
template <class InputTensors, class ProblemShape_MNKL> CUTLASS_DEVICE InputTensors tensors_perform_update( InputTensors const& input_tensors, [[maybe_unused]] Params const& mainloop_params, [[maybe_unused]] ProblemShape_MNKL problem_shape_mnkl, [[maybe_unused]] int32_t next_batch) { // scodes: remember the group for the code chunk addresses in load(). return cute::make_tuple(get<0>(input_tensors), get<1>(input_tensors), get<2>(input_tensors), get<3>(input_tensors), int32_t(next_batch)); }
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::gemm::collective
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""Scale codes for NVFP4 expert weight scales (inkling_scodes).
Input: the expert weight scales in the layout SGLang's SM120 path hands to the grouped GEMM, i.e. UE4M3 bytesswizzled into CUTLASS 128x4 atoms by swizzle_blockscale ([experts, n * k/16] or [experts, n, k/16], n % 128 == 0,k % 128 == 0). Per expert the swizzled bytes are [n/128 row blocks][k/64 k-groups][32 r32][4 r4][4 kk] withweight row = block * 128 + r4 * 32 + r32 and scale column = kgroup * 4 + kk.
Format (what csrc/scodes_sm120_mma_array.hpp decodes): bases uint8 [experts, n] per weight row: the row minimum when the row spans <= 31 codes; otherwise (an "escape row", ~0.02 % of the real rows) 0x80 | b with b the start of the 31-value window [b, b+30] that holds most of the row's bytes codes uint8 [experts * stride + 640] stride = (n/128) * (k/128) * 640 per expert, per row block, per 128-K chunk (= 2 k-groups = 256 SFA words of 4 bytes, word w = kg_local * 128 + r32 * 4 + r4): 5 bit-planes of 128 bytes; plane b, byte w // 2, nibble w % 2 (low first) holds bit b of the 4 codes (byte - row base) of word w, bit i = byte kk == i. The 640-byte zero tail keeps the kernel's whole-stage bulk copies inside the buffer when the last k tile of the last row block runs past K (tile_k 256 with k/128 odd); those words are never used.Decode: byte = base + code; in an escape row code 31 marks a byte outside the window and the kernel takes the whole4-byte SFA word from the stock (resident) swizzled scales. Exact for any UE4M3 bytes <= 0x7E."""
CHUNK_BYTES = 640PLANES = 5MAX_RANGE = (1 << PLANES) - 1
class ScodesError(ValueError): """Scales that the 5-bit code cannot represent (or a bad layout)."""
def _shapes(scale, n, k): if n % 128 or k % 128: raise ScodesError(f"n={n} and k={k} must be multiples of 128") sfk = k // 16 experts = scale.shape[0] if scale.numel() != experts * n * sfk: raise ScodesError(f"scale has {scale.numel()} bytes, expected {experts} x {n} x {sfk}") return experts, n // 128, sfk // 4, k // 128
def logical_from_swizzled(torch, swz, n, k): """[E, n, k/16] uint8 view of swizzled scales (inverse of swizzle_blockscale).""" e, mt, kg, _ = _shapes(swz, n, k) s = swz.reshape(e, mt, kg, 32, 4, 4) return s.permute(0, 1, 4, 3, 2, 5).reshape(e, n, k // 16)
def encode(torch, swz, n, k, experts_per_pass=16): """(codes, bases, expert_stride) of swizzled UE4M3 scales (any 1-byte dtype, on any device).""" swz = swz.contiguous().view(torch.uint8) e, mt, kg, kt = _shapes(swz, n, k) swz = swz.reshape(e, mt, kg, 32, 4, 4) stride = mt * kt * CHUNK_BYTES codes = torch.zeros(e * stride + CHUNK_BYTES, dtype=torch.uint8, device=swz.device) bases = torch.empty((e, n), dtype=torch.uint8, device=swz.device) weights = torch.tensor([1, 2, 4, 8], dtype=torch.int16, device=swz.device) for e0 in range(0, e, experts_per_pass): e1 = min(e, e0 + experts_per_pass) s = swz[e0:e1].to(torch.int16) # [P, mt, kg, 32, 4, 4] logical = s.permute(0, 1, 4, 3, 2, 5).reshape(e1 - e0, n, k // 16) if bool((logical > 0x7E).any()): raise ScodesError("scale byte with the sign bit or the E4M3 NaN code") lo = logical.amin(dim=2) # [P, n] esc = (logical.amax(dim=2) - lo) > MAX_RANGE base = lo.clone() if bool(esc.any()): rows = logical[esc] # [X, k/16] hist = torch.zeros((rows.shape[0], 128), dtype=torch.int32, device=rows.device) hist.scatter_add_(1, rows.long(), torch.ones_like(rows, dtype=torch.int32)) win = hist.cumsum(dim=1) # count in [b, b+30] = C[b+30] - C[b-1] upper = win[:, MAX_RANGE - 1:] # b = 0 .. 128-31 lower = torch.cat([torch.zeros_like(win[:, :1]), win[:, :128 - MAX_RANGE]], dim=1) base[esc] = (upper - lower).argmax(dim=1).to(base.dtype) bases[e0:e1] = (base + esc.to(base.dtype) * 0x80).to(torch.uint8) base_sw = base.reshape(e1 - e0, mt, 4, 32).permute(0, 1, 3, 2) # [P, mt, r32, r4] esc_sw = esc.reshape(e1 - e0, mt, 4, 32).permute(0, 1, 3, 2) c = s - base_sw[:, :, None, :, :, None] # [P, mt, kg, 32, 4, 4] out = (c < 0) | (c > MAX_RANGE - 1) c = torch.where(out & esc_sw[:, :, None, :, :, None], torch.full_like(c, MAX_RANGE), c) c = c.reshape(e1 - e0, mt, kt, 256, 4) # words of each 128-K chunk planes = [] for b in range(PLANES): nib = (((c >> b) & 1) * weights).sum(dim=-1) # [P, mt, kt, 256] planes.append((nib[..., 0::2] | (nib[..., 1::2] << 4)).to(torch.uint8)) chunk = torch.stack(planes, dim=3) # [P, mt, kt, 5, 128] codes[e0 * stride:e1 * stride] = chunk.reshape(-1) return codes, bases, stride
def decode(torch, codes, bases, n, k, stock=None): """Swizzled scale bytes [E, n * k/16] from (codes, bases), with the kernel's arithmetic (reference). Escape words (escape row and some code == 31) are taken from `stock` (the swizzled scales), as the kernel does.""" e = bases.shape[0] mt, kt = n // 128, k // 128 stride = mt * kt * CHUNK_BYTES ch = codes[: e * stride].reshape(e, mt, kt, PLANES, 128).to(torch.int64) nib = torch.stack([ch & 0xF, ch >> 4], dim=-1).reshape(e, mt, kt, PLANES, 256) # nibble of word w row = (torch.arange(256, device=codes.device) % 128) row = (row & 3) * 32 + (row >> 2) # row inside the block braw = bases.to(torch.int64).reshape(e, mt, 128)[:, :, row] # [E, mt, 256] base, esc = braw & 0x7F, (braw & 0x80) != 0 v = base[:, :, None, :] * 0x01010101 # [E, mt, 1, 256] ones = torch.full_like(nib[:, :, :, 0, :], 0xF) for b in range(PLANES): v = v + (((nib[:, :, :, b, :] * 0x00204081) & 0x01010101) << b) ones = ones & nib[:, :, :, b, :] out = torch.stack([(v >> (8 * i)) & 0xFF for i in range(4)], dim=-1) # little-endian bytes use_stock = (esc[:, :, None, :] & (ones != 0)) # [E, mt, kt, 256] if bool(use_stock.any()): if stock is None: raise ScodesError("escape words need the stock scales") st = stock.contiguous().view(torch.uint8).reshape(e, mt, kt, 256, 4).to(torch.int64) out = torch.where(use_stock[..., None], st, out) return out.to(torch.uint8).reshape(e, n * (k // 16))
def stats(torch, swz, n, k): """Byte budget of one tensor: raw scale bytes, coded bytes (codes + bases), rows over the 5-bit range.""" logical = logical_from_swizzled(torch, swz.contiguous().view(torch.uint8), n, k).to(torch.int16) rng = logical.amax(dim=2) - logical.amin(dim=2) e = logical.shape[0] return dict(raw=int(logical.numel()), coded=e * (n // 128) * (k // 128) * CHUNK_BYTES + e * n, escape_rows=int((rng > MAX_RANGE).sum()), range_max=int(rng.max()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""JIT build and call of the scale-code NVFP4 grouped GEMM (csrc/), through FlashInfer's own JIT (same nvcc flags,include paths and TVM-FFI binding as its gemm_sm120 module; output cached under FlashInfer's cache dir)."""
import hashlibimport osimport threading
CSRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "csrc")TILES = ((32, 128), (32, 256), (64, 128), (64, 256), (128, 128)) # 128x256 needs more smem than stockWORKSPACE_BYTES = 8 << 20
_lock = threading.Lock()_module = None_workspaces = {}
def sources(): names = sorted(f for f in os.listdir(CSRC) if f.endswith((".cu", ".cuh", ".hpp", ".h"))) return [os.path.join(CSRC, f) for f in names]
def source_hash(): h = hashlib.sha256() for path in sources(): h.update(os.path.basename(path).encode()) with open(path, "rb") as f: h.update(f.read()) return h.hexdigest()[:12]
def module(): """The loaded TVM-FFI module (built on first use; the build is cached by source hash).""" global _module if _module is not None: return _module with _lock: if _module is None: from flashinfer.jit import core as jit_core
ctx = jit_core.current_compilation_context flags = ctx.get_nvcc_flags_list(supported_major_versions=[12]) spec = jit_core.gen_jit_spec( "inkling_scodes_" + source_hash(), [p for p in sources() if p.endswith(".cu")], extra_cuda_cflags=flags + ["-DCUTLASS_ENABLE_GDC_FOR_SM100=1"], extra_include_paths=[CSRC], ) _module = spec.build_and_load() return _module
def _workspace(torch, device): # Same policy as FlashInfer's own grouped GEMM (_get_stream_cache_buf): one argument/tensormap workspace per # (device, stream). Calls on one stream (and graphs replayed on one stream) are ordered; two graphs captured on # the same stream must not be replayed concurrently on different streams (true for SGLang and for stock). stream = torch.cuda.current_stream(device).cuda_stream key = (device.index, stream) ws = _workspaces.get(key) if ws is None: ws = (torch.empty(WORKSPACE_BYTES, dtype=torch.uint8, device=device), torch.empty(WORKSPACE_BYTES, dtype=torch.uint8, device=device)) _workspaces[key] = ws return ws
def prepare(torch, device): """Allocate the current stream's workspace outside graph capture (called at weight-load time).""" _workspace(torch, device)
def grouped_gemm(torch, values, scales, weight, weight_scales, offsets, codes, bases, expert_stride, tile_n, tile_k, out): """out[rows, n] (BF16) = raw accumulators of the swap_ab grouped NVFP4 GEMM, weight scales from the codes.
values [rows, k/2] u8, scales: activation scales as for FlashInfer, weight [E, n, k/2] u8, weight_scales: the stock swizzled scales (read only for escape words), offsets int32 [E+1].""" if (tile_n, tile_k) not in TILES: raise ValueError(f"inkling_scodes: no instantiation for tile {tile_n}x{tile_k}") experts, n, half_k = weight.shape k = half_k * 2 dev = values.device for name, t, dtype in (("values", values, torch.uint8), ("weight", weight, torch.uint8), ("codes", codes, torch.uint8), ("bases", bases, torch.uint8), ("offsets", offsets, torch.int32), ("out", out, torch.bfloat16)): if t.device != dev or t.dtype != dtype or not t.is_contiguous(): raise ValueError(f"inkling_scodes: {name} must be a contiguous {dtype} tensor on {dev}") if (tuple(bases.shape) != (experts, n) or codes.numel() < experts * expert_stride + 640 or expert_stride != (n // 128) * (k // 128) * 640 or offsets.numel() != experts + 1 or tuple(out.shape) != (values.shape[0], n)): raise ValueError("inkling_scodes: inconsistent shapes for the scale-code GEMM") # The stock swizzled scales are read for escape words: same device, contiguous bytes, whole and aligned. if (weight_scales.device != dev or weight_scales.element_size() != 1 or not weight_scales.is_contiguous() or weight_scales.numel() != experts * n * (k // 16) or weight_scales.data_ptr() % 16): raise ValueError("inkling_scodes: weight_scales must be the contiguous swizzled [E, n * k/16] scale bytes") int_ws, float_ws = _workspace(torch, dev) module().scodes_group_gemm_nvfp4( int_ws, float_ws, values, weight, scales, weight_scales.view(torch.uint8), out, offsets, codes, bases, n, k, tile_n, tile_k, expert_stride) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""inkling_n320s: pfuse's sconvres launch at another exact tile (prefill seat, tree n320; enters the package only on an n320-1 KEEP).
INKLING_N320_SCONV=BM,BN,WARPS (needs INKLING_PFUSE with sconvres): inkling_pfuse.mix.sconv_residual is replaced by the same function (served mix.py 1e93144f lines 203-222, checks and arguments unchanged) launching _triton_sconv._sconv_residual_kernel at (BM, BN, WARPS) instead of (16, 128, 4). The kernel is per-element, so every tile is bitwise (n320-1 measures and checks it).Reach: STATE["calls"]; one log line at the first call."""import loggingimport os
import torch
STATE = {"installed": False, "calls": 0, "tile": None}_log = logging.getLogger(__name__)
def _tile(): bm, bn, warps = (int(x) for x in os.environ["INKLING_N320_SCONV"].split(",")) assert bm in (8, 16, 32, 64, 128) and bn in (32, 64, 128, 256, 512) and warps in (1, 2, 4, 8, 16), (bm, bn, warps) return bm, bn, warps
def _patch(mix): import inspect
import triton
served = mix.sconv_residual if getattr(served, "_n320s", False): return src = inspect.getsource(served) assert "(triton.cdiv(rows, 16), triton.cdiv(width, 128))" in src and "partial is not None, 16, 128," in src, "served launch changed" bm, bn, warps = _tile()
def sconv_residual(x, weight, cache, metadata, attention, partial): from inkling_pfuse import _triton_sconv
rows, width = x.shape kernel_width = weight.shape[1] assert rows >= mix.sconv_min_rows() and x.stride(-1) == 1 and x.dtype == torch.bfloat16 assert cache.ndim == 3 and cache.shape[1:] == (kernel_width - 1, width) for t in (attention, partial): assert t is None or (t.shape == x.shape and t.dtype == torch.bfloat16 and t.is_contiguous()) out = torch.empty_like(attention) _triton_sconv._sconv_residual_kernel[(triton.cdiv(rows, bm), triton.cdiv(width, bn))]( x, weight, cache, metadata["safe_idx"], metadata["cache_mask"], metadata["cu"], metadata["si"], attention, partial if partial is not None else attention, out, rows, x.stride(0), *weight.stride(), *cache.stride(), width, kernel_width, (kernel_width + 1) ** -0.5, partial is not None, bm, bn, num_warps=warps, enable_fp_fusion=False, ) STATE["calls"] += 1 if STATE["calls"] == 1: _log.warning("n320s: sconv_residual at tile (%d, %d, %d warps)", bm, bn, warps) return out
sconv_residual._n320s = True mix.sconv_residual = sconv_residual STATE.update(installed=True, tile=(bm, bn, warps))
def install(): from inkling_pfuse import _hook
_tile() # fail at start-up on a malformed switch _hook.when_imported("inkling_pfuse.mix", _patch)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""inkling_n329: phoist.prepare's _bank_stats_kernel launched per row (prefill seat, tree n329; n329-1 KEEP, kit 849ac214).
INKLING_N329=1 (needs INKLING_PFUSE_HOIST): inkling_phoist.phoist_triton._bank_stats_kernel is wrapped so that a launch on grid (T, 12) runs n329_rows._bank_stats_rows_kernel on grid (T,) with the same arguments (the 12 layer-sides looped inside the program, the served body unchanged); any other grid goes to the served kernel. Bitwise vs served (n329-1: BP / BI / MR word-equal, eager + graph, 1-bit control found); -4.73 / -3.98 ms per attention / mlp call at 12,288 rows (17.4 ms per 12K forward).Reach: STATE counts launches routed each way; the first routed launch logs one line ('n329: per-row _bank_stats').CUDA graphs: the wrapper only picks the kernel object at launch time (host side); a captured graph holds the per-row launch."""import loggingimport os
STATE = {"installed": False, "rows": 0, "served": 0}_log = logging.getLogger(__name__)
class _RowsGrid: """Stands in for the served JITFunction at `kernel[grid](...)` call sites."""
def __init__(self, served, rows): self.served = served self.rows = rows
def __getitem__(self, grid): if isinstance(grid, tuple) and len(grid) == 2 and grid[1] == 12: STATE["rows"] += 1 if STATE["rows"] == 1: _log.warning("n329: per-row _bank_stats (grid (%s, 12) -> (%s,))", grid[0], grid[0]) return self.rows[(grid[0],)] STATE["served"] += 1 return self.served[grid]
def __getattr__(self, name): return getattr(self.served, name)
def _patch(kt): if os.environ.get("N329_CONTROL", "").strip() == "1": # failing control for check boots: mrstd x (1 + 2^-18) from . import n329_rows_ctl as n329_rows _log.warning("n329: CONTROL kernel (mrstd x (1 + 2^-18)), outputs must differ") else: from . import n329_rows
kernel = kt._bank_stats_kernel if isinstance(kernel, _RowsGrid): return rows = n329_rows._bank_stats_rows_kernel if list(kernel.arg_names) != list(rows.arg_names): raise RuntimeError(f"n329: served _bank_stats_kernel arguments changed: {kernel.arg_names} vs {rows.arg_names}") kt._bank_stats_kernel = _RowsGrid(kernel, rows) STATE["installed"] = True
def install(): from inkling_phoist import _hook
_hook.when_imported("inkling_phoist.phoist_triton", _patch)12345678910111213141516171819202122232425262728293031"""n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with thelayer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers."""import tritonimport triton.language as tlfrom triton.language.extra import libdevice # noqa: F401from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401
@triton.jitdef _bank_stats_rows_kernel( B, QM, BP, BI, MR, T, eps_res, eps_ctrl, LS_Q_STRIDE, Q_OFF, NM: tl.constexpr, QP: tl.constexpr, QPM: tl.constexpr, NBP: tl.constexpr, D: tl.constexpr, CH: tl.constexpr,): """Program (row, ls): bank weights of the NM queries of layer-side ls (queries at QM + ls * LS_Q_STRIDE + Q_OFF) and the message rstd, exactly as _loop_stats_kernel computes them. BP [NLS, T, NBP, QP], BI [NLS, T, QP], MR [NLS, T, QPM].""" row = tl.program_id(0).to(tl.int64) for ls32 in tl.range(0, 12): # n329: the 12 layer-sides of the served grid's second axis, in one program ls = ls32.to(tl.int64) qm = tl.arange(0, QPM) Q = QM + ls * LS_Q_STRIDE + Q_OFF bprob, binv = _row_weights(B, B[0], Q, row, eps_res, NM, QPM, NBP, False, True, D, CH) tl.store(BP + (ls * T + row) * (NBP * QP) + tl.arange(0, NBP)[:, None] * QP + qm[None, :], bprob) tl.store(BI + (ls * T + row) * QP + qm, binv) mss = tl.zeros([QPM, CH], tl.float32) for c in tl.static_range(D // CH): m = _row_combine(B, B[0], bprob, binv, row, c, QPM, NBP, False, D, CH) mss = mss + m * m mrstd = libdevice.rsqrt(tl.div_rn(tl.sum(mss, 1), tl.full([QPM], D, tl.float32)) + eps_ctrl) tl.store(MR + (ls * T + row) * QPM + qm, mrstd)
12345678910111213141516171819202122232425262728293031"""n329 FAILING-CONTROL copy (N329_CONTROL=1, check boots only): mrstd x (1 + 2^-18). n329 GENERATED by gen_rows.py from the served inkling_phoist/phoist_triton.py: _bank_stats_kernel with thelayer-side axis looped inside the program (grid (tokens,)). Imports the served module for its helpers."""import tritonimport triton.language as tlfrom triton.language.extra import libdevice # noqa: F401from inkling_phoist.phoist_triton import _row_weights, _row_combine # noqa: F401
@triton.jitdef _bank_stats_rows_kernel( B, QM, BP, BI, MR, T, eps_res, eps_ctrl, LS_Q_STRIDE, Q_OFF, NM: tl.constexpr, QP: tl.constexpr, QPM: tl.constexpr, NBP: tl.constexpr, D: tl.constexpr, CH: tl.constexpr,): """Program (row, ls): bank weights of the NM queries of layer-side ls (queries at QM + ls * LS_Q_STRIDE + Q_OFF) and the message rstd, exactly as _loop_stats_kernel computes them. BP [NLS, T, NBP, QP], BI [NLS, T, QP], MR [NLS, T, QPM].""" row = tl.program_id(0).to(tl.int64) for ls32 in tl.range(0, 12): # n329: the 12 layer-sides of the served grid's second axis, in one program ls = ls32.to(tl.int64) qm = tl.arange(0, QPM) Q = QM + ls * LS_Q_STRIDE + Q_OFF bprob, binv = _row_weights(B, B[0], Q, row, eps_res, NM, QPM, NBP, False, True, D, CH) tl.store(BP + (ls * T + row) * (NBP * QP) + tl.arange(0, NBP)[:, None] * QP + qm[None, :], bprob) tl.store(BI + (ls * T + row) * QP + qm, binv) mss = tl.zeros([QPM, CH], tl.float32) for c in tl.static_range(D // CH): m = _row_combine(B, B[0], bprob, binv, row, c, QPM, NBP, False, D, CH) mss = mss + m * m mrstd = libdevice.rsqrt(tl.div_rn(tl.sum(mss, 1), tl.full([QPM], D, tl.float32)) + eps_ctrl) tl.store(MR + (ls * T + row) * QPM + qm, mrstd * 1.000003814697265625) # N329_CONTROL: x (1 + 2^-18), wrong by design
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""inkling_n351: the MoE NVFP4 token quantize through an exact n351 variant (prefill seat, tree n351; enters the n320 package onlyon an n351-1 KEEP).
INKLING_N351=V[,GRID] V in 1 / 3 / 5 / 7 (n351_quant.cuh variant bits), GRID optional (0 = the served 4 x SMs rule): sglang.srt.models.inkling_common.n14_moe.nvfp4_token_quantize is wrapped so that width-2304 calls run n351_quant::nvfp4_quantize_tokens<2304, V>; any other width falls through to n14's served kernel. Every written word comes from the same image helpers (n351-1 checks it bitwise vs served). Needs n351_quant.cuh mounted at the JIT csrc path inkling2/n351_quant.cuh (manifest EXTRA_DOCKER).Reach: STATE counts routed / fallen-through calls; one log line at the first routed call."""import loggingimport os
STATE = {"installed": False, "routed": 0, "served": 0, "variant": None, "grid": None}_log = logging.getLogger(__name__)
def _cfg(): parts = [int(x) for x in os.environ["INKLING_N351"].split(",")] v, g = parts[0], (parts[1] if len(parts) > 1 else 0) assert v in (1, 3, 5, 7) and 0 <= g <= 4096 and len(parts) <= 2, parts return v, g
def _module(v): from sglang.kernels.jit.utils import cache_once, load_jit # noqa: F401
key = f"q{v}" if key not in _MODS: _MODS[key] = load_jit("n351_quant", f"2304_{v}", cuda_files=["inkling2/n351_quant.cuh"], cuda_wrappers=[(key, f"n351_quant::nvfp4_quantize_tokens<2304, {v}>")]) return getattr(_MODS[key], key)
_MODS = {}
def _patch(n14): served = n14.nvfp4_token_quantize if getattr(served, "_n351", False): return import inspect assert list(inspect.signature(served).parameters) == ["x", "src2dst", "top_k", "offsets", "grid"], "served signature changed" v, g = _cfg()
def nvfp4_token_quantize(x, src2dst, top_k, offsets, grid=None): if x.shape[1] != 2304: STATE["served"] += 1 return served(x, src2dst, top_k, offsets, grid=grid) from sglang.kernels.ops.moe import inkling2_experts_sm120 as ex
values, scales, amax = ex._nvfp4_outputs(rows=src2dst.numel(), width=2304, experts=offsets.numel() - 1, device=x.device) if src2dst.numel(): _module(v)(x, src2dst, values, scales, amax, offsets, top_k, n14._sm_count(x.device), g) STATE["routed"] += 1 if STATE["routed"] == 1: _log.warning("n351: NVFP4 token quantize through variant %d (grid %s)", v, g or "4 x SMs") return values, scales, amax
nvfp4_token_quantize._n351 = True n14.nvfp4_token_quantize = nvfp4_token_quantize STATE.update(installed=True, variant=v, grid=g)
def install(): from inkling_pfuse import _hook
_cfg() # fail at start-up on a malformed switch _hook.when_imported("sglang.srt.models.inkling_common.n14_moe", _patch)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175// SPDX-License-Identifier: Apache-2.0// n351 (inkling2-spark prefill seat, 2026-11-27): exact restructures of n14's nvfp4_quantize_tokens_kernel<2304> (n14_quant.cuh// afdcb38b, served on S2 79d139b0). Every written word is computed by the same image helpers (part_max, block_max_reduce,// quantize_part, store_part, zero_expert_tail, row_expert); only the schedule changes. Variant bits V:// 1 hoist: per token, threads 0..top_k-1 compute (row, expert) of the token's destinations into shared memory before the// amax reduction (whose __syncthreads publishes them); every thread then reads them instead of running its own binary// search per destination (double-buffered by the reduction's parity, as red[] is)// 2 prefetch: the next token's BF16 row is loaded into registers before the current token's quantize + stores// 4 split 2: E = 8 values per thread, 288 threads per token (the image's split for this width is 4: E = 4, 576 threads).// quantize_part keeps the block's pairwise error-sum order for any E (its own comment), part_max / amax are maxima.// V = 0 is a copy of the served kernel (the copy null).#include <sgl_kernel/tensor.h>
#include <sgl_kernel/utils.cuh>
#include "routed_quant_sm120.cuh"#include <cstdint>
namespace sglang::n351_quant {
using namespace sglang::inkling2_routed_quant;using sglang::inkling2_routed_quant_sm120::verify_offsets;using sglang::inkling2_routed_quant_sm120::verify_rows;using sglang::inkling2_routed_quant_sm120::zero_expert_tail;
template <int K, int V>struct Cfg { static constexpr int kSplit = (V & 4) ? 2 : split(K); static constexpr int E = 16 / kSplit; static constexpr int kThreads = (K / 16 * kSplit + 31) / 32 * 32;};
template <int E>__device__ __forceinline__ void load_part(__nv_bfloat16 const* src, float (&v)[E]) { if constexpr (E == 8) { uint4 raw = *reinterpret_cast<uint4 const*>(src); __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(&raw);#pragma unroll for (int i = 0; i < E; ++i) v[i] = __bfloat162float(h[i]); } else { uint2 raw = *reinterpret_cast<uint2 const*>(src); __nv_bfloat16 const* h = reinterpret_cast<__nv_bfloat16 const*>(&raw);#pragma unroll for (int i = 0; i < E; ++i) v[i] = __bfloat162float(h[i]); }}
constexpr int kMaxTopK = 16;
template <int K, int V>__global__ void __launch_bounds__(Cfg<K, V>::kThreads) nvfp4_quantize_tokens_kernel( __nv_bfloat16 const* __restrict__ x, int32_t const* __restrict__ src2dst, uint8_t* values, uint8_t* x_scales, float* amax_out, int32_t const* __restrict__ offsets, int32_t tokens, int32_t top_k, int32_t experts) { constexpr int kThreads = Cfg<K, V>::kThreads, kSplit = Cfg<K, V>::kSplit, E = Cfg<K, V>::E; constexpr bool kHoist = V & 1, kPrefetch = V & 2; static_assert(K % 64 == 0 && kSplit > 1); __shared__ int32_t s_offsets[kMaxExperts + 1]; __shared__ float red[2][kThreads / 32]; __shared__ int32_t s_row[2][kMaxTopK]; __shared__ int32_t s_exp[2][kMaxTopK]; device::PDLWaitPrimary<true>(); device::PDLTriggerSecondary<true>(); load_offsets(offsets, experts, s_offsets); int32_t const block = threadIdx.x / kSplit, part = threadIdx.x % kSplit; bool const active = block < K / 16; int32_t const lo = s_offsets[0], hi = s_offsets[experts]; int32_t parity = 0; float nxt[E]; if constexpr (kPrefetch) {#pragma unroll for (int i = 0; i < E; ++i) nxt[i] = 0.0f; if (active && blockIdx.x < tokens) load_part<E>(x + int64_t(blockIdx.x) * K + block * 16 + part * E, nxt); } for (int32_t token = blockIdx.x; token < tokens; token += gridDim.x, parity ^= 1) { float v[E]; if constexpr (kPrefetch) {#pragma unroll for (int i = 0; i < E; ++i) v[i] = nxt[i]; int32_t const t2 = token + gridDim.x; if (active && t2 < tokens) load_part<E>(x + int64_t(t2) * K + block * 16 + part * E, nxt); } else {#pragma unroll for (int i = 0; i < E; ++i) v[i] = 0.0f; if (active) load_part<E>(x + int64_t(token) * K + block * 16 + part * E, v); } if constexpr (kHoist) { if (threadIdx.x < top_k) { int32_t const row = src2dst[int64_t(token) * top_k + threadIdx.x]; bool const live = row >= lo && row < hi; s_row[parity][threadIdx.x] = live ? row : -1; s_exp[parity][threadIdx.x] = live ? row_expert(s_offsets, experts, row) : -1; } } float block_max = part_max<E>(v); float amax = block_max_reduce<kThreads>(block_max, red[parity]); // its __syncthreads also publishes s_row / s_exp uint32_t packed; uint8_t scale; quantize_part<E>(v, amax, block_max, packed, scale); for (int32_t k = 0; k < top_k; ++k) { int32_t row, expert; if constexpr (kHoist) { row = s_row[parity][k]; if (row < 0) continue; expert = s_exp[parity][k]; } else { row = src2dst[int64_t(token) * top_k + k]; if (row < lo || row >= hi) continue; expert = row_expert(s_offsets, experts, row); } if (active) { if (threadIdx.x == 0) amax_out[row] = amax; store_part<E>(values, x_scales, s_offsets, expert, row, block, part, K, packed, scale); } if (row == s_offsets[expert + 1] - 1) zero_expert_tail(s_offsets, expert, x_scales, (K + 63) / 64 * 4); } }}
inline int32_t grid_for(int32_t tokens, int64_t sm_count, int64_t grid) { int64_t const g = grid > 0 ? grid : 4 * sm_count; return static_cast<int32_t>(std::max<int64_t>(1, std::min<int64_t>(tokens, g)));}
// = n14_quant::nvfp4_quantize_tokens<K> (same checks, grid rule and PDL launch) with the variant kernel<K, V>.template <int K, int V>void nvfp4_quantize_tokens( tvm::ffi::TensorView x, tvm::ffi::TensorView src2dst, tvm::ffi::TensorView values, tvm::ffi::TensorView x_scales, tvm::ffi::TensorView amax, tvm::ffi::TensorView offsets, int64_t top_k, int64_t sm_count, int64_t grid) { constexpr int64_t kPart = 16 / Cfg<K, V>::kSplit; auto tokens = host::SymbolicSize{"tokens"}; auto rows = host::SymbolicSize{"routed rows"}; auto scale_rows = host::SymbolicSize{"scale rows"}; auto device = host::SymbolicDevice{}; device.set_options<kDLCUDA>(); int32_t const experts = verify_offsets(offsets, device); host::TensorMatcher({tokens, K}).with_dtype<bf16_t>().with_device(device).ensure_alignment(kPart * 2).verify(x); host::TensorMatcher({rows}).with_dtype<int32_t>().with_device(device).verify(src2dst); host::TensorMatcher({rows, K / 2}).with_dtype<uint8_t>().with_device(device).ensure_alignment(kPart / 2).verify(values); host::TensorMatcher({scale_rows, K / 16}).with_dtype<uint8_t>().with_device(device).verify(x_scales); host::TensorMatcher({rows}).with_dtype<fp32_t>().with_device(device).verify(amax); CHECK_HOST(top_k > 0 && top_k <= kMaxTopK) << "top_k must be in 1.." << kMaxTopK << ", got " << top_k; int32_t const num_rows = verify_rows(rows); int32_t const num_tokens = verify_rows(tokens); CHECK_HOST(int64_t{num_tokens} * top_k == num_rows) << "src2dst must hold tokens x top_k rows"; CHECK_HOST(scale_rows.unwrap() >= host::div_ceil(num_rows + 127 * int64_t{experts}, 128) * 128) << "NVFP4 scales need 128-row blocks per expert, got " << scale_rows.unwrap() << " rows"; host::LaunchKernel(grid_for(num_tokens, sm_count, grid), Cfg<K, V>::kThreads, device.unwrap()) .enable_pdl(true)( nvfp4_quantize_tokens_kernel<K, V>, static_cast<__nv_bfloat16 const*>(x.data_ptr()), static_cast<int32_t const*>(src2dst.data_ptr()), static_cast<uint8_t*>(values.data_ptr()), static_cast<uint8_t*>(x_scales.data_ptr()), static_cast<float*>(amax.data_ptr()), static_cast<int32_t const*>(offsets.data_ptr()), num_tokens, static_cast<int32_t>(top_k), experts);}
} // namespace sglang::n351_quant123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""Combined loader for the Inkling-2-Mini SGLang overlays (verify cap, draft bytes, kernels, pico12, prefill).Each overlay activates only when its environment switch is set; with none set nothing is imported.A failing overlay stops the process (site.py would otherwise only print a warning and run the stock path)."""import osimport sys
def _on(name): return os.environ.get(name, "").strip().lower() not in ("", "0", "off", "none", "false", "no")
try: if _on("INKLING_KV12") and _on("INKLING_KV12S"): raise RuntimeError("INKLING_KV12S and INKLING_KV12 are mutually exclusive") if _on("INKLING_VERIFY_CAP"): from inkling_vcap import activate activate() if _on("INKLING_DRAFT_BYTES"): import inkling_draftbytes inkling_draftbytes.install() if _on("INKLING_KERNELS"): import inkling_kernels inkling_kernels.install() if _on("INKLING_MOE2"): # after inkling_kernels: per-token tile tables over moe_tiles' _tiles wrapper import inkling_moe2 inkling_moe2.install() if _on("INKLING_SCODES"): # NVFP4 expert scale codes (exact; wraps nvfp4_expert_matmul) import inkling_scodes inkling_scodes.install() if _on("INKLING_PICO12"): # after inkling_kernels: its _project_sources wrapper goes outside qkvr_gemv's import inkling_pico12 inkling_pico12.install() if _on("INKLING_PREFILL"): # last: its _project_sources wrapper (large M only) goes outermost import inkling_prefill inkling_prefill.install() if _on("INKLING_PFUSE"): # prefill glue fusion: Inkling2DecoderLayer._forward, extend only import inkling_pfuse inkling_pfuse.install() if _on("INKLING_PROLOGUE"): # SWA prefill: K conv + L2 clip, V conv + value norm fused (FP32-order class) import inkling_prologue inkling_prologue.install() if _on("INKLING_PFUSE_HOIST"): # prefill loop-bank hoist over pfuse's loop_mix (FP32-order class; needs PFUSE) import inkling_phoist inkling_phoist.install() if _on("INKLING_N329"): # n329: phoist _bank_stats per row (bitwise; wraps the kernel phoist launches; needs PFUSE_HOIST) import inkling_n329 inkling_n329.install() if _on("INKLING_N320_SCONV"): # n320: pfuse sconvres at another exact tile (per-element kernel; needs PFUSE sconvres) import inkling_n320s inkling_n320s.install() if _on("INKLING_N351"): # n351: MoE NVFP4 token quantize through an exact variant (bitwise; n351_quant.cuh mounted at the JIT path) import inkling_n351 inkling_n351.install() if _on("INKLING_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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Credits
- **Thinking Machines Lab** for Inkling-2-Mini, its NVFP4 / MXFP8 checkpoint and the bundled DSpark draft model (`mtp.safetensors`) ([model card](https://huggingface.co/thinkingmachines/Inkling-2-Mini), [announcement](https://thinkingmachines.ai/news/inkling-2-mini/), Apache-2.0).- **incoai**, [Inkling-2-Mini-DFlash2](https://huggingface.co/incoai/Inkling-2-Mini-DFlash2) (Apache-2.0): the DFlash2 draft model that is this recipe's default drafter, and its SGLang compatibility patch (`sglang_inkling_dflash2.py`), both used as published at revision `4f9088ea`, fetched by `scripts/download.sh` and not distributed here. The drafter byte cuts, the DFLASH verify-width cap, the certified head on DFLASH steps and the selector fix are ours, on top of it.- **The DFlash authors** ([z-lab/dflash](https://github.com/z-lab/dflash)): block-diffusion drafting for speculative decoding, the method behind the DFlash2 drafter, and SGLang's DFLASH worker that serves it.- **SGLang** project for the Inkling-2-Mini support, the `lmsysorg/sglang:inkling-2-mini` image and the [Inkling-2-Mini cookbook](https://docs.sglang.io/cookbook/autoregressive/ThinkingMachines/Inkling-2-Mini), whose DGX Spark DSpark cell (TP1/EP1, FA4, page 128, 8 draft tokens, the four `SGLANG_OPT_*` switches, `MAX_JOBS=4`, the `inkling` / `inkling2` parsers) is the base of the default profile.- **vLLM** project for the Inkling-2-Mini support (vllm-project/vllm #69027, #69028, #69039 by Woosuk Kwon and contributors), the `vllm/vllm-openai:inkling-2-mini` image and the [vLLM recipe](https://recipes.vllm.ai/thinkingmachines/Inkling-2-Mini) behind the alternative profile.- **Tech2Wild (tonyd2wild)**, [Inkling-2-Mini-NVFP4-DGX-Spark](https://github.com/tonyd2wild/Inkling-2-Mini-NVFP4-DGX-Spark): the first single-Spark vLLM recipe for this model. Reused here: the vLLM tier settings (`--gpu-memory-utilization 0.80` at 262K context with tool calling on), the hybrid KV-pool block model and the FP8-KV long-context tier with its memory budget (74 GiB of FP8 KV at 1M), the GB10 page-cache trap, and the advice to keep MemAvailable above ~6 GiB.- **thefullctx**, [inkling-2-mini-sglang-dgx-spark](https://github.com/thefullctx/inkling-2-mini-sglang-dgx-spark) and [inkling-2-mini-vllm-dgx-spark](https://github.com/thefullctx/inkling-2-mini-vllm-dgx-spark): the first published SGLang vs vLLM head-to-head on one Spark (vLLM slightly ahead on short c1 decode, SGLang ~2x on long prefill, faster long-context decode and much lower memory use), which set the arms of our comparison.- **Thien Tran (gau-nernst)**, vLLM PR #69168 (small-M GEMMs for Inkling's looped core): the split-K router / conv-projection and controller re-tiling we screened (not adopted, flat in serving).- **sxuff**, [inkling-2-mini-spark](https://github.com/sxuff/inkling-2-mini-spark) (Apache-2.0): the vLLM + DSpark + INT8 draft recipe and benchmark used for the same-harness comparison, and the `--safetensors-load-strategy eager` result (127 -> 45 s) that prompted our one-pass checkpoint load with SGLang's own flag.- **0xSero**, [inference-optimisation skill](https://github.com/sybil-solutions/inference-optimisation-skill) (MIT): the method behind sxuff's eager-load finding.- **tie-pilot-qxw**, [dspark-markov-walk](https://github.com/tie-pilot-qxw/dspark-markov-walk) (MIT), and [vLLM PR #62958](https://github.com/vllm-project/vllm/pull/62958): the one-kernel DSpark Markov walk that inspired `rnnhoist`. Our projection split is an independent implementation.- **nick398** on the [NVIDIA developer forum thread](https://forums.developer.nvidia.com/t/inkling-2-mini/389745): the first FP8-KV serving notes for this model (vLLM `--kv-cache-dtype fp8` on an RTX 5090: about half the KV memory per token, described there as a quality trade-off).- **Andy Shu (@blaesus)**, [dsgb10](https://github.com/blaesus/dsgb10) (formerly dsgx10, MIT), as carried in [Picom-code/pico-dgx-ds4](https://github.com/Picom-code/pico-dgx-ds4) ("pico"): the exactly coded 12-bit BF16 GEMV (`bf16x` format and kernel) that `overlay/inkling_pico12/` builds and calls for the dense projections and the LM head; the sources are vendored unmodified in `overlay/inkling_pico12/third_party/pico/` with their licence.- **Andy Shu's `bf16x` reader** is also copied (MIT, with its notice) into `overlay/inkling_wide/csrc/bf16x_format.cuh`, which reads pico12's coded weights in the 17-256-row GEMM, and `overlay/inkling_cert/` compiles pico's head GEMV body from the vendored copy for the exact pass of the certified LM head.- **Tri Dao et al., FlashAttention-2** (algorithm): the online-softmax tiling of the fused relative-bias prefill attention in `overlay/inkling_attn/`.- **SGLang Inkling2 kernels**: the split-KV relative-bias verify kernel that `overlay/inkling_vattn/` routes every batch size to (and copies, with the bias computed per key tile, above 32 rows), the split-KV decode kernel that `overlay/inkling_kv12/` follows with its K / V tile loads replaced, the split softmax kernels that `VCAP_FASTPROBS` calls, the block-verification accept kernel behind `--speculative-use-block-verification`, and the fused loop-controller kernels of sgl-project/sglang PR #51926, already in the image.- **SGLang PR #51681** (DSpark Markov sampler: Philox words that rounded to u == 1) and **SGLang PR #51692** (blockwise rejection precision): their fixes are carried verbatim in `overlay/inkling_rsfix/` (`RSFIX`) until the image has them. The reject-sampler CDF fix and the DFLASH selector no-match fix in the same package are ours.- **Sun et al.**, "Block Verification Accelerates Speculative Decoding" (ICLR 2025): the block-verification algorithm that sampled requests use (`VCAP_BV`, `DFLASH_BV`). Running it under the verify cap (dead drafts as a stopped draft) and its logits-only form in the fused accept are ours.- **Xiao et al.**, StreamingLLM (2023): the attention sink kept by the optional drafter global-attention window (`dwin`, 128 sink tokens by default).- **Lossless float compression by exponent coding** (ZipNN, Hershcovitch et al., 2024; SplitZip) and **Andy Shu's exactly coded 12-bit `bf16x` format**: the inspiration for the packed 12-bit global-layer KV in `overlay/inkling_kv12/` (sign + mantissa byte, 4-bit exponent code, escapes). The KV format, packer and attention kernel are our own code; nothing is copied from these projects.- **Alexey Fateev / Project Maya**, [maya-inkling-mini](https://github.com/alesha-pro/maya-inkling-mini) (MIT): launch and "bytes in flight" notes on Inkling's small per-visit kernels that framed our L2-warming screen (not adopted, see docs/experiments.md).- **FR-Spec** (Zhao et al., ACL 2025, frequency-ranked draft vocabulary) and SGLang's EAGLE `--speculative-token-map`: the idea behind the hot-vocabulary draft. The prompt corpus that ranks the shipped list comes from allenai/WildChat-1M (ODC-BY), OpenAssistant/oasst2 (Apache-2.0), NousResearch/hermes-function-calling-v1 (Apache-2.0), bigcode/self-oss-instruct-sc2-exec-filter-50k (ODC-BY), HuggingFaceH4/ultrachat_200k (MIT), ise-uiuc/Magicoder-OSS-Instruct-75K (MIT), openai/gsm8k (MIT), databricks/databricks-dolly-15k (CC-BY-SA-3.0), EleutherAI/hendrycks_math (MIT), abisee/cnn_dailymail (Apache-2.0), CohereLabs/aya_dataset (Apache-2.0), wikimedia/wikipedia (CC-BY-SA-4.0), juletxara/mgsm (CC-BY-SA-4.0) and llm-jp/oasst2-33k-ja (Apache-2.0); only token frequencies of the model's own outputs are shipped, no prompt text.- **thefullctx**: the KV page-size 16 measurement we screened (not adopted here).- **Christopher Owen** and B12X (MXFP4-CSF): the scale-code format idea behind `overlay/inkling_scodes/` (our implementation, in a modified FlashInfer / CUTLASS mainloop).- **Christopher Owen, spark-ds41f** (Apache-2.0): the packed-BF16 vocabulary projection (b12x patch 0012) whose format we ported to Triton in a screen (not adopted, see docs/experiments.md).- **FlashInfer** (CUTLASS / CuTe DSL grouped GEMMs, the GEMVs) and **CUTLASS**: the kernels the MoE tile choice and the GPU checks run on; since v2.8.4 also the b12x MXFP8 GEMM and quantiser (`mm_mxfp8`, `mxfp8_quantize`) that run the drafter's eligible linears (mx8w), used as shipped.- **NVIDIA** for the DGX Spark platform.- **speedbench** ([knapcio/speedbench](https://github.com/knapcio/speedbench)), our own benchmark, for the headline numbers and the long-context table; its frozen prompt set also feeds the decode table.
Our own earlier recipes contributed ideas reused here: the verify cap with dead-row expert remap (DeepSeek-V4.1recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bitdraft heads (DeepSeek-V4.1), and our spark-tools and speedbench for measurement.
Every lever adopted from someone else's work gets a line here and an entry in the Credit column of the README.123456789101112131415161718192021MIT License
Copyright (c) 2026 Zbigniew Majewski
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354Inkling-2-Mini on one NVIDIA DGX Spark
Repository-authored launch scripts, benchmark scripts and documentation: MIT, see LICENSE.
Third-party code vendored in this repository:- overlay/inkling_pico12/third_party/pico/: kernels/gemv16.cu, kernels/common.cuh, kernels/dsk.h, common/check.h by Andy Shu (github.com/blaesus/dsgb10, formerly dsgx10, `ds41f-4xgx10-switchless/engine/` at commit f2117916, as carried in github.com/Picom-code/pico-dgx-ds4), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_pico12/third_party/pico/LICENSE. Unmodified except a two-line header naming the origin.- overlay/inkling_wide/csrc/bf16x_format.cuh: the `bf16x` reader (layout description, bf16x_raw_off, mad_imm, bf16x_dec, ldg_bf16x) copied from the same pico gemv16.cu (commit f2117916), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_wide/third_party/pico/LICENSE.- overlay/inkling_cert/csrc/cert_ext.cu compiles kernels/gemv16.cu from overlay/inkling_pico12/third_party/pico/ (above) into its own extension; no further copy.
- overlay/inkling_scodes/csrc/scodes_sm120_mma_array.hpp: derived from CUTLASS's SM120 block-scaled grouped-GEMM collective mainloop (NVIDIA CORPORATION & AFFILIATES, BSD-3-Clause, licence text kept in the file header), modified to expand coded scale factors; scodes_group_gemm.cuh reduces FlashInfer 0.7.4's include/flashinfer/gemm/group_gemm_nvfp4_groupwise_sm120.cuh (Apache-2.0, Copyright (c) 2026 FlashInfer team) to the configuration SGLang uses and swaps in that mainloop.- overlay/inkling_kv12/ops.py: the decode / verify attention kernels (`_kv12_partials_np`, `_kv12_partials`) follow SGLang's Inkling2 split-KV decode kernel (`_decode_partials` in sglang.kernels.ops.attention.inkling2_decode_attention_sm90, sgl-project/sglang, Apache-2.0) with the same grid, tile order and online softmax, modified to read packed 12-bit K / V tiles from a side pool.- overlay/inkling_vattn/ops.py: `_inkernel_bias_partials` is the same SGLang `_decode_partials` kernel body (sgl-project/sglang, Apache-2.0), modified to compute the relative-position bias per key tile in-kernel.- overlay/inkling_rsfix/markov.py and overlay/inkling_rsfix/blockwise.py: the changes of sgl-project/sglang pull requests #51681 (dspark markov_sample) and #51692 (dspark blockwise_rejection), applied verbatim to copies of the image's functions (sgl-project/sglang, Apache-2.0). overlay/inkling_rsfix/reject.py and selector.py are copies of SGLang's reject_sampling kernels and DFLASH selector walk (Apache-2.0), modified as described in overlay/inkling_rsfix/README.md.
Third-party model files fetched at run time, not distributed in this repository:- Inkling-2-Mini-DFlash2 (huggingface.co/incoai/Inkling-2-Mini-DFlash2) by incoai, revision 4f9088ea66c21f2b99ed657d1941c306b03e84d2: the draft model (config.json, model.safetensors) and its SGLang compatibility patch (sglang_inkling_dflash2.py). Licensed under the Apache License, Version 2.0; you may not use these files except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. scripts/download.sh fetches them unmodified at that revision; scripts/launch.sh checks their sha256 and runs the patch, unmodified, inside the serving container only. The draft method builds on DFlash (github.com/z-lab/dflash).
The serving engines run from their published container images, pinned by digest in scripts/launch.sh:- SGLang (sgl-project/sglang), lmsysorg/sglang:inkling-2-mini, Apache-2.0.- vLLM (vllm-project/vllm), vllm/vllm-openai:inkling-2-mini, Apache-2.0.bench/decode_table.py reads the prompt file of speedbench (knapcio/speedbench, MIT) from a separate checkout; theprompts themselves are not copied here.
No model weights or container images are distributed. The Inkling-2-Mini weights (thinkingmachines/Inkling-2-Mini)are Apache-2.0 from Thinking Machines Lab; read the model card for the terms that apply to anything you serve.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910111213141516171819202122232425262728293031323334353637383940414243444546Inkling-2-Mini-DFlash2 (mix), a modified copy for the Strata engine====================================================================
This repository file, Inkling-2-Mini-DFlash2-mix.safetensors, is derived from the model"Inkling-2-Mini-DFlash2" (https://huggingface.co/incoai/Inkling-2-Mini-DFlash2) by Inco AI / z-lab,a DFlash 2 block-diffusion draft model for thinkingmachines/Inkling-2-Mini(https://inco.ai/blog/dflash2/, https://github.com/z-lab/dflash), which is licensed under theApache License, Version 2.0. The licence text is in the file LICENSE next to this one.
Original work Repository: incoai/Inkling-2-Mini-DFlash2 Revision: 4f9088ea66c21f2b99ed657d1941c306b03e84d2 File: model.safetensors, 989,975,616 bytes, SHA-256 217980ab00d116693fa5946df7bbfd967caf5fac1f529afd541fbd470ddb54ee Copyright and credit for the weights belong to their authors, Inco AI and z-lab. This file keeps that attribution. Strata did not train these weights.
Changes made (Apache License 2.0, section 4(b): the modified file carries this statement) Date: 2026-11-26 By: Strata (https://github.com/Niko1221/Strata), with the Strata 0.2.23 engine (strata-inkling, the 0.1.69 engine line), run with STRATA_INK_DFLASH2_DUMP. The script make_mix_from_original.py in this repository repeats the same arithmetic with numpy and produces a byte-identical file from the original. What: 1. The file format. The tensors are stored in the format "strata-dflash2-q1", a safetensors file that the Strata engine reads directly (the header's __metadata__ says {"format": "strata-dflash2-q1", "variant": "mix"}). Other programs cannot load it. 2. Quantization of the large matrices of the 5 transformer layers, the part of the weights that is a standard matrix multiplication: attention (q_proj, o_proj): 8-bit integers with one float32 scale per row; feed-forward (gate_proj, up_proj, down_proj): 4-bit SF4 (E2M1 values, a UE4M3 scale per 16 values, one float32 scale per matrix). 3. The norm weights and convolution base kernels are stored as float32 (they were bfloat16; the values are the same). All other tensors (fc, the K/V and convolution projections, the candidate selector and its two codebooks) are unchanged bfloat16 values. The unused rows of the two codebooks beyond the 200,058 vocabulary entries are left out. Everything else (architecture, the values of the unchanged tensors) is as in the original. Result: 551,600,700 bytes, SHA-256 cf7dbb08560dfd99544af0cdbab2915406fc571f516b19aff0fe113b9458d387.
The quantization loses a little precision against the original. Measured with the Strata engineon an RTX 5090 and an RTX 5060 Ti, the drafter's acceptance stays within about 2 percent of theoriginal's (see the README). A draft only proposes tokens: the main model checks every one of them,and its own answer is what is returned.
This modified file is provided under the same licence as the original (Apache License 2.0), "AS IS",without warranties or conditions of any kind. No endorsement by Inco AI or z-lab is implied.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Credits
- **Thinking Machines Lab** for Inkling-2-Mini, its NVFP4 / MXFP8 checkpoint and the bundled DSpark draft model (`mtp.safetensors`) ([model card](https://huggingface.co/thinkingmachines/Inkling-2-Mini), [announcement](https://thinkingmachines.ai/news/inkling-2-mini/), Apache-2.0).- **incoai**, [Inkling-2-Mini-DFlash2](https://huggingface.co/incoai/Inkling-2-Mini-DFlash2) (Apache-2.0): the DFlash2 draft model that is this recipe's default drafter, and its SGLang compatibility patch (`sglang_inkling_dflash2.py`), both used as published at revision `4f9088ea`, fetched by `scripts/download.sh` and not distributed here. The drafter byte cuts, the DFLASH verify-width cap, the certified head on DFLASH steps and the selector fix are ours, on top of it.- **The DFlash authors** ([z-lab/dflash](https://github.com/z-lab/dflash)): block-diffusion drafting for speculative decoding, the method behind the DFlash2 drafter, and SGLang's DFLASH worker that serves it.- **SGLang** project for the Inkling-2-Mini support, the `lmsysorg/sglang:inkling-2-mini` image and the [Inkling-2-Mini cookbook](https://docs.sglang.io/cookbook/autoregressive/ThinkingMachines/Inkling-2-Mini), whose DGX Spark DSpark cell (TP1/EP1, FA4, page 128, 8 draft tokens, the four `SGLANG_OPT_*` switches, `MAX_JOBS=4`, the `inkling` / `inkling2` parsers) is the base of the default profile.- **vLLM** project for the Inkling-2-Mini support (vllm-project/vllm #69027, #69028, #69039 by Woosuk Kwon and contributors), the `vllm/vllm-openai:inkling-2-mini` image and the [vLLM recipe](https://recipes.vllm.ai/thinkingmachines/Inkling-2-Mini) behind the alternative profile.- **Tech2Wild (tonyd2wild)**, [Inkling-2-Mini-NVFP4-DGX-Spark](https://github.com/tonyd2wild/Inkling-2-Mini-NVFP4-DGX-Spark): the first single-Spark vLLM recipe for this model. Reused here: the vLLM tier settings (`--gpu-memory-utilization 0.80` at 262K context with tool calling on), the hybrid KV-pool block model and the FP8-KV long-context tier with its memory budget (74 GiB of FP8 KV at 1M), the GB10 page-cache trap, and the advice to keep MemAvailable above ~6 GiB.- **thefullctx**, [inkling-2-mini-sglang-dgx-spark](https://github.com/thefullctx/inkling-2-mini-sglang-dgx-spark) and [inkling-2-mini-vllm-dgx-spark](https://github.com/thefullctx/inkling-2-mini-vllm-dgx-spark): the first published SGLang vs vLLM head-to-head on one Spark (vLLM slightly ahead on short c1 decode, SGLang ~2x on long prefill, faster long-context decode and much lower memory use), which set the arms of our comparison.- **Thien Tran (gau-nernst)**, vLLM PR #69168 (small-M GEMMs for Inkling's looped core): the split-K router / conv-projection and controller re-tiling we screened (not adopted, flat in serving).- **sxuff**, [inkling-2-mini-spark](https://github.com/sxuff/inkling-2-mini-spark) (Apache-2.0): the vLLM + DSpark + INT8 draft recipe and benchmark used for the same-harness comparison, and the `--safetensors-load-strategy eager` result (127 -> 45 s) that prompted our one-pass checkpoint load with SGLang's own flag.- **0xSero**, [inference-optimisation skill](https://github.com/sybil-solutions/inference-optimisation-skill) (MIT): the method behind sxuff's eager-load finding.- **tie-pilot-qxw**, [dspark-markov-walk](https://github.com/tie-pilot-qxw/dspark-markov-walk) (MIT), and [vLLM PR #62958](https://github.com/vllm-project/vllm/pull/62958): the one-kernel DSpark Markov walk that inspired `rnnhoist`. Our projection split is an independent implementation.- **nick398** on the [NVIDIA developer forum thread](https://forums.developer.nvidia.com/t/inkling-2-mini/389745): the first FP8-KV serving notes for this model (vLLM `--kv-cache-dtype fp8` on an RTX 5090: about half the KV memory per token, described there as a quality trade-off).- **Andy Shu (@blaesus)**, [dsgb10](https://github.com/blaesus/dsgb10) (formerly dsgx10, MIT), as carried in [Picom-code/pico-dgx-ds4](https://github.com/Picom-code/pico-dgx-ds4) ("pico"): the exactly coded 12-bit BF16 GEMV (`bf16x` format and kernel) that `overlay/inkling_pico12/` builds and calls for the dense projections and the LM head; the sources are vendored unmodified in `overlay/inkling_pico12/third_party/pico/` with their licence.- **Andy Shu's `bf16x` reader** is also copied (MIT, with its notice) into `overlay/inkling_wide/csrc/bf16x_format.cuh`, which reads pico12's coded weights in the 17-256-row GEMM, and `overlay/inkling_cert/` compiles pico's head GEMV body from the vendored copy for the exact pass of the certified LM head.- **Tri Dao et al., FlashAttention-2** (algorithm): the online-softmax tiling of the fused relative-bias prefill attention in `overlay/inkling_attn/`.- **SGLang Inkling2 kernels**: the split-KV relative-bias verify kernel that `overlay/inkling_vattn/` routes every batch size to (and copies, with the bias computed per key tile, above 32 rows), the split-KV decode kernel that `overlay/inkling_kv12/` follows with its K / V tile loads replaced, the split softmax kernels that `VCAP_FASTPROBS` calls, the block-verification accept kernel behind `--speculative-use-block-verification`, and the fused loop-controller kernels of sgl-project/sglang PR #51926, already in the image.- **SGLang PR #51681** (DSpark Markov sampler: Philox words that rounded to u == 1) and **SGLang PR #51692** (blockwise rejection precision): their fixes are carried verbatim in `overlay/inkling_rsfix/` (`RSFIX`) until the image has them. The reject-sampler CDF fix and the DFLASH selector no-match fix in the same package are ours.- **Sun et al.**, "Block Verification Accelerates Speculative Decoding" (ICLR 2025): the block-verification algorithm that sampled requests use (`VCAP_BV`, `DFLASH_BV`). Running it under the verify cap (dead drafts as a stopped draft) and its logits-only form in the fused accept are ours.- **Xiao et al.**, StreamingLLM (2023): the attention sink kept by the optional drafter global-attention window (`dwin`, 128 sink tokens by default).- **Lossless float compression by exponent coding** (ZipNN, Hershcovitch et al., 2024; SplitZip) and **Andy Shu's exactly coded 12-bit `bf16x` format**: the inspiration for the packed 12-bit global-layer KV in `overlay/inkling_kv12/` (sign + mantissa byte, 4-bit exponent code, escapes). The KV format, packer and attention kernel are our own code; nothing is copied from these projects.- **Alexey Fateev / Project Maya**, [maya-inkling-mini](https://github.com/alesha-pro/maya-inkling-mini) (MIT): launch and "bytes in flight" notes on Inkling's small per-visit kernels that framed our L2-warming screen (not adopted, see docs/experiments.md).- **FR-Spec** (Zhao et al., ACL 2025, frequency-ranked draft vocabulary) and SGLang's EAGLE `--speculative-token-map`: the idea behind the hot-vocabulary draft. The prompt corpus that ranks the shipped list comes from allenai/WildChat-1M (ODC-BY), OpenAssistant/oasst2 (Apache-2.0), NousResearch/hermes-function-calling-v1 (Apache-2.0), bigcode/self-oss-instruct-sc2-exec-filter-50k (ODC-BY), HuggingFaceH4/ultrachat_200k (MIT), ise-uiuc/Magicoder-OSS-Instruct-75K (MIT), openai/gsm8k (MIT), databricks/databricks-dolly-15k (CC-BY-SA-3.0), EleutherAI/hendrycks_math (MIT), abisee/cnn_dailymail (Apache-2.0), CohereLabs/aya_dataset (Apache-2.0), wikimedia/wikipedia (CC-BY-SA-4.0), juletxara/mgsm (CC-BY-SA-4.0) and llm-jp/oasst2-33k-ja (Apache-2.0); only token frequencies of the model's own outputs are shipped, no prompt text.- **thefullctx**: the KV page-size 16 measurement we screened (not adopted here).- **Christopher Owen** and B12X (MXFP4-CSF): the scale-code format idea behind `overlay/inkling_scodes/` (our implementation, in a modified FlashInfer / CUTLASS mainloop).- **Christopher Owen, spark-ds41f** (Apache-2.0): the packed-BF16 vocabulary projection (b12x patch 0012) whose format we ported to Triton in a screen (not adopted, see docs/experiments.md).- **FlashInfer** (CUTLASS / CuTe DSL grouped GEMMs, the GEMVs) and **CUTLASS**: the kernels the MoE tile choice and the GPU checks run on; since v2.8.4 also the b12x MXFP8 GEMM and quantiser (`mm_mxfp8`, `mxfp8_quantize`) that run the drafter's eligible linears (mx8w), used as shipped.- **NVIDIA** for the DGX Spark platform.- **speedbench** ([knapcio/speedbench](https://github.com/knapcio/speedbench)), our own benchmark, for the headline numbers and the long-context table; its frozen prompt set also feeds the decode table.
Our own earlier recipes contributed ideas reused here: the verify cap with dead-row expert remap (DeepSeek-V4.1recipe), the batch-aware pay-for-rows rule and the certified greedy LM head (GLM-5.3-Flash recipe), FP8 / low-bitdraft heads (DeepSeek-V4.1), and our spark-tools and speedbench for measurement.
Every lever adopted from someone else's work gets a line here and an entry in the Credit column of the README.123456789101112131415161718192021MIT License
Copyright (c) 2026 Zbigniew Majewski
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354Inkling-2-Mini on one NVIDIA DGX Spark
Repository-authored launch scripts, benchmark scripts and documentation: MIT, see LICENSE.
Third-party code vendored in this repository:- overlay/inkling_pico12/third_party/pico/: kernels/gemv16.cu, kernels/common.cuh, kernels/dsk.h, common/check.h by Andy Shu (github.com/blaesus/dsgb10, formerly dsgx10, `ds41f-4xgx10-switchless/engine/` at commit f2117916, as carried in github.com/Picom-code/pico-dgx-ds4), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_pico12/third_party/pico/LICENSE. Unmodified except a two-line header naming the origin.- overlay/inkling_wide/csrc/bf16x_format.cuh: the `bf16x` reader (layout description, bf16x_raw_off, mad_imm, bf16x_dec, ldg_bf16x) copied from the same pico gemv16.cu (commit f2117916), MIT licence, Copyright (c) 2026 Andy Shu; full text in overlay/inkling_wide/third_party/pico/LICENSE.- overlay/inkling_cert/csrc/cert_ext.cu compiles kernels/gemv16.cu from overlay/inkling_pico12/third_party/pico/ (above) into its own extension; no further copy.
- overlay/inkling_scodes/csrc/scodes_sm120_mma_array.hpp: derived from CUTLASS's SM120 block-scaled grouped-GEMM collective mainloop (NVIDIA CORPORATION & AFFILIATES, BSD-3-Clause, licence text kept in the file header), modified to expand coded scale factors; scodes_group_gemm.cuh reduces FlashInfer 0.7.4's include/flashinfer/gemm/group_gemm_nvfp4_groupwise_sm120.cuh (Apache-2.0, Copyright (c) 2026 FlashInfer team) to the configuration SGLang uses and swaps in that mainloop.- overlay/inkling_kv12/ops.py: the decode / verify attention kernels (`_kv12_partials_np`, `_kv12_partials`) follow SGLang's Inkling2 split-KV decode kernel (`_decode_partials` in sglang.kernels.ops.attention.inkling2_decode_attention_sm90, sgl-project/sglang, Apache-2.0) with the same grid, tile order and online softmax, modified to read packed 12-bit K / V tiles from a side pool.- overlay/inkling_vattn/ops.py: `_inkernel_bias_partials` is the same SGLang `_decode_partials` kernel body (sgl-project/sglang, Apache-2.0), modified to compute the relative-position bias per key tile in-kernel.- overlay/inkling_rsfix/markov.py and overlay/inkling_rsfix/blockwise.py: the changes of sgl-project/sglang pull requests #51681 (dspark markov_sample) and #51692 (dspark blockwise_rejection), applied verbatim to copies of the image's functions (sgl-project/sglang, Apache-2.0). overlay/inkling_rsfix/reject.py and selector.py are copies of SGLang's reject_sampling kernels and DFLASH selector walk (Apache-2.0), modified as described in overlay/inkling_rsfix/README.md.
Third-party model files fetched at run time, not distributed in this repository:- Inkling-2-Mini-DFlash2 (huggingface.co/incoai/Inkling-2-Mini-DFlash2) by incoai, revision 4f9088ea66c21f2b99ed657d1941c306b03e84d2: the draft model (config.json, model.safetensors) and its SGLang compatibility patch (sglang_inkling_dflash2.py). Licensed under the Apache License, Version 2.0; you may not use these files except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. scripts/download.sh fetches them unmodified at that revision; scripts/launch.sh checks their sha256 and runs the patch, unmodified, inside the serving container only. The draft method builds on DFlash (github.com/z-lab/dflash).
The serving engines run from their published container images, pinned by digest in scripts/launch.sh:- SGLang (sgl-project/sglang), lmsysorg/sglang:inkling-2-mini, Apache-2.0.- vLLM (vllm-project/vllm), vllm/vllm-openai:inkling-2-mini, Apache-2.0.bench/decode_table.py reads the prompt file of speedbench (knapcio/speedbench, MIT) from a separate checkout; theprompts themselves are not copied here.
No model weights or container images are distributed. The Inkling-2-Mini weights (thinkingmachines/Inkling-2-Mini)are Apache-2.0 from Thinking Machines Lab; read the model card for the terms that apply to anything you serve.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164# inkling_attn: prefill attention with the relative bias computed in-kernel
Switch: `INKLING_ATTN=prefill_swa[,prefill_global]` (or `all`); unset = nothing is imported.
## What it replaces
Stock prefill, per layer visit (`Inkling2Attention._forward`, non-compact branch):
1. `RelLogitsProj`: cuBLAS einsum `thd,de->the`, writes BF16 `[t, 24, 1024]` (403 MB for an 8K chunk);2. FA4 SM120 (`flash_attn_with_kvcache` -> `_flash_attn_varlen_func`): a shear kernel copies it into `[round_up(t, 64), 24, 1280]`, then the attention mainloop TMA-loads 2 bytes of bias per score.
(`inkling_prefill.bias_layout` fuses 1 and the shear copy; the mainloop still reads the sheared tensor.)
With this package, one CUDA kernel (`csrc/attn_kernel.cuh`) computes the bias inside the attention mainloop: eachwarp holds its 16 query rows' `r` (`[16, 16]`, the rel-clip output) as an MMA A fragment, multiplies it by the`proj` columns of the tile's 79 distances (10 extra m16n8k16 MMAs per 16 x 64 tile, about +8 % MMA work), stagesthe BF16-rounded `[16, 80]` result in shared memory and reads it back sheared. No `[t, 24, 1024]` tensor exists.FA2-style kernel: 4 warps x 16 rows (BM 64), 64-key tiles, Q in registers, cp.async K/V from the paged cache(page 128), ldmatrix on XOR-swizzled rows, FP32 online softmax, BF16 P, FP32 output + LSE in FA4's layout.232-236 registers, no spills, 43 KB smem, 2 CTAs per SM. `proj` is repacked per call by a tiny kernel so each lane loads itsB fragment with one 8-byte load.
| lever | layers | taken calls ||---|---|---|| `prefill_swa` | 40 sliding-window visits per token (window 1024) | prefill / extend, BF16 KV, no CP, no breakable graph || `prefill_global` | 8 global visits per token | same; bias work only on tiles within 1024 keys of the diagonal |
Decode, target verify and draft extend never enter a visit (stock paths untouched).
## Long prefixes: 8 warps from `INKLING_ATTN_W8_FROM` keys (default 131072)
The 4-warp kernel (BM 64, 2 CTAs / SM) keeps ~71 TF/s up to ~256-320K prefix keys in isolation (~150K in serving)and falls to the stock rate (~47 TF/s) at 512K-1M as its K/V traffic per FLOP stops being served from L2. The 8-warpinstantiation (BM 128, half the bytes per FLOP) holds ~69 TF/s at every prefix and computes every rowbit-identically. On global layers, for the BF16 loader and the packed-prefix loader alike, the binding launches twogrids per call (`launch_global`): requests whose prefix (seqused_k - new rows) is >= `INKLING_ATTN_W8_FROM` run on8 warps, the others on 4; each CTA reads its request's lengths on the device and returns before any shared-memoryaccess when the other grid owns the request (no host sync, CUDA-graph capturable). `INKLING_ATTN_W8_FROM=0`, SWAlayers and `INKLING_ATTN_WARPS=8` keep a single launch. Checks: `tests/test_w8split_cpu.py`,a development GPU check, not shipped (both loaders, 256K-1M, graph replay).
## Math and exactness
Same math as stock: bias = BF16(FP32 dot of r and proj) for distances 0..1023 (0 beyond on global layers),s = qk * scale + bias in FP32, causal (+ window 1023 on SWA layers), P rounded to BF16 before PV, FP32 output,natural-log LSE (-inf for a row with no key). Differences are FP32 accumulation order (QK, bias dot, PV andonline-softmax tile boundaries: 64 keys here, 128 in FA4). Measured against an FP32 reference (no TF32) on real`proj` weights: see Results; the kernel's error is at or below stock FA4's at every shape.
## Patch points (patch.py)
- `Inkling2Attention._forward`: marks an eligible visit (context variable); nothing else changes.- `RelLogitsProj.__call__`: inside the visit returns `r` itself (no einsum); SGLang then narrows it like any `rel_bias` (row prefix views keep the data pointer).- `flash_attention_v4_sm120._flash_attn_varlen_func`: a `rel_bias` that is (a row prefix of) the visit's `r` runs `ops.prefill_attention` with the layer's `proj` and returns FA4's `(out, lse)`; a call the kernel does not cover falls back to stock FA4 with the einsum bias; an `r` marker outside its visit raises.
Install-time checks: `check_sources` looks for the exact code the patches rely on in the installed sglang(`_forward`, `RelLogitsProj`, the SM120 wrapper, the backend's `rel_bias` / LSE handling, FA4's bias applicationand shear pads, the SM120 module selection, CP and breakable-graph helpers); a mismatch raises (exit 78 throughsitecustomize). `RelLogitsProj.forward`'s signature is checked at patch time.
## Arming (sitecustomize.py)
Add after the `INKLING_PREFILL` block (order does not matter for correctness; see coexistence):
```python if _on("INKLING_ATTN"): import inkling_attn inkling_attn.install()```
and forward `INKLING_ATTN` into the container in `scripts/launch.sh` like the other switches. The extension isbuilt when the model imports `inkling2_attn` (before any CUDA-graph capture), about 1 min on the first start, thenreused from `INKLING_ATTN_CACHE` (default `/root/.cache/inkling-attn`). Pre-build once with`python3 -m inkling_attn.build`. Start-up log: `[inkling_attn pid=...] enabled prefill_swa ...` and`extension built|reused ...`. `inkling_attn.patch.STATS` counts kernel / fallback / shadowed visits (eager mode).
## Coexistence with inkling_prefill
- `bias_layout` becomes unnecessary for the layers this package takes: in their visits `RelLogitsProj.__call__` returns `r` before `bias_layout`'s `forward` wrapper runs, and `bias_layout`'s varlen wrapper passes the width-16 marker through. Layers not taken (e.g. global layers with only `prefill_swa`) still get `bias_layout`. Keeping `bias_layout` armed is therefore harmless and useful for `prefill_swa`-only.- Works in either install order (dispatch is at `__call__`, one level before any `forward` wrapper).- `qkvr_split`, `quant_once`, `partial_bf16`: independent.
## CUDA graphs
SGLang captures prefill graphs for this model (Backend.FULL, buckets up to `chunked_prefill_size` 8192, chunkswith a prefix replay too; docs/prefill/PREFILL.md 2.3). The kernel is captured inside them: static grid`(cdiv(q rows, 64) + requests) x heads`, every request split read from `cu_seqlens_q` / `seqused_k` on the device,no host sync, no allocation except the LSE `torch.empty` (graph pool). Rows past `cu_seqlens_q[-1]` are notwritten, as FA4. Breakable prefill graphs (attention replayed outside the visit) are excluded.
## Results (GB10, clocks untouched, 2026-11-21)
`results/kbench/round2/attn/check_attn.py`, run5 (`runs/run5.log`, `runs/results_run5.json`). Inputs: real layer-0 / layer-5`proj`, q, k ~ N(0, 1.5^2), v ~ N(0, 1), r ~ N(0, 2^2), shuffled pages of 128.
**Correctness**: max abs error vs an FP32 reference (no TF32, the stock BF16-rounded bias), sampled rows incl.query-block edges, all 24 heads:
| case | kind | out err ours / stock | LSE err ours / stock ||---|---|---|---|| chunk 8192, prefix 0 | SWA / global | 5.149e-3 / 5.149e-3, 3.437e-3 / 3.437e-3 | 1.647e-3 / 1.646e-3, 5.7e-6 / 1.5e-5 || chunk 8192, prefix 8K | SWA / global | 3.678e-3 / 3.682e-3, 2.463e-3 / 2.452e-3 | 2.375e-4 / 2.384e-4, 7.06e-5 / 7.15e-5 || chunk 8192, prefix 32K | SWA / global | 2.609e-3 / 2.606e-3, 5.686e-3 / 5.735e-3 | 4.0e-5 / 4.0e-5, 1.698e-3 / 1.698e-3 || chunk 2048, prefix 0 | SWA / global | 3.633e-3 / 3.634e-3, 3.870e-3 / 3.869e-3 | 3.8e-6 / 3.8e-6, 9.3e-5 / 9.3e-5 || 5 requests + empty slots | SWA / global | 3.732e-3 / 3.732e-3, 3.548e-3 / 3.548e-3 | 2.77e-5 / 2.67e-5, 4.1e-5 / 4.1e-5 || tiny rows (1, 3, 65, 17) | SWA / global | 3.653e-3 / 3.653e-3, 3.141e-3 / 3.141e-3 | 1.9e-6 / 2.9e-6, 1.9e-6 / 2.9e-6 |
Ours and stock are equally far from the reference (both dominated by the BF16 rounding of P); the worst relativeexcess is +0.4 % on out and +3.6 % on one LSE at the 1e-5 absolute level. No NaN, every covered row written.CUDA-graph capture replayed with 4 different request splits: bit-equal to eager, rows past `cu_seqlens_q[-1]`untouched. Patch routing: wrapper == direct call, fallback == stock bit for bit, escaped marker raises,RelLogitsProj dispatch correct in both install orders with bias_layout. CPU emulation of the lane-level indexmath (`emulate_kernel.py`) matches a dense FP64 reference.
**Speed** (cold L2: 128 MiB read before each rep; median of 20; useful FLOPs = 4 * 24 * 128 * visible keys;stock = einsum + FA4 with shear; bias_layout = Triton sheared bias + FA4 presheared; ours = repack + kernel):
| kind | chunk | prefix | stock us (TF/s) | bias_layout us (TF/s) | ours us (TF/s) | vs stock | vs bias_layout ||---|---|---|---|---|---|---|---|| SWA | 2048 | 0 | 2336 (8.3) | 1561 (12.4) | 427 (45.2) | 5.47x | 3.65x || SWA | 2048 | 8K | 2453 (10.5) | 1680 (15.3) | 524 (49.2) | 4.68x | 3.20x || SWA | 2048 | 32K | 2465 (10.5) | 1672 (15.4) | 520 (49.5) | 4.74x | 3.21x || SWA | 8192 | 0 | 9659 (10.0) | 6245 (15.5) | 1846 (52.3) | 5.23x | 3.38x || SWA | 8192 | 8K | 9830 (10.5) | 6420 (16.1) | 1933 (53.3) | 5.08x | 3.32x || SWA | 8192 | 32K | 9816 (10.5) | 6419 (16.1) | 1966 (52.4) | 4.99x | 3.26x || global | 2048 | 0 | 2460 (10.5) | 1684 (15.3) | 520 (49.6) | 4.73x | 3.24x || global | 2048 | 8K | 6735 (34.4) | 5881 (39.4) | 3298 (70.3) | 2.04x | 1.78x || global | 2048 | 32K | 19753 (43.1) | 18934 (44.9) | 12063 (70.5) | 1.64x | 1.57x || global | 8192 | 0 | 16780 (24.6) | 13336 (30.9) | 6259 (65.9) | 2.68x | 2.13x || global | 8192 | 8K | 33887 (36.5) | 30264 (40.9) | 17916 (69.0) | 1.89x | 1.69x || global | 8192 | 32K | 86358 (43.0) | 82526 (45.0) | 53135 (69.8) | 1.63x | 1.55x || global | 8192 | 120K | 279140 (45.8) | 275093 (46.5) | 179440 (71.2) | 1.56x | 1.53x |
(The einsum alone is 2.0 ms per 8K chunk.) Global layers reach the bias-free FA4 rate (67-70 TF/s indocs/prefill/PREFILL.md); SWA reaches 52-53 TF/s against FA4's bias-free 55-56.
Variants measured (run4): `INKLING_ATTN_WARPS=8` (BM 128, 1 CTA / SM) is 4-15 % slower; the unpacked proj loads(4 x LDG.16 per fragment instead of one 8-byte load) are 10-12 % slower on SWA. Defaults: 4 warps, packed.
**End-to-end estimate** (`estimate_e2e.py`: per 8K chunk, 40 SWA + 8 global visits at the measured per-visittimes, global interpolated over the prefix):
| prompt | recipe today (all inkling_prefill levers) | + inkling_attn (SWA only) | + inkling_attn (SWA + global) ||---|---|---|---|| 8K | 1.93 s, 4,253 tok/s | 1.75 s | 1.69 s, ~4,840 tok/s (-12 %) || 32K | 8.28 s, 3,958 tok/s | 7.57 s | 7.08 s, ~4,630 tok/s (-15 %) || 128K | 47.7 s, 2,749 tok/s | 44.8 s | 38.3 s, ~3,420 tok/s (-20 %) |
Against the stock engine (no inkling_prefill): 2.40 -> 2.00 s, 10.1 -> 8.2 s, 54.0 -> 42.0 s. Microbench-based;to be confirmed by the serving benchmark.
## Files
- `csrc/attn_kernel.cuh` kernel, `csrc/inkling_attn_ext.cu` binding, `build.py`, `ops.py`, `patch.py`, `__init__.py`.- Tests: `tests/test_install.py` (CPU: env parsing, source checks). GPU tests and bench (scratch): `results/kbench/round2/attn/check_attn.py` (GPU: correctness vs FP32 reference and stock, graph replay, patch routing, microbench), `emulate_kernel.py` (CPU emulation of the kernel's lane-level index math), `estimate_e2e.py` (end-to-end estimate from the bench).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""Inkling-2-Mini prefill attention overlay for SGLang on DGX Spark (GB10, sm_121).
INKLING_ATTN=prefill_swa[,prefill_global] (or "all") unset / empty: install() does nothing and nothing is imported.
prefill_swa sliding-window layers (40 of the 48 layer visits) at prefill / extend: one CUDA kernel computes the relative-position bias inside the attention mainloop (from r [t, 24, 16] and proj [16, 1024]) instead of the stock einsum -> [t, 24, 1024] BF16 tensor -> FA4 shear copy -> FA4 with bias.prefill_global the same for the 8 global (causal) visits; the bias is non-zero only within 1024 keys of the diagonal, so most key tiles of a long prefix run without bias work.
Decode, target verify and draft extend are untouched. Same math as stock (BF16-rounded bias, FP32 scores,BF16 P, FP32 output and LSE); differences are FP32 accumulation order only (see README.md for the measurederror against an FP32 reference, side by side with stock FA4's).
install() parses the env, checks the patch targets in the installed sglang sources (without importing sglang),registers post-import hooks and prints one line. Problems raise RuntimeError (the combined sitecustomize thenexits with code 78). The CUDA extension is built (or reused from INKLING_ATTN_CACHE, default~/.cache/inkling-attn) when the Inkling attention module is imported, before any CUDA graph capture.INKLING_ATTN_VERBOSE=1 logs each applied patch."""
import importlib.utilimport osimport sys
from . import _hook
LEVERS = ("prefill_swa", "prefill_global")
ATTN = "srt/models/inkling_common/inkling2_attn.py"
_SOURCE_CHECKS = ( (ATTN, ( "class Inkling2Attention(", "def _forward(self, hidden_states, positions, forward_batch, *, attn, attn_padded):", "rel_bias = self.rel_logits_proj(r)", "attention_kwargs = dict(rel_bias=rel_bias, **bias_kwargs)", "from sglang.srt.model_executor.forward_context import get_attn_backend", "from sglang.srt.runtime_context import get_model, get_parallel, get_platform", "self.rel_extent = config.sliding_window_size if is_local else config.rel_extent", "sliding_window_size=config.sliding_window_size - 1 if is_local else -1", "out_dtype=torch.float32", "pack_gqa=False", "return_lse=True,", "r = self.rel_l2_clip(", )), ("srt/models/inkling_common/attn.py", ( "class RelLogitsProj(", "log_scaling_tau: torch.Tensor | None = None", "self.proj = nn.Parameter(torch.empty(d_rel, rel_extent), requires_grad=False)", 'return torch.einsum("thd,de->the", r, self.proj)', )), ("kernels/ops/attention/flash_attention_v4_sm120.py", ( "_flash_attn_varlen_func,", "result = _flash_attn_varlen_func(", "seqused_k=cache_seqlens,", 'rel_bias_kwargs["rel_bias"] = rel_bias', "if window_size == (-1, -1):", )), ("srt/layers/attention/flashattention_backend.py", ( 'kwargs["rel_bias"] = rel_bias', "softmax_lse.T", "cache_seqlens=cache_seqlens,", )), ("kernels/ops/attention/fa4_sm120/flash_fwd.py", ( "acc_S[i] = acc_S[i] * base_softmax_scale", "sBias[row, col, consumer_state.index].to(", )), ("kernels/ops/attention/flash_attn/cute/shearing_bias.py", ( "-Float32.inf if const_expr(window_size_left is not None) else 0.0", )), ("kernels/ops/attention/flash_attn/cute/interface.py", ( "else (num_head, total_q)", )), ("srt/model_executor/runner_backend_utils/breakable_cuda_graph/context.py", ( "def is_in_breakable_cuda_graph(", )), ("srt/layers/cp/utils.py", ( "def is_cp_active(forward_batch) -> bool:", )), ("srt/layers/attention/flashattention_backend.py", ( "if device_capability[0] == 12:", "from sglang.kernels.ops.attention.flash_attention_v4_sm120 import (", )),)
STATE = {"installed": False, "levers": (), "applied": []}
def _log(msg): sys.stderr.write(f"[inkling_attn pid={os.getpid()}] {msg}\n") sys.stderr.flush()
def parse_levers(value): items = [v.strip() for v in value.split(",") if v.strip()] items = [v for v in items if v.lower() not in ("0", "off", "none", "false", "no")] if "all" in items: items = list(LEVERS) + [v for v in items if v != "all"] levers = tuple(dict.fromkeys(items)) unknown = [v for v in levers if v not in LEVERS] if unknown: raise RuntimeError(f"inkling_attn: unknown INKLING_ATTN entries {unknown}; known: {', '.join(LEVERS)}, all") return levers
def sglang_root(): spec = importlib.util.find_spec("sglang") # does not execute sglang if spec is None or not spec.submodule_search_locations: raise RuntimeError("inkling_attn: the sglang package is not importable") return list(spec.submodule_search_locations)[0]
def check_sources(root=None): root = root or sglang_root() for rel, needles in _SOURCE_CHECKS: path = os.path.join(root, rel) try: with open(path, encoding="utf-8") as f: text = f.read() except OSError as exc: raise RuntimeError(f"inkling_attn: patch target {path} is missing") from exc missing = [n for n in needles if n not in text] if missing: raise RuntimeError(f"inkling_attn: patch target {path} lacks {missing}")
def _attach(module_name, fn): def callback(module): fn(module) STATE["applied"].append(module_name) if os.environ.get("INKLING_ATTN_VERBOSE"): _log(f"patched {module_name}")
_hook.when_imported(module_name, callback)
def _register(levers): from . import patch
kinds = tuple(lv.split("_", 1)[1] for lv in levers) # "swa" / "global"
def attn_cb(module): patch.patch_attn(module, kinds) if not os.environ.get("INKLING_ATTN_LAZY_BUILD"): from . import build
build.load() info = build.INFO _log(f"extension {'reused' if info['cached'] else 'built'} in {info['seconds']:.1f} s ({info['tag']})")
_attach(patch.SM120_MODULE, patch.patch_sm120) _attach(patch.COMMON_ATTN_MODULE, patch.patch_common_attn) _attach(patch.ATTN_MODULE, attn_cb)
def install(levers=None, root=None): """Activate the levers named in INKLING_ATTN (or `levers`). Idempotent.""" if STATE["installed"]: return STATE["levers"] levers = parse_levers(os.environ.get("INKLING_ATTN", "") if levers is None else ",".join(levers)) if not levers: STATE["installed"] = True return () check_sources(root) _register(levers) STATE.update(installed=True, levers=levers) _log("enabled " + " ".join(levers)) return levers1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Post-import hooks: run a callback right after a module finishes executing.
Patches attach lazily so that processes which never import the model pay nothingand never import sglang or torch. If the target module is already imported, thecallback runs at once. A callback that raises makes the import of its target fail.Several overlays may each install a finder of this kind; they nest (each wraps theloader the next one returned), so every package's callbacks run."""
import importlib.abcimport sysimport threading
_lock = threading.RLock()_callbacks: dict = {}_finder = None
class _Loader(importlib.abc.Loader): def __init__(self, inner, name): self._inner = inner self._name = name
def create_module(self, spec): create = getattr(self._inner, "create_module", None) return create(spec) if create is not None else None
def exec_module(self, module): self._inner.exec_module(module) _run(self._name, module)
def __getattr__(self, attr): return getattr(self._inner, attr)
class _Finder(importlib.abc.MetaPathFinder): def __init__(self): self._busy = set()
def find_spec(self, fullname, path, target=None): if fullname not in _callbacks or fullname in self._busy: return None self._busy.add(fullname) try: spec = None for finder in sys.meta_path: if finder is self or not hasattr(finder, "find_spec"): continue spec = finder.find_spec(fullname, path, target) if spec is not None: break finally: self._busy.discard(fullname) if spec is None or spec.loader is None: return None spec.loader = _Loader(spec.loader, fullname) return spec
def _run(name, module): with _lock: callbacks = _callbacks.pop(name, []) for callback in callbacks: callback(module)
def when_imported(name, callback): """Call callback(module) once module `name` has been imported.""" global _finder with _lock: module = sys.modules.get(name) if module is None: _callbacks.setdefault(name, []).append(callback) if _finder is None: _finder = _Finder() sys.meta_path.insert(0, _finder) return callback(module)
def pending(): with _lock: return sorted(_callbacks)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Build (or reuse) the inkling_attn CUDA extension with torch.utils.cpp_extension.
Sources: csrc/inkling_attn_ext.cu (binding) + csrc/attn_kernel.cuh (kernel), compiled for sm_121a into<cache>/<tag>/, where <cache> is INKLING_ATTN_CACHE (default ~/.cache/inkling-attn, i.e. /root/.cache/inkling-attnin the container) and <tag> hashes the sources, the flags and the torch / CUDA versions, so a changed input neverreuses a stale build. Needs nvcc and ninja (both in the SGLang image); no GPU is needed to build.
python3 -m inkling_attn.build # build now (once, before serving); prints the path"""
import hashlibimport osimport sysimport time
HERE = os.path.dirname(os.path.abspath(__file__))SOURCES = (os.path.join(HERE, "csrc", "inkling_attn_ext.cu"),)HEADERS = (os.path.join(HERE, "csrc", "attn_kernel.cuh"),)NAME = "inkling_attn_ext"
_UNDEF = ( "-U__CUDA_NO_HALF_OPERATORS__", "-U__CUDA_NO_HALF_CONVERSIONS__", "-U__CUDA_NO_BFLOAT16_CONVERSIONS__", "-U__CUDA_NO_HALF2_OPERATORS__",)
def default_cache_dir(): return os.environ.get("INKLING_ATTN_CACHE") or os.path.join(os.path.expanduser("~"), ".cache", "inkling-attn")
def cuda_flags(arch="121a"): return [ f"-gencode=arch=compute_{arch},code=sm_{arch}", "-O3", "-std=c++20", "-lineinfo", *_UNDEF, ]
def build_tag(flags, torch_version, cuda_version): h = hashlib.sha256() for path in SOURCES + HEADERS: with open(path, "rb") as f: h.update(os.path.basename(path).encode() + b"\0" + f.read() + b"\0") h.update("\0".join(flags).encode()) h.update(f"\0{torch_version}\0{cuda_version}".encode()) return h.hexdigest()[:16]
_EXT = 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) tag = build_tag(flags, torch.__version__, torch.version.cuda) build_dir = os.path.join(cache_dir or default_cache_dir(), tag) os.makedirs(build_dir, exist_ok=True) cached = any(f.endswith(".so") and f.startswith(NAME) for f in os.listdir(build_dir)) t0 = time.monotonic() try: ext = cpp_extension.load( name=NAME, sources=list(SOURCES), extra_cuda_cflags=flags, extra_include_paths=[os.path.join(HERE, "csrc")], build_directory=build_dir, verbose=verbose, ) except Exception as exc: # noqa: BLE001 raise RuntimeError(f"inkling_attn: building the extension in {build_dir} failed: {exc}") from exc if not callable(getattr(ext, "fwd", None)): raise RuntimeError(f"inkling_attn: extension in {build_dir} lacks fwd()") INFO.update(build_dir=build_dir, cached=cached, seconds=time.monotonic() - t0, tag=tag) _EXT = ext return ext
def main(argv=None): import argparse
p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) p.add_argument("--cache", default=default_cache_dir()) p.add_argument("--verbose", action="store_true") a = p.parse_args(argv) load(a.cache, verbose=a.verbose) print(f"inkling_attn extension {'reused' if INFO['cached'] else 'built'} in {INFO['seconds']:.1f} s: {INFO['build_dir']}") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555// inkling_attn: prefill/extend attention for Inkling-2-Mini on GB10 (sm_121) with the relative-position bias// computed inside the kernel.//// Math (the same as SGLang's FA4 path with rel_bias, flash_attn/cute/interface.py + fa4_sm120/flash_fwd.py):// for request b, query row i (0 <= i < sq), absolute position p = i + (sk - sq), key j (0 <= j < sk):// visible j <= p, and for sliding-window layers also j >= p - window_left// d = p - j (relative distance)// bias = bf16( sum_e r[t, h, e] * proj[e, d] ) if d < rel_extent, else 0 (FP32 dot, BF16 round:// the stock cuBLAS einsum thd,de->the writes a BF16 tensor)// s = qk * softmax_scale + bias (FP32)// out = softmax_j(s) @ V (P rounded to BF16 before the PV MMA, as FA4 does), FP32 [T, H, 128]// lse = ln(sum_j exp(s)) FP32 [H, T] (-inf when a row sees no key)//// Instead of reading a materialised [T, H, rel_extent] tensor (2 bytes per score from DRAM), each warp// computes the bias of its 16 query rows x 64 keys tile from r (a 16 x 16 A fragment held in registers) and// proj (10 B fragments, L1-cached loads) with 10 extra m16n8k16 MMAs, stages the 16 x 80 BF16 result in shared// memory and reads it back sheared (element (a, b) of the score tile is T[a][a + 63 - b]).//// FA2-style: 4 warps x 16 query rows (BM = 64), BN = 64 keys a tile, Q fragments in registers, K and V single// buffered with cp.async (the K load of the next tile overlaps PV, the V load overlaps QK + softmax), ldmatrix// on 128-byte XOR-swizzled rows, online softmax in FP32. Paged KV (page size a multiple of 64), GQA by head index.#pragma once
#include <cuda_bf16.h>#include <cstdint>
namespace inkling_attn {
constexpr int kD = 128; // head dimconstexpr int kBN = 64; // keys a tileconstexpr int kDRel = 16; // r / proj inner dimconstexpr int kTCols = 16 + kBN; // staged bias columns a warp tile (79 used, +1 for the odd-row shift)constexpr int kTStride = 88; // BF16 elements a staged row (bank-conflict check: <= 2-way)constexpr float kLog2e = 1.4426950408889634f;constexpr int tstage_bytes(int warps) { return warps * 16 * kTStride * 2; }
struct Params { const __nv_bfloat16* q; // [T, H, 128] long long q_st, q_sh; const __nv_bfloat16* k; // [pages, page_size, H_kv, 128] long long k_sp, k_ss, k_sh; const __nv_bfloat16* v; long long v_sp, v_ss, v_sh; // Packed planes share the byte stride of the allocator's page envelope. const uint8_t *sm, *ex; const int *esc, *off, *overflow_ref, *flags; const uint16_t *staging, *overflow; long long packed_stride; int kv_heads, stage_slots, overflow_slots; const int* page_table; // [B, max_pages] long long pt_s; const int* cu_q; // [n_req + 1] const int* seq_k; // [>= n_req] int n_req; const __nv_bfloat16* r; // [T, H, 16] long long r_st, r_sh; const __nv_bfloat16* proj; // [16, rel_extent] contiguous const __nv_bfloat16* projp; // optional packed copy [rel_extent + 1, 16] (pack_proj), row rel_extent = 0 int rel_extent; float* out; // [T, H, 128] long long o_st, o_sh; float* lse; // lse[h * lse_sh + t] long long lse_sh; int heads, group, page_size; int total_q; // rows of q (guards cu_seqlens_q) int pt_cols; // page_table columns (guards seqused_k) int num_pages; // pages of the KV cache (guards page ids) float scale; int window_left; // sliding-window layers only // request selection (global layers, two launches of different warp counts over one call, see ops.W8_FROM): // 0 = every request; 1 = requests whose prefix (seqused_k - new rows) is < sel_keys; 2 = prefix >= sel_keys. int sel_mode, sel_keys; // gated epilogue (kGate, sliding-window BF16 path): y[t, h*128 + d] = bf16(x * sigmoid(gate) * sigmoid(lse - sink)) // with x = O / l, exactly SGLang's gate_sink kernel (inkling2/gate_sink.cuh) on the FP32 out and LSE this kernel // would have written; out is then not written (lse still is). const __nv_bfloat16* gate; // [T, H * 128], row stride g_st (16-byte aligned rows: staged with 16-byte loads) long long g_st; const __nv_bfloat16* sink; // [T, H], row stride s_st long long s_st; __nv_bfloat16* y; // [T, H * 128], row stride y_st long long y_st;};
namespace dev {
__device__ __forceinline__ uint32_t smem_u32(const void* p) { return static_cast<uint32_t>(__cvta_generic_to_shared(p));}
__device__ __forceinline__ void cp_async16(uint32_t dst, const void* src, bool valid) { const int n = valid ? 16 : 0; // 0: zero-fill, nothing read asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(dst), "l"(src), "r"(n) : "memory");}__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;\n" ::: "memory"); }__device__ __forceinline__ void cp_wait_all() { asm volatile("cp.async.wait_group 0;\n" ::: "memory"); }
__device__ __forceinline__ void ldsm_x4(uint32_t& r0, uint32_t& r1, uint32_t& r2, uint32_t& r3, uint32_t addr) { asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) : "r"(addr) : "memory");}__device__ __forceinline__ void ldsm_x4_t(uint32_t& r0, uint32_t& r1, uint32_t& r2, uint32_t& r3, uint32_t addr) { asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) : "r"(addr) : "memory");}
// D += A * B, m16n8k16, BF16 inputs, FP32 accumulate__device__ __forceinline__ void mma(float (&c)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { asm volatile( "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " "{%0,%1,%2,%3};\n" : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1));}
__device__ __forceinline__ float ex2(float x) { float y; asm("ex2.approx.ftz.f32 %0, %1;\n" : "=f"(y) : "f"(x)); return y;}
__device__ __forceinline__ uint32_t pack_bf16(float lo, float hi) { const __nv_bfloat162 v = __floats2bfloat162_rn(lo, hi); return *reinterpret_cast<const uint32_t*>(&v);}
__device__ __forceinline__ uint32_t ld_u32(const __nv_bfloat16* p) { return __ldg(reinterpret_cast<const unsigned int*>(p));}
__device__ __forceinline__ uint32_t ld_u16(const __nv_bfloat16* p) { return static_cast<uint32_t>(__ldg(reinterpret_cast<const unsigned short*>(p)));}
} // namespace dev
// proj [16, E] -> projp [E + 1, 16]: row d = {P(0,d),P(1,d),P(8,d),P(9,d), P(2,d),P(3,d),P(10,d),P(11,d), ...},// i.e. lane qd's B-fragment words {P(2qd,d),P(2qd+1,d)} and {P(2qd+8,d),P(2qd+9,d)} are 8 contiguous bytes;// row E is zero (distances beyond the extent).__global__ void pack_proj(const __nv_bfloat16* __restrict__ proj, __nv_bfloat16* __restrict__ projp, int E) { const int i = blockIdx.x * blockDim.x + threadIdx.x; // one output element if (i >= (E + 1) * kDRel) return; const int d = i / kDRel, slot = i % kDRel; const int qd = slot / 4, w = slot % 4; const int e = 2 * qd + (w & 1) + 8 * (w >> 1); projp[i] = d < E ? proj[e * E + d] : __float2bfloat16_rn(0.f);}
// Eight BF16 words for one swizzled shared-memory vector. No FP conversion.__device__ __forceinline__ uint4 packed_vector(const Params& p, int page, int kind, int head, int row, int dim, bool valid) { const uint4 zero = make_uint4(0, 0, 0, 0); if (!valid || page <= 0 || page >= p.num_pages) return zero; const long long start = static_cast<long long>(page) * p.packed_stride; const int flag = p.flags[start / sizeof(int)]; if (flag <= 0) return zero; const int element = ((kind * 128 + row) * p.kv_heads + head) * kD + dim; if (flag >= 2) { // The low byte stores valid rows plus one. The high bits store the slot. const int slot = flag >> 8; const int count = (flag & 255) - 1; if (slot >= p.stage_slots || row >= count || count > 128) return zero; const auto* src = p.staging + static_cast<long long>(slot) * 2 * 128 * p.kv_heads * kD; return *reinterpret_cast<const uint4*>(src + element); } const int lane = head * 2 + kind; const int ref = p.overflow_ref[start / sizeof(int) + lane]; if (ref) { if (ref < 0 || ref > p.overflow_slots) return zero; const auto* src = p.overflow + static_cast<long long>(ref - 1) * 128 * kD; return *reinterpret_cast<const uint4*>(src + row * kD + dim); } const auto sm = *reinterpret_cast<const uint2*>(p.sm + start + element); const uint32_t ex = *reinterpret_cast<const uint32_t*>(p.ex + start + element / 2); uint32_t words[4] = {};#pragma unroll for (int i = 0; i < 8; ++i) { const uint32_t bits = ((i < 4 ? sm.x : sm.y) >> (8 * (i & 3))) & 255; const uint32_t code = (ex >> (4 * i)) & 15; const uint32_t exponent = code == 15 ? 0 : code + 116; const uint32_t word = ((bits & 128) << 8) | (exponent << 7) | (bits & 127); words[i / 2] |= word << (16 * (i & 1)); } if (((ex & (ex >> 1) & (ex >> 2) & (ex >> 3)) & 0x11111111u) != 0) { const int* offsets = p.off + start / sizeof(int) + lane * 5 + row / 32; const int* entries = p.esc + start / sizeof(int) + lane * 64; const int begin = offsets[0], end = offsets[1]; const int limit = begin >= 0 && end >= begin && end <= 64 ? end : begin; for (int i = begin; i < limit; ++i) { const unsigned entry = entries[i]; const int column = (entry >> 16) & 127; if (((entry >> 23) & 127) == row && column >= dim && column < dim + 8) { const int index = column - dim, shift = (index & 1) * 16; words[index / 2] = (words[index / 2] & ~(0xffffu << shift)) | ((entry & 0xffffu) << shift); } } } return make_uint4(words[0], words[1], words[2], words[3]);}
// kW warps x 16 query rows a CTA (BM = 16 kW): 4 warps -> 2 CTAs / SM, 8 warps -> 1 CTA / SM (half the K/V// shared-memory fills per FLOP). Dynamic shared memory: tstage_bytes(kW).// gate_sink.cuh's sigmoid: ex2.approx / rcp.approx with round-to-nearest multiply and add__device__ __forceinline__ float gs_sigmoid(float x) { float e, r; float const t = __fmul_rn(-x, 1.4426950408889634f); asm("ex2.approx.f32 %0, %1;" : "=f"(e) : "f"(t)); asm("rcp.approx.f32 %0, %1;" : "=f"(r) : "f"(__fadd_rn(e, 1.0f))); return r;}
template <bool kLocal, bool kPacked, int kW, bool kPackedKV = false, bool kGate = false>__global__ void __launch_bounds__(kW * 32, 8 / kW) prefill_fwd(const Params p) { constexpr int kThr = kW * 32; constexpr int kBMw = 16 * kW; using namespace dev; __shared__ __align__(128) __nv_bfloat16 sK[kBN * kD]; __shared__ __align__(128) __nv_bfloat16 sV[kBN * kD]; extern __shared__ __align__(16) __nv_bfloat16 sT[]; // kW * 16 * kTStride (dynamic)
const int tid = threadIdx.x; const int warp = tid >> 5, lane = tid & 31, g = lane >> 2, qd = lane & 3;
// ---- work item: heads fastest (the 24 heads of one query block share K/V in L2), the last query blocks // (the most keys on causal global layers) first. const int lin = static_cast<int>(gridDim.x - 1 - blockIdx.x); const int head = lin % p.heads; int tile = lin / p.heads; int b = -1, start = 0, sq = 0; int prev_end = 0; for (int i = 0; i < p.n_req; ++i) { // metadata guards (CTA-uniform): rows inside q and never shared by two requests, keys inside the page table const int s = max(p.cu_q[i], prev_end); const int e = min(p.cu_q[i + 1], p.total_q); const int len = e > s ? e - s : 0; prev_end = max(prev_end, e); const int nb = (len + kBMw - 1) / kBMw; if (tile < nb) { b = i; start = s; sq = len; break; } tile -= nb; } if (b < 0) return;
const int sk = min(max(p.seq_k[b], 0), p.pt_cols * p.page_size); const int off = sk - sq; // prefix length if (p.sel_mode != 0) { // the other launch takes request b (decided on the unclamped prefix) const long long pre = static_cast<long long>(p.seq_k[b]) - sq; if ((pre >= p.sel_keys) != (p.sel_mode == 2)) return; } const int m0 = tile * kBMw; const int kvh = head / p.group; const int wl = p.window_left; const int lo_key = kLocal ? max(0, m0 + off - wl) : 0; const int hi_key = static_cast<int>(min(static_cast<long long>(sk), static_cast<long long>(m0) + kBMw + off)); const int nb_lo = lo_key / kBN; const int nb_hi = hi_key > lo_key ? hi_key / kBN + (hi_key % kBN != 0) : nb_lo; // exclusive
const int wrow0 = m0 + warp * 16; // request-relative first row of this warp const bool warp_rows = wrow0 < sq; const int pw0 = wrow0 + off; // its absolute position
// ---- Q and r fragments (A operands), rows wrow0 + g and + 8 uint32_t qa[8][4]; uint32_t ra[4]; { const int r0 = wrow0 + g, r1 = r0 + 8; const bool v0 = r0 < sq, v1 = r1 < sq; const long long t0 = start + (v0 ? r0 : 0), t1 = start + (v1 ? r1 : 0); const __nv_bfloat16* q0 = p.q + t0 * p.q_st + static_cast<long long>(head) * p.q_sh; const __nv_bfloat16* q1 = p.q + t1 * p.q_st + static_cast<long long>(head) * p.q_sh;#pragma unroll for (int kk = 0; kk < 8; ++kk) { const int c = 16 * kk + 2 * qd; qa[kk][0] = v0 ? ld_u32(q0 + c) : 0u; qa[kk][1] = v1 ? ld_u32(q1 + c) : 0u; qa[kk][2] = v0 ? ld_u32(q0 + c + 8) : 0u; qa[kk][3] = v1 ? ld_u32(q1 + c + 8) : 0u; } const __nv_bfloat16* rr0 = p.r + t0 * p.r_st + static_cast<long long>(head) * p.r_sh; const __nv_bfloat16* rr1 = p.r + t1 * p.r_st + static_cast<long long>(head) * p.r_sh; ra[0] = v0 ? ld_u32(rr0 + 2 * qd) : 0u; ra[1] = v1 ? ld_u32(rr1 + 2 * qd) : 0u; ra[2] = v0 ? ld_u32(rr0 + 2 * qd + 8) : 0u; ra[3] = v1 ? ld_u32(rr1 + 2 * qd + 8) : 0u; }
float o[16][4];#pragma unroll for (int i = 0; i < 16; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.f; float mrow[2] = {-INFINITY, -INFINITY}; float lrow[2] = {0.f, 0.f};
// ---- one K or V tile of 64 keys -> shared memory (row = key, 16 chunks of 16 B, chunk ^= row & 7); // keys outside [lo_key, sk) are zero-filled (never read from memory). const long long pt_row = static_cast<long long>(b) * p.pt_s; auto load_tile = [&](__nv_bfloat16* dst, const __nv_bfloat16* base, long long sp, long long ss, long long sh, int nb, int kind) { const int n0 = nb * kBN; const int col = n0 / p.page_size; const int page = col >= 0 && col < p.pt_cols ? p.page_table[pt_row + col] : -1; const bool page_ok = page >= 0 && page < p.num_pages; // a bad page id reads nothing (zero tile) const int slot0 = n0 % p.page_size; const int chunk = tid & 15;#pragma unroll for (int i = 0; i < kBN * 16 / kThr; ++i) { const int row = (tid >> 4) + i * (kThr / 16); const int j = n0 + row; const bool ok = page_ok && j >= lo_key && j < sk; auto* target = dst + row * kD + ((chunk ^ (row & 7)) * 8); if constexpr (kPackedKV) { *reinterpret_cast<uint4*>(target) = packed_vector(p, page, kind, kvh, slot0 + row, chunk * 8, ok); } else { const auto* src0 = base + static_cast<long long>(page_ok ? page : 0) * sp + static_cast<long long>(kvh) * sh; const auto* src = ok ? src0 + static_cast<long long>(slot0 + row) * ss + chunk * 8 : src0; cp_async16(smem_u32(target), src, ok); } } };
__nv_bfloat16* tw = sT + warp * 16 * kTStride; const int par = g & 1; // odd rows are staged one column to the right so sheared reads are 4-byte aligned const __nv_bfloat16* proj = p.proj; const int ext = p.rel_extent;
if (nb_hi > nb_lo) load_tile(sK, p.k, p.k_sp, p.k_ss, p.k_sh, nb_hi - 1, 0); cp_commit();
for (int nb = nb_hi - 1; nb >= nb_lo; --nb) { const int n0 = nb * kBN; cp_wait_all(); __syncthreads(); // K(nb) visible; every warp is done with V(nb + 1) load_tile(sV, p.v, p.v_sp, p.v_ss, p.v_sh, nb, 1); cp_commit();
// this warp's rows see keys [pw0 - wl, pw0 + 15] const bool active = warp_rows && n0 <= pw0 + 15 && (!kLocal || n0 + kBN - 1 >= pw0 - wl); float s[8][4]; if (active) {#pragma unroll for (int i = 0; i < 8; ++i) s[i][0] = s[i][1] = s[i][2] = s[i][3] = 0.f; // S = Q K^T#pragma unroll for (int kk = 0; kk < 8; ++kk) {#pragma unroll for (int np = 0; np < 4; ++np) { const int key = 8 * (2 * np + (lane >> 4)) + (lane & 7); const int chunk = 2 * kk + ((lane >> 3) & 1); uint32_t b0, b1, b2, b3; ldsm_x4(b0, b1, b2, b3, smem_u32(sK + key * kD + ((chunk ^ (key & 7)) * 8))); mma(s[2 * np], qa[kk], b0, b1); mma(s[2 * np + 1], qa[kk], b2, b3); } } // relative bias: d(a, b) = pw0 + a - (n0 + b) = dbase + c, c = a + 63 - b in [0, 78] const int dbase = pw0 - n0 - (kBN - 1); if (dbase < ext) { float t[10][4];#pragma unroll for (int ct = 0; ct < 10; ++ct) { t[ct][0] = t[ct][1] = t[ct][2] = t[ct][3] = 0.f; const int d = dbase + 8 * ct + g; const bool in = d >= 0 && d < ext; // d < 0: masked (causal); d >= ext: bias 0 if constexpr (kPacked) { const int row = in ? d : ext; // the zero row const uint2 w = __ldg(reinterpret_cast<const uint2*>(p.projp + static_cast<long long>(row) * kDRel) + qd); mma(t[ct], ra, w.x, w.y); } else { const __nv_bfloat16* pc = proj + (in ? d : 0); const uint32_t k0 = in ? ld_u16(pc + (2 * qd) * ext) : 0u; const uint32_t k1 = in ? ld_u16(pc + (2 * qd + 1) * ext) : 0u; const uint32_t k8 = in ? ld_u16(pc + (2 * qd + 8) * ext) : 0u; const uint32_t k9 = in ? ld_u16(pc + (2 * qd + 9) * ext) : 0u; mma(t[ct], ra, k0 | (k1 << 16), k8 | (k9 << 16)); } }#pragma unroll for (int ct = 0; ct < 10; ++ct) { const int col = 8 * ct + 2 * qd + par; tw[g * kTStride + col] = __float2bfloat16_rn(t[ct][0]); tw[g * kTStride + col + 1] = __float2bfloat16_rn(t[ct][1]); tw[(g + 8) * kTStride + col] = __float2bfloat16_rn(t[ct][2]); tw[(g + 8) * kTStride + col + 1] = __float2bfloat16_rn(t[ct][3]); } __syncwarp();#pragma unroll for (int nt = 0; nt < 8; ++nt) {#pragma unroll for (int h = 0; h < 2; ++h) { const int a = g + 8 * h; const int s1 = a + (kBN - 2) - 8 * nt - 2 * qd + par; // even const uint32_t w = *reinterpret_cast<const uint32_t*>(tw + a * kTStride + s1); const float b_e0 = __uint_as_float(w & 0xffff0000u); // column c -> key n0 + 8nt + 2qd const float b_e1 = __uint_as_float(w << 16); // column c-1 -> key n0 + 8nt + 2qd + 1 s[nt][2 * h] = fmaf(s[nt][2 * h], p.scale, b_e0); s[nt][2 * h + 1] = fmaf(s[nt][2 * h + 1], p.scale, b_e1); } } } else {#pragma unroll for (int i = 0; i < 8; ++i) { s[i][0] *= p.scale; s[i][1] *= p.scale; s[i][2] *= p.scale; s[i][3] *= p.scale; } } // mask: causal diagonal, window left edge (rows past sq see zero-filled keys and are never stored) const bool need_mask = (n0 + kBN - 1 > pw0) || (kLocal && n0 < pw0 + 15 - wl); if (need_mask) {#pragma unroll for (int nt = 0; nt < 8; ++nt) {#pragma unroll for (int e = 0; e < 4; ++e) { const int a = g + 8 * (e >> 1); const int j = n0 + 8 * nt + 2 * qd + (e & 1); const int pr = pw0 + a; if (j > pr || (kLocal && j < pr - wl)) s[nt][e] = -INFINITY; } } } // online softmax (natural-log units, exp2 with log2(e) like FA4)#pragma unroll for (int h = 0; h < 2; ++h) { float mx = -INFINITY;#pragma unroll for (int nt = 0; nt < 8; ++nt) mx = fmaxf(mx, fmaxf(s[nt][2 * h], s[nt][2 * h + 1])); mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 1)); mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 2)); const float mnew = fmaxf(mrow[h], mx); const float muse = mnew == -INFINITY ? 0.f : mnew; const float alpha = ex2((mrow[h] - muse) * kLog2e); mrow[h] = mnew; float sum = 0.f;#pragma unroll for (int nt = 0; nt < 8; ++nt) { const float p0 = ex2((s[nt][2 * h] - muse) * kLog2e); const float p1 = ex2((s[nt][2 * h + 1] - muse) * kLog2e); s[nt][2 * h] = p0; s[nt][2 * h + 1] = p1; sum += p0 + p1; } lrow[h] = lrow[h] * alpha + sum;#pragma unroll for (int dn = 0; dn < 16; ++dn) { o[dn][2 * h] *= alpha; o[dn][2 * h + 1] *= alpha; } } }
cp_wait_all(); __syncthreads(); // V(nb) visible; every warp is done with K(nb) if (nb - 1 >= nb_lo) load_tile(sK, p.k, p.k_sp, p.k_ss, p.k_sh, nb - 1, 0); cp_commit();
if (active) { // O += P V#pragma unroll for (int kk = 0; kk < 4; ++kk) { uint32_t pa[4]; pa[0] = pack_bf16(s[2 * kk][0], s[2 * kk][1]); pa[1] = pack_bf16(s[2 * kk][2], s[2 * kk][3]); pa[2] = pack_bf16(s[2 * kk + 1][0], s[2 * kk + 1][1]); pa[3] = pack_bf16(s[2 * kk + 1][2], s[2 * kk + 1][3]);#pragma unroll for (int dp = 0; dp < 8; ++dp) { const int i4 = lane >> 3; const int key = 16 * kk + 8 * (i4 & 1) + (lane & 7); const int chunk = 2 * dp + (i4 >> 1); uint32_t v0, v1, v2, v3; ldsm_x4_t(v0, v1, v2, v3, smem_u32(sV + key * kD + ((chunk ^ (key & 7)) * 8))); mma(o[2 * dp], pa, v0, v1); mma(o[2 * dp + 1], pa, v2, v3); } } } } cp_wait_all();
// ---- epilogue: O / l (FP32), LSE = m + ln(l) // Gated (kGate): the warp's 16 x 128 gate tile is staged in shared memory (sK / sV are free once every warp left the // mainloop) with coalesced 16-byte loads, y is computed in place in the MMA layout, then stored with coalesced // 16-byte stores. 16-byte chunks are XOR-swizzled by row so the MMA-layout accesses are bank-conflict free. __nv_bfloat16* wbuf = nullptr; if constexpr (kGate) { __syncthreads(); wbuf = (warp < 4 ? sK + warp * 16 * kD : sV + (warp - 4) * 16 * kD);#pragma unroll for (int i = 0; i < 8; ++i) { const int rr = 2 * i + (lane >> 4), cc = (lane & 15) * 8; if (wrow0 + rr < sq) { const long long t = start + wrow0 + rr; *reinterpret_cast<uint4*>(wbuf + rr * kD + (((cc >> 3) ^ (rr & 7)) * 8)) = *reinterpret_cast<const uint4*>(p.gate + t * p.g_st + static_cast<long long>(head) * kD + cc); } } __syncwarp(); }#pragma unroll for (int h = 0; h < 2; ++h) { float l = lrow[h]; l += __shfl_xor_sync(0xffffffffu, l, 1); l += __shfl_xor_sync(0xffffffffu, l, 2); const int row = wrow0 + g + 8 * h; if (row < sq) { const bool ok = l > 0.f && l == l; const float inv = ok ? 1.f / l : 0.f; const long long t = start + row; if constexpr (kGate) { const float lse_v = ok ? mrow[h] + logf(l) : -INFINITY; if (qd == 0) p.lse[static_cast<long long>(head) * p.lse_sh + t] = lse_v; const float sc = gs_sigmoid(__fsub_rn(lse_v, __bfloat162float(p.sink[t * p.s_st + head]))); const int rl = g + 8 * h; // row within the warp's staged tile#pragma unroll for (int dn = 0; dn < 16; ++dn) { __nv_bfloat162* cell = reinterpret_cast<__nv_bfloat162*>(wbuf + rl * kD + ((dn ^ (rl & 7)) * 8) + 2 * qd); const __nv_bfloat162 gg = *cell; const float x0 = o[dn][2 * h] * inv, x1 = o[dn][2 * h + 1] * inv; __nv_bfloat162 yy; yy.x = __float2bfloat16_rn(__fmul_rn(__fmul_rn(x0, gs_sigmoid(__low2float(gg))), sc)); yy.y = __float2bfloat16_rn(__fmul_rn(__fmul_rn(x1, gs_sigmoid(__high2float(gg))), sc)); *cell = yy; // in place: each element is read and written by this thread only } } else { float* orow = p.out + t * p.o_st + static_cast<long long>(head) * p.o_sh;#pragma unroll for (int dn = 0; dn < 16; ++dn) { *reinterpret_cast<float2*>(orow + 8 * dn + 2 * qd) = make_float2(o[dn][2 * h] * inv, o[dn][2 * h + 1] * inv); } if (qd == 0) p.lse[static_cast<long long>(head) * p.lse_sh + t] = ok ? mrow[h] + logf(l) : -INFINITY; } } } if constexpr (kGate) { __syncwarp();#pragma unroll for (int i = 0; i < 8; ++i) { const int rr = 2 * i + (lane >> 4), cc = (lane & 15) * 8; if (wrow0 + rr < sq) { const long long t = start + wrow0 + rr; *reinterpret_cast<uint4*>(p.y + t * p.y_st + static_cast<long long>(head) * kD + cc) = *reinterpret_cast<const uint4*>(wbuf + rr * kD + (((cc >> 3) ^ (rr & 7)) * 8)); } } }}
} // namespace inkling_attn123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326// inkling_attn: PyTorch binding of the prefill attention kernel (attn_kernel.cuh).//// fwd(q, k_cache, v_cache, page_table, cu_seqlens_q, seqused_k, r, proj, out, lse, softmax_scale, window_left)// q [T, H, 128] bf16 (last dim contiguous)// k_cache [pages, page_size, H_kv, 128] bf16, v_cache the same (any strides of the first three dims)// page_table [B, max_pages] int32, cu_seqlens_q [n_req + 1] int32, seqused_k [>= n_req] int32// r [T, H, 16] bf16, proj [16, rel_extent] bf16 contiguous// out [T, H, 128] fp32 (written for the rows cu_seqlens_q covers), lse [H, T] fp32 (same rows)// window_left < 0: global (causal) layer; >= 0: sliding window [p - window_left, p]// No allocation, no host sync: the launch goes to PyTorch's current stream and is CUDA-graph capturable.// Rows of q past cu_seqlens_q[-1] are left untouched, as FA4 leaves them.// w8_from_keys > 0 (global layers, warps 4, BF16 or packed KV): requests with a prefix of >= w8_from_keys keys run// on 8 warps (BM 128), the others on 4, in two launches whose CTAs pick their requests on the device (no host sync,// CUDA-graph capturable). Both variants compute every row bit-identically.#include <torch/extension.h>#include <pybind11/stl.h>
#include <ATen/cuda/CUDAContext.h>#include <c10/cuda/CUDAException.h>#include <c10/cuda/CUDAGuard.h>
#include "attn_kernel.cuh"
namespace {
using inkling_attn::Params;
bool aligned(const void* p, size_t n) { return reinterpret_cast<uintptr_t>(p) % n == 0; }
// Gated launches: the kernel writes y only for rows < cu_q[n_req]; the rows after it (bucket padding of a captured// prefill graph) are zeroed here on the device, so a smaller replay never leaves an earlier replay's rows in y.__global__ void zero_tail_rows(__nv_bfloat16* y, long long y_st, int cols, const int* cu_q, int n_req, int rows) { const int end = cu_q[n_req]; for (int r = blockIdx.x; r < rows; r += gridDim.x) { if (r < end) continue; for (int c = threadIdx.x * 8; c < cols; c += blockDim.x * 8) *reinterpret_cast<uint4*>(y + r * y_st + c) = make_uint4(0, 0, 0, 0); }}
template <bool kLocal, bool kPacked, int kW, bool kPackedKV, bool kGate = false>void launch_w(const Params& p, dim3 blocks, cudaStream_t stream) { constexpr int smem = inkling_attn::tstage_bytes(kW); static bool configured[256] = {}; // per instantiation and device (the attribute is per context) int dev = 0; C10_CUDA_CHECK(cudaGetDevice(&dev)); TORCH_CHECK(dev >= 0 && dev < 256, "inkling_attn: device index out of range"); if (!configured[dev]) { C10_CUDA_CHECK(cudaFuncSetAttribute(inkling_attn::prefill_fwd<kLocal, kPacked, kW, kPackedKV, kGate>, cudaFuncAttributeMaxDynamicSharedMemorySize, smem)); configured[dev] = true; } inkling_attn::prefill_fwd<kLocal, kPacked, kW, kPackedKV, kGate><<<blocks, kW * 32, smem, stream>>>(p);}
template <bool kLocal, bool kPacked, bool kPackedKV = false, bool kGate = false>void launch(const Params& p, dim3 blocks, int64_t warps, cudaStream_t stream) { if (warps == 8) launch_w<kLocal, kPacked, 8, kPackedKV, kGate>(p, blocks, stream); else launch_w<kLocal, kPacked, 4, kPackedKV, kGate>(p, blocks, stream);}
// global layers: one launch, or the 8-warp (long prefixes) + 4-warp (the rest) pairtemplate <bool kPacked, bool kPackedKV, bool kGate = false>void launch_global(const Params& p, dim3 blocks, int64_t warps, int64_t w8_from_keys, int64_t grid8, cudaStream_t stream) { if (warps != 4 || w8_from_keys <= 0) { launch<false, kPacked, kPackedKV, kGate>(p, blocks, warps, stream); return; } Params p8 = p; // long-prefix requests first on 8 warps (half the K/V traffic per FLOP) p8.sel_mode = 2; p8.sel_keys = static_cast<int>(w8_from_keys); launch<false, kPacked, kPackedKV, kGate>(p8, dim3(static_cast<unsigned>(grid8)), 8, stream); C10_CUDA_KERNEL_LAUNCH_CHECK(); Params p4 = p; p4.sel_mode = 1; p4.sel_keys = static_cast<int>(w8_from_keys); launch<false, kPacked, kPackedKV, kGate>(p4, blocks, 4, stream);}
void fwd(const torch::Tensor& q, const torch::Tensor& k, const torch::Tensor& v, const torch::Tensor& page_table, const torch::Tensor& cu_q, const torch::Tensor& seq_k, const torch::Tensor& r, const torch::Tensor& proj, const torch::Tensor& out, const torch::Tensor& lse, double scale, int64_t window_left, const c10::optional<torch::Tensor>& projp_buf, int64_t warps, const c10::optional<std::vector<torch::Tensor>>& packed_kv, int64_t w8_from_keys, const c10::optional<torch::Tensor>& gate, const c10::optional<torch::Tensor>& sinks, const c10::optional<torch::Tensor>& y, bool zero_tail) { TORCH_CHECK(warps == 4 || warps == 8, "inkling_attn: warps must be 4 or 8"); TORCH_CHECK(w8_from_keys >= 0 && w8_from_keys < (int64_t(1) << 31), "inkling_attn: w8_from_keys out of range"); TORCH_CHECK(q.is_cuda() && q.scalar_type() == at::kBFloat16 && q.dim() == 3 && q.size(2) == inkling_attn::kD && q.stride(2) == 1, "inkling_attn: q must be CUDA bf16 [T, H, 128] with a contiguous last dim"); const int64_t T = q.size(0), H = q.size(1); int64_t page_size, hkv, num_pages; if (packed_kv) { TORCH_CHECK(window_left < 0 && packed_kv->size() == 8, "inkling_attn: invalid packed KV cache"); const auto& sm = (*packed_kv)[0]; TORCH_CHECK(sm.dim() == 5 && sm.size(1) == 2 && sm.size(2) == 128 && sm.size(4) == 128, "inkling_attn: invalid packed SM plane"); num_pages = sm.size(0); page_size = 128; hkv = sm.size(3); } else { for (const auto* c : {&k, &v}) { TORCH_CHECK(c->is_cuda() && c->scalar_type() == at::kBFloat16 && c->dim() == 4 && c->size(3) == inkling_attn::kD && c->stride(3) == 1, "inkling_attn: k/v cache must be CUDA bf16 [pages, page_size, H_kv, 128] with a contiguous last dim"); TORCH_CHECK(c->stride(0) % 8 == 0 && c->stride(1) % 8 == 0 && c->stride(2) % 8 == 0 && aligned(c->data_ptr(), 16), "inkling_attn: k/v cache rows must be 16-byte aligned"); } TORCH_CHECK(k.sizes() == v.sizes(), "inkling_attn: k and v caches differ in shape"); page_size = k.size(1); hkv = k.size(2); num_pages = k.size(0); TORCH_CHECK(page_size > 0 && page_size % inkling_attn::kBN == 0, "inkling_attn: page size must be a positive multiple of 64"); } TORCH_CHECK(H > 0, "inkling_attn: no heads"); TORCH_CHECK(hkv > 0 && H % hkv == 0, "inkling_attn: q heads must be a multiple of kv heads"); TORCH_CHECK(q.stride(0) % 2 == 0 && q.stride(1) % 2 == 0 && aligned(q.data_ptr(), 4), "inkling_attn: q alignment"); TORCH_CHECK(page_table.is_cuda() && page_table.scalar_type() == at::kInt && page_table.dim() == 2 && page_table.stride(1) == 1, "inkling_attn: page_table must be CUDA int32 [B, max_pages] with a contiguous last dim"); TORCH_CHECK(cu_q.is_cuda() && cu_q.scalar_type() == at::kInt && cu_q.dim() == 1 && cu_q.is_contiguous() && cu_q.numel() >= 1, "inkling_attn: cu_seqlens_q must be a contiguous CUDA int32 vector"); const int64_t n_req = cu_q.numel() - 1; TORCH_CHECK(seq_k.is_cuda() && seq_k.scalar_type() == at::kInt && seq_k.dim() == 1 && seq_k.is_contiguous() && seq_k.numel() >= n_req, "inkling_attn: seqused_k must be a contiguous CUDA int32 vector with one entry a request"); TORCH_CHECK(page_table.size(0) >= n_req, "inkling_attn: page_table has fewer rows than requests"); TORCH_CHECK(num_pages > 0 && num_pages < (int64_t(1) << 31) && page_table.size(1) * page_size < (int64_t(1) << 31), "inkling_attn: invalid KV cache or page table size"); TORCH_CHECK(r.is_cuda() && r.scalar_type() == at::kBFloat16 && r.dim() == 3 && r.size(0) == T && r.size(1) == H && r.size(2) == inkling_attn::kDRel && r.stride(2) == 1, "inkling_attn: r must be CUDA bf16 [T, H, 16] with a contiguous last dim"); TORCH_CHECK(r.stride(0) % 2 == 0 && r.stride(1) % 2 == 0 && aligned(r.data_ptr(), 4), "inkling_attn: r alignment"); TORCH_CHECK(proj.is_cuda() && proj.scalar_type() == at::kBFloat16 && proj.dim() == 2 && proj.size(0) == inkling_attn::kDRel && proj.is_contiguous() && proj.size(1) > 0, "inkling_attn: proj must be a contiguous CUDA bf16 [16, rel_extent]"); TORCH_CHECK(out.is_cuda() && out.scalar_type() == at::kFloat && out.dim() == 3 && out.size(0) == T && out.size(1) == H && out.size(2) == inkling_attn::kD && out.stride(2) == 1, "inkling_attn: out must be CUDA fp32 [T, H, 128] with a contiguous last dim"); TORCH_CHECK(out.stride(0) % 2 == 0 && out.stride(1) % 2 == 0 && aligned(out.data_ptr(), 8), "inkling_attn: out alignment"); TORCH_CHECK(lse.is_cuda() && lse.scalar_type() == at::kFloat && lse.dim() == 2 && lse.size(0) == H && lse.size(1) == T && lse.stride(1) == 1, "inkling_attn: lse must be CUDA fp32 [H, T] with a contiguous last dim"); for (const auto* t : {&k, &v, &page_table, &cu_q, &seq_k, &r, &proj, &out, &lse}) TORCH_CHECK(t->device() == q.device(), "inkling_attn: all tensors must be on q's device"); TORCH_CHECK(T < (int64_t(1) << 30) && n_req < (int64_t(1) << 20), "inkling_attn: too many rows"); if (T == 0 || (n_req == 0 && !y.has_value())) return; // gated with no requests: y is cleared after validation
Params p{}; p.q = reinterpret_cast<const __nv_bfloat16*>(q.data_ptr()); p.q_st = q.stride(0); p.q_sh = q.stride(1); if (packed_kv) { const auto& planes = *packed_kv; const std::vector<int64_t> inner_shapes[] = { {2, 128, hkv, 128}, {2, 128, hkv, 64}, {hkv, 2, 64}, {hkv, 2, 5}, {hkv, 2}, {1}, {2, 128, hkv, 128}, {128, 128}, }; for (int i = 0; i < 8; ++i) { const auto& plane = planes[i]; const auto dtype = i < 2 ? at::kByte : i < 6 ? at::kInt : at::kShort; TORCH_CHECK(plane.device() == q.device() && plane.scalar_type() == dtype && plane.dim() > 0 && plane.sizes().slice(1) == at::IntArrayRef(inner_shapes[i]), "inkling_attn: invalid packed KV device, dtype or shape"); if (i < 6) { TORCH_CHECK(plane.size(0) == num_pages && plane.select(0, 0).is_contiguous() && plane.stride(0) * plane.element_size() == planes[0].stride(0), "inkling_attn: packed planes must share a page stride"); } else { TORCH_CHECK(plane.is_contiguous() && plane.size(0) < (int64_t(1) << 31), "inkling_attn: invalid packed side arena layout"); } } p.sm = planes[0].data_ptr<uint8_t>(); p.ex = planes[1].data_ptr<uint8_t>(); p.esc = planes[2].data_ptr<int>(); p.off = planes[3].data_ptr<int>(); p.overflow_ref = planes[4].data_ptr<int>(); p.flags = planes[5].data_ptr<int>(); p.staging = reinterpret_cast<const uint16_t*>(planes[6].data_ptr<int16_t>()); p.overflow = reinterpret_cast<const uint16_t*>(planes[7].data_ptr<int16_t>()); p.packed_stride = planes[0].stride(0); p.kv_heads = static_cast<int>(hkv); p.stage_slots = static_cast<int>(planes[6].size(0)); p.overflow_slots = static_cast<int>(planes[7].size(0)); } else { p.k = reinterpret_cast<const __nv_bfloat16*>(k.data_ptr()); p.k_sp = k.stride(0); p.k_ss = k.stride(1); p.k_sh = k.stride(2); p.v = reinterpret_cast<const __nv_bfloat16*>(v.data_ptr()); p.v_sp = v.stride(0); p.v_ss = v.stride(1); p.v_sh = v.stride(2); } p.page_table = page_table.data_ptr<int>(); p.pt_s = page_table.stride(0); p.cu_q = cu_q.data_ptr<int>(); p.seq_k = seq_k.data_ptr<int>(); p.n_req = static_cast<int>(n_req); p.r = reinterpret_cast<const __nv_bfloat16*>(r.data_ptr()); p.r_st = r.stride(0); p.r_sh = r.stride(1); p.proj = reinterpret_cast<const __nv_bfloat16*>(proj.data_ptr()); p.rel_extent = static_cast<int>(proj.size(1)); p.out = out.data_ptr<float>(); p.o_st = out.stride(0); p.o_sh = out.stride(1); p.lse = lse.data_ptr<float>(); p.lse_sh = lse.stride(0); p.heads = static_cast<int>(H); p.group = static_cast<int>(H / hkv); p.page_size = static_cast<int>(page_size); p.total_q = static_cast<int>(T); p.pt_cols = static_cast<int>(page_table.size(1)); p.num_pages = static_cast<int>(num_pages); p.scale = static_cast<float>(scale); p.window_left = static_cast<int>(window_left); p.sel_mode = 0; p.sel_keys = 0; const bool gated = gate.has_value(); TORCH_CHECK(gated == sinks.has_value() && gated == y.has_value(), "inkling_attn: gate, sinks and y go together"); if (gated) { const auto& g = *gate; const auto& sk = *sinks; const auto& yy = *y; TORCH_CHECK(g.is_cuda() && g.device() == q.device() && g.scalar_type() == at::kBFloat16 && g.dim() == 2 && g.size(0) >= T && g.size(1) == H * inkling_attn::kD && g.stride(1) == 1 && g.stride(0) % 8 == 0 && aligned(g.data_ptr(), 16), "inkling_attn: gate must be CUDA bf16 [>= T, H * 128], contiguous last dim, 16-byte aligned rows"); TORCH_CHECK(sk.is_cuda() && sk.device() == q.device() && sk.scalar_type() == at::kBFloat16 && sk.dim() == 2 && sk.size(0) >= T && sk.size(1) == H && sk.stride(1) == 1, "inkling_attn: sinks must be CUDA bf16 [>= T, H] with a contiguous last dim"); TORCH_CHECK(yy.is_cuda() && yy.device() == q.device() && yy.scalar_type() == at::kBFloat16 && yy.dim() == 2 && yy.size(0) == T && yy.size(1) == H * inkling_attn::kD && yy.is_contiguous() && aligned(yy.data_ptr(), 16), "inkling_attn: y must be a contiguous CUDA bf16 [T, H * 128]"); { // y is written by many CTAs: it must not overlap anything the kernel reads or writes const auto y0 = reinterpret_cast<uintptr_t>(yy.data_ptr()), y1 = y0 + yy.numel() * 2; for (const auto* t : {&q, &k, &v, &r, &proj, &out, &lse, &g, &sk}) { const auto t0 = reinterpret_cast<uintptr_t>(t->data_ptr()); const auto t1 = t0 + (t->numel() ? (t->storage().nbytes() - t->storage_offset() * t->element_size()) : 0); TORCH_CHECK(y1 <= t0 || t1 <= y0, "inkling_attn: y overlaps an input or output buffer"); } } if (n_req == 0) { // no request rows: all of y is tail if (zero_tail) yy.zero_(); return; } p.gate = reinterpret_cast<const __nv_bfloat16*>(g.data_ptr()); p.g_st = g.stride(0); p.sink = reinterpret_cast<const __nv_bfloat16*>(sk.data_ptr()); p.s_st = sk.stride(0); p.y = reinterpret_cast<__nv_bfloat16*>(yy.data_ptr()); p.y_st = yy.stride(0); }
const int64_t bm = 16 * warps; const int64_t tiles = (T + bm - 1) / bm + n_req; const int64_t grid = tiles * H; TORCH_CHECK(grid < (int64_t(1) << 31), "inkling_attn: grid too large"); const int64_t grid8 = ((T + 127) / 128 + n_req) * H; const c10::cuda::CUDAGuard guard(q.device()); const auto stream = at::cuda::getCurrentCUDAStream(); TORCH_CHECK(window_left < 0 || proj.size(1) == window_left + 1, "inkling_attn: sliding-window layers need rel_extent == window + 1"); const bool packed = projp_buf.has_value(); if (packed) { const auto& pb = *projp_buf; TORCH_CHECK(pb.is_cuda() && pb.device() == q.device() && pb.scalar_type() == at::kBFloat16 && pb.is_contiguous() && pb.numel() == (proj.size(1) + 1) * inkling_attn::kDRel && aligned(pb.data_ptr(), 16), "inkling_attn: projp buffer must be a contiguous 16-byte aligned bf16 [(rel_extent + 1) * 16]"); const auto pb0 = reinterpret_cast<uintptr_t>(pb.data_ptr()), pb1 = pb0 + pb.numel() * 2; const auto pr0 = reinterpret_cast<uintptr_t>(proj.data_ptr()), pr1 = pr0 + proj.numel() * 2; TORCH_CHECK(pb1 <= pr0 || pr1 <= pb0, "inkling_attn: projp buffer overlaps proj"); p.projp = reinterpret_cast<const __nv_bfloat16*>(pb.data_ptr()); const int n = static_cast<int>(pb.numel()); inkling_attn::pack_proj<<<(n + 255) / 256, 256, 0, stream>>>(p.proj, reinterpret_cast<__nv_bfloat16*>(pb.data_ptr()), p.rel_extent); C10_CUDA_KERNEL_LAUNCH_CHECK(); } const dim3 blocks(static_cast<unsigned>(grid)); if (gated && zero_tail) { // zero_tail=false: a second launch into the same y (it must not clear the first's rows) const int zb = static_cast<int>(std::min<int64_t>(T, 1024)); zero_tail_rows<<<zb, 128, 0, stream>>>(p.y, p.y_st, static_cast<int>(H * inkling_attn::kD), p.cu_q, static_cast<int>(n_req), static_cast<int>(T)); C10_CUDA_KERNEL_LAUNCH_CHECK(); } if (packed_kv) { if (gated) { if (packed) launch_global<true, true, true>(p, blocks, warps, w8_from_keys, grid8, stream); else launch_global<false, true, true>(p, blocks, warps, w8_from_keys, grid8, stream); } else if (packed) launch_global<true, true>(p, blocks, warps, w8_from_keys, grid8, stream); else launch_global<false, true>(p, blocks, warps, w8_from_keys, grid8, stream); } else if (window_left >= 0) { if (gated) { if (packed) launch<true, true, false, true>(p, blocks, warps, stream); else launch<true, false, false, true>(p, blocks, warps, stream); } else if (packed) launch<true, true>(p, blocks, warps, stream); else launch<true, false>(p, blocks, warps, stream); } else { if (gated) { if (packed) launch_global<true, false, true>(p, blocks, warps, w8_from_keys, grid8, stream); else launch_global<false, false, true>(p, blocks, warps, w8_from_keys, grid8, stream); } else if (packed) launch_global<true, false>(p, blocks, warps, w8_from_keys, grid8, stream); else launch_global<false, false>(p, blocks, warps, w8_from_keys, grid8, stream); } C10_CUDA_KERNEL_LAUNCH_CHECK();}
} // namespace
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("fwd", &fwd, "Inkling-2-Mini prefill attention with the relative bias computed in-kernel", py::arg("q"), py::arg("k"), py::arg("v"), py::arg("page_table"), py::arg("cu_q"), py::arg("seq_k"), py::arg("r"), py::arg("proj"), py::arg("out"), py::arg("lse"), py::arg("scale"), py::arg("window_left"), py::arg("projp_buf") = py::none(), py::arg("warps") = 4, py::arg("packed_kv") = py::none(), py::arg("w8_from_keys") = 0, py::arg("gate") = py::none(), py::arg("sinks") = py::none(), py::arg("y") = py::none(), py::arg("zero_tail") = true);}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""Python entry point of the inkling_attn kernel (imported on the GPU path only)."""
from . import build
D_REL = 16HEAD_DIM = 128
import os
WARPS = int(os.environ.get("INKLING_ATTN_WARPS", "4")) # 4: BM 64, 2 CTAs / SM; 8: BM 128, 1 CTA / SMPACKED_PROJ = True # repack proj per call (one tiny launch) so each lane loads its B fragment with one 8-byte load# Global layers with WARPS 4 (BF16 and packed KV): a request whose prefix holds >= W8_FROM keys runs on 8 warps# (BM 128), the others on 4 (two launches, requests picked on the device). BM 64 holds ~71 TF/s up to ~256K prefix# keys in isolation (~150K in serving) and falls to ~47 TF/s at 512K-1M; BM 128 holds ~69 TF/s at every prefix and# is ~3-5 % slower below 256K. Bit-identical rows either way. 0 = off.W8_FROM = int(os.environ.get("INKLING_ATTN_W8_FROM", "131072"))
def prefill_attention(q, k_cache, v_cache, page_table, cu_seqlens_q, seqused_k, r, proj, softmax_scale, window_left, out=None, packed=None, warps=None, w8_from=None, lse=None, gate=None, sinks=None, y=None, zero_tail=True): """FA4-compatible (out, lse) of the Inkling prefill attention with the relative bias computed in-kernel.
q [T, H, 128] bf16; k_cache / v_cache [pages, page_size, H_kv, 128] bf16; page_table [B, max_pages] int32; cu_seqlens_q [n_req + 1] int32; seqused_k [n_req] int32 (prefix + new tokens); r [T, H, 16] bf16 (after the rel L2 clip, the RelLogitsProj input); proj [16, rel_extent] bf16; window_left: the layer's left window (sliding-window layers, rel_extent == window_left + 1) or None / negative (global causal layers). Returns out [T, H, 128] fp32 and lse [H, T] fp32 (FA4's varlen layout). Rows past cu_seqlens_q[-1] are not written. With gate [T, H*128] / sinks [T, H] / y [T, H*128] (any layer): the kernel writes y = bf16(out * sigmoid(gate) * sigmoid(lse - sink)) (SGLang's gate_sink on these values) instead of out and returns (y, lse). It first zeroes y's rows past cu_seqlens_q[-1] on the device; zero_tail=False skips that for a second launch into the same y (whose first launch already did it). """ import torch
ext = build.load() t, heads, _ = q.shape if out is None: out = torch.empty((t, heads, HEAD_DIM), dtype=torch.float32, device=q.device) if lse is None: lse = torch.empty((heads, t), dtype=torch.float32, device=q.device) wl = -1 if window_left is None or window_left < 0 else int(window_left) if r.stride(-1) != 1: r = r.contiguous() packed = PACKED_PROJ if packed is None else packed projp = torch.empty(((proj.shape[1] + 1) * D_REL,), dtype=torch.bfloat16, device=q.device) if packed else None ext.fwd(q, k_cache, v_cache, page_table, cu_seqlens_q, seqused_k, r, proj, out, lse, float(softmax_scale), wl, projp, WARPS if warps is None else int(warps), w8_from_keys=W8_FROM if w8_from is None else int(w8_from), gate=gate, sinks=sinks, y=y, zero_tail=bool(zero_tail)) return (out, lse) if y is None else (y, lse)
def packed_prefill_attention(q, layer, page_table, cu_seqlens_q, seqused_k, softmax_scale, *, r, proj, out=None, warps=None, w8_from=None, gate=None, sinks=None, y=None, zero_tail=True): """Run fused projected-bias prefill with exact KV reconstructed in shared memory.""" import torch
from inkling_kv12s.storage import validate_paged
validate_paged(q, layer, page_table, seqused_k, cu_seqlens_q) t, heads, _ = q.shape if out is None: out = torch.empty((t, heads, HEAD_DIM), dtype=torch.float32, device=q.device) lse = torch.empty((heads, t), dtype=torch.float32, device=q.device) if r.stride(-1) != 1: r = r.contiguous() projp = torch.empty(((proj.shape[1] + 1) * D_REL,), dtype=torch.bfloat16, device=q.device) if PACKED_PROJ else None planes = [*layer.planes, layer.stage, layer.overflow] ext = build.load() ext.fwd(q, layer.raw, layer.raw, page_table, cu_seqlens_q, seqused_k, r, proj, out, lse, float(softmax_scale), -1, projp, WARPS if warps is None else int(warps), planes, W8_FROM if w8_from is None else int(w8_from), gate=gate, sinks=sinks, y=y, zero_tail=bool(zero_tail)) return (out, lse) if y is None else (y, lse)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562"""Patch points of inkling_attn (prefill / extend attention with the relative bias computed in-kernel).
Stock prefill path per layer visit (inkling2_attn.py Inkling2Attention._forward, the non-compact branch): rel_bias = self.rel_logits_proj(r) # cuBLAS einsum -> BF16 [t, 24, rel_extent] attn(q, k, v, forward_batch, return_lse=True, rel_bias=rel_bias) -> FlashAttentionBackend.forward_extend -> flash_attn_with_kvcache (SM120) -> flash_attn_varlen_func -> _flash_attn_varlen_func (FA4: shear copy + attention with the sheared bias)
With this overlay, inside an eligible visit (prefill/extend only, see _visit_for): 1. Inkling2Attention._forward is wrapped to mark the visit (a context variable; nothing else changes); 2. RelLogitsProj.forward returns r itself (the [t, H, 16] rel-clip output, no einsum) and records it in the visit: r travels to the backend in the rel_bias slot, so every narrowing SGLang applies to rel_bias (graph_utils.attention_input_scope / _attention_on_real_rows slice rows) applies to r the same way; 3. flash_attention_v4_sm120._flash_attn_varlen_func (the module global the SM120 wrapper calls) is wrapped: a rel_bias that is (a row prefix of) the visit's r runs ops.prefill_attention with the layer's proj, returning FA4's (out, lse). Any call shape the kernel does not cover falls back to the stock call with the materialised einsum bias (same math as stock). An r-shaped rel_bias (width 16) that reaches FA4 outside its visit raises instead of being misread.
Breakable prefill graphs replay attention as a deferred eager call outside the visit, so they are excluded atthe visit check (as inkling_prefill.bias_layout does). Decode, target verify and draft extend never enter a visit.
Coexistence with inkling_prefill.bias_layout: both mark visits and wrap FA4's varlen entry, and bias_layoutwraps RelLogitsProj.forward. This package dispatches one level earlier, at RelLogitsProj.__call__ (beforenn.Module.__call__ reaches any forward wrapper), so in an eligible visit r is returned whatever order the twopackages were installed in; bias_layout's forward wrapper is not reached, its varlen wrapper sees a width-16rel_bias it did not make and passes it through, and layers this package does not take (e.g. global layers withonly prefill_swa armed) still get bias_layout's sheared bias. Should anything else consume an eligible visitfirst, the _forward wrapper notices (the visit's r stays unset) and logs it once.
Device route: the visit requires a CUDA device of compute capability 12.x, the condition under whichFlashAttentionBackend._load_fa4_kernels uses the patched SM120 module, and no context-parallel extend."""
import contextvarsimport osimport sysimport weakref
ATTN_MODULE = "sglang.srt.models.inkling_common.inkling2_attn"COMMON_ATTN_MODULE = "sglang.srt.models.inkling_common.attn"SM120_MODULE = "sglang.kernels.ops.attention.flash_attention_v4_sm120"BREAKABLE_MODULE = "sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.context"CP_MODULE = "sglang.srt.layers.cp.utils"MARK = "inkling_attn_prefill"D_REL = 16HEAD_DIM = 128
_CTX = contextvars.ContextVar("inkling_attn_ctx", default=None)STATS = {"kernel": 0, "fallback": 0, "shadowed": 0, "gated": 0, "gate_fallback": 0}# INKLING_ATTN_GATE=1: sliding-window prefill visits run the gated epilogue (gate_sink inside the attention kernel,# bit-identical to SGLang's gate_sink on the FP32 out + LSE). The visit records the gate / sinks its# _project_sources returns (an instance-level hook for the duration of the visit); the FA4 call then launches the# gated kernel (BF16 y + LSE; the FP32 out stays unwritten) and the visit's gate_sink call returns y.# INKLING_ATTN_GATE=all (or 2): global prefill visits too (BF16 and KV12S packed readers, via gate_begin / gate_commit)._GATE_ENV = os.environ.get("INKLING_ATTN_GATE", "").strip().lower()GATE_ALL = _GATE_ENV in ("all", "2")GATE = GATE_ALL or _GATE_ENV in ("1", "on", "true", "yes", "swa")
def _kernel_api_logging(): """SGLang's kernel API logging (SGLANG_KERNEL_API_LOGLEVEL > 0, parsed like kernel_api_logging._get_env) logs and may dump the FA4 wrapper's returned FP32 out before gate_sink runs; a gated launch leaves that buffer unwritten, so the gated epilogue stays off while it is enabled.""" try: return int(os.environ.get("SGLANG_KERNEL_API_LOGLEVEL", "0") or 0) != 0 except ValueError: return False
GATE_OFF_FOR_LOGGING = GATE and _kernel_api_logging()if GATE_OFF_FOR_LOGGING: GATE = False GATE_ALL = False_LOGGED = set()
def _log_once(key, msg): if key in _LOGGED: return _LOGGED.add(key) sys.stderr.write(f"[inkling_attn pid={os.getpid()}] {msg}\n") sys.stderr.flush()
if GATE_OFF_FOR_LOGGING: _log_once("gate_off", "gated epilogue OFF: SGLANG_KERNEL_API_LOGLEVEL is set (it reads the FA4 output buffer)")
class _Visit: __slots__ = ("owner", "local", "window_left", "r", "proj", "gate", "sinks", "tokens", "gated")
def __init__(self, owner, local, window_left, proj): self.owner = owner self.local = local self.window_left = window_left self.proj = proj self.r = None self.gate = self.sinks = self.tokens = None # from the visit's _project_sources (INKLING_ATTN_GATE) self.gated = None # (FP32 out buffer left unwritten, BF16 y) of a gated launch, until gate_sink takes y
class use_visit: """Context manager for direct calls (tools / tests): inside it, the patched varlen wrapper treats `r` (or a row prefix of it) passed as rel_bias as this package's marker for a layer with `proj`."""
def __init__(self, r, proj, window_left=None): local = window_left is not None and window_left >= 0 self._visit = _Visit(None, local, window_left if local else None, proj) self._visit.r = r _PRODUCED.append(weakref.ref(r)) del _PRODUCED[:-256] self._token = None
def __enter__(self): self._token = _CTX.set(self._visit) return self._visit
def __exit__(self, *exc): _CTX.reset(self._token) return False
_SM12X = {}
def _is_sm12x(device): """FlashAttentionBackend._load_fa4_kernels takes the SM120 FA4 module (the one patched here) iff major == 12.""" import torch
idx = device.index if device.index is not None else torch.cuda.current_device() if idx not in _SM12X: # GB10 only: the extension is built for sm_121a, and capability 12.x is what makes the backend use the # patched SM120 FA4 module _SM12X[idx] = tuple(torch.cuda.get_device_capability(idx)) == (12, 1) return _SM12X[idx]
def _visit_for(self, forward_batch, attn, get_attn_backend, get_model, in_breakable, kinds, cp_active=None): import torch
local = bool(getattr(self, "is_local", False)) if ("swa" if local else "global") not in kinds: return None if in_breakable is not None and in_breakable(): return None if cp_active is not None and cp_active(forward_batch): return None mode = forward_batch.forward_mode if not mode.is_extend() or mode.is_decode() or mode.is_target_verify(): return None for name in ("is_draft_extend", "is_draft_extend_v2"): fn = getattr(mode, name, None) if fn is not None and fn(): return None if getattr(attn, "pack_gqa", None): return None try: if get_model().kv_cache_dtype == "mxfp8": return None except Exception: # noqa: BLE001 return None contains = getattr(forward_batch, "contains_mm_inputs", None) if contains is not None and contains(): return None backend = get_attn_backend() if getattr(backend, "fa_skip_kv_cache", False) or getattr(backend, "use_mla", False): return None meta = getattr(backend, "forward_metadata", None) if meta is None: return None for name in ("swa_spec_metadata", "image_token_ranges", "local_attn_metadata"): if getattr(meta, name, None) is not None: return None if getattr(self, "head_dim", None) != HEAD_DIM or getattr(self, "d_rel", None) != D_REL: return None heads, kv_heads = self.num_tp_heads, self.num_tp_kv_heads if kv_heads <= 0 or heads % kv_heads: return None proj = getattr(getattr(self, "rel_logits_proj", None), "proj", None) rel = self.rel_extent if not ( isinstance(proj, torch.Tensor) and proj.is_cuda and _is_sm12x(proj.device) and proj.dtype == torch.bfloat16 and proj.dim() == 2 and tuple(proj.shape) == (D_REL, rel) and proj.is_contiguous() ): return None window = getattr(attn, "sliding_window_size", None) if local: if window is None or window < 0 or window + 1 != rel: return None elif window not in (None, -1): return None return _Visit(self, local, window if local else None, proj)
def make_forward(prev, get_attn_backend, get_model, in_breakable, kinds, cp_active=None): def _forward(self, hidden_states, positions, forward_batch, *, attn, attn_padded): visit = _visit_for(self, forward_batch, attn, get_attn_backend, get_model, in_breakable, kinds, cp_active) if visit is None: if GATE and _CTX.get() is not None: # an ineligible nested visit must not see the outer one token = _CTX.set(None) try: return prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) finally: _CTX.reset(token) return prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) token = _CTX.set(visit) hooked = False if GATE and (visit.local or GATE_ALL) and "_project_sources" not in self.__dict__: project = self._project_sources # the full (class-level, wrapped) chain
def _project_sources(sources): res = project(sources) if isinstance(res, tuple) and len(res) == 6: visit.gate, visit.sinks = res[4], res[5] visit.tokens = res[0].shape[0] return res
self.__dict__["_project_sources"] = _project_sources # instance attribute shadows the method hooked = True try: result = prev(self, hidden_states, positions, forward_batch, attn=attn, attn_padded=attn_padded) finally: if hooked: self.__dict__.pop("_project_sources", None) _CTX.reset(token) if visit.gated is not None: raise RuntimeError("inkling_attn: a gated attention output never reached gate_sink") if visit.r is None: STATS["shadowed"] += 1 _log_once( "shadowed", "an eligible visit never reached RelLogitsProj.__call__ with an r this package takes " "(something else produced the bias); that visit ran without this package", ) return result
_forward.__wrapped__ = prev setattr(_forward, MARK, True) return _forward
_PRODUCED = [] # weak references to the last r markers handed out (bounded)
def make_rel_call(prev): """RelLogitsProj.__call__: inside an eligible visit return r itself (the marker) before nn.Module.__call__, i.e. before every RelLogitsProj.forward wrapper, whatever order the overlays were installed in.""" import torch
def __call__(self, *args, **kwargs): r_out = args[0] if args else kwargs.get("r_out") log_scaling_tau = args[1] if len(args) > 1 else kwargs.get("log_scaling_tau") visit = _CTX.get() if ( visit is not None and visit.r is None and log_scaling_tau is None and visit.owner is not None and visit.owner.rel_logits_proj is self and self.proj is visit.proj and isinstance(r_out, torch.Tensor) and r_out.dim() == 3 and r_out.is_cuda and r_out.dtype == torch.bfloat16 and r_out.shape[1] == visit.owner.num_tp_heads and r_out.shape[2] == D_REL and r_out.stride(2) == 1 and len(args) + len(kwargs) <= 2 ): visit.r = r_out _PRODUCED.append(weakref.ref(r_out)) del _PRODUCED[:-256] return r_out return prev(self, *args, **kwargs)
__call__.__wrapped__ = prev setattr(__call__, MARK, True) return __call__
def _is_produced(bias): for ref in _PRODUCED: r = ref() if r is not None and r.device == bias.device and _same_storage_rows(bias, r): return True return False
def _same_storage_rows(bias, r): return ( bias.dim() == 3 and bias.data_ptr() == r.data_ptr() and bias.shape[1:] == r.shape[1:] and bias.stride() == r.stride() and bias.shape[0] <= r.shape[0] )
def packed_rel_projection(bias): """Resolve a fused projection marker intercepted by a packed attention reader.""" visit = _CTX.get() if visit is not None and visit.r is not None and _same_storage_rows(bias, visit.r): return visit.proj if bias.shape[-1] == D_REL and _is_produced(bias): raise RuntimeError("inkling_attn: packed reader received a marker outside its visit") return None
def _kernel_call(visit, bias, kwargs): """Arguments for ops.prefill_attention, or None when this call is outside what the kernel covers.""" import torch
q = kwargs.get("q") k = kwargs.get("k") v = kwargs.get("v") page_table = kwargs.get("page_table") cu_q = kwargs.get("cu_seqlens_q") seq_k = kwargs.get("seqused_k") out = kwargs.get("out") for name in ( "qv", "cu_seqlens_k", "seqused_q", "learnable_sink", "score_mod", "mask_mod", "aux_tensors", "q_descale", "k_descale", "v_descale", "sfq", "sfk", "sfv", "gather_kv_indices", "block_sparse_tensors", "aux_scalars", ): if kwargs.get(name) is not None: return None if kwargs.get("softcap") not in (None, 0.0) or kwargs.get("rel_bias_presheared"): return None if not kwargs.get("causal", False) or kwargs.get("num_splits", 1) not in (0, 1) or kwargs.get("pack_gqa"): return None window = tuple(kwargs.get("window_size", (None, None))) if visit.local: if window != (visit.window_left, 0): return None elif window not in ((None, None), (-1, -1), (None, 0), (-1, 0)): return None scale = kwargs.get("softmax_scale") if scale is None: return None if not all(isinstance(t, torch.Tensor) for t in (q, k, v, page_table, cu_q, seq_k)): return None if k.dim() != 4 or k.shape[1] <= 0 or k.shape[2] <= 0 or cu_q.numel() < 2 or q.dim() != 3 or q.shape[1] <= 0: return None if not ( q.dtype == k.dtype == v.dtype == torch.bfloat16 and q.dim() == 3 and q.shape[2] == HEAD_DIM and q.shape[1] == bias.shape[1] and q.shape[0] == bias.shape[0] and k.dim() == 4 and k.shape == v.shape and k.shape[3] == HEAD_DIM and k.shape[1] % 64 == 0 and q.shape[1] % k.shape[2] == 0 and page_table.dtype == cu_q.dtype == seq_k.dtype == torch.int32 and page_table.dim() == 2 and page_table.stride(1) == 1 and cu_q.is_contiguous() and seq_k.is_contiguous() ): return None if out is not None and not ( out.dtype == torch.float32 and tuple(out.shape) == (q.shape[0], q.shape[1], HEAD_DIM) and out.stride(2) == 1 ): return None if out is None: return None # FA4 would return q.dtype; Inkling always passes an FP32 out dev = q.device if not all(t.device == dev for t in (k, v, page_table, cu_q, seq_k, bias, out, visit.proj)): return None if not ( q.stride(2) == 1 and q.stride(0) % 2 == 0 and q.stride(1) % 2 == 0 and q.data_ptr() % 4 == 0 and all(c.stride(3) == 1 and c.stride(0) % 8 == 0 and c.stride(1) % 8 == 0 and c.stride(2) % 8 == 0 and c.data_ptr() % 16 == 0 for c in (k, v)) and bias.stride(0) % 2 == 0 and bias.stride(1) % 2 == 0 and bias.data_ptr() % 4 == 0 and out.stride(0) % 2 == 0 and out.stride(1) % 2 == 0 and out.data_ptr() % 8 == 0 and cu_q.dim() == 1 and seq_k.dim() == 1 and seq_k.numel() >= cu_q.numel() - 1 and page_table.shape[0] >= cu_q.numel() - 1 ): return None return dict( q=q, k_cache=k, v_cache=v, page_table=page_table, cu_seqlens_q=cu_q, seqused_k=seq_k, r=bias, proj=visit.proj, softmax_scale=float(scale), window_left=visit.window_left if visit.local else None, out=out, )
def make_varlen(stock): import torch
def _flash_attn_varlen_func(*args, **kwargs): bias = kwargs.get("rel_bias") if bias is not None and not args: visit = _CTX.get() if visit is not None and visit.r is not None and _same_storage_rows(bias, visit.r): call = _kernel_call(visit, bias, kwargs) if call is not None: from . import ops
STATS["kernel"] += 1 if GATE and (visit.local or GATE_ALL) and visit.gated is None and _gate_ok(visit, call): gate, sinks = visit.gate, visit.sinks y = torch.empty(tuple(gate.shape), dtype=torch.bfloat16, device=gate.device) _, lse = ops.prefill_attention(**call, gate=gate, sinks=sinks, y=y) visit.gated = (call["out"], y) STATS["gated"] += 1 kind = "SWA" if visit.local else "global" _log_once(f"gated_first_{kind}", f"first gated {kind} prefill launch ({call['q'].shape[0]} rows)") return call["out"], lse # out stays unwritten: only gate_sink consumes it, and returns y return ops.prefill_attention(**call) STATS["fallback"] += 1 _log_once("fallback", "a marked call is outside the kernel's coverage; running stock FA4 for it") kwargs["rel_bias"] = torch.einsum("thd,de->the", bias, visit.proj) kwargs.pop("rel_bias_presheared", None) return stock(**kwargs) if bias is not None and bias.dim() == 3 and bias.shape[-1] == D_REL and _is_produced(bias): raise RuntimeError( "inkling_attn: an r-shaped rel_bias (width 16) reached FA4 outside the layer visit that made it" ) return stock(*args, **kwargs)
_flash_attn_varlen_func.__wrapped__ = stock setattr(_flash_attn_varlen_func, MARK, True) return _flash_attn_varlen_func
def _gate_ok(visit, call): """The gated launch is taken only for a whole-visit call (the q rows _project_sources returned, so no real-rows narrowing between the visit and the backend) with gate / sinks in the layouts the kernel reads.""" import torch
gate, sinks, q, out = visit.gate, visit.sinks, call["q"], call["out"] if gate is None or sinks is None or visit.tokens != q.shape[0]: return False t, heads = q.shape[0], q.shape[1] ok = ( gate.dtype == sinks.dtype == torch.bfloat16 and gate.dim() == 2 and tuple(gate.shape) == (t, heads * HEAD_DIM) and gate.stride(1) == 1 and gate.stride(0) % 8 == 0 and gate.data_ptr() % 16 == 0 and sinks.dim() == 2 and tuple(sinks.shape) == (t, heads) and sinks.stride(1) == 1 and gate.device == sinks.device == q.device and tuple(out.shape[:2]) == (t, heads) ) if not ok: STATS["gate_fallback"] += 1 _log_once("gate_fallback", "gated epilogue: unexpected gate / sinks layout; stock gate_sink used") return ok
def gate_begin(q, out): """For a packed (KV12S) global prefill reader: the gate / sinks / y kwargs of a gated launch when this visit's gate_sink can take the kernel's y (INKLING_ATTN_GATE=all, whole-visit rows, kernel layouts), else None. The caller launches with them and then calls gate_commit(g, out).""" import torch
if not GATE_ALL: return None visit = _CTX.get() if visit is None or visit.local or visit.gated is not None or out is None: return None if not _gate_ok(visit, {"q": q, "out": out}): return None y = torch.empty(tuple(visit.gate.shape), dtype=torch.bfloat16, device=visit.gate.device) return {"gate": visit.gate, "sinks": visit.sinks, "y": y, "_visit": visit}
def gate_commit(g, out): """After the gated launch(es) of gate_begin's kwargs: the visit's gate_sink returns y (out stays unwritten).""" visit = g["_visit"] visit.gated = (out, g["y"]) STATS["gated"] += 1 _log_once("gated_first_global", f"first gated global prefill launch ({visit.tokens} rows, packed reader)")
def make_gate_sink(stock): """inkling2_attn's gate_sink: after a gated launch in this visit, return its BF16 y (the FP32 out it was handed was never written, so anything else is an error); every other call is the stock function."""
def gate_sink(output, gate, lse, sinks, *, output_dtype, head_groups=None): visit = _CTX.get() done = visit.gated if visit is not None else None if done is None: return stock(output, gate, lse, sinks, output_dtype=output_dtype, head_groups=head_groups) out, y = done visit.gated = None if (output.data_ptr() != out.data_ptr() or output.numel() != out.numel() or head_groups is not None or gate is not visit.gate or sinks is not visit.sinks or tuple(y.shape) != tuple(gate.shape)): raise RuntimeError("inkling_attn: gate_sink did not receive the gated visit's attention output") import torch
if output_dtype != torch.bfloat16: raise RuntimeError("inkling_attn: gated epilogue writes BF16, gate_sink asked for another dtype") return y
gate_sink.__wrapped__ = stock setattr(gate_sink, MARK, True) return gate_sink
def patch_sm120(module): stock = getattr(module, "_flash_attn_varlen_func", None) if stock is None: raise RuntimeError(f"inkling_attn: {SM120_MODULE}._flash_attn_varlen_func is missing") if getattr(stock, MARK, False): return False module._flash_attn_varlen_func = make_varlen(stock) return True
def patch_common_attn(module): import inspect
cls = getattr(module, "RelLogitsProj", None) fwd = getattr(cls, "forward", None) if cls is not None else None if fwd is None: raise RuntimeError(f"inkling_attn: {COMMON_ATTN_MODULE}.RelLogitsProj.forward is missing") params = list(inspect.signature(inspect.unwrap(fwd)).parameters) if params[:3] != ["self", "r_out", "log_scaling_tau"]: raise RuntimeError(f"inkling_attn: RelLogitsProj.forward signature changed: {params}") prev = cls.__call__ if getattr(prev, MARK, False): return False cls.__call__ = make_rel_call(prev) return True
def patch_attn(module, kinds): import importlib
cls = getattr(module, "Inkling2Attention", None) prev = getattr(cls, "_forward", None) if cls is not None else None get_attn_backend = getattr(module, "get_attn_backend", None) get_model = getattr(module, "get_model", None) if prev is None or get_attn_backend is None or get_model is None: raise RuntimeError( f"inkling_attn: {ATTN_MODULE}.Inkling2Attention._forward, get_attn_backend or get_model is missing" ) if getattr(prev, MARK, False): return False in_breakable = getattr(importlib.import_module(BREAKABLE_MODULE), "is_in_breakable_cuda_graph", None) if in_breakable is None: raise RuntimeError(f"inkling_attn: {BREAKABLE_MODULE}.is_in_breakable_cuda_graph is missing") cp_active = getattr(importlib.import_module(CP_MODULE), "is_cp_active", None) if cp_active is None: raise RuntimeError(f"inkling_attn: {CP_MODULE}.is_cp_active is missing") cls._forward = make_forward(prev, get_attn_backend, get_model, in_breakable, frozenset(kinds), cp_active) if GATE_OFF_FOR_LOGGING: _log_once("gate_off", "gated epilogue OFF: SGLANG_KERNEL_API_LOGLEVEL is set (it reads the FA4 output buffer)") if GATE: gs = getattr(module, "gate_sink", None) if gs is None: raise RuntimeError(f"inkling_attn: {ATTN_MODULE}.gate_sink is missing (INKLING_ATTN_GATE)") if not getattr(gs, MARK, False): module.gate_sink = make_gate_sink(gs) _log_once("gate", "gated epilogue on: " + ("sliding-window and global" if GATE_ALL else "sliding-window") + " prefill visits run gate_sink inside the attention kernel") return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""CPU tests of inkling_attn's install logic (no torch, no GPU).
python3 -m unittest discover -s inkling_attn/tests (from the overlay directory) INKLING_ATTN_SGLANG_ROOT=/path/to/sglang additionally checks the patch targets of that source tree."""import osimport sysimport tempfileimport unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import inkling_attn # noqa: E402
class ParseLevers(unittest.TestCase): def test_values(self): self.assertEqual(inkling_attn.parse_levers(""), ()) self.assertEqual(inkling_attn.parse_levers("0"), ()) self.assertEqual(inkling_attn.parse_levers("prefill_swa"), ("prefill_swa",)) self.assertEqual(inkling_attn.parse_levers("all"), ("prefill_swa", "prefill_global")) self.assertEqual(inkling_attn.parse_levers(" prefill_global , prefill_swa,prefill_swa"), ("prefill_global", "prefill_swa")) with self.assertRaises(RuntimeError): inkling_attn.parse_levers("prefill_swa,decode")
class SourceChecks(unittest.TestCase): def _tree(self, drop=None): root = tempfile.mkdtemp() for rel, needles in inkling_attn._SOURCE_CHECKS: path = os.path.join(root, rel) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "a", encoding="utf-8") as f: for n in needles: if n != drop: f.write(n + "\n") return root
def test_complete_tree_passes(self): inkling_attn.check_sources(self._tree())
def test_missing_needle_fails(self): needle = inkling_attn._SOURCE_CHECKS[0][1][2] with self.assertRaises(RuntimeError): inkling_attn.check_sources(self._tree(drop=needle))
@unittest.skipUnless(os.environ.get("INKLING_ATTN_SGLANG_ROOT"), "no sglang tree given") def test_real_tree(self): inkling_attn.check_sources(os.environ["INKLING_ATTN_SGLANG_ROOT"])
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""CPU check of the per-request 4/8-warp split (ops.W8_FROM): a mirror of the kernel's work-item loop and selectionblock in csrc/attn_kernel.cuh
if (p.sel_mode != 0) { pre = (long long)seq_k[b] - sq; if ((pre >= sel_keys) != (sel_mode == 2)) return; }
and of the two launches in csrc/inkling_attn_ext.cu (grid8: sel_mode 2, 128-row blocks, ceil(T/128) + n_req tiles;grid: sel_mode 1, 64-row blocks). T (rows of q) is independent of cu_seqlens_q. Checks, per head: - the union of the two launches writes exactly the physical rows the single 4-warp launch writes, each once; - every request goes entirely to the launch its unclamped prefix (seqused_k - its rows) selects.
Run: python3 overlay/inkling_attn/tests/test_w8split_cpu.py (or pytest)"""import random
def launch_rows(cu_q, seq_k, T, pt_cols, page_size, bm, sel_mode, sel_keys): """[(physical row, request)] written by one launch (one head).""" n_req = len(cu_q) - 1 tiles = (T + bm - 1) // bm + n_req rows = [] for lin in range(tiles): tile = lin b, start, sq, prev_end = -1, 0, 0, 0 for i in range(n_req): s = max(cu_q[i], prev_end) e = min(cu_q[i + 1], T) ln = e - s if e > s else 0 prev_end = max(prev_end, e) nb = (ln + bm - 1) // bm if tile < nb: b, start, sq = i, s, ln break tile -= nb if b < 0: continue sk = min(max(seq_k[b], 0), pt_cols * page_size) # used by the attention itself, not by the selection del sk if sel_mode != 0: pre = seq_k[b] - sq if (pre >= sel_keys) != (sel_mode == 2): continue m0 = tile * bm rows += [(start + r, b) for r in range(m0, min(m0 + bm, sq))] return rows
def request_rows(cu_q, T): """rows each request owns under the kernel's guards: [max(cu[i], prev_end), min(cu[i+1], T)).""" out, prev_end = [], 0 for i in range(len(cu_q) - 1): s, e = max(cu_q[i], prev_end), min(cu_q[i + 1], T) prev_end = max(prev_end, e) out.append(max(0, e - s)) return out
def check(cu_q, seq_k, T, pt_cols, page_size, w8_from): single = launch_rows(cu_q, seq_k, T, pt_cols, page_size, 64, 0, 0) r8 = launch_rows(cu_q, seq_k, T, pt_cols, page_size, 128, 2, w8_from) r4 = launch_rows(cu_q, seq_k, T, pt_cols, page_size, 64, 1, w8_from) phys = [r for r, _ in r8 + r4] assert len(phys) == len(set(phys)), "a physical row is written twice" assert sorted(r8 + r4) == sorted(single), "the split writes other rows than the single launch" lens = request_rows(cu_q, T) for b, sq in enumerate(lens): if sq == 0: continue want8 = seq_k[b] - sq >= w8_from owners = {"8" for _, rb in r8 if rb == b} | {"4" for _, rb in r4 if rb == b} assert owners == ({"8"} if want8 else {"4"}), (b, owners, want8)
def test_random(): rng = random.Random(0) for _ in range(4000): page_size = rng.choice([64, 128]) n_req = rng.randint(1, 6) sqs = [rng.choice([0, 1, 7, 63, 64, 65, 127, 128, 129, 300, 2048]) for _ in range(n_req)] w8_from = rng.choice([1, 64, 128, 1000, 131072]) pre = [rng.choice([0, 5, w8_from - 1, w8_from, w8_from + 1, 2 * w8_from, 300000]) for _ in range(n_req)] seq_k = [s + max(p, 0) for s, p in zip(sqs, pre)] if rng.random() < 0.15: seq_k[rng.randrange(n_req)] = rng.choice([0, 3]) # inconsistent metadata (sk < sq) cu = [0] for s in sqs: cu.append(cu[-1] + s) if rng.random() < 0.1 and cu[-1] > 0: cu[rng.randrange(1, len(cu))] -= rng.randint(1, 70) # non-monotone cu_seqlens: the kernel's guards apply cu = [max(0, c) for c in cu] T = max(cu) + rng.choice([0, 0, 1, 63, 200]) # q rows independent of cu_seqlens_q (padded buckets) if rng.random() < 0.1: T = max(0, max(cu) - rng.randint(1, 100)) # cu_seqlens_q beyond q: guarded by total_q pt_cols = (max(max(seq_k), 1) + page_size - 1) // page_size if rng.random() < 0.15: pt_cols = max(1, pt_cols // 4) # page table narrower than seq_k: attention clamps, selection does not check(cu, seq_k, T, pt_cols, page_size, w8_from)
def test_threshold_direction(): # one request exactly at / one below the threshold: owners must be 8 / 4 warps r8 = launch_rows([0, 100, 200], [100 + 1000, 100 + 999], 256, 64, 128, 128, 2, 1000) r4 = launch_rows([0, 100, 200], [100 + 1000, 100 + 999], 256, 64, 128, 64, 1, 1000) assert {b for _, b in r8} == {0} and {b for _, b in r4} == {1} # clamped page table: sq 16, seqused_k 256, capacity 128 keys, W8_FROM 128 -> 8 warps assert {b for _, b in launch_rows([0, 16], [256], 16, 1, 128, 128, 2, 128)} == {0}
def test_serving_shapes(): for pfx in (0, 131071, 131072, 262144, 1048576 - 8192): check([0, 8192], [8192 + pfx], 8192, 8192, 128, 131072) check([0, 100, 4196, 8192], [100 + 300000, 4096 + 7, 3996 + 131072], 8192, 8192, 128, 131072)
if __name__ == "__main__": test_random() test_threshold_direction() test_serving_shapes() print("ok")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197# inkling_cert: certified greedy argmax of the target LM head
On greedy verify steps only the argmax of each row's 201,024 logits matters. This package reads a 6-bit copy ofthe head (358 MB) instead of pico's coded head (715 MB), bounds every logit rigorously, and runs pico's exact headGEMV only on the 16-row tiles that can hold the argmax. Every other logit is written as -inf. The stock softcap,padding mask and argmax then run unchanged and return the same token as the full head, bit for bit.
Status (2026-11-21): written, CPU-tested (21 tests), and GPU-checked on GB10 with real weights:`tools/gpu_check_cert.py` PASS, `tools/smoke_hooks.py` PASS (all hooks land on the image's sglang, cert outsidepico). Not yet run in a serving boot: the next step is `INKLING_CERT_HEAD=check` for a few thousand steps, then anA/B against `=0`.
## GPU check (2026-11-21, GB10, real head, 5,983 real LM-head rows from the CPU oracle)
| gate | result ||---|---|| 6-bit copy decodes to the quantised head (by the kernel's rule); tables finite | ok || screen accumulation error / model (C_ACC ||D|| ||x||), 512 rows x 201,024 ids | max 0.0002 || pico accumulation error / model (C_ACC ||W|| ||x||) | max 0.0004 || s - B <= pico <= s + B for every logit | 0 outside; max abs(pico - s) / B = 0.13 || certified token == full-head token (stock softcap, mask, argmax), M = 8 | 5,976 rows, 0 mismatches, 747/747 steps certified || same, M = 16 | 5,968 rows, 0 mismatches, 373/373 certified || computed tiles bit-identical to pico's full head, others -inf | 0 bad steps || `on` = 0 equals pico's full head bit for bit | ok || near-tie rows (x along W_a + W_b, norms 150-800) | 2,048 rows, 0 mismatches || duplicate head rows (1 pair in the vocab): exact tie resolves to the lower id | ok || CUDA graph replay == eager, 40 steps with `on` toggled | ok |
Candidate tiles per step: M = 8 mean 57.6, p50 29, p90 96, p99 238, max 9,639 (one flat row; still exact, justslower). M = 16: mean 105, p50 52, p99 433.
Microbench (L2 flushed with a 256 MiB read before each rep, CUDA events, median of 30):
| | M = 8 | M = 16 ||---|---:|---:|| pico full head (current `lmhead`) | 2.898 ms (247 GB/s) | 3.036 ms (236 GB/s) || certified path, median-candidate batch (18 / 30 tiles) | **1.671 ms** | **1.730 ms** || certified path, p90 batch (40 / 61 tiles) | 1.680 ms | 1.730 ms || screen alone (screen + rowmax + select) | 1.569 ms = 228 GB/s of 358 MB | 1.618 ms = 221 GB/s || `on` = 0 step (full head through the masked kernel) | 2.971 ms | 3.027 ms |
Final kernel (`gpu4.log`). Saving per certified step: -1.23 ms at c1 and -1.31 ms at c2. A persistent grid-stride screen (96-384 CTAs, xloaded once per CTA) was tried and rejected: 140 GB/s at M = 8 and 202 at M = 16, because the x loads then goahead of the weight stream. A step that is not eligible pays about +90 us overpico.
## Switch
| env | default | meaning ||---|---|---|| `INKLING_CERT_HEAD` | unset (off) | `1`: certified head on eligible steps; `check`: serve pico's full head, build the certified result beside it and count token mismatches (must stay 0); `0`: off || `INKLING_CERT_HEAD_LOG_EVERY` | 2000 | counter line every N verify steps (0 = never) || `INKLING_CERT_HEAD_CACHE` | `~/.cache/inkling-cert` | extension build cache |
The package needs `INKLING_PICO12` with `lmhead`, installed first. pico's GEMV is both the exact pass and thefallback, and the certified token must equal pico's.
Arming in `sitecustomize.py`, after the `INKLING_PICO12` block:
```python if _on("INKLING_CERT_HEAD"): # after inkling_pico12: wraps its lm-head function and reads its coded head import inkling_cert inkling_cert.install()```
`_on()` already treats `check` as on, and `install()` reads the mode itself. `scripts/launch.sh` passes thevariable through `SGLANG_ENV` (`-e INKLING_CERT_HEAD=1`); `scripts/launch.sh` sets it from `CERT_HEAD`.
## Measured before building (kill-check)
Real LM-head inputs: 5,983 rows from the CPU oracle (`engine/ref/inkling2_ref.py`, FP32). They come fromteacher-forcing the 16 speedbench greedy transcripts, rounded to BF16. The real unembedding was used. Script:`results/kbench/round2/cert/cand_count.py`. The head rows have norm 1.00 and ||x|| is about 223. The top logit has a median of50.7, and the gap to the second logit has a median of 13.6.
| screen | MB read | bound B (median) | candidate tiles / step c1 (mean, p99, max) | c2 (mean, p99) | est. ms ||---|---:|---:|---|---|---:|| INT8 per row | 471 | 2.0 | 13, 25, 26 | | 2.06 || **INT6, FP16 scale per 192** | **358** | **6.2** | **43, 236, 606** | **78, 328** | **1.59** || INT6, FP16 scale per 32 | 382 | 5.0 | 23, 92, 213 | 43, 138 | 1.68 || INT7, scale per 192 | 416 | 3.1 | 14, 37, 52 | 26, 57 | 1.82 || INT5, scale per 32 | 324 | 10.4 | 305, 1638, 2279 | | 1.52 (heavy tail) || INT4, scale per 32 | 290 | 21 | ~10k (everything) | | dead |
The estimate charges screen bytes at 235 GB/s, candidate tiles at 57 KB each at 200 GB/s, plus 50 us of smallkernels. pico's full head is 2.90 ms at 8 rows. The measured screen error is about 1.4 % of the bound, because theCauchy-Schwarz bound is far from tight. Only the very peaked logits make it work.
## Per step (M <= 16 verify rows, all in the verify CUDA graph)
| kernel | what ||---|---|| `k_screen` (12564 CTAs x 12 warps) | Computes s = x . D^T from the 6-bit copy with BF16 MMAs. Each warp covers one 192-value group and scales its partial by the group's FP16 scale. ||x_g|| is computed from the same registers. Epilogue: B, then lo/hi, then the max of lo and of hi per (row, 16-row tile) over the real vocab. A non-finite value sets a flag. || `k_rowmax` | T[m] = max lo, H[m] = max hi || `k_select` | Per tile: a mask byte, set when some row has hi >= T - delta in that tile. All tiles are set when the step is not eligible (`on` = 0), a value was non-finite, or a row fails the softcap range test. Also updates the counters. || `k_exact` | pico's `gemv16_body<kBF16X, mt 2>` on the masked CTAs. This is the code of pico's coded-head GEMV (the same file, compiled into this extension) and gives its bits. Every other CTA writes -inf. |
Then the stock code continues: `fused_softcap` in place, ids >= `vocab_size` set to -inf, and the folded greedyaccept's argmax.
## Why the token is the same (cert_math.py has the full statement)
1. **Bound.** |pico - <W_v, x>| <= C_ACC ||W_v|| ||x|| and |s - <D_v, x>| <= C_ACC ||D_v|| ||x||, where C_ACC = (K/16 * 17 + 32) 2^-23 is the tensor-core accumulation model (an assumption, measured by the GPU check; pico12's own check already gates pico at (K/16 + 32) 2^-23). Also |<W_v - D_v, x>| <= sum_g ||R_vg|| ||x_g|| (Cauchy-Schwarz per group). Every table is rounded up, and every FP32 step is inflated, so lo <= l <= hi.2. **The winner is computed.** Let w be the stock token and u the id with lo_u = T. If l_w >= l_u, then hi_w >= T. Otherwise f(l_w) >= f(l_u) with l_w < l_u, where f is the stock FP32 softcap, which is monotone only up to E = 2^-14. Then l_u - l_w <= delta = 2 * 2E / exp(-2L/30) on the range L checked on the device, so hi_w >= T - delta.3. **No -inf beats it.** f(-inf) = -30, and f(l_w) >= 30 tanh(T/30) - E > -30 under the range test (|T|, |H| up to about 160; real logits are 50-70).4. **Ties.** Computed ids hold the stock values. The set of maximisers among them therefore contains w, the lowest stock maximiser, and nothing below it. The stock argmax (lowest index) returns w.
x is finite, so every logit is finite and no NaN reaches the argmax. A non-finite screen value forces the fullhead anyway.
## When the certified path runs (`on` = 1)
The device flag is written before each verify replay by the `TargetVerifyExecutor.run_non_compact` wrapper. It is1 only when all of these hold:- `begin_static_step(bs, armed)` was called with `armed = fold_eligible`. That means a static-mode step whose in-graph folded greedy accept is used: all requests greedy, `verify_logits_adjustments_are_noop` (no penalties, logit bias, grammar mask or custom processor), and no grammar.- The batch has no `return_logprob`, no watermark candidates and no sampling-mask capture.- None of the DSpark debug observers that read the verify logits is set (checked at load; the package disables itself if one is).
`begin_step` (compact mode, idle participation) sets it to 0. Eager forwards (no graph) always compute the fullhead. The first eager call per row bucket goes through these kernels in full-fallback mode, and later eager callsgo straight to pico. Rows > 16 (c3 and up) never reach here: pico itself takes only 1-16.
### On the DFLASH worker (`dflash.py`, `SPEC=dflash2`, launch `CERT_DFLASH` / `CERT_WIDE_DFLASH`)
DFLASH has no verify epilogue: its accept runs eagerly after the target-verify graph, as the argmax of the verifylogits on greedy batches. A wrapper of `DFlashWorkerV2.forward_batch_generation` marks the step, and a wrapper of`TpModelWorker.forward_batch_generation` sets `on` right before that step's target verify to`batch_ok(batch)` and `DFlashWorkerV2._can_skip_verify_logits(batch, sampling_info)` (all greedy, no grammar,logprobs, logit adjustments or selector sample), and back to 0 right after it, so no other replay reads a stale 1.- Narrow head (<= 16 rows): it writes pico's exact logits on the candidate tiles and -inf elsewhere, so the stock argmax over the verify logits returns the certified token. Under the verify cap (`inkling_vcap` on DFLASH, `STATE.src_index`), dead rows are given their anchor's hidden row before the screen, selected on the device by `on`, so they add no candidate tiles; live rows keep their own rows and no accept reads a dead row's token.- Wide head (17..`INKLING_CERT_WIDE_MAX_ROWS` rows): the certified IDs, which the wide head returns instead of writing the logits, are looked up after each target-verify replay (`DecodeCudaGraphRunner._process_output_after_replay`, from the replayed graph's own output) and passed to `DFlashWorkerV2._accept_block` as its target prediction. A wide replay whose IDs cannot be identified stops the server; the compact ragged verify layout is refused.- Check mode (`CERT_DFLASH=check`): 34,808 rows, 0 mismatches.
## Patch points
| target | what ||---|---|| `models/inkling2.py: Inkling2LogitsProcessor._get_logits` | marks target-verify calls (`forward_mode.is_target_verify()`) || `models/inkling2.py: Inkling2ForConditionalGeneration.post_load_weights` | after pico coded the head: builds the 6-bit copy and the tables on the GPU (chunked, float64), runs the self-test (full fallback == pico bit for bit, certified argmax == full argmax on random rows at M = 8 and 16; this also loads every kernel before capture), and logs one line || `layers/quantization/unquant.py: sm12x_fp32_lm_head` | wraps pico's wrapper. It takes target-verify calls that pico would take, as long as the processor has softcap 30, no `logit_scale`, no TP gather, and `vocab_size` <= rows. Everything else goes to pico or stock. || `speculative/dspark_components/dspark_verify.py: DsparkVerifyEpilogue.begin_static_step / begin_step, TargetVerifyExecutor.run_non_compact` | the per-step device flag (above) and the periodic counter line |
Source strings are checked at `install()`, and attributes when each module is imported. A mismatch exits with 78.TP > 1 disables the package with a log line.
Coexistence:- `inkling_pico12`: required, and its wrapper sits inside ours.- `inkling_vcap`: under DSpark, independent: dead rows are still verify rows with real hidden states, and their logits are certified like the others. Under DFLASH, see above (dead rows take their anchor's row).- `inkling_draftbytes`: the draft head is not touched.
## Cost and memory
- Extra memory is 358 MB (Q 347.4, scales 4.8, residual norms 4.8, row norms 0.8) plus about 1.7 MB of buffers.- A step that is not eligible (`on` = 0: sampled, logprobs, ...) costs pico's head plus about 20-30 us. The screen and row-max kernels return at once, and the masked kernel runs every tile (pico's full head). An eligible step that fails the range test pays the screen and the full head; this is never seen on real rows.
## Reviews and logs
- GPU logs (GB10): `results/kbench/round2/cert/gpu2.log` (first PASS), `gpu3.log` (persistent variant, rejected), `gpu4.log` (final kernel).
## Files
| path | origin ||---|---|| `csrc/cert_ext.cu`, `*.py`, `tests/`, `tools/` | ours (ported in spirit from our GLM-5.3-Flash `glm_cert_head.py` / `cert_math.py`) || pico's `gemv16.cu`, `common.cuh`, `dsk.h`, `check.h` | not copied: `#include`d from `../inkling_pico12/third_party/pico` (MIT, Copyright (c) 2026 Andy Shu) |
## Checks
- CPU: `python3 -m unittest discover -s inkling_cert/tests -v` from `overlay/` (needs numpy and torch). It covers pack/unpack, the lane/MMA k-mapping of the packed layout, tables (torch vs numpy), bound coverage, adversarial screen errors, exact ties, softcap ties, padded ids, range fallback and the fill.- GPU: `python3 inkling_cert/tools/gpu_check_cert.py --model /model --hidden DIR`, where DIR holds real LM-head input rows as `.npz`. It gates the packing, the accumulation model (screen and pico vs FP64), coverage (lo <= pico <= hi for every logit), and token identity on every real row at M = 8 and 16. It also gates near-tie rows, duplicate head rows, computed tiles bit-identical to pico, `on` = 0 equal to pico, and graph replay equal to eager. It then benches.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Inkling-2-Mini on DGX Spark: certified greedy argmax of the target LM head (exact; see README.md).
INKLING_CERT_HEAD=1 | check | 0 (default: unset -> install() does nothing)
1 greedy target-verify steps (the in-graph folded greedy accept, no logprobs / grammar / penalties / logit bias / watermark / sampling masks) read a 6-bit copy of the head (358 MB) plus pico's exact head GEMV on the candidate tiles instead of pico's whole coded head (715 MB); every other step runs the head unchanged.check serve pico's full head; build the certified result beside it and count token mismatches (must be 0).
INKLING_CERT_WIDE=1 with INKLING_CERT_HEAD=1 also certifies 17–192 rowswhen the packed, unsplit inkling_wide head would serve the same call. INKLING_CERT_WIDE_MAX_ROWS largest verify batch (rows, 17..192) the wide path serves (default WIDE_MAX_ROWS_DEFAULT); larger batches run the head unchanged INKLING_CERT_WIDE_STATS=1 diagnostic: count wide outcomes (certified / unsafe / too many / off) and the candidate-tile union per batch size in the graph, logged with the counters line
Needs INKLING_PICO12 with `lmhead` armed first (pico's GEMV is the exact pass and the fallback). Other settings: INKLING_CERT_HEAD_LOG_EVERY counters line every N verify steps (default 2000, 0 = never) INKLING_CERT_HEAD_CACHE extension build cache (default ~/.cache/inkling-cert)"""
import importlib.utilimport osimport sys
STATE = {"installed": False, "mode": "0", "cfg": None}
_SOURCE_CHECKS = ( ("srt/layers/quantization/unquant.py", ("def sm12x_fp32_lm_head(", "def sm12x_fp32_lm_head_applies(")), ("srt/layers/logits_processor.py", ("sm12x_fp32_lm_head_applies(hidden_states, lm_head.weight, out)", "logits = self._compute_lm_head(")), ("srt/models/inkling2.py", ("class Inkling2LogitsProcessor(", "def _get_logits(", "fused_softcap(logits, self.shard_softcap)", "logits[..., self.config.vocab_size :] = float(\"-inf\")", "def post_load_weights(")), ("srt/speculative/dspark_components/dspark_verify.py", ("class DsparkVerifyEpilogue:", "def begin_static_step(self, bs: int, armed: bool)", "def begin_step(self, verify_lens, armed: bool)", "def run_non_compact(", "target_predict = sampling_argmax(logits).view(-1)")), ("srt/speculative/dspark_components/dspark_worker_v2.py", ("self._verify_epilogue.begin_static_step(bs, fold_eligible)", "and (sampling_info is None or sampling_info.is_all_greedy)", "and verify_logits_adjustments_are_noop(sampling_info)", "compute_spec_logprobs(")),)
_WIDE_SOURCE_CHECKS = ( ("kernels/ops/activation/softcap.py", ("x = x / softcapping_value", "x = libdevice.tanh(x)", "x = x * softcapping_value")), ("kernels/ops/speculative/dspark/dspark_accept.py", ("target_predict: Optional[torch.Tensor] = None", "if target_predict is None:")), ("srt/speculative/dspark_components/dspark_verify.py", ("AcceptGreedy.execute(", "target_logits=logits", "logits=out.next_token_logits")), ("srt/model_executor/runner/decode_cuda_graph_runner.py", ("class DecodeCudaGraphRunner(", "def execute(", "output = self.backend.replay(")),)
UNQUANT = "sglang.srt.layers.quantization.unquant"MODEL = "sglang.srt.models.inkling2"VERIFY = "sglang.srt.speculative.dspark_components.dspark_verify"GRAPH_RUNNER = "sglang.srt.model_executor.runner.decode_cuda_graph_runner"
def _log(msg): sys.stderr.write(f"[inkling_cert pid={os.getpid()}] {msg}\n") sys.stderr.flush()
# Largest verify batch (rows) the wide certified head serves; larger batches run the head unchanged. GB10 sweep# 2026-11-24 (tools/gpu_check_certwide.py, CW_ROWS 64..192, real head, captured rows): at 129-192 rows the screen# runs the 12-row-group kernel at 1 CTA/SM (143 registers) and takes 4.85-5.92 ms, so even a fully certified batch# is 0.09-0.19 ms slower than the dense head at 136/160/176/192 rows (+0.01 at 144); at 128 rows (2 CTAs/SM) the# certified head wins 1.65 ms and loses 2.70 ms on an overflow (break-even at a 38 % fallback rate).WIDE_MAX_ROWS_DEFAULT = 128
def parse_mode(value): v = (value or "").strip().lower() if v in ("", "0", "off", "none", "false", "no"): return "0" if v in ("1", "on", "true", "yes"): return "1" if v == "check": return "check" raise RuntimeError(f"inkling_cert: INKLING_CERT_HEAD={value!r}: 1, check or 0")
def config_from_env(env): raw = env.get("INKLING_CERT_HEAD_LOG_EVERY", "").strip() try: every = int(raw) if raw else 2000 except ValueError as exc: raise RuntimeError(f"inkling_cert: INKLING_CERT_HEAD_LOG_EVERY={raw!r}") from exc cache = env.get("INKLING_CERT_HEAD_CACHE", "").strip() or os.path.join(os.path.expanduser("~"), ".cache", "inkling-cert") wide = parse_mode(env.get("INKLING_CERT_WIDE", "")) if wide == "check": raise RuntimeError("inkling_cert: INKLING_CERT_WIDE accepts 0 or 1") raw = env.get("INKLING_CERT_WIDE_MAX_ROWS", "").strip() try: max_rows = int(raw) if raw else WIDE_MAX_ROWS_DEFAULT except ValueError as exc: raise RuntimeError(f"inkling_cert: INKLING_CERT_WIDE_MAX_ROWS={raw!r}") from exc if not 17 <= max_rows <= 192: raise RuntimeError(f"inkling_cert: INKLING_CERT_WIDE_MAX_ROWS={max_rows} outside 17..192") stats = parse_mode(env.get("INKLING_CERT_WIDE_STATS", "")) if stats == "check": raise RuntimeError("inkling_cert: INKLING_CERT_WIDE_STATS accepts 0 or 1") return {"log_every": max(0, every), "cache_dir": cache, "wide": wide == "1", "wide_max_rows": max_rows, "wide_stats": stats == "1"}
def check_sources(root=None, wide=False): if root is None: spec = importlib.util.find_spec("sglang") if spec is None or not spec.submodule_search_locations: raise RuntimeError("inkling_cert: the sglang package is not importable") root = list(spec.submodule_search_locations)[0] checks = _SOURCE_CHECKS + (_WIDE_SOURCE_CHECKS if wide else ()) for rel, needles in checks: path = os.path.join(root, rel) try: with open(path, encoding="utf-8") as f: text = f.read() except OSError as exc: raise RuntimeError(f"inkling_cert: patch target {path} is missing") from exc missing = [n for n in needles if n not in text] if missing: raise RuntimeError(f"inkling_cert: patch target {path} lacks {missing}")
def _callback(name): def run(module): try: from . import patches
if patches.STATE["cfg"] is None: patches.STATE.update(mode=STATE["mode"], cfg=STATE["cfg"], log=_log) except BaseException as exc: # noqa: BLE001 _log(f"FATAL importing the patches: {exc!r}") os._exit(78) patches._guarded(getattr(patches, name))(module)
run.__name__ = f"inkling_cert.{name}" return run
def install(env=None, sglang_root=None): """Arm INKLING_CERT_HEAD. Idempotent; returns the mode ("0" = nothing armed).""" if STATE["installed"]: return STATE["mode"] env = os.environ if env is None else env mode = parse_mode(env.get("INKLING_CERT_HEAD", "")) STATE["installed"] = True STATE["mode"] = mode if mode == "0": return mode pico = sys.modules.get("inkling_pico12") if pico is None or "lmhead" not in tuple(pico.STATE.get("levers", ())): raise RuntimeError("inkling_cert: INKLING_CERT_HEAD needs inkling_pico12 installed first with `lmhead`") STATE["cfg"] = config_from_env(env) if STATE["cfg"]["wide"]: wide = sys.modules.get("inkling_wide") if mode != "1" or wide is None or "lmhead" not in tuple(wide.STATE.get("levers", ())): raise RuntimeError("inkling_cert: INKLING_CERT_WIDE needs INKLING_CERT_HEAD=1 and INKLING_WIDE with lmhead") check_sources(sglang_root, wide=STATE["cfg"]["wide"]) from . import _hook
for module, cb in ((UNQUANT, "patch_unquant"), (MODEL, "patch_model"), (VERIFY, "patch_verify")): _hook.when_imported(module, _callback(cb)) if STATE["cfg"]["wide"]: _hook.when_imported(GRAPH_RUNNER, _callback("patch_graph_runner")) # DFLASH worker (SPEC=dflash2): per-step arming on greedy verify steps (dflash.py); inert under DSpark _hook.when_imported("sglang.srt.speculative.dflash_worker_v2", _callback("patch_dflash_worker")) _hook.when_imported("sglang.srt.managers.tp_worker", _callback("patch_dflash_tp_worker")) return mode123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Build (or reuse) the inkling_cert CUDA extension with torch.utils.cpp_extension.
The only source is csrc/cert_ext.cu; it #includes pico's gemv16.cu from inkling_pico12's vendored copy(../inkling_pico12/third_party/pico, MIT, Andy Shu), so the exact pass is compiled from the very file the`lmhead` GEMV is built from. Flags are pico's. The build directory is <cache>/<tag>, <tag> a hash of every sourceand header, the flags, torch's and CUDA's versions. <cache> = INKLING_CERT_CACHE (default ~/.cache/inkling-cert).
python3 -m inkling_cert.build # build now (in the container, no GPU needed); prints the path"""
import hashlibimport osimport sysimport time
HERE = os.path.dirname(os.path.abspath(__file__))PICO = os.path.join(os.path.dirname(HERE), "inkling_pico12", "third_party", "pico")SOURCES = (os.path.join(HERE, "csrc", "cert_ext.cu"),)HEADERS = ( os.path.join(HERE, "csrc", "screen6.cuh"), os.path.join(HERE, "csrc", "certwide_screen.cuh"), os.path.join(PICO, "kernels", "gemv16.cu"), os.path.join(PICO, "kernels", "dsk.h"), os.path.join(PICO, "kernels", "common.cuh"), os.path.join(PICO, "common", "check.h"),)NAME = "inkling_cert_ext"_UNDEF = ( "-U__CUDA_NO_HALF_OPERATORS__", "-U__CUDA_NO_HALF_CONVERSIONS__", "-U__CUDA_NO_BFLOAT16_CONVERSIONS__", "-U__CUDA_NO_HALF2_OPERATORS__",)
def default_cache_dir(): return os.path.join(os.path.expanduser("~"), ".cache", "inkling-cert")
def cuda_flags(std="c++20", arch="121a"): return [f"-gencode=arch=compute_{arch},code=sm_{arch}", "-O3", f"-std={std}", "--expt-relaxed-constexpr", "-lineinfo", *_UNDEF]
def build_tag(flags, torch_version, cuda_version): h = hashlib.sha256() for path in SOURCES + HEADERS: with open(path, "rb") as f: h.update(os.path.basename(path).encode() + b"\0" + f.read() + b"\0") h.update("\0".join(flags).encode()) h.update(f"\0{torch_version}\0{cuda_version}".encode()) return h.hexdigest()[:16]
_EXT = NoneINFO = {}
def load(cache_dir=None, std="c++20", arch="121a", verbose=False): global _EXT if _EXT is not None: return _EXT import torch from torch.utils import cpp_extension
missing = [p for p in SOURCES + HEADERS if not os.path.isfile(p)] if missing: raise RuntimeError(f"inkling_cert: sources missing (inkling_pico12 must sit next to inkling_cert): {missing}") flags = cuda_flags(std, arch) tag = build_tag(flags, torch.__version__, torch.version.cuda) build_dir = os.path.join(cache_dir or default_cache_dir(), tag) os.makedirs(build_dir, exist_ok=True) cached = any(f.endswith(".so") and f.startswith(NAME) for f in os.listdir(build_dir)) t0 = time.monotonic() try: ext = cpp_extension.load(name=NAME, sources=list(SOURCES), extra_cuda_cflags=flags, extra_include_paths=[PICO], build_directory=build_dir, verbose=verbose) except Exception as exc: # noqa: BLE001 raise RuntimeError(f"inkling_cert: building the extension in {build_dir} failed: {exc}") from exc for attr in ("screen", "exact", "prepare_certwide", "screen_wide", "screen_wide_info", "debug_select_wide"): if not callable(getattr(ext, attr, None)): raise RuntimeError(f"inkling_cert: extension in {build_dir} lacks {attr}()") INFO.update(build_dir=build_dir, cached=cached, seconds=time.monotonic() - t0, tag=tag) _EXT = ext return ext
def main(argv=None): import argparse
p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) p.add_argument("--cache", default=os.environ.get("INKLING_CERT_CACHE") or default_cache_dir()) p.add_argument("--verbose", action="store_true") a = p.parse_args(argv) load(a.cache, verbose=a.verbose) print(f"inkling_cert extension {'reused' if INFO['cached'] else 'built'} in {INFO['seconds']:.1f} s: " f"{INFO['build_dir']}") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""NumPy model of the certified greedy LM-head argmax (what cert_ext.cu computes), for the CPU tests and as thestatement of the argument. No torch, no sglang.
Stock pipeline (the reference the certificate must reproduce), per verify row m: l = pico's FP32 head GEMV of x_m (inkling_pico12 `lmhead`), f(l) = fl(fl(tanh(fl(l / c))) * c) (stock softcap, c = 30), y_v = f(l_v) for v < v_real and -inf for the padded ids, token = the lowest v with y_v = max y (the stock argmax kernel's tie rule; with finite x every l is finite, so there is no NaN).
Certified pipeline: screen s_v ~ <D_v, x> (6-bit copy), B_v = sum_g Rt[g, v] ||x_g|| + CN Nv[v] ||x||, lo = s - B - slop, hi = s + B + slop; T = max_{v < v_real} lo_v; H = max hi. select tile (16 ids) is computed iff some row has a tile member with hi >= T - delta, where delta (from T, H) makes every pair a < b in [T - DMAX, H] with f(a) >= f(b) satisfy b - a <= delta. Not certifiable (all tiles computed): the step is not eligible, a non-finite value, or the range test fails. exact computed tiles hold pico's l (the same kernel body: the same bits); every other id holds -inf. Then the stock softcap, padding mask and argmax run unchanged.
Why the token is the same. (1) |acc - <W_v, x>| and |s - <D_v, x>| are both <= C_ACC * N_v * ||x|| (accumulationmodel below; flushed subnormal inputs or products add at most K * 2^-126 * (||W_v||_1 + ||x||_1), covered by theabsolute slop while ||x|| <= 2^20, which the screen checks) and |<W_v - D_v, x>| <= sum_g ||R_vg|| ||x_g||(Cauchy-Schwarz per group), so lo_v <= l_v <= hi_v. (2) Let w be the stock token and u the id with lo_u = T, soT <= l_u <= hi_u <= H, and f(l_w) >= f(l_u) with |f - g| <= E, g = c tanh(. / c) increasing. If l_w >= l_u thenhi_w >= l_w >= l_u >= T. Otherwise g(l_u) - g(l_w) <= 2E. Every y in [l_u - DMAX, l_u] has |y| <= L = max(|T| + DMAX,|H|) and g' = sech^2(y / c) >= exp(-2L / c) there; if l_u - l_w > DMAX then g(l_u) - g(l_w) >= DMAX exp(-2L / c)>= delta exp(-2L / c) = 4E > 2E (the device checks delta <= DMAX), a contradiction; so l_u - l_w <= DMAX and then(l_u - l_w) exp(-2L / c) <= 2E, i.e. l_u - l_w <= delta / 2. Either way hi_w >= l_w >= T - delta: w's tile iscomputed. (3) Every other id holds -inf, f(-inf) = -c, and y_w >= f(l_u) >= g(T) - E >= -c + c exp(-2L / c) - E > -c(the device checks c exp(-2L / c) > 8E), so no uncomputed id reaches the maximum. (4) Computed ids hold the stockvalues, so the maximum and the set of ids attaining it among computed ids are the stock ones restricted to computedids, and that set contains w, the lowest stock maximiser. Hence the stock argmax returns w on the certified buffer.E = 2^-14 covers Triton's div.full (<= 2 ulp), libdevice tanhf (<= 2 ulp) and the final multiply for every |l|(about 2.5e-5 at |f| ~ 30; tanhf saturates exactly to +-1 for large |l|).
Accumulation model (an ASSUMPTION about the tensor cores, validated on the GPU): products of BF16 values are exact inFP32, and each chained m16n8k16 MMA step adds at most 17 rounding errors of one FP32 ulp of the running magnitude(Fasi, Higham, Mikaitis, Pranesh 2021); with K / 16 chained steps and the cross-warp FP32 sums this givesC_ACC = (K / 16 * 17 + 32) * 2^-23 per unit of sum |w_k x_k| <= ||w|| ||x||. inkling_pico12's GPU check alreadygates pico's head against FP64 with the tighter (K / 16 + 32) * 2^-23; tools/gpu_check_cert.py measures both thescreen and the exact pass against FP64 and against this bound."""
import math
import numpy as np
K = 2304GROUP = 192NGROUPS = K // GROUPTILE = 16QMAX = 31C_ACC = (K / 16 * 17 + 32) * 2.0 ** -23CN = 2.0 * C_ACC # exact path + screenCAP = 30.0 # final_logit_softcappingE_SOFTCAP = 2.0 ** -14 # |stock f(l) - c tanh(l / c)| (div.full + libdevice tanhf + one multiply: ~2.5e-5)TWO_E = 2.0 * E_SOFTCAPDMAX = 16.0INFL = 1.0 + 2.0 ** -16X_ABS = 2.0 ** -58 # covers squares of tiny activations that underflow in FP32
def f32(a): return np.asarray(a, dtype=np.float32)
def bf16_round(a): u = np.ascontiguousarray(a, dtype=np.float32).view(np.uint32).astype(np.uint64) r = ((u >> 16) & 1) + 0x7FFF return ((u + r) >> 16 << 16).astype(np.uint32).view(np.float32)
def round_up_f16(x): h = np.asarray(x, dtype=np.float64).astype(np.float16) bump = h.astype(np.float64) < x return np.where(bump, np.nextafter(h, np.float16(np.inf)), h).astype(np.float16)
def round_up_f32(x): f = np.asarray(x, dtype=np.float64).astype(np.float32) bump = f.astype(np.float64) < x return np.where(bump, np.nextafter(f, np.float32(np.inf)), f).astype(np.float32)
def quantize(W): """W [V, K] -> (q int8, sc fp16 [V, NGROUPS], D float64).""" V = W.shape[0] w = W.astype(np.float64).reshape(V, NGROUPS, GROUP) amax = np.abs(w).max(-1) sc = round_up_f16(amax / QMAX) s = sc.astype(np.float64) q = np.where(s[..., None] > 0, np.clip(np.rint(w / np.where(s > 0, s, 1)[..., None]), -QMAX, QMAX), 0) return q.reshape(V, K).astype(np.int8), sc, (q * s[..., None]).reshape(V, K)
def tables(W, D): V = W.shape[0] R = (W.astype(np.float64) - D).reshape(V, NGROUPS, GROUP) rt = round_up_f16(np.sqrt((R ** 2).sum(-1)) * (1 + 2.0 ** -40)) nv = round_up_f32(np.maximum(np.linalg.norm(W.astype(np.float64), axis=1), np.linalg.norm(D, axis=1)) * (1 + 2.0 ** -40)) return rt, nv
def screen(x, D, rt, nv, v_real, s_err=None): """-> (lo, hi) float32 [M, V], mirrors the kernel epilogue. s_err: an injected screen error (tests).""" M = x.shape[0] x64 = x.astype(np.float64) s = x64 @ D.T if s_err is not None: s = s + s_err s = f32(s) xg2 = f32((x64.reshape(M, NGROUPS, GROUP) ** 2).sum(-1)) xg2 = f32(np.where(xg2 < 2.0 ** -126, 0.0, xg2)) # worst case: everything below the normal range is lost xg = f32(np.sqrt(xg2) * np.float32(INFL) + np.float32(X_ABS)) xn = f32(np.sqrt(xg2.sum(-1, dtype=np.float32)) * np.float32(INFL) + np.float32(4 * X_ABS)) b = f32(xg.astype(np.float64) @ rt.astype(np.float64).T) b = f32((b * np.float32(INFL) + np.float32(CN) * nv[None, :] * xn[:, None]) * np.float32(INFL)) slop = f32((np.abs(s) + b) * np.float32(2.0 ** -20) + np.float32(1e-30)) lo, hi = f32(s - b - slop), f32(s + b + slop) lo[:, v_real:] = -np.inf hi[:, v_real:] = -np.inf return lo, hi
def select(lo, hi, on=True, bad=False): """-> (tile mask bool [V/16], certified bool). Mirrors k_rowmax + k_select.""" M, V = lo.shape T, H = lo.max(1), hi.max(1) ht = hi.reshape(M, V // TILE, TILE).max(-1) full = (not on) or bad thr = np.empty(M, np.float32) for m in range(M): L = max(abs(float(T[m])) + DMAX, abs(float(H[m]))) ex = math.exp(-2.0 * L / CAP) delta = 2.0 * TWO_E / max(ex, 1e-30) ok = math.isfinite(T[m]) and math.isfinite(H[m]) and L < 1e4 and delta <= DMAX and CAP * ex > 4 * TWO_E full |= not ok thr[m] = T[m] - (delta if ok else 0.0) if full: return np.ones(V // TILE, bool), False return (ht >= thr[:, None]).any(0), True
def softcap(l): """The stock softcap in FP32 (division, tanh, multiply each rounded once).""" l = f32(l) with np.errstate(invalid="ignore", over="ignore"): return f32(f32(np.tanh(f32(l / np.float32(CAP)))) * np.float32(CAP))
def stock_token(l, v_real, f=softcap): y = f(l) y[..., v_real:] = -np.inf return y.argmax(-1) # numpy argmax: first maximum = lowest id (no NaN here)
def certified_buffer(l, mask): buf = np.full_like(l, -np.inf, dtype=np.float32) cols = np.repeat(mask, TILE) buf[:, cols] = l[:, cols] return buf
def certified_token(l, mask, v_real, f=softcap): return stock_token(certified_buffer(l, mask), v_real, f)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Certified packed head for 17–192 activation rows. The public result is token IDs."""
import threading
import torch
from . import cert_math, quant
MIN_ROWS = 17MAX_ROWS = 192MAX_TILES = 2048PARTS = 16# Give each path 2 * C_ACC to cover the compounded rounding model.CN = 4 * cert_math.C_ACCMAX_WEIGHT_NORM = 2.0**28ABS_SLOP = 2.0**-78
CERTIFIED, UNSAFE, TOO_MANY, OFF, INVALID = range(5)
def weight_radius(tables): """Upper bound on ||W-D|| + CN * max(||W||, ||D||), one FP32 value per vocab ID.""" nv = tables["nv"] if not bool((nv <= MAX_WEIGHT_NORM).all()): raise ValueError("inkling_certwide: weight norms outside the supported range") r = tables["rt"].double().square().sum(0).sqrt() + CN * nv.double() return quant.round_up_f32(r * (1.0 + 2.0**-40)).contiguous()
class CertWide: """Caller-owned fallback logit buffer. Launches and scratch are fixed under graph capture.
All serving replays and gate writes use one host thread and CUDA stream. Standalone callers must maintain the same ordering through reduction. """
def __init__(self, screen_ext, wide_ext, entry, tables, capacity=MAX_TILES): from . import certwide_reduce
self.screen_ext, self.wide_ext, self.entry = screen_ext, wide_ext, entry self.reduce = certwide_reduce.reduce self.q, self.sc = tables["q"], tables["sc"] self.radius = weight_radius(tables) self.V = entry.n if entry.k != cert_math.K or self.V <= 0 or self.V % cert_math.TILE: raise ValueError("inkling_certwide: invalid packed head geometry") self._replay_owner = None self._owner_lock = threading.Lock() self.ntiles = self.V // cert_math.TILE self.capacity = min(int(capacity), self.ntiles) if self.capacity < 1: raise ValueError("inkling_certwide: tile capacity must be positive") device = self.q.device self.lower = torch.empty((MAX_ROWS, self.ntiles), dtype=torch.float32, device=device) self.upper = torch.empty_like(self.lower) self.norms = torch.empty(MAX_ROWS, dtype=torch.float32, device=device) self.threshold = torch.empty_like(self.norms) self.state = torch.empty(2, dtype=torch.int32, device=device) self.tiles = torch.empty(self.capacity, dtype=torch.int32, device=device) self.groups = torch.empty_like(self.tiles) self.sparse = torch.empty((MAX_ROWS, self.capacity * cert_math.TILE), dtype=torch.float32, device=device) self.partial = torch.empty((MAX_ROWS, PARTS), dtype=torch.int64, device=device) self.empty = torch.empty(0, dtype=torch.float32, device=device) self.stats = None # optional [MAX_ROWS + 1, 5 outcomes, UNION_BUCKETS] int64 (enable_stats) self.counting = True # False while the startup / reload self-tests run screen_ext.prepare_certwide(device.index) wide_ext.prepare_certwide(device.index)
def require_replay_stream(self): stream = torch.cuda.current_stream(self.q.device) owner = (threading.current_thread(), stream) with self._owner_lock: if self._replay_owner is None: self._replay_owner = owner elif self._replay_owner != owner: raise RuntimeError("inkling_certwide: verify gate and replay must use the owning thread and CUDA stream")
def screen(self, x, on, v_real, debug=None, *, three_stages=False): s, lo, hi = (self.empty,) * 3 if debug is None else debug self.screen_ext.screen_wide( x, self.q, self.sc, self.radius, self.V, v_real, self.norms, self.lower, self.upper, self.threshold, on, self.state, self.tiles, self.groups, s, lo, hi, cert_math.CAP, cert_math.TWO_E, cert_math.DMAX, three_stages, )
def exact(self, x, fallback, v_real, settings): self.wide_ext.certwide_exact( x, self.entry.buf, fallback, self.sparse[:x.shape[0]], self.state, self.tiles, self.groups, self.entry.n, v_real, settings.mt, settings.mg, settings.pfd, )
def run(self, x, fallback, on, v_real, settings, *, debug=None, capped=None, three_stages=False): """Return [M] int64 IDs. On fallback only, also write capped, masked logits.""" m = x.shape[0] if capped is not None and (capped.shape != self.sparse.shape or capped.device != self.sparse.device or capped.dtype != self.sparse.dtype or not capped.is_contiguous()): raise ValueError("inkling_certwide: invalid capped debug buffer") ids = torch.empty(m, dtype=torch.int64, device=x.device) self.screen(x, on, v_real, debug, three_stages=three_stages) self.exact(x, fallback, v_real, settings) self.reduce(fallback, self.sparse, self.state, self.tiles, self.groups, self.partial, ids, v_real, cert_math.CAP, capped) if self.stats is not None and self.counting: self._count(m) return ids
UNION_STEP = 256 # tiles per union bucket UNION_BUCKETS = 17 # the last one holds unions >= 16 * UNION_STEP (> the 2048-tile capacity)
def enable_stats(self): """Diagnostic counters, written inside the graph after each run (three small launches, no sync).""" device = self.state.device self.stats = torch.zeros((MAX_ROWS + 1, 5, self.UNION_BUCKETS), dtype=torch.int64, device=device) self._one = torch.ones(1, dtype=torch.int64, device=device)
def _count(self, m): reason = self.state[0:1].clamp(0, 4).long() # CERTIFIED, UNSAFE, TOO_MANY, OFF, INVALID bucket = torch.div(self.state[1:2], self.UNION_STEP, rounding_mode="floor").clamp_(0, self.UNION_BUCKETS - 1) self.stats[m].view(-1).index_add_(0, reason * self.UNION_BUCKETS + bucket.long(), self._one)
def describe_stats(self, host): names = ("cert", "unsafe", "too_many", "off", "invalid") parts = [] for m in range(host.shape[0]): per = host[m] if int(per.sum()) == 0: continue counts = " ".join(f"{names[r]}={int(per[r].sum())}" for r in range(5) if int(per[r].sum())) union = ",".join(f"{b * self.UNION_STEP}+:{int(per[:3, b].sum())}" for b in range(self.UNION_BUCKETS) if int(per[:3, b].sum())) parts.append(f"M={m}: {counts} (union tiles {union})") return "; ".join(parts) if parts else "none"
def refresh(self, entry, tables): # The graph captures the table and packed-buffer addresses. if (entry.n != self.V or entry.k != self.entry.k or self.entry.buf.data_ptr() != entry.buf.data_ptr()): raise ValueError("inkling_certwide: reload changed a graph buffer address") self.radius.copy_(weight_radius(tables)) self.entry = entry1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""CPU model of the wide certificate's intervals and candidate selection."""
import numpy as np
from . import cert_math as cmfrom .certwide import ABS_SLOP, CN, MAX_WEIGHT_NORM
def weight_radius(rt, nv): """rt is [vocab, 12] and already rounded up, as is nv [vocab].""" if not np.all(nv <= MAX_WEIGHT_NORM): raise ValueError("weight norms outside the supported range") radius = np.sqrt(np.square(rt.astype(np.float64)).sum(-1)) + CN * nv.astype(np.float64) return cm.round_up_f32(radius * (1 + 2.0**-40))
def activation_norm(x): x64 = x.astype(np.float64) norm = np.linalg.norm(x64, axis=-1).astype(np.float32) return norm * np.float32(cm.INFL) + np.float32(4 * cm.X_ABS)
def intervals(screen, norm, radius): """Reference intervals for FP32 screen logits. Absolute slop covers FTZ.""" b = cm.round_up_f32(norm.astype(np.float64)[:, None] * radius.astype(np.float64)[None, :]) s = screen.astype(np.float32, copy=False) e = (np.abs(s) + b) * np.float32(2.0**-20) + np.float32(ABS_SLOP) return s - b - e, s + b + e
def derivative_lower(L): """CPU model of the device's downward-rounded repeated squaring.""" z = np.nextafter(2 * L.astype(np.float64) / cm.CAP, np.inf) base = np.nextafter(1 - np.minimum(z, 32) * 2.0**-20, -np.inf) for _ in range(20): base = np.nextafter(base * base, -np.inf) return np.where(z <= 32, -cm.round_up_f32(-base), np.float32(0))
def thresholds(T, H): """Return an inclusive cutoff and a safe flag per row.""" with np.errstate(invalid="ignore", divide="ignore", under="ignore", over="ignore"): L = np.maximum(cm.round_up_f32(np.abs(T.astype(np.float64)) + cm.DMAX), np.abs(H)) slope = derivative_lower(L) delta = cm.round_up_f32(2.0 * cm.TWO_E / slope.astype(np.float64)) rounded_down = -cm.round_up_f32(delta.astype(np.float64) - T.astype(np.float64)) ok = np.isfinite(T) & np.isfinite(H) & (delta <= cm.DMAX) return rounded_down, ok
def select(lo, hi, v_real, capacity, norm, on=True): """Return (row mask, union mask, wide activation-group mask, sparse route).""" m, v = lo.shape ht = hi.copy() ht[:, v_real:] = -np.inf ht = ht.reshape(m, v // cm.TILE, cm.TILE).max(-1) thr, ok = thresholds(lo[:, :v_real].max(-1), ht.max(-1)) rows = (ht >= thr[:, None]) & (np.arange(v // cm.TILE) * cm.TILE < v_real) union = rows.any(0) groups = np.zeros(v // cm.TILE, np.uint16) for start in range(0, m, 16): groups |= rows[start:start + 16].any(0).astype(np.uint16) << (start // 16) count = int(union.sum()) sparse = on and np.all(ok & (norm <= 2.0**20)) and 0 < count <= capacity and count < len(union) return rows, union, groups, bool(sparse)
def compact_token(logits, v_real, groups, f=cm.softcap): """Model the CUDA reduction, including its lowest-ID rule and NaN handling.""" m, _ = logits.shape tile = np.arange(v_real) // cm.TILE live = (groups[tile][None, :] & (1 << (np.arange(m) // 16))[:, None]) != 0 capped = f(logits[:, :v_real]) return np.where(live & ~np.isnan(capped), capped, -np.inf).argmax(-1)recipe/stack/cands/n292-v2-v297-pk3c/recipe/serve/sl.jsonAdded
recipe/stack/cands/n343a-s2-verify-scodes/CREDITS.mdAdded+94
recipe/stack/cands/n343a-s2-verify-scodes/LICENSEAdded+21
recipe/stack/cands/n343a-s2-verify-scodes/NOTICEAdded+54
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/README.mdAdded+85
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/__init__.pyAdded+288
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/_hook.pyAdded+78
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_args.hAdded+35
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_binding.cuAdded+58
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_group_gemm.cuhAdded+247
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_128_128.cuAdded+4
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_32_128.cuAdded+4
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_32_256.cuAdded+4
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_64_128.cuAdded+4
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_inst_64_256.cuAdded+4
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/csrc/scodes_sm120_mma_array.hppAdded+1333
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/encode.pyAdded+123
recipe/stack/cands/n343a-s2-verify-scodes/overlay/inkling_scodes/kernel.pyAdded+99
recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n320s/__init__.pyAdded+66
recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n329/__init__.pyAdded+58
recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n329/n329_rows.pyAdded+31
recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n329/n329_rows_ctl.pyAdded+31
recipe/stack/cands/n361-s3b-p/overlay_n320/inkling_n351/__init__.pyAdded+68
recipe/stack/cands/n361-s3b-p/overlay_n320/n351_quant.cuhAdded+175
recipe/stack/cands/n361-s3b-p/overlay_n320/sitecustomize.pyAdded+107
recipe/stack/cands/n361-s3b-p/recipe/CREDITS.mdAdded+94
recipe/stack/cands/n361-s3b-p/recipe/LICENSEAdded+21
recipe/stack/cands/n361-s3b-p/recipe/NOTICEAdded+54
recipe/stack/cands/n361-s3b-p/recipe/draft-mix/LICENSEAdded+202
recipe/stack/cands/n361-s3b-p/recipe/draft-mix/NOTICEAdded+46
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/CREDITS.knapcio-v2.9.3.mdAdded+94
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/LICENSE.knapcio-v2.9.3Added+21
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/NOTICE.knapcio-v2.9.3Added+54
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/README.mdAdded+164
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/__init__.pyAdded+170
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/_hook.pyAdded+83
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/build.pyAdded+102
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/csrc/attn_kernel.cuhAdded+555
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/csrc/inkling_attn_ext.cuAdded+326
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/ops.pyAdded+76
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/patch.pyAdded+562
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/tests/test_install.pyAdded+54
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_attn/tests/test_w8split_cpu.pyAdded+118
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/README.mdAdded+197
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/__init__.pyAdded+172
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/_hook.pyAdded+78
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/build.pyAdded+102
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/cert_math.pyAdded+163
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/certwide.pyAdded+140
recipe/stack/cands/n361-s3b-p/recipe/overlay/inkling_cert/certwide_math.pyAdded+74