sync 4385228f788d
Browse filesFiles changed (19)
- README.md+61-26
- build/webgpu/bench.json+1174
- build/webgpu/gemm-subgroup-matrix.wgsl.jinjaAdded+287
- build/webgpu/manifest.json
- build/webgpu/matmul-native16-splitk-reduce.wgsl.jinjaAdded+52
- build/webgpu/matmul-nbits-gemv-clusters.wgsl.jinjaAdded+114
- build/webgpu/matmul-nbits-gemv-q4.wgsl.jinja+24-24
- build/webgpu/matmul-nbits-q4-dp4a-prefill.wgsl.jinja+13-1
- build/webgpu/matmul-nbits-q4-native16-packed.wgsl.jinjaAdded+282
- build/webgpu/matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja+105-48
- build/webgpu/matmul-nbits-q4-prefill-tiled.wgsl.jinja+7-5
- build/webgpu/matmul-nbits-q4-range-guarded.wgsl.jinjaAdded+488
- build/webgpu/matmul-nbits-q4-sgmat.wgsl.jinja+129-27
- build/webgpu/matmul-nbits-split-f32-rows.wgsl.jinjaAdded+47
- build/webgpu/matmul-nbits.wgsl.jinja+9-6
- build/webgpu/metadata.json+1-63
- build/webgpu/q4-block-scale.wgsl.jinjaAdded+385
- build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja+19-4
- build/webgpu/test.json
15 unmodified lines16171819202122232425262727 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061 unmodified line10810911011115 unmodified linesSee the [ONNX Runtime `MatMulNBits` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.MatMulNBits) for the reference semantics.## Inputs| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence || --- | --- | --- | --- | --- | --- | --- || `aT` | `A` | `T1` | — | — | Float input matrix, not quantized. Rank 2 has shape `(M, K)` and rank 3 has shape `(batch, sequence, K)`; only the last axis is the reduction axis and the leading axes fold into the row count, so the ordinary activation needs no surrounding Reshape. | required || `bT` | `B` | `uint8` | `3` | — | Bit-packed uint8 weight matrix of shape `(N, k_blocks, blob_size)`, where `k_blocks = ceil(K / block_size)` and `blob_size = block_size * bits / 8`. Codes are packed low-first along K. Bound in the packed storage layout: four blob bytes per u32 word, so the kernels stream the blob's own bytes rather than one widened word per byte. | required || `scalesT` | `scales` | `T1` | `2` | — | Per-block dequantization scale factors of shape `(N, k_blocks)`, with the same dtype as `A`. | required || `zeroPointsT` | `zero_points` | `T3` | `2` | — | Standard unpacked per-block zero points with shape `(N, k_blocks)` and the same dtype as `A`. Omission uses `2^(bits - 1)`. | optional || `biasT` | `bias` | `T1` | `1` | — | Optional bias vector of shape `[N]` added to the output. | optional |27 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `prefill_tiled_reg_vec4_splitk_default_zero` — Splits the vec4 register-tiled K reduction across dispatch.z, then combines f32 partials and bias. Large 2-bit f16 tiles pin the narrowest subgroup width of a variable range under subgroup-size control; fixed 32-lane paths reuse each packed word, scale, and zero point across four vectors.- `prefill_tiled_reg_vec4_default_zero` — Register-blocked prefill with vec4 activation loads. Taller inputs use 128-row tiles. Large 2-bit f16 grids pin the narrowest width of a variable subgroup range under size control, with BK=16 on 16–32 lanes; other tiers use BK=32. Deep 2-bit reductions on fixed 32-lane subgroups unpack four vectors per packed word and reuse its scale and zero point.- `prefill_tiled_reg_vec4_splitk_zero_bias` — Splits the vec4 register-tiled K reduction across dispatch.z, then combines f32 partials and bias. Large 2-bit f16 tiles pin the narrowest subgroup width of a variable range under subgroup-size control; fixed 32-lane paths reuse each packed word, scale, and zero point across four vectors.- `prefill_tiled_reg_vec4_zero_bias` — Register-blocked prefill with vec4 activation loads. Taller inputs use 128-row tiles. Large 2-bit f16 grids pin the narrowest width of a variable subgroup range under size control, with BK=16 on 16–32 lanes; other tiers use BK=32. Deep 2-bit reductions on fixed 32-lane subgroups unpack four vectors per packed word and reuse its scale and zero point.- `prefill_tiled_reg_vec4_splitk_zero_only` — Splits the vec4 register-tiled K reduction across dispatch.z, then combines f32 partials and bias. Large 2-bit f16 tiles pin the narrowest subgroup width of a variable range under subgroup-size control; fixed 32-lane paths reuse each packed word, scale, and zero point across four vectors.- `prefill_tiled_reg_vec4_zero_only` — Register-blocked prefill with vec4 activation loads. Taller inputs use 128-row tiles. Large 2-bit f16 grids pin the narrowest width of a variable subgroup range under size control, with BK=16 on 16–32 lanes; other tiers use BK=32. Deep 2-bit reductions on fixed 32-lane subgroups unpack four vectors per packed word and reuse its scale and zero point.- `prefill_tiled_reg_vec4_splitk_bias_only` — Splits the vec4 register-tiled K reduction across dispatch.z, then combines f32 partials and bias. Large 2-bit f16 tiles pin the narrowest subgroup width of a variable range under subgroup-size control; fixed 32-lane paths reuse each packed word, scale, and zero point across four vectors.- `prefill_tiled_reg_vec4_bias_only` — Register-blocked prefill with vec4 activation loads. Taller inputs use 128-row tiles. Large 2-bit f16 grids pin the narrowest width of a variable subgroup range under size control, with BK=16 on 16–32 lanes; other tiers use BK=32. Deep 2-bit reductions on fixed 32-lane subgroups unpack four vectors per packed word and reuse its scale and zero point.## Device requirementsSome implementation variants require `subgroup-matrix` and `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.## Files- [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)- [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](build/webgpu/test.json) — correctness cases- [`bench.json`](build/webgpu/bench.json) — benchmark cases- [`matmul-nbits-dp4a-quantize.wgsl.jinja`](build/webgpu/matmul-nbits-dp4a-quantize.wgsl.jinja)- [`matmul-nbits-gemv-q4.wgsl.jinja`](build/webgpu/matmul-nbits-gemv-q4.wgsl.jinja)- [`matmul-nbits-q4-dp4a-prefill.wgsl.jinja`](build/webgpu/matmul-nbits-q4-dp4a-prefill.wgsl.jinja)- [`matmul-nbits-q4-prefill-tile4x4.wgsl.jinja`](build/webgpu/matmul-nbits-q4-prefill-tile4x4.wgsl.jinja)- [`matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja`](build/webgpu/matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja)- [`matmul-nbits-q4-prefill-tiled.wgsl.jinja`](build/webgpu/matmul-nbits-q4-prefill-tiled.wgsl.jinja)- [`matmul-nbits-q4-sgmat.wgsl.jinja`](build/webgpu/matmul-nbits-q4-sgmat.wgsl.jinja)- [`matmul-nbits.wgsl.jinja`](build/webgpu/matmul-nbits.wgsl.jinja)- [`reduce-axis0-splitk-combine.wgsl.jinja`](build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.3```Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.Replace each `*Data` placeholder with a typed array containing the corresponding input data.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.MatMulNBits", { version: 1 });const { yT } = await kernel({aT: { data: aTData, shape: [2, 17] },bT: { data: bTData, shape: [2, 2, 8] },1 unmodified line}, {attrs: { K: 17, N: 2, block_size: 16 },});```15 unmodified lines161718192021222324252627282930313227 unmodified lines606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401 unmodified line14214314414514615 unmodified linesSee the [ONNX Runtime `MatMulNBits` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.MatMulNBits) for the reference semantics.## Differences from the ONNX Runtime spec- Input `g_idx`: The deprecated group-index input is not implemented by this inference package.- Attribute `weight_prepacked`: Prepacked weight layouts are not accepted; `B` must use the public bit-packed uint8 layout.## Inputs| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence || --- | --- | --- | --- | --- | --- | --- || `aT` | `A` | `T1` | — | — | Float input matrix, not quantized. Rank 2 has shape `(M, K)` and rank 3 has shape `(batch, sequence, K)`; only the last axis is the reduction axis and the leading axes fold into the row count, so the ordinary activation needs no surrounding Reshape. | required || `bT` | `B` | `uint8` | `3` | — | Bit-packed uint8 weight matrix of shape `(N, k_blocks, blob_size)`, where `k_blocks = ceil(K / block_size)` and `blob_size = block_size * bits / 8`. Codes are packed low-first along K. The kernels read the uint8 data directly as 32-bit words, four bytes each, so no repacking is needed. | required || `scalesT` | `scales` | `T1` | `2` | — | Per-block dequantization scale factors of shape `(N, k_blocks)`, with the same dtype as `A`. | required || `zeroPointsT` | `zero_points` | `T3` | `2` | — | Standard unpacked per-block zero points with shape `(N, k_blocks)` and the same dtype as `A`. Omission uses `2^(bits - 1)`. | optional || `biasT` | `bias` | `T1` | `1` | — | Optional bias vector of shape `[N]` added to the output. | optional |27 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `gemv_clusters` — Four subgroup-owned 32-lane clusters accumulate two output columns each, loading two packed words per lane. Complete 32-wide subgroups reduce without workgroup memory or barriers; if the subgroups found at run time differ, a general path that works for any subgroup size is used.- `prefill_q4_block_scale_wide` — Runs the exact raw-code 4-bit products on 128 x 64 tiles of eight subgroups, reusing each staged weight block across twice the rows.- `prefill_q4_block_scale_splitk` — Splits underfilled exact 4-bit products along block-aligned K slices: f16 activations times the raw codes on subgroup matrices, each block folded into float32 sums times its scale (minus scale x zero x the row's block sum), float32 partials summed and biased once by a combine pass.- `prefill_q4_block_scale` — Multiplies f16 activations by raw 4-bit codes on subgroup matrices with exact products, folding each quantization block into float32 sums times its per-column scale; zero points subtract scale x zero x the row's block sum. Products are exact for every operand range, so no pass is needed to check value ranges and no temporary buffer is used.- `prefill_q4_block_scale_f32_splitk` — For `accuracy_level` 2 to 4 with f32 storage, splits underfilled 4-bit products along block-aligned K slices: rows as a plane of halves and a plane of remainders times a power of two, both multiplied by the raw codes on subgroup matrices and folded per block times its scale; a combine pass sums, rescales and biases.- `prefill_q4_block_scale_f32` — For `accuracy_level` 2 to 4 with f32 storage: a split pass writes each row as halves plus half remainders times a power of two (about 22 bits; values far below the row peak lose precision); both multiply the raw codes into one float32 matrix per block, folded times its scale (minus scale x zero x the block row sum).- `prefill_native16_packed_64x64`, `prefill_native16_packed_128x128` — Multiplies f16 activations by inline-decoded 2- or 4-bit weights with f32 accumulation. Each workgroup checks whether its decoded weights fit half precision safely; if not, they are dequantized in f32, otherwise packed half tiles are used. Converts each output to half once. Not used for `accuracy_level` 1, or for 4-bit weights at `accuracy_level` 0.- `prefill_native16_packed_splitk` — Splits underfilled 2- or 4-bit products along K, stores f32 partials for padded rows, then combines and biases once. Each workgroup checks decoded-weight range and uses f32 dequantization when packed half operands are unsafe. Not used for `accuracy_level` 1, or for 4-bit weights at `accuracy_level` 0.- `prefill_native16_split_f32` — Explicit `accuracy_level=2` Q4 path for f32 storage. Row-scaled activation and weight high/low half pairs form three products with f32 accumulation, omitting low×low. Half operand precision and range apply: residuals may underflow and decoded weights may overflow. This path does not implement exact f32 contraction.- `gemv` — Packed-weight GEMV with workgroup size bounded by the available K vectors and reported subgroup geometry. With the WGSL `subgroup_id` feature, subgroup IDs compact the partial totals; otherwise partials are reduced through a workgroup-memory array indexed by local invocation. Folded grids balance their columns to avoid excessive padding.- `prefill_sgmat_packed` — Float32 rows of whole 64-row blocks against 4-bit weights in blocks of 32: the shared subgroup-matrix GEMM reads the rows straight from storage and decodes each lane's half block of codes into a double-buffered float32 tile as `(code - 8) * scale`, with consecutive workgroups covering groups of row tiles.- `prefill_sgmat_packed_splitk` — `prefill_sgmat_packed` over K slices when its output tiles underfill the device: each slice writes float32 partials and a combine pass sums them in slice order.- `prefill_sgmat_splitk` — The subgroup-matrix prefill over K slices when its output tiles underfill the device: each slice folds its 32-wide K tiles into float32 partials, and a combine pass sums them in slice order and adds the bias.- `prefill_tiled_reg_vec4_splitk` — Register-blocked prefill with vec4 activation loads and split-K f32 partials. Subgroup geometry selects the weight order and packed-word reuse. Complete reduction tiles omit redundant K bounds.- `prefill_tiled_reg_vec4` — Register-blocked prefill with `vec4` activation loads. Reported subgroup width redistributes a fixed output tile across invocation rows and columns. Geometry selects row tiles, weight order and packed-word reuse within workgroup limits. Some 2-bit f16 cases use `BK=16`; others use `BK=32`. Complete tiles omit K bounds.- `prefill_tiled_reg` — Register-blocked prefill with scalar activation loads. Row fill and subgroup geometry select the micro-tile and weight order. Quant-block alignment selects packed-word reuse. Complete reduction tiles omit redundant K bounds; partial tiles check them.## Device requirementsSome implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.## Files- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/test.json) — correctness cases- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/bench.json) — benchmark cases- [`gemm-subgroup-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/gemm-subgroup-matrix.wgsl.jinja)- [`matmul-native16-splitk-reduce.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-native16-splitk-reduce.wgsl.jinja)- [`matmul-nbits-dp4a-quantize.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-dp4a-quantize.wgsl.jinja)- [`matmul-nbits-gemv-clusters.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-gemv-clusters.wgsl.jinja)- [`matmul-nbits-gemv-q4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-gemv-q4.wgsl.jinja)- [`matmul-nbits-q4-dp4a-prefill.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-dp4a-prefill.wgsl.jinja)- [`matmul-nbits-q4-native16-packed.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-native16-packed.wgsl.jinja)- [`matmul-nbits-q4-prefill-tile4x4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-prefill-tile4x4.wgsl.jinja)- [`matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja)- [`matmul-nbits-q4-prefill-tiled.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-prefill-tiled.wgsl.jinja)- [`matmul-nbits-q4-range-guarded.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-range-guarded.wgsl.jinja)- [`matmul-nbits-q4-sgmat.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-sgmat.wgsl.jinja)- [`matmul-nbits-split-f32-rows.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-split-f32-rows.wgsl.jinja)- [`matmul-nbits.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits.wgsl.jinja)- [`q4-block-scale.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/q4-block-scale.wgsl.jinja)- [`reduce-axis0-splitk-combine.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.4```Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.MatMulNBits", { version: 1 });const aTData = Float32Array.of(0.14603463, 0.12950113, 0.10649598, 0.085161425, 0.07283477, 0.07489503, 0.093901455,0.12914494, 0.17667694, 0.22981437, 0.28005305, 0.31826597, 0.3360224, 0.32684615,0.28723875, 0.21732353, 0.12101746, 0.005700612, -0.11857925, -0.24026643, -0.34767178,-0.4303828, -0.4805244, -0.4937053, -0.46952623, -0.41158408, -0.3269733, -0.22535284,-0.11770318, -0.01494011, 0.07343123, 0.1404443, 0.18243429, 0.19933969,);const bTData = Uint8Array.of(16, 50, 84, 118, 152, 186, 220, 254, 33, 0, 0, 0, 0, 0, 0, 0, 255, 238, 221, 204, 187,170, 153, 136, 240, 0, 0, 0, 0, 0, 0, 0,);const scalesTData = Float32Array.of(0.04, 0.08, 0.06, 0.12);const { yT } = await kernel({aT: { data: aTData, shape: [2, 17] },bT: { data: bTData, shape: [2, 2, 8] },1 unmodified line}, {attrs: { K: 17, N: 2, block_size: 16 },});console.log({ yT });```
123456705 unmodified lines712713714715716717207 unmodified lines925926927928929930{"tunableSpace": { "workgroupSize": [64, 128, 256] },"cases": [{"name": "qwen3-qproj-decode-m1-q8g32-zero-bias-gemv","preset": "smoke",705 unmodified lines"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2560, "N": 4096, "bits": 4, "block_size": 64, "accuracy_level": 4 }},{"name": "mmnb-q4-dp4a-prefill-smoke-m128-k1024-n1024-al4","preset": "smoke",207 unmodified lines"outputs": { "yT": { "shape": [128, 10240], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 5120, "N": 10240, "bits": 2, "block_size": 128 }}]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111705 unmodified lines817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887207 unmodified lines10951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104{"tunableSpace": { "workgroupSize": [64, 128, 256] },"cases": [{"name": "qwen3-0.6b-pte-prefill-m512-oproj-k2048-n1024-q4g64","preset": "model","vars": { "M": 512, "K": 2048, "N": 1024, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [512, 2048], "dtype": "float32", "dist": "normal", "seed": 9301, "scale": 0.2 },"bT": { "shape": [1024, 32, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9302 },"scalesT": {"shape": [1024, 32],"dtype": "float32","dist": "uniform","seed": 9303,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [512, 1024], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 1024, "bits": 4, "block_size": 64 }},{"name": "qwen3-0.6b-pte-prefill-m512-gate-k1024-n3072-q4g64","preset": "model","vars": { "M": 512, "K": 1024, "N": 3072, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [512, 1024], "dtype": "float32", "dist": "normal", "seed": 9311, "scale": 0.2 },"bT": { "shape": [3072, 16, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9312 },"scalesT": {"shape": [3072, 16],"dtype": "float32","dist": "uniform","seed": 9313,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [512, 3072], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 1024, "N": 3072, "bits": 4, "block_size": 64 }},{"name": "qwen3-0.6b-pte-prefill-m512-kv-k1024-n1024-q4g64","preset": "model","vars": { "M": 512, "K": 1024, "N": 1024, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [512, 1024], "dtype": "float32", "dist": "normal", "seed": 9321, "scale": 0.2 },"bT": { "shape": [1024, 16, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9322 },"scalesT": {"shape": [1024, 16],"dtype": "float32","dist": "uniform","seed": 9323,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [512, 1024], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 1024, "N": 1024, "bits": 4, "block_size": 64 }},{"name": "qwen3-0.6b-pte-prefill-m256-down-k3072-n1024-q4g64","preset": "model","vars": { "M": 256, "K": 3072, "N": 1024, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [256, 3072], "dtype": "float32", "dist": "normal", "seed": 9331, "scale": 0.2 },"bT": { "shape": [1024, 48, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9332 },"scalesT": {"shape": [1024, 48],"dtype": "float32","dist": "uniform","seed": 9333,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [256, 1024], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 3072, "N": 1024, "bits": 4, "block_size": 64 }},{"name": "qwen3-0.6b-pte-decode-gateup-k1024-n6144-q4g64","preset": "model","vars": { "M": 1, "K": 1024, "N": 6144, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [1, 1024], "dtype": "float32", "dist": "normal", "seed": 9341, "scale": 0.2 },"bT": { "shape": [6144, 16, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9342 },"scalesT": {"shape": [6144, 16],"dtype": "float32","dist": "uniform","seed": 9343,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 6144], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 1024, "N": 6144, "bits": 4, "block_size": 64 }},{"name": "qwen3-qproj-decode-m1-q8g32-zero-bias-gemv","preset": "smoke",705 unmodified lines"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2560, "N": 4096, "bits": 4, "block_size": 64, "accuracy_level": 4 }},{"name": "qwen3-qproj-prefill-m512-q4g64-al2","preset": "model","vars": { "M": 512, "K": 2560, "N": 4096, "bits": 4, "blockSize": 64, "accuracyLevel": 2 },"inputs": {"aT": { "shape": [512, 2560], "dtype": "float32", "dist": "normal", "seed": 353, "scale": 0.2 },"bT": { "shape": [4096, 40, 32], "dtype": "uint8", "dist": "q4pair", "seed": 354 },"scalesT": {"shape": [4096, 40],"dtype": "float32","dist": "uniform","seed": 355,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [512, 4096], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2560, "N": 4096, "bits": 4, "block_size": 64, "accuracy_level": 2 }},{"name": "qwen3-qproj-prefill-m128-q4g64-al4-zero-bias","preset": "model","vars": { "M": 128, "K": 2560, "N": 4096, "bits": 4, "blockSize": 64, "accuracyLevel": 4 },"inputs": {"aT": { "shape": [128, 2560], "dtype": "float32", "dist": "normal", "seed": 359, "scale": 0.2 },"bT": { "shape": [4096, 40, 32], "dtype": "uint8", "dist": "q4pair", "seed": 360 },"scalesT": {"shape": [4096, 40],"dtype": "float32","dist": "uniform","seed": 361,"offset": 0.04,"scale": 0.01,"signed": false},"zeroPointsT": { "shape": [4096, 40], "dtype": "float32", "dist": "randint", "seed": 362, "min": 6, "max": 10 },"biasT": { "shape": [4096], "dtype": "float32", "dist": "normal", "seed": 363, "scale": 0.05 }},"outputs": { "yT": { "shape": [128, 4096], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2560, "N": 4096, "bits": 4, "block_size": 64, "accuracy_level": 4 }},{"name": "qwen3-mlp-down-prefill-m512-q4g32-al4","preset": "model","vars": { "M": 512, "K": 9728, "N": 2560, "bits": 4, "blockSize": 32, "accuracyLevel": 4 },"inputs": {"aT": { "shape": [512, 9728], "dtype": "float32", "dist": "normal", "seed": 353, "scale": 0.2 },"bT": { "shape": [2560, 304, 16], "dtype": "uint8", "dist": "q4pair", "seed": 354 },"scalesT": {"shape": [2560, 304],"dtype": "float32","dist": "uniform","seed": 355,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [512, 2560], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 9728, "N": 2560, "bits": 4, "block_size": 32, "accuracy_level": 4 }},{"name": "mmnb-q4-dp4a-prefill-smoke-m128-k1024-n1024-al4","preset": "smoke",207 unmodified lines"outputs": { "yT": { "shape": [128, 10240], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 5120, "N": 10240, "bits": 2, "block_size": 128 }},{"name": "matmul-nbits-q4-vec4-partial-tiles-m65-k132-n1025","preset": "model","inputs": {"aT": { "shape": [65, 132], "dtype": "float32", "dist": "normal", "seed": 440, "scale": 0.2 },"bT": { "shape": [1025, 5, 16], "dtype": "uint8", "dist": "q4pair", "seed": 441 },"scalesT": {"shape": [1025, 5],"dtype": "float32","dist": "uniform","seed": 442,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [65, 1025], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * numel(shapes.yT) * dim(shapes.aT, ranks.aT - 1)" }] },"attrs": { "K": 132, "N": 1025, "bits": 4, "block_size": 32 }},{"name": "matmul-nbits-q4-quant-block-smaller-than-tile-m129-k65-n1025","preset": "edge","vars": { "M": 129, "K": 65, "N": 1025, "bits": 4, "blockSize": 16 },"inputs": {"aT": { "shape": [129, 65], "dtype": "float32", "dist": "normal", "seed": 610, "scale": 0.2 },"bT": { "shape": [1025, 5, 8], "dtype": "uint8", "dist": "q4pair", "seed": 611 },"scalesT": {"shape": [1025, 5],"dtype": "float32","dist": "uniform","seed": 612,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [129, 1025], "dtype": "float32" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 65, "N": 1025, "bits": 4, "block_size": 16 }},{"name": "ort-narrow-dp4a-m32-k1024-n16-b32","preset": "edge","vars": { "M": 32, "K": 1024, "N": 16, "bits": 4, "blockSize": 32, "accuracyLevel": 4 },"inputs": {"aT": { "shape": [32, 1024], "dtype": "float32", "dist": "normal", "seed": 353, "scale": 0.2 },"bT": { "shape": [16, 32, 16], "dtype": "uint8", "dist": "q4pair", "seed": 354 },"scalesT": {"shape": [16, 32],"dtype": "float32","dist": "uniform","seed": 355,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [32, 16], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 1024, "N": 16, "bits": 4, "block_size": 32, "accuracy_level": 4 }},{"name": "ort-narrow-dp4a-m32-k2048-n32-b64","preset": "edge","vars": { "M": 32, "K": 2048, "N": 32, "bits": 4, "blockSize": 64, "accuracyLevel": 4 },"inputs": {"aT": { "shape": [32, 2048], "dtype": "float32", "dist": "normal", "seed": 353, "scale": 0.2 },"bT": { "shape": [32, 32, 32], "dtype": "uint8", "dist": "q4pair", "seed": 354 },"scalesT": {"shape": [32, 32],"dtype": "float32","dist": "uniform","seed": 355,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [32, 32], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 32, "bits": 4, "block_size": 64, "accuracy_level": 4 }},{"name": "ort-narrow-dp4a-m128-k4096-n32-b128","preset": "edge","vars": { "M": 128, "K": 4096, "N": 32, "bits": 4, "blockSize": 128, "accuracyLevel": 4 },"inputs": {"aT": { "shape": [128, 4096], "dtype": "float32", "dist": "normal", "seed": 353, "scale": 0.2 },"bT": { "shape": [32, 32, 64], "dtype": "uint8", "dist": "q4pair", "seed": 354 },"scalesT": {"shape": [32, 32],"dtype": "float32","dist": "uniform","seed": 355,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [128, 32], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 32, "bits": 4, "block_size": 128, "accuracy_level": 4 }},{"name": "ort-narrow-dp4a-m33-k1152-n17-b64","preset": "edge","vars": { "M": 33, "K": 1152, "N": 17, "bits": 4, "blockSize": 64, "accuracyLevel": 4 },"inputs": {"aT": { "shape": [33, 1152], "dtype": "float32", "dist": "normal", "seed": 353, "scale": 0.2 },"bT": { "shape": [17, 18, 32], "dtype": "uint8", "dist": "q4pair", "seed": 354 },"scalesT": {"shape": [17, 18],"dtype": "float32","dist": "uniform","seed": 355,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [33, 17], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 1152, "N": 17, "bits": 4, "block_size": 64, "accuracy_level": 4 }},{"name": "ort-narrow-dp4a-m64-k4096-n48-b256","preset": "edge","vars": { "M": 64, "K": 4096, "N": 48, "bits": 4, "blockSize": 256, "accuracyLevel": 4 },"inputs": {"aT": { "shape": [64, 4096], "dtype": "float32", "dist": "normal", "seed": 353, "scale": 0.2 },"bT": { "shape": [48, 16, 128], "dtype": "uint8", "dist": "q4pair", "seed": 354 },"scalesT": {"shape": [48, 16],"dtype": "float32","dist": "uniform","seed": 355,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [64, 48], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 48, "bits": 4, "block_size": 256, "accuracy_level": 4 }},{"name": "ort-narrow-dp4a-m128-k4096-n64-b32","preset": "edge","vars": { "M": 128, "K": 4096, "N": 64, "bits": 4, "blockSize": 32, "accuracyLevel": 4 },"inputs": {"aT": { "shape": [128, 4096], "dtype": "float32", "dist": "normal", "seed": 353, "scale": 0.2 },"bT": { "shape": [64, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 354 },"scalesT": {"shape": [64, 128],"dtype": "float32","dist": "uniform","seed": 355,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [128, 64], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 64, "bits": 4, "block_size": 32, "accuracy_level": 4 }},{"name": "q4f16-prefill-m128-k2048-n2048-g32","preset": "model","vars": { "M": 128, "K": 2048, "N": 2048, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 128, 2048], "dtype": "float16", "dist": "normal", "seed": 1401, "scale": 0.2 },"bT": { "shape": [2048, 64, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1402 },"scalesT": {"shape": [2048, 64],"dtype": "float16","dist": "uniform","seed": 1403,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 128, 2048], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 2048, "bits": 4, "block_size": 32 }},{"name": "q4f16-prefill-m512-k2048-n8192-g32-up","preset": "model","vars": { "M": 512, "K": 2048, "N": 8192, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 512, 2048], "dtype": "float16", "dist": "normal", "seed": 1411, "scale": 0.2 },"bT": { "shape": [8192, 64, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1412 },"scalesT": {"shape": [8192, 64],"dtype": "float16","dist": "uniform","seed": 1413,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 512, 8192], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 8192, "bits": 4, "block_size": 32 }},{"name": "q4f16-prefill-m512-k8192-n2048-g32-down","preset": "model","vars": { "M": 512, "K": 8192, "N": 2048, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 512, 8192], "dtype": "float16", "dist": "normal", "seed": 1421, "scale": 0.2 },"bT": { "shape": [2048, 256, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1422 },"scalesT": {"shape": [2048, 256],"dtype": "float16","dist": "uniform","seed": 1423,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 512, 2048], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 8192, "N": 2048, "bits": 4, "block_size": 32 }},{"name": "q4f16-prefill-m2048-k4096-n4096-g32","preset": "model","vars": { "M": 2048, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [2048, 4096], "dtype": "float16", "dist": "normal", "seed": 1431, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1432 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1433,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [2048, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-prefill-m512-k2560-n4096-g128-zp-bias","preset": "model","vars": { "M": 512, "K": 2560, "N": 4096, "bits": 4, "blockSize": 128 },"inputs": {"aT": { "shape": [512, 2560], "dtype": "float16", "dist": "normal", "seed": 1441, "scale": 0.2 },"bT": { "shape": [4096, 20, 64], "dtype": "uint8", "dist": "q4pair", "seed": 1442 },"scalesT": {"shape": [4096, 20],"dtype": "float16","dist": "uniform","seed": 1443,"offset": 0.04,"scale": 0.01,"signed": false},"zeroPointsT": {"shape": [4096, 20],"dtype": "float16","dist": "uniform","seed": 1444,"offset": 6,"scale": 4,"signed": false},"biasT": { "shape": [4096], "dtype": "float16", "dist": "normal", "seed": 1445, "scale": 0.1 }},"outputs": { "yT": { "shape": [512, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2560, "N": 4096, "bits": 4, "block_size": 128 }},{"name": "q4f16-prefill-m77-k768-n3072-g32-zp","preset": "model","vars": { "M": 77, "K": 768, "N": 3072, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 77, 768], "dtype": "float16", "dist": "normal", "seed": 1451, "scale": 0.2 },"bT": { "shape": [3072, 24, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1452 },"scalesT": {"shape": [3072, 24],"dtype": "float16","dist": "uniform","seed": 1453,"offset": 0.04,"scale": 0.01,"signed": false},"zeroPointsT": {"shape": [3072, 24],"dtype": "float16","dist": "uniform","seed": 1454,"offset": 6,"scale": 4,"signed": false}},"outputs": { "yT": { "shape": [1, 77, 3072], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 768, "N": 3072, "bits": 4, "block_size": 32 }},{"name": "q4f16-prefill-m32-k2048-n2048-g32","preset": "model","vars": { "M": 32, "K": 2048, "N": 2048, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 32, 2048], "dtype": "float16", "dist": "normal", "seed": 1461, "scale": 0.2 },"bT": { "shape": [2048, 64, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1462 },"scalesT": {"shape": [2048, 64],"dtype": "float16","dist": "uniform","seed": 1463,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 32, 2048], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 2048, "bits": 4, "block_size": 32 }},{"name": "q4f16-prefill-m48-k4096-n4096-g32","preset": "model","vars": { "M": 48, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 48, 4096], "dtype": "float16", "dist": "normal", "seed": 1471, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1472 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1473,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 48, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-prefill-m64-k2048-n2048-g32","preset": "model","vars": { "M": 64, "K": 2048, "N": 2048, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 64, 2048], "dtype": "float16", "dist": "normal", "seed": 1481, "scale": 0.2 },"bT": { "shape": [2048, 64, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1482 },"scalesT": {"shape": [2048, 64],"dtype": "float16","dist": "uniform","seed": 1483,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 64, 2048], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 2048, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m16-k4096-n4096-g32","preset": "model","vars": { "M": 16, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 16, 4096], "dtype": "float16", "dist": "normal", "seed": 1601, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1602 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1603,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 16, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m32-k4096-n4096-g32","preset": "model","vars": { "M": 32, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 32, 4096], "dtype": "float16", "dist": "normal", "seed": 1606, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1607 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1608,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 32, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m64-k4096-n4096-g32-qproj","preset": "model","vars": { "M": 64, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 64, 4096], "dtype": "float16", "dist": "normal", "seed": 1611, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1612 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1613,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 64, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m32-k8192-n2048-g32-down","preset": "model","vars": { "M": 32, "K": 8192, "N": 2048, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 32, 8192], "dtype": "float16", "dist": "normal", "seed": 1616, "scale": 0.2 },"bT": { "shape": [2048, 256, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1617 },"scalesT": {"shape": [2048, 256],"dtype": "float16","dist": "uniform","seed": 1618,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 32, 2048], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 8192, "N": 2048, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m64-k2560-n4096-g128-zp-bias","preset": "model","vars": { "M": 64, "K": 2560, "N": 4096, "bits": 4, "blockSize": 128 },"inputs": {"aT": { "shape": [1, 64, 2560], "dtype": "float16", "dist": "normal", "seed": 1621, "scale": 0.2 },"bT": { "shape": [4096, 20, 64], "dtype": "uint8", "dist": "q4pair", "seed": 1622 },"scalesT": {"shape": [4096, 20],"dtype": "float16","dist": "uniform","seed": 1623,"offset": 0.04,"scale": 0.01,"signed": false},"zeroPointsT": {"shape": [4096, 20],"dtype": "float16","dist": "uniform","seed": 1624,"offset": 6,"scale": 4,"signed": false},"biasT": { "shape": [4096], "dtype": "float16", "dist": "normal", "seed": 1625, "scale": 0.1 }},"outputs": { "yT": { "shape": [1, 64, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2560, "N": 4096, "bits": 4, "block_size": 128 }},{"name": "q4f16-smallm-m16-k1024-n1024-g32","preset": "model","vars": { "M": 16, "K": 1024, "N": 1024, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 16, 1024], "dtype": "float16", "dist": "normal", "seed": 1626, "scale": 0.2 },"bT": { "shape": [1024, 32, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1627 },"scalesT": {"shape": [1024, 32],"dtype": "float16","dist": "uniform","seed": 1628,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 16, 1024], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 1024, "N": 1024, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m48-k3072-n3072-g64","preset": "model","vars": { "M": 48, "K": 3072, "N": 3072, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [1, 48, 3072], "dtype": "float16", "dist": "normal", "seed": 1631, "scale": 0.2 },"bT": { "shape": [3072, 48, 32], "dtype": "uint8", "dist": "q4pair", "seed": 1632 },"scalesT": {"shape": [3072, 48],"dtype": "float16","dist": "uniform","seed": 1633,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 48, 3072], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 3072, "N": 3072, "bits": 4, "block_size": 64 }},{"name": "q4f16-smallm-m9-k4096-n4096-g32","preset": "model","vars": { "M": 9, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 9, 4096], "dtype": "float16", "dist": "normal", "seed": 1641, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1642 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1643,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 9, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m37-k4096-n4096-g32","preset": "model","vars": { "M": 37, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 37, 4096], "dtype": "float16", "dist": "normal", "seed": 1646, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1647 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1648,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 37, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m21-k2048-n8192-g32-up","preset": "model","vars": { "M": 21, "K": 2048, "N": 8192, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 21, 2048], "dtype": "float16", "dist": "normal", "seed": 1651, "scale": 0.2 },"bT": { "shape": [8192, 64, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1652 },"scalesT": {"shape": [8192, 64],"dtype": "float16","dist": "uniform","seed": 1653,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 21, 8192], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 8192, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m32-k2048-n8192-g32-up","preset": "model","vars": { "M": 32, "K": 2048, "N": 8192, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 32, 2048], "dtype": "float16", "dist": "normal", "seed": 1656, "scale": 0.2 },"bT": { "shape": [8192, 64, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1657 },"scalesT": {"shape": [8192, 64],"dtype": "float16","dist": "uniform","seed": 1658,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 32, 8192], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 8192, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m96-k4096-n4096-g32","preset": "model","vars": { "M": 96, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 96, 4096], "dtype": "float16", "dist": "normal", "seed": 1661, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1662 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1663,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 96, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m128-k3072-n8192-g32-up","preset": "model","vars": { "M": 128, "K": 3072, "N": 8192, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 128, 3072], "dtype": "float16", "dist": "normal", "seed": 1666, "scale": 0.2 },"bT": { "shape": [8192, 96, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1667 },"scalesT": {"shape": [8192, 96],"dtype": "float16","dist": "uniform","seed": 1668,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 128, 8192], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 3072, "N": 8192, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m80-k1024-n4096-g32","preset": "model","vars": { "M": 80, "K": 1024, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 80, 1024], "dtype": "float16", "dist": "normal", "seed": 1681, "scale": 0.2 },"bT": { "shape": [4096, 32, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1682 },"scalesT": {"shape": [4096, 32],"dtype": "float16","dist": "uniform","seed": 1683,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 80, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 1024, "N": 4096, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m128-k1024-n2048-g32","preset": "model","vars": { "M": 128, "K": 1024, "N": 2048, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 128, 1024], "dtype": "float16", "dist": "normal", "seed": 1686, "scale": 0.2 },"bT": { "shape": [2048, 32, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1687 },"scalesT": {"shape": [2048, 32],"dtype": "float16","dist": "uniform","seed": 1688,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 128, 2048], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 1024, "N": 2048, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m200-k2048-n2048-g32","preset": "model","vars": { "M": 200, "K": 2048, "N": 2048, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 200, 2048], "dtype": "float16", "dist": "normal", "seed": 1691, "scale": 0.2 },"bT": { "shape": [2048, 64, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1692 },"scalesT": {"shape": [2048, 64],"dtype": "float16","dist": "uniform","seed": 1693,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 200, 2048], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2048, "N": 2048, "bits": 4, "block_size": 32 }},{"name": "q4f16-smallm-m64-k512-n8192-g32","preset": "model","vars": { "M": 64, "K": 512, "N": 8192, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1, 64, 512], "dtype": "float16", "dist": "normal", "seed": 1696, "scale": 0.2 },"bT": { "shape": [8192, 16, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1697 },"scalesT": {"shape": [8192, 16],"dtype": "float16","dist": "uniform","seed": 1698,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 64, 8192], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 512, "N": 8192, "bits": 4, "block_size": 32 }},{"name": "q4f16-grid-aspect-m512-k4096-n4096-g32","preset": "model","vars": { "M": 512, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [512, 4096], "dtype": "float16", "dist": "normal", "seed": 1431, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1432 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1433,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [512, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 },"provenance": {"source": "Block-quantized matrix multiplication with representative projection dimensions.","notes": "Half-precision 4-bit projections with 32-wide blocks and N=4096 at neighbouring row counts: M=480 and 481 at K=2560, and M=512, 992, 1024 and 1056 at K=4096, with the same seeded weights and scales at each K."}},{"name": "q4f16-grid-aspect-m992-k4096-n4096-g32","preset": "model","vars": { "M": 992, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [992, 4096], "dtype": "float16", "dist": "normal", "seed": 1431, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1432 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1433,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [992, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 },"provenance": {"source": "Block-quantized matrix multiplication with representative projection dimensions.","notes": "Half-precision 4-bit projections with 32-wide blocks and N=4096 at neighbouring row counts: M=480 and 481 at K=2560, and M=512, 992, 1024 and 1056 at K=4096, with the same seeded weights and scales at each K."}},{"name": "q4f16-grid-aspect-m1024-k4096-n4096-g32","preset": "model","vars": { "M": 1024, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1024, 4096], "dtype": "float16", "dist": "normal", "seed": 1431, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1432 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1433,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1024, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 },"provenance": {"source": "Block-quantized matrix multiplication with representative projection dimensions.","notes": "Half-precision 4-bit projections with 32-wide blocks and N=4096 at neighbouring row counts: M=480 and 481 at K=2560, and M=512, 992, 1024 and 1056 at K=4096, with the same seeded weights and scales at each K."}},{"name": "q4f16-grid-aspect-m1056-k4096-n4096-g32","preset": "model","vars": { "M": 1056, "K": 4096, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [1056, 4096], "dtype": "float16", "dist": "normal", "seed": 1431, "scale": 0.2 },"bT": { "shape": [4096, 128, 16], "dtype": "uint8", "dist": "q4pair", "seed": 1432 },"scalesT": {"shape": [4096, 128],"dtype": "float16","dist": "uniform","seed": 1433,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1056, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 4096, "N": 4096, "bits": 4, "block_size": 32 },"provenance": {"source": "Block-quantized matrix multiplication with representative projection dimensions.","notes": "Half-precision 4-bit projections with 32-wide blocks and N=4096 at neighbouring row counts: M=480 and 481 at K=2560, and M=512, 992, 1024 and 1056 at K=4096, with the same seeded weights and scales at each K."}},{"name": "q4f16-grid-aspect-m480-k2560-n4096-g32","preset": "model","vars": { "M": 480, "K": 2560, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [480, 2560], "dtype": "float16", "dist": "normal", "seed": 350, "scale": 0.2 },"bT": { "shape": [4096, 80, 16], "dtype": "uint8", "dist": "q4pair", "seed": 351 },"scalesT": {"shape": [4096, 80],"dtype": "float16","dist": "uniform","seed": 352,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [480, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2560, "N": 4096, "bits": 4, "block_size": 32 },"provenance": {"source": "Block-quantized matrix multiplication with representative projection dimensions.","notes": "Half-precision 4-bit projections with 32-wide blocks and N=4096 at neighbouring row counts: M=480 and 481 at K=2560, and M=512, 992, 1024 and 1056 at K=4096, with the same seeded weights and scales at each K."}},{"name": "q4f16-grid-aspect-m481-k2560-n4096-g32","preset": "model","vars": { "M": 481, "K": 2560, "N": 4096, "bits": 4, "blockSize": 32 },"inputs": {"aT": { "shape": [481, 2560], "dtype": "float16", "dist": "normal", "seed": 350, "scale": 0.2 },"bT": { "shape": [4096, 80, 16], "dtype": "uint8", "dist": "q4pair", "seed": 351 },"scalesT": {"shape": [4096, 80],"dtype": "float16","dist": "uniform","seed": 352,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [481, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] },"attrs": { "K": 2560, "N": 4096, "bits": 4, "block_size": 32 },"provenance": {"source": "Block-quantized matrix multiplication with representative projection dimensions.","notes": "Half-precision 4-bit projections with 32-wide blocks and N=4096 at neighbouring row counts: M=480 and 481 at K=2560, and M=512, 992, 1024 and 1056 at K=4096, with the same seeded weights and scales at each K."}},{"name": "gemv-clusters-qkv-k1024-n4096-q4g64","preset": "model","vars": { "M": 1, "K": 1024, "N": 4096, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [1, 1024], "dtype": "float32", "dist": "normal", "seed": 9341, "scale": 0.2 },"bT": { "shape": [4096, 16, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9342 },"scalesT": {"shape": [4096, 16],"dtype": "float32","dist": "uniform","seed": 9343,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 4096], "dtype": "float32" } },"attrs": { "K": 1024, "N": 4096, "bits": 4, "block_size": 64 },"bench": {"metrics": [{"type": "bandwidth","value": "numel(shapes.bT) + (numel(shapes.aT) + numel(shapes.scalesT) + numel(shapes.yT)) * 4"}]}},{"name": "gemv-clusters-o-k2048-n1024-q4g64","preset": "model","vars": { "M": 1, "K": 2048, "N": 1024, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [1, 2048], "dtype": "float32", "dist": "normal", "seed": 9341, "scale": 0.2 },"bT": { "shape": [1024, 32, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9342 },"scalesT": {"shape": [1024, 32],"dtype": "float32","dist": "uniform","seed": 9343,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 1024], "dtype": "float32" } },"attrs": { "K": 2048, "N": 1024, "bits": 4, "block_size": 64 },"bench": {"metrics": [{"type": "bandwidth","value": "numel(shapes.bT) + (numel(shapes.aT) + numel(shapes.scalesT) + numel(shapes.yT)) * 4"}]}},{"name": "gemv-clusters-down-k3072-n1024-q4g64","preset": "model","vars": { "M": 1, "K": 3072, "N": 1024, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [1, 3072], "dtype": "float32", "dist": "normal", "seed": 9341, "scale": 0.2 },"bT": { "shape": [1024, 48, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9342 },"scalesT": {"shape": [1024, 48],"dtype": "float32","dist": "uniform","seed": 9343,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 1024], "dtype": "float32" } },"attrs": { "K": 3072, "N": 1024, "bits": 4, "block_size": 64 },"bench": {"metrics": [{"type": "bandwidth","value": "numel(shapes.bT) + (numel(shapes.aT) + numel(shapes.scalesT) + numel(shapes.yT)) * 4"}]}},{"name": "gemv-clusters-head-k1024-n151936-q4g64","preset": "model","vars": { "M": 1, "K": 1024, "N": 151936, "bits": 4, "blockSize": 64 },"inputs": {"aT": { "shape": [1, 1024], "dtype": "float32", "dist": "normal", "seed": 9341, "scale": 0.2 },"bT": { "shape": [151936, 16, 32], "dtype": "uint8", "dist": "q4pair", "seed": 9342 },"scalesT": {"shape": [151936, 16],"dtype": "float32","dist": "uniform","seed": 9343,"offset": 0.04,"scale": 0.01,"signed": false}},"outputs": { "yT": { "shape": [1, 151936], "dtype": "float32" } },"attrs": { "K": 1024, "N": 151936, "bits": 4, "block_size": 64 },"bench": {"metrics": [{"type": "bandwidth","value": "numel(shapes.bT) + (numel(shapes.aT) + numel(shapes.scalesT) + numel(shapes.yT)) * 4"}]}}]}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287enable subgroups;{% if pinSubgroupSize32 %}enable subgroup_size_control;{% endif %}enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);
{% if not env.device.wgslLanguageFeatures.has("packed_4x8_integer_dot_product") %}// Runtime source-compatible fallbacks for the packed 4x8 integer built-ins used// by quantized kernels. Native implementations remain unshadowed when the// language feature is present. The user functions retain the built-ins'// @must_use contract, but cannot be @const; every call is runtime.// Inputs are function parameters, so replacing a built-in call with one of// these same-name functions preserves WGSL's single evaluation of each// argument. Byte extraction is unsigned. Signed lanes use the exact// i32(byte ^ 0x80u) - 128i sign extension, avoiding signed-left-shift overflow// while preserving every 8-bit two's-complement value.@must_use fn unpack4xU8(e: u32) -> vec4<u32> { return (vec4<u32>(e) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(0xffu);}{% endif %}{{ env.wgsl.resourceDeclarations }}
{% set operandScalar = "f32" %}{% set accScalar = "f32" %}{% set SPLIT_K = splitK if splitK is defined else 1 %}{% set kPerSplit = kPerSplit | default(0) %}{% set OUT = outputBuffer if outputBuffer is defined else "y" %}{% set tileMValue = 64 %}{% set tileNValue = 64 %}{% set tileKValue = 32 %}{% set packedKTail = false %}{% set useDoubleBufferedB = true %}{% set useBalancedAccumulation = false %}{% set columnTileBaseValue = 0 %}{% set rowTileBaseValue = 0 %}{% set tileGroup = tileGroupRows if (tileGroupRows is defined and SPLIT_K == 1) else 1 %}{% set lastRowTileAtEnd = false %}{% set tileGroupColsValue = tileGroupCols | default(0) %}// Four subgroups cover 32xN as a 2x2 grid, or taller tiles as four row bands.{% set subgroupRows = 2 %}{% set subtileRows = 32 %}{% set subtileCols = 32 %}{% set aTilesPerSubgroup = 4 %}{% set bTilesPerSubgroup = 4 %}{% set workgroupThreads = 128 %}{% macro matrixAccumulators(matrixSoftware) %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %} var matC{{ m }}{{ n }}: {{ matrixType(matrixSoftware, "result", accScalar) }};{% endfor %}{% endfor %}{% endmacro %}
const IN_F: u32 = {{ inFeatures }}u;{% set useRegionStore = false %}{% set OUT_ROW = "OUT_F" %}const OUT_F: u32 = {{ outFeatures }}u;{% set kLoopEndValue = "IN_F" %}const TILE_COLS: u32 = {{ tileNValue }}u;const TILE_ROWS: u32 = {{ tileMValue }}u;const TILE_K: u32 = {{ tileKValue }}u;const SUB_COLS: u32 = {{ subtileCols }}u;const SUB_ROWS: u32 = {{ subtileRows }}u;const COLUMN_TILE_BASE: u32 = {{ columnTileBaseValue }}u;const ROW_TILE_BASE: u32 = {{ rowTileBaseValue }}u;{% if SPLIT_K > 1 %}const K_PER_SPLIT: u32 = {{ kPerSplit }}u;{% endif %}var<workgroup> tile_B: array<{{ operandScalar }}, {{ (2 if useDoubleBufferedB else 1) * tileNValue }} * {{ tileKValue }}>;fn loadSHMB(tile_base: u32, k_idx: u32, row: u32, c_idx: u32, bank_offset: u32) { // `w` holds one packed GGUF linear in its native block layout and `scales` its scale or metadata // words; `params.block_offset` is this matrix's first 32-element block. Each lane decodes half a // block, 16 consecutive K values of one weight row, to f32 with the source's own arithmetic: // the values the non-subgroup-matrix kernel multiplies by. let col: u32 = c_idx * 16u; for (var row_offset: u32 = 0u; row_offset < TILE_COLS; row_offset += {{ (workgroupThreads * 16 / tileKValue)|int }}u) { let b_row: u32 = row + row_offset; if (b_row < TILE_COLS) { let k: u32 = k_idx + col; let blk: u32 = params.block_offset + (tile_base + b_row) * (IN_F / 32u) + k / 32u; let blk_half: u32 = (k / 16u) & 1u; // MatMulNBits' 4-bit codes: byte j of a 32-code block holds element 2j in its low nibble and // 2j + 1 in its high one, so this half is the block's words 2 * blk_half and + 1; a scale // covers `packedScaleBlocks` consecutive blocks of a row. Value = d * (q - 8). let qb_p = w[blk];{% set scaleBlocks = packedScaleBlocks | default(1) %} let s_p = f32(scales[blk{{ (" / " ~ scaleBlocks ~ "u") if scaleBlocks > 1 else "" }}]);{% for i in range(2) %} let qw{{ i }}_p = select(qb_p.{{ "xy"[i] }}, qb_p.{{ "zw"[i] }}, blk_half == 1u); let lo{{ i }}_p = vec4<f32>(unpack4xU8(qw{{ i }}_p & 0x0F0F0F0Fu)) - 8.0; let hi{{ i }}_p = vec4<f32>(unpack4xU8((qw{{ i }}_p >> 4u) & 0x0F0F0F0Fu)) - 8.0; let hv{{ 2 * i }} = s_p * vec4<f32>(lo{{ i }}_p.x, hi{{ i }}_p.x, lo{{ i }}_p.y, hi{{ i }}_p.y); let hv{{ 2 * i + 1 }} = s_p * vec4<f32>(lo{{ i }}_p.z, hi{{ i }}_p.z, lo{{ i }}_p.w, hi{{ i }}_p.w);{% endfor %} let dst: u32 = bank_offset + b_row * TILE_K + col;{% for i in range(4) %} tile_B[dst + {{ 4 * i }}u] = hv{{ i }}.x; tile_B[dst + {{ 4 * i + 1 }}u] = hv{{ i }}.y; tile_B[dst + {{ 4 * i + 2 }}u] = hv{{ i }}.z; tile_B[dst + {{ 4 * i + 3 }}u] = hv{{ i }}.w;{% endfor %} } }}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}// The portable arm owns two result components per logical 32-invocation group.// Staging casts, 8-wide K steps, barriers and the epilogue match the// subgroup-matrix arm.var<private> matrixSoftwareLane: u32;
fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>, acc: vec2<f32>) -> vec2<f32> { var value = acc; for (var k = 0u; k < 8u; k += 1u) { value = fma(vec2<f32>(lhs[k]), rhs[k], value); } return value;}
{% macro matrixType(software, kind, scalar) %}{% if software %}{% if kind == "left" %}array<f32, 8>{% elif kind == "right" %}array<vec2<f32>, 8>{% else %}vec2<{{ scalar }}>{% endif %}{% else %}subgroup_matrix_{{ kind }}<{{ scalar }}, 8, 8>{% endif %}{% endmacro %}
{% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}{% if kind == "left" %}array<f32, 8>({% for k in range(8) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}(matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u{% else %}{{ k }}u * ({{ stride }}) + matrixSoftwareLane / 4u{% endif %}]){{ "," if k < 7 else "" }}{% endfor %}){% else %}array<vec2<f32>, 8>({% for k in range(8) %}vec2<f32>({% for h in range(2) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}{{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u{% else %}((matrixSoftwareLane % 4u) * 2u + {{ h }}u) * ({{ stride }}) + {{ k }}u{% endif %}]){{ "," if h == 0 else "" }}{% endfor %}){{ "," if k < 7 else "" }}{% endfor %}){% endif %}{% endif %}{% endmacro %}
{% macro matrixMma(software, scalar, lhs, rhs, acc) %}{% if not software %}subgroupMatrixMultiplyAccumulate({{ lhs }}, {{ rhs }}, {{ acc }}){% else %}vec2<{{ scalar }}>(matrixSoftwareMultiplyAccumulate({{ lhs }}, {{ rhs }}, vec2<f32>({{ acc }}))){% endif %}{% endmacro %}
{% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{ let matrixPointer = {{ pointer }}; let matrixValue = {{ value }};{% for h in range(2) %} (*matrixPointer)[({{ offset }}) + {{ {"row_major": "(matrixSoftwareLane / 4u) * (" ~ stride ~ ") + (matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u", "col_major": "((matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u) * (" ~ stride ~ ") + matrixSoftwareLane / 4u"}[major] }}] = matrixValue.{{ "x" if h == 0 else "y" }};{% endfor %}}{% endif %}{% endmacro %}
{% macro matrixKernelBody(matrixSoftware) %}
// 2D-folded M-tile (row) base: workgroup_id.z carries the high bits when the // row tile exceeds the per-dimension dispatch limit. // Reduces to workgroup_id.y when nwg.z == 1; the row_limit guard in storeOutput // (i32(M) - i32(a_global_base + ...)) drops the over-dispatched tail.{% if SPLIT_K > 1 %} // Split-K reuses z as the K-segment id, so the M-tile fold stays on y alone. let a_global_base: u32 = (ROW_TILE_BASE + workgroup_id.y) * TILE_ROWS; let split_id: u32 = workgroup_id.z;{% elif tileGroup > 1 %} let tile_linear: u32 = workgroup_id.x + workgroup_id.y * {{ tileGroupColsValue }}u; let tile_group: u32 = tile_linear / {{ tileGroup * tileGroupColsValue }}u; let group_first_row: u32 = tile_group * {{ tileGroup }}u; let group_rows: u32 = min(nwg.y - group_first_row, {{ tileGroup }}u); let in_group: u32 = tile_linear - tile_group * {{ tileGroup * tileGroupColsValue }}u; let a_global_base: u32 = {{ "min(" if lastRowTileAtEnd else "" }}(ROW_TILE_BASE + group_first_row + in_group % group_rows) * TILE_ROWS{{ ", params.M - TILE_ROWS)" if lastRowTileAtEnd else "" }};{% else %} let a_global_base: u32 = (ROW_TILE_BASE + workgroup_id.y + workgroup_id.z * nwg.y) * TILE_ROWS;{% endif %}{% if tileGroup > 1 %} let w_global_base: u32 = (COLUMN_TILE_BASE + in_group / group_rows) * TILE_COLS;{% else %} let w_global_base: u32 = (COLUMN_TILE_BASE + workgroup_id.x) * TILE_COLS;{% endif %}
let subtile_id: u32 = matrixRole; let subtile_idx: u32 = subtile_id / {{ subgroupRows }}u; let subtile_idy: u32 = subtile_id % {{ subgroupRows }}u; let base_A: u32 = subtile_idy * SUB_ROWS; let base_B: u32 = subtile_idx * SUB_COLS;
{{ matrixAccumulators(matrixSoftware) }} // Large aligned f32 tiles do not benefit from staging A: each row band is // consumed by exactly one subgroup. Load those matrices directly from x and // ping-pong only B, which is reused by all four subgroups. The barrier that // publishes the next B bank also proves the previous bank is no longer read, // reducing the steady-state schedule from two barriers per K tile to one. var b_bank: u32 = 0u;{% if SPLIT_K > 1 %} // This workgroup's K segment; the ping-pong runs within it. let k_begin: u32 = split_id * K_PER_SPLIT; let k_end: u32 = min(k_begin + K_PER_SPLIT, {{ kLoopEndValue }});{% endif %}{% set kFirst = "k_begin" if SPLIT_K > 1 else "0u" %}{% set kLast = "k_end" if SPLIT_K > 1 else kLoopEndValue %} loadSHMB(w_global_base, {{ kFirst }}, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, 0u); workgroupBarrier(); for (var kidx: u32 = {{ kFirst }}; kidx < {{ kLast }}; kidx += TILE_K) { let b_bank_offset = b_bank * TILE_COLS * TILE_K; for (var step: u32 = 0u; step < {{ "min(TILE_K, IN_F - kidx)" if packedKTail else "TILE_K" }}; step += {{ 32 if useBalancedAccumulation else 8 }}u) {{% set dynamicATiles = 4 %}{% set matrixAccumulator = matrixAccumulator | default("matC") %}{% set matrixStepOffset = matrixStepOffset | default(0) %}{% set matrixStep = "step" if matrixStepOffset == 0 else "(step + " ~ matrixStepOffset ~ "u)" %}{% set B_BANK = "b_bank_offset + " %}{% set matrixAStorage = matrixAStorage | default("x") %}{% set matrixAStride = matrixAStride | default("IN_F") %} // Direct storage guarantees a full aligned M/K tile, so subgroup-matrix // loads need no guarded workgroup staging. let matrix_a_offset = (a_global_base + base_A) * {{ matrixAStride }} + kidx + {{ matrixStep }};{% for m in range(dynamicATiles) %} var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ (matrixAStorage), ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * " ~ matrixAStride if m > 0 else "")), matrixAStride) }};{% endfor %}
let matrix_b_offset = {{ B_BANK }}subtile_idx * SUB_COLS * TILE_K + {{ matrixStep }};{% for n in range(bTilesPerSubgroup) %} var matB{{ n }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {{ matrixLoad(matrixSoftware, "right", operandScalar, "col_major", "&tile_B", "matrix_b_offset + " ~ (n * 8) ~ "u * TILE_K", "TILE_K") }};{% endfor %}
{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %} {{ matrixAccumulator }}{{ m }}{{ n }} = {{ matrixMma(matrixSoftware, accScalar, "matA" ~ (m), "matB" ~ (n), (matrixAccumulator) ~ (m) ~ (n)) }};{% endfor %}{% endfor %} } let next_kidx = kidx + TILE_K; if (next_kidx < {{ kLast }}) { let next_bank = 1u - b_bank; loadSHMB(w_global_base, next_kidx, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, next_bank * TILE_COLS * TILE_K); workgroupBarrier(); b_bank = next_bank; } }
let matrix_c_offset: u32 = {% if SPLIT_K > 1 %}split_id * params.M * OUT_F + {% endif %}(a_global_base + base_A) * {{ OUT_ROW }} + {{ "DST_COL + " if useRegionStore else "" }}w_global_base + base_B; // Aligned, no-bias tiles can store matrix results directly without the // scratch-backed scalar epilogue.{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixStore(matrixSoftware, "row_major", "&" ~ (OUT), "matrix_c_offset + " ~ (m * 8) ~ "u * " ~ OUT_ROW ~ " + " ~ (n * 8) ~ "u", "matC" ~ (m) ~ (n), OUT_ROW) }}{% endfor %}{% endfor %}
{% endmacro %}@compute @workgroup_size({{ workgroupThreads }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main( @builtin(workgroup_id) workgroup_id: vec3<u32>,{% if SPLIT_K == 1 %} @builtin(num_workgroups) nwg: vec3<u32>,{% endif %} @builtin(local_invocation_index) local_idx: u32, @builtin(subgroup_size) sg_size: u32) { let matrixRole = claimMatrixSubgroupRole(sg_size, 32u); let matrixAcceptedHere = matrixTopologyAccepted(local_idx, {{ workgroupThreads }}u / 32u); matrixSoftwareLane = local_idx % 32u; if (matrixAcceptedHere) { {{ matrixKernelBody(false) }} } else { let matrixRole = local_idx / 32u; {{ matrixKernelBody(true) }} }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{% set BIAS = registerBiasMode | default("none") %}{% set ROW_SCALE = splitRowScale | default(false) %}{% set OUT_F32 = splitOutputF32 | default(false) %}{%- macro result(component) -%}{{ "" if OUT_F32 else "f16" }}(params.alpha * values[{{ component }}]{% if ROW_SCALE %} * rowScale{% endif %}{% if BIAS != "none" %} + params.beta * f32(bias[{% if BIAS == "scalar" %}0u{% elif BIAS == "row" %}col + {{ component }}u{% elif BIAS == "column" %}row{% else %}row * N + col + {{ component }}u{% endif %}]){% endif %}){%- endmacro -%}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %} // 2D-folded flat index: gid.y carries the high bits past the dispatch's // per-axis workgroup fold width. let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }}; if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}{{ env.wgsl.resourceDeclarations }}const N: u32 = {{ N }}u;const SPLITS: u32 = {{ splitSlices }}u;const WG: u32 = 128u;@compute @workgroup_size(128, 1, 1)fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d("WG", "index", "params.M * N / 8u") }}{% if BIAS == "column" or BIAS == "matrix" or ROW_SCALE %} let row = index / (N / 8u);{% endif %}{% if BIAS == "row" or BIAS == "matrix" %} let col = (index % (N / 8u)) * 8u;{% endif %} var low = vec4<f32>(0.0); var high = vec4<f32>(0.0); // Each slice holds the rows rounded up to whole 16-row fragments. let sliceWords = (params.M + 15u) / 16u * 16u * N / 4u; for (var slice = 0u; slice < SPLITS; slice += 1u) { let source = slice * {{ "sliceWords" }} + index * 2u; low = low + partials[source]; high = high + partials[source + 1u]; } let values = array<f32, 8>(low.x, low.y, low.z, low.w, high.x, high.y, high.z, high.w);{% if ROW_SCALE %} let rowScale = row_scales[row];{% endif %}{% if OUT_F32 %} y[index * 2u] = vec4<f32>({{ result(0) }}, {{ result(1) }}, {{ result(2) }}, {{ result(3) }}); y[index * 2u + 1u] = vec4<f32>({{ result(4) }}, {{ result(5) }}, {{ result(6) }}, {{ result(7) }});{% else %} y[index] = vec4<u32>({% for pair in range(4) %} bitcast<u32>(vec2<f16>({{ result(pair * 2) }}, {{ result(pair * 2 + 1) }})){{ "," if pair != 3 else "" }}{% endfor %} );{% endif %}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114enable subgroups;{{ env.wgsl.resourceDeclarations }}{% macro active_lanes(lane, prefix="active") %} let {{ prefix }}Mask = subgroupBallot(true); let {{ prefix }}Word = {{ lane }} / 32u; let {{ prefix }}Lower = (1u << ({{ lane }} % 32u)) - 1u; let {{ prefix }}Count = max(countOneBits({{ prefix }}Mask.x) + countOneBits({{ prefix }}Mask.y) + countOneBits({{ prefix }}Mask.z) + countOneBits({{ prefix }}Mask.w), 1u); var {{ prefix }}Rank = countOneBits({{ prefix }}Mask[{{ prefix }}Word] & {{ prefix }}Lower); for (var word = 0u; word < {{ prefix }}Word; word++) { {{ prefix }}Rank += countOneBits({{ prefix }}Mask[word]); }{% endmacro %}{% set sgClusterPaths = ["general", "full"] %}{% set sgClusterBuiltins = ", @builtin(subgroup_invocation_id) sg_lid: u32, @builtin(subgroup_size) sg_size: u32, @builtin(subgroup_id) sg_id: u32, @builtin(num_subgroups) sg_count: u32" %}{% macro sg_cluster_open(path, clusters, totals) %}{% if path == "general" %} if (sg_size != 32u || sg_count != {{ clusters }}) { if (sg_id == 0u) {{{ active_lanes("sg_lid") }} let lane = activeRank; var sgTotals: array<f32, {{ totals }}>; for (var cluster = 0u; cluster < {{ clusters }}; cluster = cluster + 1u) {{% else %} } else { let cluster = sg_id; let lane = sg_lid & 31u;{% endif %}{% endmacro %}{% macro sg_cluster_store(clusters) %} } for (var cluster = 0u; cluster < {{ clusters }}; cluster = cluster + 1u) {{% endmacro %}{% macro sg_cluster_close(path) %}{% if path == "general" %} } }{% else %} }{% endif %}{% endmacro %}{% set comps = ["x", "y", "z", "w"] %}// com.microsoft.MatMulNBits decode GEMV in subgroup-owned 32-lane clusters.const CLUSTERS: u32 = {{ clusters }}u;const REG_ROWS: u32 = {{ regRows }}u;const VEC_PER_COL: u32 = {{ vecPerCol }}u;const VEC_PER_BLOCK: u32 = {{ vecPerBlock }}u;const VEC4_PER_VEC: u32 = {{ codesPerVec4 }}u;
@compute @workgroup_size({{ 32 * clusters }})fn main(@builtin(workgroup_id) wid: vec3<u32>{{ sgClusterBuiltins }}) {{% for sgPath in sgClusterPaths %}{{ sg_cluster_open(sgPath, "CLUSTERS", clusters * regRows) }} let col0 = (wid.x * CLUSTERS + cluster) * REG_ROWS;{% for r in range(regRows) %} var acc{{ r }} = 0.0; let n{{ r }} = min(col0 + {{ r }}u, params.N - 1u);{% endfor %} for (var v = lane; v < VEC_PER_COL; v = v + {{ "activeCount" if sgPath == "general" else "32u" }}) { let block = v / VEC_PER_BLOCK; let abase = v * VEC4_PER_VEC;{% for q in range(codesPerVec4) %} let av{{ q }} = vec4<f32>(a[abase + {{ q }}u]);{% endfor %}{% for q in range(codesPerVec4) %}{% for c in range(4) %} let a{{ q * 4 + c }} = av{{ q }}.{{ comps[c] }};{% endfor %}{% endfor %} let asum = {% for j in range(codesPerVec) %}{{ " + " if j > 0 else "" }}a{{ j }}{% endfor %};{% for r in range(regRows) %} { let words = b[n{{ r }} * VEC_PER_COL + v]; let scale = f32(scales[n{{ r }} * params.kBlocks + block]); var dot = 0.0;{% for w in range(vecWords) %}{% set word = "words." ~ comps[w] %}{% for h in range(codesPerWord) %} dot = dot + a{{ w * codesPerWord + h }} * f32(({{ word }} >> {{ h * bits }}u) & {{ codeMask }}u);{% endfor %}{% endfor %} acc{{ r }} = acc{{ r }} + (dot - {{ defaultZero }} * asum) * scale; }{% endfor %} }{% set sgTotalsSlot = "cluster * 2u + " %}{% set accPrefix = accPrefix | default("acc") %}{% set totalPrefix = totalPrefix | default("total") %}{% if (sgPath | default("")) == "general" %}{% for r in range(regRows) %} sgTotals[{{ sgTotalsSlot | default("") }}{{ r }}u] = subgroupAdd({{ accPrefix }}{{ r }});{% endfor %}{% else %}{% for r in range(regRows) %} let {{ totalPrefix }}{{ r }} = subgroupAdd({{ accPrefix }}{{ r }});{% endfor %}{% endif %}{% if sgPath == "general" %}{{ sg_cluster_store("CLUSTERS") }} let col0 = (wid.x * CLUSTERS + cluster) * REG_ROWS;{% for r in range(regRows) %} let total{{ r }} = sgTotals[cluster * {{ regRows }}u + {{ r }}u];{% endfor %}{% endif %} if ({{ "activeRank" if sgPath == "general" else "lane" }} == 0u) {{% for r in range(regRows) %} if (col0 + {{ r }}u < params.N) { y[col0 + {{ r }}u] = {{ outputScalar }}(total{{ r }}); }{% endfor %} }{{ sg_cluster_close(sgPath) }}{% endfor %}}12345678910111213141516171819202127 unmodified lines49505152535455565758596061626336 unmodified lines1001011021031041051065 unmodified lines112113114115116117118119120121122123124125126127128129130131132133134135136{% if useSubgroups %}enable subgroups;{% endif %}{{ env.wgsl.resourceDeclarations }}// com.microsoft.MatMulNBits decode GEMV: one activation row against the packed// weight blob. A workgroup owns gemvNCols output columns; its lanes stride the// reduction axis in whole VECTORS of the blob -- a vec4<u32> of sixteen packed// bytes when the quantization block is a multiple of sixteen bytes, else one// u32 word -- so every weight byte arrives in the widest load the layout admits.// A vector never straddles a block, so one scale (and zero point) covers every// code it carries.//// Per vector and column the lane accumulates dot(a, codes) over the vector's// codes and applies the block's (scale, zero) once:// sum_j a_j (c_j - z) s == s (dot(a, c) - z sum_j a_j)// so the per-code work is a shift, a mask, a convert and one fma, and the// activation sum is shared by every column. Partials fold through workgroup// memory, so no subgroup feature is required.{% set nCols = gemvNCols %}{% set groups = 2 if nCols == 8 else 1 %}{% set comps = ["x", "y", "z", "w"] %}27 unmodified lines@compute @workgroup_size({{ workgroupSize }}, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if useSubgroups %},@builtin(subgroup_invocation_id) sgLane: u32,@builtin(subgroup_size) sgSize: u32{% endif %}) {let tid = lid.x;// 2D-folded dispatch: wid.y carries the high bits past the per-dimension// limit (vocab-sized N). The fold over-dispatches, so the tail workgroups// return before any barrier.let col_base = (wid.x + wid.y * {{ DISPATCH_FOLD_WIDTH }}u) * N_COLS;if (col_base >= params.N) {return;}36 unmodified lineslet zero = zero_point({% if hasZero %}n, block{% endif %});var dot = 0.0;{% for w in range(vecWords) %}{% set word = ("words." ~ comps[w]) if vecWords == 4 else "words" %}{% for h in range(codesPerWord) %}dot = dot + a{{ w * codesPerWord + h }} * f32(({{ word }} >> {{ h * bits }}u) & {{ codeMask }}u);{% endfor %}5 unmodified lines}{% if useSubgroups %}// Subgroup fold: one collective per accumulator, then the WG / subgroup-size// per-subgroup partials fold once through workgroup memory. The lanes of a// subgroup are contiguous in local_invocation_id, so tid / sgSize names it.// Every lane reaches this point (the only early return is workgroup-uniform),// so the collective runs in uniform control flow.{% for g in range(groups) %}{% set sfx = "" if groups == 1 else g %}let sgSum{{ sfx }} = subgroupAdd(acc{{ sfx }});{% endfor %}if (sgLane == 0u) {{% for g in range(groups) %}{% set sfx = "" if groups == 1 else g %}partials{{ sfx }}[tid / sgSize] = sgSum{{ sfx }};{% endfor %}}workgroupBarrier();if (tid == 0u) {let subgroupCount = WG / sgSize;{% for g in range(groups) %}{% set sfx = "" if groups == 1 else g %}var total{{ sfx }} = partials{{ sfx }}[0];12345678910111213141516171819202127 unmodified lines49505152535455565758596061626336 unmodified lines1001011021031041051065 unmodified lines112113114115116117118119120121122123124125126127128129130131132133134135136{% set COMPACT_SUBGROUP = useSubgroups and compactSubgroupPartials | default(false) %}{% if useSubgroups %}enable subgroups;{% endif %}{{ env.wgsl.resourceDeclarations }}// Packed MatMulNBits decode GEMV: one activation row against the packed// weight blob. A workgroup owns gemvNCols output columns; its lanes stride the// reduction axis in whole VECTORS of the blob -- one, two or four packed u32// words -- and read each vector's activations as consecutive vec4s. A vector// never straddles a block, so one scale (and zero point) covers every code it// carries.//// Per vector and column the lane accumulates dot(a, codes) over the vector's// codes and applies the block's (scale, zero) once:// sum_j a_j (c_j - z) s == s (dot(a, c) - z sum_j a_j)// so the per-code work is a shift, a mask, a convert and one fma, and the// activation sum is shared by every column. Partials fold through workgroup// memory; where subgroups are available each subgroup first reduces its lanes with subgroupAdd.{% set nCols = gemvNCols %}{% set groups = 2 if nCols == 8 else 1 %}{% set comps = ["x", "y", "z", "w"] %}27 unmodified lines@compute @workgroup_size({{ workgroupSize }}, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>,@builtin(num_workgroups) nwg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if COMPACT_SUBGROUP %},@builtin(subgroup_id) subgroupId: u32,@builtin(num_subgroups) numSubgroups: u32{% endif %}) {let tid = lid.x;// Folded grids balance x across their y rows. The actual x extent supplies// the linear stride; only the final padded column workgroups return early.let col_base = (wid.x + wid.y * nwg.x) * N_COLS;if (col_base >= params.N) {return;}36 unmodified lineslet zero = zero_point({% if hasZero %}n, block{% endif %});var dot = 0.0;{% for w in range(vecWords) %}{% set word = ("words." ~ comps[w]) if vecWords > 1 else "words" %}{% for h in range(codesPerWord) %}dot = dot + a{{ w * codesPerWord + h }} * f32(({{ word }} >> {{ h * bits }}u) & {{ codeMask }}u);{% endfor %}5 unmodified lines}{% if useSubgroups %}// Subgroup IDs compact elected totals without assuming a lane mapping.// Other language tiers publish into the full local-invocation bank.{% for g in range(groups) %}{% set sfx = "" if groups == 1 else g %}let sgSum{{ sfx }} = subgroupAdd(acc{{ sfx }});{% endfor %}let elected = subgroupElect();{% for g in range(groups) %}{% set sfx = "" if groups == 1 else g %}{% if COMPACT_SUBGROUP %}if (elected) { partials{{ sfx }}[subgroupId] = sgSum{{ sfx }}; }{% else %}partials{{ sfx }}[tid] = select(vec4<f32>(0.0), sgSum{{ sfx }}, elected);{% endif %}{% endfor %}workgroupBarrier();if (tid == 0u) {let subgroupCount = {{ "numSubgroups" if COMPACT_SUBGROUP else "WG" }};{% for g in range(groups) %}{% set sfx = "" if groups == 1 else g %}var total{{ sfx }} = partials{{ sfx }}[0];
37 unmodified lines38394041424339 unmodified lines83848586878889909137 unmodified linesvar acc: array<f32, 16u>;for (var t = 0u; t < 16u; t = t + 1u) { acc[t] = 0.0; }let numTiles = K / 32u;for (var kt = 0u; kt < numTiles; kt = kt + 1u) {let kBase = kt * 32u;39 unmodified lineslet sa = tAscale[ar];for (var j = 0u; j < 4u; j = j + 1u) {let bc = bCol + j;var d = 0i;for (var w = 0u; w < 8u; w = w + 1u) { d = d + dot4_packed(aw[w], tB[bc][w]); }acc[i * 4u + j] = acc[i * 4u + j] + f32(d) * sa * tBscale[bc];}}workgroupBarrier();37 unmodified lines38394041424344454639 unmodified lines868788899091929394959697989910010110210337 unmodified linesvar acc: array<f32, 16u>;for (var t = 0u; t < 16u; t = t + 1u) { acc[t] = 0.0; }{% if dp4aScaleParts > 1 %}var block_acc: array<i32, 16>;{% endif %}let numTiles = K / 32u;for (var kt = 0u; kt < numTiles; kt = kt + 1u) {let kBase = kt * 32u;39 unmodified lineslet sa = tAscale[ar];for (var j = 0u; j < 4u; j = j + 1u) {let bc = bCol + j;var d = {{ "block_acc[i * 4u + j]" if dp4aScaleParts > 1 else "0i" }};for (var w = 0u; w < 8u; w = w + 1u) { d = d + dot4_packed(aw[w], tB[bc][w]); }{% if dp4aScaleParts > 1 %}if ((kt + 1u) % {{ dp4aScaleParts|int }}u == 0u) {acc[i * 4u + j] = acc[i * 4u + j] + f32(d) * sa * tBscale[bc];block_acc[i * 4u + j] = 0i;} else {block_acc[i * 4u + j] = d;}{% else %}acc[i * 4u + j] = acc[i * 4u + j] + f32(d) * sa * tBscale[bc];{% endif %}}}workgroupBarrier();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282{%- macro registerPackedBPrelude() -%}fn q4_split_word(column: u32, reduction: u32) -> vec4<u32> { let k = reduction % {{ q4K }}u; let block = column * {{ kBlocks }}u + k / {{ blockSize }}u; let codes = vec4<u32>(b[column * {{ (q4K / 8) | int }}u + k / 8u]); let scale = scales[block]; let zero = {% if hasZero %}zero_points[block]{% else %}8.0{% endif %}; let even = (vec4<f32>((codes >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(15u)) - zero) * scale; let odd = (vec4<f32>((codes >> vec4<u32>(4u, 12u, 20u, 28u)) & vec4<u32>(15u)) - zero) * scale; // Clearing the low 13 mantissa bits leaves a value a half holds exactly. let evenHigh = bitcast<vec4<f32>>(bitcast<vec4<u32>>(even) & vec4<u32>(0xffffe000u)); let oddHigh = bitcast<vec4<f32>>(bitcast<vec4<u32>>(odd) & vec4<u32>(0xffffe000u)); let low = reduction / {{ q4K }}u == 1u; let e = select(evenHigh, even - evenHigh, low); let o = select(oddHigh, odd - oddHigh, low); return vec4<u32>( bitcast<u32>(vec2<f16>(f16(e.x), f16(o.x))), bitcast<u32>(vec2<f16>(f16(e.y), f16(o.y))), bitcast<u32>(vec2<f16>(f16(e.z), f16(o.z))), bitcast<u32>(vec2<f16>(f16(e.w), f16(o.w))));}{%- endmacro -%}{%- macro registerLoadPackedB(column, reduction) -%}q4_split_word({{ column }}, {{ reduction }}){%- endmacro -%}{% set RESULT_SCRATCH_WORDS = 256 %}{%- set PAIRED_SWIGLU = false -%}{%- set TA = false -%}{%- set TB = true -%}{%- set BM = registerTileM -%}{%- set BN = registerTileN -%}{%- set BK = registerTileK -%}{%- set PAD = registerSharedPad | default(0) -%}{%- set FR = (BM / 32) | int -%}{%- set FC = (BN / 32) | int -%}{%- set ACOLS = BM if TA else BK -%}{%- set AROWS = BK if TA else BM -%}{%- set ASTRIDE = ((ACOLS + PAD) / 8) | int -%}{%- set BSTRIDE = (((BK if TB else BN) + PAD) / 8) | int -%}{%- set AWORDS = ((AROWS * (ACOLS + PAD)) / 8) | int -%}{%- set BWORDS = (((BN if TB else BK) * ((BK if TB else BN) + PAD)) / 8) | int -%}{%- set ASIZE = max(AWORDS, RESULT_SCRATCH_WORDS) -%}{%- set OUT_SLOTS = ((BM * BN) / 8 / 128) | int -%}{%- set SPLIT_K = true -%}{%- set SPLIT_COUNT = registerSplitSlices | default(1) -%}{%- set SPLIT_PAD = true -%}{%- macro coordinates(name) -%}{% if name == "a" %} let row = rowBase + flat / {{ (BK / 8) | int }}u; let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;{% else %} let col = colBase + flat / {{ (BK / 8) | int }}u; let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;{% endif %}{%- endmacro -%}{%- macro guard(name) -%}{%- if name == "a" -%}row < M && k + 7u < K{%- else -%}col < N && k + 7u < K{%- endif -%}{%- endmacro -%}{%- macro address(name) -%}{%- if name == "a" -%}({{ "k * M + row" if TA else "row * K + k" }}) / 8u{%- else -%}({{ "col * K + k" if TB else "k * N + col" }}) / 8u{%- endif -%}{%- endmacro -%}{%- macro shared_index(name) -%}{%- set PAYLOAD = ((ACOLS if name == "a" else BK if TB else BN) / 8) | int -%}{%- set STRIDE = ASTRIDE if name == "a" else BSTRIDE -%}(flat / {{ PAYLOAD }}u) * {{ STRIDE }}u + flat % {{ PAYLOAD }}u{%- endmacro -%}{%- macro load_left_fragment(r, step) %} let left{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>( &tileA, subgroupRow * {{ ASTRIDE }}u + {{ r * 16 * ASTRIDE + (step / 8) | int }}u, {{ ASTRIDE }}u);{%- endmacro -%}{%- macro load_right_fragment(c, step) %} let right{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, col_major>( &tileB, subgroupCol * {{ BSTRIDE }}u + {{ c * 16 * BSTRIDE + (step / 8) | int }}u, {{ BSTRIDE }}u);{%- endmacro -%}{%- macro multiply_fragment(r, c) %} acc{{ r }}_{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ r }}, right{{ c }}, acc{{ r }}_{{ c }});{%- endmacro -%}enable subgroups;enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{% if registerPackedBPrelude is defined %}{{ registerPackedBPrelude() }}{% endif %}{{ env.wgsl.resourceDeclarations }}const N: u32 = {{ N }}u;const K: u32 = {{ K }}u;const TILE_M: u32 = {{ BM }}u;const TILE_N: u32 = {{ BN }}u;const TILE_K: u32 = {{ BK }}u;const K_STAGES: u32 = {{ ceilDiv(K, BK) }}u;const SPLITS: u32 = {{ SPLIT_COUNT }}u;var<workgroup> tileA: array<vec4<u32>, {{ ASIZE }}>;var<workgroup> tileB: array<vec4<u32>, {{ BWORDS }}>;
fn loadTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) { let M = params.M;{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %} for (var flat = tid; flat < {{ WORDS }}u; flat += 128u) {{{ coordinates(name) }} var value = vec4<u32>(0u);{% if name == "b" and registerLoadPackedB is defined %} if ({{ guard(name) }}) { value = {{ registerLoadPackedB("col", "k") }}; }{% else %} if ({{ guard(name) }}) { value = {{ name }}[{{ address(name) }}]; }{% endif %} tile{{ "A" if name == "a" else "B" }}[{{ shared_index(name) }}] = value; }{% endfor %}}
struct PrefetchedTiles { a: array<vec4<u32>, {{ ((BM * BK / 8 + 127) / 128) | int }}>, b: array<vec4<u32>, {{ ((BK * (2 * BN if PAIRED_SWIGLU else BN) / 8 + 127) / 128) | int }}>,};fn prefetchTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) -> PrefetchedTiles { let M = params.M; var values: PrefetchedTiles;{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}{% for slot in range(((WORDS + 127) / 128) | int) %} { let flat = tid + {{ slot * 128 }}u; if (flat < {{ WORDS }}u) {{{ coordinates(name) }}{% if name == "b" and registerLoadPackedB is defined %} if ({{ guard(name) }}) { values.b[{{ slot }}] = {{ registerLoadPackedB("col", "k") }}; }{% else %} if ({{ guard(name) }}) { values.{{ name }}[{{ slot }}] = {{ name }}[{{ address(name) }}]; }{% endif %} } }{% endfor %}{% endfor %} return values;}fn stagePrefetchedTiles(values: PrefetchedTiles, tid: u32) {{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}{% for slot in range(((WORDS + 127) / 128) | int) %} { let flat = tid + {{ slot * 128 }}u; if (flat < {{ WORDS }}u) { tile{{ "A" if name == "a" else "B" }}[{{ shared_index(name) }}] = values.{{ name }}[{{ slot }}]; } }{% endfor %}{% endfor %}}
fn readA(row: u32, k: u32) -> f32 { let word = tileA[row * {{ ASTRIDE }}u + k / 8u]; return f32(bitcast<vec2<f16>>(word[(k % 8u) / 2u])[k % 2u]);}fn readB(k: u32, col: u32) -> f32 { let contiguous = {{ "k" if TB else "col" }}; let word = tileB[{{ "col" if TB else "k" }} * {{ BSTRIDE }}u + contiguous / 8u]; return f32(bitcast<vec2<f16>>(word[(contiguous % 8u) / 2u])[contiguous % 2u]);}
// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}@compute @workgroup_size(128, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32) { let M = params.M; let rowBase = wid.y * TILE_M; let colBase = wid.x * TILE_N; let beginK = (wid.z * K_STAGES / SPLITS) * TILE_K; let endK = ((wid.z + 1u) * K_STAGES / SPLITS) * TILE_K; // Partial slices hold the rows rounded up to whole fragments, so a fragment that // straddles the last row stores whole; the combine pass reads only real rows. let sliceRows = (M + 15u) / 16u * 16u; let role = min(claimMatrixSubgroupRole(width, 32u), 3u); let nativeTopology = matrixTopologyAccepted(tid, 4u); if (nativeTopology) { let subgroupRow = (role / 2u) * {{ FR * 16 }}u; let subgroupCol = (role % 2u) * {{ FC * 16 }}u;{% for r in range(FR) %}{% for c in range(FC) %} var acc{{ r }}_{{ c }}: subgroup_matrix_result<f32, 16, 16>;{% endfor %}{% endfor %} var nextTiles = prefetchTiles(rowBase, colBase, {{ "beginK" if SPLIT_K else "0u" }}, tid); for (var kk = {{ "beginK" if SPLIT_K else "0u" }}; kk < {{ "endK" if SPLIT_K else "K" }}; kk += TILE_K) { stagePrefetchedTiles(nextTiles, tid); workgroupBarrier(); if (kk + TILE_K < {{ "endK" if SPLIT_K else "K" }}) { nextTiles = prefetchTiles(rowBase, colBase, kk + TILE_K, tid); }{% for step in range(0, BK, 16) %} {{% for r in range(FR) %}{{ load_left_fragment(r, step) }}{% endfor %}{% for c in range(FC) %}{{ load_right_fragment(c, step) }}{% endfor %}{% for r in range(FR) %}{% for c in range(FC) %}{{ multiply_fragment(r, c) }}{% endfor %}{% endfor %} }{% endfor %} workgroupBarrier(); }{% for r in range(FR) %}{% for c in range(FC) %} { let row = rowBase + subgroupRow + {{ r * 16 }}u; let col = colBase + subgroupCol + {{ c * 16 }}u; if ({{ "row < M" if SPLIT_PAD else "row + 15u < M" }} && col + 15u < N) { subgroupMatrixStore<row_major>(&y, (wid.z * {{ "sliceRows" if SPLIT_PAD else "M" }} * N + row * N + col) / 4u, acc{{ r }}_{{ c }}, N / 4u); } }{% endfor %}{% endfor %} } else { for (var slot = 0u; slot < {{ OUT_SLOTS }}u; slot += 1u) { let flat = tid + slot * 128u; let tileRow = flat / {{ (BN / 8) | int }}u; let tileCol = (flat % {{ (BN / 8) | int }}u) * 8u; var acc: array<f32, 8>;{% for component in range(8) %} acc[{{ component }}] = 0.0;{% endfor %} for (var kk = {{ "beginK" if SPLIT_K else "0u" }}; kk < {{ "endK" if SPLIT_K else "K" }}; kk += TILE_K) { loadTiles(rowBase, colBase, kk, tid); workgroupBarrier(); for (var k = 0u; k < TILE_K; k += 1u) { let left = readA(tileRow, k); for (var component = 0u; component < 8u; component += 1u) { acc[component] = fma(left, readB(k, tileCol + component), acc[component]); } } workgroupBarrier(); } let row = rowBase + tileRow; let col = colBase + tileCol; if (row < M && col + 7u < N) { let values = array<f32, 8>({% for component in range(8) %} acc[{{ component }}u]{{ "," if component != 7 else "" }}{% endfor %} ); let outputWord = (wid.z * {{ "sliceRows" if SPLIT_PAD else "M" }} * N + row * N + col) / 4u; y[outputWord] = bitcast<vec4<u32>>(vec4<f32>(values[0], values[1], values[2], values[3])); y[outputWord + 1u] = bitcast<vec4<u32>>(vec4<f32>(values[4], values[5], values[6], values[7])); } } }}12345678910111213141534 unmodified lines505152535455565758596061626364656667686970717273747576777828 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511523 unmodified lines1561571581591601611621631641651665 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241{% set subgroupPin = tileSubgroupPin if tileSubgroupPin is defined else 0 %}{% if subgroupPin %}enable subgroup_size_control;{% endif %}{{ env.wgsl.resourceDeclarations }}// com.microsoft.MatMulNBits q4/q8 prefill, no-subgroup-matrix tier — register-blocked.// Y[M,N] = A[M,K] @ W[K,N] (+ bias), W[k,n] = (q(n,block,offset) - zero) * scale// Dequantizes into a shared [BN][BK/4] tile with device-selected register// blocking. Both tiles are indexed by their own output axis and group four K// values per vector word, so the micro-tile accumulates through dot() and the// column-owning loader writes whole words instead of a BN-strided column.// The full geometry computes a 4x4 micro-tile over a 64x64 output tile. A// device-selected 32x8 workgroup can use an 8x2 micro-tile on that same output// tile. The portable geometry computes 2x4 over 32x64 to bound the accumulator34 unmodified lines{% set aReadEnd = ")" if usesF16 else "" %}const K_VECS: u32 = BK / 4u;var<workgroup> tileA: array<array<vec4<{{ aTile }}>, K_VECS>, BM>; // [BM][BK/4]var<workgroup> tileB: array<array<vec4<f32>, K_VECS>, BN>; // [BN][BK/4]{% if not alignedBlockLoads %}// Generic unpack used only when a quant block does not contain a whole BK tile.{% macro matmul_nbits_packed_code(fn="packed_weight", buffer="b", kBlocks="params.kBlocks", blobSize="params.blobSize", bits=4) %}fn {{ fn }}(n: u32, block: u32, offset: u32) -> u32 {{% if bits == 2 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 2u);let shift = (byte_index & 3u) * 8u + (offset & 3u) * 2u;return ({{ buffer }}[byte_index >> 2u] >> shift) & 3u;{% elif bits == 4 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 1u);let shift = (byte_index & 3u) * 8u + (offset & 1u) * 4u;return ({{ buffer }}[byte_index >> 2u] >> shift) & 15u;{% else %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + offset;return ({{ buffer }}[byte_index >> 2u] >> ((byte_index & 3u) * 8u)) & 255u;{% endif %}}{% endmacro %}{{ matmul_nbits_packed_code(bits=bits, kBlocks="KBLOCKS", blobSize="BLOB_SIZE") }}{% endif %}{% macro zero_of(blockExpr) %}{% if hasZero %}f32(zero_points[bn * KBLOCKS + {{ blockExpr }}]){% else %}{{ defaultZero }}{% endif %}{% endmacro %}@compute @workgroup_size({{ wgX }}, {{ wgY }}, 1){{ (" @subgroup_size(" ~ subgroupPin ~ ")") if subgroupPin else "" }}fn main(@builtin(workgroup_id) wg: vec3<u32>,28 unmodified linesvar aWord = vec4<{{ aTile }}>({{ aTile }}(0.0));{% if aVec4Loads is defined and aVec4Loads %}// K is a multiple of four, so every staged word is one aligned vector load.if (am < M) {aWord = vec4<{{ aTile }}>(a[(am * K + ak) / 4u]);}{% else %}if (am < M) {{% for component in range(4) %}if (ak + {{ component }}u < K) { aWord[{{ component }}u] = {{ aTile }}(a[am * K + ak + {{ component }}u]); }{% endfor %}}{% endif %}tileA[ar][ac4] = aWord;}{% if alignedBlockLoads %}{% if q2ChunkLoads is defined and q2ChunkLoads and bits == 2 and bk % 16 == 0 %}// A 32-bit word carries sixteen adjacent 2-bit codes. Decode it once per// column and quant chunk, reusing the scale and zero for four staged vec4s.for (var idx: u32 = li; idx < BN * (BK / 16u); idx = idx + WG_THREADS) {let chunksPerCol = BK / 16u;let bc = idx / chunksPerCol;let chunk = idx % chunksPerCol;let bn = nBase + bc;let baseK = kBase + chunk * 16u;var packed: u32 = 0u;var scale: f32 = 0.0;var zero: f32 = 0.0;if (bn < N && baseK < K) {let block = baseK / BLOCK_SIZE;let offset = baseK % BLOCK_SIZE;let byteIndex = (bn * KBLOCKS + block) * BLOB_SIZE + (offset >> 2u);packed = b[byteIndex >> 2u];scale = f32(scales[bn * KBLOCKS + block]);zero = {{ zero_of("block") }};}{% for vec in range(4) %}let word{{ vec }} = vec4<f32>({% for component in range(4) %}(f32((packed >> {{ 2 * (vec * 4 + component) }}u) & 3u) - zero) * scale{% if not loop.last %},{% endif %}{% endfor %});tileB[bc][chunk * 4u + {{ vec }}u] = word{{ vec }};{% endfor %}}{% else %}3 unmodified lines// K-adjacent codes of a vector word are byte-contiguous from a 4-aligned// offset, so they always come out of ONE packed word: one load per vector.for (var idx: u32 = li; idx < BN * K_VECS; idx = idx + WG_THREADS) {let bc = idx / K_VECS;let kv = idx % K_VECS;let bn = nBase + bc;var word = vec4<f32>(0.0);if (bn < N && kBase < K) {let block = kBase / BLOCK_SIZE;let offset0 = kBase % BLOCK_SIZE;let scale = f32(scales[bn * KBLOCKS + block]);5 unmodified lineslet byte_index = blob_base + ((offset0 + kk) >> 2u);let packed = b[byte_index >> 2u] >> ((byte_index & 3u) * 8u);{% for component in range(4) %}if (kBase + kk + {{ component }}u < K) {word[{{ component }}u] = (f32((packed >> {{ component * 2 }}u) & 3u) - zero) * scale;}{% endfor %}{% elif bits == 4 %}// Two bytes carry the four K-adjacent codes of one vector word.let byte_index = blob_base + ((offset0 + kk) >> 1u);let packed = b[byte_index >> 2u] >> ((byte_index & 3u) * 8u);{% for component in range(4) %}if (kBase + kk + {{ component }}u < K) {word[{{ component }}u] = (f32((packed >> {{ component * 4 }}u) & 15u) - zero) * scale;}{% endfor %}{% else %}let byte_index = blob_base + offset0 + kk;let packed = b[byte_index >> 2u];{% for component in range(4) %}if (kBase + kk + {{ component }}u < K) {word[{{ component }}u] = (f32((packed >> {{ component * 8 }}u) & 255u) - zero) * scale;}{% endfor %}{% endif %}}tileB[bc][kv] = word;}{% endif %}{% else %}// Quant blocks that do not contain a whole BK tile use the element-wise loader.for (var idx: u32 = li; idx < BN * K_VECS; idx = idx + WG_THREADS) {let bc = idx / K_VECS;let br4 = idx % K_VECS;let bk = kBase + br4 * 4u;let bn = nBase + bc;var word = vec4<f32>(0.0);if (bn < N) {{% for component in range(4) %}if (bk + {{ component }}u < K) {let block{{ component }} = (bk + {{ component }}u) / BLOCK_SIZE;let offset{{ component }} = (bk + {{ component }}u) % BLOCK_SIZE;let scale{{ component }} = f32(scales[bn * KBLOCKS + block{{ component }}]);let zero{{ component }} = {{ zero_of("block" ~ component) }};word[{{ component }}u] = (f32(packed_weight(bn, block{{ component }}, offset{{ component }})) - zero{{ component }}) * scale{{ component }};}{% endfor %}}tileB[bc][br4] = word;}{% endif %}workgroupBarrier();let aRow = lid.y * TM;let bCol = lid.x * TN;for (var kv: u32 = 0u; kv < K_VECS; kv = kv + 1u) {{% for i in range(threadRows) %}let av{{ i }} = {{ aRead }}tileA[aRow + {{ i }}u][kv]{{ aReadEnd }};{% endfor %}{% for j in range(threadCols) %}let bv{{ j }} = tileB[bCol + {{ j }}u][kv];{% endfor %}{% for i in range(threadRows) %}{% for j in range(threadCols) %}acc{{ i }}{{ j }} = acc{{ i }}{{ j }} + dot(av{{ i }}, bv{{ j }});{% endfor %}{% endfor %}}workgroupBarrier();}12345678910111213141516171834 unmodified lines535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911028 unmodified lines1391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961973 unmodified lines2012022032042052062072082092102112122132142152165 unmodified lines222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298{% set subgroupPin = tileSubgroupPin if tileSubgroupPin is defined else 0 %}{% if subgroupPin %}enable subgroups;enable subgroup_size_control;{% endif %}{{ env.wgsl.resourceDeclarations }}// com.microsoft.MatMulNBits q4/q8 prefill for devices without subgroup matrices, register-blocked.// Y[M,N] = A[M,K] @ W[K,N] (+ bias), W[k,n] = (q(n,block,offset) - zero) * scale// Dequantizes into a shared tile with subgroup-selected weight order and register// blocking. Both tiles group four K values per vector word. Weight vectors use// K-major order with lane-interleaved columns when a reported subgroup spans// multiple workgroup rows, so adjacent lanes read adjacent words, and the// micro-tile accumulates each word as four chained FMAs. Narrower and portable// schedules retain column-major order and accumulate through dot().// The full geometry computes a 4x4 micro-tile over a 64x64 output tile. A// device-selected 32x8 workgroup can use an 8x2 micro-tile on that same output// tile. The portable geometry computes 2x4 over 32x64 to bound the accumulator34 unmodified lines{% set aReadEnd = ")" if usesF16 else "" %}const K_VECS: u32 = BK / 4u;var<workgroup> tileA: array<array<vec4<{{ aTile }}>, K_VECS>, BM>; // [BM][BK/4]{% set laneInterleaved = (tileLaneInterleaved | default(false)) or weightTileKMajor %}{% if laneInterleaved %}var<workgroup> tileB: array<array<array<vec4<f32>, WG_X>, TN>, K_VECS>;{% else %}var<workgroup> tileB: array<array<vec4<f32>, K_VECS>, BN>;{% endif %}{% macro tile_b(col, kv) %}tileB{% if laneInterleaved %}[{{ kv }}][({{ col }}) % TN][({{ col }}) / TN]{% else %}[{{ col }}][{{ kv }}]{% endif %}{% endmacro %}{% if not alignedBlockLoads %}// Generic unpack used only when a quant block does not contain a whole BK tile.{% macro matmul_nbits_packed_code(fn="packed_weight", buffer="b", kBlocks="params.kBlocks", blobSize="params.blobSize", bits=4, vectorWords=false) %}{% set wordIndex = "byte_index >> 4u][(byte_index >> 2u) & 3u" if vectorWords else "byte_index >> 2u" %}fn {{ fn }}(n: u32, block: u32, offset: u32) -> u32 {{% if bits == 2 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 2u);let shift = (byte_index & 3u) * 8u + (offset & 3u) * 2u;return ({{ buffer }}[{{ wordIndex }}] >> shift) & 3u;{% elif bits == 4 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 1u);let shift = (byte_index & 3u) * 8u + (offset & 1u) * 4u;return ({{ buffer }}[{{ wordIndex }}] >> shift) & 15u;{% else %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + offset;return ({{ buffer }}[{{ wordIndex }}] >> ((byte_index & 3u) * 8u)) & 255u;{% endif %}}{% endmacro %}{{ matmul_nbits_packed_code(bits=bits, kBlocks="KBLOCKS", blobSize="BLOB_SIZE") }}{% endif %}{% macro zero_of(blockExpr) %}{% if hasZero %}f32(zero_points[bn * KBLOCKS + {{ blockExpr }}]){% else %}{{ defaultZero }}{% endif %}{% endmacro %}{% macro accumulate_k_word(kvExpr) %}{% for i in range(threadRows) %}let av{{ i }} = {{ aRead }}tileA[aRow + {{ i }}u][{{ kvExpr }}]{{ aReadEnd }};{% endfor %}{% for j in range(threadCols) %}{% if laneInterleaved %}let bv{{ j }} = tileB[{{ kvExpr }}][{{ j }}u][lid.x];{% else %}let bv{{ j }} = {{ tile_b("bCol + " ~ j ~ "u", kvExpr) }};{% endif %}{% endfor %}{% for i in range(threadRows) %}{% for j in range(threadCols) %}{% if weightTileKMajor %}acc{{ i }}{{ j }} = fma(av{{ i }}.w, bv{{ j }}.w, fma(av{{ i }}.z, bv{{ j }}.z, fma(av{{ i }}.y, bv{{ j }}.y, fma(av{{ i }}.x, bv{{ j }}.x, acc{{ i }}{{ j }}))));{% else %}acc{{ i }}{{ j }} = acc{{ i }}{{ j }} + dot(av{{ i }}, bv{{ j }});{% endif %}{% endfor %}{% endfor %}{% endmacro %}@compute @workgroup_size({{ wgX }}, {{ wgY }}, 1){{ (" @subgroup_size(" ~ subgroupPin ~ ")") if subgroupPin else "" }}fn main(@builtin(workgroup_id) wg: vec3<u32>,28 unmodified linesvar aWord = vec4<{{ aTile }}>({{ aTile }}(0.0));{% if aVec4Loads is defined and aVec4Loads %}// K is a multiple of four, so every staged word is one aligned vector load.if (am < M{% if K % bk != 0 %} && ak < K{% endif %}) {aWord = vec4<{{ aTile }}>(a[(am * K + ak) / 4u]);}{% else %}if (am < M) {{% for component in range(4) %}{% if K % bk != 0 %}if (ak + {{ component }}u < K) { aWord[{{ component }}u] = {{ aTile }}(a[am * K + ak + {{ component }}u]); }{% else %}aWord[{{ component }}u] = {{ aTile }}(a[am * K + ak + {{ component }}u]);{% endif %}{% endfor %}}{% endif %}tileA[ar][ac4] = aWord;}{% if alignedBlockLoads %}{% set chunkCodes = 16 if bits == 2 else 8 %}{% set chunkVectors = chunkCodes // 4 %}{% set chunkMask = 3 if bits == 2 else 15 %}{% if (q2ChunkLoads is defined and q2ChunkLoads and bits == 2 and bk % 16 == 0) or (weightTileKMajor and bits == 4 and bk % 8 == 0) %}// Decode one complete packed word per column and quant chunk. Its scale and// zero point feed every adjacent vector the word carries.// With the K-major, lane-interleaved weight tile, columns run fastest so// consecutive subgroup lanes store to different banks.for (var idx: u32 = li; idx < BN * (BK / {{ chunkCodes }}u); idx = idx + WG_THREADS) {let bc = idx % BN;let chunk = idx / BN;let bn = nBase + bc;let baseK = kBase + chunk * {{ chunkCodes }}u;var packed: u32 = 0u;var scale: f32 = 0.0;var zero: f32 = 0.0;if (bn < N{% if K % bk != 0 %} && baseK < K{% endif %}) {let block = baseK / BLOCK_SIZE;let offset = baseK % BLOCK_SIZE;let byteIndex = (bn * KBLOCKS + block) * BLOB_SIZE + (offset >> {{ 2 if bits == 2 else 1 }}u);packed = b[byteIndex >> 2u];scale = f32(scales[bn * KBLOCKS + block]);zero = {{ zero_of("block") }};}{% for vec in range(chunkVectors) %}{% if bits == 2 %}let word{{ vec }} = vec4<f32>({% for component in range(4) %}(f32((packed >> {{ bits * (vec * 4 + component) }}u) & {{ chunkMask }}u) - zero) * scale{% if not loop.last %},{% endif %}{% endfor %});{% else %}var word{{ vec }} = vec4<f32>(0.0);{% for component in range(4) %}if (baseK + {{ vec * 4 + component }}u < K) {word{{ vec }}[{{ component }}u] = (f32((packed >> {{ bits * (vec * 4 + component) }}u) & {{ chunkMask }}u) - zero) * scale;}{% endfor %}{% endif %}{{ tile_b("bc", "chunk * " ~ chunkVectors ~ "u + " ~ vec ~ "u") }} = word{{ vec }};{% endfor %}}{% else %}3 unmodified lines// K-adjacent codes of a vector word are byte-contiguous from a 4-aligned// offset, so they always come out of ONE packed word: one load per vector.for (var idx: u32 = li; idx < BN * K_VECS; idx = idx + WG_THREADS) {{% if weightTileKMajor %}let bc = idx % BN;let kv = idx / BN;{% else %}let bc = idx / K_VECS;let kv = idx % K_VECS;{% endif %}let bn = nBase + bc;var word = vec4<f32>(0.0);if (bn < N{% if K % bk != 0 %} && kBase < K{% endif %}) {let block = kBase / BLOCK_SIZE;let offset0 = kBase % BLOCK_SIZE;let scale = f32(scales[bn * KBLOCKS + block]);5 unmodified lineslet byte_index = blob_base + ((offset0 + kk) >> 2u);let packed = b[byte_index >> 2u] >> ((byte_index & 3u) * 8u);{% for component in range(4) %}{% if K % bk != 0 %} if (kBase + kk + {{ component }}u < K) {{% endif %}word[{{ component }}u] = (f32((packed >> {{ component * 2 }}u) & 3u) - zero) * scale;{% if K % bk != 0 %} }{% endif %}{% endfor %}{% elif bits == 4 %}// Two bytes carry the four K-adjacent codes of one vector word.let byte_index = blob_base + ((offset0 + kk) >> 1u);let packed = b[byte_index >> 2u] >> ((byte_index & 3u) * 8u);{% for component in range(4) %}{% if K % bk != 0 %} if (kBase + kk + {{ component }}u < K) {{% endif %}word[{{ component }}u] = (f32((packed >> {{ component * 4 }}u) & 15u) - zero) * scale;{% if K % bk != 0 %} }{% endif %}{% endfor %}{% else %}let byte_index = blob_base + offset0 + kk;let packed = b[byte_index >> 2u];{% for component in range(4) %}{% if K % bk != 0 %} if (kBase + kk + {{ component }}u < K) {{% endif %}word[{{ component }}u] = (f32((packed >> {{ component * 8 }}u) & 255u) - zero) * scale;{% if K % bk != 0 %} }{% endif %}{% endfor %}{% endif %}}{{ tile_b("bc", "kv") }} = word;}{% endif %}{% else %}// Quant blocks that do not contain a whole BK tile use the element-wise loader.for (var idx: u32 = li; idx < BN * K_VECS; idx = idx + WG_THREADS) {{% if weightTileKMajor %}let bc = idx % BN;let br4 = idx / BN;{% else %}let bc = idx / K_VECS;let br4 = idx % K_VECS;{% endif %}let bk = kBase + br4 * 4u;let bn = nBase + bc;var word = vec4<f32>(0.0);if (bn < N) {{% for component in range(4) %}{% if K % bk != 0 %} if (bk + {{ component }}u < K) {{% endif %}let block{{ component }} = (bk + {{ component }}u) / BLOCK_SIZE;let offset{{ component }} = (bk + {{ component }}u) % BLOCK_SIZE;let scale{{ component }} = f32(scales[bn * KBLOCKS + block{{ component }}]);let zero{{ component }} = {{ zero_of("block" ~ component) }};word[{{ component }}u] = (f32(packed_weight(bn, block{{ component }}, offset{{ component }})) - zero{{ component }}) * scale{{ component }};{% if K % bk != 0 %} }{% endif %}{% endfor %}}{{ tile_b("bc", "br4") }} = word;}{% endif %}workgroupBarrier();let aRow = lid.y * TM;{% if not laneInterleaved %}let bCol = lid.x * TN;{% endif %}{% if nbitsStaticKv | default(false) %}{% for staticKv in range(bk // 4) %}{{{ accumulate_k_word(staticKv ~ "u") }} }{% endfor %}{% else %}for (var kv: u32 = 0u; kv < K_VECS; kv = kv + 1u) {{{ accumulate_k_word("kv") }} }{% endif %}workgroupBarrier();}
12345621 unmodified lines282930313233343536373839404142434445464748{{ env.wgsl.resourceDeclarations }}// com.microsoft.MatMulNBits q4/q8 prefill, no-subgroup-matrix tier:// Y[M,N] = A[M,K] @ W[K,N] (+ bias), W[k,n] = (q(n,block,offset) - zero) * scale// Register-blocked 32x32 shared-memory tiled GEMM (16x16 threads, each computes a// 2x2 micro-tile, K stepped in BK=16 chunks). The B operand is dequantized from21 unmodified linesvar<workgroup> tileB: array<array<f32, 32>, 16>;// {{ bits }}-bit unpack: q2 stores four codes per byte, q4 two, and q8 one.{% macro matmul_nbits_packed_code(fn="packed_weight", buffer="b", kBlocks="params.kBlocks", blobSize="params.blobSize", bits=4) %}fn {{ fn }}(n: u32, block: u32, offset: u32) -> u32 {{% if bits == 2 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 2u);let shift = (byte_index & 3u) * 8u + (offset & 3u) * 2u;return ({{ buffer }}[byte_index >> 2u] >> shift) & 3u;{% elif bits == 4 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 1u);let shift = (byte_index & 3u) * 8u + (offset & 1u) * 4u;return ({{ buffer }}[byte_index >> 2u] >> shift) & 15u;{% else %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + offset;return ({{ buffer }}[byte_index >> 2u] >> ((byte_index & 3u) * 8u)) & 255u;{% endif %}}{% endmacro %}{{ matmul_nbits_packed_code(bits=bits, kBlocks="KBLOCKS", blobSize="BLOB_SIZE") }}@compute @workgroup_size({{ tiledWorkgroupSide }}, {{ tiledWorkgroupSide }}, 1)12345621 unmodified lines2829303132333435363738394041424344454647484950{{ env.wgsl.resourceDeclarations }}// com.microsoft.MatMulNBits q4/q8 prefill for devices without subgroup matrices:// Y[M,N] = A[M,K] @ W[K,N] (+ bias), W[k,n] = (q(n,block,offset) - zero) * scale// Register-blocked 32x32 shared-memory tiled GEMM (16x16 threads, each computes a// 2x2 micro-tile, K stepped in BK=16 chunks). The B operand is dequantized from21 unmodified linesvar<workgroup> tileB: array<array<f32, 32>, 16>;// {{ bits }}-bit unpack: q2 stores four codes per byte, q4 two, and q8 one.{% macro matmul_nbits_packed_code(fn="packed_weight", buffer="b", kBlocks="params.kBlocks", blobSize="params.blobSize", bits=4, vectorWords=false) %}{% set wordIndex = "byte_index >> 4u][(byte_index >> 2u) & 3u" if vectorWords else "byte_index >> 2u" %}fn {{ fn }}(n: u32, block: u32, offset: u32) -> u32 {{% if bits == 2 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 2u);let shift = (byte_index & 3u) * 8u + (offset & 3u) * 2u;return ({{ buffer }}[{{ wordIndex }}] >> shift) & 3u;{% elif bits == 4 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 1u);let shift = (byte_index & 3u) * 8u + (offset & 1u) * 4u;return ({{ buffer }}[{{ wordIndex }}] >> shift) & 15u;{% else %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + offset;return ({{ buffer }}[{{ wordIndex }}] >> ((byte_index & 3u) * 8u)) & 255u;{% endif %}}{% endmacro %}{{ matmul_nbits_packed_code(bits=bits, kBlocks="KBLOCKS", blobSize="BLOB_SIZE") }}@compute @workgroup_size({{ tiledWorkgroupSide }}, {{ tiledWorkgroupSide }}, 1)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488{%- macro registerBeforeEntryPoint() %}struct Q4WeightRangeGate { rejected: atomic<u32>, accepted: u32,};var<workgroup> q4WeightRangeGate: Q4WeightRangeGate;
fn q4WeightRangeAccepted(colBase: u32, beginK: u32, endK: u32, tid: u32) -> bool { let firstBlock = beginK / {{ blockSize }}u; let liveEnd = min(endK, K); var blockCount = 0u; if (beginK < liveEnd) { blockCount = (liveEnd - 1u) / {{ blockSize }}u + 1u - firstBlock; } let activeCols = min(TILE_N, N - min(colBase, N)); for (var flat = tid; flat < activeCols * blockCount; flat += 128u) { let col = colBase + flat / blockCount; let block = col * {{ kBlocks }}u + firstBlock + flat % blockCount; let scale = f32(scales[block]); let zero = {% if hasZero %}f32(zero_points[block]){% else %}{{ defaultZero }}{% endif %}; if ((bitcast<u32>(scale) & 0x7f800000u) == 0x7f800000u || (bitcast<u32>(zero) & 0x7f800000u) == 0x7f800000u) { atomicStore(&q4WeightRangeGate.rejected, 1u); continue; } if (scale == 0.0) { continue; } let maxCode = {{ (2 ** bits) - 1 }}.0; let peak = max(abs(-zero * scale), abs((maxCode - zero) * scale)); var nearest = min(abs(zero), abs(maxCode - zero)); if (zero >= 0.0 && zero <= maxCode) { let fraction = zero - floor(zero); nearest = select(min(fraction, 1.0 - fraction), 1.0, fraction == 0.0); } let minimumNonzero = abs(scale) * nearest; if (peak > 65504.0 || minimumNonzero < 0.00006103515625) { atomicStore(&q4WeightRangeGate.rejected, 1u); } } workgroupBarrier(); if (tid == 0u) { q4WeightRangeGate.accepted = select(0u, 1u, atomicLoad(&q4WeightRangeGate.rejected) == 0u); } return workgroupUniformLoad(&q4WeightRangeGate.accepted) != 0u;}
{% endmacro -%}{%- macro registerWorkgroupPrelude() %} let weightRangeSafe = q4WeightRangeAccepted(colBase, {{ "beginK" if registerSplitK | default(false) else "0u" }}, {{ "endK" if registerSplitK | default(false) else "K" }}, tid);{% endmacro -%}{%- macro registerNativeCondition() %}nativeTopology && weightRangeSafe{% endmacro -%}{%- macro registerFallbackReadB() %} if (k >= K || col >= N) { return 0.0; } let word = b[col * {{ (K * bits / 32) | int }}u + k / {{ (32 / bits) | int }}u]; let code = (word >> ((k % {{ (32 / bits) | int }}u) * {{ bits }}u)) & {{ (2 ** bits) - 1 }}u; let block = col * {{ kBlocks }}u + k / {{ blockSize }}u; let zero = {% if hasZero %}f32(zero_points[block]){% else %}{{ defaultZero }}{% endif %}; return (f32(code) - zero) * f32(scales[block]);{% endmacro -%}{%- macro registerPackedBPrelude() -%}{% if bits == 2 %}fn q4_packed_word(column: u32, reduction: u32) -> vec4<u32> { let block = column * {{ kBlocks }}u + reduction / {{ blockSize }}u; // Sixteen codes per word from the low bits up; the eight from `reduction` share a half. let word = b[column * {{ (K / 16) | int }}u + reduction / 16u]; let first = (reduction % 16u) * 2u; let scale = f32(scales[block]); let zero = {% if hasZero %}f32(zero_points[block]){% else %}{{ defaultZero }}{% endif %}; var codes: array<f32, 8>; for (var j = 0u; j < 8u; j++) { codes[j] = (f32((word >> (first + 2u * j)) & 3u) - zero) * scale; } return vec4<u32>( bitcast<u32>(vec2<f16>(f16(codes[0]), f16(codes[1]))), bitcast<u32>(vec2<f16>(f16(codes[2]), f16(codes[3]))), bitcast<u32>(vec2<f16>(f16(codes[4]), f16(codes[5]))), bitcast<u32>(vec2<f16>(f16(codes[6]), f16(codes[7]))));}{% else %}fn q4_packed_word(column: u32, reduction: u32) -> vec4<u32> { let block = column * {{ kBlocks }}u + reduction / {{ blockSize }}u; let codes = vec4<u32>(b[column * {{ (K / 8) | int }}u + reduction / 8u]); let scale = f32(scales[block]); let zero = {% if hasZero %}f32(zero_points[block]){% else %}8.0{% endif %}; let even = (vec4<f32>((codes >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(15u)) - zero) * scale; let odd = (vec4<f32>((codes >> vec4<u32>(4u, 12u, 20u, 28u)) & vec4<u32>(15u)) - zero) * scale; return vec4<u32>( bitcast<u32>(vec2<f16>(f16(even.x), f16(odd.x))), bitcast<u32>(vec2<f16>(f16(even.y), f16(odd.y))), bitcast<u32>(vec2<f16>(f16(even.z), f16(odd.z))), bitcast<u32>(vec2<f16>(f16(even.w), f16(odd.w))));}{%- endif %}{%- endmacro -%}{%- macro registerLoadPackedB(column, reduction) -%}q4_packed_word({{ column }}, {{ reduction }}){%- endmacro -%}{% set RESULT_SCRATCH_WORDS = 256 %}{%- set PAIRED_SWIGLU = false -%}{%- set EPILOGUE = registerEpilogue | default("none") -%}{%- set TA = false -%}{%- set TB = true -%}{%- set BIAS = registerBiasMode | default("none") -%}{%- set BM = registerTileM -%}{%- set BN = registerTileN -%}{%- set BK = registerTileK -%}{%- set PAD = registerSharedPad | default(0) -%}{%- set FR = (BM / 32) | int -%}{%- set FC = (BN / 32) | int -%}{%- set ACOLS = BM if TA else BK -%}{%- set AROWS = BK if TA else BM -%}{%- set ASTRIDE = ((ACOLS + PAD) / 8) | int -%}{%- set BSTRIDE = (((BK if TB else BN) + PAD) / 8) | int -%}{%- set AWORDS = ((AROWS * (ACOLS + PAD)) / 8) | int -%}{%- set BWORDS = (((BN if TB else BK) * ((BK if TB else BN) + PAD)) / 8) | int -%}{%- set ASIZE = max(AWORDS, RESULT_SCRATCH_WORDS) -%}{%- set OUT_SLOTS = ((BM * BN) / 8 / 128) | int -%}{%- set PREFETCH = registerPrefetch | default(false) -%}{%- set SPLIT_K = registerSplitK | default(false) -%}{%- set SPLIT_COUNT = registerSplitSlices | default(1) -%}{%- set SPLIT_PAD = SPLIT_K and (registerSplitPadRows | default(false)) -%}{%- set OUTPUT_F32 = registerOutputF32 | default(false) -%}{%- set F32_TAIL = false -%}{%- macro coordinates(name) -%}{% if name == "a" %} let row = rowBase + flat / {{ (BK / 8) | int }}u; let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;{% else %} let col = colBase + flat / {{ (BK / 8) | int }}u; let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;{% endif %}{%- endmacro -%}{%- macro guard(name) -%}{%- if name == "a" -%}row < M && k + 7u < K{%- else -%}col < N && k + 7u < K{%- endif -%}{%- endmacro -%}{%- macro address(name) -%}{%- if name == "a" -%}({{ "k * M + row" if TA else "row * K + k" }}) / 8u{%- else -%}({% if EPILOGUE == "prefill" %}params.weightOffset + {% endif %}{{ "col * K + k" if TB else "k * N + col" }}) / 8u{%- endif -%}{%- endmacro -%}{%- macro shared_index(name) -%}{%- set PAYLOAD = ((ACOLS if name == "a" else BK if TB else BN) / 8) | int -%}{%- set STRIDE = ASTRIDE if name == "a" else BSTRIDE -%}(flat / {{ PAYLOAD }}u) * {{ STRIDE }}u + flat % {{ PAYLOAD }}u{%- endmacro -%}{%- macro result(value, column) -%}f16({% if EPILOGUE == "activation" %}fused_act({% endif %}{% if EPILOGUE == "fp8" %}{{ value }}{% if BIAS == "row" %} + f32(bias[{{ column }}]){% endif %}{% elif EPILOGUE == "fastgelu" %}gelu_tanh({{ value }}{% if BIAS == "row" %} + f32(bias[{{ column }}]){% endif %}){% elif EPILOGUE == "gemm" or EPILOGUE == "activation" %}params.alpha * {{ value }}{% if BIAS != "none" %} + params.beta * f32(bias[{% if BIAS == "scalar" %}0u{% elif BIAS == "row" %}{{ column }}{% elif BIAS == "column" %}row{% else %}row * N + {{ column }}{% endif %}]){% endif %}{% else %}{{ value }}{% endif %}{% if EPILOGUE == "activation" %}){% endif %}){%- endmacro -%}{%- macro output_address() -%}({% if EPILOGUE == "prefill" %}row * params.outStride + params.dstColStart + col{% else %}row * N + col{% endif %}) / 8u{%- endmacro -%}{%- macro half_output_guard() -%}row < M && {{ "col + 7u < N" }}{%- endmacro -%}{%- macro store_half_result() -%}y[{{ output_address() }}] = {{ pack_result("values") }};{%- endmacro -%}{%- macro pack_result(source) -%}vec4<u32>({% for pair in range(4) %} bitcast<u32>(vec2<f16>({{ result(source ~ "[" ~ (pair * 2) ~ "]", "col + " ~ (pair * 2) ~ "u") }}, {{ result(source ~ "[" ~ (pair * 2 + 1) ~ "]", "col + " ~ (pair * 2 + 1) ~ "u") }})){{ "," if pair != 3 else "" }}{% endfor %} ){%- endmacro -%}{%- macro load_left_fragment(r, step) %} let left{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>( &tileA, subgroupRow * {{ ASTRIDE }}u + {{ r * 16 * ASTRIDE + (step / 8) | int }}u, {{ ASTRIDE }}u);{%- endmacro -%}{%- macro load_right_fragment(c, step) %} let right{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, col_major>( &tileB, subgroupCol * {{ BSTRIDE }}u + {{ c * 16 * BSTRIDE + (step / 8) | int }}u, {{ BSTRIDE }}u);{%- endmacro -%}{%- macro multiply_fragment(r, c) %} acc{{ r }}_{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ r }}, right{{ c }}, acc{{ r }}_{{ c }});{%- endmacro -%}enable subgroups;enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{% if registerPackedBPrelude is defined %}{{ registerPackedBPrelude() }}{% endif %}{% if EPILOGUE == "fastgelu" %}fn tanh_safe(x: f32) -> f32 { // tanh rounds to its saturated value for these tails in f32. Return that // value directly, including for infinite input, before invoking the builtin. if (x > 10.0) { return 1.0; } if (x < -10.0) { return -1.0; } // For tiny |x|, return x directly to preserve its sign and magnitude without // relying on backend-specific builtin behavior near zero. if (x > -1.0e-4 && x < 1.0e-4) { return x; } return tanh(x);}
fn gelu_tanh(v: f32) -> f32 { return 0.5 * v * (1.0 + tanh_safe(0.7978845608028654 * (v + 0.044715 * v * v * v)));}{% elif EPILOGUE == "activation" %}{% set actMode = "" %}{% set actA = 0.0 %}{% set actB = 0.0 %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "" %} return v;{% elif mode == "Relu" %} let bits = bitcast<u32>(v); return bitcast<f32>(select(0u, bits, (bits & 0x80000000u) == 0u || (bits & 0x7fffffffu) > 0x7f800000u));{% elif mode == "Clip" %} return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %} return select(v * f32({{ alpha }}), v, v >= 0.0);{% elif mode == "Sigmoid" %} return 1.0 / (1.0 + exp(-v));{% elif mode == "Tanh" %} // tanh is already +/-1 to f32 precision at the clamp bounds. Clamping before // the builtin preserves that saturated result for larger accumulators. return tanh(clamp(v, -10.0, 10.0));{% elif mode == "HardSigmoid" %} return clamp(f32({{ alpha }}) * v + f32({{ beta }}), 0.0, 1.0);{% elif mode == "QuickGelu" %}{% if alpha == 1 %} // alpha == 1 is SiLU: the multiply folds away (the spelling yolov8-class detectors emit). return v * (1.0 / (1.0 + exp(-v)));{% else %} return v * (1.0 / (1.0 + exp(-(f32({{ alpha }}) * v))));{% endif %}{% elif mode == "Elu" %} return select(f32({{ alpha }}) * (exp(v) - 1.0), v, v >= 0.0);{% elif mode == "ThresholdedRelu" %} return select(0.0, v, v > f32({{ alpha }}));{% elif mode == "Softplus" %} // log(1 + exp(v)) spelled overflow-safe: max(v, 0) + log(1 + exp(-|v|)). return max(v, 0.0) + log(1.0 + exp(-abs(v)));{% elif mode == "Erf" %} // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7), the same polynomial the standalone // Erf/Gelu kernels use, so a fused and an unfused graph agree to f32 rounding. let a = abs(v); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return sign(v) * (1.0 - poly * exp(-a * a));{% elif mode == "Gelu" and alpha == 0 %} // ONNX Gelu, erf form: 0.5 * v * (1 + erf(v / sqrt(2))); activation_params[0] == 0. let u = v * 0.70710678118654752; let a = abs(u); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return 0.5 * v * (1.0 + sign(u) * (1.0 - poly * exp(-a * a)));{% elif mode == "Gelu" or mode == "FastGelu" %} // tanh approximation (ONNX Gelu approximate="tanh" arrives as activation_params[0] != 0; // com.microsoft.FastGelu always). tanh saturates to +/-1 well inside the clamp. let inner = v * (0.035677408136300125 * v * v + 0.7978845608028654); return v * (0.5 + 0.5 * tanh(clamp(inner, -10.0, 10.0)));{% else %} return v * clamp(v * 0.16666666666666666 + 0.5, 0.0, 1.0);{% endif %}}{% endmacro %}{{ fused_act_fn(actMode, actA, actB) }}{% endif %}{{ env.wgsl.resourceDeclarations }}const N: u32 = {{ N }}u;const K: u32 = {{ K }}u;const TILE_M: u32 = {{ BM }}u;const TILE_N: u32 = {{ BN }}u;const TILE_K: u32 = {{ BK }}u;{% if SPLIT_K %}const K_STAGES: u32 = {{ ceilDiv(K, BK) }}u;const SPLITS: u32 = {{ SPLIT_COUNT }}u;{% endif %}var<workgroup> tileA: array<vec4<u32>, {{ ASIZE }}>;var<workgroup> tileB: array<vec4<u32>, {{ BWORDS }}>;
fn loadTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) { let M = params.M;{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %} for (var flat = tid; flat < {{ WORDS }}u; flat += 128u) {{{ coordinates(name) }} var value = vec4<u32>(0u);{% if name == "b" and registerLoadPackedB is defined %} if ({{ guard(name) }}) { value = {{ registerLoadPackedB("col", "k") }}; }{% else %} if ({{ guard(name) }}) { value = {{ name }}[{{ address(name) }}]; }{% endif %} tile{{ "A" if name == "a" else "B" }}[{{ shared_index(name) }}] = value; }{% endfor %}}
{% if PREFETCH %}struct PrefetchedTiles { a: array<vec4<u32>, {{ ((BM * BK / 8 + 127) / 128) | int }}>, b: array<vec4<u32>, {{ ((BK * (2 * BN if PAIRED_SWIGLU else BN) / 8 + 127) / 128) | int }}>,};fn prefetchTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) -> PrefetchedTiles { let M = params.M; var values: PrefetchedTiles;{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}{% for slot in range(((WORDS + 127) / 128) | int) %} { let flat = tid + {{ slot * 128 }}u; if (flat < {{ WORDS }}u) {{{ coordinates(name) }}{% if name == "b" and registerLoadPackedB is defined %} if ({{ guard(name) }}) { values.b[{{ slot }}] = {{ registerLoadPackedB("col", "k") }}; }{% else %} if ({{ guard(name) }}) { values.{{ name }}[{{ slot }}] = {{ name }}[{{ address(name) }}]; }{% endif %} } }{% endfor %}{% endfor %} return values;}fn stagePrefetchedTiles(values: PrefetchedTiles, tid: u32) {{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}{% for slot in range(((WORDS + 127) / 128) | int) %} { let flat = tid + {{ slot * 128 }}u; if (flat < {{ WORDS }}u) { tile{{ "A" if name == "a" else "B" }}[{{ shared_index(name) }}] = values.{{ name }}[{{ slot }}]; } }{% endfor %}{% endfor %}}{% endif %}
fn readA(row: u32, k: u32) -> f32 { let word = tileA[row * {{ ASTRIDE }}u + k / 8u]; return f32(bitcast<vec2<f16>>(word[(k % 8u) / 2u])[k % 2u]);}fn readB(k: u32, col: u32) -> f32 {{% if registerFallbackReadB is defined %}{{ registerFallbackReadB() }}{% else %} let contiguous = {{ "k" if TB else "col" }}; let word = tileB[{{ "col" if TB else "k" }} * {{ BSTRIDE }}u + contiguous / 8u]; return f32(bitcast<vec2<f16>>(word[(contiguous % 8u) / 2u])[contiguous % 2u]);{% endif %}}
// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}{% if registerBeforeEntryPoint is defined %}{{ registerBeforeEntryPoint() }}{% endif %}@compute @workgroup_size(128, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32{% if not OUTPUT_F32 or F32_TAIL %}, @builtin(subgroup_invocation_id) lane: u32{% endif %}) { let M = params.M; let rowBase = wid.y * TILE_M; let colBase = wid.x * TILE_N;{% if SPLIT_K %} let beginK = (wid.z * K_STAGES / SPLITS) * TILE_K; let endK = ((wid.z + 1u) * K_STAGES / SPLITS) * TILE_K;{% endif %}{% if SPLIT_PAD %} // Partial slices hold the rows rounded up to whole fragments, so a fragment that // straddles the last row stores whole; the combine pass reads only real rows. let sliceRows = (M + 15u) / 16u * 16u;{% endif %}{% if registerWorkgroupPrelude is defined %}{{ registerWorkgroupPrelude() }}{% endif %} let role = min(claimMatrixSubgroupRole(width, 32u), 3u); let nativeTopology = matrixTopologyAccepted(tid, 4u); if ({% if registerNativeCondition is defined %}{{ registerNativeCondition() }}{% else %}nativeTopology{% endif %}) { let subgroupRow = (role / 2u) * {{ FR * 16 }}u; let subgroupCol = (role % 2u) * {{ FC * 16 }}u;{% for r in range(FR) %}{% for c in range(FC) %} var acc{{ r }}_{{ c }}: subgroup_matrix_result<f32, 16, 16>;{% endfor %}{% endfor %}{% if PREFETCH %} var nextTiles = prefetchTiles(rowBase, colBase, {{ "beginK" if SPLIT_K else "0u" }}, tid);{% endif %} for (var kk = {{ "beginK" if SPLIT_K else "0u" }}; kk < {{ "endK" if SPLIT_K else "K" }}; kk += TILE_K) {{% if PREFETCH %} stagePrefetchedTiles(nextTiles, tid);{% else %} loadTiles(rowBase, colBase, kk, tid);{% endif %} workgroupBarrier();{% if PREFETCH %} if (kk + TILE_K < {{ "endK" if SPLIT_K else "K" }}) { nextTiles = prefetchTiles(rowBase, colBase, kk + TILE_K, tid); }{% endif %}{% for step in range(0, BK, 16) %} {{% for r in range(FR) %}{{ load_left_fragment(r, step) }}{% endfor %}{% for c in range(FC) %}{{ load_right_fragment(c, step) }}{% endfor %}{% for r in range(FR) %}{% for c in range(FC) %}{{ multiply_fragment(r, c) }}{% endfor %}{% endfor %} }{% endfor %} workgroupBarrier(); }{% if OUTPUT_F32 %}{% for r in range(FR) %}{% for c in range(FC) %} { let row = rowBase + subgroupRow + {{ r * 16 }}u; let col = colBase + subgroupCol + {{ c * 16 }}u; if ({{ "row < M" if SPLIT_PAD else "row + 15u < M" }} && col + 15u < N) { subgroupMatrixStore<row_major>(&y, ({% if SPLIT_K %}wid.z * {{ "sliceRows" if SPLIT_PAD else "M" }} * N + {% endif %}row * N + col) / 4u, acc{{ r }}_{{ c }}, N / 4u); } }{% endfor %}{% endfor %}{% else %} let scratchBase = role * 64u;{% for r in range(FR) %}{% for c in range(FC) %} { subgroupMatrixStore<row_major>(&tileA, scratchBase, acc{{ r }}_{{ c }}, 4u); workgroupBarrier(); let row = rowBase + subgroupRow + {{ r * 16 }}u + lane / 2u; let col = colBase + subgroupCol + {{ c * 16 }}u + (lane % 2u) * 8u; if ({{ half_output_guard() }}) { let first = bitcast<vec4<f32>>(tileA[scratchBase + lane * 2u]); let second = bitcast<vec4<f32>>(tileA[scratchBase + lane * 2u + 1u]); let values = array<f32, 8>(first.x, first.y, first.z, first.w, second.x, second.y, second.z, second.w); {{ store_half_result() }} } workgroupBarrier(); }{% endfor %}{% endfor %}{% endif %} } else { for (var slot = 0u; slot < {{ OUT_SLOTS }}u; slot += 1u) { let flat = tid + slot * 128u; let tileRow = flat / {{ (BN / 8) | int }}u; let tileCol = (flat % {{ (BN / 8) | int }}u) * 8u; var acc: array<f32, 8>;{% for component in range(8) %} acc[{{ component }}] = 0.0;{% endfor %} for (var kk = {{ "beginK" if SPLIT_K else "0u" }}; kk < {{ "endK" if SPLIT_K else "K" }}; kk += TILE_K) { loadTiles(rowBase, colBase, kk, tid); workgroupBarrier(); for (var k = 0u; k < TILE_K; k += 1u) { let left = readA(tileRow, k); for (var component = 0u; component < 8u; component += 1u) { acc[component] = fma(left, readB({% if registerFallbackReadB is defined %}kk + k, colBase + tileCol + component{% else %}k, tileCol + component{% endif %}), acc[component]); } } workgroupBarrier(); } let row = rowBase + tileRow; let col = colBase + tileCol;{% if OUTPUT_F32 %} if (row < M && col + 7u < N) { let values = array<f32, 8>({% for component in range(8) %} acc[{{ component }}u]{{ "," if component != 7 else "" }}{% endfor %} ); let outputWord = ({% if SPLIT_K %}wid.z * {{ "sliceRows" if SPLIT_PAD else "M" }} * N + {% endif %}row * N + col) / 4u; y[outputWord] = bitcast<vec4<u32>>(vec4<f32>(values[0], values[1], values[2], values[3])); y[outputWord + 1u] = bitcast<vec4<u32>>(vec4<f32>(values[4], values[5], values[6], values[7])); }{% else %} if ({{ half_output_guard() }}) { let values = array<f32, 8>({% for component in range(8) %} acc[{{ component }}u]{{ "," if component != 7 else "" }}{% endfor %} ); {{ store_half_result() }} }{% endif %}
} }}123456789101114 unmodified lines26272829303173 unmodified lines1051061071081091101111121131148 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481492 unmodified lines1521531541551561571581591601611621631641651661671681691701711721735 unmodified lines179180181182183184185186187188189190191192193194195196197198199200// com.microsoft.MatMulNBits q4 prefill subgroup-matrix tier:// Y[M,N] = A[M,K] @ W[K,N] + bias?, W[k,n] = (q4(n,block,offset) - zero) * scale// Uses a 32x64 or 64x64 subgroup-matrix output tile with an M-tail row_limit guard; the// B operand is materialized on the fly by dequantizing the packed q4 blob into// the shared B tile, so no f32 weight matrix is stored. Dequantized operands and// accumulations use f32.// Alignment gates keep K % 32 == 0 and N % 64 == 0 so subgroupMatrixLoad never// sees partial 8x8 tiles; M tails handled by row_limit + the loadSHMA zero-fill.enable subgroups;{% if pinSubgroupSize32 %}enable subgroup_size_control;14 unmodified linesconst TILE_K: u32 = 32u;const SUB_COLS: u32 = 32u;const SUB_ROWS: u32 = 16u;var<workgroup> tile_A: array<f32, {{ tileRows }} * 32>;var<workgroup> tile_B: array<f32, 64 * 32>;73 unmodified linesfn storeCol(offset: u32, col_base: u32, row: u32, cc: u32, slot: u32, src_slot: u32) {let c = cc + slot * 8u;if (col_base + c < N) {{% if hasBias %}y[offset + row * N + c] = {{ outputScalar }}(scratch[src_slot][slot][row * 8u + cc] + f32(bias[col_base + c]));{% else %}y[offset + row * N + c] = {{ outputScalar }}(scratch[src_slot][slot][row * 8u + cc]);{% endif %}}}8 unmodified lines}}@compute @workgroup_size({{ workgroupSize }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) workgroup_id: vec3<u32>,@builtin(local_invocation_index) local_idx: u32,@builtin(subgroup_invocation_id) sg_id: u32,@builtin(subgroup_size) sg_size: u32) {let a_global_base = workgroup_id.y * TILE_ROWS;let b_global_base = workgroup_id.x * TILE_COLS;let subtile_id = local_idx / sg_size;let subtile_idx = subtile_id / {{ rowSubtiles }}u;let subtile_idy = subtile_id % {{ rowSubtiles }}u;let base_A = subtile_idy * SUB_ROWS;let base_B = subtile_idx * SUB_COLS;{% for row in [0, 1] %}{% for col in [0, 1, 2, 3] %}var matC{{ row }}{{ col }}: subgroup_matrix_result<f32, 8, 8>;{% endfor %}{% endfor %}for (var kidx = 0u; kidx < K; kidx = kidx + TILE_K) {loadSHMA(a_global_base, kidx, local_idx / 4u, local_idx % 4u);loadSHMB(b_global_base, kidx, local_idx / {{ bLoadsPerRow }}u, local_idx % {{ bLoadsPerRow }}u);workgroupBarrier();2 unmodified lines{% set operandScalar = "f32" %}{% set directInputs = false %}let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;{% for r in range(2) %}var matA{{ r }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&{{ "w" if directInputs else "tile_A" }}, matrix_a_offset{% if r > 0 %} + 8u * {{ "K" if directInputs else "TILE_K" }}{% endif %}, {{ "K" if directInputs else "TILE_K" }});{% endfor %}let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;{% for c in range(4) %}var matB{{ c }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, col_major>(&{{ "xm" if directInputs else "tile_B" }}, matrix_b_offset{% if c > 0 %} + {{ c * 8 }}u * TILE_K{% endif %}, {{ "N" if directInputs else "TILE_K" }});{% endfor %}matC00 = subgroupMatrixMultiplyAccumulate(matA0, matB0, matC00);matC01 = subgroupMatrixMultiplyAccumulate(matA0, matB1, matC01);matC02 = subgroupMatrixMultiplyAccumulate(matA0, matB2, matC02);matC03 = subgroupMatrixMultiplyAccumulate(matA0, matB3, matC03);matC10 = subgroupMatrixMultiplyAccumulate(matA1, matB0, matC10);matC11 = subgroupMatrixMultiplyAccumulate(matA1, matB1, matC11);matC12 = subgroupMatrixMultiplyAccumulate(matA1, matB2, matC12);matC13 = subgroupMatrixMultiplyAccumulate(matA1, matB3, matC13);}workgroupBarrier();5 unmodified lines// clobbering the first's still-in-flight readback when a partial final M-tile// diverges storeOutput's guard. Without both barriers the last valid row can be corrupted.{% for col in [0, 1, 2, 3] %}subgroupMatrixStore<row_major>(&scratch[subtile_id][{{ col }}], 0u, matC0{{ col }}, 8u);{% endfor %}workgroupBarrier();let row = sg_id / 4u;let col = (sg_id % 4u) * 2u;let col_base = b_global_base + base_B;var matrix_c_offset = (a_global_base + base_A) * N + col_base;var row_limit = i32(M) - i32(a_global_base + base_A);storeOutput(matrix_c_offset, col_base, row, col, subtile_id, row_limit);workgroupBarrier();{% for col in [0, 1, 2, 3] %}subgroupMatrixStore<row_major>(&scratch[subtile_id][{{ col }}], 0u, matC1{{ col }}, 8u);{% endfor %}workgroupBarrier();matrix_c_offset = matrix_c_offset + 8u * N;row_limit = i32(M) - i32(a_global_base + base_A + 8u);storeOutput(matrix_c_offset, col_base, row, col, subtile_id, row_limit);}1234567891011121314151614 unmodified lines31323334353637383973 unmodified lines1131141151161171181191201211228 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272 unmodified lines2302312322332342352362372382392402412422432442452462472482492502512525 unmodified lines258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302// com.microsoft.MatMulNBits q4 prefill subgroup-matrix variant:// Y[M,N] = A[M,K] @ W[K,N] + bias?, W[k,n] = (q4(n,block,offset) - zero) * scale// Uses a 32x64 or 64x64 subgroup-matrix output tile with an M-tail row_limit guard; the// B operand is materialized on the fly by dequantizing the packed q4 blob into// the shared B tile, so no f32 weight matrix is stored. Dequantized operands and// accumulations use f32.// Alignment requirements keep K % 32 == 0 and N % 64 == 0 so subgroupMatrixLoad never// sees partial 8x8 tiles; M tails handled by row_limit + the loadSHMA zero-fill.// With splitK > 1 each workgroup z folds one run of 32-wide K tiles into float32// partials [splitK, M, N]; a combine pass sums them in slice order and adds the bias.{% set splitK = splitK | default(1) %}{% set storeScalar = "f32" if splitK > 1 else outputScalar %}{% set storeBias = hasBias and splitK == 1 %}enable subgroups;{% if pinSubgroupSize32 %}enable subgroup_size_control;14 unmodified linesconst TILE_K: u32 = 32u;const SUB_COLS: u32 = 32u;const SUB_ROWS: u32 = 16u;{% if splitK > 1 %}const SPLIT_TILES: u32 = {{ splitTiles }}u;{% endif %}var<workgroup> tile_A: array<f32, {{ tileRows }} * 32>;var<workgroup> tile_B: array<f32, 64 * 32>;73 unmodified linesfn storeCol(offset: u32, col_base: u32, row: u32, cc: u32, slot: u32, src_slot: u32) {let c = cc + slot * 8u;if (col_base + c < N) {{% if storeBias %}y[offset + row * N + c] = {{ storeScalar }}(scratch[src_slot][slot][row * 8u + cc] + f32(bias[col_base + c]));{% else %}y[offset + row * N + c] = {{ storeScalar }}(scratch[src_slot][slot][row * 8u + cc]);{% endif %}}}8 unmodified lines}}{% set accScalar = "f32" %}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {// WGSL initializes workgroup variables to zero before this entry point.let population = subgroupBallot(true);let populationCount = countOneBits(population.x) + countOneBits(population.y)+ countOneBits(population.z) + countOneBits(population.w);var claimed = 0u;if (subgroupElect()) {claimed = atomicAdd(&matrixRoleCount, 1u);if (width != requiredWidth || populationCount != requiredWidth) {atomicStore(&matrixRejected, 1u);}}// Reconverge every invocation before broadcasting the elected claim.workgroupBarrier();return subgroupBroadcastFirst(claimed);}fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {if (localIndex == 0u) {matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u&& atomicLoad(&matrixRoleCount) == bankCount);}// The uniform load both publishes the leader's decision and gives the// compiler a workgroup-uniform condition for the barrier-containing arms.return workgroupUniformLoad(&matrixAccepted) != 0u;}// The portable arm owns two result components per logical 32-invocation group.// Staging casts, 8-wide K steps, barriers and the epilogue match the// subgroup-matrix arm.var<private> matrixSoftwareLane: u32;fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,acc: vec2<f32>) -> vec2<f32> {var value = acc;for (var k = 0u; k < 8u; k += 1u) {value = fma(vec2<f32>(lhs[k]), rhs[k], value);}return value;}{% macro matrixType(software, kind, scalar) %}{% if software %}{% if kind == "left" %}array<f32, 8>{% elif kind == "right" %}array<vec2<f32>, 8>{% else %}vec2<{{ scalar }}>{% endif %}{% else %}subgroup_matrix_{{ kind }}<{{ scalar }}, 8, 8>{% endif %}{% endmacro %}{% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}{% if kind == "left" %}array<f32, 8>({% for k in range(8) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}(matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u{% else %}{{ k }}u * ({{ stride }}) + matrixSoftwareLane / 4u{% endif %}]){{ "," if k < 7 else "" }}{% endfor %}){% else %}array<vec2<f32>, 8>({% for k in range(8) %}vec2<f32>({% for h in range(2) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}{{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u{% else %}((matrixSoftwareLane % 4u) * 2u + {{ h }}u) * ({{ stride }}) + {{ k }}u{% endif %}]){{ "," if h == 0 else "" }}{% endfor %}){{ "," if k < 7 else "" }}{% endfor %}){% endif %}{% endif %}{% endmacro %}{% macro matrixMma(software, scalar, lhs, rhs, acc) %}{% if not software %}subgroupMatrixMultiplyAccumulate({{ lhs }}, {{ rhs }}, {{ acc }}){% else %}vec2<{{ scalar }}>(matrixSoftwareMultiplyAccumulate({{ lhs }}, {{ rhs }}, vec2<f32>({{ acc }}))){% endif %}{% endmacro %}{% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{let matrixPointer = {{ pointer }};let matrixValue = {{ value }};{% for h in range(2) %} (*matrixPointer)[({{ offset }}) + {{ {"row_major": "(matrixSoftwareLane / 4u) * (" ~ stride ~ ") + (matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u", "col_major": "((matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u) * (" ~ stride ~ ") + matrixSoftwareLane / 4u"}[major] }}] = matrixValue.{{ "x" if h == 0 else "y" }};{% endfor %}}{% endif %}{% endmacro %}{% macro matrixKernelBody(matrixSoftware) %}let a_global_base = workgroup_id.y * TILE_ROWS;let b_global_base = workgroup_id.x * TILE_COLS;let subtile_id = matrixRole;let subtile_idx = subtile_id / {{ rowSubtiles }}u;let subtile_idy = subtile_id % {{ rowSubtiles }}u;let base_A = subtile_idy * SUB_ROWS;let base_B = subtile_idx * SUB_COLS;{% for row in [0, 1] %}{% for col in [0, 1, 2, 3] %}var matC{{ row }}{{ col }}: {{ matrixType(matrixSoftware, "result", "f32") }};{% endfor %}{% endfor %}{% if splitK > 1 %}let k_begin = workgroup_id.z * SPLIT_TILES * TILE_K;let k_end = min(K, k_begin + SPLIT_TILES * TILE_K);for (var kidx = k_begin; kidx < k_end; kidx = kidx + TILE_K) {{% else %}for (var kidx = 0u; kidx < K; kidx = kidx + TILE_K) {{% endif %}loadSHMA(a_global_base, kidx, local_idx / 4u, local_idx % 4u);loadSHMB(b_global_base, kidx, local_idx / {{ bLoadsPerRow }}u, local_idx % {{ bLoadsPerRow }}u);workgroupBarrier();2 unmodified lines{% set operandScalar = "f32" %}{% set directInputs = false %}let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;{% for r in range(2) %}var matA{{ r }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ ("w" if directInputs else "tile_A"), ("matrix_a_offset" ~ (" + 8u * " ~ ("K" if directInputs else "TILE_K") if r > 0 else "")), "K" if directInputs else "TILE_K") }};{% endfor %}{% set storageB = "" %}let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;{% for c in range(4) %}var matB{{ c }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {% set stepBPointer %}&{{ storageB if storageB else "tile_B" }}{% endset %}{{ matrixLoad(matrixSoftware, "right", operandScalar, ("row_major" if storageB else "col_major"), stepBPointer, ("matrix_b_offset" ~ (" + " ~ (c * 8) ~ "u" ~ (" * TILE_K" if not storageB else "") if c > 0 else "")), "N" if storageB else "TILE_K") }};{% endfor %}matC00 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB0", "matC00") }};matC01 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB1", "matC01") }};matC02 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB2", "matC02") }};matC03 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB3", "matC03") }};matC10 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB0", "matC10") }};matC11 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB1", "matC11") }};matC12 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB2", "matC12") }};matC13 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB3", "matC13") }};}workgroupBarrier();5 unmodified lines// clobbering the first's still-in-flight readback when a partial final M-tile// diverges storeOutput's guard. Without both barriers the last valid row can be corrupted.{% for col in [0, 1, 2, 3] %}{{ matrixStore(matrixSoftware, "row_major", "&scratch[subtile_id][" ~ (col) ~ "]", "0u", "matC0" ~ (col), "8u") }}{% endfor %}workgroupBarrier();let row = sg_id / 4u;let col = (sg_id % 4u) * 2u;let col_base = b_global_base + base_B;var matrix_c_offset = {{ "workgroup_id.z * M * N + " if splitK > 1 else "" }}(a_global_base + base_A) * N + col_base;var row_limit = i32(M) - i32(a_global_base + base_A);storeOutput(matrix_c_offset, col_base, row, col, subtile_id, row_limit);workgroupBarrier();{% for col in [0, 1, 2, 3] %}{{ matrixStore(matrixSoftware, "row_major", "&scratch[subtile_id][" ~ (col) ~ "]", "0u", "matC1" ~ (col), "8u") }}{% endfor %}workgroupBarrier();matrix_c_offset = matrix_c_offset + 8u * N;row_limit = i32(M) - i32(a_global_base + base_A + 8u);storeOutput(matrix_c_offset, col_base, row, col, subtile_id, row_limit);{% endmacro %}{% macro matrix_topology_dispatch(groupSize, withSubgroupLane) %}let matrixRole = claimMatrixSubgroupRole(matrixPhysicalWidth, 32u);let matrixAcceptedHere = matrixTopologyAccepted(local_idx, {{ groupSize }} / 32u);matrixSoftwareLane = local_idx % 32u;if (matrixAcceptedHere) {let sg_id = matrixPhysicalLane;{{ matrixKernelBody(false) }}} else {let matrixRole = local_idx / 32u;let sg_id = local_idx % 32u;{{ matrixKernelBody(true) }}}{%- endmacro -%}@compute @workgroup_size({{ workgroupSize }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) workgroup_id: vec3<u32>,@builtin(local_invocation_index) local_idx: u32,@builtin(subgroup_size) matrixPhysicalWidth: u32,@builtin(subgroup_invocation_id) matrixPhysicalLane: u32) {{{ matrix_topology_dispatch(workgroupSize ~ "u", true) }}}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{%- set PLANES = splitPlanes | default(false) -%}{{ env.wgsl.resourceDeclarations }}
const K: u32 = {{ splitK }}u;
var<workgroup> lane_peak: array<f32, 64>;
@compute @workgroup_size(64, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32) { // One row per workgroup. let row = wid.x + wid.y * {{ DISPATCH_FOLD_WIDTH }}u; let live = row < params.M; var peak = 0.0; if (live) { for (var k = tid; k < K; k += 64u) { peak = max(peak, abs(a[row * K + k])); } } lane_peak[tid] = peak; workgroupBarrier(); if (!live) { return; } var rowPeak = 0.0; for (var i = 0u; i < 64u; i++) { rowPeak = max(rowPeak, lane_peak[i]); } // rowPeak = f * 2^e with f in [0.5, 1): scaling by 2^(14 - e) puts it in [2^13, 2^14). let exponent = clamp(frexp(rowPeak).exp, -112, 128); let scale = ldexp(1.0, 14 - exponent); if (tid == 0u) { row_scales[row] = ldexp(1.0, exponent - 14); } for (var k = tid; k < K; k += 64u) { let x = a[row * K + k] * scale; // Clearing the low 13 mantissa bits leaves a value a half holds exactly. let high = bitcast<f32>(bitcast<u32>(x) & 0xffffe000u);{% if PLANES %} a_split[row * K + k] = f16(high); a_split[params.M * K + row * K + k] = f16(x - high);{% else %} a_split[row * 3u * K + k] = f16(high); a_split[row * 3u * K + K + k] = f16(high); a_split[row * 3u * K + 2u * K + k] = f16(x - high);{% endif %} }}123456782 unmodified lines111213141516171819202122232425262728293031{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}{{ env.wgsl.resourceDeclarations }}const WG: u32 = {{ workgroupSize }}u;2 unmodified lines// codes per stored byte, q4 two nibbles, and q8 is one byte per weight// (blobSize == blockSize). `b` is bound u32-per-byte in every case, so all three// index the stored byte directly.{% macro matmul_nbits_packed_code(fn="packed_weight", buffer="b", kBlocks="params.kBlocks", blobSize="params.blobSize", bits=4) %}fn {{ fn }}(n: u32, block: u32, offset: u32) -> u32 {{% if bits == 2 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 2u);let shift = (byte_index & 3u) * 8u + (offset & 3u) * 2u;return ({{ buffer }}[byte_index >> 2u] >> shift) & 3u;{% elif bits == 4 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 1u);let shift = (byte_index & 3u) * 8u + (offset & 1u) * 4u;return ({{ buffer }}[byte_index >> 2u] >> shift) & 15u;{% else %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + offset;return ({{ buffer }}[byte_index >> 2u] >> ((byte_index & 3u) * 8u)) & 255u;{% endif %}}{% endmacro %}{{ matmul_nbits_packed_code(bits=bits) }}@compute @workgroup_size(WG, 1, 1)1234567892 unmodified lines1213141516171819202122232425262728293031323334{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}{{ env.wgsl.resourceDeclarations }}const WG: u32 = {{ workgroupSize }}u;2 unmodified lines// codes per stored byte, q4 two nibbles, and q8 is one byte per weight// (blobSize == blockSize). `b` is bound u32-per-byte in every case, so all three// index the stored byte directly.{% macro matmul_nbits_packed_code(fn="packed_weight", buffer="b", kBlocks="params.kBlocks", blobSize="params.blobSize", bits=4, vectorWords=false) %}{% set wordIndex = "byte_index >> 4u][(byte_index >> 2u) & 3u" if vectorWords else "byte_index >> 2u" %}fn {{ fn }}(n: u32, block: u32, offset: u32) -> u32 {{% if bits == 2 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 2u);let shift = (byte_index & 3u) * 8u + (offset & 3u) * 2u;return ({{ buffer }}[{{ wordIndex }}] >> shift) & 3u;{% elif bits == 4 %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + (offset >> 1u);let shift = (byte_index & 3u) * 8u + (offset & 1u) * 4u;return ({{ buffer }}[{{ wordIndex }}] >> shift) & 15u;{% else %}let byte_index = (n * {{ kBlocks }} + block) * {{ blobSize }} + offset;return ({{ buffer }}[{{ wordIndex }}] >> ((byte_index & 3u) * 8u)) & 255u;{% endif %}}{% endmacro %}{{ matmul_nbits_packed_code(bits=bits) }}@compute @workgroup_size(WG, 1, 1)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263{"name": "com.microsoft.MatMulNBits","id": "_com_microsoft_matmulnbits_webgpu_544d369","version": 1,"license": "Apache-2.0","backend": { "type": "webgpu" },"digest": {"algorithm": "sha256","files": {"bench.json": "jsZTXUF4MjY52ewIINIKTdgXYZvvFfi+Ch6E3mCRIbo=","manifest.json": "C1+nZAAnjkvjvNZMOCbeF0zCAyPt3GIyqvbRUnz4KJo=","matmul-nbits-dp4a-quantize.wgsl.jinja": "7Ywrm3pRk4HfGeL5D0YcObG/kKLAgpr4dfu9vUJw8SM=","matmul-nbits-gemv-q4.wgsl.jinja": "0NkQ1G4eYRQGokjjMW7XKRvU76j8Dno9mrCBoXzeOc8=","matmul-nbits-q4-dp4a-prefill.wgsl.jinja": "w6qZuxXnJFteFjjDq+HonDn70RMHtPHreWxRtDiPIdU=","matmul-nbits-q4-prefill-tile4x4.wgsl.jinja": "8DVy3szxcxwVItIlEXoioQi2YxDmmd5TCFW4BCYPiCQ=","matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja": "Z22EQeNnROI5Vpy6mNgPK733TkxWXZB9rlp7qKV6fps=","matmul-nbits-q4-prefill-tiled.wgsl.jinja": "RzrALqTo5135awvgG96cJ029Hl8gsQtwujplaGYzcUs=","matmul-nbits-q4-sgmat.wgsl.jinja": "tUpNHvX4uEflOZ1HuFy4dezyL83kWO/5fYlxsHe5yaA=","matmul-nbits.wgsl.jinja": "i+euJpHwxE67Ejb8Pi9XzHDrK3FS/d2nT1odJJxR9rk=","reduce-axis0-splitk-combine.wgsl.jinja": "6S5tsaqhzGAZ66UOQ8u9LfKIlYeGnWu6B722kLl/auc=","test.json": "xR0ewiJSnSNGdmdIovbtC36Xsm1yv4aC8i3l8CaXdaY="}},"provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },"webgpu": {"manifestSpec": "2.1","variants": {"q4_dp4a_prefill": ["matmul-nbits-dp4a-quantize.wgsl.jinja", "matmul-nbits-q4-dp4a-prefill.wgsl.jinja"],"gemv_default_zero": ["matmul-nbits-gemv-q4.wgsl.jinja"],"prefill_sgmat_default_zero": ["matmul-nbits-q4-sgmat.wgsl.jinja"],"prefill_tiled_reg_vec4_splitk_default_zero": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja", "reduce-axis0-splitk-combine.wgsl.jinja"],"prefill_tiled_reg_vec4_default_zero": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja"],"prefill_tiled_reg_default_zero": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja"],"prefill_tiled_default_zero": ["matmul-nbits-q4-prefill-tiled.wgsl.jinja"],"prefill_tile4x4_default_zero": ["matmul-nbits-q4-prefill-tile4x4.wgsl.jinja"],"default_zero": ["matmul-nbits.wgsl.jinja"],"gemv_zero_bias": ["matmul-nbits-gemv-q4.wgsl.jinja"],"prefill_sgmat_zero_bias": ["matmul-nbits-q4-sgmat.wgsl.jinja"],"prefill_tiled_reg_vec4_splitk_zero_bias": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja", "reduce-axis0-splitk-combine.wgsl.jinja"],"prefill_tiled_reg_vec4_zero_bias": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja"],"prefill_tiled_reg_zero_bias": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja"],"prefill_tiled_zero_bias": ["matmul-nbits-q4-prefill-tiled.wgsl.jinja"],"prefill_tile4x4_zero_bias": ["matmul-nbits-q4-prefill-tile4x4.wgsl.jinja"],"zero_bias": ["matmul-nbits.wgsl.jinja"],"gemv_zero_only": ["matmul-nbits-gemv-q4.wgsl.jinja"],"prefill_sgmat_zero_only": ["matmul-nbits-q4-sgmat.wgsl.jinja"],"prefill_tiled_reg_vec4_splitk_zero_only": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja", "reduce-axis0-splitk-combine.wgsl.jinja"],"prefill_tiled_reg_vec4_zero_only": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja"],"prefill_tiled_reg_zero_only": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja"],"prefill_tiled_zero_only": ["matmul-nbits-q4-prefill-tiled.wgsl.jinja"],"prefill_tile4x4_zero_only": ["matmul-nbits-q4-prefill-tile4x4.wgsl.jinja"],"zero_only": ["matmul-nbits.wgsl.jinja"],"gemv_bias_only": ["matmul-nbits-gemv-q4.wgsl.jinja"],"prefill_sgmat_bias_only": ["matmul-nbits-q4-sgmat.wgsl.jinja"],"prefill_tiled_reg_vec4_splitk_bias_only": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja", "reduce-axis0-splitk-combine.wgsl.jinja"],"prefill_tiled_reg_vec4_bias_only": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja"],"prefill_tiled_reg_bias_only": ["matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja"],"prefill_tiled_bias_only": ["matmul-nbits-q4-prefill-tiled.wgsl.jinja"],"prefill_tile4x4_bias_only": ["matmul-nbits-q4-prefill-tile4x4.wgsl.jinja"],"bias_only": ["matmul-nbits.wgsl.jinja"]}}}1{"name":"com.microsoft.MatMulNBits","id":"_com_microsoft_matmulnbits_webgpu_43d3033","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"bench.json":"R/G9TZAp2KD+IPBBwglYwC8AXitduq3zFPUb5JL2MQg=","gemm-subgroup-matrix.wgsl.jinja":"FJxBPHRRgMSkLU4KepNdR8kXxIowJRhIMNq1KwuJLVo=","manifest.json":"1wM3k6ho5CpRB3aOTgoZ0gU4a/pp2TfnrNZPdOPZ/eo=","matmul-native16-splitk-reduce.wgsl.jinja":"TjJ2iLNrUNfiO5BLrBZ0xlv8obJ/IT8BpEm3dU32zWw=","matmul-nbits-dp4a-quantize.wgsl.jinja":"7Ywrm3pRk4HfGeL5D0YcObG/kKLAgpr4dfu9vUJw8SM=","matmul-nbits-gemv-clusters.wgsl.jinja":"U3Htb8PDTBX1c2yTmXRZP1MOySRGn6tEbgFsXWr6Jso=","matmul-nbits-gemv-q4.wgsl.jinja":"EEmKZmJ3ePCurw3FnI6BiGo9/2WnTqCvVM/rMNdT/6c=","matmul-nbits-q4-dp4a-prefill.wgsl.jinja":"N3qYnMtQBdVBPnBXkuR0ht79vOvE1Klk/P1P1aCg6W4=","matmul-nbits-q4-native16-packed.wgsl.jinja":"yXdKo4Kef8j0CPEy/xJIIZnlG/dDarHOC7Z4xpsaIOY=","matmul-nbits-q4-prefill-tile4x4.wgsl.jinja":"8DVy3szxcxwVItIlEXoioQi2YxDmmd5TCFW4BCYPiCQ=","matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja":"DsGEdripKQ3+CDsElhwiKw0aaCuXpIO7kSknObtX3dI=","matmul-nbits-q4-prefill-tiled.wgsl.jinja":"wRLVOb+WK2lkd93OJMnCbuknETuy+KA61KPMevlz7XE=","matmul-nbits-q4-range-guarded.wgsl.jinja":"5KryveZ16TKhzgHccVbgi9HTuCdfB+kEJFTP2MlwQ/k=","matmul-nbits-q4-sgmat.wgsl.jinja":"YyoBOjqWqKHFk3QXUdWTd+pM5i8Slnn8HS5W0VvXP4Y=","matmul-nbits-split-f32-rows.wgsl.jinja":"KMT0Bhcwfev4gBQ+ynoJsLYYHQX5W913FHOdTvAGZAw=","matmul-nbits.wgsl.jinja":"uPsWCbpBiVfNr1+rVFBr46leVhRChPNQnGXnTytwCGc=","q4-block-scale.wgsl.jinja":"IrrO+upVNDJeAXcLtf8fghjSQpNFBg5+8XZxfcZ9WCs=","reduce-axis0-splitk-combine.wgsl.jinja":"lXBD5BgB2mwBWfWkKhkW1nA99X6HVIOmZE8FGtMB6uc=","test.json":"FvKJmjIladDhKvVejH+4vDX0JlCVjWd6nAb6BMSRkFs="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385{%- set SG = SGR * SGC -%}{%- set THREADS = SG * 32 -%}{%- set STRIDE = ((BK + 8) / 8) | int -%}{%- set KW = (BK / 8) | int -%}{%- set FRAGS = 4 -%}{%- set SLICE = SLICE_K | default(0) -%}{%- set PLANES = halfPlanes | default(false) -%}{%- set F32OUT = outputF32 | default(false) -%}{%- set A = "planes" if PLANES else "a" -%}{%- set A_ROWS = 2 * BM if PLANES else BM -%}{%- set RESULT_BASE = (A_ROWS + BN) * STRIDE -%}{%- set ASLOTS = ((BM * KW) / THREADS) | int -%}{%- set BSLOTS = ((BN * KW) / THREADS) | int -%}{%- set ZP = hasZero | default(false) -%}{%- set BIAS = (hasBias | default(false)) and not SLICE -%}{%- set PER_STAGE = blockSize == BK -%}{%- macro if_block_end() -%}{% if not PER_STAGE %}if (blockEnd) {{ '{' }}{% else %}{{ '{' }}{% endif %}{%- endmacro -%}{%- macro store_tile(at, lo, hi) -%}{% if SLICE %} y[{{ at }}] = bitcast<vec4<u32>>({{ lo }}); y[{{ at }} + 1u] = bitcast<vec4<u32>>({{ hi }});{% elif F32OUT %} y[{{ at }}] = bitcast<vec4<u32>>({{ lo }}); y[{{ at }} + 1u] = bitcast<vec4<u32>>({{ hi }});{% else %} y[{{ at }}] = vec4<u32>(bitcast<vec2<u32>>(vec4<f16>({{ lo }})), bitcast<vec2<u32>>(vec4<f16>({{ hi }})));{% endif %}{%- endmacro -%}{%- set OUT_AT = "(wid.z * sliceRows * N + row * N + col) / 4u" if SLICE else ("(row * N + col) / 4u" if F32OUT else "(row * N + col) / 8u") -%}{%- set FACTOR = " * factor" if PLANES and not SLICE else "" -%}enable subgroups;enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{{ env.wgsl.resourceDeclarations }}const N: u32 = {{ N }}u;const K: u32 = {{ K }}u;const TILE_M: u32 = {{ BM }}u;const TILE_N: u32 = {{ BN }}u;const TILE_K: u32 = {{ BK }}u;const BLOCK_SIZE: u32 = {{ blockSize }}u;const STRIDE: u32 = {{ STRIDE }}u;{% if PLANES %}const A_LOW: u32 = {{ BM * STRIDE }}u;{% endif %}const B_CODES: u32 = {{ A_ROWS * STRIDE }}u;{% if PLANES %}// A rows, then their remainder rows, then the weight codes, each K-contiguous and padded by// one word, then one stored matrix of sixteen four-word rows per fragment.{% else %}// A rows, then the weight codes, each K-contiguous and padded by one word, then one stored// matrix of sixteen four-word rows per fragment.{% endif %}var<workgroup> stage: array<vec4<u32>, {{ RESULT_BASE + SG * FRAGS * 64 }}>;// Per-column block scales (and scale x zero), double-buffered by block parity so staging the// next block never races the fold of this one.var<workgroup> blockScales: array<vec4<f32>, {{ (2 * BN / 4) | int }}>;{% if ZP %}var<workgroup> blockZeroScales: array<vec4<f32>, {{ (2 * BN / 4) | int }}>;var<workgroup> rowSums: array<f32, {{ 2 * BM }}>;{% endif %}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}
struct Staged { activations: array<vec4<u32>, {{ ASLOTS }}>,{% if PLANES %} low: array<vec4<u32>, {{ ASLOTS }}>,{% endif %} words: array<u32, {{ BSLOTS }}>, scale: vec4<f32>,{% if ZP %} zeroScale: vec4<f32>,{% endif %}};
fn loadStage(rowBase: u32, colBase: u32, kBase: u32, tid: u32, M: u32) -> Staged { var activations: array<vec4<u32>, {{ ASLOTS }}>;{% if PLANES %} var low: array<vec4<u32>, {{ ASLOTS }}>; let lowBase = M * (K / 8u);{% endif %} var words: array<u32, {{ BSLOTS }}>;{% for slot in range(ASLOTS) %} { let flat = tid + {{ slot * THREADS }}u; let row = rowBase + flat / {{ KW }}u; let k = kBase + (flat % {{ KW }}u) * 8u; activations[{{ slot }}] = vec4<u32>(0u);{% if PLANES %} low[{{ slot }}] = vec4<u32>(0u); if (row < M) { activations[{{ slot }}] = planes[(row * K + k) / 8u]; low[{{ slot }}] = planes[lowBase + (row * K + k) / 8u]; }{% else %} if (row < M) { activations[{{ slot }}] = a[(row * K + k) / 8u]; }{% endif %} }{% endfor %}{% for slot in range(BSLOTS) %} { let flat = tid + {{ slot * THREADS }}u; let col = colBase + flat / {{ KW }}u; let k = kBase + (flat % {{ KW }}u) * 8u; words[{{ slot }}] = {{ "0u" if ZP else "0x88888888u" }}; if (col < N) { words[{{ slot }}] = b[col * {{ (K / 8) | int }}u + k / 8u]; } }{% endfor %} var scale = vec4<f32>(0.0);{% if ZP %} var zeroScale = vec4<f32>(0.0);{% endif %} if (tid < {{ (BN / 4) | int }}u) { let col = colBase + tid * 4u; let at = col * {{ kBlocks }}u + kBase / BLOCK_SIZE; if (col < N) { scale = vec4<f32>(f32(scales[at]), f32(scales[at + {{ kBlocks }}u]), f32(scales[at + {{ 2 * kBlocks }}u]), f32(scales[at + {{ 3 * kBlocks }}u]));{% if ZP %} zeroScale = scale * vec4<f32>(f32(zero_points[at]), f32(zero_points[at + {{ kBlocks }}u]), f32(zero_points[at + {{ 2 * kBlocks }}u]), f32(zero_points[at + {{ 3 * kBlocks }}u]));{% endif %} } } return Staged(activations, {{ "low, " if PLANES else "" }}words, scale{{ ", zeroScale" if ZP else "" }});}
{% if ZP %}fn halfSum(word: vec4<u32>) -> f32 { let low = vec4<f32>(vec4<f16>(bitcast<vec2<f16>>(word.x), bitcast<vec2<f16>>(word.y))); let high = vec4<f32>(vec4<f16>(bitcast<vec2<f16>>(word.z), bitcast<vec2<f16>>(word.w))); return dot(low + high, vec4<f32>(1.0));}{% endif %}
fn commitStage(staged: Staged, tid: u32, buf: u32) { let activations = staged.activations;{% if PLANES %} let low = staged.low;{% endif %} let words = staged.words; if (tid < {{ (BN / 4) | int }}u) { blockScales[buf * {{ (BN / 4) | int }}u + tid] = staged.scale;{% if ZP %} blockZeroScales[buf * {{ (BN / 4) | int }}u + tid] = staged.zeroScale;{% endif %} }{% for slot in range(ASLOTS) %} { let flat = tid + {{ slot * THREADS }}u;{% if PLANES %} let at = (flat / {{ KW }}u) * STRIDE + flat % {{ KW }}u; stage[at] = activations[{{ slot }}]; stage[A_LOW + at] = low[{{ slot }}];{% else %} stage[(flat / {{ KW }}u) * STRIDE + flat % {{ KW }}u] = activations[{{ slot }}];{% endif %} }{% endfor %}{% for slot in range(BSLOTS) %} { let flat = tid + {{ slot * THREADS }}u; let word = words[{{ slot }}]; let first = vec4<f16>((vec4<u32>(word) >> vec4<u32>(0u, 4u, 8u, 12u)) & vec4<u32>(15u)){{ "" if ZP else " - vec4<f16>(8.0h)" }}; let second = vec4<f16>((vec4<u32>(word) >> vec4<u32>(16u, 20u, 24u, 28u)) & vec4<u32>(15u)){{ "" if ZP else " - vec4<f16>(8.0h)" }}; stage[B_CODES + (flat / {{ KW }}u) * STRIDE + flat % {{ KW }}u] = vec4<u32>(bitcast<vec2<u32>>(first), bitcast<vec2<u32>>(second)); }{% endfor %}}
fn readHalf(row: u32, k: u32) -> f32 { let word = {{ A }}[(row * K + k) / 8u];{% if PLANES %} let low = planes[params.M * (K / 8u) + (row * K + k) / 8u]; return f32(bitcast<vec2<f16>>(word[(k % 8u) / 2u])[k % 2u]) + f32(bitcast<vec2<f16>>(low[(k % 8u) / 2u])[k % 2u]);{% else %} return f32(bitcast<vec2<f16>>(word[(k % 8u) / 2u])[k % 2u]);{% endif %}}
@compute @workgroup_size({{ THREADS }}, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32, @builtin(subgroup_invocation_id) lane: u32) { let M = params.M; let rowBase = wid.y * TILE_M; let colBase = wid.x * TILE_N;{% if SLICE %} let kBegin = wid.z * {{ SLICE }}u; let kEnd = min(K, kBegin + {{ SLICE }}u); let sliceRows = (M + 15u) / 16u * 16u;{% else %} let kBegin = 0u; let kEnd = K;{% endif %} let role = min(claimMatrixSubgroupRole(width, 32u), {{ SG - 1 }}u); let nativeTopology = matrixTopologyAccepted(tid, {{ SG }}u); if (nativeTopology) { let subgroupRow = (role / {{ SGC }}u) * {{ FR * 16 }}u; let subgroupCol = (role % {{ SGC }}u) * {{ FC * 16 }}u; let resultBase = {{ RESULT_BASE }}u + role * {{ FRAGS * 64 }}u;{% for r in range(FR) %}{% for c in range(FC) %} var run{{ r }}_{{ c }}_0 = vec4<f32>(0.0); var run{{ r }}_{{ c }}_1 = vec4<f32>(0.0);{% if not PER_STAGE %} var block{{ r }}_{{ c }} = subgroup_matrix_result<f32, 16, 16>(0.0);{% endif %}{% endfor %}{% endfor %}{% if ZP %} var rowPart = array<f32, {{ ASLOTS }}>({% for slot in range(ASLOTS) %}0.0{{ ", " if not loop.last else "" }}{% endfor %});{% endif %} // An empty slice (kBegin >= K) issues one prefetch that is never staged; // its partial stays zero. var staged = loadStage(rowBase, colBase, kBegin, tid, M); for (var kk = kBegin; kk < kEnd; kk += TILE_K) { let buf = (kk / BLOCK_SIZE) % 2u;{% if not PER_STAGE %} let blockEnd = (kk + TILE_K) % BLOCK_SIZE == 0u;{% endif %} commitStage(staged, tid, buf);{% if ZP %} // The four lanes staging one row's eight-half chunks sum the block for that row.{% for slot in range(ASLOTS) %} rowPart[{{ slot }}] += halfSum(staged.activations[{{ slot }}]){{ " + halfSum(staged.low[" ~ slot ~ "])" if PLANES else "" }};{% endfor %} {{ if_block_end() }}{% for slot in range(ASLOTS) %} { var total = rowPart[{{ slot }}] + subgroupShuffleXor(rowPart[{{ slot }}], 1u); total = total + subgroupShuffleXor(total, 2u); let flat = tid + {{ slot * THREADS }}u; if (flat % {{ KW }}u == 0u) { rowSums[buf * {{ BM }}u + flat / {{ KW }}u] = total; } rowPart[{{ slot }}] = 0.0; }{% endfor %} }{% endif %} workgroupBarrier(); // The next stage's global words load while this stage's products run. if (kk + TILE_K < kEnd) { staged = loadStage(rowBase, colBase, kk + TILE_K, tid, M); }{% if PER_STAGE %}{% for r in range(FR) %}{% for c in range(FC) %} var block{{ r }}_{{ c }} = subgroup_matrix_result<f32, 16, 16>(0.0);{% endfor %}{% endfor %}{% endif %}{% for step in range(0, KW, 2) %} {{% if PLANES %}{% for c in range(FC) %} let right{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, col_major>( &stage, B_CODES + (subgroupCol + {{ c * 16 }}u) * STRIDE + {{ step }}u, STRIDE);{% endfor %}{% for plane in ["0u", "A_LOW"] %}{% for r in range(FR) %} let left{{ r }}{{ "h" if plane == "0u" else "l" }} = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>( &stage, {{ plane }} + (subgroupRow + {{ r * 16 }}u) * STRIDE + {{ step }}u, STRIDE);{% endfor %}{% for r in range(FR) %}{% for c in range(FC) %} block{{ r }}_{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ r }}{{ "h" if plane == "0u" else "l" }}, right{{ c }}, block{{ r }}_{{ c }});{% endfor %}{% endfor %}{% endfor %}{% else %}{% for r in range(FR) %} let left{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>( &stage, (subgroupRow + {{ r * 16 }}u) * STRIDE + {{ step }}u, STRIDE);{% endfor %}{% for c in range(FC) %} let right{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, col_major>( &stage, B_CODES + (subgroupCol + {{ c * 16 }}u) * STRIDE + {{ step }}u, STRIDE);{% endfor %}{% for r in range(FR) %}{% for c in range(FC) %} block{{ r }}_{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ r }}, right{{ c }}, block{{ r }}_{{ c }});{% endfor %}{% endfor %}{% endif %} }{% endfor %} {{ if_block_end() }}{% for r in range(FR) %}{% for c in range(FC) %} subgroupMatrixStore<row_major>(&stage, resultBase + {{ (r * FC + c) * 64 }}u, block{{ r }}_{{ c }}, 4u);{% endfor %}{% endfor %} } workgroupBarrier(); {{ if_block_end() }} // Each lane folds row lane / 2, columns (lane % 2) * 8 .. + 8 of every fragment.{% for r in range(FR) %}{% if ZP %} let rowSum{{ r }} = vec4<f32>(rowSums[buf * {{ BM }}u + subgroupRow + {{ r * 16 }}u + lane / 2u]);{% endif %}{% for c in range(FC) %} { let word = resultBase + {{ (r * FC + c) * 64 }}u + (lane / 2u) * 4u + (lane % 2u) * 2u; let scaleAt = buf * {{ (BN / 4) | int }}u + (subgroupCol + {{ c * 16 }}u + (lane % 2u) * 8u) / 4u; run{{ r }}_{{ c }}_0 = fma(bitcast<vec4<f32>>(stage[word]), blockScales[scaleAt], run{{ r }}_{{ c }}_0); run{{ r }}_{{ c }}_1 = fma(bitcast<vec4<f32>>(stage[word + 1u]), blockScales[scaleAt + 1u], run{{ r }}_{{ c }}_1);{% if ZP %} run{{ r }}_{{ c }}_0 = fma(-blockZeroScales[scaleAt], rowSum{{ r }}, run{{ r }}_{{ c }}_0); run{{ r }}_{{ c }}_1 = fma(-blockZeroScales[scaleAt + 1u], rowSum{{ r }}, run{{ r }}_{{ c }}_1);{% endif %}{% if not PER_STAGE %} block{{ r }}_{{ c }} = subgroup_matrix_result<f32, 16, 16>(0.0);{% endif %} }{% endfor %}{% endfor %} } }{% for r in range(FR) %}{% if FACTOR %} let factor{{ r }} = row_factor[min(rowBase + subgroupRow + {{ r * 16 }}u + lane / 2u, M - 1u)];{% endif %}{% for c in range(FC) %} { let row = rowBase + subgroupRow + {{ r * 16 }}u + lane / 2u; let col = colBase + subgroupCol + {{ c * 16 }}u + (lane % 2u) * 8u; if (row < M && col + 7u < N) {{% if BIAS or FACTOR %} let lo = run{{ r }}_{{ c }}_0{{ FACTOR ~ r if FACTOR else "" }}{% if BIAS %} + vec4<f32>(f32(bias[col]), f32(bias[col + 1u]), f32(bias[col + 2u]), f32(bias[col + 3u])){% endif %}; let hi = run{{ r }}_{{ c }}_1{{ FACTOR ~ r if FACTOR else "" }}{% if BIAS %} + vec4<f32>(f32(bias[col + 4u]), f32(bias[col + 5u]), f32(bias[col + 6u]), f32(bias[col + 7u])){% endif %};{{ store_tile(OUT_AT, "lo", "hi") }}{% else %}{{ store_tile(OUT_AT, "run" ~ r ~ "_" ~ c ~ "_0", "run" ~ r ~ "_" ~ c ~ "_1") }}{% endif %} } }{% endfor %}{% endfor %} } else { // An unproven subgroup layout: float32 dequantization in K order. for (var slot = tid; slot < {{ ((BM * BN) / 8) | int }}u; slot += {{ THREADS }}u) { let row = rowBase + slot / {{ (BN / 8) | int }}u; let col = colBase + (slot % {{ (BN / 8) | int }}u) * 8u; if (row < M && col + 7u < N) { var lo = vec4<f32>(0.0); var hi = vec4<f32>(0.0); for (var k = kBegin; k < kEnd; k += 1u) { let left = readHalf(row, k); var w = array<f32, 8>(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); for (var component = 0u; component < 8u; component += 1u) { let at = (col + component) * {{ kBlocks }}u + k / BLOCK_SIZE; let code = (b[(col + component) * {{ (K / 8) | int }}u + k / 8u] >> ((k % 8u) * 4u)) & 15u; w[component] = (f32(code) - {{ "f32(zero_points[at])" if ZP else "8.0" }}) * f32(scales[at]); } lo = fma(vec4<f32>(left), vec4<f32>(w[0], w[1], w[2], w[3]), lo); hi = fma(vec4<f32>(left), vec4<f32>(w[4], w[5], w[6], w[7]), hi); }{% if FACTOR %} lo = lo * row_factor[row]; hi = hi * row_factor[row];{% endif %}{% if BIAS %} lo = lo + vec4<f32>(f32(bias[col]), f32(bias[col + 1u]), f32(bias[col + 2u]), f32(bias[col + 3u])); hi = hi + vec4<f32>(f32(bias[col + 4u]), f32(bias[col + 5u]), f32(bias[col + 6u]), f32(bias[col + 7u]));{% endif %}{{ store_tile(OUT_AT, "lo", "hi") }} } } }}1234567891070 unmodified lines818283848586878889909192// Pass 2 of the split-K column-wise reduction. One invocation per output column// folds the segment partials and applies the selected reduction's final step.// Segments are folded in ascending order for deterministic results. This order// differs from the single-pass reduction but remains within the f32 tolerance.{% set yv = "f16(" if outputF16 else "" %}{% set vy = ")" if outputF16 else "" %}{{ env.wgsl.resourceDeclarations }}{% macro wgsl_minmax_identity(name, op, scalar="f32") %}/* Exact {{ op }} reduction identity. WGSL rejects infinity during constant* evaluation, so an f32 identity is constructed from its IEEE-754 bits. */70 unmodified lines{% endif %}}{% if addBias %}total = total + f32(bias[col % BIAS_COLS]);{% endif %}{% if op == "l2" %}y[col] = {{ yv }}sqrt(total){{ vy }};{% elif op == "logsum" %}y[col] = {{ yv }}log(total){{ vy }};{% elif op == "mean" %}y[col] = {{ yv }}total / f32(params.rows){{ vy }};{% else %}1234567891011121314151617181920212223242570 unmodified lines96979899100101102103104105106107// Pass 2 of the split-K column-wise reduction. One invocation per output column// folds the segment partials and applies the selected reduction's final step.// Segments are folded in ascending order for deterministic results.{% set biasIndex = "col % BIAS_COLS" %}{% set yv = "f16(" if outputF16 else "" %}{% set vy = ")" if outputF16 else "" %}{{ env.wgsl.resourceDeclarations }}{% if op == "logsum" %}// log() returns an indeterminate value outside (0, inf), so the IEEE results// for the logarithm of a sum are chosen explicitly: a negative or NaN sum gives// NaN, a zero sum gives -inf, and +inf stays +inf. The sum is classified by its// bits because a value != value test may be folded away, and the special values// are built from those bits because a constant infinity or NaN does not compile.fn log_of_sum(total: f32) -> f32 {let bits = bitcast<u32>(total);let magnitude = bits & 0x7fffffffu;let defined = select(log(total), total, magnitude == 0x7f800000u);let zero_or_defined = select(defined, bitcast<f32>(bits | 0xff800000u), magnitude == 0u);return select(zero_or_defined, bitcast<f32>(bits | 0x7fc00000u), magnitude > 0x7f800000u || bits > 0x80000000u);}{% endif %}{% macro wgsl_minmax_identity(name, op, scalar="f32") %}/* Exact {{ op }} reduction identity. WGSL rejects infinity during constant* evaluation, so an f32 identity is constructed from its IEEE-754 bits. */70 unmodified lines{% endif %}}{% if addBias %}total = total + f32(bias[{{ biasIndex }}]);{% endif %}{% if op == "l2" %}y[col] = {{ yv }}sqrt(total){{ vy }};{% elif op == "logsum" %}y[col] = {{ yv }}log_of_sum(total){{ vy }};{% elif op == "mean" %}y[col] = {{ yv }}total / f32(params.rows){{ vy }};{% else %}
README.md+61-26
build/webgpu/bench.json+1174
build/webgpu/gemm-subgroup-matrix.wgsl.jinjaAdded+287
build/webgpu/manifest.json
build/webgpu/matmul-native16-splitk-reduce.wgsl.jinjaAdded+52
build/webgpu/matmul-nbits-gemv-clusters.wgsl.jinjaAdded+114
build/webgpu/matmul-nbits-gemv-q4.wgsl.jinja+24-24
build/webgpu/matmul-nbits-q4-dp4a-prefill.wgsl.jinja+13-1
build/webgpu/matmul-nbits-q4-native16-packed.wgsl.jinjaAdded+282
build/webgpu/matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja+105-48
build/webgpu/matmul-nbits-q4-prefill-tiled.wgsl.jinja+7-5
build/webgpu/matmul-nbits-q4-range-guarded.wgsl.jinjaAdded+488
build/webgpu/matmul-nbits-q4-sgmat.wgsl.jinja+129-27
build/webgpu/matmul-nbits-split-f32-rows.wgsl.jinjaAdded+47
build/webgpu/matmul-nbits.wgsl.jinja+9-6
build/webgpu/metadata.json+1-63
build/webgpu/q4-block-scale.wgsl.jinjaAdded+385
build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja+19-4
build/webgpu/test.json