sync 4385228f788d
Browse filesFiles changed (14)
- README.md+44-17
- build/webgpu/bench.json+30-2
- build/webgpu/cast-scalar-x4.wgsl.jinja+18-1
- build/webgpu/manifest.json+1-406
- build/webgpu/matmul-bnb4-gemv-words.wgsl.jinjaAdded+90
- build/webgpu/matmul-bnb4-gemv.wgsl.jinja+133-13
- build/webgpu/matmul-bnb4-native16-packed.wgsl.jinjaAdded+331
- build/webgpu/matmul-bnb4-sgmat.wgsl.jinja+122-45
- build/webgpu/matmul-bnb4-tiled-reg.wgsl.jinjaAdded+132
- build/webgpu/matmul-bnb4-tiled.wgsl.jinja+19-12
- build/webgpu/matmul-bnb4.wgsl.jinja+15-7
- build/webgpu/metadata.json+1-34
- build/webgpu/reduce-axis0-splitk-combine.wgsl.jinjaAdded+109
- build/webgpu/test.json+331-59
20 unmodified lines212223242425262726 unmodified lines54555657585960585960616263646566676864697071726869707172737475767374757677787980818283848586878889819091929394959697989989901001011021031041051061071081091101111121131141151161171181191201211221236 unmodified lines13013113213313420 unmodified lines| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence || --- | --- | --- | --- | --- | --- | --- || `aT` | `A` | `T1` | `2` | — | Float input matrix of shape `(M, K)`, not quantized. | required || `bT` | `B` | `T2` | `1` | — | The `[N, K]` weight, flattened and quantized to 4 bits, stored as `(N * K + 1) / 2` bytes; the ONNX type is uint8 (this WebGPU implementation reads one widened u32 per stored byte). | required || `bT` | `B` | `T2` | `1` | — | The `[N, K]` weight, flattened and quantized to 4 bits, stored as `(N * K + 1) / 2` bytes; the ONNX type is uint8. The kernels read the uint8 data directly as 32-bit words, four bytes each, so no repacking is needed. | required || `absmaxT` | `absmax` | `T1` | `1` | — | Per-block absolute-maximum dequantization scales of shape `((N * K + block_size - 1) / block_size)`, same dtype as A. | required |
## Outputs26 unmodified lines
One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
- `native16_packed_64x64`, `native16_packed_128x128` — Decodes 4-bit bitsandbytes weights into packed shared half operands and multiplies half activations by them with float32 accumulation, converting each output to half once.- `gemv_row_groups` — Distributes small matrix products across independent column and row groups with cooperative f32 reduction along K.- `gemv_rows` — Shares each dequantized weight across a small query-row block and cooperatively reduces f32 sums along K.- `sgmat_hybrid_rows` — Combines full and partial row tiles in one matrix dispatch. Complete tiles read activations directly; partial tiles stage bounded rows in f32 and reuse weight staging for output. Float16 requests widen before the multiply and narrow once afterward.- `sgmat_hybrid_rows_widened` — Combines full and partial row tiles in one matrix dispatch. Complete tiles read activations directly; partial tiles stage bounded rows in f32 and reuse weight staging for output. Float16 requests widen before the multiply and narrow once afterward.- `sgmat_staged_rows` — Stages partial activation rows in f32, dequantizes the shared weight tile, and reuses dead weight staging for masked output stores.- `sgmat_widened` — Runs the subgroup-matrix tier for a float16 request by widening the activations to float32 either side of the multiply. The matrix units this operator uses accumulate in float32 from float32 operands; the device's float16 configuration returns a float16 result, so feeding them float16 directly would drop the accumulator's precision.- `sgmat_widened` — Runs the subgroup-matrix variant for a float16 request by widening the activations to float32 either side of the multiply, since the device's float16 configuration returns a float16 result. Full row tiles read activations directly; a partial last tile stages bounded rows and reuses weight staging for output.- `sgmat` — Multiplies activations by dequantized weight tiles on subgroup matrices. Full float32 row tiles read activations directly; partial row counts stage activation rows in f32 and reuse dead weight staging for masked output stores.- `gemv_words` — Few-row products for up to 8 rows: thirty-two lanes share an output column and eight columns a workgroup; each lane decodes four independent stored words per step into eight K-consecutive weights each and applies them to every row from registers, then a tree reduction closes each column.- `tiled_reg_splitk` — Splits underfilled register tiles (16 to 128 rows by 64 columns, sized to the batch) along K: each slice decodes one stored word per lane into eight K-consecutive float32 weights of a lane-interleaved tile and stores float32 partials, which a combine pass sums in slice order.- `tiled_reg` — Register tiles of 16 to 128 rows by 64 columns, sized to the batch: each lane decodes one stored word into eight K-consecutive float32 weights of a K-major, lane-interleaved tile, then accumulates its rows by four columns with chained FMAs in K order.
## Device requirements
Some 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.Some implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.
## Files
- [`metadata.json`](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- [`cast-scalar-x4.wgsl.jinja`](build/webgpu/cast-scalar-x4.wgsl.jinja)- [`matmul-bnb4-gemv.wgsl.jinja`](build/webgpu/matmul-bnb4-gemv.wgsl.jinja)- [`matmul-bnb4-sgmat.wgsl.jinja`](build/webgpu/matmul-bnb4-sgmat.wgsl.jinja)- [`matmul-bnb4-tiled.wgsl.jinja`](build/webgpu/matmul-bnb4-tiled.wgsl.jinja)- [`matmul-bnb4.wgsl.jinja`](build/webgpu/matmul-bnb4.wgsl.jinja)- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/test.json) — correctness cases- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/bench.json) — benchmark cases- [`cast-scalar-x4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/cast-scalar-x4.wgsl.jinja)- [`matmul-bnb4-gemv-words.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/matmul-bnb4-gemv-words.wgsl.jinja)- [`matmul-bnb4-gemv.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/matmul-bnb4-gemv.wgsl.jinja)- [`matmul-bnb4-native16-packed.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/matmul-bnb4-native16-packed.wgsl.jinja)- [`matmul-bnb4-sgmat.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/matmul-bnb4-sgmat.wgsl.jinja)- [`matmul-bnb4-tiled-reg.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/matmul-bnb4-tiled-reg.wgsl.jinja)- [`matmul-bnb4-tiled.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/matmul-bnb4-tiled.wgsl.jinja)- [`matmul-bnb4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/matmul-bnb4.wgsl.jinja)- [`reduce-axis0-splitk-combine.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulBnb4/blob/v1/build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja)
## Use with `@huggingface/kernels`
```shnpm install --save-exact @huggingface/kernels@0.0.1-preview.3npm 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`.
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.MatMulBnb4", { version: 1 });
const aTData = Float32Array.of( 0.17091933, 0.16533019, 0.15063293, 0.1313149, 0.11202312, 0.097040445, 0.08980678, 0.092533216, 0.10594729, 0.12919523, 0.15991104, 0.19444641, 0.22823927, 0.25628528, 0.2736664, 0.2760843, 0.2603464, 0.2247556, 0.16936424, 0.09606541, 0.008510161, -0.08814437, -0.18763463, -0.28310272, -0.3676744, -0.43505034, -0.48005563, -0.49909735, -0.49048677, -0.4545969, -0.3938397, -0.31246522, -0.21620105, -0.11176469, -0.0062940842, 0.09325158, 0.18066607, 0.2509931, 0.30090147, 0.32890537, 0.3354117, 0.32259256, 0.29409772, 0.25463665, 0.20947203, 0.16387495, 0.122594416, 0.08939305,);const bTData = Uint8Array.of( 1, 35, 69, 103, 137, 171, 205, 239, 254, 220, 186, 152, 118, 84, 50, 16, 90, 1, 35, 69, 103, 137, 171, 205, 239, 254, 220, 186, 152, 118, 84, 50, 16, 90, 1, 35,);const absmaxTData = Float32Array.of(0.07530118, 0.07724273, 0.07906845, 0.08075418, 0.08227701);
const { yT } = await kernel({ aT: { data: aTData, shape: [2, 24] }, bT: { data: bTData, shape: [36] },6 unmodified lines quant_type: 1, },});console.log({ yT });```22 unmodified lines23242526262728293031323334353637383940414243444546474849505152535455565792 unmodified lines15015115212515315415515622 unmodified lines "metrics": [ { "type": "bandwidth", "value": "numel(shapes.bT) * 4 + (numel(shapes.aT) + numel(shapes.absmaxT) + numel(shapes.yT)) * 4" "value": "numel(shapes.bT) + (numel(shapes.aT) + numel(shapes.absmaxT) + numel(shapes.yT)) * 4" } ] } }, { "name": "bnb4-nf4-decode-m1-k4096-n11008-b64", "preset": "model", "vars": { "M": 1, "K": 4096, "N": 11008, "blockSize": 64 }, "attrs": { "K": 4096, "N": 11008, "block_size": 64, "quant_type": 1 }, "inputs": { "aT": { "shape": [1, 4096], "dtype": "float32", "dist": "normal", "seed": 410, "scale": 0.2 }, "bT": { "shape": [22544384], "dtype": "uint8", "dist": "linearMod", "mod": 256, "step": 7 }, "absmaxT": { "shape": [704512], "dtype": "float32", "dist": "uniform", "seed": 411, "offset": 0.04, "scale": 0.01, "signed": false } }, "outputs": { "yT": { "shape": [1, 11008], "dtype": "float32" } }, "bench": { "metrics": [ { "type": "bandwidth", "value": "numel(shapes.bT) + (numel(shapes.aT) + numel(shapes.absmaxT) + numel(shapes.yT)) * 4" } ] }92 unmodified lines { "name": "bnb4-nf4-speculative-m15-k4096-n4096-b64-band", "provenance": { "notes": "Measures a 15-row NF4 multiply (K=4096, N=4096, block size 64), the verification width of a speculative decoder. `bnb4-nf4-speculative-m16-k4096-n4096-b64-tile-floor-control` is the same multiply with 16 rows." "notes": "Measures an NF4 multiply with M=15, K=4096, N=4096 and block size 64, matching a 15-row verification batch; M=15 is one short of 16." }, "preset": "model", "vars": { "M": 15, "K": 4096, "N": 4096, "blockSize": 64 },1234567891011121314151617181920213 unmodified lines2526271128293031{{ env.wgsl.resourceDeclarations }}{% set narrowsToHalf = outScalar == "f16" and scalar != "f16" %}{% if narrowsToHalf %}
// WGSL lets an f32 -> f16 conversion that overflows return any value (the// finite math assumption), and an implementation may return the largest finite half.// ONNX expects a signed infinity, so magnitudes from 65520 (where round to// nearest overflows) through infinity take an infinity built from the// operand's own sign bit. NaN keeps the ordinary conversion. The infinity is// made from runtime bits: a constant one is a shader-creation error.fn half_ieee(v: f32) -> f16 { let bits = bitcast<u32>(v); let magnitude = bits & 0x7fffffffu; let infinity = bitcast<vec2<f16>>(((bits >> 16u) & 0x8000u) | 0x7c00u).x; return select(f16(v), infinity, magnitude >= 0x477ff000u && magnitude <= 0x7f800000u);}
{% endif %}@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) { // Four scalar conversions per invocation retain vector-like dispatch density even when the3 unmodified lines let base = invocation * 4u;{% for lane in range(4) %} if (base + {{ lane }}u < params.count) { y[base + {{ lane }}u] = {{ outScalar }}(x[base + {{ lane }}u]); y[base + {{ lane }}u] = {% if narrowsToHalf %}half_ieee(f32(x[base + {{ lane }}u])){% else %}{{ outScalar }}(x[base + {{ lane }}u]){% endif %}; }{% endfor %}}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054061{ "domain": "com.microsoft", "name": "MatMulBnb4", "sinceVersion": 1, "inputs": { "aT": { "onnx": "A", "dtype": "T1", "rank": 2 }, "bT": { "onnx": "B", "dtype": "T2", "rank": 1 }, "absmaxT": { "onnx": "absmax", "dtype": "T1", "rank": 1 } }, "outputs": { "yT": { "onnx": "Y", "dtype": "T1", "rank": 2, "shape": "[dim(shapes.aT, 0), attrs.N]" } }, "attributes": { "training_mode": { "default": 0 }, "transB": { "default": 1 }, "K": {}, "N": {}, "block_size": {}, "quant_type": {} }, "attributeConstraints": { "K": { "required": true }, "N": { "required": true }, "block_size": { "required": true }, "quant_type": { "required": true, "values": [0, 1] }, "training_mode": { "values": [0] }, "transB": { "values": [1] } }, "typeConstraints": { "T1": ["float32", "float16"], "T2": ["uint8"] }, "tunables": { "WORKGROUP_SIZE": { "default": 64 }, "TILE_MIN_M": { "default": 4 }, "PORTABLE_TILE_K": { "default": 16 }, "SGMAT_TILE_ROWS": { "default": 64 }, "SGMAT_TALL_TILE_ROWS": { "default": 128 }, "SGMAT_TALL_MIN_M": { "default": 128 }, "SGMAT_TILE_COLS": { "default": 64 }, "SGMAT_TILE_K": { "default": 32 } }, "derive": { "deviceWorkgroupCap": "min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)", "wave32Adapter": "has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 32 and device.adapterInfo.subgroupMaxSize == 32", "canPinSubgroupSize32": "device.features.has(\"subgroups\") and device.features.has(\"subgroup-size-control\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize <= 32 and device.adapterInfo.subgroupMaxSize >= 32", "pinSubgroupSize32": "canPinSubgroupSize32 and not wave32Adapter", "wave32Effective": "wave32Adapter or pinSubgroupSize32", "portableTileRows": "8 * min(8, max(1, ceilDiv(dim(shapes.aT, 0), 8)))", "packedBytesExpected": "ceilDiv(attrs.N * attrs.K, 2)", "absmaxCountExpected": "ceilDiv(attrs.N * attrs.K, attrs.block_size)", "aFloatOk": "(tensorDtypes.aT == \"float32\" or tensorDtypes.aT == \"float16\") and f16Ok(tensorDtypes.aT)", "portableWorkgroupSize": "min(tunables.WORKGROUP_SIZE, deviceWorkgroupCap)", "commonShapeValid": "ranks.aT == 2 and ranks.bT == 1 and ranks.absmaxT == 1 and ranks.yT == 2 and aFloatOk and tensorDtypes.bT == \"uint8\" and tensorDtypes.absmaxT == tensorDtypes.aT and tensorDtypes.yT == tensorDtypes.aT and attrs.K > 0 and attrs.N > 0 and attrs.block_size >= 16 and pow2ceil(attrs.block_size) == attrs.block_size and dim(shapes.aT, 1) == attrs.K and dim(shapes.bT, 0) == packedBytesExpected and dim(shapes.absmaxT, 0) == absmaxCountExpected and dim(shapes.yT, 0) == dim(shapes.aT, 0) and dim(shapes.yT, 1) == attrs.N", "gemvShapeValid": "commonShapeValid and dim(shapes.aT, 0) == 1", "portableWorkgroupFits": "portableWorkgroupSize > 0 and portableWorkgroupSize * 16 <= device.limits.maxComputeWorkgroupStorageSize", "portableTileKValid": "tunables.PORTABLE_TILE_K >= 8 and tunables.PORTABLE_TILE_K % 8 == 0", "tileEligible": "commonShapeValid and dim(shapes.aT, 0) >= tunables.TILE_MIN_M and portableTileKValid", "tileWorkgroupStorageBytes": "(portableTileRows * dtypeBytes(tensorDtypes.aT) + 64 * 4) * tunables.PORTABLE_TILE_K", "tileWorkgroupFits": "16 <= device.limits.maxComputeWorkgroupSizeX and 8 <= device.limits.maxComputeWorkgroupSizeY and 128 <= device.limits.maxComputeInvocationsPerWorkgroup and tileWorkgroupStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and ceilDiv(attrs.N, 64) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(dim(shapes.aT, 0), portableTileRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)", "sgmatMatrixSize": "8", "sgmatTileRows": "tunables.SGMAT_TALL_TILE_ROWS if dim(shapes.aT, 0) >= tunables.SGMAT_TALL_MIN_M else tunables.SGMAT_TILE_ROWS", "sgmatRowSubtiles": "4", "sgmatSubRows": "sgmatTileRows / sgmatRowSubtiles", "sgmatSubCols": "4 * sgmatMatrixSize", "sgmatLoadWidth": "sgmatMatrixSize", "sgmatColSubtiles": "tunables.SGMAT_TILE_COLS / sgmatSubCols", "sgmatNumSubgroups": "sgmatRowSubtiles * sgmatColSubtiles", "sgmatSubgroupSize": "32", "sgmatWorkgroupSize": "sgmatNumSubgroups * sgmatSubgroupSize", "sgmatBLoadsPerRow": "tunables.SGMAT_TILE_K / sgmatLoadWidth", "sgmatWorkgroupStorageBytes": "4 * tunables.SGMAT_TILE_COLS * tunables.SGMAT_TILE_K", "sgmatDispatchN": "ceilDiv(attrs.N, tunables.SGMAT_TILE_COLS)", "sgmatDispatchM": "ceilDiv(dim(shapes.aT, 0), sgmatTileRows)", "sgmatWorkgroupFits": "sgmatWorkgroupSize <= deviceWorkgroupCap and sgmatWorkgroupStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and sgmatDispatchN <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and sgmatDispatchM <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)", "sgmatWidenBytes": "numel(shapes.aT) * 4", "sgmatWidenOutBytes": "dim(shapes.aT, 0) * attrs.N * 4", "sgmatWidenFits": "sgmatWidenBytes <= device.limits.maxStorageBufferBindingSize and sgmatWidenBytes <= device.limits.maxBufferSize and sgmatWidenOutBytes <= device.limits.maxStorageBufferBindingSize and sgmatWidenOutBytes <= device.limits.maxBufferSize", "quantType": "attrs.quant_type", "K": "attrs.K", "N": "attrs.N", "blockSize": "attrs.block_size", "tileCols": "tunables.SGMAT_TILE_COLS", "tileK": "tunables.SGMAT_TILE_K", "matrixSize": "sgmatMatrixSize", "subCols": "sgmatSubCols", "colMatrices": "sgmatSubCols / sgmatMatrixSize", "loadWidth": "sgmatLoadWidth", "rowSubtiles": "sgmatRowSubtiles", "workgroupSize": "sgmatWorkgroupSize", "bLoadsPerRow": "sgmatBLoadsPerRow", "aScalar": "\"f16\" if tensorDtypes.aT == \"float16\" else \"f32\"", "usesF16": "tensorDtypes.aT == \"float16\"", "absmaxScalar": "\"f16\" if tensorDtypes.absmaxT == \"float16\" else \"f32\"", "ABSMAX_LEN": "ceilDiv(attrs.N * attrs.K, attrs.block_size)", "stagedGeometryValid": "tunables.SGMAT_TILE_COLS >= sgmatSubCols and tunables.SGMAT_TILE_COLS % sgmatSubCols == 0 and tunables.SGMAT_TILE_K >= sgmatMatrixSize and tunables.SGMAT_TILE_K % sgmatMatrixSize == 0", "stagedRowSubtiles": "max(1, min(sgmatRowSubtiles, pow2ceil(ceilDiv(dim(shapes.aT, 0), sgmatMatrixSize)), floor(deviceWorkgroupCap / (32 * max(1, sgmatColSubtiles))), floor(tunables.SGMAT_TILE_K / sgmatMatrixSize), floor((device.limits.maxComputeWorkgroupStorageSize - sgmatWorkgroupStorageBytes) / (4 * sgmatMatrixSize * max(1, tunables.SGMAT_TILE_K)))))", "stagedTileRows": "stagedRowSubtiles * sgmatMatrixSize", "stagedLoadWorkgroupTarget": "max(1, min(deviceWorkgroupCap, tunables.SGMAT_TILE_COLS * tunables.SGMAT_TILE_K / sgmatLoadWidth))", "stagedColumnMatrices": "min(4, pow2ceil(max(1, ceilDiv(stagedRowSubtiles * tunables.SGMAT_TILE_COLS * 32, stagedLoadWorkgroupTarget * sgmatMatrixSize))))", "stagedSubCols": "stagedColumnMatrices * sgmatMatrixSize", "stagedWorkgroupSize": "stagedRowSubtiles * (tunables.SGMAT_TILE_COLS / stagedSubCols) * 32", "stagedStorageBytes": "4 * (stagedTileRows + tunables.SGMAT_TILE_COLS) * tunables.SGMAT_TILE_K", "stagedResourcesFit": "stagedWorkgroupSize <= deviceWorkgroupCap and stagedStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and sgmatDispatchN <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(dim(shapes.aT, 0), stagedTileRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)", "sgmatGeometryValid": "tunables.SGMAT_TILE_COLS >= sgmatSubCols and tunables.SGMAT_TILE_COLS % sgmatSubCols == 0 and tunables.SGMAT_TILE_K >= sgmatMatrixSize and tunables.SGMAT_TILE_K % sgmatMatrixSize == 0 and sgmatTileRows >= sgmatRowSubtiles * sgmatMatrixSize and sgmatTileRows % (sgmatRowSubtiles * sgmatMatrixSize) == 0", "prefixTileRows": "tunables.SGMAT_TILE_ROWS", "sgmatFullRows": "floor(dim(shapes.aT, 0) / max(1, prefixTileRows)) * prefixTileRows", "sgmatTailRows": "dim(shapes.aT, 0) - sgmatFullRows", "tailGeometryValid": "tunables.SGMAT_TILE_COLS >= sgmatSubCols and tunables.SGMAT_TILE_COLS % sgmatSubCols == 0 and tunables.SGMAT_TILE_K >= sgmatMatrixSize and tunables.SGMAT_TILE_K % sgmatMatrixSize == 0", "tailRowSubtiles": "max(1, min(sgmatRowSubtiles, pow2ceil(ceilDiv(sgmatTailRows, sgmatMatrixSize)), floor(deviceWorkgroupCap / (32 * max(1, sgmatColSubtiles))), floor(tunables.SGMAT_TILE_K / sgmatMatrixSize), floor((device.limits.maxComputeWorkgroupStorageSize - sgmatWorkgroupStorageBytes) / (4 * sgmatMatrixSize * max(1, tunables.SGMAT_TILE_K)))))", "prefixGeometryValid": "tunables.SGMAT_TILE_COLS >= sgmatSubCols and tunables.SGMAT_TILE_COLS % sgmatSubCols == 0 and tunables.SGMAT_TILE_K >= sgmatMatrixSize and tunables.SGMAT_TILE_K % sgmatMatrixSize == 0 and prefixTileRows >= sgmatRowSubtiles * sgmatMatrixSize and prefixTileRows % (sgmatRowSubtiles * sgmatMatrixSize) == 0", "prefixResourcesFit": "sgmatWorkgroupFits and ceilDiv(sgmatFullRows, max(1, prefixTileRows)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)", "hybridTailRowSubtiles": "pow2ceil(tailRowSubtiles) / (2 if pow2ceil(tailRowSubtiles) > tailRowSubtiles else 1)", "hybridTailTileRows": "hybridTailRowSubtiles * sgmatMatrixSize", "hybridTailSubCols": "sgmatSubCols * hybridTailRowSubtiles / sgmatRowSubtiles", "hybridStorageBytes": "4 * (tunables.SGMAT_TILE_COLS + hybridTailTileRows) * tunables.SGMAT_TILE_K", "hybridDispatchRows": "sgmatFullRows / max(1, prefixTileRows) + ceilDiv(sgmatTailRows, hybridTailTileRows)", "hybridResourcesFit": "prefixResourcesFit and hybridStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and hybridDispatchRows <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)" }, "bindings": { "a": { "arg": "aT", "elementType": "$aScalar" }, "b": { "arg": "bT", "elementType": "u32" }, "absmax": { "arg": "absmaxT", "elementType": "$absmaxScalar", "length": "$ABSMAX_LEN" }, "y": { "arg": "yT", "elementType": "$aScalar" }, "params": { "struct": [ { "name": "rows", "type": "u32", "value": "dim(shapes.aT, 0)" }, { "name": "K", "type": "u32", "value": "attrs.K" }, { "name": "N", "type": "u32", "value": "attrs.N" }, { "name": "blockSize", "type": "u32", "value": "attrs.block_size" } ] } }, "variants": [ { "id": "sgmat_hybrid_rows", "priority": 21, "when": ["prefixGeometryValid", "commonShapeValid", "tensorDtypes.aT == \"float32\"", "attrs.N % tunables.SGMAT_TILE_COLS == 0", "attrs.K % tunables.SGMAT_TILE_K == 0", "attrs.K % attrs.block_size == 0", "attrs.block_size % sgmatLoadWidth == 0", "wave32Effective", "prefixResourcesFit", "sgmatFullRows > 0", "sgmatTailRows > 0", "tailGeometryValid", "hybridResourcesFit"], "requires": { "features": ["subgroups", "chromium-experimental-subgroup-matrix"], "limits": { "maxComputeWorkgroupStorageSize": 8192 }, "subgroupMatrixConfigs": [{ "componentType": "f32", "resultComponentType": "f32", "M": 8, "N": 8, "K": 8 }] }, "derive": { "tileRows": "prefixTileRows", "subRows": "prefixTileRows / sgmatRowSubtiles", "rowMatrices": "prefixTileRows / (sgmatRowSubtiles * sgmatMatrixSize)", "hybridRows": true, "rowCount": "dim(shapes.aT, 0)", "fullDispatchRows": "sgmatFullRows / prefixTileRows", "rowOffset": "sgmatFullRows" }, "passes": [ { "id": "main", "shader": "matmul-bnb4-sgmat.wgsl.jinja", "bindings": ["a", "b", "absmax", "y"], "dispatch": { "x": "sgmatDispatchN", "y": "hybridDispatchRows" } } ] }, { "id": "sgmat_hybrid_rows_widened", "priority": 21, "when": ["prefixGeometryValid", "commonShapeValid", "tensorDtypes.aT == \"float16\"", "attrs.N % tunables.SGMAT_TILE_COLS == 0", "attrs.K % tunables.SGMAT_TILE_K == 0", "attrs.K % attrs.block_size == 0", "attrs.block_size % sgmatLoadWidth == 0", "wave32Effective", "prefixResourcesFit", "sgmatWidenFits", "sgmatFullRows > 0", "sgmatTailRows > 0", "tailGeometryValid", "hybridResourcesFit"], "requires": { "features": ["subgroups", "chromium-experimental-subgroup-matrix"], "limits": { "maxComputeWorkgroupStorageSize": 8192 }, "subgroupMatrixConfigs": [{ "componentType": "f32", "resultComponentType": "f32", "M": 8, "N": 8, "K": 8 }] }, "derive": { "tileRows": "prefixTileRows", "subRows": "prefixTileRows / sgmatRowSubtiles", "rowMatrices": "prefixTileRows / (sgmatRowSubtiles * sgmatMatrixSize)", "aScalar": "\"f32\"", "srcScalar": "\"f16\"", "outScalar": "\"f32\"", "hybridRows": true, "rowCount": "dim(shapes.aT, 0)", "fullDispatchRows": "sgmatFullRows / prefixTileRows", "rowOffset": "sgmatFullRows" }, "intermediates": [ { "id": "aF32", "dtype": "float32", "shape": "[numel(shapes.aT)]" }, { "id": "yF32", "dtype": "float32", "shape": "[numel(shapes.yT)]" } ], "passes": [ { "id": "widen_a", "name": "MatMulBnb4.WidenActivations", "shader": "cast-scalar-x4.wgsl.jinja", "bindings": [ { "arg": "aT", "name": "x", "elementType": "$srcScalar" }, { "scratch": "aF32", "name": "y", "elementType": "f32" }, { "name": "params", "struct": [{ "name": "count", "type": "u32", "value": "numel(shapes.aT)" }] } ], "dispatch": { "x": "min(ceilDiv((ceilDiv(numel(shapes.aT), 4)), (tunables.WORKGROUP_SIZE)), 65535)", "y": "ceilDiv(ceilDiv((ceilDiv(numel(shapes.aT), 4)), (tunables.WORKGROUP_SIZE)), 65535)", "z": 1 } }, { "id": "main", "name": "MatMulBnb4.SubgroupMatrixWidened", "shader": "matmul-bnb4-sgmat.wgsl.jinja", "bindings": [ { "scratch": "aF32", "name": "a", "buffer": "read-only-storage", "elementType": "f32" }, "b", "absmax", { "scratch": "yF32", "name": "y", "elementType": "f32" } ], "dispatch": { "x": "sgmatDispatchN", "y": "hybridDispatchRows" } }, { "id": "narrow_y", "name": "MatMulBnb4.NarrowOutput", "shader": "cast-scalar-x4.wgsl.jinja", "derive": { "outScalar": "\"f16\"" }, "bindings": [ { "scratch": "yF32", "name": "x", "buffer": "read-only-storage", "elementType": "f32" }, { "arg": "yT", "name": "y", "elementType": "$srcScalar" }, { "name": "params", "struct": [{ "name": "count", "type": "u32", "value": "numel(shapes.yT)" }] } ], "dispatch": { "x": "min(ceilDiv((ceilDiv(numel(shapes.yT), 4)), (tunables.WORKGROUP_SIZE)), 65535)", "y": "ceilDiv(ceilDiv((ceilDiv(numel(shapes.yT), 4)), (tunables.WORKGROUP_SIZE)), 65535)", "z": 1 } } ] }, { "id": "sgmat_staged_rows", "priority": 19, "when": ["commonShapeValid", "dim(shapes.aT, 0) > 1", "dim(shapes.aT, 0) < sgmatTileRows or dim(shapes.aT, 0) % sgmatTileRows != 0", "stagedGeometryValid", "attrs.N % tunables.SGMAT_TILE_COLS == 0", "attrs.K % tunables.SGMAT_TILE_K == 0", "attrs.K % attrs.block_size == 0", "attrs.block_size % sgmatLoadWidth == 0", "wave32Effective", "stagedResourcesFit"], "requires": { "features": ["subgroups", "chromium-experimental-subgroup-matrix"], "subgroupMatrixConfigs": [{ "componentType": "f32", "resultComponentType": "f32", "M": 8, "N": 8, "K": 8 }] }, "derive": { "tileRows": "stagedTileRows", "subRows": "sgmatMatrixSize", "subCols": "stagedSubCols", "rowMatrices": 1, "colMatrices": "stagedColumnMatrices", "rowSubtiles": "stagedRowSubtiles", "workgroupSize": "stagedWorkgroupSize", "stageActivations": true, "rowCount": "dim(shapes.aT, 0)" }, "passes": [ { "id": "main", "shader": "matmul-bnb4-sgmat.wgsl.jinja", "bindings": ["a", "b", "absmax", "y"], "dispatch": { "x": "sgmatDispatchN", "y": "ceilDiv(dim(shapes.aT, 0), stagedTileRows)" } } ] }, { "id": "gemv", "priority": 20, "when": ["gemvShapeValid", "portableWorkgroupFits"], "derive": { "workgroupSize": "portableWorkgroupSize" }, "passes": [ { "id": "main", "shader": "matmul-bnb4-gemv.wgsl.jinja", "bindings": [ "a", "b", "absmax", "y", { "name": "params", "struct": [ { "name": "K", "type": "u32", "value": "attrs.K" }, { "name": "N", "type": "u32", "value": "attrs.N" }, { "name": "blockSize", "type": "u32", "value": "attrs.block_size" } ] } ], "dispatch": { "x": "min(attrs.N, 65535)", "y": "ceilDiv(attrs.N, 65535)", "z": 1 } } ] }, { "id": "sgmat", "priority": 15, "when": ["sgmatGeometryValid", "commonShapeValid", "tensorDtypes.aT == \"float32\"", "dim(shapes.aT, 0) >= sgmatTileRows", "dim(shapes.aT, 0) % sgmatTileRows == 0", "attrs.N % tunables.SGMAT_TILE_COLS == 0", "attrs.K % tunables.SGMAT_TILE_K == 0", "attrs.K % attrs.block_size == 0", "attrs.block_size % sgmatLoadWidth == 0", "wave32Effective", "sgmatWorkgroupFits"], "requires": { "features": ["subgroups", "chromium-experimental-subgroup-matrix"], "limits": { "maxComputeWorkgroupStorageSize": 8192 }, "subgroupMatrixConfigs": [{ "componentType": "f32", "resultComponentType": "f32", "M": 8, "N": 8, "K": 8 }] }, "derive": { "tileRows": "sgmatTileRows", "subRows": "sgmatSubRows", "rowMatrices": "sgmatSubRows / sgmatMatrixSize" }, "passes": [ { "id": "main", "shader": "matmul-bnb4-sgmat.wgsl.jinja", "bindings": ["a", "b", "absmax", "y"], "dispatch": { "x": "sgmatDispatchN", "y": "sgmatDispatchM" } } ] }, { "id": "sgmat_widened", "priority": 16, "when": ["sgmatGeometryValid", "commonShapeValid", "tensorDtypes.aT == \"float16\"", "dim(shapes.aT, 0) >= sgmatTileRows", "dim(shapes.aT, 0) % sgmatTileRows == 0", "attrs.N % tunables.SGMAT_TILE_COLS == 0", "attrs.K % tunables.SGMAT_TILE_K == 0", "attrs.K % attrs.block_size == 0", "attrs.block_size % sgmatLoadWidth == 0", "wave32Effective", "sgmatWorkgroupFits", "sgmatWidenFits"], "requires": { "features": ["subgroups", "chromium-experimental-subgroup-matrix"], "limits": { "maxComputeWorkgroupStorageSize": 8192 }, "subgroupMatrixConfigs": [{ "componentType": "f32", "resultComponentType": "f32", "M": 8, "N": 8, "K": 8 }] }, "derive": { "tileRows": "sgmatTileRows", "subRows": "sgmatSubRows", "rowMatrices": "sgmatSubRows / sgmatMatrixSize", "aScalar": "\"f32\"", "srcScalar": "\"f16\"", "outScalar": "\"f32\"" }, "intermediates": [ { "id": "aF32", "dtype": "float32", "shape": "[numel(shapes.aT)]" }, { "id": "yF32", "dtype": "float32", "shape": "[dim(shapes.aT, 0) * attrs.N]" } ], "passes": [ { "id": "widen_a", "name": "MatMulBnb4.WidenActivations", "shader": "cast-scalar-x4.wgsl.jinja", "bindings": [ { "arg": "aT", "name": "x", "elementType": "$srcScalar" }, { "scratch": "aF32", "name": "y", "elementType": "f32" }, { "name": "params", "struct": [{ "name": "count", "type": "u32", "value": "numel(shapes.aT)" }] } ], "dispatch": { "x": "min(ceilDiv((ceilDiv(numel(shapes.aT), 4)), (tunables.WORKGROUP_SIZE)), 65535)", "y": "ceilDiv(ceilDiv((ceilDiv(numel(shapes.aT), 4)), (tunables.WORKGROUP_SIZE)), 65535)", "z": 1 } }, { "id": "main", "name": "MatMulBnb4.SubgroupMatrixWidened", "shader": "matmul-bnb4-sgmat.wgsl.jinja", "bindings": [ { "scratch": "aF32", "name": "a", "buffer": "read-only-storage", "elementType": "f32" }, "b", "absmax", { "scratch": "yF32", "name": "y", "elementType": "f32" } ], "dispatch": { "x": "sgmatDispatchN", "y": "sgmatDispatchM" } }, { "id": "narrow_y", "name": "MatMulBnb4.NarrowOutput", "shader": "cast-scalar-x4.wgsl.jinja", "derive": { "outScalar": "\"f16\"" }, "bindings": [ { "scratch": "yF32", "name": "x", "buffer": "read-only-storage", "elementType": "f32" }, { "arg": "yT", "name": "y", "elementType": "$srcScalar" }, { "name": "params", "struct": [{ "name": "count", "type": "u32", "value": "dim(shapes.aT, 0) * attrs.N" }] } ], "dispatch": { "x": "min(ceilDiv((ceilDiv(dim(shapes.aT, 0) * attrs.N, 4)), (tunables.WORKGROUP_SIZE)), 65535)", "y": "ceilDiv(ceilDiv((ceilDiv(dim(shapes.aT, 0) * attrs.N, 4)), (tunables.WORKGROUP_SIZE)), 65535)", "z": 1 } } ] }, { "id": "tiled", "priority": 10, "when": ["tileEligible", "tileWorkgroupFits"], "derive": { "tileK": "tunables.PORTABLE_TILE_K", "tileRows": "portableTileRows" }, "passes": [ { "id": "main", "shader": "matmul-bnb4-tiled.wgsl.jinja", "bindings": ["a", "b", "absmax", "y", "params"], "dispatch": { "x": "ceilDiv(attrs.N, 64)", "y": "ceilDiv(dim(shapes.aT, 0), portableTileRows)" } } ] }, { "id": "scalar", "priority": 0, "when": ["commonShapeValid", "portableWorkgroupSize > 0"], "derive": { "workgroupSize": "portableWorkgroupSize" }, "passes": [ { "id": "main", "shader": "matmul-bnb4.wgsl.jinja", "bindings": ["a", "b", "absmax", "y", "params"], "dispatch": { "x": "min(ceilDiv((numel(shapes.yT)), (workgroupSize)), 65535)", "y": "ceilDiv(ceilDiv((numel(shapes.yT)), (workgroupSize)), 65535)", "z": 1 } } ] } ]}{"domain":"com.microsoft","name":"MatMulBnb4","sinceVersion":1,"inputs":{"aT":{"onnx":"A","dtype":"T1","rank":2},"bT":{"onnx":"B","dtype":"T2","rank":1,"layout":"packed"},"absmaxT":{"onnx":"absmax","dtype":"T1","rank":1}},"outputs":{"yT":{"onnx":"Y","dtype":"T1","rank":2,"shape":"[dim(shapes.aT, 0), attrs.N]"}},"attributes":{"training_mode":{"default":0},"transB":{"default":1},"K":{},"N":{},"block_size":{},"quant_type":{}},"attributeConstraints":{"K":{"required":true},"N":{"required":true},"block_size":{"required":true},"quant_type":{"required":true,"values":[0,1]},"training_mode":{"values":[0]},"transB":{"values":[1]}},"typeConstraints":{"T1":["float32","float16"],"T2":["uint8"]},"tunables":{"WORKGROUP_SIZE":{"default":64},"TILE_MIN_M":{"default":4},"PORTABLE_TILE_K":{"default":16},"SGMAT_TILE_ROWS":{"default":64},"SGMAT_TALL_TILE_ROWS":{"default":128},"SGMAT_TALL_MIN_M":{"default":128},"SGMAT_TILE_COLS":{"default":64},"SGMAT_TILE_K":{"default":32}},"derive":{"deviceWorkgroupCap":"min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)","wave32Adapter":"has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 32 and device.adapterInfo.subgroupMaxSize == 32","canPinSubgroupSize32":"device.features.has(\"subgroups\") and device.features.has(\"subgroup-size-control\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize <= 32 and device.adapterInfo.subgroupMaxSize >= 32","pinSubgroupSize32":"canPinSubgroupSize32 and not wave32Adapter","wave32Effective":"wave32Adapter or pinSubgroupSize32","subgroupMatrixTopologyBytes":"3 * 16","native16PackedBaseTile":64,"native16PackedWideTile":"2 * native16PackedBaseTile","native16PackedStageK":32,"native16PackedSharedPad":8,"native16PackedWideGridFloor":128,"native16PackedPrefetchGridCeiling":256,"native16PackedOutputScratchBytes":"4 * 16 * 16 * dtypeBytes(\"float32\")","native16PackedStageStrideBytes":"dtypeBytes(\"float16\") * (native16PackedStageK + native16PackedSharedPad)","native16PackedBaseAStorageBytes":"max(native16PackedBaseTile * native16PackedStageStrideBytes, native16PackedOutputScratchBytes)","native16PackedWideAStorageBytes":"max(native16PackedWideTile * native16PackedStageStrideBytes, native16PackedOutputScratchBytes)","native16PackedBaseColumnStorageBytes":"native16PackedBaseAStorageBytes + native16PackedBaseTile * native16PackedStageStrideBytes + subgroupMatrixTopologyBytes","native16PackedWideColumnStorageBytes":"native16PackedWideAStorageBytes + native16PackedWideTile * native16PackedStageStrideBytes + subgroupMatrixTopologyBytes","portableTileRows":"8 * min(8, max(1, ceilDiv(dim(shapes.aT, 0), 8)))","packedBytesExpected":"ceilDiv(attrs.N * attrs.K, 2)","absmaxCountExpected":"ceilDiv(attrs.N * attrs.K, attrs.block_size)","aFloatOk":"(tensorDtypes.aT == \"float32\" or tensorDtypes.aT == \"float16\") and f16Ok(tensorDtypes.aT)","portableWorkgroupSize":"min(tunables.WORKGROUP_SIZE, deviceWorkgroupCap)","commonShapeValid":"ranks.aT == 2 and ranks.bT == 1 and ranks.absmaxT == 1 and ranks.yT == 2 and aFloatOk and tensorDtypes.bT == \"uint8\" and tensorDtypes.absmaxT == tensorDtypes.aT and tensorDtypes.yT == tensorDtypes.aT and attrs.K > 0 and attrs.N > 0 and attrs.block_size >= 16 and pow2ceil(attrs.block_size) == attrs.block_size and dim(shapes.aT, 1) == attrs.K and dim(shapes.bT, 0) == packedBytesExpected and dim(shapes.absmaxT, 0) == absmaxCountExpected and dim(shapes.yT, 0) == dim(shapes.aT, 0) and dim(shapes.yT, 1) == attrs.N","gemvShapeValid":"commonShapeValid and dim(shapes.aT, 0) == 1","portableWorkgroupFits":"portableWorkgroupSize > 0 and portableWorkgroupSize * 16 <= device.limits.maxComputeWorkgroupStorageSize","portableTileKValid":"tunables.PORTABLE_TILE_K >= 8 and tunables.PORTABLE_TILE_K % 8 == 0","tileEligible":"commonShapeValid and dim(shapes.aT, 0) >= tunables.TILE_MIN_M and portableTileKValid","tileWorkgroupStorageBytes":"(portableTileRows * dtypeBytes(tensorDtypes.aT) + 64 * 4) * tunables.PORTABLE_TILE_K","tileWorkgroupFits":"16 <= device.limits.maxComputeWorkgroupSizeX and 8 <= device.limits.maxComputeWorkgroupSizeY and 128 <= device.limits.maxComputeInvocationsPerWorkgroup and tileWorkgroupStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and ceilDiv(attrs.N, 64) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(dim(shapes.aT, 0), portableTileRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","sgmatMatrixSize":"8","sgmatTileRows":"tunables.SGMAT_TALL_TILE_ROWS if dim(shapes.aT, 0) >= tunables.SGMAT_TALL_MIN_M else tunables.SGMAT_TILE_ROWS","sgmatRowSubtiles":"4","sgmatSubRows":"sgmatTileRows / sgmatRowSubtiles","sgmatSubCols":"4 * sgmatMatrixSize","sgmatLoadWidth":"sgmatMatrixSize","sgmatColSubtiles":"tunables.SGMAT_TILE_COLS / sgmatSubCols","sgmatNumSubgroups":"sgmatRowSubtiles * sgmatColSubtiles","sgmatSubgroupSize":"32","sgmatWorkgroupSize":"sgmatNumSubgroups * sgmatSubgroupSize","sgmatBLoadsPerRow":"tunables.SGMAT_TILE_K / sgmatLoadWidth","sgmatWorkgroupStorageBytes":"subgroupMatrixTopologyBytes + 4 * tunables.SGMAT_TILE_COLS * tunables.SGMAT_TILE_K","sgmatDispatchN":"ceilDiv(attrs.N, tunables.SGMAT_TILE_COLS)","sgmatDispatchM":"ceilDiv(dim(shapes.aT, 0), sgmatTileRows)","sgmatWorkgroupFits":"sgmatWorkgroupSize <= deviceWorkgroupCap and sgmatWorkgroupStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and sgmatDispatchN <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and sgmatDispatchM <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","sgmatWidenBytes":"numel(shapes.aT) * 4","sgmatWidenOutBytes":"dim(shapes.aT, 0) * attrs.N * 4","sgmatWidenFits":"sgmatWidenBytes <= device.limits.maxStorageBufferBindingSize and sgmatWidenBytes <= device.limits.maxBufferSize and sgmatWidenOutBytes <= device.limits.maxStorageBufferBindingSize and sgmatWidenOutBytes <= device.limits.maxBufferSize","quantType":"attrs.quant_type","K":"attrs.K","N":"attrs.N","blockSize":"attrs.block_size","tileCols":"tunables.SGMAT_TILE_COLS","tileK":"tunables.SGMAT_TILE_K","matrixSize":"sgmatMatrixSize","subCols":"sgmatSubCols","colMatrices":"sgmatSubCols / sgmatMatrixSize","loadWidth":"sgmatLoadWidth","rowSubtiles":"sgmatRowSubtiles","workgroupSize":"sgmatWorkgroupSize","bLoadsPerRow":"sgmatBLoadsPerRow","aScalar":"\"f16\" if tensorDtypes.aT == \"float16\" else \"f32\"","usesF16":"tensorDtypes.aT == \"float16\"","absmaxScalar":"\"f16\" if tensorDtypes.absmaxT == \"float16\" else \"f32\"","ABSMAX_LEN":"ceilDiv(attrs.N * attrs.K, attrs.block_size)","stagedGeometryValid":"tunables.SGMAT_TILE_COLS >= sgmatSubCols and tunables.SGMAT_TILE_COLS % sgmatSubCols == 0 and tunables.SGMAT_TILE_K >= sgmatMatrixSize and tunables.SGMAT_TILE_K % sgmatMatrixSize == 0","stagedRowSubtiles":"max(1, min(sgmatRowSubtiles, pow2ceil(ceilDiv(dim(shapes.aT, 0), sgmatMatrixSize)), floor(deviceWorkgroupCap / (32 * max(1, sgmatColSubtiles))), floor(tunables.SGMAT_TILE_K / sgmatMatrixSize), floor((device.limits.maxComputeWorkgroupStorageSize - sgmatWorkgroupStorageBytes) / (4 * sgmatMatrixSize * max(1, tunables.SGMAT_TILE_K)))))","stagedTileRows":"stagedRowSubtiles * sgmatMatrixSize","stagedLoadWorkgroupTarget":"max(2 * sgmatSubgroupSize, min(deviceWorkgroupCap, tunables.SGMAT_TILE_COLS * tunables.SGMAT_TILE_K / sgmatLoadWidth))","stagedColumnMatrices":"min(4, pow2ceil(max(1, ceilDiv(stagedRowSubtiles * tunables.SGMAT_TILE_COLS * 32, stagedLoadWorkgroupTarget * sgmatMatrixSize))))","stagedSubCols":"stagedColumnMatrices * sgmatMatrixSize","stagedWorkgroupSize":"stagedRowSubtiles * (tunables.SGMAT_TILE_COLS / stagedSubCols) * 32","stagedStorageBytes":"subgroupMatrixTopologyBytes + 4 * (stagedTileRows + tunables.SGMAT_TILE_COLS) * tunables.SGMAT_TILE_K","stagedResourcesFit":"stagedWorkgroupSize <= deviceWorkgroupCap and stagedStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and sgmatDispatchN <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(dim(shapes.aT, 0), stagedTileRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","sgmatGeometryValid":"stagedGeometryValid and sgmatTileRows >= sgmatRowSubtiles * sgmatMatrixSize and sgmatTileRows % (sgmatRowSubtiles * sgmatMatrixSize) == 0","prefixTileRows":"tunables.SGMAT_TILE_ROWS","sgmatFullRows":"floor(dim(shapes.aT, 0) / max(1, prefixTileRows)) * prefixTileRows","sgmatTailRows":"dim(shapes.aT, 0) - sgmatFullRows","tailGeometryValid":"stagedGeometryValid","tailRowSubtiles":"max(1, min(sgmatRowSubtiles, pow2ceil(ceilDiv(sgmatTailRows, sgmatMatrixSize)), floor(deviceWorkgroupCap / (32 * max(1, sgmatColSubtiles))), floor(tunables.SGMAT_TILE_K / sgmatMatrixSize), floor((device.limits.maxComputeWorkgroupStorageSize - sgmatWorkgroupStorageBytes) / (4 * sgmatMatrixSize * max(1, tunables.SGMAT_TILE_K)))))","prefixGeometryValid":"stagedGeometryValid and prefixTileRows >= sgmatRowSubtiles * sgmatMatrixSize and prefixTileRows % (sgmatRowSubtiles * sgmatMatrixSize) == 0","prefixResourcesFit":"sgmatWorkgroupFits and ceilDiv(sgmatFullRows, max(1, prefixTileRows)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","hybridTailRowSubtiles":"pow2ceil(tailRowSubtiles) / (2 if pow2ceil(tailRowSubtiles) > tailRowSubtiles else 1)","hybridTailTileRows":"hybridTailRowSubtiles * sgmatMatrixSize","hybridTailSubCols":"sgmatSubCols * hybridTailRowSubtiles / sgmatRowSubtiles","hybridStorageBytes":"subgroupMatrixTopologyBytes + 4 * (tunables.SGMAT_TILE_COLS + hybridTailTileRows) * tunables.SGMAT_TILE_K","hybridDispatchRows":"sgmatFullRows / max(1, prefixTileRows) + ceilDiv(sgmatTailRows, hybridTailTileRows)","hybridResourcesFit":"prefixResourcesFit and hybridStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and hybridDispatchRows <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","hybridRowsFit":"prefixGeometryValid and prefixResourcesFit and sgmatFullRows > 0 and sgmatTailRows > 0 and tailGeometryValid and hybridResourcesFit","bnb4PackedFixed32":"device.features.has(\"subgroups\") and has(device.adapterInfo, \"vendor\") and has(device.adapterInfo, \"architecture\") and device.adapterInfo.vendor == \"nvidia\" and device.adapterInfo.architecture == \"blackwell\" and wave32Effective and not pinSubgroupSize32","bnb4PackedWidePreferred":"dim(shapes.aT, 0) >= native16PackedWideTile and attrs.N >= native16PackedWideTile and ceilDiv(dim(shapes.aT, 0), native16PackedWideTile) * ceilDiv(attrs.N, native16PackedWideTile) >= native16PackedWideGridFloor and native16PackedWideColumnStorageBytes <= device.limits.maxComputeWorkgroupStorageSize","bnb4PackedWorthTiming":"ceilDiv(dim(shapes.aT, 0), native16PackedBaseTile) * ceilDiv(attrs.N, native16PackedBaseTile) >= 16","bnb4RegRows":"16 if dim(shapes.aT, 0) <= 16 else (32 if dim(shapes.aT, 0) <= 32 else (128 if ceilDiv(dim(shapes.aT, 0), 128) * ceilDiv(attrs.N, 64) >= 256 else 64))","bnb4RegTiles":"ceilDiv(dim(shapes.aT, 0), bnb4RegRows) * ceilDiv(attrs.N, 64)","bnb4RegSplitCount":"max(1, min(16, ceilDiv(1024, bnb4RegTiles), floor(attrs.K / 256)))","bnb4RegStorageBytes":"bnb4RegRows * 8 * 4 * dtypeBytes(tensorDtypes.aT) + 8 * 4 * 16 * 16","bnb4RegFits":"commonShapeValid and attrs.K % 8 == 0 and 16 <= device.limits.maxComputeWorkgroupSizeX and 16 <= device.limits.maxComputeWorkgroupSizeY and 256 <= device.limits.maxComputeInvocationsPerWorkgroup and bnb4RegStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and ceilDiv(attrs.N, 64) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(dim(shapes.aT, 0), bnb4RegRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","bnb4RegSplitFits":"bnb4RegSplitCount >= 2 and bnb4RegSplitCount * dim(shapes.aT, 0) * attrs.N * 4 <= min(device.limits.maxStorageBufferBindingSize, device.limits.maxBufferSize)","bnb4RegYieldsToRows":"dim(shapes.aT, 0) <= 4 or ceilDiv(attrs.N, 64) * ceilDiv(dim(shapes.aT, 0), portableTileRows) * 128 < deviceWorkgroupCap"},"bindings":{"a":{"arg":"aT","elementType":"$aScalar"},"b":{"arg":"bT","elementType":"u32"},"absmax":{"arg":"absmaxT","elementType":"$absmaxScalar","length":"$ABSMAX_LEN"},"y":{"arg":"yT","elementType":"$aScalar"},"params_gemv":{"name":"params","struct":[{"name":"K","type":"u32","value":"attrs.K"},{"name":"N","type":"u32","value":"attrs.N"},{"name":"blockSize","type":"u32","value":"attrs.block_size"}]},"params":{"struct":[{"name":"rows","type":"u32","value":"dim(shapes.aT, 0)"},{"name":"K","type":"u32","value":"attrs.K"},{"name":"N","type":"u32","value":"attrs.N"},{"name":"blockSize","type":"u32","value":"attrs.block_size"}]},"a_f32_input":{"scratch":"aF32","name":"a","buffer":"read-only-storage","elementType":"f32"},"x_src_scalar":{"arg":"aT","name":"x","elementType":"$srcScalar"},"params_input_count":{"name":"params","struct":[{"name":"count","type":"u32","value":"numel(shapes.aT)"}]},"y_f32_read":{"scratch":"yF32","name":"x","buffer":"read-only-storage","elementType":"f32"},"y_src_scalar":{"arg":"yT","name":"y","elementType":"$srcScalar"},"a_vec4":{"arg":"aT","name":"a","elementType":"$aVec4"},"params_input_rows":{"name":"params","struct":[{"name":"rows","type":"u32","value":"dim(shapes.aT, 0)"}]}},"variants":[{"id":"native16_packed_64x64","priority":31,"when":["commonShapeValid","tensorDtypes.aT == \"float16\"","attrs.K % 8 == 0 and attrs.N % 8 == 0","dim(shapes.aT, 0) > 8","bnb4PackedFixed32","128 <= deviceWorkgroupCap","native16PackedBaseColumnStorageBytes + 64 <= device.limits.maxComputeWorkgroupStorageSize","ceilDiv(dim(shapes.aT, 0), native16PackedBaseTile) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(attrs.N, native16PackedBaseTile) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","has(device.adapterInfo, \"subgroupMatrixConfigs\") and subgroupMatrixConfigAvailable(\"f16\", \"f32\", 16, 16, 16)"],"requires":{"features":["shader-f16","subgroups","chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs":[{"componentType":"f16","resultComponentType":"f32","M":16,"N":16,"K":16}]},"derive":{"N":"attrs.N","K":"attrs.K","registerTileM":"native16PackedBaseTile","registerTileN":"native16PackedBaseTile","registerTileK":"native16PackedStageK","registerSharedPad":"native16PackedSharedPad","registerPrefetch":"ceilDiv(dim(shapes.aT, 0), native16PackedBaseTile) * ceilDiv(attrs.N, native16PackedBaseTile) < native16PackedPrefetchGridCeiling","needDequantWeight":false},"passes":[{"id":"main","name":"MatMulBnb4.Native16Packed.64x64","shader":"matmul-bnb4-native16-packed.wgsl.jinja","bindings":[{"arg":"aT","name":"a","elementType":"vec4<u32>"},"b","absmax",{"arg":"yT","name":"y","elementType":"vec4<u32>"},{"name":"params","struct":[{"name":"M","type":"u32","value":"dim(shapes.aT, 0)"}]}],"dispatch":{"x":"ceilDiv(attrs.N, registerTileN)","y":"ceilDiv(dim(shapes.aT, 0), registerTileM)"}}],"demoteWhen":["not bnb4PackedWorthTiming","bnb4PackedWidePreferred"]},{"id":"native16_packed_128x128","priority":32,"when":["commonShapeValid","tensorDtypes.aT == \"float16\"","attrs.K % 8 == 0 and attrs.N % 8 == 0","dim(shapes.aT, 0) > 8","bnb4PackedFixed32","128 <= deviceWorkgroupCap","native16PackedWideColumnStorageBytes + 64 <= device.limits.maxComputeWorkgroupStorageSize","ceilDiv(dim(shapes.aT, 0), native16PackedWideTile) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(attrs.N, native16PackedWideTile) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","has(device.adapterInfo, \"subgroupMatrixConfigs\") and subgroupMatrixConfigAvailable(\"f16\", \"f32\", 16, 16, 16)"],"requires":{"features":["shader-f16","subgroups","chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs":[{"componentType":"f16","resultComponentType":"f32","M":16,"N":16,"K":16}]},"derive":{"N":"attrs.N","K":"attrs.K","registerTileM":"native16PackedWideTile","registerTileN":"native16PackedWideTile","registerTileK":"native16PackedStageK","registerSharedPad":"native16PackedSharedPad","registerPrefetch":true,"needDequantWeight":false},"passes":[{"id":"main","name":"MatMulBnb4.Native16Packed.128x128","shader":"matmul-bnb4-native16-packed.wgsl.jinja","bindings":[{"arg":"aT","name":"a","elementType":"vec4<u32>"},"b","absmax",{"arg":"yT","name":"y","elementType":"vec4<u32>"},{"name":"params","struct":[{"name":"M","type":"u32","value":"dim(shapes.aT, 0)"}]}],"dispatch":{"x":"ceilDiv(attrs.N, registerTileN)","y":"ceilDiv(dim(shapes.aT, 0), registerTileM)"}}],"demoteWhen":["not bnb4PackedWorthTiming","not bnb4PackedWidePreferred"]},{"id":"gemv_row_groups","priority":11,"when":["commonShapeValid","dim(shapes.aT, 0) > 1","attrs.K >= portableWorkgroupSize","attrs.N >= portableWorkgroupSize","portableWorkgroupFits","ceilDiv(attrs.N, 64) * ceilDiv(dim(shapes.aT, 0), portableTileRows) * 128 < deviceWorkgroupCap","ceilDiv(dim(shapes.aT, 0), 4) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","ceilDiv(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)"],"derive":{"workgroupSize":"portableWorkgroupSize","rowBlock":4,"rowBatch":true,"staticGeometry":true,"vectorDecode":true,"rowCount":"dim(shapes.aT, 0)","bnbVec4AlignedRows":"attrs.K % 4 == 0","vectorActivationElement":"(\"vec4<f16>\" if usesF16 else \"vec4<f32>\") if bnbVec4AlignedRows else aScalar"},"passes":[{"id":"main","shader":"matmul-bnb4-gemv.wgsl.jinja","bindings":[{"arg":"aT","name":"a","buffer":"read-only-storage","elementType":"$vectorActivationElement"},"b","absmax","y"],"dispatch":{"x":"min(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535))","y":"ceilDiv(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535))","z":"ceilDiv(dim(shapes.aT, 0), 4)"}}]},{"id":"gemv_rows","priority":9,"when":["commonShapeValid","dim(shapes.aT, 0) > 1","dim(shapes.aT, 0) <= 4","attrs.K >= portableWorkgroupSize","attrs.N >= portableWorkgroupSize","portableWorkgroupFits","ceilDiv(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)"],"derive":{"workgroupSize":"portableWorkgroupSize","rowBlock":"dim(shapes.aT, 0)"},"passes":[{"id":"main","shader":"matmul-bnb4-gemv.wgsl.jinja","bindings":["a","b","absmax","y","params_gemv"],"dispatch":{"x":"min(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535))","y":"ceilDiv(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535))"}}]},{"id":"sgmat_hybrid_rows","priority":21,"when":["commonShapeValid","tensorDtypes.aT == \"float32\"","attrs.N % tunables.SGMAT_TILE_COLS == 0","attrs.K % tunables.SGMAT_TILE_K == 0","attrs.K % attrs.block_size == 0","attrs.block_size % sgmatLoadWidth == 0","wave32Effective","hybridRowsFit"],"requires":{"features":["subgroups","chromium-experimental-subgroup-matrix"],"limits":{"maxComputeWorkgroupStorageSize":8240},"subgroupMatrixConfigs":[{"componentType":"f32","resultComponentType":"f32","M":8,"N":8,"K":8}]},"derive":{"tileRows":"prefixTileRows","subRows":"prefixTileRows / sgmatRowSubtiles","rowMatrices":"prefixTileRows / (sgmatRowSubtiles * sgmatMatrixSize)","hybridRows":true,"rowCount":"dim(shapes.aT, 0)","fullDispatchRows":"sgmatFullRows / prefixTileRows","rowOffset":"sgmatFullRows"},"passes":[{"id":"main","shader":"matmul-bnb4-sgmat.wgsl.jinja","bindings":["a","b","absmax","y"],"dispatch":{"x":"sgmatDispatchN","y":"hybridDispatchRows"}}]},{"id":"sgmat_widened","priority":21,"when":["commonShapeValid","usesF16","attrs.N % tunables.SGMAT_TILE_COLS == 0","attrs.K % tunables.SGMAT_TILE_K == 0","attrs.K % attrs.block_size == 0","attrs.block_size % sgmatLoadWidth == 0","wave32Effective","sgmatWidenFits","hybridRowsFit or (sgmatGeometryValid and dim(shapes.aT, 0) >= sgmatTileRows and dim(shapes.aT, 0) % sgmatTileRows == 0 and sgmatWorkgroupFits)"],"requires":{"features":["subgroups","chromium-experimental-subgroup-matrix"],"limits":{"maxComputeWorkgroupStorageSize":8240},"subgroupMatrixConfigs":[{"componentType":"f32","resultComponentType":"f32","M":8,"N":8,"K":8}]},"derive":{"hybridRows":"hybridRowsFit","tileRows":"prefixTileRows if hybridRows else sgmatTileRows","subRows":"prefixTileRows / sgmatRowSubtiles if hybridRows else sgmatSubRows","rowMatrices":"prefixTileRows / (sgmatRowSubtiles * sgmatMatrixSize) if hybridRows else sgmatSubRows / sgmatMatrixSize","aScalar":"\"f32\"","srcScalar":"\"f16\"","outScalar":"\"f32\"","rowCount":"dim(shapes.aT, 0) if hybridRows else 0","fullDispatchRows":"sgmatFullRows / prefixTileRows if hybridRows else 0","rowOffset":"sgmatFullRows if hybridRows else 0"},"intermediates":[{"id":"aF32","dtype":"float32","shape":"[numel(shapes.aT)]"},{"id":"yF32","dtype":"float32","shape":"[numel(shapes.yT)]"}],"passes":[{"id":"widen_a","name":"MatMulBnb4.WidenActivations","shader":"cast-scalar-x4.wgsl.jinja","bindings":["x_src_scalar",{"scratch":"aF32","name":"y","elementType":"f32"},"params_input_count"],"dispatch":{"x":"min(ceilDiv((ceilDiv(numel(shapes.aT), 4)), (tunables.WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((ceilDiv(numel(shapes.aT), 4)), (tunables.WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"MatMulBnb4.SubgroupMatrixWidened","shader":"matmul-bnb4-sgmat.wgsl.jinja","bindings":["a_f32_input","b","absmax",{"scratch":"yF32","name":"y","elementType":"f32"}],"dispatch":{"x":"sgmatDispatchN","y":"hybridDispatchRows if hybridRows else sgmatDispatchM"}},{"id":"narrow_y","name":"MatMulBnb4.NarrowOutput","shader":"cast-scalar-x4.wgsl.jinja","derive":{"scalar":"\"f32\"","outScalar":"\"f16\""},"bindings":["y_f32_read","y_src_scalar",{"name":"params","struct":[{"name":"count","type":"u32","value":"numel(shapes.yT)"}]}],"dispatch":{"x":"min(ceilDiv((ceilDiv(numel(shapes.yT), 4)), (tunables.WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((ceilDiv(numel(shapes.yT), 4)), (tunables.WORKGROUP_SIZE)), 65535)","z":1}}]},{"id":"sgmat","priority":19,"when":["commonShapeValid","attrs.N % tunables.SGMAT_TILE_COLS == 0","attrs.K % tunables.SGMAT_TILE_K == 0","attrs.K % attrs.block_size == 0","attrs.block_size % sgmatLoadWidth == 0","wave32Effective","(dim(shapes.aT, 0) > 1 and stagedGeometryValid and stagedResourcesFit) if dim(shapes.aT, 0) < sgmatTileRows or dim(shapes.aT, 0) % sgmatTileRows != 0 else (tensorDtypes.aT == \"float32\" and sgmatGeometryValid and sgmatWorkgroupFits and device.limits.maxComputeWorkgroupStorageSize >= 8240)"],"requires":{"features":["subgroups","chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs":[{"componentType":"f32","resultComponentType":"f32","M":8,"N":8,"K":8}]},"derive":{"stageActivations":"dim(shapes.aT, 0) < sgmatTileRows or dim(shapes.aT, 0) % sgmatTileRows != 0","tileRows":"stagedTileRows if stageActivations else sgmatTileRows","subRows":"sgmatMatrixSize if stageActivations else sgmatSubRows","subCols":"stagedSubCols if stageActivations else sgmatSubCols","rowMatrices":"1 if stageActivations else sgmatSubRows / sgmatMatrixSize","colMatrices":"stagedColumnMatrices if stageActivations else sgmatSubCols / sgmatMatrixSize","rowSubtiles":"stagedRowSubtiles if stageActivations else sgmatRowSubtiles","workgroupSize":"stagedWorkgroupSize if stageActivations else sgmatWorkgroupSize","rowCount":"dim(shapes.aT, 0) if stageActivations else 0"},"passes":[{"id":"main","shader":"matmul-bnb4-sgmat.wgsl.jinja","bindings":["a","b","absmax","y"],"dispatch":{"x":"sgmatDispatchN","y":"ceilDiv(dim(shapes.aT, 0), tileRows)"}}]},{"id":"gemv_words","priority":22,"when":["commonShapeValid","attrs.K % 8 == 0","dim(shapes.aT, 0) >= 1 and dim(shapes.aT, 0) <= 8","256 <= deviceWorkgroupCap","256 <= device.limits.maxComputeWorkgroupSizeX","ceilDiv(dim(shapes.aT, 0), 4) * 4096 + 64 <= device.limits.maxComputeWorkgroupStorageSize","ceilDiv(ceilDiv(attrs.N, 8), min(device.limits.maxComputeWorkgroupsPerDimension, 65535)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)"],"derive":{"K":"attrs.K","N":"attrs.N","blockSize":"attrs.block_size","rowBlock":"dim(shapes.aT, 0)","aVec4":"\"vec4<\" ~ aScalar ~ \">\""},"passes":[{"id":"main","name":"MatMulBnb4.GemvWords","shader":"matmul-bnb4-gemv-words.wgsl.jinja","bindings":["a_vec4","b","absmax","y"],"dispatch":{"x":"min(ceilDiv(attrs.N, 8), min(device.limits.maxComputeWorkgroupsPerDimension, 65535))","y":"ceilDiv(ceilDiv(attrs.N, 8), min(device.limits.maxComputeWorkgroupsPerDimension, 65535))"}}],"demoteWhen":["dim(shapes.aT, 0) > 1 and ceilDiv(attrs.N, 64) * ceilDiv(dim(shapes.aT, 0), portableTileRows) * 128 < deviceWorkgroupCap","dim(shapes.aT, 0) > 4 and has(device.adapterInfo, \"subgroupMatrixConfigs\") and subgroupMatrixConfigAvailable(\"f32\", \"f32\", 8, 8, 8)"]},{"id":"gemv","priority":20,"when":["gemvShapeValid","portableWorkgroupFits","ceilDiv(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)"],"derive":{"workgroupSize":"portableWorkgroupSize"},"passes":[{"id":"main","shader":"matmul-bnb4-gemv.wgsl.jinja","bindings":["a","b","absmax","y","params_gemv"],"dispatch":{"x":"min(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535))","y":"ceilDiv(attrs.N, min(device.limits.maxComputeWorkgroupsPerDimension, 65535))"}}]},{"id":"tiled_reg_splitk","priority":13,"when":["bnb4RegFits","bnb4RegSplitFits","bnb4RegSplitCount <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)"],"demoteWhen":["bnb4RegYieldsToRows"],"derive":{"K":"attrs.K","N":"attrs.N","blockSize":"attrs.block_size","aVec4":"\"vec4<\" ~ aScalar ~ \">\"","splitK":"bnb4RegSplitCount","tilesPerSplit":"ceilDiv(ceilDiv(attrs.K, 32), bnb4RegSplitCount)","tileRows":"bnb4RegRows"},"intermediates":[{"id":"partials","dtype":"float32","shape":"[bnb4RegSplitCount * dim(shapes.aT, 0) * attrs.N]"}],"passes":[{"id":"partial","name":"MatMulBnb4.TiledReg.SplitK","shader":"matmul-bnb4-tiled-reg.wgsl.jinja","bindings":["a_vec4","b","absmax",{"scratch":"partials","name":"y","buffer":"storage","elementType":"f32"},"params_input_rows"],"dispatch":{"x":"ceilDiv(attrs.N, 64)","y":"ceilDiv(dim(shapes.aT, 0), bnb4RegRows)","z":"bnb4RegSplitCount"}},{"id":"combine","name":"MatMulBnb4.TiledReg.SplitK.Combine","shader":"reduce-axis0-splitk-combine.wgsl.jinja","derive":{"op":"\"sum\"","outputF16":"usesF16","workgroupSize":256,"split":"bnb4RegSplitCount"},"bindings":[{"scratch":"partials","name":"partials","buffer":"read-only-storage","elementType":"f32"},"y",{"name":"params","struct":[{"name":"cols","type":"u32","value":"numel(shapes.yT)"}]}],"dispatch":{"x":"min(ceilDiv((numel(shapes.yT)), (256)), 65535)","y":"ceilDiv(ceilDiv((numel(shapes.yT)), (256)), 65535)","z":1}}]},{"id":"tiled_reg","priority":12,"when":["bnb4RegFits"],"demoteWhen":["bnb4RegYieldsToRows","bnb4RegSplitFits and bnb4RegSplitCount <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)"],"derive":{"K":"attrs.K","N":"attrs.N","blockSize":"attrs.block_size","aVec4":"\"vec4<\" ~ aScalar ~ \">\"","tileRows":"bnb4RegRows"},"passes":[{"id":"main","name":"MatMulBnb4.TiledReg","shader":"matmul-bnb4-tiled-reg.wgsl.jinja","bindings":["a_vec4","b","absmax","y","params_input_rows"],"dispatch":{"x":"ceilDiv(attrs.N, 64)","y":"ceilDiv(dim(shapes.aT, 0), bnb4RegRows)"}}]},{"id":"tiled","priority":10,"when":["tileEligible","tileWorkgroupFits"],"derive":{"tileK":"tunables.PORTABLE_TILE_K","tileRows":"portableTileRows"},"passes":[{"id":"main","shader":"matmul-bnb4-tiled.wgsl.jinja","bindings":["a","b","absmax","y","params"],"dispatch":{"x":"ceilDiv(attrs.N, 64)","y":"ceilDiv(dim(shapes.aT, 0), portableTileRows)"}}]},{"id":"scalar","priority":0,"when":["commonShapeValid","portableWorkgroupSize > 0"],"derive":{"workgroupSize":"portableWorkgroupSize"},"passes":[{"id":"main","shader":"matmul-bnb4.wgsl.jinja","bindings":["a","b","absmax","y","params"],"dispatch":{"x":"min(ceilDiv((numel(shapes.yT)), (workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((numel(shapes.yT)), (workgroupSize)), 65535)","z":1}}]}]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990/* bitsandbytes 4-bit weight decoding.
Only the selected FP4 or NF4 codebook is emitted. The codebook uses var<private> rather than const because its runtime index requires a memory location in WGSL.
FP4 is sign-magnitude (bit 3 is sign), so its table is non-monotonic. NF4 is the ascending normal-float quantile codebook. The stored bytes are packed four per u32 word, byte e at bits 8 * (e % 4) of word e / 4. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */{% if quantType == 0 %}var<private> quant_map: array<f32, 16> = array<f32, 16>( 0.0, 5.208333333e-03, 0.66666667, 1.0, 0.33333333, 0.5, 0.16666667, 0.25, -0.0, -5.208333333e-03, -0.66666667, -1.0, -0.33333333, -0.5, -0.16666667, -0.25);{% else %}var<private> quant_map: array<f32, 16> = array<f32, 16>( -1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453, -0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0.0, 0.07958029955625534, 0.16093020141124725, 0.24611230194568634, 0.33791524171829224, 0.44070982933044434, 0.5626170039176941, 0.7229568362236023, 1.0);{% endif %}{{ env.wgsl.resourceDeclarations }}{% set ROWS = rowBlock %}{% set VECS = ((ROWS + 3) / 4) | int %}const K: u32 = {{ K }}u;const N: u32 = {{ N }}u;const BLOCK_SIZE: u32 = {{ blockSize }}u;const WORDS: u32 = K / 8u;var<workgroup> partials: array<array<vec4<f32>, 256>, {{ VECS }}>;// The codebook lives in workgroup memory: sixteen entries in sixteen banks, so per-lane// lookups never conflict and never touch the private table.var<workgroup> codebook: array<f32, 16>;
@compute @workgroup_size(256, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32) { let lane = tid % 32u; if (tid < 16u) { codebook[tid] = quant_map[tid]; } workgroupBarrier(); let col = (wid.x + wid.y * {{ DISPATCH_FOLD_WIDTH }}u) * 8u + tid / 32u;{% for v in range(VECS) %} var acc{{ v }} = vec4<f32>(0.0);{% endfor %} if (col < N) { // Four independent words per lane per step keep loads in flight. for (var w0 = lane; w0 < WORDS; w0 += 128u) { var stored: array<u32, 4>; var scale: vec4<f32>;{% for u in range(4) %} if (w0 + {{ u * 32 }}u < WORDS) { stored[{{ u }}] = b[col * WORDS + w0 + {{ u * 32 }}u]; scale[{{ u }}] = f32(absmax[(col * K + (w0 + {{ u * 32 }}u) * 8u) / BLOCK_SIZE]); }{% endfor %}{% for u in range(4) %} if (w0 + {{ u * 32 }}u < WORDS) { let w = w0 + {{ u * 32 }}u; // Byte j holds codes 2j (high nibble) and 2j + 1 (low nibble). let first = vec4<f32>(codebook[(stored[{{ u }}] >> 4u) & 15u], codebook[stored[{{ u }}] & 15u], codebook[(stored[{{ u }}] >> 12u) & 15u], codebook[(stored[{{ u }}] >> 8u) & 15u]) * scale[{{ u }}]; let second = vec4<f32>(codebook[(stored[{{ u }}] >> 20u) & 15u], codebook[(stored[{{ u }}] >> 16u) & 15u], codebook[(stored[{{ u }}] >> 28u) & 15u], codebook[(stored[{{ u }}] >> 24u) & 15u]) * scale[{{ u }}];{% for r in range(ROWS) %} acc{{ (r / 4) | int }}[{{ r % 4 }}] += dot(vec4<f32>(a[{{ r }}u * (K / 4u) + w * 2u]), first) + dot(vec4<f32>(a[{{ r }}u * (K / 4u) + w * 2u + 1u]), second);{% endfor %} }{% endfor %} } }{% for v in range(VECS) %} partials[{{ v }}][tid] = acc{{ v }};{% endfor %} for (var stride = 16u; stride > 0u; stride = stride / 2u) { workgroupBarrier(); if (lane < stride) {{% for v in range(VECS) %} partials[{{ v }}][tid] += partials[{{ v }}][tid + stride];{% endfor %} } } if (lane == 0u && col < N) {{% for r in range(ROWS) %} y[{{ r }}u * N + col] = {{ aScalar }}(partials[{{ (r / 4) | int }}][tid][{{ r % 4 }}]);{% endfor %} }}12345678910115121314151617181 unmodified line2021221415162324252627282930313233349 unmodified lines4445464748495051525354555657355859376061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011140411121131141151161171181191201211221231241251265212712812913056571311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701716117217317417517612 unmodified lines18919019180192193194195196197198199200201202{% set rowBlock = rowBlock | default(1) %}{% set rowBatch = rowBatch | default(false) %}{% set vectorDecode = vectorDecode | default(false) %}{% set staticGeometry = staticGeometry | default(false) %}{% set kCount = K ~ "u" if staticGeometry else "params.K" %}{% set nCount = N ~ "u" if staticGeometry else "params.N" %}{% set accType = "f32" if rowBlock == 1 else "vec" ~ rowBlock ~ "<f32>" %}{{ env.wgsl.resourceDeclarations }}
const WG: u32 = {{ workgroupSize }}u;
var<workgroup> partials: array<f32, {{ workgroupSize }}>;var<workgroup> partials: array<{{ accType }}, {{ workgroupSize }}>;
{% set needDequantWeight4 = vectorDecode %}{% set needDequantWeight = not vectorDecode or not bnbVec4AlignedRows %}/* bitsandbytes 4-bit weight decoding.
Only the selected FP4 or NF4 codebook is emitted. The codebook uses1 unmodified line location in WGSL.
FP4 is sign-magnitude (bit 3 is sign), so its table is non-monotonic. NF4 is the ascending normal-float quantile codebook. Each stored byte is carried in one widened u32. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */ the ascending normal-float quantile codebook. The stored bytes are packed four per u32 word, byte e at bits 8 * (e % 4) of word e / 4. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */{% set quantBlockSize = blockSize ~ "u" if staticGeometry is defined and staticGeometry else "params.blockSize" %}{% set alignedWeight4 = bnbVec4AlignedRows is defined and bnbVec4AlignedRows %}{% set scalarDequant = needDequantWeight is not defined or needDequantWeight %}{% set vectorDequant = needDequantWeight4 is defined and needDequantWeight4 %}{% set byteReads = scalarDequant or (vectorDequant and not alignedWeight4) %}{% if quantType == 0 %}var<private> quant_map: array<f32, 16> = array<f32, 16>( 0.0, 5.208333333e-03, 0.66666667, 1.0,9 unmodified lines 0.44070982933044434, 0.5626170039176941, 0.7229568362236023, 1.0);{% endif %}{% if byteReads %}
// Stored byte `index` of the packed weight words.fn weight_byte(index: u32) -> u32 { return (b[index >> 2u] >> ((index & 3u) * 8u)) & 0xFFu;}{% endif %}{% if scalarDequant %}
// One dequantized weight at flat index `flat` into the [N, K] weight.fn dequant_weight(flat: u32) -> f32 { let byte = b[flat >> 1u]; let byte = weight_byte(flat >> 1u); let code = select(byte & 0xFu, (byte >> 4u) & 0xFu, (flat & 1u) == 0u); return quant_map[code] * f32(absmax[flat / params.blockSize]); return quant_map[code] * f32(absmax[flat / {{ quantBlockSize }}]);}{% endif %}{% if vectorDequant %}
// Four consecutive dequantized weights starting at flat index `flat` into the// [N, K] weight. Consecutive indices share a stored byte, so the run costs two// or three byte loads instead of four; the parity of `flat` decides which// nibble opens the run.fn dequant_weight4(flat: u32) -> vec4<f32> { let base = flat >> 1u;{% if alignedWeight4 %} // An aligned run starts on an even byte, so both bytes share one word. let pair = b[base >> 2u] >> ((base & 2u) * 8u); let byte0 = pair & 0xFFu; let byte1 = (pair >> 8u) & 0xFFu;{% else %} let byte0 = weight_byte(base); let byte1 = weight_byte(base + 1u); let byte2 = weight_byte(base + 2u);{% endif %}{% if alignedWeight4 %} let codes = vec4<u32>((byte0 >> 4u) & 0xFu, byte0 & 0xFu, (byte1 >> 4u) & 0xFu, byte1 & 0xFu);{% else %} var codes: vec4<u32>; if ((flat & 1u) == 0u) { codes = vec4<u32>((byte0 >> 4u) & 0xFu, byte0 & 0xFu, (byte1 >> 4u) & 0xFu, byte1 & 0xFu); } else { codes = vec4<u32>(byte0 & 0xFu, (byte1 >> 4u) & 0xFu, byte1 & 0xFu, (byte2 >> 4u) & 0xFu); }{% endif %} // block_size is a power of two of at least 16, so a four-weight run stays // inside one block unless it starts within three of the block's end.{% if alignedWeight4 %} let scales = vec4<f32>(f32(absmax[flat / {{ quantBlockSize }}]));{% else %} var scales: vec4<f32>; if (flat % {{ quantBlockSize }} + 3u < {{ quantBlockSize }}) { scales = vec4<f32>(f32(absmax[flat / {{ quantBlockSize }}])); } else { scales = vec4<f32>( f32(absmax[flat / {{ quantBlockSize }}]), f32(absmax[(flat + 1u) / {{ quantBlockSize }}]), f32(absmax[(flat + 2u) / {{ quantBlockSize }}]), f32(absmax[(flat + 3u) / {{ quantBlockSize }}]) ); }{% endif %} return vec4<f32>(quant_map[codes.x], quant_map[codes.y], quant_map[codes.z], quant_map[codes.w]) * scales;}{% endif %}
// Decode (M == 1): one workgroup owns each output column, with lanes striding K.// Each lane keeps one accumulator and the workgroup closes with a tree reduction.// Each workgroup owns an output column and a query-row block, with lanes striding K.// Each lane keeps one f32 accumulator per row and closes with a tree reduction.@compute @workgroup_size(WG, 1, 1)fn main( @builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) { let tid = lid.x;{% if rowBatch %} let rowBase = wid.z * {{ rowBlock }}u;{% endif %} // 2D-folded dispatch: wid.y carries the high bits past the per-dimension // limit. The fold over-dispatches, so tail workgroups must leave before the // first barrier — hence the early return here rather than a guarded write. let col = wid.x + wid.y * {{ DISPATCH_FOLD_WIDTH }}u; if (col >= params.N) { if (col >= {{ nCount }}) { return; }
var acc = 0.0; let b_row_base = col * params.K;{% for r in range(rowBlock) %} var acc{% if rowBlock > 1 %}{{ r }}{% endif %} = 0.0;{% endfor %} let b_row_base = col * {{ kCount }};{% if vectorDecode %} for (var k = tid * 4u; k + 3u < {{ kCount }}; k += WG * 4u) { let weights = dequant_weight4(b_row_base + k);{% for r in range(rowBlock) %} if (rowBase + {{ r }}u < {{ rowCount }}u) { let ai{{ r }} = (rowBase + {{ r }}u) * {{ kCount }} + k;{% if bnbVec4AlignedRows %} let activation{{ r }} = vec4<f32>(a[ai{{ r }} / 4u]);{% else %} let activation{{ r }} = vec4<f32>(f32(a[ai{{ r }}]), f32(a[ai{{ r }} + 1u]), f32(a[ai{{ r }} + 2u]), f32(a[ai{{ r }} + 3u]));{% endif %} acc{{ r }} += dot(activation{{ r }}, weights); }{% endfor %} }{% if not bnbVec4AlignedRows %} let tail_k = ({{ kCount }} / 4u) * 4u + tid; if (tail_k < {{ kCount }}) { let weight = dequant_weight(b_row_base + tail_k);{% for r in range(rowBlock) %} if (rowBase + {{ r }}u < {{ rowCount }}u) { acc{{ r }} += f32(a[(rowBase + {{ r }}u) * {{ kCount }} + tail_k]) * weight; }{% endfor %} }{% endif %}{% else %} for (var k = tid; k < params.K; k = k + WG) {{% if rowBlock == 1 %} acc = acc + f32(a[k]) * dequant_weight(b_row_base + k);{% else %} let weight = dequant_weight(b_row_base + k);{% for r in range(rowBlock) %} acc{{ r }} = acc{{ r }} + f32(a[{% if r > 0 %}{{ r }}u * params.K + {% endif %}k]) * weight;{% endfor %}{% endif %} } partials[tid] = acc;{% endif %} partials[tid] = {% if rowBlock > 1 %}{{ accType }}({% endif %}{% for r in range(rowBlock) %}acc{% if rowBlock > 1 %}{{ r }}{% endif %}{% if not loop.last %}, {% endif %}{% endfor %}{% if rowBlock > 1 %}){% endif %};
// Ceil-halving tree reduce: WG is device-bounded and need not be // a power of two, so the live count is carried explicitly. Plain `stride /= 2`12 unmodified lines }
if (tid == 0u) { y[col] = {{ aScalar }}(partials[0]);{% for r in range(rowBlock) %}{% if rowBatch %} if (rowBase + {{ r }}u < {{ rowCount }}u) { y[(rowBase + {{ r }}u) * {{ nCount }} + col] = {{ aScalar }}(partials[0][{{ r }}]); }{% else %} y[{% if r > 0 %}{{ r }}u * {{ nCount }} + {% endif %}col] = {{ aScalar }}(partials[0]{% if rowBlock > 1 %}[{{ r }}]{% endif %});{% endif %}{% endfor %} }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331{%- macro registerPackedBPrelude() -%}/* bitsandbytes 4-bit weight decoding.
Only the selected FP4 or NF4 codebook is emitted. The codebook uses var<private> rather than const because its runtime index requires a memory location in WGSL.
FP4 is sign-magnitude (bit 3 is sign), so its table is non-monotonic. NF4 is the ascending normal-float quantile codebook. The stored bytes are packed four per u32 word, byte e at bits 8 * (e % 4) of word e / 4. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */{% if quantType == 0 %}var<private> quant_map: array<f32, 16> = array<f32, 16>( 0.0, 5.208333333e-03, 0.66666667, 1.0, 0.33333333, 0.5, 0.16666667, 0.25, -0.0, -5.208333333e-03, -0.66666667, -1.0, -0.33333333, -0.5, -0.16666667, -0.25);{% else %}var<private> quant_map: array<f32, 16> = array<f32, 16>( -1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453, -0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0.0, 0.07958029955625534, 0.16093020141124725, 0.24611230194568634, 0.33791524171829224, 0.44070982933044434, 0.5626170039176941, 0.7229568362236023, 1.0);{% endif %}fn bnb4_packed_word(column: u32, reduction: u32) -> vec4<u32> { let flat = column * {{ K }}u + reduction; let scale = f32(absmax[flat / {{ blockSize }}u]); // Eight codes from a multiple of eight fill one stored word. let stored = b[flat >> 3u]; var word: vec4<u32>; for (var i = 0u; i < 4u; i++) { let byte = (stored >> (i * 8u)) & 0xFFu; word[i] = bitcast<u32>(vec2<f16>(f16(codebook[(byte >> 4u) & 0xFu] * scale), f16(codebook[byte & 0xFu] * scale))); } return word;}{%- endmacro -%}{%- macro registerBeforeEntryPoint() %}var<workgroup> codebook: array<f32, 16>;{% endmacro -%}{%- macro registerWorkgroupPrelude() %} if (tid < 16u) { codebook[tid] = quant_map[tid]; }{% endmacro -%}{%- macro registerLoadPackedB(column, reduction) -%}bnb4_packed_word({{ column }}, {{ reduction }}){%- endmacro -%}{% set RESULT_SCRATCH_WORDS = 256 %}{%- set PAIRED_SWIGLU = false -%}{%- set TA = false -%}{%- set TB = true -%}{%- set BM = registerTileM -%}{%- set BN = registerTileN -%}{%- set BK = registerTileK -%}{%- set PAD = registerSharedPad | default(0) -%}{%- set FR = (BM / 32) | int -%}{%- set FC = (BN / 32) | int -%}{%- set ACOLS = BM if TA else BK -%}{%- set AROWS = BK if TA else BM -%}{%- set ASTRIDE = ((ACOLS + PAD) / 8) | int -%}{%- set BSTRIDE = (((BK if TB else BN) + PAD) / 8) | int -%}{%- set AWORDS = ((AROWS * (ACOLS + PAD)) / 8) | int -%}{%- set BWORDS = (((BN if TB else BK) * ((BK if TB else BN) + PAD)) / 8) | int -%}{%- set ASIZE = max(AWORDS, RESULT_SCRATCH_WORDS) -%}{%- set OUT_SLOTS = ((BM * BN) / 8 / 128) | int -%}{%- set PREFETCH = registerPrefetch | default(false) -%}{%- set SPLIT_K = false -%}{%- macro coordinates(name) -%}{% if name == "a" %} let row = rowBase + flat / {{ (BK / 8) | int }}u; let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;{% else %} let col = colBase + flat / {{ (BK / 8) | int }}u; let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;{% endif %}{%- endmacro -%}{%- macro guard(name) -%}{%- if name == "a" -%}row < M && k + 7u < K{%- else -%}col < N && k + 7u < K{%- endif -%}{%- endmacro -%}{%- macro address(name) -%}{%- if name == "a" -%}({{ "k * M + row" if TA else "row * K + k" }}) / 8u{%- else -%}({{ "col * K + k" if TB else "k * N + col" }}) / 8u{%- endif -%}{%- endmacro -%}{%- macro shared_index(name) -%}{%- set PAYLOAD = ((ACOLS if name == "a" else BK if TB else BN) / 8) | int -%}{%- set STRIDE = ASTRIDE if name == "a" else BSTRIDE -%}(flat / {{ PAYLOAD }}u) * {{ STRIDE }}u + flat % {{ PAYLOAD }}u{%- endmacro -%}{%- macro result(value, column) -%}f16({{ value }}){%- endmacro -%}{%- macro output_address() -%}(row * N + col) / 8u{%- endmacro -%}{%- macro half_output_guard() -%}row < M && {{ "col + 7u < N" }}{%- endmacro -%}{%- macro store_half_result() -%}y[{{ output_address() }}] = {{ pack_result("values") }};{%- endmacro -%}{%- macro pack_result(source) -%}vec4<u32>({% for pair in range(4) %} bitcast<u32>(vec2<f16>({{ result(source ~ "[" ~ (pair * 2) ~ "]", "col + " ~ (pair * 2) ~ "u") }}, {{ result(source ~ "[" ~ (pair * 2 + 1) ~ "]", "col + " ~ (pair * 2 + 1) ~ "u") }})){{ "," if pair != 3 else "" }}{% endfor %} ){%- endmacro -%}{%- macro load_left_fragment(r, step) %} let left{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>( &tileA, subgroupRow * {{ ASTRIDE }}u + {{ r * 16 * ASTRIDE + (step / 8) | int }}u, {{ ASTRIDE }}u);{%- endmacro -%}{%- macro load_right_fragment(c, step) %} let right{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, col_major>( &tileB, subgroupCol * {{ BSTRIDE }}u + {{ c * 16 * BSTRIDE + (step / 8) | int }}u, {{ BSTRIDE }}u);{%- endmacro -%}{%- macro multiply_fragment(r, c) %} acc{{ r }}_{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ r }}, right{{ c }}, acc{{ r }}_{{ c }});{%- endmacro -%}enable subgroups;enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{% if registerPackedBPrelude is defined %}{{ registerPackedBPrelude() }}{% endif %}{{ env.wgsl.resourceDeclarations }}const N: u32 = {{ N }}u;const K: u32 = {{ K }}u;const TILE_M: u32 = {{ BM }}u;const TILE_N: u32 = {{ BN }}u;const TILE_K: u32 = {{ BK }}u;var<workgroup> tileA: array<vec4<u32>, {{ ASIZE }}>;var<workgroup> tileB: array<vec4<u32>, {{ BWORDS }}>;
fn loadTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) { let M = params.M;{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %} for (var flat = tid; flat < {{ WORDS }}u; flat += 128u) {{{ coordinates(name) }} var value = vec4<u32>(0u);{% if name == "b" and registerLoadPackedB is defined %} if ({{ guard(name) }}) { value = {{ registerLoadPackedB("col", "k") }}; }{% else %} if ({{ guard(name) }}) { value = {{ name }}[{{ address(name) }}]; }{% endif %} tile{{ "A" if name == "a" else "B" }}[{{ shared_index(name) }}] = value; }{% endfor %}}
{% if PREFETCH %}struct PrefetchedTiles { a: array<vec4<u32>, {{ ((BM * BK / 8 + 127) / 128) | int }}>, b: array<vec4<u32>, {{ ((BK * (2 * BN if PAIRED_SWIGLU else BN) / 8 + 127) / 128) | int }}>,};fn prefetchTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) -> PrefetchedTiles { let M = params.M; var values: PrefetchedTiles;{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}{% for slot in range(((WORDS + 127) / 128) | int) %} { let flat = tid + {{ slot * 128 }}u; if (flat < {{ WORDS }}u) {{{ coordinates(name) }}{% if name == "b" and registerLoadPackedB is defined %} if ({{ guard(name) }}) { values.b[{{ slot }}] = {{ registerLoadPackedB("col", "k") }}; }{% else %} if ({{ guard(name) }}) { values.{{ name }}[{{ slot }}] = {{ name }}[{{ address(name) }}]; }{% endif %} } }{% endfor %}{% endfor %} return values;}fn stagePrefetchedTiles(values: PrefetchedTiles, tid: u32) {{% for name in ["a", "b"] %}{% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}{% for slot in range(((WORDS + 127) / 128) | int) %} { let flat = tid + {{ slot * 128 }}u; if (flat < {{ WORDS }}u) { tile{{ "A" if name == "a" else "B" }}[{{ shared_index(name) }}] = values.{{ name }}[{{ slot }}]; } }{% endfor %}{% endfor %}}{% endif %}
fn readA(row: u32, k: u32) -> f32 { let word = tileA[row * {{ ASTRIDE }}u + k / 8u]; return f32(bitcast<vec2<f16>>(word[(k % 8u) / 2u])[k % 2u]);}fn readB(k: u32, col: u32) -> f32 { let contiguous = {{ "k" if TB else "col" }}; let word = tileB[{{ "col" if TB else "k" }} * {{ BSTRIDE }}u + contiguous / 8u]; return f32(bitcast<vec2<f16>>(word[(contiguous % 8u) / 2u])[contiguous % 2u]);}
// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}{% if registerBeforeEntryPoint is defined %}{{ registerBeforeEntryPoint() }}{% endif %}@compute @workgroup_size(128, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32, @builtin(subgroup_invocation_id) lane: u32) { let M = params.M; let rowBase = wid.y * TILE_M; let colBase = wid.x * TILE_N;{% if registerWorkgroupPrelude is defined %}{{ registerWorkgroupPrelude() }}{% endif %} let role = min(claimMatrixSubgroupRole(width, 32u), 3u); let nativeTopology = matrixTopologyAccepted(tid, 4u); if (nativeTopology) { let subgroupRow = (role / 2u) * {{ FR * 16 }}u; let subgroupCol = (role % 2u) * {{ FC * 16 }}u;{% for r in range(FR) %}{% for c in range(FC) %} var acc{{ r }}_{{ c }}: subgroup_matrix_result<f32, 16, 16>;{% endfor %}{% endfor %}{% if PREFETCH %} var nextTiles = prefetchTiles(rowBase, colBase, {{ "beginK" if SPLIT_K else "0u" }}, tid);{% endif %} for (var kk = {{ "beginK" if SPLIT_K else "0u" }}; kk < {{ "endK" if SPLIT_K else "K" }}; kk += TILE_K) {{% if PREFETCH %} stagePrefetchedTiles(nextTiles, tid);{% else %} loadTiles(rowBase, colBase, kk, tid);{% endif %} workgroupBarrier();{% if PREFETCH %} if (kk + TILE_K < {{ "endK" if SPLIT_K else "K" }}) { nextTiles = prefetchTiles(rowBase, colBase, kk + TILE_K, tid); }{% endif %}{% for step in range(0, BK, 16) %} {{% for r in range(FR) %}{{ load_left_fragment(r, step) }}{% endfor %}{% for c in range(FC) %}{{ load_right_fragment(c, step) }}{% endfor %}{% for r in range(FR) %}{% for c in range(FC) %}{{ multiply_fragment(r, c) }}{% endfor %}{% endfor %} }{% endfor %} workgroupBarrier(); } let scratchBase = role * 64u;{% for r in range(FR) %}{% for c in range(FC) %} { subgroupMatrixStore<row_major>(&tileA, scratchBase, acc{{ r }}_{{ c }}, 4u); workgroupBarrier(); let row = rowBase + subgroupRow + {{ r * 16 }}u + lane / 2u; let col = colBase + subgroupCol + {{ c * 16 }}u + (lane % 2u) * 8u; if ({{ half_output_guard() }}) { let first = bitcast<vec4<f32>>(tileA[scratchBase + lane * 2u]); let second = bitcast<vec4<f32>>(tileA[scratchBase + lane * 2u + 1u]); let values = array<f32, 8>(first.x, first.y, first.z, first.w, second.x, second.y, second.z, second.w); {{ store_half_result() }} } workgroupBarrier(); }{% endfor %}{% endfor %} } else { for (var slot = 0u; slot < {{ OUT_SLOTS }}u; slot += 1u) { let flat = tid + slot * 128u; let tileRow = flat / {{ (BN / 8) | int }}u; let tileCol = (flat % {{ (BN / 8) | int }}u) * 8u; var acc: array<f32, 8>;{% for component in range(8) %} acc[{{ component }}] = 0.0;{% endfor %} for (var kk = {{ "beginK" if SPLIT_K else "0u" }}; kk < {{ "endK" if SPLIT_K else "K" }}; kk += TILE_K) { loadTiles(rowBase, colBase, kk, tid); workgroupBarrier(); for (var k = 0u; k < TILE_K; k += 1u) { let left = readA(tileRow, k); for (var component = 0u; component < 8u; component += 1u) { acc[component] = fma(left, readB(k, tileCol + component), acc[component]); } } workgroupBarrier(); } let row = rowBase + tileRow; let col = colBase + tileCol; if ({{ half_output_guard() }}) { let values = array<f32, 8>({% for component in range(8) %} acc[{{ component }}u]{{ "," if component != 7 else "" }}{% endfor %} ); {{ store_half_result() }} } } }}1 unmodified line2345567838 unmodified lines4748495051525051525354555617 unmodified lines7475767677787980818283777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615787158159160901611621631641651661679716816917017116 unmodified lines1881891901201911921931231241251941951961971291301311981992001342012022032041 unmodified line2062072081421431441451461472092102112127 unmodified lines2202212221612232242252262271651662282292301682312321702332342352362372382392402412422432442452461771782472482492502512522532542551802562572582592602612622632642652662671831841851861871881891901 unmodified line{% set stageActivations = stageActivations | default(false) %}{% set aStride = "TILE_K" if stageActivations else "K" %}{% set yStride = "TILE_COLS" if stageActivations else "N" %}// Large aligned prefill tier. The packed B tile is dequantized once per// Large aligned prefill variant. The packed B tile is dequantized once per// workgroup, then reused by subgroup-matrix f32 multiply-accumulate operations.// This specialization operates on full A, B, and output tiles, so both// subgroupMatrixLoad and the direct output stores are in bounds.38 unmodified lines location in WGSL.
FP4 is sign-magnitude (bit 3 is sign), so its table is non-monotonic. NF4 is the ascending normal-float quantile codebook. Each stored byte is carried in one widened u32. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */ the ascending normal-float quantile codebook. The stored bytes are packed four per u32 word, byte e at bits 8 * (e % 4) of word e / 4. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */{% if quantType == 0 %}var<private> quant_map: array<f32, 16> = array<f32, 16>( 0.0, 5.208333333e-03, 0.66666667, 1.0,17 unmodified lines let tile_offset = row * TILE_K + col;
// Eligibility guarantees that each aligned LOAD_WIDTH slice stays in one // quantization block and begins on an even weight. This shader widens each // packed byte once and reuses both nibbles. for (var i = 0u; i < LOAD_WIDTH; i = i + 2u) { let packed = b[(flat + i) >> 1u]; let high = (packed >> 4u) & 0xFu; let low = packed & 0xFu; tile_B[tile_offset + i] = quant_map[high] * scale; tile_B[tile_offset + i + 1u] = quant_map[low] * scale; // quantization block and begins on a multiple of eight weights, so every // eight codes come from one stored word whose bytes each carry two. for (var w = 0u; w < LOAD_WIDTH / 8u; w = w + 1u) { let stored = b[(flat >> 3u) + w]; for (var j = 0u; j < 4u; j = j + 1u) { let packed = (stored >> (j * 8u)) & 0xFFu; let i = w * 8u + j * 2u; tile_B[tile_offset + i] = quant_map[(packed >> 4u) & 0xFu] * scale; tile_B[tile_offset + i + 1u] = quant_map[packed & 0xFu] * scale; } }}
// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}// The portable arm owns two result components per logical 32-invocation group.// Staging casts, 8-wide K steps, barriers and the epilogue match the// subgroup-matrix arm.var<private> matrixSoftwareLane: u32;
fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>, acc: vec2<f32>) -> vec2<f32> { var value = acc; for (var k = 0u; k < 8u; k += 1u) { value = fma(vec2<f32>(lhs[k]), rhs[k], value); } return value;}
{% macro matrixType(software, kind, scalar) %}{% if software %}{% if kind == "left" %}array<f32, 8>{% elif kind == "right" %}array<vec2<f32>, 8>{% else %}vec2<{{ scalar }}>{% endif %}{% else %}subgroup_matrix_{{ kind }}<{{ scalar }}, 8, 8>{% endif %}{% endmacro %}
{% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}{% if kind == "left" %}array<f32, 8>({% for k in range(8) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}(matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u{% else %}{{ k }}u * ({{ stride }}) + matrixSoftwareLane / 4u{% endif %}]){{ "," if k < 7 else "" }}{% endfor %}){% else %}array<vec2<f32>, 8>({% for k in range(8) %}vec2<f32>({% for h in range(2) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}{{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u{% else %}((matrixSoftwareLane % 4u) * 2u + {{ h }}u) * ({{ stride }}) + {{ k }}u{% endif %}]){{ "," if h == 0 else "" }}{% endfor %}){{ "," if k < 7 else "" }}{% endfor %}){% endif %}{% endif %}{% endmacro %}
{% macro matrixMma(software, scalar, lhs, rhs, acc) %}{% if not software %}subgroupMatrixMultiplyAccumulate({{ lhs }}, {{ rhs }}, {{ acc }}){% else %}vec2<{{ scalar }}>(matrixSoftwareMultiplyAccumulate({{ lhs }}, {{ rhs }}, vec2<f32>({{ acc }}))){% endif %}{% endmacro %}
{% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{ let matrixPointer = {{ pointer }}; let matrixValue = {{ value }};{% for h in range(2) %} (*matrixPointer)[({{ offset }}) + {{ {"row_major": "(matrixSoftwareLane / 4u) * (" ~ stride ~ ") + (matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u", "col_major": "((matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u) * (" ~ stride ~ ") + matrixSoftwareLane / 4u"}[major] }}] = matrixValue.{{ "x" if h == 0 else "y" }};{% endfor %}}{% endif %}{% endmacro %}
{% macro tile_body(stageActivations, tileRows, subRows, subCols, rowMatrices, colMatrices, rowSubtiles, workgroupSize, rowOffset, aStride, yStride) %} let a_base = workgroup_id.y * TILE_ROWS{% if (rowOffset | default(0)) > 0 %} + {{ rowOffset | default(0) }}u{% endif %};{% macro tile_body(matrixSoftware, stageActivations, tileRows, subRows, subCols, rowMatrices, colMatrices, rowSubtiles, workgroupSize, rowOffset, aStride, yStride) %} let a_base = workgroup_id.y * TILE_ROWS{% if (rowOffset | default(0)) > 0 %} + {{ rowOffset | default(0) }}u{% endif %}; let b_base = workgroup_id.x * TILE_COLS;
let subgroup_id = local_idx / subgroup_size; let subgroup_id = matrixRole; let subtile_idx = subgroup_id / {{ rowSubtiles }}u; let subtile_idy = subgroup_id % {{ rowSubtiles }}u; let base_A = subtile_idy * SUB_ROWS; let base_B = subtile_idx * SUB_COLS;
{% for row in range(rowMatrices) %}{% for col in range(colMatrices) %} var matC{{ row }}{{ col }}: subgroup_matrix_result<f32, {{ matrixSize }}, {{ matrixSize }}>; var matC{{ row }}{{ col }}: {{ matrixType(matrixSoftware, "result", "f32") }};{% endfor %}{% endfor %}
for (var k_base = 0u; k_base < K; k_base += TILE_K) {16 unmodified lines{% endif %} workgroupBarrier();
for (var step = 0u; step < TILE_K; step += {{ matrixSize }}u) { for (var step = 0u; step < TILE_K; step += 8u) { let matrix_a_offset = {% if stageActivations %}base_A * TILE_K + step{% else %}(a_base + base_A) * K + k_base + step{% endif %};{% for row in range(rowMatrices) %} let matA{{ row }} = subgroupMatrixLoad<subgroup_matrix_left<f32, {{ matrixSize }}, {{ matrixSize }}>, row_major>( &{{ "tile_A" if stageActivations else "a" }}, matrix_a_offset + {{ row * matrixSize }}u * {{ aStride }}, {{ aStride }} ); let matA{{ row }} = {{ matrixLoad(matrixSoftware, "left", "f32", "row_major", "&" ~ ("tile_A" if stageActivations else "a"), "matrix_a_offset + " ~ (row * matrixSize) ~ "u * " ~ (aStride), aStride) }};{% endfor %} let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;{% for col in range(colMatrices) %} let matB{{ col }} = subgroupMatrixLoad<subgroup_matrix_right<f32, {{ matrixSize }}, {{ matrixSize }}>, col_major>( &tile_B, matrix_b_offset + {{ col * matrixSize }}u * TILE_K, TILE_K ); let matB{{ col }} = {{ matrixLoad(matrixSoftware, "right", "f32", "col_major", "&tile_B", "matrix_b_offset + " ~ (col * matrixSize) ~ "u * TILE_K", "TILE_K") }};{% endfor %}{% for row in range(rowMatrices) %}{% for col in range(colMatrices) %} matC{{ row }}{{ col }} = subgroupMatrixMultiplyAccumulate(matA{{ row }}, matB{{ col }}, matC{{ row }}{{ col }}); matC{{ row }}{{ col }} = {{ matrixMma(matrixSoftware, "f32", "matA" ~ (row), "matB" ~ (col), "matC" ~ (row) ~ (col)) }};{% endfor %}{% endfor %} } workgroupBarrier();1 unmodified line
let output_offset = {% if stageActivations %}base_A * TILE_COLS + base_B{% else %}(a_base + base_A) * N + b_base + base_B{% endif %};{% for row in range(rowMatrices) %}{% for col in range(colMatrices) %} subgroupMatrixStore<row_major>( &{{ "tile_B" if stageActivations else "y" }}, output_offset + {{ row * matrixSize }}u * {{ yStride }} + {{ col * matrixSize }}u, matC{{ row }}{{ col }}, {{ yStride }} );{{ matrixStore(matrixSoftware, "row_major", "&" ~ ("tile_B" if stageActivations else "y"), "output_offset + " ~ (row * matrixSize) ~ "u * " ~ (yStride) ~ " + " ~ (col * matrixSize) ~ "u", "matC" ~ (row) ~ (col), yStride) }}{% endfor %}{% endfor %}{% if stageActivations %} // The closing K-loop barrier ends all weight reads. Output banks reuse B7 unmodified lines }{% endif %}{% endmacro %}{% if hybridRows %}fn full_tile(workgroup_id: vec3<u32>, local_idx: u32, subgroup_size: u32) {{% for matrixSoftware in [false, true] %}fn full_tile{{ "_software" if matrixSoftware else "" }}(workgroup_id: vec3<u32>, local_idx: u32, matrixRole: u32) { const TILE_ROWS: u32 = {{ tileRows }}u; const SUB_ROWS: u32 = {{ subRows }}u; const SUB_COLS: u32 = {{ subCols }}u;{{ tile_body(false, tileRows, subRows, subCols, rowMatrices, colMatrices, rowSubtiles, workgroupSize, 0, "K", "N") }}}fn partial_tile(workgroup_id: vec3<u32>, local_idx: u32, subgroup_size: u32) {{{ tile_body(matrixSoftware, false, tileRows, subRows, subCols, rowMatrices, colMatrices, rowSubtiles, workgroupSize, 0, "K", "N") }}}fn partial_tile{{ "_software" if matrixSoftware else "" }}(workgroup_id: vec3<u32>, local_idx: u32, matrixRole: u32) { const TILE_ROWS: u32 = {{ hybridTailTileRows }}u; const SUB_ROWS: u32 = {{ matrixSize }}u; const SUB_ROWS: u32 = 8u; const SUB_COLS: u32 = {{ hybridTailSubCols }}u;{{ tile_body(true, hybridTailTileRows, matrixSize, hybridTailSubCols, 1, ((hybridTailSubCols / matrixSize) | int), hybridTailRowSubtiles, workgroupSize, rowOffset, "TILE_K", "TILE_COLS") }}}{{ tile_body(matrixSoftware, true, hybridTailTileRows, matrixSize, hybridTailSubCols, 1, ((hybridTailSubCols / matrixSize) | int), hybridTailRowSubtiles, workgroupSize, rowOffset, "TILE_K", "TILE_COLS") }}}{% endfor %}{% endif %}@compute @workgroup_size({{ workgroupSize }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main( @builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(local_invocation_index) local_idx: u32, @builtin(subgroup_size) subgroup_size: u32) { let matrixRole = claimMatrixSubgroupRole(subgroup_size, 32u); let matrixAcceptedHere = matrixTopologyAccepted(local_idx, {{ workgroupSize }}u / 32u); matrixSoftwareLane = local_idx % 32u; if (matrixAcceptedHere) {{% if hybridRows %} if (workgroup_id.y < {{ fullDispatchRows }}u) { full_tile(workgroup_id, local_idx, subgroup_size); if (workgroup_id.y < {{ fullDispatchRows }}u) { full_tile(workgroup_id, local_idx, matrixRole); } else { partial_tile(vec3<u32>(workgroup_id.x, workgroup_id.y - {{ fullDispatchRows }}u, workgroup_id.z), local_idx, matrixRole); }{% else %}{{ tile_body(false, stageActivations, tileRows, subRows, subCols, rowMatrices, colMatrices, rowSubtiles, workgroupSize, (rowOffset | default(0)), aStride, yStride) }}{% endif %} } else { partial_tile(vec3<u32>(workgroup_id.x, workgroup_id.y - {{ fullDispatchRows }}u, workgroup_id.z), local_idx, subgroup_size); let matrixRole = local_idx / 32u;{% if hybridRows %} if (workgroup_id.y < {{ fullDispatchRows }}u) { full_tile_software(workgroup_id, local_idx, matrixRole); } else { partial_tile_software(vec3<u32>(workgroup_id.x, workgroup_id.y - {{ fullDispatchRows }}u, workgroup_id.z), local_idx, matrixRole); }{% else %}{{ tile_body(true, stageActivations, tileRows, subRows, subCols, rowMatrices, colMatrices, rowSubtiles, workgroupSize, (rowOffset | default(0)), aStride, yStride) }}{% endif %} }}{% else %}@compute @workgroup_size({{ workgroupSize }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main( @builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(local_invocation_index) local_idx: u32, @builtin(subgroup_size) subgroup_size: u32) {{{ tile_body(stageActivations, tileRows, subRows, subCols, rowMatrices, colMatrices, rowSubtiles, workgroupSize, (rowOffset | default(0)), aStride, yStride) }}}{% endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132/* bitsandbytes 4-bit weight decoding.
Only the selected FP4 or NF4 codebook is emitted. The codebook uses var<private> rather than const because its runtime index requires a memory location in WGSL.
FP4 is sign-magnitude (bit 3 is sign), so its table is non-monotonic. NF4 is the ascending normal-float quantile codebook. The stored bytes are packed four per u32 word, byte e at bits 8 * (e % 4) of word e / 4. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */{% if quantType == 0 %}var<private> quant_map: array<f32, 16> = array<f32, 16>( 0.0, 5.208333333e-03, 0.66666667, 1.0, 0.33333333, 0.5, 0.16666667, 0.25, -0.0, -5.208333333e-03, -0.66666667, -1.0, -0.33333333, -0.5, -0.16666667, -0.25);{% else %}var<private> quant_map: array<f32, 16> = array<f32, 16>( -1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453, -0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0.0, 0.07958029955625534, 0.16093020141124725, 0.24611230194568634, 0.33791524171829224, 0.44070982933044434, 0.5626170039176941, 0.7229568362236023, 1.0);{% endif %}{{ env.wgsl.resourceDeclarations }}{% set SPLIT = splitK | default(1) %}{% set aTile = "f16" if aScalar == "f16" else "f32" %}{% set TM = (tileRows / 16) | int %}{% set A_WORDS = tileRows * 8 %}const K: u32 = {{ K }}u;const N: u32 = {{ N }}u;const BLOCK_SIZE: u32 = {{ blockSize }}u;const BK: u32 = 32u;const BM: u32 = {{ tileRows }}u;const BN: u32 = 64u;const K_VECS: u32 = BK / 4u;{% if SPLIT > 1 %}const SPLIT_TILES: u32 = {{ tilesPerSplit }}u;{% endif %}// A rows keep their storage width; weights are float32 so no decoded value narrows.var<workgroup> tileA: array<array<vec4<{{ aTile }}>, K_VECS>, BM>;var<workgroup> tileB: array<array<array<vec4<f32>, 16>, 4>, K_VECS>;
@compute @workgroup_size(16, 16, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) { let M = params.rows; let mBase = wg.y * BM; let nBase = wg.x * BN; let li = lid.y * 16u + lid.x;{% for i in range(TM) %}{% for j in range(4) %} var acc{{ i }}{{ j }} = 0.0;{% endfor %}{% endfor %} let numTiles = (K + BK - 1u) / BK;{% if SPLIT > 1 %} let ktBegin = wg.z * SPLIT_TILES; let ktEnd = min(numTiles, ktBegin + SPLIT_TILES);{% else %} let ktBegin = 0u; let ktEnd = numTiles;{% endif %} for (var kt = ktBegin; kt < ktEnd; kt++) { let kBase = kt * BK;{% for slot in range(((A_WORDS + 255) / 256) | int) %} { let at = li + {{ slot * 256 }}u;{% if A_WORDS < 256 %} if (at < {{ A_WORDS }}u) {{% endif %} let row = at / K_VECS; let k = kBase + (at % K_VECS) * 4u; var word = vec4<{{ aTile }}>(0.0); if (mBase + row < M && k < K) { word = a[((mBase + row) * K + k) / 4u]; } tileA[row][at % K_VECS] = word;{% if A_WORDS < 256 %} }{% endif %} }{% endfor %} { // Columns run fastest so a subgroup's stores spread over the lane-interleaved tile. let column = li % BN; let chunk = li / BN; let n = nBase + column; let k = kBase + chunk * 8u; var first = vec4<f32>(0.0); var second = vec4<f32>(0.0); if (n < N && k < K) { let flat = n * K + k; let stored = b[flat >> 3u]; let scale = f32(absmax[flat / BLOCK_SIZE]); // Byte j holds codes 2j (high nibble) and 2j + 1 (low nibble). first = vec4<f32>(quant_map[(stored >> 4u) & 15u], quant_map[stored & 15u], quant_map[(stored >> 12u) & 15u], quant_map[(stored >> 8u) & 15u]) * scale; second = vec4<f32>(quant_map[(stored >> 20u) & 15u], quant_map[(stored >> 16u) & 15u], quant_map[(stored >> 28u) & 15u], quant_map[(stored >> 24u) & 15u]) * scale; } tileB[chunk * 2u][column % 4u][column / 4u] = first; tileB[chunk * 2u + 1u][column % 4u][column / 4u] = second; } workgroupBarrier(); let aRow = lid.y * {{ TM }}u; for (var kv = 0u; kv < K_VECS; kv++) {{% for i in range(TM) %} let av{{ i }} = vec4<f32>(tileA[aRow + {{ i }}u][kv]);{% endfor %}{% for j in range(4) %} let bv{{ j }} = tileB[kv][{{ j }}u][lid.x];{% endfor %}{% for i in range(TM) %}{% for j in range(4) %} acc{{ i }}{{ j }} = fma(av{{ i }}.w, bv{{ j }}.w, fma(av{{ i }}.z, bv{{ j }}.z, fma(av{{ i }}.y, bv{{ j }}.y, fma(av{{ i }}.x, bv{{ j }}.x, acc{{ i }}{{ j }}))));{% endfor %}{% endfor %} } workgroupBarrier(); } let m0 = mBase + lid.y * {{ TM }}u; let n0 = nBase + lid.x * 4u;{% for i in range(TM) %} if (m0 + {{ i }}u < M) {{% for j in range(4) %} if (n0 + {{ j }}u < N) {{% if SPLIT > 1 %} y[wg.z * M * N + (m0 + {{ i }}u) * N + n0 + {{ j }}u] = acc{{ i }}{{ j }};{% else %} y[(m0 + {{ i }}u) * N + n0 + {{ j }}u] = {{ aScalar }}(acc{{ i }}{{ j }});{% endif %} }{% endfor %} }{% endfor %}}30 unmodified lines313233343536343536373839404110 unmodified lines52535455565758596061626364655960616667686970713 unmodified lines757677717278798081757677788283848586878830 unmodified lines location in WGSL.
FP4 is sign-magnitude (bit 3 is sign), so its table is non-monotonic. NF4 is the ascending normal-float quantile codebook. Each stored byte is carried in one widened u32. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */ the ascending normal-float quantile codebook. The stored bytes are packed four per u32 word, byte e at bits 8 * (e % 4) of word e / 4. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */{% set quantBlockSize = "params.blockSize" %}{% if quantType == 0 %}var<private> quant_map: array<f32, 16> = array<f32, 16>( 0.0, 5.208333333e-03, 0.66666667, 1.0,10 unmodified lines);{% endif %}
// Stored byte `index` of the packed weight words.fn weight_byte(index: u32) -> u32 { return (b[index >> 2u] >> ((index & 3u) * 8u)) & 0xFFu;}
// Four consecutive dequantized weights starting at flat index `flat` into the// [N, K] weight. Consecutive indices share a stored byte, so the run costs two// or three byte loads instead of four; the parity of `flat` decides which// nibble opens the run.fn dequant_weight4(flat: u32) -> vec4<f32> { let base = flat >> 1u; let byte0 = b[base]; let byte1 = b[base + 1u]; let byte2 = b[base + 2u]; let byte0 = weight_byte(base); let byte1 = weight_byte(base + 1u); let byte2 = weight_byte(base + 2u); var codes: vec4<u32>; if ((flat & 1u) == 0u) { codes = vec4<u32>((byte0 >> 4u) & 0xFu, byte0 & 0xFu, (byte1 >> 4u) & 0xFu, byte1 & 0xFu);3 unmodified lines // block_size is a power of two of at least 16, so a four-weight run stays // inside one block unless it starts within three of the block's end. var scales: vec4<f32>; if (flat % params.blockSize + 3u < params.blockSize) { scales = vec4<f32>(f32(absmax[flat / params.blockSize])); if (flat % {{ quantBlockSize }} + 3u < {{ quantBlockSize }}) { scales = vec4<f32>(f32(absmax[flat / {{ quantBlockSize }}])); } else { scales = vec4<f32>( f32(absmax[flat / params.blockSize]), f32(absmax[(flat + 1u) / params.blockSize]), f32(absmax[(flat + 2u) / params.blockSize]), f32(absmax[(flat + 3u) / params.blockSize]) f32(absmax[flat / {{ quantBlockSize }}]), f32(absmax[(flat + 1u) / {{ quantBlockSize }}]), f32(absmax[(flat + 2u) / {{ quantBlockSize }}]), f32(absmax[(flat + 3u) / {{ quantBlockSize }}]) ); } return vec4<f32>(quant_map[codes.x], quant_map[codes.y], quant_map[codes.z], quant_map[codes.w]) * scales;112345567895 unmodified lines151617171819181920212223242510 unmodified lines363738394041424344453846474048495051{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %} // 2D-folded flat index: gid.y carries the high bits past the dispatch's // per-axis workgroup fold width. let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %} let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}{{ env.wgsl.resourceDeclarations }}
const WG: u32 = {{ workgroupSize }}u;5 unmodified lines location in WGSL.
FP4 is sign-magnitude (bit 3 is sign), so its table is non-monotonic. NF4 is the ascending normal-float quantile codebook. Each stored byte is carried in one widened u32. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */ the ascending normal-float quantile codebook. The stored bytes are packed four per u32 word, byte e at bits 8 * (e % 4) of word e / 4. A flat weight index maps to byte flat >> 1, and an even index reads the high nibble, matching (vi0 << 4) | vi1 packing. */{% set quantBlockSize = "params.blockSize" %}{% if quantType == 0 %}var<private> quant_map: array<f32, 16> = array<f32, 16>( 0.0, 5.208333333e-03, 0.66666667, 1.0,10 unmodified lines);{% endif %}
// Stored byte `index` of the packed weight words.fn weight_byte(index: u32) -> u32 { return (b[index >> 2u] >> ((index & 3u) * 8u)) & 0xFFu;}
// One dequantized weight at flat index `flat` into the [N, K] weight.fn dequant_weight(flat: u32) -> f32 { let byte = b[flat >> 1u]; let byte = weight_byte(flat >> 1u); let code = select(byte & 0xFu, (byte >> 4u) & 0xFu, (flat & 1u) == 0u); return quant_map[code] * f32(absmax[flat / params.blockSize]); return quant_map[code] * f32(absmax[flat / {{ quantBlockSize }}]);}
@compute @workgroup_size(WG, 1, 1)123456789101112131415161718192021222324252627282930313233341{ "name": "com.microsoft.MatMulBnb4", "id": "_com_microsoft_matmulbnb4_webgpu_2efe1ae", "version": 1, "license": "Apache-2.0", "backend": { "type": "webgpu" }, "digest": { "algorithm": "sha256", "files": { "bench.json": "Ixtu6FBToeEWEbpbM/+lGVS3jt0IPtrmZrxRfxo7Uj8=", "cast-scalar-x4.wgsl.jinja": "s8Y9E2+D7cFgYTUEJhiuPsUzvHjv2mXVoiRmv0A0vTU=", "manifest.json": "TTpD+bhv4VB93QlNQ4Z2xGHvG4ClFxnokPMIbKMH2Bc=", "matmul-bnb4-gemv.wgsl.jinja": "5mV78S/5vyeTFu8anlXAsKA+OVz7iy3fmo990lgf/yU=", "matmul-bnb4-sgmat.wgsl.jinja": "A0jgHcIQrjdodubOI3bgHSYU9SsGew+/3IJwkMMr6eo=", "matmul-bnb4-tiled.wgsl.jinja": "auoAXKsuYOXVbPmzjXMm6IQ5L1HxzjDWaPTSxD+Wd/s=", "matmul-bnb4.wgsl.jinja": "81lKMMKBPnPeNbcFXiZZe4KBGefTeBfNaHH1LSgP/6U=", "test.json": "KPAf0hjucty64auyD+xOS5RAGDEPYeAlUSJPhbig7CA=" } }, "provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } }, "webgpu": { "manifestSpec": "2.1", "variants": { "sgmat_hybrid_rows": ["matmul-bnb4-sgmat.wgsl.jinja"], "sgmat_hybrid_rows_widened": ["cast-scalar-x4.wgsl.jinja", "matmul-bnb4-sgmat.wgsl.jinja"], "sgmat_staged_rows": ["matmul-bnb4-sgmat.wgsl.jinja"], "gemv": ["matmul-bnb4-gemv.wgsl.jinja"], "sgmat": ["matmul-bnb4-sgmat.wgsl.jinja"], "sgmat_widened": ["cast-scalar-x4.wgsl.jinja", "matmul-bnb4-sgmat.wgsl.jinja"], "tiled": ["matmul-bnb4-tiled.wgsl.jinja"], "scalar": ["matmul-bnb4.wgsl.jinja"] } }}{"name":"com.microsoft.MatMulBnb4","id":"_com_microsoft_matmulbnb4_webgpu_a298375","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"bench.json":"gZ78TD1kkzo2orJp197gcm7D6lGCuZLNv07Jp0cK6fQ=","cast-scalar-x4.wgsl.jinja":"LsMttgYxu9otSS2+RK1J5X5djby/CqbbNL84WDbRiIU=","manifest.json":"MkMiIkYr8JJMsq4vohhmWPBvZcyeguE7dH0xH2BEmG4=","matmul-bnb4-gemv-words.wgsl.jinja":"+C8VE7GfV2qtanK7b2IrkJOpqBC4ykqtKJon6vuOQZ0=","matmul-bnb4-gemv.wgsl.jinja":"21Po2yJD5Y1ndp6bH3b2ABPooYYF7gJhKhUMqc52yGs=","matmul-bnb4-native16-packed.wgsl.jinja":"be1UMRoqiqGk/uIrhtYulTEq+5omemkkPoSFdC0vMQY=","matmul-bnb4-sgmat.wgsl.jinja":"7clXoUFqhJD2Tbrb87sHd9Ib0C03fRwBBZUI8yslHms=","matmul-bnb4-tiled-reg.wgsl.jinja":"td/QTwfEN8r7Hc9wnH+2V/nSousoyT98np8ZSb3Wh1o=","matmul-bnb4-tiled.wgsl.jinja":"J2k5Zf2DmvAWX0FW0caeV2sIBdhuqtDMSr0EkPmwh9Q=","matmul-bnb4.wgsl.jinja":"MZOXI7G5XA9Y1zmZBC4DbONUeKOhmM2ihSl9gpNzY1s=","reduce-axis0-splitk-combine.wgsl.jinja":"wOlms7ZUiBjREWqLuaEy8spVx+N1SAdB3jDdh3c9+2U=","test.json":"v84Nyqw+Fqd20662oFbe8Bfv0Ieu4LY0JkPY3dvM2P4="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109// Pass 2 of the split-K column-wise reduction. One invocation per output column// folds the segment partials and applies the selected reduction's final step.// Segments are folded in ascending order for deterministic results.{% set yv = "f16(" if outputF16 else "" %}{% set vy = ")" if outputF16 else "" %}{{ env.wgsl.resourceDeclarations }}{% if op == "logsum" %}
// log() returns an indeterminate value outside (0, inf), so the IEEE results// for the logarithm of a sum are chosen explicitly: a negative or NaN sum gives// NaN, a zero sum gives -inf, and +inf stays +inf. The sum is classified by its// bits because a value != value test may be folded away, and the special values// are built from those bits because a constant infinity or NaN does not compile.fn log_of_sum(total: f32) -> f32 { let bits = bitcast<u32>(total); let magnitude = bits & 0x7fffffffu; let defined = select(log(total), total, magnitude == 0x7f800000u); let zero_or_defined = select(defined, bitcast<f32>(bits | 0xff800000u), magnitude == 0u); return select(zero_or_defined, bitcast<f32>(bits | 0x7fc00000u), magnitude > 0x7f800000u || bits > 0x80000000u);}{% endif %}{% macro wgsl_minmax_identity(name, op, scalar="f32") %}/* Exact {{ op }} reduction identity. WGSL rejects infinity during constant * evaluation, so an f32 identity is constructed from its IEEE-754 bits. */fn {{ name }}() -> {{ scalar }} { var bits = {{ "0xff800000u" if op == "max" else "0x7f800000u" }}; return bitcast<f32>(bits);}{% endmacro %}
const WG: u32 = {{ workgroupSize }}u;const SPLIT: u32 = {{ split }}u;{% if op == "logsumexp" %}const F32_MIN: f32 = -3.4028234663852886e38;const F32_MAX: f32 = 3.4028234663852886e38;
fn is_nan_f32(value: f32) -> bool { let bits = bitcast<u32>(value); return (bits & 0x7f800000u) == 0x7f800000u && (bits & 0x007fffffu) != 0u;}{% elif op == "max" or op == "min" %}{{ wgsl_minmax_identity("reduction_identity", op) }}{% endif %}
@compute @workgroup_size(WG, 1, 1)fn main(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) { // The start already folds gid.y in, so the stride must span every y row too; // an x-only stride would send y = 0 lanes over columns the y >= 1 rows own. let stride = nwg.x * nwg.y * WG; let start = (gid.y * {{ DISPATCH_FOLD_WIDTH }}u * WG) + gid.x; for (var col = start; col < params.cols; col = col + stride) {{% if op == "logsumexp" %} // Merge SPLIT (segMax, segSumExp) pairs stably; carry NaN / +Inf markers. var nan_value = 0.0; var has_nan = false; var global_max = F32_MIN; for (var seg = 0u; seg < SPLIT; seg = seg + 1u) { let nv = partials[(2u * SPLIT + seg) * params.cols + col]; if (nv != 0.0 || is_nan_f32(nv)) { has_nan = true; nan_value = nv; } global_max = max(global_max, partials[seg * params.cols + col]); } var sum = 0.0; for (var seg = 0u; seg < SPLIT; seg = seg + 1u) { let seg_max = partials[seg * params.cols + col]; let seg_sum = partials[(SPLIT + seg) * params.cols + col]; sum = sum + seg_sum * exp(seg_max - global_max); } let has_positive_inf = global_max > F32_MAX; let finite_or_inf = select(global_max + log(sum), global_max, has_positive_inf); y[col] = {{ yv }}select(finite_or_inf, nan_value, has_nan){{ vy }};{% else %}{% if op == "max" %} var total = reduction_identity();{% elif op == "min" %} var total = reduction_identity();{% elif op == "prod" %} var total = 1.0;{% else %} var total = 0.0;{% endif %} for (var seg = 0u; seg < SPLIT; seg = seg + 1u) { let p = partials[seg * params.cols + col];{% if op == "max" or op == "min" %} total = {{ op }}(total, p);{% elif op == "prod" %} total = total * p;{% else %} total = total + p;{% endif %} }{% if op == "l2" %} y[col] = {{ yv }}sqrt(total){{ vy }};{% elif op == "logsum" %} y[col] = {{ yv }}log_of_sum(total){{ vy }};{% elif op == "mean" %} y[col] = {{ yv }}total / f32(params.rows){{ vy }};{% else %}{% if outputF16 %} y[col] = f16(total);{% else %} y[col] = total;{% endif %}{% endif %}{% endif %} }}400 unmodified lines40140240340440440540640740840941041041141241318 unmodified lines43243343443543543643743837 unmodified lines47647747847947948048148218 unmodified lines50150250350450450550650718 unmodified lines52652752852952953053153218 unmodified lines55155255355455455555655718 unmodified lines57657757857957958058158218 unmodified lines60160260360460460560660718 unmodified lines62662762862962963063163218 unmodified lines65165265365465465565665718 unmodified lines67667767867967968068168218 unmodified lines70170270370470470570670718 unmodified lines72672772872972973073173218 unmodified lines75175275375475475575675718 unmodified lines77677777877977978078178218 unmodified lines80180280380480480580680718 unmodified lines82682782882982983083183218 unmodified lines85185285385485485585685718 unmodified lines87687787887987988088188218 unmodified lines90190290390490490590690718 unmodified lines92692792892992993093193218 unmodified lines95195295395495495595695718 unmodified lines97697797897997998098198218 unmodified lines1001100210031004100410051006100718 unmodified lines1026102710281029102910301031103218 unmodified lines1051105210531054105410551056105718 unmodified lines1076107710781079107910801081108218 unmodified lines1101110211031104110411051106110718 unmodified lines1126112711281129112911301131113218 unmodified lines1151115211531154115411551156115718 unmodified lines1176117711781179117911801181118219 unmodified lines1202120312041205120512061207120819 unmodified lines1228122912301231123112321233123419 unmodified lines1254125512561257125712581259126019 unmodified lines1280128112821283128312841285128619 unmodified lines1306130713081309130913101311131219 unmodified lines1332133313341335133513361337133819 unmodified lines1358135913601361136113621363136419 unmodified lines1384138513861387138713881389139019 unmodified lines1410141114121413141314141415141619 unmodified lines1436143714381439143914401441144219 unmodified lines1462146314641465146514661467146819 unmodified lines1488148914901491149114921493149419 unmodified lines1514151515161517151715181519152019 unmodified lines1540154115421543154315441545154619 unmodified lines1566156715681569156915701571157219 unmodified lines1592159315941595159515961597159818 unmodified lines1617161816191620162016211622162318 unmodified lines1642164316441645164516461647164818 unmodified lines1667166816691670167016711672167318 unmodified lines1692169316941695169516961697169819 unmodified lines1718171917201721172117221723172419 unmodified lines1744174517461747174717481749175018 unmodified lines1769177017711772177217731774177518 unmodified lines1794179517961797179717981799180018 unmodified lines1819182018211822182218231824182518 unmodified lines1844184518461847184718481849185018 unmodified lines18691870187118721872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148400 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [32, 32], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "The other f16 fixtures all run K <= 64, where an f16 accumulator is indistinguishable from an f32 one. This one accumulates over K=512 so the tiled path's f32 accumulation is actually pinned." "notes": "Float16 activations and absmax values over a K=512 reduction (M=32, N=32, block_size=64, NF4 weights)." } }, { "name": "nf4_sgmat_widened_f16", "provenance": { "notes": "A float16 request on an aligned subgroup-matrix shape widens activations to float32 around the multiply, accumulates in float32, and narrows the result afterward." "notes": "Float16 activations with M=128, K=64 and N=64 (block_size=32, NF4 weights); all three dimensions are multiples of 32." }, "attrs": { "K": 64, "N": 64, "block_size": 32, "quant_type": 1 }, "inputs": {18 unmodified lines { "name": "nf4_tiled_speculative_band_m5", "provenance": { "notes": "A five-row speculative-decoder multiply exercises the tiled route within the 2-to-15-row band, using a ragged K dimension and NF4 block-quantized weights." "notes": "A five-row multiply (M=5, as in a speculative-decoding verification batch) with K=33, which is not a multiple of the 16-wide quantization block, N=19 and NF4 weights." }, "attrs": { "K": 33, "N": 19, "block_size": 16, "quant_type": 1 }, "inputs": {37 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [2, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=2, K=64, N=64, block_size=16 with float32 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [3, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=3, K=128, N=128, block_size=32 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [7, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=7, K=512, N=64, block_size=64 with float32 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [8, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=8, K=64, N=128, block_size=16 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [9, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=9, K=128, N=64, block_size=32 with float32 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [15, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=512, N=128, block_size=64 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [16, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=16, K=64, N=64, block_size=16 with float32 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [17, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=17, K=128, N=128, block_size=32 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [24, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=24, K=512, N=64, block_size=64 with float32 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [31, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=31, K=64, N=128, block_size=16 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [33, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=33, K=128, N=64, block_size=32 with float32 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [63, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=63, K=512, N=128, block_size=64 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [65, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=65, K=64, N=64, block_size=16 with float32 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [129, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=129, K=128, N=128, block_size=32 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [2, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=2, K=64, N=64, block_size=16 with float16 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [3, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=3, K=128, N=128, block_size=32 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [7, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=7, K=512, N=64, block_size=64 with float16 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [8, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=8, K=64, N=128, block_size=16 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [9, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=9, K=128, N=64, block_size=32 with float16 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [15, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=512, N=128, block_size=64 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [16, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=16, K=64, N=64, block_size=16 with float16 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [17, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=17, K=128, N=128, block_size=32 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [24, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=24, K=512, N=64, block_size=64 with float16 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [31, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=31, K=64, N=128, block_size=16 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [33, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=33, K=128, N=64, block_size=32 with float16 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [63, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=63, K=512, N=128, block_size=64 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [65, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=65, K=64, N=64, block_size=16 with float16 activations and FP4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [129, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=129, K=128, N=128, block_size=32 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [15, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=192, N=64, block_size=16 with float32 activations and FP4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 32, "SGMAT_TILE_K": 8 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [128, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=128, K=192, N=64, block_size=16 with float32 activations and FP4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 32, "SGMAT_TILE_K": 8 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [15, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=192, N=128, block_size=16 with float16 activations and NF4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 64, "SGMAT_TILE_K": 16 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [128, 128], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=128, K=192, N=128, block_size=16 with float16 activations and NF4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 64, "SGMAT_TILE_K": 16 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [15, 192], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=192, N=192, block_size=16 with float32 activations and FP4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 96, "SGMAT_TILE_K": 24 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [128, 192], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=128, K=192, N=192, block_size=16 with float32 activations and FP4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 96, "SGMAT_TILE_K": 24 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [15, 256], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=192, N=256, block_size=16 with float16 activations and NF4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 128, "SGMAT_TILE_K": 64 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [128, 256], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=128, K=192, N=256, block_size=16 with float16 activations and NF4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 128, "SGMAT_TILE_K": 64 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [15, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=192, N=64, block_size=16 with float32 activations and FP4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 32, "SGMAT_TILE_K": 64 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [128, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=128, K=192, N=64, block_size=16 with float32 activations and FP4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 32, "SGMAT_TILE_K": 64 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [15, 256], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=192, N=256, block_size=16 with float16 activations and NF4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 128, "SGMAT_TILE_K": 8 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [128, 256], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=128, K=192, N=256, block_size=16 with float16 activations and NF4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 128, "SGMAT_TILE_K": 8 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [15, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=192, N=128, block_size=16 with float32 activations and FP4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 64, "SGMAT_TILE_K": 24 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [128, 128], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=128, K=192, N=128, block_size=16 with float32 activations and FP4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 64, "SGMAT_TILE_K": 24 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [15, 192], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=15, K=192, N=192, block_size=16 with float16 activations and NF4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 96, "SGMAT_TILE_K": 16 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [128, 192], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=128, K=192, N=192, block_size=16 with float16 activations and NF4 weights whose codes vary by position." }, "tunables": { "SGMAT_TILE_COLS": 96, "SGMAT_TILE_K": 16 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [9, 65], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=9, K=31, N=65, block_size=16 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [33, 127], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=33, K=129, N=127, block_size=16 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [9, 65], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=9, K=31, N=65, block_size=16 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [33, 127], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=33, K=129, N=127, block_size=16 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [17, 65], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=17, K=129, N=65, block_size=16 with float16 activations and FP4 weights whose codes vary by position." }, "tunables": { "PORTABLE_TILE_K": 32 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [17, 65], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=17, K=129, N=65, block_size=16 with float16 activations and FP4 weights whose codes vary by position." }, "tunables": { "PORTABLE_TILE_K": 64 } },19 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [0, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=0, K=32, N=64, block_size=16 with float32 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [0, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "Covers row-tile boundaries, f32 accumulation and position-varying NF4/FP4 weights on matrix and portable capability tiers." "notes": "M=0, K=32, N=64, block_size=16 with float16 activations and NF4 weights whose codes vary by position." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [95, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "The full-row prefix and a multi-fragment tail write disjoint rows, including the last output, with f32 accumulation." "notes": "M=95 (1 x 64 + 31) float32 rows against FP4 weights (K=64, N=64, block_size=16): the rows after the whole 64-row blocks form a tail, and the last output row must be written." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float32", "shape": [191, 64], "tolerance": 0.00002, "relTolerance": 0.00001 } }, "provenance": { "notes": "The full-row prefix and a multi-fragment tail write disjoint rows, including the last output, with f32 accumulation." "notes": "M=191 (2 x 64 + 63) float32 rows against FP4 weights (K=64, N=64, block_size=16): the rows after the whole 64-row blocks form a tail, and the last output row must be written." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [95, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "The full-row prefix and a multi-fragment tail write disjoint rows, including the last output, with f32 accumulation." "notes": "M=95 (1 x 64 + 31) float16 rows against FP4 weights (K=64, N=64, block_size=16): the rows after the whole 64-row blocks form a tail, and the last output row must be written." } }, {18 unmodified lines }, "outputs": { "yT": { "dtype": "float16", "shape": [191, 64], "tolerance": 0.001, "relTolerance": 0.001 } }, "provenance": { "notes": "The full-row prefix and a multi-fragment tail write disjoint rows, including the last output, with f32 accumulation." "notes": "M=191 (2 x 64 + 63) float16 rows against FP4 weights (K=64, N=64, block_size=16): the rows after the whole 64-row blocks form a tail, and the last output row must be written." } }, { "name": "row_groups_float32_q0_m5_k65_n67", "attrs": { "K": 65, "N": 67, "block_size": 16, "quant_type": 0 }, "inputs": { "aT": { "dtype": "float32", "shape": [5, 65], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2178], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float32", "shape": [273], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float32", "shape": [5, 67], "tolerance": 0.00001 } } }, { "name": "row_groups_float32_q1_m7_k67_n69", "attrs": { "K": 67, "N": 69, "block_size": 16, "quant_type": 1 }, "inputs": { "aT": { "dtype": "float32", "shape": [7, 67], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2312], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float32", "shape": [289], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float32", "shape": [7, 69], "tolerance": 0.00001 } } }, { "name": "row_groups_float32_q0_m8_k68_n67", "attrs": { "K": 68, "N": 67, "block_size": 16, "quant_type": 0 }, "inputs": { "aT": { "dtype": "float32", "shape": [8, 68], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2278], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float32", "shape": [285], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float32", "shape": [8, 67], "tolerance": 0.00001 } } }, { "name": "row_groups_float32_q1_m4_k64_n64", "attrs": { "K": 64, "N": 64, "block_size": 16, "quant_type": 1 }, "inputs": { "aT": { "dtype": "float32", "shape": [4, 64], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2048], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float32", "shape": [256], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float32", "shape": [4, 64], "tolerance": 0.00001 } } }, { "name": "row_groups_float16_q0_m5_k65_n67", "attrs": { "K": 65, "N": 67, "block_size": 16, "quant_type": 0 }, "inputs": { "aT": { "dtype": "float16", "shape": [5, 65], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2178], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float16", "shape": [273], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float16", "shape": [5, 67], "tolerance": 0.01 } } }, { "name": "row_groups_float16_q1_m7_k67_n69", "attrs": { "K": 67, "N": 69, "block_size": 16, "quant_type": 1 }, "inputs": { "aT": { "dtype": "float16", "shape": [7, 67], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2312], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float16", "shape": [289], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float16", "shape": [7, 69], "tolerance": 0.01 } } }, { "name": "row_groups_float16_q0_m8_k68_n67", "attrs": { "K": 68, "N": 67, "block_size": 16, "quant_type": 0 }, "inputs": { "aT": { "dtype": "float16", "shape": [8, 68], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2278], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float16", "shape": [285], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float16", "shape": [8, 67], "tolerance": 0.01 } } }, { "name": "row_groups_float16_q1_m4_k64_n64", "attrs": { "K": 64, "N": 64, "block_size": 16, "quant_type": 1 }, "inputs": { "aT": { "dtype": "float16", "shape": [4, 64], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2048], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float16", "shape": [256], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float16", "shape": [4, 64], "tolerance": 0.01 } } }, { "name": "row_groups_float32_odd_workgroup", "attrs": { "K": 65, "N": 67, "block_size": 16, "quant_type": 0 }, "inputs": { "aT": { "dtype": "float32", "shape": [5, 65], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2178], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float32", "shape": [273], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float32", "shape": [5, 67], "tolerance": 0.00001 } }, "tunables": { "WORKGROUP_SIZE": 31 } }, { "name": "row_groups_float16_odd_workgroup", "attrs": { "K": 65, "N": 67, "block_size": 16, "quant_type": 0 }, "inputs": { "aT": { "dtype": "float16", "shape": [5, 65], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [2178], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float16", "shape": [273], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float16", "shape": [5, 67], "tolerance": 0.01 } }, "tunables": { "WORKGROUP_SIZE": 31 } }, { "name": "nf4_f16_packed_tails_m77_k256_n72_b64", "provenance": { "notes": "NF4 codes over 64-wide absmax blocks with half activations: M=77 and N=72 leave a 13-row tail and an 8-column tail past 64, and nothing beyond row 77 or column 72 may leak into the stored output." }, "attrs": { "K": 256, "N": 72, "block_size": 64, "quant_type": 1 }, "inputs": { "aT": { "dtype": "float16", "shape": [77, 256], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [9216], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float16", "shape": [288], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float16", "shape": [77, 72], "tolerance": 0.001, "relTolerance": 0.001 } } }, { "name": "fp4_f16_packed_m130_k512_n200_b128", "provenance": { "notes": "Sign-magnitude FP4 codes over 128-wide absmax blocks with half activations, K=512: M=130 leaves a two-row tail past 128 and N=200 leaves eight columns past 192." }, "attrs": { "K": 512, "N": 200, "block_size": 128, "quant_type": 0 }, "inputs": { "aT": { "dtype": "float16", "shape": [130, 512], "data": { "kind": "fillFloat32", "sinStep": 0.17, "cosStep": 0.31 } }, "bT": { "dtype": "uint8", "shape": [51200], "data": { "kind": "cycle", "values": { "$ref": "#/fixtureArrays/bnb4_weight_cycle_b_t" } } }, "absmaxT": { "dtype": "float16", "shape": [800], "data": { "kind": "fillFloat32", "sinStep": 0.11, "cosStep": 0.07, "scale": 0.02, "offset": 0.06 } } }, "outputs": { "yT": { "dtype": "float16", "shape": [130, 200], "tolerance": 0.001, "relTolerance": 0.001 } } } ]}README.md+44-17
build/webgpu/bench.json+30-2
build/webgpu/cast-scalar-x4.wgsl.jinja+18-1
build/webgpu/manifest.json+1-406
build/webgpu/matmul-bnb4-gemv-words.wgsl.jinjaAdded+90
build/webgpu/matmul-bnb4-gemv.wgsl.jinja+133-13
build/webgpu/matmul-bnb4-native16-packed.wgsl.jinjaAdded+331
build/webgpu/matmul-bnb4-sgmat.wgsl.jinja+122-45
build/webgpu/matmul-bnb4-tiled-reg.wgsl.jinjaAdded+132
build/webgpu/matmul-bnb4-tiled.wgsl.jinja+19-12
build/webgpu/matmul-bnb4.wgsl.jinja+15-7
build/webgpu/metadata.json+1-34
build/webgpu/reduce-axis0-splitk-combine.wgsl.jinjaAdded+109
build/webgpu/test.json+331-59