sync 4385228f788d
Browse filesFiles changed (15)
- README.md+39-65
- build/webgpu/bench.json+35-6
- build/webgpu/integer-pack-columns.wgsl.jinjaAdded+20
- build/webgpu/integer-pack-rows.wgsl.jinjaAdded+16
- build/webgpu/manifest.json
- build/webgpu/matrix-shaped-integer-gemm.wgsl.jinjaAdded+217
- build/webgpu/metadata.json+1-75
- build/webgpu/qattention-attend.wgsl.jinja+702-46
- build/webgpu/qattention-kv-permute.wgsl.jinja+3-2
- build/webgpu/qattention-mask.wgsl.jinja+3-2
- build/webgpu/quant-dp4a-matmul.wgsl.jinja → build/webgpu/qattention-project.wgsl.jinjaRenamed+185-10
- build/webgpu/qattention-qkv-scatter.wgsl.jinja+27-3
- build/webgpu/quant-exact-matrix.wgsl.jinja+97-12
- build/webgpu/subgroup-matrix-gemm.wgsl.jinjaAdded+305
- build/webgpu/test.json
15 unmodified lines16171819202124 unmodified lines4647484950515210 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815 unmodified linesSee the [ONNX Runtime `QAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.QAttention) for the reference semantics.## Inputs| Name | Logical dtype | Rank | Shape | Description | Presence |24 unmodified lines| `do_rotary` | `0` | Rotary position embedding switch. Defaults to `0`, and only `0` is accepted: the reference CPU kernel ignores the attribute, so no reference definition of the rotation exists for this operator. || `mask_filter_value` | `-10000` | Value added to the score of a masked-out key. Defaults to `-10000.0`. || `num_heads` | — | Number of attention heads; `hidden_size` must be divisible by it. The request must supply it. || `past_present_share_buffer` | — | Declared for schema fidelity. Only `0` is accepted: `past` and `present` are distinct tensors with distinct bindings in every variant of this package, so there is no shared buffer for a non-zero value to name. || `scale` | — | Scale applied to the query-key product. When absent or `0`, `1 / sqrt(head_size)` is used. || `unidirectional` | `0` | When `1`, a token attends only to itself and earlier tokens. Defaults to `0`. A single-token query is never restricted, matching the reference kernel. |10 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `sgmat_plain_mask_izp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_plain_mask_izp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_plain_mask_izp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_plain_mask_izp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_plain_mask_noizp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_plain_mask_noizp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_plain_mask_noizp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_plain_mask_noizp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_plain_nomask_izp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_plain_nomask_izp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_plain_nomask_izp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_plain_nomask_izp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_plain_nomask_noizp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_plain_nomask_noizp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_plain_nomask_noizp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_plain_nomask_noizp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_present_mask_izp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_present_mask_izp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_present_mask_izp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_present_mask_izp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_present_mask_noizp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_present_mask_noizp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_present_mask_noizp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_present_mask_noizp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_present_nomask_izp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_present_nomask_izp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_present_nomask_izp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_present_nomask_izp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_present_nomask_noizp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_present_nomask_noizp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_present_nomask_noizp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_present_nomask_noizp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_past_mask_izp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_past_mask_izp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_past_mask_izp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_past_mask_izp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_past_mask_noizp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_past_mask_noizp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_past_mask_noizp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_past_mask_noizp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_past_nomask_izp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_past_nomask_izp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_past_nomask_izp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_past_nomask_izp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_past_nomask_noizp_wzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_past_nomask_noizp_wzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_past_nomask_noizp_nowzp` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed_past_nomask_noizp_nowzp` — Projects QKV with the packed 8-bit integer dot product (portable helpers where the language feature is absent), then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.## 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- [`qattention-attend.wgsl.jinja`](build/webgpu/qattention-attend.wgsl.jinja)- [`qattention-kv-permute.wgsl.jinja`](build/webgpu/qattention-kv-permute.wgsl.jinja)- [`qattention-mask.wgsl.jinja`](build/webgpu/qattention-mask.wgsl.jinja)- [`qattention-qkv-scatter.wgsl.jinja`](build/webgpu/qattention-qkv-scatter.wgsl.jinja)- [`quant-dp4a-matmul.wgsl.jinja`](build/webgpu/quant-dp4a-matmul.wgsl.jinja)- [`quant-exact-matrix.wgsl.jinja`](build/webgpu/quant-exact-matrix.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.QAttention", { version: 1 });const { output } = await kernel({input: { data: inputData, shape: [1, 2, 4] },weight: { data: weightData, shape: [4, 12] },bias: { data: biasData, shape: [12] },input_scale: { data: input_scaleData, shape: [1] },weight_scale: { data: weight_scaleData, shape: [1] },}, {attrs: { num_heads: 2 },});```15 unmodified lines1617181920212223242524 unmodified lines5051525354555610 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113215 unmodified linesSee the [ONNX Runtime `QAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.QAttention) for the reference semantics.## Differences from the ONNX Runtime spec- Attribute `mask_filter_value`: Sets the value padded keys receive; it has no effect when no key is padded.## Inputs| Name | Logical dtype | Rank | Shape | Description | Presence |24 unmodified lines| `do_rotary` | `0` | Rotary position embedding switch. Defaults to `0`, and only `0` is accepted: the reference CPU kernel ignores the attribute, so no reference definition of the rotation exists for this operator. || `mask_filter_value` | `-10000` | Value added to the score of a masked-out key. Defaults to `-10000.0`. || `num_heads` | — | Number of attention heads; `hidden_size` must be divisible by it. The request must supply it. || `past_present_share_buffer` | — | Kept to match the ONNX Runtime schema. Only `0` is accepted: `past` and `present` are distinct tensors with distinct bindings in every variant of this package, so there is no shared buffer for a non-zero value to name. || `scale` | — | Scale applied to the query-key product. When absent or `0`, `1 / sqrt(head_size)` is used. || `unidirectional` | `0` | When `1`, a token attends only to itself and earlier tokens. Defaults to `0`. A single-token query is never restricted, matching the reference kernel. |10 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `sgmat` — Projects QKV with exact integer products through bounded float32 matrix partials, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `packed` — Computes exact int32 QKV projections with packed byte dot products or tiled, centered byte operands. Dequantizes and scatters the projections into the head-padded buffers used by the attention pass.- `tiled_i8` — Projects QKV with the general 8-bit subgroup-matrix GEMM over byte-packed input and weight, then dequantizes and scatters into the head-padded working buffers the flash scoring pass reads.- `sgmat_integer_16x16x16` — Experimental `16x16x16` unsigned-byte matrices project QKV with exact `int32` zero-point correction. The mask, dequantization, cache and attention passes are shared with the other variants. If the subgroups are not laid out as expected, the kernel uses plain integer arithmetic instead.- `sgmat_integer_16x16x32` — Experimental `16x16x32` unsigned-byte matrices project QKV with exact `int32` zero-point correction. The mask, dequantization, cache and attention passes are shared with the other variants. If the subgroups are not laid out as expected, the kernel uses plain integer arithmetic instead.- `sgmat_integer_16x8x32` — Experimental `16x8x32` unsigned-byte matrices project QKV with exact `int32` zero-point correction. The mask, dequantization, cache and attention passes are shared with the other variants. If the subgroups are not laid out as expected, the kernel uses plain integer arithmetic instead.## Device requirementsSome implementation variants require `subgroup-matrix` 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.QAttention/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/test.json) — correctness cases- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/bench.json) — benchmark cases- [`integer-pack-columns.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/integer-pack-columns.wgsl.jinja)- [`integer-pack-rows.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/integer-pack-rows.wgsl.jinja)- [`matrix-shaped-integer-gemm.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/matrix-shaped-integer-gemm.wgsl.jinja)- [`qattention-attend.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/qattention-attend.wgsl.jinja)- [`qattention-kv-permute.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/qattention-kv-permute.wgsl.jinja)- [`qattention-mask.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/qattention-mask.wgsl.jinja)- [`qattention-project.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/qattention-project.wgsl.jinja)- [`qattention-qkv-scatter.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/qattention-qkv-scatter.wgsl.jinja)- [`quant-exact-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/quant-exact-matrix.wgsl.jinja)- [`subgroup-matrix-gemm.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QAttention/blob/v1/build/webgpu/subgroup-matrix-gemm.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.QAttention", { version: 1 });const inputData = new Uint8Array(4);const weightData = new Int8Array(48);const biasData = Float32Array.of(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);const input_scaleData = Float32Array.of(1);const weight_scaleData = Float32Array.of(1);const { output } = await kernel({input: { data: inputData, shape: [1, 1, 4] },weight: { data: weightData, shape: [4, 12] },bias: { data: biasData, shape: [12] },input_scale: { data: input_scaleData, shape: [1] },weight_scale: { data: weight_scaleData, shape: [1] },}, {attrs: { num_heads: 1 },});console.log({ output });```
12345678910163 unmodified lines174175176177178179{"tunableSpace": {"DP4A_TILE_M": [8, 16, 32, 64],"DP4A_TILE_N": [32, 64, 128],"DP4A_K_TILE_WORDS": [8, 16, 32],"ATTEND_WORKGROUP": [32, 64, 128, 256]},"cases": [{"name": "qattention-bert-b1-s128",163 unmodified lines},"provenance": { "model": "all-MiniLM-L6-v2 encoder: hidden 384, 12 heads, head size 32" }},{"name": "qattention-bert-decode-p127","preset": "smoke",12345163 unmodified lines169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208{"tunableSpace": { "ATTEND_WORKGROUP": [32, 64, 256] },"cases": [{"name": "qattention-bert-b1-s128",163 unmodified lines},"provenance": { "model": "all-MiniLM-L6-v2 encoder: hidden 384, 12 heads, head size 32" }},{"name": "qattention-minilm-b32-s128-diffuse","preset": "model","vars": { "batch": 32, "seq": 128, "inHidden": 384, "hidden": 384, "heads": 12, "past": 0 },"attrs": { "num_heads": 12 },"inputs": {"input": { "dtype": "uint8", "shape": [32, 128, 384], "dist": "randint", "min": 0, "max": 256, "seed": 101 },"weight": { "dtype": "int8", "shape": [384, 1152], "dist": "randint", "min": -128, "max": 128, "seed": 102 },"bias": { "dtype": "float32", "shape": [1152], "dist": "normal", "scale": 0.3, "seed": 103 },"input_scale": { "dtype": "float32", "shape": [1], "dist": "constant", "value": 0.0005 },"weight_scale": { "dtype": "float32", "shape": [1], "dist": "constant", "value": 0.012 },"mask_index": { "dtype": "int32", "shape": [32], "dist": "randint", "min": 1, "max": 129, "seed": 105 },"input_zero_point": { "dtype": "uint8", "shape": [1], "dist": "constant", "value": 128 },"weight_zero_point": { "dtype": "int8", "shape": [1], "dist": "constant", "value": 1 }},"outputs": { "output": { "dtype": "float32", "shape": [32, 128, 384], "dist": "empty" } },"bench": {"metrics": [{"type": "gflops","name": "projection+attention","value": "2 * args.batch * args.seq * args.inHidden * 3 * args.hidden + 4 * args.batch * args.hidden * args.seq * (args.past + args.seq)"},{"type": "bandwidth","name": "operands","value": "args.inHidden * 3 * args.hidden * 4 + args.batch * args.seq * args.inHidden * 4 + args.batch * args.seq * args.hidden * 4"}]},"provenance": {"model": "MiniLM encoder geometry with a smaller activation scale to exercise diffuse attention weights."}},{"name": "qattention-bert-decode-p127","preset": "smoke",
1234567891011121314151617181920{{ env.wgsl.resourceDeclarations }}const BYTE_FLIP: u32 = {{ "0x80808080u" if bUnsigned else "0u" }};
@compute @workgroup_size(256, 1, 1)fn main(@builtin(global_invocation_id) gid: vec3<u32>) { let i = gid.x; if (i >= pack_params.count) { return; } let n = i % pack_params.N; let kv = i / pack_params.N; var words = vec4<u32>(); for (var w = 0u; w < 4u; w++) { var word = 0u; for (var j = 0u; j < 4u; j++) { let k = kv * 16u + w * 4u + j; word |= (bitcast<u32>(src[k * pack_params.N + n]) & 0xffu) << (8u * j); } words[w] = word ^ BYTE_FLIP; } dst[n * (pack_params.K / 16u) + kv] = words;}12345678910111213141516{{ env.wgsl.resourceDeclarations }}const BYTE_FLIP: u32 = {{ "0x80808080u" }};
fn packBytes(v: vec4<u32>) -> u32 { let b = v & vec4<u32>(0xffu); return (b.x | (b.y << 8u) | (b.z << 16u) | (b.w << 24u)) ^ BYTE_FLIP;}
@compute @workgroup_size(256, 1, 1)fn main(@builtin(global_invocation_id) gid: vec3<u32>) { let i = gid.x; if (i >= pack_params.count) { return; } let s = i * 4u; dst[i] = vec4<u32>(packBytes(bitcast<vec4<u32>>(src[s])), packBytes(bitcast<vec4<u32>>(src[s + 1u])), packBytes(bitcast<vec4<u32>>(src[s + 2u])), packBytes(bitcast<vec4<u32>>(src[s + 3u])));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217{% set WIDTH = integerSubgroupWidth | default(32) %}{% set GROUPS = (128 / WIDTH) | int %}{% set OWNED = (WIDTH / 32) | int %}enable subgroups;enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{{ env.wgsl.resourceDeclarations }}fn read_a(index: u32) -> i32 { return i32(a[index]);}
fn read_b(index: u32) -> i32 { {% if bUnsigned %} return i32(b[index]); {% else %} return b[index]; {% endif %}}{% macro quant_read_scalar_zero(fn_name, buffer_name, is_unsigned, present=true) %}fn {{ fn_name }}() -> i32 { {% if is_unsigned %} return i32({{ buffer_name }}[0]); {% else %} return {{ buffer_name }}[0]; {% endif %}}{% endmacro %}{% macro quant_read_column_zero(fn_name, buffer_name, is_unsigned, present=true, per_column=false, param_name="col", return_type="i32") %}fn {{ fn_name }}({% if per_column %}{{ param_name }}: u32{% endif %}) -> {{ return_type }} { {% if per_column %} {% if is_unsigned %} return i32({{ buffer_name }}[{{ param_name }}]); {% else %} return {{ buffer_name }}[{{ param_name }}]; {% endif %} {% else %} {% if is_unsigned %} return i32({{ buffer_name }}[0]); {% else %} return {{ buffer_name }}[0]; {% endif %} {% endif %}}{% endmacro %}{% if hasAZero %}{{ quant_read_scalar_zero("read_a_zero", "a_zero_point", aUnsigned) }}{% endif %}{% if hasBZero %}{{ quant_read_column_zero("read_b_zero", "b_zero_point", bUnsigned, true, bZeroPerColumn) }}{% endif %}const TILE_M: u32 = 32u;const TILE_N: u32 = {{ integerMatrixN * 2 }}u;const TILE_K: u32 = 32u;var<workgroup> tileA: array<{{ integerBackingScalar }}, 256>;var<workgroup> tileB: array<{{ integerBackingScalar }}, {{ (32 * integerMatrixN * 2 / 4) | int }}>;{% if hasBZero %}var<workgroup> rowSums: array<i32, 32>;{% endif %}{% if hasAZero %}var<workgroup> colSums: array<i32, {{ integerMatrixN * 2 }}>;{% endif %}var<workgroup> tileC: array<{{ integerAccumulatorScalar }}, {{ 32 * integerMatrixN * 2 }}>;// 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;}
fn unpackByte(word: {{ integerBackingScalar }}, byte: u32) -> i32 { let bits = (bitcast<u32>(word) >> (byte * 8u)) & 255u; return i32(bits);}fn readTileA(index: u32) -> i32 { return unpackByte(tileA[index / 4u], index % 4u); }fn readTileB(index: u32) -> i32 { return unpackByte(tileB[index / 4u], index % 4u); }
fn loadTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) { for (var word = tid; word < TILE_M * TILE_K / 4u; word += 128u) { let row = rowBase + word / (TILE_K / 4u); let k = kBase + (word % (TILE_K / 4u)) * 4u; var packed = 0u; for (var byte = 0u; byte < 4u; byte++) { if (row < params.M && k + byte < params.K) { packed |= (bitcast<u32>(read_a(row * params.K + k + byte)) & 255u) << (byte * 8u); } } tileA[word] = bitcast<{{ integerBackingScalar }}>(packed); } for (var word = tid; word < TILE_K * TILE_N / 4u; word += 128u) { let k = kBase + word / (TILE_N / 4u); let col = colBase + (word % (TILE_N / 4u)) * 4u; var packed = 0u; for (var byte = 0u; byte < 4u; byte++) { if (k < params.K && col + byte < params.N) { packed |= (bitcast<u32>(read_b(k * params.N + col + byte)) & 255u) << (byte * 8u); } } tileB[word] = bitcast<{{ integerBackingScalar }}>(packed); }}
{% if hasAZero or hasBZero %}fn accumulateTileSums(tid: u32) {{% if hasBZero %} if (tid < TILE_M) { var sum = 0i; for (var k = 0u; k < TILE_K; k++) { sum += readTileA(tid * TILE_K + k); } rowSums[tid] += sum; }{% endif %}{% if hasAZero %} if (tid < TILE_N) { var sum = 0i; for (var k = 0u; k < TILE_K; k++) { sum += readTileB(k * TILE_N + tid); } colSums[tid] += sum; }{% endif %}}{% endif %}
fn corrected(raw: i32{% if hasBZero %}, row: u32{% endif %}{% if hasAZero %}, col: u32{% endif %}{% if hasBZero and bZeroPerColumn %}, outputCol: u32{% endif %}) -> i32 { var value = raw;{% if hasAZero %} let aZero = read_a_zero(); value -= aZero * colSums[col];{% endif %}{% if hasBZero %} let bZero = read_b_zero({% if bZeroPerColumn %}outputCol{% endif %}); value -= bZero * rowSums[row];{% endif %}{% if hasAZero and hasBZero %} value += bitcast<i32>(params.K * bitcast<u32>(aZero) * bitcast<u32>(bZero));{% endif %} return value;}
@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 rowBase = wid.y * TILE_M; let colBase = wid.x * TILE_N; let role = claimMatrixSubgroupRole(width, {{ WIDTH }}u); let nativeTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u); if (nativeTopology) {{% for slot in range(OWNED) %} let tile{{ slot }} = role + {{ slot * GROUPS }}u; let tileRow{{ slot }} = (tile{{ slot }} / 2u) * 16u; let tileCol{{ slot }} = (tile{{ slot }} % 2u) * {{ integerMatrixN }}u; var acc{{ slot }}: subgroup_matrix_result<{{ integerAccumulatorScalar }}, {{ integerMatrixN }}, 16>;{% endfor %} for (var kk = 0u; kk < params.K; kk += TILE_K) { loadTiles(rowBase, colBase, kk, tid); workgroupBarrier();{% if hasAZero or hasBZero %} accumulateTileSums(tid);{% endif %} for (var step = 0u; step < TILE_K; step += {{ integerMatrixK }}u) {{% for slot in range(OWNED) %} let left{{ slot }} = subgroupMatrixLoad<subgroup_matrix_left<{{ integerOperandScalar }}, {{ integerMatrixK }}, 16>, row_major>( &tileA, (tileRow{{ slot }} * TILE_K + step) / 4u, TILE_K / 4u); let right{{ slot }} = subgroupMatrixLoad<subgroup_matrix_right<{{ integerOperandScalar }}, {{ integerMatrixN }}, {{ integerMatrixK }}>, row_major>( &tileB, (step * TILE_N + tileCol{{ slot }}) / 4u, TILE_N / 4u); acc{{ slot }} = subgroupMatrixMultiplyAccumulate(left{{ slot }}, right{{ slot }}, acc{{ slot }});{% endfor %} } workgroupBarrier(); }{% for slot in range(OWNED) %} subgroupMatrixStore<row_major>(&tileC, tileRow{{ slot }} * TILE_N + tileCol{{ slot }}, acc{{ slot }}, TILE_N);{% endfor %} workgroupBarrier(); for (var flat = tid; flat < TILE_M * TILE_N; flat += 128u) { let row = flat / TILE_N; let col = flat % TILE_N; if (rowBase + row < params.M && colBase + col < params.N) { y[(rowBase + row) * params.N + colBase + col] = corrected(bitcast<i32>(tileC[flat]){% if hasBZero %}, row{% endif %}{% if hasAZero %}, col{% endif %}{% if hasBZero and bZeroPerColumn %}, colBase + col{% endif %}); } } } else { var acc: array<i32, {{ (32 * integerMatrixN * 2 / 128) | int }}>; for (var kk = 0u; kk < params.K; kk += TILE_K) { loadTiles(rowBase, colBase, kk, tid); workgroupBarrier();{% if hasAZero or hasBZero %} accumulateTileSums(tid);{% endif %} for (var cell = 0u; cell < {{ (32 * integerMatrixN * 2 / 128) | int }}u; cell++) { let flat = tid + cell * 128u; let row = flat / TILE_N; let col = flat % TILE_N; for (var k = 0u; k < TILE_K; k++) { acc[cell] += readTileA(row * TILE_K + k) * readTileB(k * TILE_N + col); } } workgroupBarrier(); } for (var cell = 0u; cell < {{ (32 * integerMatrixN * 2 / 128) | int }}u; cell++) { let flat = tid + cell * 128u; let row = flat / TILE_N; let col = flat % TILE_N; if (rowBase + row < params.M && colBase + col < params.N) { y[(rowBase + row) * params.N + colBase + col] = corrected(acc[cell]{% if hasBZero %}, row{% endif %}{% if hasAZero %}, col{% endif %}{% if hasBZero and bZeroPerColumn %}, colBase + col{% endif %}); } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475{"name": "com.microsoft.QAttention","id": "_com_microsoft_qattention_webgpu_026c861","version": 1,"license": "Apache-2.0","backend": { "type": "webgpu" },"digest": {"algorithm": "sha256","files": {"bench.json": "WUARGQXLHdRwRaYeigTM1jvVwWdzu47zbI09h8lRXsc=","manifest.json": "ulKRNtTBgoA8Wz+aAQFJIL0QWRYUwEjKv9NM7k/uNSg=","qattention-attend.wgsl.jinja": "UGc6Q7OUoCatgxhKNvEhHNFyJo+Es1skiNgWXQmsuqE=","qattention-kv-permute.wgsl.jinja": "jUf53tE21TwhtJHLipUtAN8SRpNf802Gv2U1AyzquDs=","qattention-mask.wgsl.jinja": "C2ro05i/MqgrdCj4ovrE/6Ynfr2GgILZlXN1M7PYQh4=","qattention-qkv-scatter.wgsl.jinja": "oOYfxtZyxa+p8x3Qa8nBQmR2mfaSuuQqC4bnHtGodGM=","quant-dp4a-matmul.wgsl.jinja": "aqvfh8ylqkGgD9hpgcF3VaqrfTd9nxFAOajSYefyKIw=","quant-exact-matrix.wgsl.jinja": "cxPvYjw5Y+zzLhFVmg++2hZHj/4n3My4GCigHAYzZgo=","test.json": "sYqqYfG5fzcotj12ayetyuHKBoOhjFxY2UXs7liRv5k="}},"provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },"webgpu": {"manifestSpec": "2.1","variants": {"sgmat_plain_mask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_plain_mask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_plain_mask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_plain_mask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_plain_mask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_plain_mask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_plain_mask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_plain_mask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_plain_nomask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_plain_nomask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_plain_nomask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_plain_nomask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_plain_nomask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_plain_nomask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_plain_nomask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_plain_nomask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_present_mask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_present_mask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_present_mask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_present_mask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_present_mask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_present_mask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_present_mask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_present_mask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_present_nomask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_present_nomask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_present_nomask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_present_nomask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_present_nomask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_present_nomask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_present_nomask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_present_nomask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_past_mask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_past_mask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_past_mask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_past_mask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_past_mask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_past_mask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_past_mask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_past_mask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_past_nomask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_past_nomask_izp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_past_nomask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_past_nomask_izp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_past_nomask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_past_nomask_noizp_wzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"sgmat_past_nomask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"packed_past_nomask_noizp_nowzp": ["qattention-attend.wgsl.jinja", "qattention-kv-permute.wgsl.jinja", "qattention-mask.wgsl.jinja", "qattention-qkv-scatter.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"]}}}1{"name":"com.microsoft.QAttention","id":"_com_microsoft_qattention_webgpu_d402e65","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"bench.json":"lwA3ONK3+ci2JjpiJJ07EkIfevZw4RRFTMOdy9sxGqI=","integer-pack-columns.wgsl.jinja":"SNH5l5pje8hh8cXtoZeAVT7avUiEnpg+6qdQi4JEtZs=","integer-pack-rows.wgsl.jinja":"nO4v1vhX/frdesHIddfn92kAlSSlaSyxI8BwJfVz00s=","manifest.json":"THUfK6l3BEBU73oX8+rAwf5ejQQbVBw/jCxesWH0WxE=","matrix-shaped-integer-gemm.wgsl.jinja":"dLLW37vOzTJ+1BChJsf/oZXmP56iRftxTyWwxwMOt40=","qattention-attend.wgsl.jinja":"mBnlZubBe0eeGjoxkoAa0+4rDMgrNQj8l2RESLdAdkI=","qattention-kv-permute.wgsl.jinja":"y9jQYdg3Z6RwJvDobtnCHGe9Qzwtd4AxeRCwQg/PRZk=","qattention-mask.wgsl.jinja":"XwqmtfIiQvflZPyvBKqax5tFaSYwObXuTr4LrWy9RGo=","qattention-project.wgsl.jinja":"pyFCrXKvXL8B/FriZZd68qA/h/ttX8gSf67in0Lmr70=","qattention-qkv-scatter.wgsl.jinja":"TEbUUHnGwbDKy0YMGXuUNrGzKdBxVRRbMtSHdVBNBeE=","quant-exact-matrix.wgsl.jinja":"fAs0Wh3wSZCYaf9ExpojWKZxOzPI75TkyMU+NqeRW6Q=","subgroup-matrix-gemm.wgsl.jinja":"BpgQPAzs0QkaNeNNkoqOOyXgrLYhBiCDMrZ2VlhbbHo=","test.json":"Ip3RiNPQvitDRyPyF0ZgQ/b5R65ewdmREuLRfnkkEP8="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
1234567891011121314151617181920212223242526272829303132333435363717 unmodified lines555657585960616263646566673 unmodified lines71727374757656 unmodified lines1331341351361371381391401411421433 unmodified lines1471481491501511521531541553 unmodified lines15916016116216316416516 unmodified lines1821831841851861871881891901911921931941952 unmodified lines19819920020120220320420520620720819 unmodified lines2282292302312322332342352363 unmodified lines2402412422432442452462472481 unmodified line2502512522532542552562572582592604 unmodified lines2652662672682692702712722732742752762772782792802812822837 unmodified lines291292293{{ env.wgsl.resourceDeclarations }}// Flash-style tiled online-softmax attention over the projected QKV working// buffers. One workgroup owns QUERY_TILE consecutive query tokens of one// (batch, head) and sweeps the key axis in tiles of WG keys, each invocation// owning one key of the tile. A key row is loaded once and scored against every// query of the tile, so one pass over the key and value streams serves QUERY_TILE// queries instead of one.//// Q lives in [batch, sequence, heads, paddedHeadSize] and K/V in// [2, batch, total, heads, paddedHeadSize]; both are read as vec4 words, which is// what the padded head size buys. The padding lanes hold zero, so they add// nothing to a score and nothing to a value sum. The op output has the UNPADDED// [batch, sequence, heads * headSize] layout, so the epilogue stores scalars.//// Every mask rule — padding, the mask_filter_value fill, and causal exclusion —// arrives as one additive f32 table with broadcast strides, so this kernel has no// mask-shape or unidirectional branch.const HEAD_DIM_V4: u32 = {{ headPadV4 }}u;const HEAD_SIZE: u32 = {{ headSize }}u;const NUM_HEADS: u32 = {{ numHeads }}u;const QKV_HIDDEN_V4: u32 = NUM_HEADS * HEAD_DIM_V4;const HIDDEN: u32 = NUM_HEADS * HEAD_SIZE;const WG: u32 = {{ attendWorkgroup }}u;const QUERY_TILE: u32 = {{ queryTile }}u;// One value lane per (query, output word). V_STRIPES splits the tile's keys when// the tile owns fewer output words than the workgroup has invocations, so the// value accumulation — which carries as many multiply-adds as the score sweep —// is spread over the same invocations rather than a fraction of them.const V_LANES: u32 = QUERY_TILE * HEAD_DIM_V4;{% if vStripes > 1 %}const V_STRIPES: u32 = {{ vStripes }}u;{% endif %}{% set mdStreams = queryTile %}// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret17 unmodified linesfn exp_shift(value: f32, maxValue: f32) -> f32 {return exp(shifted_value(value, maxValue));}var<workgroup> q_shared: array<vec4<f32>, V_LANES>;var<workgroup> running_out: array<vec4<f32>, V_LANES>;var<workgroup> probs: array<f32, QUERY_TILE * WG>;var<workgroup> tile_correction: array<f32, QUERY_TILE>;{% if vStripes > 1 %}var<workgroup> v_part: array<vec4<f32>, V_STRIPES * V_LANES>;{% endif %}// Workgroup-cooperative merge of per-thread online-softmax (m, d) partials:// mNew = max(m1, m2)3 unmodified lines// calls before their shared partial storage is reused.{% set mdStreamed = mdStreams is defined %}{% set mdStreams = mdStreams if mdStreams is defined else 1 %}{% set mdExtent = "WG" if mdStreams == 1 else "WG * " ~ mdStreams ~ "u" %}var<workgroup> partialM: array<f32, {{ mdExtent }}>;var<workgroup> partialD: array<f32, {{ mdExtent }}>;56 unmodified linesreturn merged;}{% endif %}@compute @workgroup_size(WG, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>) {let qBase = wg.x * QUERY_TILE;let h = wg.y;3 unmodified lines}let tid = lid.x;let lastQuery = params.qSeq - 1u;let kvPartStrideV4 = params.batch * params.kvSeq * QKV_HIDDEN_V4;let keyBaseV4 = b * params.kvSeq * QKV_HIDDEN_V4 + h * HEAD_DIM_V4;let valueBaseV4 = keyBaseV4 + kvPartStrideV4;let maskBase = b * params.maskBatchStride;3 unmodified linesfor (var i: u32 = tid; i < V_LANES; i = i + WG) {let qRow = min(qBase + i / HEAD_DIM_V4, lastQuery);q_shared[i] = query[(b * params.qSeq + qRow) * QKV_HIDDEN_V4 + h * HEAD_DIM_V4 + i % HEAD_DIM_V4];running_out[i] = vec4<f32>(0.0);}workgroupBarrier();16 unmodified linesvar score{{ q }} = -FLT_MAX;{% endfor %}if (keyAllowed) {let kRowV4 = keyBaseV4 + kj * QKV_HIDDEN_V4;{% for q in range(queryTile) %}var acc{{ q }}: f32 = 0.0;{% endfor %}for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {let kWord = key_value[kRowV4 + d4];{% for q in range(queryTile) %}acc{{ q }} = acc{{ q }} + dot(q_shared[{{ q }}u * HEAD_DIM_V4 + d4], kWord);{% endfor %}}{% for q in range(queryTile) %}2 unmodified lines}// Identity (-FLT_MAX, 0) for the out-of-range lanes of a tail key tile.let dPart = select(0.0, 1.0, keyAllowed);{% for q in range(queryTile) %}partialM[{{ q }}u * WG + tid] = score{{ q }};partialD[{{ q }}u * WG + tid] = dPart;{% endfor %}combine_partials_streams(tid);// Online merge of each query's tile pair into its running state.{% for q in range(queryTile) %}19 unmodified lineslet stripe = tid / V_LANES;let q = lane / HEAD_DIM_V4;let d4 = lane % HEAD_DIM_V4;var vSum = vec4<f32>(0.0);for (var t: u32 = stripe; t < tileCount; t = t + V_STRIPES) {vSum = vSum + probs[q * WG + t] * key_value[valueBaseV4 + (kjBase + t) * QKV_HIDDEN_V4 + d4];}v_part[tid] = vSum;}3 unmodified linesif (tid < V_LANES) {var folded = v_part[tid];for (var s: u32 = 1u; s < V_STRIPES; s = s + 1u) {folded = folded + v_part[tid + s * V_LANES];}running_out[tid] = running_out[tid] * tile_correction[tid / HEAD_DIM_V4] + folded;}{% else %}// running_out[lane] is owned by invocation `lane` across all tiles, so the1 unmodified linefor (var lane: u32 = tid; lane < V_LANES; lane = lane + WG) {let q = lane / HEAD_DIM_V4;let d4 = lane % HEAD_DIM_V4;var vSum = vec4<f32>(0.0);for (var t: u32 = 0u; t < tileCount; t = t + 1u) {vSum = vSum + probs[q * WG + t] * key_value[valueBaseV4 + (kjBase + t) * QKV_HIDDEN_V4 + d4];}running_out[lane] = running_out[lane] * tile_correction[q] + vSum;}{% endif %}// Orders this tile's probs and stripe reads before the next tile's writes.4 unmodified lines// A row whose denominator is zero has no attended key at all; emit zero rather// than 0 * (1 / 0) = NaN.{% for q in range(queryTile) %}let invDenom{{ q }} = select(0.0, 1.0 / runningDenom{{ q }}, runningDenom{{ q }} > 0.0);{% endfor %}for (var lane: u32 = tid; lane < V_LANES; lane = lane + WG) {let q = lane / HEAD_DIM_V4;let d4 = lane % HEAD_DIM_V4;let queryIndex = qBase + q;if (queryIndex < params.qSeq) {var invDenom = invDenom0;{% for qq in range(1, queryTile) %}if (q == {{ qq }}u) { invDenom = invDenom{{ qq }}; }{% endfor %}let outValue = running_out[lane] * invDenom;let outBase = (b * params.qSeq + queryIndex) * HIDDEN + h * HEAD_SIZE + d4 * 4u;{% for c in range(4) %}{% if headPad == headSize %}7 unmodified lines}}}1234567891011121314151617181920212223242517 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216223 unmodified lines62662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671756 unmodified lines7747757767777787797807817827837847857867877883 unmodified lines7927937947957967977987998008018028038048053 unmodified lines80981081181281381481516 unmodified lines8328338348358368378388398408418428438448458468478488492 unmodified lines85285385485585685785885986086186286386486586619 unmodified lines8868878888898908918928938943 unmodified lines8988999009019029039049059061 unmodified line9089099109119129139149159169179184 unmodified lines9239249259269279289299309319329339349359369379387 unmodified lines946947948949{% if combineSubgroups %}enable subgroups;{% if qaStreamPin > 0 %}enable subgroup_size_control;{% endif %}{% endif %}{{ env.wgsl.resourceDeclarations }}{% if headLocalKV %}{% set floatType = "vec4<f32>" %}{% set uintType = "vec4<u32>" %}fn rounded_product(a: {{ floatType }}, b: {{ floatType }}) -> {{ floatType }} {let sign = (bitcast<{{ uintType }}>(a) ^ bitcast<{{ uintType }}>(b)) & {{ uintType }}(0x80000000u);return fma(a, b, bitcast<{{ floatType }}>(sign));}{% endif %}// One workgroup scores a tile of consecutive queries against one head's keys.// Head-local prefill reads component-major K and token-major V. A stateful// request reads both tensors in the public cache layout.const HEAD_DIM_V4: u32 = {{ headPadV4 }}u;const HEAD_SIZE: u32 = {{ headSize }}u;const NUM_HEADS: u32 = {{ numHeads }}u;const WG: u32 = {{ attendWorkgroup }}u;const QUERY_TILE: u32 = {{ queryTile }}u;// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret17 unmodified linesfn exp_shift(value: f32, maxValue: f32) -> f32 {return exp(shifted_value(value, maxValue));}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}) -> bool {return all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = (abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), weight{% if coefficientType != "f32" %}[{{ i }}]{% endif %}, ScaledValueScalar(value{{ c }}, 0.0, 0));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), 1.0, ScaledValueScalar(other.hi{{ c }}, other.lo{{ c }}, other.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{% macro ordered_score(q, queryWord, keyWord) %}let products{{ q }} = rounded_product({{ queryWord }}, {{ keyWord }});{% for component in ["x", "y", "z", "w"] %}acc{{ q }} = fma(1.0, acc{{ q }}, products{{ q }}.{{ component }});{% endfor %}{% endmacro %}{% if residentKeys %}// Each lane keeps up to two logits per query in registers. Once the row's// maximum is known, publish all weights and fold each output channel once.{{ scaled_value_functions("f32", lean=true) }}const KEYS = {{ seqLen }}u;var<workgroup> q_shared: array<vec4<f32>, QUERY_TILE * HEAD_DIM_V4>;{% set masked = useWeightMask | default(false) %}{% if masked %}const MASK_WORDS = {{ ceilDiv(seqLen, 32) }}u;var<workgroup> live: array<u32, QUERY_TILE * MASK_WORDS>;{% endif %}var<workgroup> probs: array<f32, QUERY_TILE * KEYS>;var<workgroup> partial: array<f32, QUERY_TILE * WG>;{% macro fold_value() -%}let w = probs[q * KEYS + key];let v = key_value[word + key * HEAD_DIM_V4][component];wLow = select(wLow, min(wLow, w), w != 0.0);vLow = scaled_value_nonzero_low(vLow, v);acc = scaled_value_lean_step(acc, w, v);{%- endmacro %}{% macro reduce(mode) %}{% if combineSubgroups %}{% for q in range(queryTile) %}let sub{{ mode }}{{ q }} = subgroup{{ "Max" if mode == "max" else "Add" }}({{ mode }}{{ q }});{% endfor %}if (subgroupElect()) {{% for q in range(queryTile) %}partial[{{ q }}u * WG + sg] = sub{{ mode }}{{ q }};{% endfor %}}workgroupBarrier();if (tid < QUERY_TILE) {var result = partial[tid * WG];for (var g = 1u; g < groups; g++) {result = {{ "max(result, partial[tid * WG + g])" if mode == "max" else "result + partial[tid * WG + g]" }};}partial[tid * WG] = result;}workgroupBarrier();{% else %}{% for q in range(queryTile) %}partial[{{ q }}u * WG + tid] = {{ mode }}{{ q }};{% endfor %}workgroupBarrier();for (var count = WG; count > 1u; count = (count + 1u) / 2u) {let n = (count + 1u) / 2u;if (tid < count - n) {{% for q in range(queryTile) %}{% set i = q ~ "u * WG + tid" %}partial[{{ i }}] = {% if mode == "max" %}max(partial[{{ i }}], partial[{{ i }} + n]){% else %}partial[{{ i }}] + partial[{{ i }} + n]{% endif %};{% endfor %}}workgroupBarrier();}{% endif %}{% endmacro %}{% if qaStreamPin > 0 %}@subgroup_size({{ qaStreamPin }}){% endif %}@compute @workgroup_size(WG)fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) tid: u32{% if combineSubgroups %},@builtin(subgroup_id) sg: u32, @builtin(num_subgroups) groups: u32{% endif %}) {let row = wg.x * QUERY_TILE;let h = wg.y;let b = wg.z;let kBase = (b * NUM_HEADS + h) * params.kvSeq * HEAD_DIM_V4;let vBase = kBase + params.batch * params.kvSeq * NUM_HEADS * HEAD_DIM_V4;for (var i = tid; i < QUERY_TILE * HEAD_DIM_V4; i += WG) {let r = min(row + i / HEAD_DIM_V4, params.qSeq - 1u);q_shared[i] = query[((b * params.qSeq + r) * NUM_HEADS + h) * HEAD_DIM_V4 + i % HEAD_DIM_V4];}workgroupBarrier();{% for q in range(queryTile) %}let mask{{ q }} = b * params.maskBatchStride + min(row + {{ q }}u, params.qSeq - 1u) * params.maskSeqStride;var max{{ q }} = -FLT_MAX;var sum{{ q }} = 0.0;var scores{{ q }}: array<f32, {{ ceilDiv(seqLen, attendWorkgroup) }}>;{% endfor %}for (var key = tid; key < KEYS; key += WG) {{% for q in range(queryTile) %}var acc{{ q }} = 0.0;{% endfor %}for (var d = 0u; d < HEAD_DIM_V4; d++) {let k = key_value[kBase + d * params.kvSeq + key];{% for q in range(queryTile) %}{{ ordered_score(q, "q_shared[" ~ q ~ "u * HEAD_DIM_V4 + d]", "k") }}{% endfor %}}{% for q in range(queryTile) %}let masked{{ q }} = acc{{ q }} * params.scale + attn_mask[mask{{ q }} + key];scores{{ q }}[key / WG] = masked{{ q }};max{{ q }} = max(max{{ q }}, masked{{ q }});{% endfor %}}{{ reduce("max") }}for (var key = tid; key < KEYS; key += WG) {{% for q in range(queryTile) %}let p{{ q }} = exp_shift(scores{{ q }}[key / WG], partial[{{ q }}u * WG]);probs[{{ q }}u * KEYS + key] = p{{ q }};sum{{ q }} += p{{ q }};{% endfor %}}// All lanes must finish reading the maxima before the sum reuses partial.workgroupBarrier();{% if masked %}// Each lane builds a complete word. The sum reduction publishes it to all lanes.for (var i = tid; i < QUERY_TILE * MASK_WORDS; i += WG) {let first = (i % MASK_WORDS) * 32u;var bits = 0u;for (var j = 0u; j < min(32u, KEYS - first); j++) {bits |= select(0u, 1u << j, probs[i / MASK_WORDS * KEYS + first + j] != 0.0);}live[i] = bits;}{% endif %}{{ reduce("sum") }}for (var i = tid; i < QUERY_TILE * HEAD_SIZE; i += WG) {let q = i / HEAD_SIZE;if (row + q >= params.qSeq) { continue; }let d = i % HEAD_SIZE;let word = vBase + d / 4u;let component = d % 4u;var acc = scaled_value_zero();var wLow = FLT_MAX;var vLow = FLT_MAX;{% if masked %}let valueColumn = (2u * NUM_HEADS + h) * HEAD_SIZE + d;let scale = input_scale[0] * weight_scale[{{ "valueColumn" if weightScalePerColumn else "0u" }}];var count = 0u;for (var j = 0u; j < MASK_WORDS; j++) { count += countOneBits(live[q * MASK_WORDS + j]); }// With these bounds every int32 accumulator dequantizes to a finite value.// Otherwise even a zero weight must visit V to preserve NaN propagation.if (count * 2u < KEYS && abs(scale) <= 0x1p94f && abs(bias[valueColumn]) <= 0x1p126f) {for (var j = 0u; j < MASK_WORDS; j++) {var bits = live[q * MASK_WORDS + j];while (bits != 0u) {let key = j * 32u + firstTrailingBit(bits);{{ fold_value() | indent(10, true) }}bits &= bits - 1u;}}} else {{% endif %}for (var key = 0u; key < KEYS; key++) {{{ fold_value() | indent(6, true) }}}{% if masked %}}{% endif %}// Recompute exceptional products and sums with a separate binary exponent.if (!scaled_value_lean_exact(scaled_value_zero(), acc, wLow, vLow)) {acc = scaled_value_zero();for (var key = 0u; key < KEYS; key++) {acc = scaled_value_add(acc, probs[q * KEYS + key], key_value[word + key * HEAD_DIM_V4][component]);}}let outBase = ((b * params.qSeq + row + q) * NUM_HEADS + h) * HEAD_SIZE;let v = scaled_value_mean(acc, partial[q * WG]);output[outBase + d] = v;}}{% else %}const QKV_HIDDEN_V4: u32 = NUM_HEADS * HEAD_DIM_V4;const HIDDEN: u32 = NUM_HEADS * HEAD_SIZE;// One value lane per (query, output word). V_STRIPES splits the tile's keys when// the tile owns fewer output words than the workgroup has invocations, so the// value accumulation — which carries as many multiply-adds as the score sweep —// is spread over the same invocations rather than a fraction of them.const V_LANES: u32 = QUERY_TILE * HEAD_DIM_V4;{% if vStripes > 1 %}const V_STRIPES: u32 = {{ vStripes }}u;{% endif %}{% set mdStreams = queryTile %}{{ scaled_value_functions("vec4<f32>", rescale=true, merge=true) }}var<workgroup> q_shared: array<vec4<f32>, V_LANES>;var<workgroup> probs: array<f32, QUERY_TILE * WG>;var<workgroup> tile_correction: array<f32, QUERY_TILE>;{% if vStripes > 1 %}var<workgroup> v_part: array<ScaledValue, V_STRIPES * V_LANES>;{% endif %}// Workgroup-cooperative merge of per-thread online-softmax (m, d) partials:// mNew = max(m1, m2)3 unmodified lines// calls before their shared partial storage is reused.{% set mdStreamed = mdStreams is defined %}{% set mdStreams = mdStreams if mdStreams is defined else 1 %}{% if combineSubgroups and mdStreamed %}var<workgroup> partialM: array<f32, WG * {{ mdStreams }}u>;var<workgroup> partialD: array<f32, WG * {{ mdStreams }}u>;fn combine_partials_streams(tid: u32, sgId: u32, foldCount: u32, valid: f32{% for g in range(mdStreams) %}, score_{{ g }}: f32{% endfor %}) {{% for g in range(mdStreams) %}let subgroupMax_{{ g }} = subgroupMax(score_{{ g }});let subgroupDenom_{{ g }} = subgroupAdd(valid * exp_shift(score_{{ g }}, subgroupMax_{{ g }}));{% endfor %}if (subgroupElect()) {{% for g in range(mdStreams) %}partialM[{{ g }}u * WG + sgId] = subgroupMax_{{ g }};partialD[{{ g }}u * WG + sgId] = subgroupDenom_{{ g }};{% endfor %}}workgroupBarrier();if (tid == 0u) {{% for g in range(mdStreams) %}var m_{{ g }} = -FLT_MAX;var d_{{ g }} = 0.0;{% endfor %}for (var s = 0u; s < foldCount; s = s + 1u) {{% for g in range(mdStreams) %}let sm_{{ g }} = partialM[{{ g }}u * WG + s];let newM_{{ g }} = max(m_{{ g }}, sm_{{ g }});d_{{ g }} = d_{{ g }} * exp_shift(m_{{ g }}, newM_{{ g }}) + partialD[{{ g }}u * WG + s] * exp_shift(sm_{{ g }}, newM_{{ g }});m_{{ g }} = newM_{{ g }};{% endfor %}}{% for g in range(mdStreams) %}partialM[{{ g }}u * WG] = m_{{ g }};partialD[{{ g }}u * WG] = d_{{ g }};{% endfor %}}workgroupBarrier();}{% elif combineSubgroups %}// Cross-subgroup merge that assumes nothing about which invocations share a// subgroup or how many subgroups there are: each subgroup's elected lane// publishes the subgroup pair in the slot at its OWN invocation index and sets// that index's bit in a workgroup bitmask; thread 0 then folds exactly the// published slots, in ascending index order (the online (m, d) merge is not// float-associative, so the order is fixed), and clears the mask for the next// call as it reads it. Workgroup memory starts zeroed, so the mask needs no// setup. Same three collectives as a single-subgroup reduce, two barriers.var<workgroup> partialM: array<f32, WG>;var<workgroup> partialD: array<f32, WG>;var<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;var<workgroup> combinedMD: vec2<f32>;fn combine_partials(m: f32, d: f32, lidx: u32) -> vec2<f32> {let sgM = subgroupMax(m);// A lane with no elements contributes d == 0 (exact identity). A +inf// element made exp(inf - inf) = NaN stick in that lane's d; a NaN element// landed in d via exp(NaN); both survive the merge and are detected by the// code after the reduction.let sgD = subgroupAdd(d * exp_shift(m, sgM));if (subgroupElect()) {partialM[lidx] = sgM;partialD[lidx] = sgD;atomicOr(&leaderMask[lidx / 32u], 1u << (lidx % 32u));}workgroupBarrier();if (lidx == 0u) {var accM = -FLT_MAX;var accD = 0.0;for (var w = 0u; w < (WG + 31u) / 32u; w = w + 1u) {var bits = atomicExchange(&leaderMask[w], 0u);while (bits != 0u) {let slot = w * 32u + firstTrailingBit(bits);bits = bits & (bits - 1u);let mNew = max(accM, partialM[slot]);accD = accD * exp_shift(accM, mNew) + partialD[slot] * exp_shift(partialM[slot], mNew);accM = mNew;}}combinedMD = vec2<f32>(accM, accD);}workgroupBarrier();return combinedMD;}{% else %}{% set mdExtent = "WG" if mdStreams == 1 else "WG * " ~ mdStreams ~ "u" %}var<workgroup> partialM: array<f32, {{ mdExtent }}>;var<workgroup> partialD: array<f32, {{ mdExtent }}>;56 unmodified linesreturn merged;}{% endif %}{% endif %}{% if qaStreamPin > 0 %}@subgroup_size({{ qaStreamPin }}){% endif %}@compute @workgroup_size(WG, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if combineSubgroups %},@builtin(subgroup_id) sgId: u32,@builtin(num_subgroups) foldCount: u32{% endif %}) {let qBase = wg.x * QUERY_TILE;let h = wg.y;3 unmodified lines}let tid = lid.x;var value_acc: array<ScaledValue, {{ ceilDiv(queryTile * headPadV4, attendWorkgroup) }}>;let lastQuery = params.qSeq - 1u;let kvPartStrideV4 = params.batch * params.kvSeq * QKV_HIDDEN_V4;{% if headLocalKV %}let keyBaseV4 = (b * NUM_HEADS + h) * params.kvSeq * HEAD_DIM_V4;{% else %}let keyBaseV4 = b * params.kvSeq * QKV_HIDDEN_V4 + h * HEAD_DIM_V4;{% endif %}let valueBaseV4 = keyBaseV4 + kvPartStrideV4;let maskBase = b * params.maskBatchStride;3 unmodified linesfor (var i: u32 = tid; i < V_LANES; i = i + WG) {let qRow = min(qBase + i / HEAD_DIM_V4, lastQuery);q_shared[i] = query[(b * params.qSeq + qRow) * QKV_HIDDEN_V4 + h * HEAD_DIM_V4 + i % HEAD_DIM_V4];value_acc[i / WG] = scaled_value_zero();}workgroupBarrier();16 unmodified linesvar score{{ q }} = -FLT_MAX;{% endfor %}if (keyAllowed) {let kRowV4 = keyBaseV4 + kj * {% if headLocalKV %}1u{% else %}QKV_HIDDEN_V4{% endif %};{% for q in range(queryTile) %}var acc{{ q }}: f32 = 0.0;{% endfor %}for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {let kWord = key_value[kRowV4 + d4{% if headLocalKV %} * params.kvSeq{% endif %}];{% for q in range(queryTile) %}{% if headLocalKV %}{{ ordered_score(q, "q_shared[" ~ q ~ "u * HEAD_DIM_V4 + d4]", "kWord") }}{% else %}acc{{ q }} = acc{{ q }} + dot(q_shared[{{ q }}u * HEAD_DIM_V4 + d4], kWord);{% endif %}{% endfor %}}{% for q in range(queryTile) %}2 unmodified lines}// Identity (-FLT_MAX, 0) for the out-of-range lanes of a tail key tile.let dPart = select(0.0, 1.0, keyAllowed);{% if combineSubgroups %}combine_partials_streams(tid, sgId, foldCount, dPart{% for q in range(queryTile) %}, score{{ q }}{% endfor %});{% else %}{% for q in range(queryTile) %}partialM[{{ q }}u * WG + tid] = score{{ q }};partialD[{{ q }}u * WG + tid] = dPart;{% endfor %}combine_partials_streams(tid);{% endif %}// Online merge of each query's tile pair into its running state.{% for q in range(queryTile) %}19 unmodified lineslet stripe = tid / V_LANES;let q = lane / HEAD_DIM_V4;let d4 = lane % HEAD_DIM_V4;var vSum = scaled_value_zero();for (var t: u32 = stripe; t < tileCount; t = t + V_STRIPES) {vSum = scaled_value_add(vSum, probs[q * WG + t], key_value[valueBaseV4 + (kjBase + t) * {% if headLocalKV %}HEAD_DIM_V4{% else %}QKV_HIDDEN_V4{% endif %} + d4]);}v_part[tid] = vSum;}3 unmodified linesif (tid < V_LANES) {var folded = v_part[tid];for (var s: u32 = 1u; s < V_STRIPES; s = s + 1u) {folded = scaled_value_merge(folded, v_part[tid + s * V_LANES]);}value_acc[tid / WG] = scaled_value_merge(scaled_value_rescale(value_acc[tid / WG], tile_correction[tid / HEAD_DIM_V4]), folded);}{% else %}// running_out[lane] is owned by invocation `lane` across all tiles, so the1 unmodified linefor (var lane: u32 = tid; lane < V_LANES; lane = lane + WG) {let q = lane / HEAD_DIM_V4;let d4 = lane % HEAD_DIM_V4;var vSum = scaled_value_zero();for (var t: u32 = 0u; t < tileCount; t = t + 1u) {vSum = scaled_value_add(vSum, probs[q * WG + t], key_value[valueBaseV4 + (kjBase + t) * {% if headLocalKV %}HEAD_DIM_V4{% else %}QKV_HIDDEN_V4{% endif %} + d4]);}value_acc[lane / WG] = scaled_value_merge(scaled_value_rescale(value_acc[lane / WG], tile_correction[q]), vSum);}{% endif %}// Orders this tile's probs and stripe reads before the next tile's writes.4 unmodified lines// A row whose denominator is zero has no attended key at all; emit zero rather// than 0 * (1 / 0) = NaN.for (var lane: u32 = tid; lane < V_LANES; lane = lane + WG) {let q = lane / HEAD_DIM_V4;let d4 = lane % HEAD_DIM_V4;let queryIndex = qBase + q;if (queryIndex < params.qSeq) {var denominator = runningDenom0;{% for qq in range(1, queryTile) %}if (q == {{ qq }}u) { denominator = runningDenom{{ qq }}; }{% endfor %}let outValue = scaled_value_mean(value_acc[lane / WG], denominator);let outBase = (b * params.qSeq + queryIndex) * HIDDEN + h * HEAD_SIZE + d4 * 4u;{% for c in range(4) %}{% if headPad == headSize %}7 unmodified lines}}}{% endif %}
1234567891011{% 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 }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}{% if direction == "past_in" %}123456789101112{% 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 }}{% if direction == "past_in" %}
1234567891011{% 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 }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}// Materializes the ADDITIVE attention mask the scoring kernel adds to every123456789101112{% 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 }}// Materializes the ADDITIVE attention mask the scoring kernel adds to every
12344 unmodified lines484950515253541 unmodified line5657585960616249 unmodified lines11211311411511611711833 unmodified lines15215315415515615715815916016116216316456 unmodified lines22122222322422522622722822923023123223323423524 unmodified lines2602612622632642652665 unmodified lines2722732742752762772782 unmodified lines281282283{% macro quant_read_column_zero(fn_name, buffer_name, is_unsigned, present=true, per_column=false, param_name="col", return_type="i32") %}fn {{ fn_name }}({% if per_column %}{{ param_name }}: u32{% endif %}) -> {{ return_type }} {{% if per_column %}44 unmodified lines{% set needsBSum = hasAZero or aUnsigned %}var<workgroup> a_tile: array<u32, A_TILE_WORDS>;{% if needsASum %}var<workgroup> a_row_sum: array<atomic<i32>, TILE_M>;{% endif %}// Pack 4 widened A values into one u32 (byte 0 = lowest k).1 unmodified line// u8 -> biased i8: (u - 128) two's-complement low byte == u ^ 0x80.return ((v.x ^ 0x80u) & 0xFFu) | (((v.y ^ 0x80u) & 0xFFu) << 8u) | (((v.z ^ 0x80u) & 0xFFu) << 16u) | (((v.w ^ 0x80u) & 0xFFu) << 24u);}{% if needsASum %}// Sum of the 4 bias-shifted A values of one packed word.fn sum4_a(v: vec4<{{ aScalar }}>) -> i32 {49 unmodified lines{% if needsASum %}if (tid < TILE_M) {atomicStore(&a_row_sum[tid], 0);}workgroupBarrier();33 unmodified linesa[a_row + k4 + 3u],);packed = pack_a(v);{% if needsASum %}atomicAdd(&a_row_sum[mi], sum4_a(v));{% endif %}}a_tile[mi * KT_WORDS + ki] = packed;}workgroupBarrier();if (n_valid) {{% if tileM == 1 %}56 unmodified lineslet k4 = k_words_total * 4u;let a_row = a_base4 + src_m * params.K;let a0 = a[a_row + k4];var a1: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};var a2: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};if (tail_lanes > 1u) { a1 = a[a_row + k4 + 1u]; }if (tail_lanes > 2u) { a2 = a[a_row + k4 + 2u]; }let a3: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};let v = vec4<{{ aScalar }}>(a0, a1, a2, a3);packed = pack_a(v);{% if needsASum %}atomicAdd(&a_row_sum[tid], sum4_a(v));{% endif %}}a_tile[tid * KT_WORDS] = packed;24 unmodified lines// Fold bias + zero-point corrections (exact in modular i32 arithmetic).let cb: i32 = {{ "128" if bUnsigned else "0" }}{% if hasBZero %} - read_b_zero({% if bZeroPerColumn %}col{% endif %}){% endif %};let ca: i32 = {{ "128" if aUnsigned else "0" }}{% if hasAZero %} - read_a_zero(){% endif %};let kcc: i32 = i32(params.K) * ca * cb;{% if needsBSum and tileM == 1 %}let sum_b_total = sum_b{% for u in range(1, GEMV_UNROLL) %} + sum_b_{{ u }}{% endfor %};5 unmodified linesif (mr < params.M) {var acc = r{{ m }}{% if tileM == 1 %}{% for u in range(1, GEMV_UNROLL) %} + r0_{{ u }}{% endfor %}{% endif %};{% if needsASum %}acc = acc + cb * atomicLoad(&a_row_sum[{{ m }}u]);{% endif %}acc = acc + ca * {% if tileM == 1 %}sum_b_total{% else %}sum_b{% endif %};acc = acc + kcc;2 unmodified lines}{% endfor %}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616744 unmodified lines2122132142152162172181 unmodified line22022122222322422522649 unmodified lines27627727827928028128233 unmodified lines31631731831932032132232332432532632732832933033133233333433533633733856 unmodified lines39539639739839940040140240340440540640740840924 unmodified lines4344354364374384394405 unmodified lines4464474484494504514522 unmodified lines455456457458{% if inlineProjection %}{% set scalar = "f16" %}{% set M = gemmRows %}{% set N = hiddenX3 %}{% set K = inputHidden %}{% set preparedN = N %}fn center_a(value: vec4<{{ aScalar }}>) -> vec4<{{ scalar }}> {return vec4<{{ scalar }}>(vec4<i32>(value){% if hasAZero %} - vec4<i32>(i32(a_zero_point[0])){% endif %});}fn center_b(value: vec4<{{ bScalar }}>{% if hasBZero and bZeroPerColumn %}, column: u32{% endif %}) -> vec4<{{ scalar }}> {{% if hasBZero and bZeroPerColumn %}let zero = vec4<i32>({% for i in range(4) %}i32(b_zero_point[column + {{ i }}u]){{ ", " if not loop.last else "" }}{% endfor %});{% endif %}return vec4<{{ scalar }}>(vec4<i32>(value){% if hasBZero %} - {{ "zero" if bZeroPerColumn else "vec4<i32>(i32(b_zero_point[0]))" }}{% endif %});}// Both integer-output and requantizing consumers share the vector GEMM body.// Its callback stores scalar outputs so padded operands also cover column tails.fn store_integer_result(value: i32, output_index: u32) {y[output_index] = value;}{% set exactIntegerPartialsValue = true %}{% set inlineColumnZero = (hasBZero | default(false)) and (bZeroPerColumn | default(false)) %}{% set preparedNValue = preparedN | default(0) %}{% set integerPartialKValue = 256 %}{{ env.wgsl.resourceDeclarations }}{% set kTileValue = 16 %}{% set blockRowsValue = 64 %}{% set blockColsValue = 64 %}{% set accumulatorScalarValue = "f32" %}{% set workgroupColsValue = 8 %}{% set workgroupRowsValue = 8 %}{% set laneCount = 64 %}{% set threadRows = 8 %}{% set threadColVectors = 2 %}{% set threadCols = 8 %}{% set aVectorCount = 4 %}{% set bVectorCount = 4 %}{% set STATIC_M = M is defined %}{% set accName = "acc" %}// High-intensity matrix multiplication:// Y[M,N] = alpha * A[M,K] @ B[K,N].// A may be stored physically as [K,M], and B as [N,K]; a [N,K] B keeps vec4// K loads and transposes only while staging the tile in workgroup memory.//// Unless the shape is ragged, both inputs and the output are four-wide along// their contiguous dimension.// The output-tile geometry and BK are selected from the shape and device's// workgroup-storage limit. f16 operands stay packed in global and workgroup// memory, then widen at the FMA so accumulation remains f32.{% if M is defined %}const M: u32 = {{ M }}u;{% endif %}const K: u32 = {{ K }}u;const N: u32 = {{ N }}u;const K_V4: u32 = K / 4u;const B_N_V4: u32 = {{ preparedNValue }}u / 4u;const BK: u32 = {{ kTileValue }}u;const BM: u32 = {{ blockRowsValue }}u;const BN: u32 = {{ blockColsValue }}u;const TM: u32 = {{ threadRows }}u;const TN: u32 = {{ threadCols }}u;// A is loaded and consumed four K values at a time. Keeping that packing in// workgroup memory reduces A-side shared-memory instructions and inner-loop// control without changing the four scalar FMA operations or their order.var<workgroup> tileA: array<array<vec4<{{ scalar }}>, BK / 4u>, BM>;var<workgroup> tileB: array<vec4<{{ scalar }}>, BK * (BN / 4u)>;@compute @workgroup_size({{ workgroupColsValue }}, {{ workgroupRowsValue }}, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>) {{% if not STATIC_M %}let M = params.M;{% endif %}let li = lid.y * {{ workgroupColsValue }}u + lid.x;let mBase = wg.y * BM;let nBase = wg.x * BN;{% set aOff = "" %}{% set bOff = "" %}{% for i in range(threadRows) %}{% for j in range(threadColVectors) %}var acc{{ i }}_{{ j }} = vec4<{{ accumulatorScalarValue }}>(0.0);var total{{ i }}_{{ j }} = vec4<i32>(0);{% endfor %}{% endfor %}for (var kBase: u32 = 0u; kBase < K; kBase = kBase + BK) {{% for av in range(aVectorCount) %}let aVector{{ av }} = li + {{ av * laneCount }}u;let aRow{{ av }} = aVector{{ av }} / (BK / 4u);let aColV4_{{ av }} = aVector{{ av }} % (BK / 4u);let am{{ av }} = mBase + aRow{{ av }};var av4_{{ av }} = vec4<{{ scalar }}>({{ scalar }}(0));if (am{{ av }} < M) {av4_{{ av }} = center_a(a[{{ aOff }}am{{ av }} * K_V4 + kBase / 4u + aColV4_{{ av }}]);}tileA[aRow{{ av }}][aColV4_{{ av }}] = av4_{{ av }};{% endfor %}{% for bv in range(bVectorCount) %}let bVector{{ bv }} = li + {{ bv * laneCount }}u;let bRow{{ bv }} = bVector{{ bv }} / (BN / 4u);let bColV4_{{ bv }} = bVector{{ bv }} % (BN / 4u);let bn{{ bv }} = nBase + bColV4_{{ bv }} * 4u;var bv4_{{ bv }} = vec4<{{ scalar }}>({{ scalar }}(0));if (bn{{ bv }} < {{ (preparedNValue ~ "u") if exactIntegerPartialsValue and preparedNValue != N else "N" }}) {bv4_{{ bv }} = center_b(b[{{ bOff }}(kBase + bRow{{ bv }}) * {{ "B_N_V4" if exactIntegerPartialsValue else "N_V4" }} + bn{{ bv }} / 4u]{% if inlineColumnZero %}, bn{{ bv }}{% endif %});}tileB[bRow{{ bv }} * (BN / 4u) + bColV4_{{ bv }}] = bv4_{{ bv }};{% endfor %}workgroupBarrier();let aRow = lid.y * TM;let bCol4 = lid.x * {{ threadColVectors }}u;for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {let kk = kv * 4u;{% for j in range(threadColVectors) %}let bv0_{{ j }} = vec4<{{ accumulatorScalarValue }}>(tileB[(kk + 0u) * (BN / 4u) + bCol4 + {{ j }}u]);let bv1_{{ j }} = vec4<{{ accumulatorScalarValue }}>(tileB[(kk + 1u) * (BN / 4u) + bCol4 + {{ j }}u]);let bv2_{{ j }} = vec4<{{ accumulatorScalarValue }}>(tileB[(kk + 2u) * (BN / 4u) + bCol4 + {{ j }}u]);let bv3_{{ j }} = vec4<{{ accumulatorScalarValue }}>(tileB[(kk + 3u) * (BN / 4u) + bCol4 + {{ j }}u]);{% endfor %}{% for i in range(threadRows) %}let av{{ i }} = tileA[aRow + {{ i }}u][kv];{% for j in range(threadColVectors) %}{{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.x)) * bv0_{{ j }};{{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.y)) * bv1_{{ j }};{{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.z)) * bv2_{{ j }};{{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.w)) * bv3_{{ j }};{% endfor %}{% endfor %}}workgroupBarrier();// Adjusted byte integers and each bounded partial are exact in f32.// Convert before exceeding that bound; int32 additions retain wraparound.if ((kBase + BK) % {{ integerPartialKValue }}u == 0u || kBase + BK == K) {{% for i in range(threadRows) %}{% for j in range(threadColVectors) %}total{{ i }}_{{ j }} += vec4<i32>(acc{{ i }}_{{ j }});acc{{ i }}_{{ j }} = vec4<f32>(0.0);{% endfor %}{% endfor %}}}let m0 = mBase + lid.y * TM;{% for j in range(threadColVectors) %}let n{{ j }} = nBase + lid.x * TN + {{ j * 4 }}u;{% endfor %}{% for i in range(threadRows) %}{% for j in range(threadColVectors) %}if (m0 + {{ i }}u < M && n{{ j }} < N) {{% for h in range(4) %}if (n{{ j }} + {{ h }}u < N) {store_integer_result(total{{ i }}_{{ j }}[{{ h }}], (m0 + {{ i }}u) * N + n{{ j }} + {{ h }}u);}{% endfor %}}{% endfor %}{% endfor %}}{% else %}{% macro quant_read_column_zero(fn_name, buffer_name, is_unsigned, present=true, per_column=false, param_name="col", return_type="i32") %}fn {{ fn_name }}({% if per_column %}{{ param_name }}: u32{% endif %}) -> {{ return_type }} {{% if per_column %}44 unmodified lines{% set needsBSum = hasAZero or aUnsigned %}var<workgroup> a_tile: array<u32, A_TILE_WORDS>;{% if needsASum %}var<workgroup> a_row_sum: array<{{ "i32" if ownRowSums else "atomic<i32>" }}, TILE_M>;{% endif %}// Pack 4 widened A values into one u32 (byte 0 = lowest k).1 unmodified line// u8 -> biased i8: (u - 128) two's-complement low byte == u ^ 0x80.return ((v.x ^ 0x80u) & 0xFFu) | (((v.y ^ 0x80u) & 0xFFu) << 8u) | (((v.z ^ 0x80u) & 0xFFu) << 16u) | (((v.w ^ 0x80u) & 0xFFu) << 24u);}{% if needsASum and not ownRowSums %}// Sum of the 4 bias-shifted A values of one packed word.fn sum4_a(v: vec4<{{ aScalar }}>) -> i32 {49 unmodified lines{% if needsASum %}if (tid < TILE_M) {{{ "a_row_sum[tid] = 0;" if ownRowSums else "atomicStore(&a_row_sum[tid], 0);" }}}workgroupBarrier();33 unmodified linesa[a_row + k4 + 3u],);packed = pack_a(v);{% if needsASum and not ownRowSums %}atomicAdd(&a_row_sum[mi], sum4_a(v));{% endif %}}a_tile[mi * KT_WORDS + ki] = packed;}workgroupBarrier();{% if needsASum and ownRowSums %}// One owner folds each staged row, avoiding contended row-sum atomics.if (tid < TILE_M) {var tile_sum = 0i;for (var kk = 0u; kk < words; kk++) {tile_sum += dot4_packed(a_tile[tid * KT_WORDS + kk], 0x01010101u);}a_row_sum[tid] += tile_sum;}{% endif %}if (n_valid) {{% if tileM == 1 %}56 unmodified lineslet k4 = k_words_total * 4u;let a_row = a_base4 + src_m * params.K;let a0 = a[a_row + k4];var a1: {{ aScalar }} = {{ "128u" }};var a2: {{ aScalar }} = {{ "128u" }};if (tail_lanes > 1u) { a1 = a[a_row + k4 + 1u]; }if (tail_lanes > 2u) { a2 = a[a_row + k4 + 2u]; }let a3: {{ aScalar }} = {{ "128u" }};let v = vec4<{{ aScalar }}>(a0, a1, a2, a3);packed = pack_a(v);{% if needsASum %}{{ "a_row_sum[tid] += dot4_packed(packed, 0x01010101u);" if ownRowSums else "atomicAdd(&a_row_sum[tid], sum4_a(v));" }}{% endif %}}a_tile[tid * KT_WORDS] = packed;24 unmodified lines// Fold bias + zero-point corrections (exact in modular i32 arithmetic).let cb: i32 = {{ "128" if bUnsigned else "0" }}{% if hasBZero %} - read_b_zero({% if bZeroPerColumn %}col{% endif %}){% endif %};let ca: i32 = {{ "128" }}{% if hasAZero %} - read_a_zero(){% endif %};let kcc: i32 = i32(params.K) * ca * cb;{% if needsBSum and tileM == 1 %}let sum_b_total = sum_b{% for u in range(1, GEMV_UNROLL) %} + sum_b_{{ u }}{% endfor %};5 unmodified linesif (mr < params.M) {var acc = r{{ m }}{% if tileM == 1 %}{% for u in range(1, GEMV_UNROLL) %} + r0_{{ u }}{% endfor %}{% endif %};{% if needsASum %}acc = acc + cb * {% if ownRowSums %}a_row_sum[{{ m }}u]{% else %}atomicLoad(&a_row_sum[{{ m }}u]){% endif %};{% endif %}acc = acc + ca * {% if tileM == 1 %}sum_b_total{% else %}sum_b{% endif %};acc = acc + kcc;2 unmodified lines}{% endfor %}}{% endif %}
12345678910111230 unmodified lines434445464748492 unmodified lines52535455565758{% 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 }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}// Leaves the integer domain once, at the end of the QKV projection: the exact// int32 accumulator becomes `accumulator * input_scale * weight_scale[column] + bias[column]`,30 unmodified lineslet column = part * HIDDEN + head * HEAD_SIZE + lane;let accumulator = qkv_accumulator[row * (3u * HIDDEN) + column];let dequantScale = input_scale[0] * weight_scale[{{ "column" if weightScalePerColumn else "0u" }}];value = f32(accumulator) * dequantScale + bias[column];}let batchIndex = row / params.seq;2 unmodified linesif (part == 0u) {q_scratch[row * QKV_HIDDEN + laneOffset] = value;} else {let stateRow = ((part - 1u) * params.batch + batchIndex) * params.total + params.past + token;kv_scratch[stateRow * QKV_HIDDEN + laneOffset] = value;}}12345678910111213141516171819202130 unmodified lines525354555657585960616263642 unmodified lines67686970717273747576777879808182{% 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 }}{% if headLocalKV %}{% set floatType = "f32" %}{% set uintType = "u32" %}fn rounded_product(a: {{ floatType }}, b: {{ floatType }}) -> {{ floatType }} {let sign = (bitcast<{{ uintType }}>(a) ^ bitcast<{{ uintType }}>(b)) & {{ uintType }}(0x80000000u);return fma(a, b, bitcast<{{ floatType }}>(sign));}{% endif %}// Leaves the integer domain once, at the end of the QKV projection: the exact// int32 accumulator becomes `accumulator * input_scale * weight_scale[column] + bias[column]`,30 unmodified lineslet column = part * HIDDEN + head * HEAD_SIZE + lane;let accumulator = qkv_accumulator[row * (3u * HIDDEN) + column];let dequantScale = input_scale[0] * weight_scale[{{ "column" if weightScalePerColumn else "0u" }}];{% if headLocalKV %}// Round the scaled projection to f32 before adding the bias.let scaled = rounded_product(f32(accumulator), dequantScale);value = fma(1.0, scaled, bias[column]);{% else %}value = f32(accumulator) * dequantScale + bias[column];{% endif %}}let batchIndex = row / params.seq;2 unmodified linesif (part == 0u) {q_scratch[row * QKV_HIDDEN + laneOffset] = value;} else {{% if headLocalKV %}let headBase = (batchIndex * NUM_HEADS + head) * params.total * HEAD_PAD;if (part == 1u) {kv_scratch[headBase + ((lane / 4u) * params.total + token) * 4u + lane % 4u] = value;} else {kv_scratch[params.batch * params.total * QKV_HIDDEN + headBase + token * HEAD_PAD + lane] = value;}{% else %}let stateRow = ((part - 1u) * params.batch + batchIndex) * params.total + (params.total - params.seq) + token;kv_scratch[stateRow * QKV_HIDDEN + laneOffset] = value;{% endif %}}}
20 unmodified lines2122232425262728293031323334353637383940414243444518 unmodified lines646566676869707172737475764 unmodified lines8182838485868711 unmodified lines9910010110220 unmodified linesvar<workgroup> scratch: array<array<array<f32, 64>, 4>, {{ sgmatSubgroups }}>;{% endif %}@compute @workgroup_size({{ sgmatWorkgroup }}){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) wid: vec3<u32>,@builtin(local_invocation_index) tid: u32,@builtin(subgroup_invocation_id) lane: u32,@builtin(subgroup_size) subgroup_size: u32) {let subgroup = tid / subgroup_size;let base_A = (subgroup % {{ sgmatRowGroups }}u) * 16u;let base_B = (subgroup / {{ sgmatRowGroups }}u) * 32u;let row = lane / 4u;let col = (lane % 4u) * 2u;// Bound adjusted byte magnitudes from scalar zero points. A column-wise// B zero point keeps the full byte-difference bound for the whole tile.let max_a = {% if hasAZero %}u32(max(abs({{ 0 if aUnsigned else (0 - 128) }} - i32(a_zero_point[0])), abs({{ 255 if aUnsigned else 127 }} - i32(a_zero_point[0])))){% else %}{{ 255 if aUnsigned else 128 }}u{% endif %};let max_b = {% if hasBZero and not bZeroPerColumn %}u32(max(abs({{ 0 if bUnsigned else (0 - 128) }} - i32(b_zero_point[0])), abs({{ 255 if bUnsigned else 127 }} - i32(b_zero_point[0])))){% else %}{{ 255 if hasBZero or bUnsigned else 128 }}u{% endif %};let partial_k = (16777216u / (max_a * max_b) / TILE_K) * TILE_K;var totals: array<i32, 16>;for (var partial = 0u; partial < params.K; partial += partial_k) {{% for r in range(2) %}{% for c in range(4) %}var matC{{ r }}{{ c }}: subgroup_matrix_result<f32, 8, 8>;{% endfor %}{% endfor %}let partial_end = min(params.K, partial + partial_k);for (var kb = partial; kb < partial_end; kb += TILE_K) {18 unmodified linesworkgroupBarrier();for (var step = 0u; step < TILE_K; step += 8u) {{% for r in range(2) %}let matA{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<{{ precastScalar if precastOperands else "f32" }}, 8, 8>, row_major>(&{{ "a" if precastOperands else "tile_A" }}, (base_A + {{ r * 8 }}u) * TILE_K + step, {{ "PADDED_K" if precastOperands else "TILE_K" }});{% endfor %}{% for c in range(4) %}let matB{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<{{ precastScalar if precastOperands else "f32" }}, 8, 8>, row_major>(&{{ "b" if precastOperands else "tile_B" }}, step * TILE_N + base_B + {{ c * 8 }}u, {{ "PADDED_N" if precastOperands else "TILE_N" }});{% endfor %}{% for r in range(2) %}{% for c in range(4) %}matC{{ r }}{{ c }} = subgroupMatrixMultiplyAccumulate(matA{{ r }}, matB{{ c }}, matC{{ r }}{{ c }});{% endfor %}{% endfor %}}workgroupBarrier();4 unmodified lines{% endif %}{% for r in range(2) %}{% for c in range(4) %}subgroupMatrixStore<row_major>({% if sgmatReuseStaging %}&tile_A{% else %}&scratch[subgroup][{{ c }}]{% endif %}, {% if sgmatReuseStaging %}subgroup * 256u + {{ c * 64 }}u{% else %}0u{% endif %}, matC{{ r }}{{ c }}, 8u);{% endfor %}workgroupBarrier();{% for c in range(4) %}{% for h in range(2) %}11 unmodified lines}}{% endfor %}{% endfor %}{% endfor %}}20 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401414 unmodified lines14614714814915015115211 unmodified lines16416516616716816917017117217317417517617717817918018118218318418518618720 unmodified linesvar<workgroup> scratch: array<array<array<f32, 64>, 4>, {{ sgmatSubgroups }}>;{% 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;}// 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 }}) + (matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u]){{ "," 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 }}) + {{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u]){{ "," 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 subgroup = matrixRole;let base_A = (subgroup % {{ sgmatRowGroups }}u) * 16u;let base_B = (subgroup / {{ sgmatRowGroups }}u) * 32u;let row = lane / 4u;let col = (lane % 4u) * 2u;// Bound adjusted byte magnitudes from scalar zero points. A column-wise// B zero point keeps the full byte-difference bound for the whole tile.let max_a = {% if hasAZero %}u32(max(abs({{ 0 }} - i32(a_zero_point[0])), abs({{ 255 }} - i32(a_zero_point[0])))){% else %}{{ 255 }}u{% endif %};let max_b = {% if hasBZero and not bZeroPerColumn %}u32(max(abs({{ 0 if bUnsigned else (0 - 128) }} - i32(b_zero_point[0])), abs({{ 255 if bUnsigned else 127 }} - i32(b_zero_point[0])))){% else %}{{ 255 if hasBZero or bUnsigned else 128 }}u{% endif %};let partial_k = (16777216u / (max_a * max_b) / TILE_K) * TILE_K;var totals: array<i32, 16>;for (var partial = 0u; partial < params.K; partial += partial_k) {{% for r in range(2) %}{% for c in range(4) %}var matC{{ r }}{{ c }}: {{ matrixType(matrixSoftware, "result", "f32") }};{% endfor %}{% endfor %}let partial_end = min(params.K, partial + partial_k);for (var kb = partial; kb < partial_end; kb += TILE_K) {18 unmodified linesworkgroupBarrier();for (var step = 0u; step < TILE_K; step += 8u) {{% for r in range(2) %}let matA{{ r }} = {% set quantExactAOffset %}(base_A + {{ r * 8 }}u) * TILE_K + step{% endset %}{{ matrixLoad(matrixSoftware, "left", precastScalar if precastOperands else "f32", "row_major", "&" ~ ("a" if precastOperands else "tile_A"), quantExactAOffset, "PADDED_K" if precastOperands else "TILE_K") }};{% endfor %}{% for c in range(4) %}let matB{{ c }} = {% set quantExactBOffset %}step * TILE_N + base_B + {{ c * 8 }}u{% endset %}{{ matrixLoad(matrixSoftware, "right", precastScalar if precastOperands else "f32", "row_major", "&" ~ ("b" if precastOperands else "tile_B"), quantExactBOffset, "PADDED_N" if precastOperands else "TILE_N") }};{% endfor %}{% for r in range(2) %}{% for c in range(4) %}matC{{ r }}{{ c }} = {{ matrixMma(matrixSoftware, "f32", "matA" ~ (r), "matB" ~ (c), "matC" ~ (r) ~ (c)) }};{% endfor %}{% endfor %}}workgroupBarrier();4 unmodified lines{% endif %}{% for r in range(2) %}{% for c in range(4) %}{% set quantExactStorePointer %}{% if sgmatReuseStaging %}&tile_A{% else %}&scratch[subgroup][{{ c }}]{% endif %}{% endset %}{% set quantExactStoreOffset %}{% if sgmatReuseStaging %}subgroup * 256u + {{ c * 64 }}u{% else %}0u{% endif %}{% endset %}{{ matrixStore(matrixSoftware, "row_major", quantExactStorePointer, quantExactStoreOffset, "matC" ~ (r) ~ (c), "8u") }}{% endfor %}workgroupBarrier();{% for c in range(4) %}{% for h in range(2) %}11 unmodified lines}}{% endfor %}{% endfor %}{% endfor %}{% endmacro %}@compute @workgroup_size({{ sgmatWorkgroup }}){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) wid: vec3<u32>,@builtin(local_invocation_index) tid: u32,@builtin(subgroup_size) matrixPhysicalWidth: u32,@builtin(subgroup_invocation_id) matrixPhysicalLane: u32) {let matrixRole = claimMatrixSubgroupRole(matrixPhysicalWidth, 32u);let matrixAcceptedHere = matrixTopologyAccepted(tid, {{ sgmatWorkgroup }}u / 32u);matrixSoftwareLane = tid % 32u;if (matrixAcceptedHere) {let lane = matrixPhysicalLane;{{ matrixKernelBody(false) }}} else {let matrixRole = tid / 32u;let lane = tid % 32u;{{ matrixKernelBody(true) }}}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305{%- set EPW = 16 -%}{%- set FK = 32 -%}{%- set VT = "i8" -%}{%- set ACC = "i32" -%}{%- set SR = 2 -%}{%- set SC = 2 -%}{%- set FR = sgGemmFragRows -%}{%- set FC = sgGemmFragCols -%}{%- set BK = 64 -%}{%- set PAD = 16 -%}{%- set AM = "row" -%}{%- set BMJ = "col" -%}{%- set ASUMS = needRowSums | default(false) -%}{%- set TM = SR * FR * 16 -%}{%- set TN = SC * FC * 16 -%}{%- set T = 128 -%}{%- set A_ROWS = TM if AM == "row" else BK -%}{%- set A_LEN = BK if AM == "row" else TM -%}{%- set B_ROWS = BK if BMJ == "row" else TN -%}{%- set B_LEN = TN if BMJ == "row" else BK -%}{%- set ASTRIDE = ((A_LEN + PAD) / EPW) | int -%}{%- set BSTRIDE = ((B_LEN + PAD) / EPW) | int -%}{%- set A_SLOTS = ((TM * BK / EPW) / T) | int -%}{%- set B_SLOTS = ((BK * TN / EPW) / T) | int -%}{%- set SCRATCH = SR * SC * 64 * FC -%}{%- set A_SIZE = max(A_ROWS * ASTRIDE, SCRATCH) -%}{%- set BIAS_A = 128 -%}{%- set BIAS_B = 128 if bUnsigned else 0 -%}{%- set AOFF = "" -%}{%- set BOFF = "" -%}{%- macro stage_load(name, kb) -%}{%- set LEN = A_LEN if name == "a" else B_LEN -%}{%- set SLOTS = A_SLOTS if name == "a" else B_SLOTS -%}{%- for s in range(SLOTS) %} { let flat = tid + {{ s * T }}u; let r = flat / {{ (LEN / EPW) | int }}u; let c = (flat % {{ (LEN / EPW) | int }}u) * {{ EPW }}u;{%- if name == "a" and AM == "row" %} if (rowBase + r < M && {{ kb }} + c < K) { next{{ name | upper }}{{ s }} = a[({{ AOFF }}(rowBase + r) * K + {{ kb }} + c) / {{ EPW }}u]; } else { next{{ name | upper }}{{ s }} = vec4<u32>(); }{%- elif name == "a" %} if ({{ kb }} + r < K && rowBase + c < M) { next{{ name | upper }}{{ s }} = a[({{ AOFF }}({{ kb }} + r) * M + rowBase + c) / {{ EPW }}u]; } else { next{{ name | upper }}{{ s }} = vec4<u32>(); }{%- else %} if (colBase + r < N && {{ kb }} + c < K) { next{{ name | upper }}{{ s }} = b[({{ BOFF }}(colBase + r) * K + {{ kb }} + c) / {{ EPW }}u]; } else { next{{ name | upper }}{{ s }} = vec4<u32>(); }{%- endif %} }{%- endfor %}{%- endmacro -%}{%- macro stage_store(name) -%}{%- set LEN = A_LEN if name == "a" else B_LEN -%}{%- set SLOTS = A_SLOTS if name == "a" else B_SLOTS -%}{%- set STRIDE = ASTRIDE if name == "a" else BSTRIDE -%}{%- for s in range(SLOTS) %} tile{{ name | upper }}[((tid + {{ s * T }}u) / {{ (LEN / EPW) | int }}u) * {{ STRIDE }}u + (tid + {{ s * T }}u) % {{ (LEN / EPW) | int }}u] = next{{ name | upper }}{{ s }};{%- endfor %}{%- endmacro -%}{%- macro load_left(r, step) -%}subgroupMatrixLoad<subgroup_matrix_left<{{ VT }}, {{ FK }}, 16>, row_major>(&tileA, subRow * {{ ASTRIDE }}u + {{ r * 16 * ASTRIDE + step * 2 }}u, {{ ASTRIDE }}u){%- endmacro -%}{%- macro load_right(c, step) -%}subgroupMatrixLoad<subgroup_matrix_right<{{ VT }}, 16, {{ FK }}>, col_major>(&tileB, subCol * {{ BSTRIDE }}u + {{ c * 16 * BSTRIDE + step * 2 }}u, {{ BSTRIDE }}u){%- endmacro -%}enable subgroups;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 dot4I8Packed(e1: u32, e2: u32) -> i32 { let shifts = vec4<u32>(0u, 8u, 16u, 24u); let a_bytes = (vec4<u32>(e1) >> shifts) & vec4<u32>(0xffu); let b_bytes = (vec4<u32>(e2) >> shifts) & vec4<u32>(0xffu); let a = vec4<i32>(a_bytes ^ vec4<u32>(0x80u)) - vec4<i32>(128i); let b = vec4<i32>(b_bytes ^ vec4<u32>(0x80u)) - vec4<i32>(128i); return dot(a, b);}{% endif %}{{ env.wgsl.resourceDeclarations }}const N: u32 = {{ sgGemmN }}u;const K: u32 = {{ sgGemmK }}u;// vec4 elements give each tile a 16-byte base, which eight-bit matrix loads need.var<workgroup> tileA: array<vec4<u32>, {{ A_SIZE }}>;var<workgroup> tileB: array<vec4<u32>, {{ B_ROWS * BSTRIDE }}>;{% if ASUMS %}var<workgroup> rowPart: array<i32, {{ (BK / 16) | int * TM }}>;var<workgroup> rowSum: array<i32, {{ TM }}>;var<workgroup> colCb: array<vec4<i32>, {{ (TN / 4) | int }}>;{% endif %}var<workgroup> colPart: array<i32, {{ (BK / 16) | int * TN }}>;var<workgroup> colAdd: array<vec4<i32>, {{ (TN / 4) | int }}>;// 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;}
fn zeroCa() -> i32 {{% if hasAZero %} return {{ BIAS_A }}i - i32(a_zero_point[0]);{% else %} return {{ BIAS_A }}i;{% endif %}}{% if hasBZero and bZeroPerColumn %}fn zeroCb(n: u32) -> i32 { return {{ BIAS_B }}i - i32(b_zero_point[min(n, N - 1u)]);}{% else %}fn zeroCb() -> i32 {{% if hasBZero %} return {{ BIAS_B }}i - i32(b_zero_point[0]);{% else %} return {{ BIAS_B }}i;{% endif %}}{% endif %}fn byteSum(v: vec4<u32>) -> i32 { return dot4I8Packed(v.x, 0x01010101u) + dot4I8Packed(v.y, 0x01010101u) + dot4I8Packed(v.z, 0x01010101u) + dot4I8Packed(v.w, 0x01010101u);}fn byteA(m: u32, k: u32) -> i32 { let e = {{ "m * K + k" if AM == "row" else "k * params.M + m" }}; return extractBits(bitcast<i32>(a[e / 16u][(e % 16u) / 4u]), 8u * (e % 4u), 8u);}fn byteB(k: u32, n: u32) -> i32 { let e = {{ "k * N + n" if BMJ == "row" else "n * K + k" }}; return extractBits(bitcast<i32>(b[e / 16u][(e % 16u) / 4u]), 8u * (e % 4u), 8u);}{% macro cbAt(column) %}zeroCb({{ column if hasBZero and bZeroPerColumn else "" }}){% endmacro %}
@compute @workgroup_size({{ T }}, 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 * {{ TM }}u; let colBase = wid.x * {{ TN }}u; let role = min(claimMatrixSubgroupRole(width, 32u), {{ SR * SC - 1 }}u); if (matrixTopologyAccepted(tid, {{ SR * SC }}u)) { let subRow = (role / {{ SC }}u) * {{ FR * 16 }}u; let subCol = (role % {{ SC }}u) * {{ FC * 16 }}u;{% for s in range(A_SLOTS) %} var nextA{{ s }}: vec4<u32>;{% if ASUMS %} var sumA{{ s }} = 0i;{% endif %}{% endfor %}{% for s in range(B_SLOTS) %} var nextB{{ s }}: vec4<u32>; var sumB{{ s }} = 0i;{% endfor %}{{ stage_load("a", "0u") }}{{ stage_load("b", "0u") }}{% for r in range(FR) %}{% for c in range(FC) %} var acc{{ r }}_{{ c }}: subgroup_matrix_result<{{ ACC }}, 16, 16>;{% endfor %}{% endfor %} for (var kk = 0u; kk < K; kk += {{ BK }}u) {{{ stage_store("a") }}{{ stage_store("b") }}{% if ASUMS %}{% for s in range(A_SLOTS) %} sumA{{ s }} += byteSum(nextA{{ s }});{% endfor %}{% endif %}{% for s in range(B_SLOTS) %} sumB{{ s }} += byteSum(nextB{{ s }});{% endfor %} workgroupBarrier(); // Issue the next slice's global loads before this slice's multiplies. if (kk + {{ BK }}u < K) {{{ stage_load("a", "kk + " ~ BK ~ "u") }}{{ stage_load("b", "kk + " ~ BK ~ "u") }} }{% for step in range((BK / FK) | int) %} {{% for r in range(FR) %} let left{{ r }} = {{ load_left(r, step) }};{% endfor %}{% for c in range(FC) %} let right{{ c }} = {{ load_right(c, step) }};{% endfor %}{% for r in range(FR) %}{% for c in range(FC) %} acc{{ r }}_{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ r }}, right{{ c }}, acc{{ r }}_{{ c }});{% endfor %}{% endfor %} }{% endfor %} workgroupBarrier(); } // Each staged word's row (A) or column (B) is fixed across K slices, so its partial sums // reduce once here over the words of one slice.{% if ASUMS %}{% for s in range(A_SLOTS) %} rowPart[((tid + {{ s * T }}u) % {{ (BK / 16) | int }}u) * {{ TM }}u + (tid + {{ s * T }}u) / {{ (BK / 16) | int }}u] = sumA{{ s }};{% endfor %}{% endif %}{% for s in range(B_SLOTS) %} colPart[((tid + {{ s * T }}u) % {{ (BK / 16) | int }}u) * {{ TN }}u + (tid + {{ s * T }}u) / {{ (BK / 16) | int }}u] = sumB{{ s }};{% endfor %} workgroupBarrier();{% if ASUMS %} for (var r = tid; r < {{ TM }}u; r += {{ T }}u) { var s = 0i; for (var w = 0u; w < {{ (BK / 16) | int }}u; w++) { s += rowPart[w * {{ TM }}u + r]; } rowSum[r] = s; }{% endif %} for (var c4 = tid; c4 < {{ (TN / 4) | int }}u; c4 += {{ T }}u) {{% if ASUMS %} var cbv = vec4<i32>();{% endif %} let ca = zeroCa(); var addv = vec4<i32>(); for (var j = 0u; j < 4u; j++) { let c = c4 * 4u + j; let cb = {{ cbAt("colBase + c") }};{% if ASUMS %} cbv[j] = cb;{% endif %} var s = 0i; for (var w = 0u; w < {{ (BK / 16) | int }}u; w++) { s += colPart[w * {{ TN }}u + c]; } addv[j] = ca * s + i32(K) * ca * cb; }{% if ASUMS %} colCb[c4] = cbv;{% endif %} colAdd[c4] = addv; } workgroupBarrier(); // One row of fragments at a time goes through a per-subgroup scratch block so each lane // writes whole 16-byte vectors with row/column guards, corrections and conversion. let scratch = role * {{ 64 * FC }}u;{% for r in range(FR) %}{% for c in range(FC) %} subgroupMatrixStore<row_major>(&tileA, scratch + {{ 4 * c }}u, acc{{ r }}_{{ c }}, {{ 4 * FC }}u);{% endfor %} workgroupBarrier(); for (var j = 0u; j < {{ 2 * FC }}u; j++) { let v = j * 32u + lane; let rowL = subRow + {{ 16 * r }}u + v / {{ 4 * FC }}u; let col4L = subCol / 4u + v % {{ 4 * FC }}u; let row = rowBase + rowL; let col4 = colBase / 4u + col4L; if (row < M && col4 < N / 4u) { var o = bitcast<vec4<i32>>(tileA[scratch + v]);{% if ASUMS %} o += colCb[col4L] * rowSum[rowL];{% endif %} o += colAdd[col4L]; y[row * (N / 4u) + col4] = o; } } workgroupBarrier();{% endfor %} } else { // Portable fallback when the subgroup topology check fails. let ca = zeroCa(); for (var cell = tid; cell < {{ (TM * TN / 4) | int }}u; cell += {{ T }}u) { let row = rowBase + cell / {{ (TN / 4) | int }}u; let n = colBase + (cell % {{ (TN / 4) | int }}u) * 4u; if (row < M && n < N) { let cb = vec4<i32>({{ cbAt("n") }}, {{ cbAt("n + 1u") }}, {{ cbAt("n + 2u") }}, {{ cbAt("n + 3u") }}); var sum = vec4<i32>(); for (var k = 0u; k < K; k++) { let av = byteA(row, k) + ca; sum += av * (vec4<i32>(byteB(k, n), byteB(k, n + 1u), byteB(k, n + 2u), byteB(k, n + 3u)) + cb); } y[(row * N + n) / 4u] = sum; } } }}README.md+39-65
build/webgpu/bench.json+35-6
build/webgpu/integer-pack-columns.wgsl.jinjaAdded+20
build/webgpu/integer-pack-rows.wgsl.jinjaAdded+16
build/webgpu/manifest.json
build/webgpu/matrix-shaped-integer-gemm.wgsl.jinjaAdded+217
build/webgpu/metadata.json+1-75
build/webgpu/qattention-attend.wgsl.jinja+702-46
build/webgpu/qattention-kv-permute.wgsl.jinja+3-2
build/webgpu/qattention-mask.wgsl.jinja+3-2
build/webgpu/quant-dp4a-matmul.wgsl.jinja → build/webgpu/qattention-project.wgsl.jinjaRenamed+185-10
build/webgpu/qattention-qkv-scatter.wgsl.jinja+27-3
build/webgpu/quant-exact-matrix.wgsl.jinja+97-12
build/webgpu/subgroup-matrix-gemm.wgsl.jinjaAdded+305
build/webgpu/test.json