sync 4385228f788d
Browse filesFiles changed (12)
- README.md+30-15
- build/webgpu/bench.json+441
- build/webgpu/fusedgemm-native16-packed-register.wgsl.jinjaAdded+360
- build/webgpu/gemm-epilogue-tiled-reg.wgsl.jinja+14-5
- build/webgpu/gemm-subgroup-matrix.wgsl.jinja+171-46
- build/webgpu/gemv-contiguous.wgsl.jinja+61-11
- build/webgpu/manifest.json+1-311
- build/webgpu/matmul-notrans-vec4-tiled-reg.wgsl.jinjaAdded+351
- build/webgpu/matrix-shaped-projection-gemm.wgsl.jinjaAdded+243
- build/webgpu/metadata.json+1-30
- build/webgpu/reduce-axis0-splitk-combine.wgsl.jinjaAdded+197
- build/webgpu/test.json
11 unmodified lines1213141516171819202132 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969711 unmodified lines## DescriptionGemm with a fused activation: `Y = act(alpha * A' * B' + beta * C)`, where `A'` and `B'` are optionally transposed and `C` is broadcastable to `(M, N)`. The activation runs in the f32 accumulator before the single output narrowing. This package supports `Relu`, `LeakyRelu`, `Sigmoid`, `Tanh` and `HardSigmoid`; the other activation strings and numeric types admitted by the open schema are not implemented. Omitting `activation` gives plain Gemm.See the [ONNX Runtime `FusedGemm` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.FusedGemm) for the reference semantics.## Inputs| Name | Logical dtype | Rank | Shape | Description | Presence |32 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `gemv_plain` — Reduces contiguous weight rows for a single output row in f32, applies alpha and activation, and casts once. Four aligned columns share the input vector; other widths use one column. The reduction width is bounded by K and device workgroup limits. Either storage orientation of A is supported.- `gemv_bias` — Reduces contiguous weight rows for a single output row in f32, applies alpha, broadcast beta-scaled bias and activation, and casts once. Four aligned columns share the input vector; other widths use one column. The reduction width is bounded by K and device workgroup limits. Either storage orientation of A is supported.- `sgmat_bias` — Uses supported subgroup matrices with f32 accumulation and a fused epilogue. Complete non-transposed f32 A tiles load directly from storage; long reductions on that path merge two-tile sums with f32 compensation. Staged A clamps row tails. Workgroup memory is checked against device limits.- `sgmat` — Uses supported subgroup matrices with f32 accumulation and a fused epilogue. Complete non-transposed f32 A tiles load directly from storage; long reductions on that path merge two-tile sums with f32 compensation. Staged A clamps row tails. Workgroup memory is checked against device limits.## Device requirementsSome implementation variants require `subgroup-matrix` and `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.## Files- [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)- [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](build/webgpu/test.json) — correctness cases- [`bench.json`](build/webgpu/bench.json) — benchmark cases- [`gemm-epilogue-tiled-reg.wgsl.jinja`](build/webgpu/gemm-epilogue-tiled-reg.wgsl.jinja)- [`gemm-subgroup-matrix.wgsl.jinja`](build/webgpu/gemm-subgroup-matrix.wgsl.jinja)- [`gemv-contiguous.wgsl.jinja`](build/webgpu/gemv-contiguous.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.3```Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.Replace each `*Data` placeholder with a typed array containing the corresponding input data.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.FusedGemm", { version: 1 });const { Y } = await kernel({A: { data: AData, shape: [32, 224] },B: { data: BData, shape: [224, 64] },});```11 unmodified lines121314151617181920212223242532 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211 unmodified lines## DescriptionGemm with a fused activation: `Y = act(alpha * A' * B' + beta * C)`, where `A'` and `B'` are optionally transposed and `C` is broadcastable to `(M, N)`. The activation runs in the f32 accumulator before the single output narrowing. This package supports `Relu`, `LeakyRelu`, `Sigmoid`, `Tanh` and `HardSigmoid`; the other activation strings and numeric types allowed by the open schema are not implemented. Omitting `activation` gives plain Gemm.See the [ONNX Runtime `FusedGemm` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.FusedGemm) for the reference semantics.## Differences from the ONNX Runtime spec- Attribute `activation_gamma`: The supported activation subset does not include Selu, the only upstream fused activation that consumes gamma.## Inputs| Name | Logical dtype | Rank | Shape | Description | Presence |32 unmodified linesOne 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`, `native16_packed_64x128` — Uses packed half operands and padded shared tiles with f32 accumulation. Product scaling, the optional broadcast bias and the optional activation execute before the single half output conversion.- `gemv` — Reduces a single output row in f32 and applies scaling, broadcast bias and activation before narrowing. Transposed weights stream contiguous rows. K-by-N f16 weights share input values across adjacent columns. Wide unaligned rows mask the final output group.- `sgmat` — Uses supported subgroup matrices with f32 accumulation and a fused epilogue. Complete non-transposed f32 A tiles load directly from storage; long reductions on that path merge two-tile sums with f32 compensation. Staged A clamps row tails. Workgroup memory is checked against device limits.- `vec4_tiled` — Float32 128x64 or 64x64 register tiles with four-wide operand loads for every transpose combination; a transposed operand is staged through a 4x4 register transpose. Alpha, the optional broadcast beta-scaled bias and the activation run on the f32 result before the store.- `vec4_splitk` — Cuts K of the float32 four-wide register tile into power-of-two slices across dispatch.z when its output tiles alone cannot fill the device. Each slice writes alpha-scaled f32 partials; a second pass sums them in slice order, adds the optional broadcast beta-scaled bias and applies the activation before the single store.- `subgroup_matrix_16x16x16`, `subgroup_matrix_16x16x16_m_bias` — Experimental `16x16x16` half-precision subgroup matrices with `f32` accumulation. The `alpha` scale, any `beta`-scaled bias and the fused activation are applied in `f32` before the output cast. The matrix path runs only when the workgroup's subgroups are complete and of the expected width; otherwise the kernel computes every output element without them.## Device requirementsSome implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.## Files- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/test.json) — correctness cases- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/bench.json) — benchmark cases- [`fusedgemm-native16-packed-register.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/fusedgemm-native16-packed-register.wgsl.jinja)- [`gemm-epilogue-tiled-reg.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/gemm-epilogue-tiled-reg.wgsl.jinja)- [`gemm-subgroup-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/gemm-subgroup-matrix.wgsl.jinja)- [`gemv-contiguous.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/gemv-contiguous.wgsl.jinja)- [`matmul-notrans-vec4-tiled-reg.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/matmul-notrans-vec4-tiled-reg.wgsl.jinja)- [`matrix-shaped-projection-gemm.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/matrix-shaped-projection-gemm.wgsl.jinja)- [`reduce-axis0-splitk-combine.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedGemm/blob/v1/build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.4```Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.FusedGemm", { version: 1 });const AData = Float32Array.from({ length: 7168 }, (_, i) => Math.sin((i + 1) * 0.017) * 0.2 + Math.cos((i + 3) * 0.037) * (0.2 * 0.67));const BData = Float32Array.from({ length: 14336 }, (_, i) => Math.sin((i + 1) * 0.029) * 0.2 + Math.cos((i + 3) * 0.043) * (0.2 * 0.67));const { Y } = await kernel({A: { data: AData, shape: [32, 224] },B: { data: BData, shape: [224, 64] },});console.log({ Y });```
205 unmodified lines206207208209210211234 unmodified lines446447448449450451205 unmodified lines"notes": "Single-row fused projection spanning reduction length, output width, weight orientation and activation, with f32 accumulation and f16 output."}},{"name": "gemv-float32-k128-n4096-ta0-none-plain","preset": "model",234 unmodified lines},"outputs": { "Y": { "shape": [64, 128], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "16777216" }] }}]}205 unmodified lines206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427234 unmodified lines662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892205 unmodified lines"notes": "Single-row fused projection spanning reduction length, output width, weight orientation and activation, with f32 accumulation and f16 output."}},{"name": "gemv-f16-stored-k1024-n65-ta0","preset": "stress","vars": { "M": 1, "K": 1024, "N": 65, "dtype": "float16" },"attrs": { "transB": 0, "activation": "Relu", "transA": 0 },"inputs": {"A": { "shape": [1, 1024], "dtype": "float16", "dist": "normal", "seed": 5350, "scale": 1 },"B": { "shape": [1024, 65], "dtype": "float16", "dist": "normal", "seed": 5351, "scale": 1 },"C": { "shape": [65], "dtype": "float16", "dist": "normal", "seed": 5352, "scale": 1 }},"outputs": { "Y": { "shape": [1, 65], "dtype": "float16" } },"bench": {"metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" },{"type": "bandwidth","name": "logical input/output bytes","value": "dtypeBytes(args.dtype) * (numel(shapes.A) + numel(shapes.B) + numel(shapes.Y) + numel(shapes.C))","provenance": "logical"}]},"provenance": {"source": "synthetic benchmark","notes": "Single-row projection with K-by-N weights, output-channel bias and a fused rectifier."}},{"name": "gemv-f16-stored-k1023-n260-ta1","preset": "stress","vars": { "M": 1, "K": 1023, "N": 260, "dtype": "float16" },"attrs": { "transB": 0, "activation": "Relu", "transA": 1 },"inputs": {"A": { "shape": [1023, 1], "dtype": "float16", "dist": "normal", "seed": 5350, "scale": 1 },"B": { "shape": [1023, 260], "dtype": "float16", "dist": "normal", "seed": 5351, "scale": 1 },"C": { "shape": [260], "dtype": "float16", "dist": "normal", "seed": 5352, "scale": 1 }},"outputs": { "Y": { "shape": [1, 260], "dtype": "float16" } },"bench": {"metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" },{"type": "bandwidth","name": "logical input/output bytes","value": "dtypeBytes(args.dtype) * (numel(shapes.A) + numel(shapes.B) + numel(shapes.Y) + numel(shapes.C))","provenance": "logical"}]},"provenance": {"source": "synthetic benchmark","notes": "Single-row projection with K-by-N weights, output-channel bias and a fused rectifier."}},{"name": "gemv-f16-stored-k511-n1024-ta0","preset": "stress","vars": { "M": 1, "K": 511, "N": 1024, "dtype": "float16" },"attrs": { "transB": 0, "activation": "Relu", "transA": 0 },"inputs": {"A": { "shape": [1, 511], "dtype": "float16", "dist": "normal", "seed": 5350, "scale": 1 },"B": { "shape": [511, 1024], "dtype": "float16", "dist": "normal", "seed": 5351, "scale": 1 },"C": { "shape": [1024], "dtype": "float16", "dist": "normal", "seed": 5352, "scale": 1 }},"outputs": { "Y": { "shape": [1, 1024], "dtype": "float16" } },"bench": {"metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" },{"type": "bandwidth","name": "logical input/output bytes","value": "dtypeBytes(args.dtype) * (numel(shapes.A) + numel(shapes.B) + numel(shapes.Y) + numel(shapes.C))","provenance": "logical"}]},"provenance": {"source": "synthetic benchmark","notes": "Single-row projection with K-by-N weights, output-channel bias and a fused rectifier."}},{"name": "gemv-f16-stored-k1024-n1025-ta0","preset": "stress","vars": { "M": 1, "K": 1024, "N": 1025, "dtype": "float16" },"attrs": { "transB": 0, "activation": "Relu", "transA": 0 },"inputs": {"A": { "shape": [1, 1024], "dtype": "float16", "dist": "normal", "seed": 5350, "scale": 1 },"B": { "shape": [1024, 1025], "dtype": "float16", "dist": "normal", "seed": 5351, "scale": 1 },"C": { "shape": [1025], "dtype": "float16", "dist": "normal", "seed": 5352, "scale": 1 }},"outputs": { "Y": { "shape": [1, 1025], "dtype": "float16" } },"bench": {"metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" },{"type": "bandwidth","name": "logical input/output bytes","value": "dtypeBytes(args.dtype) * (numel(shapes.A) + numel(shapes.B) + numel(shapes.Y) + numel(shapes.C))","provenance": "logical"}]},"provenance": {"source": "synthetic benchmark","notes": "Single-row projection with K-by-N weights, output-channel bias and a fused rectifier."}},{"name": "gemv-f16-stored-k768-n3072-ta0","preset": "stress","vars": { "M": 1, "K": 768, "N": 3072, "dtype": "float16" },"attrs": { "transB": 0, "activation": "Relu", "transA": 0 },"inputs": {"A": { "shape": [1, 768], "dtype": "float16", "dist": "normal", "seed": 5350, "scale": 1 },"B": { "shape": [768, 3072], "dtype": "float16", "dist": "normal", "seed": 5351, "scale": 1 },"C": { "shape": [3072], "dtype": "float16", "dist": "normal", "seed": 5352, "scale": 1 }},"outputs": { "Y": { "shape": [1, 3072], "dtype": "float16" } },"bench": {"metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" },{"type": "bandwidth","name": "logical input/output bytes","value": "dtypeBytes(args.dtype) * (numel(shapes.A) + numel(shapes.B) + numel(shapes.Y) + numel(shapes.C))","provenance": "logical"}]},"provenance": {"source": "synthetic benchmark","notes": "Single-row projection with K-by-N weights, output-channel bias and a fused rectifier."}},{"name": "gemv-f16-stored-k1536-n6144-ta0","preset": "stress","vars": { "M": 1, "K": 1536, "N": 6144, "dtype": "float16" },"attrs": { "transB": 0, "activation": "Relu", "transA": 0 },"inputs": {"A": { "shape": [1, 1536], "dtype": "float16", "dist": "normal", "seed": 5350, "scale": 1 },"B": { "shape": [1536, 6144], "dtype": "float16", "dist": "normal", "seed": 5351, "scale": 1 },"C": { "shape": [6144], "dtype": "float16", "dist": "normal", "seed": 5352, "scale": 1 }},"outputs": { "Y": { "shape": [1, 6144], "dtype": "float16" } },"bench": {"metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" },{"type": "bandwidth","name": "logical input/output bytes","value": "dtypeBytes(args.dtype) * (numel(shapes.A) + numel(shapes.B) + numel(shapes.Y) + numel(shapes.C))","provenance": "logical"}]},"provenance": {"source": "synthetic benchmark","notes": "Single-row projection with K-by-N weights, output-channel bias and a fused rectifier."}},{"name": "gemv-f16-stored-k4096-n4096-ta0","preset": "stress","vars": { "M": 1, "K": 4096, "N": 4096, "dtype": "float16" },"attrs": { "transB": 0, "activation": "Relu", "transA": 0 },"inputs": {"A": { "shape": [1, 4096], "dtype": "float16", "dist": "normal", "seed": 5350, "scale": 1 },"B": { "shape": [4096, 4096], "dtype": "float16", "dist": "normal", "seed": 5351, "scale": 1 },"C": { "shape": [4096], "dtype": "float16", "dist": "normal", "seed": 5352, "scale": 1 }},"outputs": { "Y": { "shape": [1, 4096], "dtype": "float16" } },"bench": {"metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" },{"type": "bandwidth","name": "logical input/output bytes","value": "dtypeBytes(args.dtype) * (numel(shapes.A) + numel(shapes.B) + numel(shapes.Y) + numel(shapes.C))","provenance": "logical"}]},"provenance": {"source": "synthetic benchmark","notes": "Single-row projection with K-by-N weights, output-channel bias and a fused rectifier."}},{"name": "gemv-f16-stored-k4096-n4097-ta0","preset": "stress","vars": { "M": 1, "K": 4096, "N": 4097, "dtype": "float16" },"attrs": { "transB": 0, "activation": "Relu", "transA": 0 },"inputs": {"A": { "shape": [1, 4096], "dtype": "float16", "dist": "normal", "seed": 5350, "scale": 1 },"B": { "shape": [4096, 4097], "dtype": "float16", "dist": "normal", "seed": 5351, "scale": 1 },"C": { "shape": [4097], "dtype": "float16", "dist": "normal", "seed": 5352, "scale": 1 }},"outputs": { "Y": { "shape": [1, 4097], "dtype": "float16" } },"bench": {"metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" },{"type": "bandwidth","name": "logical input/output bytes","value": "dtypeBytes(args.dtype) * (numel(shapes.A) + numel(shapes.B) + numel(shapes.Y) + numel(shapes.C))","provenance": "logical"}]},"provenance": {"source": "synthetic benchmark","notes": "Single-row projection with K-by-N weights, output-channel bias and a fused rectifier."}},{"name": "gemv-float32-k128-n4096-ta0-none-plain","preset": "model",234 unmodified lines},"outputs": { "Y": { "shape": [64, 128], "dtype": "float32" } },"bench": { "metrics": [{ "type": "gflops", "value": "16777216" }] }},{"name": "fusedgemm-f16-extra-m32-k4096-n4096-tb1-relu-row","preset": "model","vars": { "dtype": "float16", "M": 32, "K": 4096, "N": 4096 },"attrs": { "transA": 0, "transB": 1, "alpha": 1, "beta": 1, "activation": "Relu" },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Short prefill of a square hidden projection, with a conventional per-column bias."},"inputs": {"A": { "shape": [32, 4096], "dtype": "float16", "dist": "normal", "seed": 77000, "scale": 0.125 },"B": { "shape": [4096, 4096], "dtype": "float16", "dist": "normal", "seed": 77001, "scale": 0.125 },"C": { "shape": [4096], "dtype": "float16", "dist": "normal", "seed": 77002, "scale": 0.125 }},"outputs": { "Y": { "shape": [32, 4096], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m64-k4096-n11008-tb1-relu-row","preset": "model","vars": { "dtype": "float16", "M": 64, "K": 4096, "N": 11008 },"attrs": { "transA": 0, "transB": 1, "alpha": 1, "beta": 1, "activation": "Relu" },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Short prefill with transformer expansion geometry and a Relu activation."},"inputs": {"A": { "shape": [64, 4096], "dtype": "float16", "dist": "normal", "seed": 77003, "scale": 0.125 },"B": { "shape": [11008, 4096], "dtype": "float16", "dist": "normal", "seed": 77004, "scale": 0.125 },"C": { "shape": [11008], "dtype": "float16", "dist": "normal", "seed": 77005, "scale": 0.125 }},"outputs": { "Y": { "shape": [64, 11008], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m128-k11008-n4096-tb1-identity-none","preset": "model","vars": { "dtype": "float16", "M": 128, "K": 11008, "N": 4096 },"attrs": { "transA": 0, "transB": 1, "alpha": 1, "beta": 1 },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Deep reduction of a transformer contraction geometry, without an activation or bias."},"inputs": {"A": { "shape": [128, 11008], "dtype": "float16", "dist": "normal", "seed": 77006, "scale": 0.125 },"B": { "shape": [4096, 11008], "dtype": "float16", "dist": "normal", "seed": 77007, "scale": 0.125 }},"outputs": { "Y": { "shape": [128, 4096], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m512-k4096-n11008-tb0-relu-row","preset": "model","vars": { "dtype": "float16", "M": 512, "K": 4096, "N": 11008 },"attrs": { "transA": 0, "transB": 0, "alpha": 1, "beta": 1, "activation": "Relu" },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Longer prefill of the 4096-to-11008 expansion with untransposed weights."},"inputs": {"A": { "shape": [512, 4096], "dtype": "float16", "dist": "normal", "seed": 77009, "scale": 0.125 },"B": { "shape": [4096, 11008], "dtype": "float16", "dist": "normal", "seed": 77010, "scale": 0.125 },"C": { "shape": [11008], "dtype": "float16", "dist": "normal", "seed": 77011, "scale": 0.125 }},"outputs": { "Y": { "shape": [512, 11008], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m512-k11008-n4096-tb1-identity-none","preset": "model","vars": { "dtype": "float16", "M": 512, "K": 11008, "N": 4096 },"attrs": { "transA": 0, "transB": 1, "alpha": 1, "beta": 1 },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Longer prefill with a transposed-weight contraction and no bias or activation."},"inputs": {"A": { "shape": [512, 11008], "dtype": "float16", "dist": "normal", "seed": 77012, "scale": 0.125 },"B": { "shape": [4096, 11008], "dtype": "float16", "dist": "normal", "seed": 77013, "scale": 0.125 }},"outputs": { "Y": { "shape": [512, 4096], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m1536-k3072-n9216-tb0-relu-row","preset": "model","vars": { "dtype": "float16", "M": 1536, "K": 3072, "N": 9216 },"attrs": { "transA": 0, "transB": 0, "alpha": 1, "beta": 1, "activation": "Relu" },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Image-transformer-sized dense expansion (1536 rows, 3072 to 9216 features) with a length-N bias and Relu."},"inputs": {"A": { "shape": [1536, 3072], "dtype": "float16", "dist": "normal", "seed": 77015, "scale": 0.125 },"B": { "shape": [3072, 9216], "dtype": "float16", "dist": "normal", "seed": 77016, "scale": 0.125 },"C": { "shape": [9216], "dtype": "float16", "dist": "normal", "seed": 77017, "scale": 0.125 }},"outputs": { "Y": { "shape": [1536, 9216], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m256-k1024-n4096-tb0-leakyrelu-scalar","preset": "model","vars": { "dtype": "float16", "M": 256, "K": 1024, "N": 4096 },"attrs": {"transA": 0,"transB": 0,"alpha": 0.75,"beta": 0.25,"activation": "LeakyRelu","activation_alpha": 0.125},"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Dense expansion with a scalar additive term and nonunit coefficients."},"inputs": {"A": { "shape": [256, 1024], "dtype": "float16", "dist": "normal", "seed": 77018, "scale": 0.125 },"B": { "shape": [1024, 4096], "dtype": "float16", "dist": "normal", "seed": 77019, "scale": 0.125 },"C": { "shape": [], "dtype": "float16", "dist": "normal", "seed": 77020, "scale": 0.125 }},"outputs": { "Y": { "shape": [256, 4096], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m256-k4096-n1024-tb1-tanh-row","preset": "model","vars": { "dtype": "float16", "M": 256, "K": 4096, "N": 1024 },"attrs": { "transA": 0, "transB": 1, "alpha": 1, "beta": 1, "activation": "Tanh" },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Transposed-weight hidden projection with a Tanh activation."},"inputs": {"A": { "shape": [256, 4096], "dtype": "float16", "dist": "normal", "seed": 77021, "scale": 0.125 },"B": { "shape": [1024, 4096], "dtype": "float16", "dist": "normal", "seed": 77022, "scale": 0.125 },"C": { "shape": [1024], "dtype": "float16", "dist": "normal", "seed": 77023, "scale": 0.125 }},"outputs": { "Y": { "shape": [256, 1024], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m512-k2048-n2048-tb0-sigmoid-column","preset": "model","vars": { "dtype": "float16", "M": 512, "K": 2048, "N": 2048 },"attrs": { "transA": 0, "transB": 0, "alpha": 1, "beta": 1, "activation": "Sigmoid" },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Gate-shaped projection with a per-row additive term and Sigmoid activation."},"inputs": {"A": { "shape": [512, 2048], "dtype": "float16", "dist": "normal", "seed": 77024, "scale": 0.125 },"B": { "shape": [2048, 2048], "dtype": "float16", "dist": "normal", "seed": 77025, "scale": 0.125 },"C": { "shape": [512, 1], "dtype": "float16", "dist": "normal", "seed": 77026, "scale": 0.125 }},"outputs": { "Y": { "shape": [512, 2048], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-extra-m513-k1032-n2056-tb1-hardsigmoid-matrix","preset": "edge","vars": { "dtype": "float16", "M": 513, "K": 1032, "N": 2056 },"attrs": {"transA": 0,"transB": 1,"alpha": 0.75,"beta": -0.5,"activation": "HardSigmoid","activation_alpha": 0.125,"activation_beta": 0.375},"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Ragged stress shape (M=513, K=1032, N=2056) with matrix C; not a model geometry."},"inputs": {"A": { "shape": [513, 1032], "dtype": "float16", "dist": "normal", "seed": 77027, "scale": 0.125 },"B": { "shape": [2056, 1032], "dtype": "float16", "dist": "normal", "seed": 77028, "scale": 0.125 },"C": { "shape": [513, 2056], "dtype": "float16", "dist": "normal", "seed": 77029, "scale": 0.125 }},"outputs": { "Y": { "shape": [513, 2056], "dtype": "float16" } },"bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }},{"name": "fusedgemm-f16-relu-grid192-m1024-k768-n3072","preset": "model","vars": { "dtype": "float16" },"attrs": { "activation": "Relu" },"inputs": {"A": { "shape": [1024, 768], "dtype": "float16", "dist": "normal", "seed": 5330, "scale": 1 },"B": { "shape": [768, 3072], "dtype": "float16", "dist": "normal", "seed": 5331, "scale": 1 },"C": { "shape": [3072], "dtype": "float16", "dist": "normal", "seed": 5332, "scale": 1 }},"outputs": { "Y": { "shape": [1024, 3072], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * 1024 * 768 * 3072" }] }},{"name": "fusedgemm-f16-relu-grid128-m512-k1024-n4096","preset": "model","vars": { "dtype": "float16" },"attrs": { "activation": "Relu" },"inputs": {"A": { "shape": [512, 1024], "dtype": "float16", "dist": "normal", "seed": 5333, "scale": 1 },"B": { "shape": [1024, 4096], "dtype": "float16", "dist": "normal", "seed": 5334, "scale": 1 },"C": { "shape": [4096], "dtype": "float16", "dist": "normal", "seed": 5335, "scale": 1 }},"outputs": { "Y": { "shape": [512, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * 512 * 1024 * 4096" }] }},{"name": "fusedgemm-f16-extra-grid256-m1024-k4096-n4096-tb1-identity-none","preset": "model","vars": { "dtype": "float16", "M": 1024, "K": 4096, "N": 4096 },"attrs": { "transA": 0, "transB": 1, "alpha": 1, "beta": 1 },"provenance": {"source": "Seeded half-precision dense projection geometries.","notes": "Transposed-weight contraction with M=1024, K=4096 and N=4096 and no bias or activation."},"inputs": {"A": { "shape": [1024, 4096], "dtype": "float16", "dist": "normal", "seed": 77040, "scale": 0.125 },"B": { "shape": [4096, 4096], "dtype": "float16", "dist": "normal", "seed": 77041, "scale": 0.125 }},"outputs": { "Y": { "shape": [1024, 4096], "dtype": "float16" } },"bench": { "metrics": [{ "type": "gflops", "value": "2 * args.M * args.K * args.N" }] }}]}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360{% set RESULT_SCRATCH_WORDS = 256 %}{%- set PAIRED_SWIGLU = false -%}{%- set EPILOGUE = registerEpilogue | default("none") -%}{%- set TA = false -%}{%- set TB = registerTransposeB | default(false) -%}{%- set BIAS = registerBiasMode | default("none") -%}{%- set BM = registerTileM -%}{%- set BN = registerTileN -%}{%- set BK = registerTileK -%}{%- set PAD = registerSharedPad | default(0) -%}{%- set FR = (BM / 32) | int -%}{%- set FC = (BN / 32) | int -%}{%- set ACOLS = BM if TA else BK -%}{%- set AROWS = BK if TA else BM -%}{%- set ASTRIDE = ((ACOLS + PAD) / 8) | int -%}{%- set BSTRIDE = (((BK if TB else BN) + PAD) / 8) | int -%}{%- set AWORDS = ((AROWS * (ACOLS + PAD)) / 8) | int -%}{%- set BWORDS = (((BN if TB else BK) * ((BK if TB else BN) + PAD)) / 8) | int -%}{%- set ASIZE = max(AWORDS, RESULT_SCRATCH_WORDS) -%}{%- set OUT_SLOTS = ((BM * BN) / 8 / 128) | int -%}{%- set PREFETCH = registerPrefetch | default(false) -%}{%- set SPLIT_K = false -%}{%- macro coordinates(name) -%}{% if name == "a" %} let row = rowBase + flat / {{ (BK / 8) | int }}u; let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;{% elif TB %} let col = colBase + flat / {{ (BK / 8) | int }}u; let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;{% else %} let k = kBase + flat / {{ (BN / 8) | int }}u; let col = colBase + (flat % {{ (BN / 8) | int }}u) * 8u;{% endif %}{%- endmacro -%}{%- macro guard(name) -%}{%- if name == "a" -%}row < M && k + 7u < K{%- elif TB -%}col < N && k + 7u < K{%- else -%}k < K && col + 7u < N{%- endif -%}{%- endmacro -%}{%- macro address(name) -%}{%- if name == "a" -%}({{ "k * M + row" if TA else "row * K + k" }}) / 8u{%- else -%}({% if EPILOGUE == "prefill" %}params.weightOffset + {% endif %}{{ "col * K + k" if TB else "k * N + col" }}) / 8u{%- endif -%}{%- endmacro -%}{%- macro shared_index(name) -%}{%- set PAYLOAD = ((ACOLS if name == "a" else BK if TB else BN) / 8) | int -%}{%- set STRIDE = ASTRIDE if name == "a" else BSTRIDE -%}(flat / {{ PAYLOAD }}u) * {{ STRIDE }}u + flat % {{ PAYLOAD }}u{%- endmacro -%}{%- macro result(value, column) -%}f16({% if EPILOGUE == "activation" %}fused_act({% endif %}{% if EPILOGUE == "fp8" %}{{ value }}{% if BIAS == "row" %} + f32(bias[{{ column }}]){% endif %}{% elif EPILOGUE == "fastgelu" %}gelu_tanh({{ value }}{% if BIAS == "row" %} + f32(bias[{{ column }}]){% endif %}){% elif EPILOGUE == "gemm" or EPILOGUE == "activation" %}params.alpha * {{ value }}{% if BIAS != "none" %} + params.beta * f32(bias[{% if BIAS == "scalar" %}0u{% elif BIAS == "row" %}{{ column }}{% elif BIAS == "column" %}row{% else %}row * N + {{ column }}{% endif %}]){% endif %}{% else %}{{ value }}{% endif %}{% if EPILOGUE == "activation" %}){% endif %}){%- endmacro -%}{%- macro output_address() -%}({% if EPILOGUE == "prefill" %}row * params.outStride + params.dstColStart + col{% else %}row * N + col{% endif %}) / 8u{%- endmacro -%}{%- macro half_output_guard() -%}row < M && {{ "col + 7u < N" }}{%- endmacro -%}{%- macro store_half_result() -%}y[{{ output_address() }}] = {{ pack_result("values") }};{%- endmacro -%}{%- macro pack_result(source) -%}vec4<u32>({% for pair in range(4) %} bitcast<u32>(vec2<f16>({{ result(source ~ "[" ~ (pair * 2) ~ "]", "col + " ~ (pair * 2) ~ "u") }}, {{ result(source ~ "[" ~ (pair * 2 + 1) ~ "]", "col + " ~ (pair * 2 + 1) ~ "u") }})){{ "," if pair != 3 else "" }}{% endfor %} ){%- endmacro -%}{%- macro load_left_fragment(r, step) %} let left{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>( &tileA, subgroupRow * {{ ASTRIDE }}u + {{ r * 16 * ASTRIDE + (step / 8) | int }}u, {{ ASTRIDE }}u);{%- endmacro -%}{%- macro load_right_fragment(c, step) %}{% if TB %} 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);{%- else %} let right{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, row_major>( &tileB, subgroupCol / 8u + {{ step * BSTRIDE + c * 2 }}u, {{ BSTRIDE }}u);{%- endif %}{%- 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 EPILOGUE == "fastgelu" %}fn tanh_safe(x: f32) -> f32 { // tanh rounds to its saturated value for these tails in f32. Return that // value directly, including for infinite input, before invoking the builtin. if (x > 10.0) { return 1.0; } if (x < -10.0) { return -1.0; } // For tiny |x|, return x directly to preserve its sign and magnitude without // relying on backend-specific builtin behavior near zero. if (x > -1.0e-4 && x < 1.0e-4) { return x; } return tanh(x);}
fn gelu_tanh(v: f32) -> f32 { return 0.5 * v * (1.0 + tanh_safe(0.7978845608028654 * (v + 0.044715 * v * v * v)));}{% elif EPILOGUE == "activation" %}{% set actMode = gemmActivation | default("") %}{% set actA = gemmActAlpha | default(0.0) %}{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "" %} return v;{% elif mode == "Relu" %} let bits = bitcast<u32>(v); return bitcast<f32>(select(0u, bits, (bits & 0x80000000u) == 0u || (bits & 0x7fffffffu) > 0x7f800000u));{% elif mode == "Clip" %} return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %} return select(v * f32({{ alpha }}), v, v >= 0.0);{% elif mode == "Sigmoid" %} return 1.0 / (1.0 + exp(-v));{% elif mode == "Tanh" %} // tanh is already +/-1 to f32 precision at the clamp bounds. Clamping before // the builtin preserves that saturated result for larger accumulators. return tanh(clamp(v, -10.0, 10.0));{% elif mode == "HardSigmoid" %} return clamp(f32({{ alpha }}) * v + f32({{ beta }}), 0.0, 1.0);{% elif mode == "QuickGelu" %}{% if alpha == 1 %} // alpha == 1 is SiLU: the multiply folds away (the spelling yolov8-class detectors emit). return v * (1.0 / (1.0 + exp(-v)));{% else %} return v * (1.0 / (1.0 + exp(-(f32({{ alpha }}) * v))));{% endif %}{% elif mode == "Elu" %} return select(f32({{ alpha }}) * (exp(v) - 1.0), v, v >= 0.0);{% elif mode == "ThresholdedRelu" %} return select(0.0, v, v > f32({{ alpha }}));{% elif mode == "Softplus" %} // log(1 + exp(v)) spelled overflow-safe: max(v, 0) + log(1 + exp(-|v|)). return max(v, 0.0) + log(1.0 + exp(-abs(v)));{% elif mode == "Erf" %} // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7), the same polynomial the standalone // Erf/Gelu kernels use, so a fused and an unfused graph agree to f32 rounding. let a = abs(v); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return sign(v) * (1.0 - poly * exp(-a * a));{% elif mode == "Gelu" and alpha == 0 %} // ONNX Gelu, erf form: 0.5 * v * (1 + erf(v / sqrt(2))); activation_params[0] == 0. let u = v * 0.70710678118654752; let a = abs(u); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return 0.5 * v * (1.0 + sign(u) * (1.0 - poly * exp(-a * a)));{% elif mode == "Gelu" or mode == "FastGelu" %} // tanh approximation (ONNX Gelu approximate="tanh" arrives as activation_params[0] != 0; // com.microsoft.FastGelu always). tanh saturates to +/-1 well inside the clamp. let inner = v * (0.035677408136300125 * v * v + 0.7978845608028654); return v * (0.5 + 0.5 * tanh(clamp(inner, -10.0, 10.0)));{% else %} return v * clamp(v * 0.16666666666666666 + 0.5, 0.0, 1.0);{% endif %}}{% endmacro %}{{ fused_act_fn(actMode, actA, actB) }}{% endif %}{{ env.wgsl.resourceDeclarations }}const N: u32 = {{ N }}u;const K: u32 = {{ K }}u;const TILE_M: u32 = {{ BM }}u;const TILE_N: u32 = {{ BN }}u;const TILE_K: u32 = {{ BK }}u;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 ({{ guard(name) }}) { value = {{ name }}[{{ address(name) }}]; } 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 ({{ guard(name) }}) { values.{{ name }}[{{ slot }}] = {{ name }}[{{ address(name) }}]; } } }{% 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;}@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; 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() }} } } }}30 unmodified lines3132333435363738167 unmodified lines20620720820921021121221321421521621721821922022122222322430 unmodified lines{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "Relu" %}return max(v, 0.0);{% elif mode == "Clip" %}return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %}167 unmodified lines{% set regT = "f32" %}{% set regCast = 1 if tileT != "f32" else 0 %}{% filter indent(8, true) %}{% set regAccumulator = "acc" %}let aRow = lid.y * TM;let bCol = lid.x * TN;for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {var av: array<vec4<{{ regT }}>, TM>;var bv: array<vec4<{{ regT }}>, TN>;for (var i: u32 = 0u; i < TM; i = i + 1u) { av[i] = {% if regCast %}vec4<{{ regT }}>(tileA[aRow + i][kv]){% else %}tileA[aRow + i][kv]{% endif %}; }for (var j: u32 = 0u; j < TN; j = j + 1u) { bv[j] = {% if regCast %}vec4<{{ regT }}>(tileB[bCol + j][kv]){% else %}tileB[bCol + j][kv]{% endif %}; }for (var i: u32 = 0u; i < TM; i = i + 1u) {for (var j: u32 = 0u; j < TN; j = j + 1u) {{{ regAccumulator }}[i * TN + j] = {{ regAccumulator }}[i * TN + j] + dot(av[i], bv[j]);}}}{% endfilter %}workgroupBarrier();}30 unmodified lines3132333435363738394041167 unmodified lines20921021121221321421521621721821922022122222322422522622722822923023123223330 unmodified lines{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "" %}return v;{% elif mode == "Relu" %}let bits = bitcast<u32>(v);return bitcast<f32>(select(0u, bits, (bits & 0x80000000u) == 0u || (bits & 0x7fffffffu) > 0x7f800000u));{% elif mode == "Clip" %}return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %}167 unmodified lines{% set regT = "f32" %}{% set regCast = 1 if tileT != "f32" else 0 %}{% filter indent(8, true) %}{% set regAccumulator = "acc" %}{% set regColumnStride = 0 %}{% set regStaticK = 0 %}{% macro regKAddress(literalKv, scale=1, offset=0) %}{% if regStaticK %}{{ scale * literalKv + offset }}u{% else %}kv{% endif %}{% endmacro %}{% macro regARead(row, literalKv) %}{% set aK = regKAddress(literalKv) %}{% if regCast %}vec4<{{ regT }}>(tileA[{{ row }}][{{ aK }}]){% else %}tileA[{{ row }}][{{ aK }}]{% endif %}{% endmacro %}{% macro regBRead(column, literalKv) %}{% set bK = regKAddress(literalKv) %}{% set regBWord = ("tileB[" ~ bK ~ "][" ~ column ~ "]") if regColumnStride else ("tileB[" ~ column ~ "][" ~ bK ~ "]") %}{% if regCast %}vec4<{{ regT }}>({{ regBWord }}){% else %}{{ regBWord }}{% endif %}{% endmacro %}let aRow = lid.y * TM;let bCol = lid.x * TN;{% for literalKv in range(regStaticK // 4 if regStaticK else 1) %}for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {var av: array<vec4<{{ regT }}>, TM>;var bv: array<vec4<{{ regT }}>, TN>;for (var i: u32 = 0u; i < TM; i = i + 1u) { av[i] = {{ regARead("aRow + i", literalKv) }}; }for (var j: u32 = 0u; j < TN; j = j + 1u) { bv[j] = {{ regBRead(("bCol + j * " ~ regColumnStride ~ "u") if regColumnStride else "bCol + j", literalKv) }}; }for (var i: u32 = 0u; i < TM; i = i + 1u) {for (var j: u32 = 0u; j < TN; j = j + 1u) {{{ regAccumulator }}[i * TN + j] = {{ regAccumulator }}[i * TN + j] + dot(av[i], bv[j]);}}}{% endfor %}{% endfilter %}workgroupBarrier();}
10 unmodified lines111213141516171819202122235 unmodified lines293031323334353637383940414243444546474849505152535455565758596015 unmodified lines767778798081828346 unmodified lines13013113213313413520 unmodified lines1561571581591601611628 unmodified lines17117217317417517617717817913 unmodified lines1931941951961971981995 unmodified lines2052062072082092102119 unmodified lines2212222232242252262271 unmodified line2292302312322332342352362372382392402412422432442452462471 unmodified line2492502512522532542552562572582592602612622632642652662672 unmodified lines2702712722732742752764 unmodified lines2812822832842852862872882892902912922932942952962974 unmodified lines3023033043053063073083093103113124 unmodified lines31731831932032132232332432532632732832933033133233333433533633733812 unmodified lines35135235335435535635710 unmodified lines36836937037137237337412 unmodified lines38738838939010 unmodified lines{% set accScalar = "f32" %}{% set SPLIT_K = 1 %}{% set OUT = "y" %}{% set OUT_SCALAR = outScalar if outScalar is defined else yScalar %}{% set tileMValue = tileM if tileM is defined else 32 %}{% set tileNValue = tileN if tileN is defined else 64 %}{% set tileKValue = tileK if tileK is defined else 32 %}{% set gemmEpi = gemmEpilogue if gemmEpilogue is defined else "none" %}{% set epiOpen = "gelu_tanh(" if gemmEpi == "fastgelu" else ("fused_act(" if gemmEpi == "activation" else "") %}{% set epiClose = ")" if gemmEpi != "none" else "" %}{% set useDirectStore = false %}{% set useDirectAStorage = directAStorage is defined and directAStorage %}{% set useDoubleBufferedB = false %}5 unmodified lines{% set columnTileBaseValue = 0 %}{% set rowTileBaseValue = 0 %}// Four subgroups cover 32xN as a 2x2 grid, or taller tiles as four row bands.{% if tileMValue > 32 %}{% set subtileCols = tileNValue %}{% set subtileRows = (tileMValue / 4)|int %}{% else %}{% set subtileCols = (tileNValue / 2)|int %}{% set subtileRows = 16 %}{% endif %}{% set aTilesPerSubgroup = (subtileRows / 8)|int %}{% set bTilesPerSubgroup = (subtileCols / 8)|int %}{% set subgroupCount = 4 %}{% set scratchBanks = subgroupCount * aTilesPerSubgroup * bTilesPerSubgroup %}{% macro matrixAccumulators() %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}var matC{{ m }}{{ n }}: subgroup_matrix_result<{{ accScalar }}, 8, 8>;{% endfor %}{% endfor %}{% endmacro %}{% macro storeMatrixAccumulators() %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}subgroupMatrixStore<row_major>(&scratch[bank + {{ m * bTilesPerSubgroup + n }}u], 0u, matC{{ m }}{{ n }}, 8u);{% endfor %}{% endfor %}{% endmacro %}{% if gemmEpi == "fastgelu" %}fn tanh_safe(x: f32) -> f32 {// tanh rounds to its saturated value for these tails in f32. Return that15 unmodified lines{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "Relu" %}return max(v, 0.0);{% elif mode == "Clip" %}return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %}46 unmodified lines{{ fused_act_fn(actMode, actA, actB) }}{% endif %}const IN_F: u32 = {{ inFeatures }}u;const OUT_F: u32 = {{ outFeatures }}u;{% set kLoopEndValue = "IN_F" %}const TILE_COLS: u32 = {{ tileNValue }}u;20 unmodified lineslet local_idx = row * {{ (tileKValue / 8)|int }}u + c_idx;let vectors_per_k = TILE_ROWS / 4u;let total_vectors = TILE_K * vectors_per_k;for (var vector_idx = local_idx; vector_idx < total_vectors; vector_idx += 128u) {let k_local = vector_idx / vectors_per_k;let m4 = (vector_idx - k_local * vectors_per_k) * 4u;for (var component = 0u; component < 4u; component++) {8 unmodified lines// it. Some subgroup-matrix implementations let a zero-padded left tile corrupt// the adjacent valid row. Replicating row M-1 avoids that boundary; the// replicated rows are discarded by storeOutput's row_limit guard, so every valid// output row stays bit-identical. M >= 1 is guaranteed by the when-clause args.M > 0.let col: u32 = c_idx * 8u;for (var row_offset: u32 = 0u; row_offset < TILE_ROWS; row_offset += {{ (1024 / tileKValue)|int }}u) {let r: u32 = row + row_offset;let a_global: u32 = min(tile_base + r, params.M - 1u);for (var col_offset: u32 = 0u; col_offset < 8u; col_offset++) {13 unmodified lineslet local_idx = row * {{ (tileKValue / 16)|int }}u + c_idx;let vectors_per_k = TILE_COLS / 4u;let total_vectors = TILE_K * vectors_per_k;for (var vector_idx = local_idx; vector_idx < total_vectors; vector_idx += 128u) {let k_local = vector_idx / vectors_per_k;let n4 = (vector_idx - k_local * vectors_per_k) * 4u;for (var component = 0u; component < 4u; component++) {5 unmodified lines}{% else %}let col: u32 = c_idx * 16u;for (var row_offset: u32 = 0u; row_offset < TILE_COLS; row_offset += {{ (2048 / tileKValue)|int }}u) {let b_row: u32 = row + row_offset;// Non-power-of-two tile widths (TILE_COLS 48/96) use only a prefix of lanes on the// final row band. Keep those inactive lanes out of tile_B and global memory.9 unmodified lines{% endif %}}{% set needsColBase = hasBias or (tailSafe is defined and tailSafe) %}{% set BIAS_1 = (" + " ~ accScalar ~ "(bias[col_base + col])") if hasBias else "" %}{% set BIAS_2 = (" + " ~ accScalar ~ "(bias[col_base + col2])") if hasBias else "" %}{% set ACC_1 = "scratch[src_slot][row * 8u + col]" %}1 unmodified linefn storeOutput(offset: u32{% if needsColBase %}, col_base: u32{% endif %}, row: u32, col: u32, src_slot: u32, row_limit: i32) {if (row_limit > 0 && row < u32(row_limit)) {let col2: u32 = col + 1u;{{ OUT }}[offset + row * OUT_F + col] = {{ OUT_SCALAR }}({{ epiOpen }}{{ ACC_1 }}{{ BIAS_1 }}{{ epiClose }});{{ OUT }}[offset + row * OUT_F + col2] = {{ OUT_SCALAR }}({{ epiOpen }}{{ ACC_2 }}{{ BIAS_2 }}{{ epiClose }});}}@compute @workgroup_size(128, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) workgroup_id: vec3<u32>,@builtin(num_workgroups) nwg: vec3<u32>,@builtin(local_invocation_index) local_idx: u32,@builtin(subgroup_invocation_id) sg_id: u32,@builtin(subgroup_size) sg_size: u32) {// 2D-folded M-tile (row) base: workgroup_id.z carries the high bits when the// row tile exceeds the per-dimension dispatch limit.// Reduces to workgroup_id.y when nwg.z == 1; the row_limit guard in storeOutput1 unmodified linelet a_global_base: u32 = (ROW_TILE_BASE + workgroup_id.y + workgroup_id.z * nwg.y) * TILE_ROWS;let w_global_base: u32 = (COLUMN_TILE_BASE + workgroup_id.x) * TILE_COLS;let subtile_id: u32 = local_idx / sg_size;{% if tileMValue > 32 %}let subtile_idx: u32 = 0u;let subtile_idy: u32 = subtile_id;{% else %}let subtile_idx: u32 = subtile_id / 2u;let subtile_idy: u32 = subtile_id % 2u;{% endif %}let base_A: u32 = subtile_idy * SUB_ROWS;let base_B: u32 = subtile_idx * SUB_COLS;{% if not useChunkedAccumulation %}{{ matrixAccumulators() }}{% endif %}{% if useChunkedAccumulation %}let row = sg_id / 4u;2 unmodified linesvar chunkSums: array<vec2<f32>, {{ aTilesPerSubgroup * bTilesPerSubgroup }}>;var chunkErrors: array<vec2<f32>, {{ aTilesPerSubgroup * bTilesPerSubgroup }}>;for (var chunk_base = 0u; chunk_base < IN_F; chunk_base += TILE_K * {{ matrixChunkTiles }}u) {{{ matrixAccumulators() }}for (var kidx = chunk_base; kidx < min(chunk_base + TILE_K * {{ matrixChunkTiles }}u, IN_F); kidx += TILE_K) {{% else %}for (var kidx: u32 = 0u; kidx < {{ kLoopEndValue }}; kidx += TILE_K) {4 unmodified linesloadSHMB(w_global_base, kidx, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, 0u);workgroupBarrier();for (var step: u32 = 0u; step < TILE_K; step += 8u) {{% set dynamicATiles = aTilesPerSubgroup if aTilesPerSubgroup is defined else 2 %}{% set matrixAccumulator = "matC" %}{% set matrixStep = "step" %}{% set aTransposed = aTransposedStorage if aTransposedStorage is defined else (matrixInputsTransposed is defined and matrixInputsTransposed) %}{% set bTransposed = bTransposedStorage if bTransposedStorage is defined else (matrixInputsTransposed is defined and matrixInputsTransposed) %}{% set directA = directAStorage is defined and directAStorage %}{% set B_BANK = "" %}{% if directA %}{% set matrixAStorage = "x" %}{% set matrixAStride = "IN_F" %}// Direct storage guarantees a full aligned M/K tile, so subgroup-matrix// loads need no guarded workgroup staging.let matrix_a_offset = (a_global_base + base_A) * {{ matrixAStride }} + kidx + {{ matrixStep }};4 unmodified lines{% endif %}{% for m in range(dynamicATiles) %}{% if directA %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&{{ matrixAStorage }}, matrix_a_offset{% if m > 0 %} + {{ m * 8 }}u * {{ matrixAStride }}{% endif %}, {{ matrixAStride }});{% elif aTransposed %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, col_major>(&tile_A, matrix_a_offset + {{ m * 8 }}u, TILE_ROWS);{% else %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&tile_A, matrix_a_offset{% if m > 0 %} + {{ m * 8 }}u * TILE_K{% endif %}, TILE_K);{% endif %}{% endfor %}4 unmodified lines{% endif %}{% for n in range(bTilesPerSubgroup) %}{% if bTransposed %}var matB{{ n }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, row_major>(&tile_B, matrix_b_offset + {{ n * 8 }}u, TILE_COLS);{% else %}var matB{{ n }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, col_major>(&tile_B, matrix_b_offset + {{ n * 8 }}u * TILE_K, TILE_K);{% endif %}{% endfor %}{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixAccumulator }}{{ m }}{{ n }} = subgroupMatrixMultiplyAccumulate(matA{{ m }}, matB{{ n }}, {{ matrixAccumulator }}{{ m }}{{ n }});{% endfor %}{% endfor %}}workgroupBarrier();}{% if useChunkedAccumulation %}{{ storeMatrixAccumulators() }}workgroupBarrier();{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}12 unmodified lines}{% endif %}let matrix_c_offset: u32 = (a_global_base + base_A) * OUT_F + w_global_base + base_B;{% if useChunkedAccumulation %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}10 unmodified lines// across lanes, so its cross-lane readback must be published before partial-M// guards diverge. The epilogue also handles output conversion and bias.let bank: u32 = subtile_id * {{ aTilesPerSubgroup * bTilesPerSubgroup }}u;{{ storeMatrixAccumulators() }}workgroupBarrier();{% endif %}12 unmodified lines);{% endfor %}{% endfor %}}10 unmodified lines1112131415161718192021222324255 unmodified lines3132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969715 unmodified lines11311411511611711811912012112212346 unmodified lines17017117217317417517617720 unmodified lines1981992002012022032048 unmodified lines21321421521621721821922022113 unmodified lines2352362372382392402415 unmodified lines2472482492502512522539 unmodified lines2632642652662672682691 unmodified line2712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503511 unmodified line3533543553563573583593603613623633643653663673683693703712 unmodified lines3743753763773783793804 unmodified lines3853863873883893903913923933943953963973983994004014024 unmodified lines4074084094104114124134144154164174 unmodified lines42242342442542642742842943043143243343443543643743843944044144244312 unmodified lines45645745845946046146210 unmodified lines47347447547647747847912 unmodified lines49249349449549649749849950050150250350450550650750850951051151251351451510 unmodified lines{% set accScalar = "f32" %}{% set SPLIT_K = 1 %}{% set OUT = "y" %}{% set OUT_SCALAR = yScalar %}{% set tileMValue = tileM if tileM is defined else 32 %}{% set tileNValue = tileN if tileN is defined else 64 %}{% set tileKValue = tileK if tileK is defined else 32 %}{% set gemmEpi = gemmEpilogue if gemmEpilogue is defined else "none" %}{% set epiOpen = "gelu_tanh(" if gemmEpi == "fastgelu" else ("fused_act(" if gemmEpi == "activation" else ("gelu_erf(" if gemmEpi == "erfgelu" else "")) %}{% set epiClose = ")" if gemmEpi != "none" else "" %}{% set packedNTail = false %}{% set packedKTail = false %}{% set useDirectStore = false %}{% set useDirectAStorage = directAStorage is defined and directAStorage %}{% set useDoubleBufferedB = false %}5 unmodified lines{% set columnTileBaseValue = 0 %}{% set rowTileBaseValue = 0 %}// Four subgroups cover 32xN as a 2x2 grid, or taller tiles as four row bands.{% if tileMValue == 16 %}{% set subgroupCount = 4 %}{% set subgroupRows = 1 %}{% set subgroupCols = 4 %}{% set subtileCols = (tileNValue / 4)|int %}{% set subtileRows = 16 %}{% elif tileMValue == 48 %}{% set subgroupCount = 4 %}{% set subgroupRows = 2 %}{% set subgroupCols = 2 %}{% set subtileCols = (tileNValue / 2)|int %}{% set subtileRows = 24 %}{% elif tileMValue > 32 %}{% set subgroupCount = 4 %}{% set subgroupRows = 4 %}{% set subgroupCols = 1 %}{% set subtileCols = tileNValue %}{% set subtileRows = (tileMValue / 4)|int %}{% else %}{% set subgroupCount = 4 %}{% set subgroupRows = 2 %}{% set subgroupCols = 2 %}{% set subtileCols = (tileNValue / 2)|int %}{% set subtileRows = 16 %}{% endif %}{% set aTilesPerSubgroup = (subtileRows / 8)|int %}{% set bTilesPerSubgroup = (subtileCols / 8)|int %}{% set workgroupThreads = 128 %}{% set scratchBanks = subgroupCount * aTilesPerSubgroup * bTilesPerSubgroup %}{% macro matrixAccumulators(matrixSoftware) %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}var matC{{ m }}{{ n }}: {{ matrixType(matrixSoftware, "result", accScalar) }};{% endfor %}{% endfor %}{% endmacro %}{% macro storeMatrixAccumulators(matrixSoftware) %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixStore(matrixSoftware, "row_major", "&scratch[bank + " ~ (m * bTilesPerSubgroup + n) ~ "u]", "0u", "matC" ~ (m) ~ (n), "8u") }}{% endfor %}{% endfor %}{% endmacro %}{% if gemmEpi == "erfgelu" %}fn erf_approx(x: f32) -> f32 {let ax = abs(x);// The polynomial has a small nonzero floor near zero. Use erf(x) ~=// 2/sqrt(pi)*x below 2^-20 to preserve erf(0) == 0, odd symmetry, and the// small-input linear behavior. The threshold is exactly representable in// f32. NaN falls through to the polynomial and propagates.if (ax < 9.5367431640625e-7) {return 1.1283791670955126 * x;}let sign = select(-1.0, 1.0, x >= 0.0);let t = 1.0 / (1.0 + 0.3275911 * ax);let y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-(ax * ax));return sign * y;}fn gelu_erf(v: f32) -> f32 { return 0.5 * v * (1.0 + erf_approx(v * 0.7071067811865476)); }{% endif %}{% if gemmEpi == "fastgelu" %}fn tanh_safe(x: f32) -> f32 {// tanh rounds to its saturated value for these tails in f32. Return that15 unmodified lines{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "" %}return v;{% elif mode == "Relu" %}let bits = bitcast<u32>(v);return bitcast<f32>(select(0u, bits, (bits & 0x80000000u) == 0u || (bits & 0x7fffffffu) > 0x7f800000u));{% elif mode == "Clip" %}return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %}46 unmodified lines{{ fused_act_fn(actMode, actA, actB) }}{% endif %}const IN_F: u32 = {{ inFeatures }}u;{% set useRegionStore = false %}{% set OUT_ROW = "OUT_F" %}const OUT_F: u32 = {{ outFeatures }}u;{% set kLoopEndValue = "IN_F" %}const TILE_COLS: u32 = {{ tileNValue }}u;20 unmodified lineslet local_idx = row * {{ (tileKValue / 8)|int }}u + c_idx;let vectors_per_k = TILE_ROWS / 4u;let total_vectors = TILE_K * vectors_per_k;for (var vector_idx = local_idx; vector_idx < total_vectors; vector_idx += {{ workgroupThreads }}u) {let k_local = vector_idx / vectors_per_k;let m4 = (vector_idx - k_local * vectors_per_k) * 4u;for (var component = 0u; component < 4u; component++) {8 unmodified lines// it. Some subgroup-matrix implementations let a zero-padded left tile corrupt// the adjacent valid row. Replicating row M-1 avoids that boundary; the// replicated rows are discarded by storeOutput's row_limit guard, so every valid// output row stays bit-identical. This assumes M >= 1.let col: u32 = c_idx * 8u;for (var row_offset: u32 = 0u; row_offset < TILE_ROWS; row_offset += {{ (workgroupThreads * 8 / tileKValue)|int }}u) {let r: u32 = row + row_offset;let a_global: u32 = min(tile_base + r, params.M - 1u);for (var col_offset: u32 = 0u; col_offset < 8u; col_offset++) {13 unmodified lineslet local_idx = row * {{ (tileKValue / 16)|int }}u + c_idx;let vectors_per_k = TILE_COLS / 4u;let total_vectors = TILE_K * vectors_per_k;for (var vector_idx = local_idx; vector_idx < total_vectors; vector_idx += {{ workgroupThreads }}u) {let k_local = vector_idx / vectors_per_k;let n4 = (vector_idx - k_local * vectors_per_k) * 4u;for (var component = 0u; component < 4u; component++) {5 unmodified lines}{% else %}let col: u32 = c_idx * 16u;for (var row_offset: u32 = 0u; row_offset < TILE_COLS; row_offset += {{ (workgroupThreads * 16 / tileKValue)|int }}u) {let b_row: u32 = row + row_offset;// Non-power-of-two tile widths (TILE_COLS 48/96) use only a prefix of lanes on the// final row band. Keep those inactive lanes out of tile_B and global memory.9 unmodified lines{% endif %}}{% set needsColBase = hasBias or (tailSafe is defined and tailSafe) or packedNTail %}{% set BIAS_1 = (" + " ~ accScalar ~ "(bias[col_base + col])") if hasBias else "" %}{% set BIAS_2 = (" + " ~ accScalar ~ "(bias[col_base + col2])") if hasBias else "" %}{% set ACC_1 = "scratch[src_slot][row * 8u + col]" %}1 unmodified linefn storeOutput(offset: u32{% if needsColBase %}, col_base: u32{% endif %}, row: u32, col: u32, src_slot: u32, row_limit: i32) {if (row_limit > 0 && row < u32(row_limit)) {let col2: u32 = col + 1u;{{ OUT }}[offset + row * OUT_F + col] = {{ OUT_SCALAR }}({{ epiOpen }}({{ ACC_1 }}{{ BIAS_1 }}){{ epiClose }});{{ OUT }}[offset + row * OUT_F + col2] = {{ OUT_SCALAR }}({{ epiOpen }}({{ ACC_2 }}{{ BIAS_2 }}){{ epiClose }});}}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {// WGSL initializes workgroup variables to zero before this entry point.let population = subgroupBallot(true);let populationCount = countOneBits(population.x) + countOneBits(population.y)+ countOneBits(population.z) + countOneBits(population.w);var claimed = 0u;if (subgroupElect()) {claimed = atomicAdd(&matrixRoleCount, 1u);if (width != requiredWidth || populationCount != requiredWidth) {atomicStore(&matrixRejected, 1u);}}// Reconverge every invocation before broadcasting the elected claim.workgroupBarrier();return subgroupBroadcastFirst(claimed);}fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {if (localIndex == 0u) {matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u&& atomicLoad(&matrixRoleCount) == bankCount);}// The uniform load both publishes the leader's decision and gives the// compiler a workgroup-uniform condition for the barrier-containing arms.return workgroupUniformLoad(&matrixAccepted) != 0u;}// The portable arm owns two result components per logical 32-invocation group.// Staging casts, 8-wide K steps, barriers and the epilogue match the// subgroup-matrix arm.var<private> matrixSoftwareLane: u32;fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,acc: vec2<f32>) -> vec2<f32> {var value = acc;for (var k = 0u; k < 8u; k += 1u) {value = fma(vec2<f32>(lhs[k]), rhs[k], value);}return value;}{% macro matrixType(software, kind, scalar) %}{% if software %}{% if kind == "left" %}array<f32, 8>{% elif kind == "right" %}array<vec2<f32>, 8>{% else %}vec2<{{ scalar }}>{% endif %}{% else %}subgroup_matrix_{{ kind }}<{{ scalar }}, 8, 8>{% endif %}{% endmacro %}{% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}{% if kind == "left" %}array<f32, 8>({% for k in range(8) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}(matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u{% else %}{{ k }}u * ({{ stride }}) + matrixSoftwareLane / 4u{% endif %}]){{ "," if k < 7 else "" }}{% endfor %}){% else %}array<vec2<f32>, 8>({% for k in range(8) %}vec2<f32>({% for h in range(2) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}{{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u{% else %}((matrixSoftwareLane % 4u) * 2u + {{ h }}u) * ({{ stride }}) + {{ k }}u{% endif %}]){{ "," if h == 0 else "" }}{% endfor %}){{ "," if k < 7 else "" }}{% endfor %}){% endif %}{% endif %}{% endmacro %}{% macro matrixMma(software, scalar, lhs, rhs, acc) %}{% if not software %}subgroupMatrixMultiplyAccumulate({{ lhs }}, {{ rhs }}, {{ acc }}){% else %}vec2<{{ scalar }}>(matrixSoftwareMultiplyAccumulate({{ lhs }}, {{ rhs }}, vec2<f32>({{ acc }}))){% endif %}{% endmacro %}{% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{let matrixPointer = {{ pointer }};let matrixValue = {{ value }};{% for h in range(2) %} (*matrixPointer)[({{ offset }}) + {{ {"row_major": "(matrixSoftwareLane / 4u) * (" ~ stride ~ ") + (matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u", "col_major": "((matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u) * (" ~ stride ~ ") + matrixSoftwareLane / 4u"}[major] }}] = matrixValue.{{ "x" if h == 0 else "y" }};{% endfor %}}{% endif %}{% endmacro %}{% macro matrixKernelBody(matrixSoftware) %}// 2D-folded M-tile (row) base: workgroup_id.z carries the high bits when the// row tile exceeds the per-dimension dispatch limit.// Reduces to workgroup_id.y when nwg.z == 1; the row_limit guard in storeOutput1 unmodified linelet a_global_base: u32 = (ROW_TILE_BASE + workgroup_id.y + workgroup_id.z * nwg.y) * TILE_ROWS;let w_global_base: u32 = (COLUMN_TILE_BASE + workgroup_id.x) * TILE_COLS;let subtile_id: u32 = matrixRole;{% if subgroupCols == 1 %}let subtile_idx: u32 = 0u;let subtile_idy: u32 = subtile_id;{% else %}let subtile_idx: u32 = subtile_id / {{ subgroupRows }}u;let subtile_idy: u32 = subtile_id % {{ subgroupRows }}u;{% endif %}let base_A: u32 = subtile_idy * SUB_ROWS;let base_B: u32 = subtile_idx * SUB_COLS;{% if not useChunkedAccumulation %}{{ matrixAccumulators(matrixSoftware) }}{% endif %}{% if useChunkedAccumulation %}let row = sg_id / 4u;2 unmodified linesvar chunkSums: array<vec2<f32>, {{ aTilesPerSubgroup * bTilesPerSubgroup }}>;var chunkErrors: array<vec2<f32>, {{ aTilesPerSubgroup * bTilesPerSubgroup }}>;for (var chunk_base = 0u; chunk_base < IN_F; chunk_base += TILE_K * {{ matrixChunkTiles }}u) {{{ matrixAccumulators(matrixSoftware) }}for (var kidx = chunk_base; kidx < min(chunk_base + TILE_K * {{ matrixChunkTiles }}u, IN_F); kidx += TILE_K) {{% else %}for (var kidx: u32 = 0u; kidx < {{ kLoopEndValue }}; kidx += TILE_K) {4 unmodified linesloadSHMB(w_global_base, kidx, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, 0u);workgroupBarrier();for (var step: u32 = 0u; step < {{ "min(TILE_K, IN_F - kidx)" if packedKTail else "TILE_K" }}; step += 8u) {{% set dynamicATiles = aTilesPerSubgroup if aTilesPerSubgroup is defined else 2 %}{% set matrixAccumulator = matrixAccumulator | default("matC") %}{% set matrixStepOffset = matrixStepOffset | default(0) %}{% set matrixStep = "step" if matrixStepOffset == 0 else "(step + " ~ matrixStepOffset ~ "u)" %}{% set aTransposed = aTransposedStorage if aTransposedStorage is defined else (matrixInputsTransposed is defined and matrixInputsTransposed) %}{% set bTransposed = bTransposedStorage if bTransposedStorage is defined else (matrixInputsTransposed is defined and matrixInputsTransposed) %}{% set directA = directAStorage is defined and directAStorage %}{% set B_BANK = "" %}{% if directA %}{% set matrixAStorage = matrixAStorage | default("x") %}{% set matrixAStride = matrixAStride | default("IN_F") %}// Direct storage guarantees a full aligned M/K tile, so subgroup-matrix// loads need no guarded workgroup staging.let matrix_a_offset = (a_global_base + base_A) * {{ matrixAStride }} + kidx + {{ matrixStep }};4 unmodified lines{% endif %}{% for m in range(dynamicATiles) %}{% if directA %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ (matrixAStorage), ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * " ~ matrixAStride if m > 0 else "")), matrixAStride) }};{% elif aTransposed %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "col_major", "&tile_A", "matrix_a_offset + " ~ (m * 8) ~ "u", "TILE_ROWS") }};{% else %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&tile_A", ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * TILE_K" if m > 0 else "")), "TILE_K") }};{% endif %}{% endfor %}4 unmodified lines{% endif %}{% for n in range(bTilesPerSubgroup) %}{% if bTransposed %}var matB{{ n }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {{ matrixLoad(matrixSoftware, "right", operandScalar, "row_major", "&tile_B", "matrix_b_offset + " ~ (n * 8) ~ "u", "TILE_COLS") }};{% else %}var matB{{ n }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {{ matrixLoad(matrixSoftware, "right", operandScalar, "col_major", "&tile_B", "matrix_b_offset + " ~ (n * 8) ~ "u * TILE_K", "TILE_K") }};{% endif %}{% endfor %}{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixAccumulator }}{{ m }}{{ n }} = {{ matrixMma(matrixSoftware, accScalar, "matA" ~ (m), "matB" ~ (n), (matrixAccumulator) ~ (m) ~ (n)) }};{% endfor %}{% endfor %}}workgroupBarrier();}{% if useChunkedAccumulation %}{{ storeMatrixAccumulators(matrixSoftware) }}workgroupBarrier();{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}12 unmodified lines}{% endif %}let matrix_c_offset: u32 = (a_global_base + base_A) * {{ OUT_ROW }} + {{ "DST_COL + " if useRegionStore else "" }}w_global_base + base_B;{% if useChunkedAccumulation %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}10 unmodified lines// across lanes, so its cross-lane readback must be published before partial-M// guards diverge. The epilogue also handles output conversion and bias.let bank: u32 = subtile_id * {{ aTilesPerSubgroup * bTilesPerSubgroup }}u;{{ storeMatrixAccumulators(matrixSoftware) }}workgroupBarrier();{% endif %}12 unmodified lines);{% endfor %}{% endfor %}{% endmacro %}@compute @workgroup_size({{ workgroupThreads }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) workgroup_id: vec3<u32>,@builtin(num_workgroups) nwg: vec3<u32>,@builtin(local_invocation_index) local_idx: u32,@builtin(subgroup_invocation_id) sg_id: u32,@builtin(subgroup_size) sg_size: u32) {let matrixRole = claimMatrixSubgroupRole(sg_size, 32u);let matrixAcceptedHere = matrixTopologyAccepted(local_idx, {{ workgroupThreads }}u / 32u);matrixSoftwareLane = local_idx % 32u;if (matrixAcceptedHere) {{{ matrixKernelBody(false) }}} else {let matrixRole = local_idx / 32u;let sg_id = local_idx % 32u;{{ matrixKernelBody(true) }}}}
123456789108 unmodified lines192021222324252627282930313246 unmodified lines79808182838485864 unmodified lines919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135{% set COLS = gemvColumns | default(4) %}{% set ACC = "f32" if COLS == 1 else "vec4<f32>" %}{% macro wgsl_tree_fold_stmt(a, op, idx, svar) %}{% if op == "max" or op == "min" %}{{ a }}[{{ idx }}] = {{ op }}({{ a }}[{{ idx }}], {{ a }}[{{ idx }} + {{ svar }}]);{% else %}{{ a }}[{{ idx }}] = {{ a }}[{{ idx }}] {{ "*" if op == "prod" else "+" }} {{ a }}[{{ idx }} + {{ svar }}];{% endif %}{% endmacro %}{% macro wgsl_tree_fold(arrays, op="add", idx="lid", wg="WORKGROUP_SIZE", svar="stride", typed=false, form="tail", breakInline=false, bodyInline=false, barrierFirst=false, reuse=false) %}var {{ svar }}{{ ": u32 " if typed else " " }}= {{ wg }} / 2u;loop {if ({{ svar }} == 0u) {8 unmodified linesworkgroupBarrier();}{% endmacro %}{{ env.wgsl.resourceDeclarations }}{% if gemvFused and (hasActivation | default(false)) %}{% set actMode = gemmActivation | default("") %}{% set actA = gemmActAlpha | default(0.0) %}{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "Relu" %}return max(v, 0.0);{% elif mode == "Clip" %}return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %}46 unmodified lines{{ fused_act_fn(actMode, actA, actB) }}{% endif %}const IN_F: u32 = {{ inFeatures }}u;const OUT_F: u32 = {{ outFeatures }}u;const WG: u32 = {{ workgroupSize }}u;var<workgroup> partials: array<{{ ACC }}, {{ workgroupSize }}>;4 unmodified lines@builtin(local_invocation_id) lid: vec3<u32>) {let tid = lid.x;// wg.z carries column-group bits past the per-dimension dispatch limit.// This reduces to wg.x when the dispatch does not fold. col_base is workgroup-uniform, so// this guard returns the whole over-dispatched workgroup before any barrier.let col_base = (wg.x + wg.z * {{ DISPATCH_FOLD_WIDTH }}u) * {{ COLS }}u;if (col_base >= OUT_F) {return;}var acc = {{ ACC }}(0.0);for (var i = tid; i < IN_F; i = i + WG) {{% if xScalar == "f16" %}let xv = f32(x[i]);{% else %}let xv = x[i];{% endif %}{% for j in range(COLS) %}let w{{ j }} = w[(col_base + {{ j }}u) * IN_F + i];{% endfor %}{% if wScalar == "f16" %}acc = acc + xv * {{ "f32(w0)" if COLS == 1 else "vec4<f32>(f32(w0), f32(w1), f32(w2), f32(w3))" }};{% else %}acc = acc + xv * {{ "w0" if COLS == 1 else "vec4<f32>(w0, w1, w2, w3)" }};{% endif %}}partials[tid] = acc;workgroupBarrier();{{ wgsl_tree_fold(["partials"], idx="tid", wg="WG", form="head") }}if (tid == 0u) {{% for j in range(COLS) %}{let n = col_base + {{ j }}u;let product = select(partials[0]{% if COLS > 1 %}[{{ j }}u]{% endif %} * params.alpha, 0.0, params.alpha == 0.0);{% if hasBias %}let bias_term = select(f32(bias[{% if scalarBiasOk | default(false) %}0u{% else %}n{% endif %}]) * params.beta, 0.0, params.beta == 0.0);{% endif %}y[n] = {{ yScalar }}({% if hasActivation | default(false) %}fused_act({% endif %}product{% if hasBias %} + bias_term{% endif %}{% if hasActivation | default(false) %}){% endif %});}{% endfor %}}12345678910111213148 unmodified lines232425262728293031323334353637383946 unmodified lines868788899091929394959697984 unmodified lines103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185{% set gemvRowOffset = "" %}{% set GROUPS = gemvColumnLanes | default(1) %}{% set COLS = gemvColumns | default(4) %}{% set MASKED = gemvMaskedColumns | default(false) %}{% set K_STEP = " / " ~ GROUPS ~ "u" if GROUPS > 1 else "" %}{% set PARTIAL = "tid" if GROUPS > 1 else "0" %}{% set ACC = "f32" if COLS == 1 else "vec4<f32>" %}{% macro wgsl_tree_fold_stmt(a, op, idx, svar) %}{% if op == "max" or op == "min" %}{{ a }}[{{ idx }}] = {{ op }}({{ a }}[{{ idx }}], {{ a }}[{{ idx }} + {{ svar }}]);{% else %}{{ a }}[{{ idx }}] = {{ a }}[{{ idx }}] {{ "*" if op == "prod" else "+" }} {{ a }}[{{ idx }} + {{ svar }}];{% endif %}{% endmacro %}{% macro wgsl_tree_fold(arrays, op="add", idx="lid", wg="WORKGROUP_SIZE", svar="stride", typed=false, form="tail", barrierFirst=false, reuse=false) %}var {{ svar }}{{ ": u32 " if typed else " " }}= {{ wg }} / 2u;loop {if ({{ svar }} == 0u) {8 unmodified linesworkgroupBarrier();}{% endmacro %}{{ env.wgsl.resourceDeclarations }}{% if (hasActivation | default(false)) %}{% set actMode = gemmActivation | default("") %}{% set actA = gemmActAlpha | default(0.0) %}{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "" %}return v;{% elif mode == "Relu" %}let bits = bitcast<u32>(v);return bitcast<f32>(select(0u, bits, (bits & 0x80000000u) == 0u || (bits & 0x7fffffffu) > 0x7f800000u));{% elif mode == "Clip" %}return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %}46 unmodified lines{{ fused_act_fn(actMode, actA, actB) }}{% endif %}{% if gemvUniformDims | default(false) %}{% set GEMV_IN = "params.inner" %}{% set GEMV_OUT = "params.columns" %}{% else %}{% set GEMV_IN = "IN_F" %}{% set GEMV_OUT = "OUT_F" %}const IN_F: u32 = {{ inFeatures }}u;const OUT_F: u32 = {{ outFeatures }}u;{% endif %}const WG: u32 = {{ workgroupSize }}u;var<workgroup> partials: array<{{ ACC }}, {{ workgroupSize }}>;4 unmodified lines@builtin(local_invocation_id) lid: vec3<u32>) {let tid = lid.x;{% if GROUPS > 1 %}// Each K lane processes neighboring column vectors.let group_base = (wg.x + wg.z * {{ DISPATCH_FOLD_WIDTH }}u) * {{ COLS * GROUPS }}u;if (group_base >= {{ GEMV_OUT }}) { return; }let col_base = group_base + (tid % {{ GROUPS }}u) * {{ COLS }}u;{% else %}// wg.z carries column-group bits past the per-dimension dispatch limit.// This reduces to wg.x when the dispatch does not fold. col_base is workgroup-uniform, so// this guard returns the whole over-dispatched workgroup before any barrier.let col_base = (wg.x + wg.z * {{ DISPATCH_FOLD_WIDTH }}u) * {{ COLS }}u;if (col_base >= {{ GEMV_OUT }}) {return;}{% endif %}var acc = {{ ACC }}(0.0);for (var i = tid{{ K_STEP }}; i < {{ GEMV_IN }}; i = i + WG{{ K_STEP }}) {{% if xScalar == "f16" %}let xv = f32(x[i]);{% else %}let xv = x[i];{% endif %}{% if gemvStoredColumns | default(false) %}{% if MASKED %}let w_base = i * {{ GEMV_OUT }};let last_col = {{ GEMV_OUT }} - 1u;// Extra vector components reuse the last valid input and are dropped at the output.acc += xv * vec4<f32>({% for j in range(4) %}f32(w[w_base + min(col_base + {{ j }}u, last_col)]){{ "," if j < 3 else ");" }}{% endfor %}{% elif COLS == 1 %}acc += xv * f32(w[i * {{ GEMV_OUT }} + col_base]);{% else %}acc += xv * vec4<f32>(w[i * ({{ GEMV_OUT }} / 4u) + col_base / 4u]);{% endif %}{% else %}{% for j in range(COLS) %}let w{{ j }} = w[(col_base + {{ j }}u) * {{ GEMV_IN }} + i];{% endfor %}{% if wScalar == "f16" %}acc = acc + xv * {{ "f32(w0)" if COLS == 1 else "vec4<f32>(f32(w0), f32(w1), f32(w2), f32(w3))" }};{% else %}acc = acc + xv * {{ "w0" if COLS == 1 else "vec4<f32>(w0, w1, w2, w3)" }};{% endif %}{% endif %}}partials[tid] = acc;workgroupBarrier();{% if GROUPS > 1 %}for (var stride = WG / 2u; stride >= {{ GROUPS }}u; stride /= 2u) {if (tid < stride) { partials[tid] += partials[tid + stride]; }workgroupBarrier();}{% else %}{{ wgsl_tree_fold(["partials"], idx="tid", wg="WG", form="head") }}{% endif %}if (tid {% if GROUPS > 1 %}< {{ GROUPS }}u{% else %}== 0u{% endif %}) {{% for j in range(COLS) %}{let n = col_base + {{ j }}u;{% if MASKED %}if (n < {{ GEMV_OUT }}) {{% endif %}{% filter indent(8 if MASKED else 6, true) %}let product = select(partials[{{ PARTIAL }}]{% if COLS > 1 %}[{{ j }}u]{% endif %} * params.alpha, 0.0, params.alpha == 0.0);{% if hasBias %}let bias_term = select(f32(bias[{% if scalarBiasOk | default(false) %}0u{% else %}n{% endif %}]) * params.beta, 0.0, params.beta == 0.0);{% endif %}y[{{ gemvRowOffset }}n] = {{ yScalar }}({% if hasActivation | default(false) %}fused_act({% endif %}product{% if hasBias %} + bias_term{% endif %}{% if hasActivation | default(false) %}){% endif %});{% endfilter %}{% if MASKED %}}{% endif %}}{% endfor %}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311{"domain": "com.microsoft","name": "FusedGemm","sinceVersion": 1,"inputs": {"A": { "dtype": "T", "rank": 2 },"B": { "dtype": "T", "rank": 2 },"C": { "dtype": "T", "optional": true }},"outputs": { "Y": { "dtype": "T", "rank": 2, "shape": "[gemmM, gemmN]" } },"attributes": {"alpha": { "default": 1 },"beta": { "default": 1 },"transA": { "default": 0 },"transB": { "default": 0 },"activation": {},"activation_alpha": {},"activation_beta": {}},"attributeConstraints": { "activation": { "values": ["Relu", "LeakyRelu", "Sigmoid", "Tanh", "HardSigmoid"] } },"typeConstraints": { "T": ["float32", "float16"] },"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","variableSubgroup16To32": "device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 16 and device.adapterInfo.subgroupMaxSize == 32","transAFlag": "has(attrs, \"transA\") and attrs.transA != 0","transBFlag": "has(attrs, \"transB\") and attrs.transB != 0","gemmM": "dim(shapes.A, 1) if transAFlag else dim(shapes.A, 0)","gemmK": "dim(shapes.A, 0) if transAFlag else dim(shapes.A, 1)","gemmN": "dim(shapes.B, 0) if transBFlag else dim(shapes.B, 1)","gemmKB": "dim(shapes.B, 1) if transBFlag else dim(shapes.B, 0)","shapeOk": "ranks.A == 2 and ranks.B == 2 and ranks.Y == 2 and gemmK == gemmKB and dim(shapes.Y, 0) == gemmM and dim(shapes.Y, 1) == gemmN","dtypeOk": "(tensorDtypes.A == \"float32\" or tensorDtypes.A == \"float16\") and tensorDtypes.B == tensorDtypes.A and tensorDtypes.Y == tensorDtypes.A and f16Ok(dtypes.T)","rowBiasOk": "present.C and ((ranks.C == 1 and dim(shapes.C, 0) == gemmN) or (ranks.C == 2 and dim(shapes.C, 0) == 1 and dim(shapes.C, 1) == gemmN))","scalarBiasOk": "present.C and (ranks.C == 0 or (ranks.C == 1 and dim(shapes.C, 0) == 1) or (ranks.C == 2 and dim(shapes.C, 0) == 1 and dim(shapes.C, 1) == 1))","columnBiasOk": "present.C and ranks.C == 2 and dim(shapes.C, 0) == gemmM and dim(shapes.C, 1) == 1","matrixBiasOk": "present.C and ranks.C == 2 and dim(shapes.C, 0) == gemmM and dim(shapes.C, 1) == gemmN","cOk": "tensorDtypes.C == tensorDtypes.A and (rowBiasOk or scalarBiasOk or columnBiasOk or matrixBiasOk)","hasActivation": "has(attrs, \"activation\")","activationName": "attrs.activation if hasActivation else \"\"","activationOk": "not hasActivation or activationName == \"Relu\" or activationName == \"LeakyRelu\" or activationName == \"Sigmoid\" or activationName == \"Tanh\" or activationName == \"HardSigmoid\"","activationAlpha": "attrs.activation_alpha if has(attrs, \"activation_alpha\") else (0.2 if activationName == \"HardSigmoid\" else (0.01 if activationName == \"LeakyRelu\" else 0.0))","activationBeta": "attrs.activation_beta if has(attrs, \"activation_beta\") else (0.5 if activationName == \"HardSigmoid\" else 0.0)","baseContract": "shapeOk and dtypeOk and activationOk","noBiasContract": "baseContract and not present.C","biasContract": "baseContract and present.C and cOk","sgmatOperandBytes": "2 if tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" else 4","sgmatTileM": "32","sgmatTileN": "64","sgmatTileK": "32","sgmatDirectA": "tensorDtypes.A == \"float32\" and not transAFlag and gemmK > 0 and gemmM % sgmatTileM == 0","sgmatStorageBytes": "((0 if sgmatDirectA else sgmatTileM) + sgmatTileN) * sgmatTileK * sgmatOperandBytes + sgmatTileM * sgmatTileN * 4","sgmatResourcesFit": "128 <= deviceWorkgroupCap and sgmatStorageBytes <= device.limits.maxComputeWorkgroupStorageSize","sgmatScalingOk": "(attrs.alpha if has(attrs, \"alpha\") else 1) == 1 and (attrs.beta if has(attrs, \"beta\") else 1) == 1","sgmatLayoutOk": "gemmM > 0 and gemmK % sgmatTileK == 0 and gemmN % sgmatTileN == 0 and ((tensorDtypes.A == \"float16\" and device.features.has(\"shader-f16\") and (gemmM >= 2 or (not transAFlag and transBFlag))) or (tensorDtypes.A == \"float32\" and gemmM >= sgmatTileM)) and ceilDiv(gemmM, sgmatTileM) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(gemmN, sgmatTileN) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","sgmatContract": "wave32Effective and sgmatLayoutOk and sgmatScalingOk and sgmatResourcesFit","sgmatRowBiasContract": "sgmatContract and rowBiasOk and ranks.C == 1","usesF16": "tensorDtypes.A == \"float16\"","gemmActivation": "activationName","gemmActAlpha": "activationAlpha","gemmActBeta": "activationBeta","gemmEpilogue": "\"activation\" if hasActivation else \"none\"","gemvColumns": "4 if gemmN % 4 == 0 else 1","gemvWorkgroup": "min(pow(2, log2ceil(deviceWorkgroupCap + 1) - 1), pow2ceil(max(gemmK, 1)), 64)","portableMicro8x2Preferred": "(variableSubgroup16To32 or (wave32Effective and not device.features.has(\"shader-f16\"))) and 256 <= deviceWorkgroupCap and 32 <= device.limits.maxComputeWorkgroupSizeX and 8 <= device.limits.maxComputeWorkgroupSizeY","gemmMicroRows": "8 if portableMicro8x2Preferred else 4","gemmMicroCols": "2 if portableMicro8x2Preferred else 4","gemmStaticM": "gemmM","gemmStaticN": "gemmN","gemmStaticK": "gemmK"},"bindings": {"x": { "arg": "A", "elementType": "$T" },"w": { "arg": "B", "elementType": "$T" },"bias": { "arg": "C", "elementType": "$T" },"y": { "arg": "Y", "elementType": "$T" },"params": { "struct": [{ "name": "M", "type": "u32", "value": "gemmM" }] },"a": { "arg": "A", "elementType": "$T" },"b": { "arg": "B", "elementType": "$T" }},"variants": [{"id": "gemv_plain","priority": 200,"when": ["noBiasContract", "gemmM == 1 and gemmN > 0 and gemmK > 0 and transBFlag", "gemvWorkgroup * gemvColumns * 4 <= device.limits.maxComputeWorkgroupStorageSize"],"derive": {"hasBias": false,"workgroupSize": "gemvWorkgroup","gemvFused": true,"inFeatures": "gemmK","outFeatures": "gemmN","xScalar": "\"f16\" if usesF16 else \"f32\"","wScalar": "\"f16\" if usesF16 else \"f32\"","yScalar": "\"f16\" if usesF16 else \"f32\""},"passes": [{"id": "main","name": "FusedGemm.Gemv","shader": "gemv-contiguous.wgsl.jinja","bindings": ["x","w","y",{"name": "params","struct": [{ "name": "alpha", "type": "f32", "value": "attrs.alpha if has(attrs, \"alpha\") else 1" }]}],"dispatch": {"x": "min(ceilDiv(gemmN, gemvColumns), DISPATCH_FOLD_WIDTH)","y": "1","z": "ceilDiv(ceilDiv(gemmN, gemvColumns), DISPATCH_FOLD_WIDTH)"}}]},{"id": "gemv_bias","priority": 200,"when": ["biasContract", "gemmM == 1 and gemmN > 0 and gemmK > 0 and transBFlag", "gemvWorkgroup * gemvColumns * 4 <= device.limits.maxComputeWorkgroupStorageSize"],"derive": {"hasBias": true,"workgroupSize": "gemvWorkgroup","gemvFused": true,"inFeatures": "gemmK","outFeatures": "gemmN","xScalar": "\"f16\" if usesF16 else \"f32\"","wScalar": "\"f16\" if usesF16 else \"f32\"","yScalar": "\"f16\" if usesF16 else \"f32\""},"passes": [{"id": "main","name": "FusedGemm.Gemv","shader": "gemv-contiguous.wgsl.jinja","bindings": ["x","w","bias","y",{"name": "params","struct": [{ "name": "alpha", "type": "f32", "value": "attrs.alpha if has(attrs, \"alpha\") else 1" },{ "name": "beta", "type": "f32", "value": "attrs.beta if has(attrs, \"beta\") else 1" }]}],"dispatch": {"x": "min(ceilDiv(gemmN, gemvColumns), DISPATCH_FOLD_WIDTH)","y": "1","z": "ceilDiv(ceilDiv(gemmN, gemvColumns), DISPATCH_FOLD_WIDTH)"}}]},{"id": "sgmat_bias","priority": 100,"when": ["sgmatRowBiasContract"],"requires": {"features": ["subgroups", "chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs": [{ "componentType": "f16", "M": 8, "N": 8, "K": 8 },{ "componentType": "f32", "resultComponentType": "f32", "M": 8, "N": 8, "K": 8 }]},"derive": {"hasBias": true,"aTransposedStorage": "transAFlag","bTransposedStorage": "not transBFlag","yScalar": "\"f16\" if tensorDtypes.Y == \"float16\" else \"f32\"","mmaScalar": "\"f16\" if tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" else \"f32\"","inFeatures": "gemmK","outFeatures": "gemmN","tileM": "sgmatTileM","tileN": "sgmatTileN","tileK": "sgmatTileK","directAStorage": "sgmatDirectA","compensatedMatrixChunkTiles": "2 if sgmatDirectA and gemmK >= 8 * sgmatTileK else 0"},"passes": [{"id": "main","name": "FusedGemm.SubgroupMatrixBias","shader": "gemm-subgroup-matrix.wgsl.jinja","bindings": ["x", "w", "bias", "y", "params"],"dispatch": {"x": "ceilDiv(gemmN, sgmatTileN)","y": "min(ceilDiv(gemmM, sgmatTileM), DISPATCH_FOLD_WIDTH)","z": "ceilDiv(ceilDiv(gemmM, sgmatTileM), DISPATCH_FOLD_WIDTH)"}}]},{"id": "sgmat","priority": 100,"when": ["noBiasContract and sgmatContract"],"requires": {"features": ["subgroups", "chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs": [{ "componentType": "f16", "M": 8, "N": 8, "K": 8 },{ "componentType": "f32", "resultComponentType": "f32", "M": 8, "N": 8, "K": 8 }]},"derive": {"hasBias": false,"aTransposedStorage": "transAFlag","bTransposedStorage": "not transBFlag","yScalar": "\"f16\" if tensorDtypes.Y == \"float16\" else \"f32\"","mmaScalar": "\"f16\" if tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" else \"f32\"","inFeatures": "gemmK","outFeatures": "gemmN","tileM": "sgmatTileM","tileN": "sgmatTileN","tileK": "sgmatTileK","directAStorage": "sgmatDirectA","compensatedMatrixChunkTiles": "2 if sgmatDirectA and gemmK >= 8 * sgmatTileK else 0"},"passes": [{"id": "main","name": "FusedGemm.SubgroupMatrix","shader": "gemm-subgroup-matrix.wgsl.jinja","bindings": ["x", "w", "y", "params"],"dispatch": {"x": "ceilDiv(gemmN, sgmatTileN)","y": "min(ceilDiv(gemmM, sgmatTileM), DISPATCH_FOLD_WIDTH)","z": "ceilDiv(ceilDiv(gemmM, sgmatTileM), DISPATCH_FOLD_WIDTH)"}}]},{"id": "tiled_reg_bias","priority": 0,"when": ["biasContract"],"derive": {"transA": "transAFlag","transB": "transBFlag","hasBias": true,"rowBias": "rowBiasOk","scalarBias": "scalarBiasOk","columnBias": "columnBiasOk"},"passes": [{"id": "main","name": "FusedGemm.Bias","shader": "gemm-epilogue-tiled-reg.wgsl.jinja","bindings": ["a","b","bias","y",{"name": "params","struct": [{ "name": "M", "type": "u32", "value": "gemmM" },{ "name": "N", "type": "u32", "value": "gemmN" },{ "name": "K", "type": "u32", "value": "gemmK" },{ "name": "alpha", "type": "f32", "value": "attrs.alpha if has(attrs, \"alpha\") else 1" },{ "name": "beta", "type": "f32", "value": "attrs.beta if has(attrs, \"beta\") else 1" }]}],"dispatch": {"x": "min(ceilDiv(gemmN, 64), min(device.limits.maxComputeWorkgroupsPerDimension, 65535))","y": "min(ceilDiv(gemmM, 64), min(device.limits.maxComputeWorkgroupsPerDimension, 65535))"}}]},{"id": "tiled_reg","priority": 0,"when": ["noBiasContract"],"derive": { "transA": "transAFlag", "transB": "transBFlag", "hasBias": false },"passes": [{"id": "main","name": "FusedGemm","shader": "gemm-epilogue-tiled-reg.wgsl.jinja","bindings": ["a","b","y",{"name": "params","struct": [{ "name": "M", "type": "u32", "value": "gemmM" },{ "name": "N", "type": "u32", "value": "gemmN" },{ "name": "K", "type": "u32", "value": "gemmK" },{ "name": "alpha", "type": "f32", "value": "attrs.alpha if has(attrs, \"alpha\") else 1" }]}],"dispatch": {"x": "min(ceilDiv(gemmN, 64), min(device.limits.maxComputeWorkgroupsPerDimension, 65535))","y": "min(ceilDiv(gemmM, 64), min(device.limits.maxComputeWorkgroupsPerDimension, 65535))"}}]}]}1{"domain":"com.microsoft","name":"FusedGemm","sinceVersion":1,"inputs":{"A":{"dtype":"T","rank":2},"B":{"dtype":"T","rank":2},"C":{"dtype":"T","optional":true}},"outputs":{"Y":{"dtype":"T","rank":2,"shape":"[gemmM, gemmN]"}},"attributes":{"alpha":{"default":1},"beta":{"default":1},"transA":{"default":0},"transB":{"default":0},"activation":{},"activation_alpha":{},"activation_beta":{}},"attributeConstraints":{"activation":{"values":["Relu","LeakyRelu","Sigmoid","Tanh","HardSigmoid"]}},"typeConstraints":{"T":["float32","float16"]},"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","variableSubgroup16To32":"device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 16 and device.adapterInfo.subgroupMaxSize == 32","subgroupMatrix8F16Available":"subgroupMatrixConfigAvailable(\"f16\", \"f32\", 8, 8, 8)","subgroupMatrix8F32Available":"subgroupMatrixConfigAvailable(\"f32\", \"f32\", 8, 8, 8)","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)","native16PackedBaseStrideBytes":"dtypeBytes(\"float16\") * (native16PackedBaseTile + native16PackedSharedPad)","native16PackedWideStrideBytes":"dtypeBytes(\"float16\") * (native16PackedWideTile + native16PackedSharedPad)","native16PackedBaseAStorageBytes":"max(native16PackedBaseTile * native16PackedStageStrideBytes, native16PackedOutputScratchBytes)","native16PackedWideAStorageBytes":"max(native16PackedWideTile * native16PackedStageStrideBytes, native16PackedOutputScratchBytes)","native16PackedBaseRowStorageBytes":"native16PackedBaseAStorageBytes + native16PackedStageK * native16PackedBaseStrideBytes + subgroupMatrixTopologyBytes","native16PackedBaseColumnStorageBytes":"native16PackedBaseAStorageBytes + native16PackedBaseTile * native16PackedStageStrideBytes + subgroupMatrixTopologyBytes","native16PackedWideRowStorageBytes":"native16PackedWideAStorageBytes + native16PackedStageK * native16PackedWideStrideBytes + subgroupMatrixTopologyBytes","native16PackedWideColumnStorageBytes":"native16PackedWideAStorageBytes + native16PackedWideTile * native16PackedStageStrideBytes + subgroupMatrixTopologyBytes","matrixSubgroupRangeReported":"has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\")","matrixAllowsWidth32":"(not has(device.adapterInfo, \"subgroupMinSize\") and not has(device.adapterInfo, \"subgroupMaxSize\")) or (matrixSubgroupRangeReported and device.adapterInfo.subgroupMinSize <= 32 and device.adapterInfo.subgroupMaxSize >= 32)","matrixAllowsWidth64":"matrixSubgroupRangeReported and device.adapterInfo.subgroupMinSize <= 64 and device.adapterInfo.subgroupMaxSize >= 64","matrixSubgroupWidth":"32 if matrixAllowsWidth32 else (64 if matrixAllowsWidth64 else 0)","transAFlag":"has(attrs, \"transA\") and attrs.transA != 0","transBFlag":"has(attrs, \"transB\") and attrs.transB != 0","gemmM":"dim(shapes.A, 1) if transAFlag else dim(shapes.A, 0)","gemmK":"dim(shapes.A, 0) if transAFlag else dim(shapes.A, 1)","gemmN":"dim(shapes.B, 0) if transBFlag else dim(shapes.B, 1)","gemmKB":"dim(shapes.B, 1) if transBFlag else dim(shapes.B, 0)","shapeOk":"ranks.A == 2 and ranks.B == 2 and ranks.Y == 2 and gemmK == gemmKB and dim(shapes.Y, 0) == gemmM and dim(shapes.Y, 1) == gemmN","dtypeOk":"(tensorDtypes.A == \"float32\" or tensorDtypes.A == \"float16\") and tensorDtypes.B == tensorDtypes.A and tensorDtypes.Y == tensorDtypes.A and f16Ok(dtypes.T)","rowBiasOk":"present.C and ((ranks.C == 1 and dim(shapes.C, 0) == gemmN) or (ranks.C == 2 and dim(shapes.C, 0) == 1 and dim(shapes.C, 1) == gemmN))","scalarBiasOk":"present.C and (ranks.C == 0 or (ranks.C == 1 and dim(shapes.C, 0) == 1) or (ranks.C == 2 and dim(shapes.C, 0) == 1 and dim(shapes.C, 1) == 1))","columnBiasOk":"present.C and ranks.C == 2 and dim(shapes.C, 0) == gemmM and dim(shapes.C, 1) == 1","matrixBiasOk":"present.C and ranks.C == 2 and dim(shapes.C, 0) == gemmM and dim(shapes.C, 1) == gemmN","cOk":"tensorDtypes.C == tensorDtypes.A and (rowBiasOk or scalarBiasOk or columnBiasOk or matrixBiasOk)","hasActivation":"has(attrs, \"activation\")","activationName":"attrs.activation if hasActivation else \"\"","activationOk":"not hasActivation or activationName == \"Relu\" or activationName == \"LeakyRelu\" or activationName == \"Sigmoid\" or activationName == \"Tanh\" or activationName == \"HardSigmoid\"","activationAlpha":"attrs.activation_alpha if has(attrs, \"activation_alpha\") else (0.2 if activationName == \"HardSigmoid\" else (0.01 if activationName == \"LeakyRelu\" else 0.0))","activationBeta":"attrs.activation_beta if has(attrs, \"activation_beta\") else (0.5 if activationName == \"HardSigmoid\" else 0.0)","baseContract":"shapeOk and dtypeOk and activationOk","noBiasContract":"baseContract and not present.C","gemmContract":"baseContract and (not present.C or cOk)","packedBias":"present.C and attrs.beta != 0","packedBiasOk":"not present.C or (cOk and (attrs.beta == 0 or (attrs.beta >= -340282346638528859811704183484516925440 and attrs.beta <= 340282346638528859811704183484516925440 and (attrs.beta <= -0.000000000000000000000000000000000000000000001401298464324817 or attrs.beta >= 0.000000000000000000000000000000000000000000001401298464324817))))","packedBiasMode":"\"none\" if not packedBias else \"scalar\" if scalarBiasOk else \"row\" if rowBiasOk else \"column\" if columnBiasOk else \"matrix\"","sgmatOperandBytes":"2 if tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" else 4","sgmatTileM":"32","sgmatTileN":"64","sgmatTileK":"32","sgmatDirectA":"tensorDtypes.A == \"float32\" and not transAFlag and gemmK > 0 and gemmM % sgmatTileM == 0","sgmatStorageBytes":"(((0 if sgmatDirectA else sgmatTileM) + sgmatTileN) * sgmatTileK * sgmatOperandBytes + sgmatTileM * sgmatTileN * 4) + subgroupMatrixTopologyBytes","sgmatResourcesFit":"128 <= deviceWorkgroupCap and sgmatStorageBytes <= device.limits.maxComputeWorkgroupStorageSize","sgmatScalingOk":"(attrs.alpha if has(attrs, \"alpha\") else 1) == 1 and (attrs.beta if has(attrs, \"beta\") else 1) == 1","sgmatLayoutOk":"gemmM > 0 and gemmK % sgmatTileK == 0 and gemmN % sgmatTileN == 0 and ((tensorDtypes.A == \"float16\" and device.features.has(\"shader-f16\") and (gemmM >= 2 or (not transAFlag and transBFlag))) or (tensorDtypes.A == \"float32\" and gemmM >= sgmatTileM)) and ceilDiv(gemmM, sgmatTileM) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(gemmN, sgmatTileN) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","sgmatContract":"wave32Effective and sgmatLayoutOk and sgmatScalingOk and sgmatResourcesFit","usesF16":"tensorDtypes.A == \"float16\"","gemmActivation":"activationName","gemmActAlpha":"activationAlpha","gemmActBeta":"activationBeta","gemmEpilogue":"\"activation\" if hasActivation else \"none\"","gemvStoredColumns":"usesF16 and not transBFlag","gemvWorkgroup":"min(pow(2, log2ceil(deviceWorkgroupCap + 1) - 1), pow2ceil(max(gemmK, 1)), 64)","gemvColumns":"4 if gemmN % 4 == 0 or (gemvStoredColumns and gemmN >= 4 * gemvWorkgroup) else 1","gemvMaskedColumns":"gemvStoredColumns and gemvColumns == 4 and gemmN % 4 != 0","gemvColumnLanes":"4 if gemvStoredColumns and (gemmN % (4 * gemvColumns) == 0 or gemvMaskedColumns) and gemvWorkgroup >= 4 and gemmN >= 4 * gemvColumns * gemvWorkgroup else 1","gemvUniformDims":"gemvStoredColumns and gemvColumnLanes == 1","gemvColumnGroups":"ceilDiv(gemmN, gemvColumns * gemvColumnLanes)","portableMicro8x2Preferred":"(variableSubgroup16To32 or (wave32Effective and not device.features.has(\"shader-f16\"))) and 256 <= deviceWorkgroupCap and 32 <= device.limits.maxComputeWorkgroupSizeX and 8 <= device.limits.maxComputeWorkgroupSizeY","gemmMicroRows":"8 if portableMicro8x2Preferred else 4","gemmMicroCols":"2 if portableMicro8x2Preferred else 4","gemmStaticM":"gemmM","gemmStaticN":"gemmN","gemmStaticK":"gemmK","vecTallBlocks":"ceilDiv(gemmM, 128) * ceilDiv(gemmN, 64)","vecRows":"128 if vecTallBlocks >= tunables.VEC4_TALL_TILE_MIN_BLOCKS else 64","vecTiles":"ceilDiv(gemmM, vecRows) * ceilDiv(gemmN, 64)","vecSplitWant":"ceilDiv(tunables.VEC4_SPLITK_TARGET_WORKGROUPS, max(1, vecTiles))","vecSplitK":"8 if (vecSplitWant >= 8 and gemmK % 256 == 0 and gemmK >= 1024) else (4 if (vecSplitWant >= 4 and gemmK % 128 == 0 and gemmK >= 512) else (2 if (vecSplitWant >= 2 and gemmK % 64 == 0 and gemmK >= 256) else 1))","vecStorageBytes":"(vecRows * 32 + 32 * 65) * 4","vecContract":"tensorDtypes.A == \"float32\" and gemmM >= 32 and gemmK > 0 and gemmK % 32 == 0 and gemmN % 4 == 0 and (not transAFlag or gemmM % 4 == 0) and ceilDiv(gemmM, vecRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(gemmN, 64) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and 16 <= device.limits.maxComputeWorkgroupSizeX and 16 <= device.limits.maxComputeWorkgroupSizeY and 256 <= device.limits.maxComputeInvocationsPerWorkgroup and (vecRows * 16 + 16 * 65) * 4 <= device.limits.maxComputeWorkgroupStorageSize","blackwellFixed32Subgroups":"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","vecTilePreferred":"wave32Effective and not device.features.has(\"shader-f16\") or (blackwellFixed32Subgroups and vecSplitK == 1 and not subgroupMatrixConfigAvailable(\"f32\", \"f32\", 8, 8, 8))","vecBiasMode":"\"row\" if rowBiasOk else (\"scalar\" if scalarBiasOk else (\"column\" if columnBiasOk else \"matrix\"))","vecBiasElement":"\"vec4<f32>\" if vecBiasMode == \"row\" or vecBiasMode == \"matrix\" else \"f32\"","vecAlpha":"attrs.alpha if has(attrs, \"alpha\") else 1","vecBeta":"attrs.beta if has(attrs, \"beta\") else 1","packedBaseWorkgroups":"ceilDiv(gemmM, native16PackedBaseTile) * ceilDiv(gemmN, native16PackedBaseTile)","packedWideWorkgroups":"ceilDiv(gemmM, native16PackedWideTile) * ceilDiv(gemmN, native16PackedWideTile)","packedBaseStorageBytes":"native16PackedBaseColumnStorageBytes if transBFlag else native16PackedBaseRowStorageBytes","packedWideStorageBytes":"native16PackedWideColumnStorageBytes if transBFlag else native16PackedWideRowStorageBytes","packedMeasuredPreference":"gemmM >= native16PackedBaseTile / 2 and gemmK >= 16 * native16PackedStageK and packedBaseWorkgroups >= 4","packedWidePreferred":"gemmM >= native16PackedWideTile and gemmN >= native16PackedWideTile and packedWideWorkgroups >= native16PackedWideGridFloor and packedWideStorageBytes <= device.limits.maxComputeWorkgroupStorageSize","packedRectStorageBytes":"native16PackedBaseAStorageBytes + (native16PackedWideTile * native16PackedStageStrideBytes if transBFlag else native16PackedStageK * native16PackedWideStrideBytes) + subgroupMatrixTopologyBytes","packedRectGridCeiling":256,"packedRectPreferred":"packedWidePreferred and packedWideWorkgroups < packedRectGridCeiling and packedRectStorageBytes <= device.limits.maxComputeWorkgroupStorageSize"},"bindings":{"x":{"arg":"A","elementType":"$T"},"w":{"arg":"B","elementType":"$T"},"bias":{"arg":"C","elementType":"$T","when":"present.C"},"y":{"arg":"Y","elementType":"$T"},"params":{"struct":[{"name":"M","type":"u32","value":"gemmM"}]},"a":{"arg":"A","elementType":"$T"},"b":{"arg":"B","elementType":"$T"},"packed_bias":{"arg":"C","name":"bias","elementType":"f16","when":"packedBias"},"packed_params_plain":{"name":"params","when":"not packedBias","struct":[{"name":"M","type":"u32","value":"gemmM"},{"name":"alpha","type":"f32","value":"attrs.alpha"}]},"packed_params_bias":{"name":"params","when":"packedBias","struct":[{"name":"M","type":"u32","value":"gemmM"},{"name":"alpha","type":"f32","value":"attrs.alpha"},{"name":"beta","type":"f32","value":"attrs.beta"}]}},"variants":[{"id":"native16_packed_64x64","priority":201,"when":["baseContract","tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" and tensorDtypes.Y == \"float16\"","not transAFlag","gemmM > 0 and gemmK > 0 and gemmN > 0","gemmK % 8 == 0 and gemmN % 8 == 0","packedBiasOk","attrs.alpha >= -340282346638528859811704183484516925440 and attrs.alpha <= 340282346638528859811704183484516925440 and (attrs.alpha <= -0.000000000000000000000000000000000000000000001401298464324817 or attrs.alpha >= 0.000000000000000000000000000000000000000000001401298464324817)","blackwellFixed32Subgroups","128 <= deviceWorkgroupCap","packedBaseStorageBytes <= device.limits.maxComputeWorkgroupStorageSize","ceilDiv(gemmM, native16PackedBaseTile) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(gemmN, 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":{"M":"gemmM","N":"gemmN","K":"gemmK","registerTileM":"native16PackedBaseTile","registerTileN":"native16PackedBaseTile","registerTileK":"native16PackedStageK","registerTransposeB":"transBFlag","registerAElement":"\"vec4<u32>\"","registerBElement":"\"vec4<u32>\"","registerSharedPad":"native16PackedSharedPad","registerPrefetch":"packedBaseWorkgroups < native16PackedPrefetchGridCeiling","registerEpilogue":"\"activation\" if hasActivation else \"gemm\"","registerBiasMode":"packedBiasMode"},"passes":[{"id":"main","name":"FusedGemm.PackedRegister.64x64","shader":"fusedgemm-native16-packed-register.wgsl.jinja","bindings":[{"arg":"A","name":"a","elementType":"$registerAElement"},{"arg":"B","name":"b","elementType":"$registerBElement"},"packed_bias",{"arg":"Y","name":"y","elementType":"vec4<u32>"},"packed_params_plain","packed_params_bias"],"dispatch":{"x":"ceilDiv(N, registerTileN)","y":"ceilDiv(M, registerTileM)"}}],"demoteWhen":["not packedMeasuredPreference","packedWidePreferred"]},{"id":"native16_packed_128x128","priority":202,"when":["baseContract","tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" and tensorDtypes.Y == \"float16\"","not transAFlag","gemmM > 0 and gemmK > 0 and gemmN > 0","gemmK % 8 == 0 and gemmN % 8 == 0","packedBiasOk","attrs.alpha >= -340282346638528859811704183484516925440 and attrs.alpha <= 340282346638528859811704183484516925440 and (attrs.alpha <= -0.000000000000000000000000000000000000000000001401298464324817 or attrs.alpha >= 0.000000000000000000000000000000000000000000001401298464324817)","blackwellFixed32Subgroups","128 <= deviceWorkgroupCap","packedWideStorageBytes <= device.limits.maxComputeWorkgroupStorageSize","ceilDiv(gemmM, native16PackedWideTile) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(gemmN, 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":{"M":"gemmM","N":"gemmN","K":"gemmK","registerTileM":"native16PackedWideTile","registerTileN":"native16PackedWideTile","registerTileK":"native16PackedStageK","registerTransposeB":"transBFlag","registerAElement":"\"vec4<u32>\"","registerBElement":"\"vec4<u32>\"","registerSharedPad":"native16PackedSharedPad","registerPrefetch":true,"registerEpilogue":"\"activation\" if hasActivation else \"gemm\"","registerBiasMode":"packedBiasMode"},"passes":[{"id":"main","name":"FusedGemm.PackedRegister.128x128","shader":"fusedgemm-native16-packed-register.wgsl.jinja","bindings":[{"arg":"A","name":"a","elementType":"$registerAElement"},{"arg":"B","name":"b","elementType":"$registerBElement"},"packed_bias",{"arg":"Y","name":"y","elementType":"vec4<u32>"},"packed_params_plain","packed_params_bias"],"dispatch":{"x":"ceilDiv(N, registerTileN)","y":"ceilDiv(M, registerTileM)"}}],"demoteWhen":["not packedMeasuredPreference","not packedWidePreferred or packedRectPreferred"]},{"id":"native16_packed_64x128","priority":202,"when":["baseContract","tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" and tensorDtypes.Y == \"float16\"","not transAFlag","gemmM > 0 and gemmK > 0 and gemmN > 0","gemmK % 8 == 0 and gemmN % 8 == 0","packedBiasOk","attrs.alpha >= -340282346638528859811704183484516925440 and attrs.alpha <= 340282346638528859811704183484516925440 and (attrs.alpha <= -0.000000000000000000000000000000000000000000001401298464324817 or attrs.alpha >= 0.000000000000000000000000000000000000000000001401298464324817)","blackwellFixed32Subgroups","128 <= deviceWorkgroupCap","packedRectStorageBytes <= device.limits.maxComputeWorkgroupStorageSize","ceilDiv(gemmM, native16PackedBaseTile) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(gemmN, 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":{"M":"gemmM","N":"gemmN","K":"gemmK","registerTileM":"native16PackedBaseTile","registerTileN":"native16PackedWideTile","registerTileK":"native16PackedStageK","registerTransposeB":"transBFlag","registerAElement":"\"vec4<u32>\"","registerBElement":"\"vec4<u32>\"","registerSharedPad":"native16PackedSharedPad","registerPrefetch":true,"registerEpilogue":"\"activation\" if hasActivation else \"gemm\"","registerBiasMode":"packedBiasMode"},"passes":[{"id":"main","name":"FusedGemm.PackedRegister.64x128","shader":"fusedgemm-native16-packed-register.wgsl.jinja","bindings":[{"arg":"A","name":"a","elementType":"$registerAElement"},{"arg":"B","name":"b","elementType":"$registerBElement"},"packed_bias",{"arg":"Y","name":"y","elementType":"vec4<u32>"},"packed_params_plain","packed_params_bias"],"dispatch":{"x":"ceilDiv(N, registerTileN)","y":"ceilDiv(M, registerTileM)"}}],"demoteWhen":["not packedMeasuredPreference","not packedRectPreferred"]},{"id":"gemv","priority":200,"when":["gemmContract","gemmM == 1 and gemmN > 0 and gemmK > 0 and (transBFlag or gemvStoredColumns)","gemvWorkgroup * gemvColumns * 4 <= device.limits.maxComputeWorkgroupStorageSize"],"derive":{"hasBias":"present.C","workgroupSize":"gemvWorkgroup","inFeatures":"gemmK","outFeatures":"gemmN","xScalar":"\"f16\" if usesF16 else \"f32\"","wScalar":"\"f16\" if usesF16 else \"f32\"","yScalar":"\"f16\" if usesF16 else \"f32\"","gemvWeightElement":"\"vec4<f16>\" if gemvStoredColumns and gemmN % 4 == 0 else wScalar"},"passes":[{"id":"main","name":"FusedGemm.Gemv","shader":"gemv-contiguous.wgsl.jinja","bindings":["x",{"arg":"B","name":"w","elementType":"$gemvWeightElement"},"bias","y",{"name":"params","when":"not gemvUniformDims and not present.C","struct":[{"name":"alpha","type":"f32","value":"attrs.alpha"}]},{"name":"params","when":"not gemvUniformDims and present.C","struct":[{"name":"alpha","type":"f32","value":"attrs.alpha"},{"name":"beta","type":"f32","value":"attrs.beta"}]},{"name":"params","when":"gemvUniformDims and not present.C","struct":[{"name":"inner","type":"u32","value":"gemmK"},{"name":"columns","type":"u32","value":"gemmN"},{"name":"alpha","type":"f32","value":"attrs.alpha"}]},{"name":"params","when":"gemvUniformDims and present.C","struct":[{"name":"inner","type":"u32","value":"gemmK"},{"name":"columns","type":"u32","value":"gemmN"},{"name":"alpha","type":"f32","value":"attrs.alpha"},{"name":"beta","type":"f32","value":"attrs.beta"}]}],"dispatch":{"x":"min(gemvColumnGroups, DISPATCH_FOLD_WIDTH)","y":"1","z":"ceilDiv(gemvColumnGroups, DISPATCH_FOLD_WIDTH)"}}]},{"id":"sgmat","priority":100,"when":["sgmatContract","noBiasContract or (rowBiasOk and ranks.C == 1)","subgroupMatrix8F16Available if tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" else subgroupMatrix8F32Available"],"requires":{"features":["subgroups","chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs":[{"componentType":"f16","resultComponentType":"f32","M":8,"N":8,"K":8},{"componentType":"f32","resultComponentType":"f32","M":8,"N":8,"K":8}]},"derive":{"hasBias":"present.C","aTransposedStorage":"transAFlag","bTransposedStorage":"not transBFlag","yScalar":"\"f16\" if tensorDtypes.Y == \"float16\" else \"f32\"","mmaScalar":"\"f16\" if tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" else \"f32\"","inFeatures":"gemmK","outFeatures":"gemmN","tileM":"sgmatTileM","tileN":"sgmatTileN","tileK":"sgmatTileK","directAStorage":"sgmatDirectA","compensatedMatrixChunkTiles":"2 if sgmatDirectA and gemmK >= 8 * sgmatTileK else 0"},"passes":[{"id":"main","name":"FusedGemm.SubgroupMatrix","shader":"gemm-subgroup-matrix.wgsl.jinja","bindings":["x","w","bias","y","params"],"dispatch":{"x":"ceilDiv(gemmN, sgmatTileN)","y":"min(ceilDiv(gemmM, sgmatTileM), DISPATCH_FOLD_WIDTH)","z":"ceilDiv(ceilDiv(gemmM, sgmatTileM), DISPATCH_FOLD_WIDTH)"}}]},{"id":"vec4_tiled","priority":20,"when":["gemmContract","vecContract","vecSplitK == 1"],"demoteWhen":["not vecTilePreferred"],"derive":{"scalar":"\"f32\"","K":"gemmK","N":"gemmN","blockRows":"vecRows","kTile":"32 if vecStorageBytes <= device.limits.maxComputeWorkgroupStorageSize else 16","vec4BTile":"variableSubgroup16To32","physicalTransposedA":"transAFlag","physicalTransposedB":"transBFlag","hasBias":"present.C","biasMode":"vecBiasMode","biasBeta":true,"outputEpilogue":"gemmEpilogue"},"passes":[{"id":"main","name":"FusedGemm.Vec4TiledReg","shader":"matmul-notrans-vec4-tiled-reg.wgsl.jinja","bindings":[{"name":"a","arg":"A","elementType":"vec4<f32>"},{"name":"b","arg":"B","elementType":"vec4<f32>"},{"arg":"C","name":"bias","elementType":"$vecBiasElement","when":"present.C"},{"name":"y","arg":"Y","elementType":"vec4<f32>"},{"name":"params","when":"not present.C","struct":[{"name":"alpha","type":"f32","value":"vecAlpha"},{"name":"M","type":"u32","value":"gemmM"}]},{"name":"params","when":"present.C","struct":[{"name":"alpha","type":"f32","value":"vecAlpha"},{"name":"M","type":"u32","value":"gemmM"},{"name":"beta","type":"f32","value":"vecBeta"}]}],"dispatch":{"x":"ceilDiv(gemmN, 64)","y":"ceilDiv(gemmM, vecRows)"}}]},{"id":"vec4_splitk","priority":20,"when":["gemmContract","vecContract","vecSplitK >= 2","vecSplitK * gemmM * gemmN * 4 <= device.limits.maxStorageBufferBindingSize","vecSplitK <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)"],"demoteWhen":["not vecTilePreferred"],"derive":{"scalar":"\"f32\"","K":"gemmK","N":"gemmN","blockRows":"vecRows","kTile":"32 if vecStorageBytes <= device.limits.maxComputeWorkgroupStorageSize else 16","vec4BTile":"variableSubgroup16To32","physicalTransposedA":"transAFlag","physicalTransposedB":"transBFlag","hasBias":false,"splitK":"vecSplitK","kPerSplit":"gemmK / vecSplitK","split":"vecSplitK","workgroupSize":256},"intermediates":[{"id":"partials","dtype":"float32","shape":"[vecSplitK * gemmM * gemmN]"}],"passes":[{"id":"partial","name":"FusedGemm.Vec4SplitK","shader":"matmul-notrans-vec4-tiled-reg.wgsl.jinja","bindings":[{"name":"a","arg":"A","elementType":"vec4<f32>"},{"name":"b","arg":"B","elementType":"vec4<f32>"},{"scratch":"partials","name":"y","elementType":"vec4<f32>"},{"name":"params","struct":[{"name":"alpha","type":"f32","value":"vecAlpha"},{"name":"M","type":"u32","value":"gemmM"}]}],"dispatch":{"x":"ceilDiv(gemmN, 64)","y":"ceilDiv(gemmM, vecRows)","z":"vecSplitK"}},{"id":"combine","name":"FusedGemm.Vec4SplitKCombine","shader":"reduce-axis0-splitk-combine.wgsl.jinja","derive":{"op":"\"sum\"","addBias":"present.C","biasCols":"1 if vecBiasMode == \"scalar\" else (gemmM * gemmN if vecBiasMode == \"matrix\" else gemmN)","biasPerRow":"vecBiasMode == \"column\"","biasBeta":true,"outputEpilogue":"gemmEpilogue"},"bindings":[{"name":"partials","buffer":"read-only-storage","elementType":"f32"},{"arg":"C","name":"bias","elementType":"f32","when":"present.C"},{"name":"y","arg":"Y","elementType":"f32"},{"name":"params","when":"not present.C","struct":[{"name":"cols","type":"u32","value":"gemmM * gemmN"}]},{"name":"params","when":"present.C","struct":[{"name":"cols","type":"u32","value":"gemmM * gemmN"},{"name":"beta","type":"f32","value":"vecBeta"}]}],"dispatch":{"x":"min(ceilDiv((gemmM * gemmN), (256)), 65535)","y":"ceilDiv(ceilDiv((gemmM * gemmN), (256)), 65535)","z":1}}]},{"id":"tiled_reg","priority":0,"when":["gemmContract"],"derive":{"transA":"transAFlag","transB":"transBFlag","hasBias":"present.C","rowBias":"rowBiasOk","scalarBias":"scalarBiasOk","columnBias":"columnBiasOk"},"passes":[{"id":"main","name":"FusedGemm","shader":"gemm-epilogue-tiled-reg.wgsl.jinja","bindings":["a","b","bias","y",{"name":"params","when":"not present.C","struct":[{"name":"M","type":"u32","value":"gemmM"},{"name":"N","type":"u32","value":"gemmN"},{"name":"K","type":"u32","value":"gemmK"},{"name":"alpha","type":"f32","value":"attrs.alpha if has(attrs, \"alpha\") else 1"}]},{"name":"params","when":"present.C","struct":[{"name":"M","type":"u32","value":"gemmM"},{"name":"N","type":"u32","value":"gemmN"},{"name":"K","type":"u32","value":"gemmK"},{"name":"alpha","type":"f32","value":"attrs.alpha if has(attrs, \"alpha\") else 1"},{"name":"beta","type":"f32","value":"attrs.beta if has(attrs, \"beta\") else 1"}]}],"dispatch":{"x":"min(ceilDiv(gemmN, 64), min(device.limits.maxComputeWorkgroupsPerDimension, 65535))","y":"min(ceilDiv(gemmM, 64), min(device.limits.maxComputeWorkgroupsPerDimension, 65535))"}}]},{"id":"subgroup_matrix_16x16x16","priority":-1000,"demoteWhen":["true"],"when":["baseContract","attrs.alpha != 0","not present.C or attrs.beta != 0","tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" and tensorDtypes.Y == \"float16\"","not present.C or (tensorDtypes.C == \"float16\" and (scalarBiasOk or rowBiasOk))","(gemmM) > 0 and (gemmN) > 0 and (gemmK) > 0","ceilDiv((gemmM), 32) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv((gemmN), 32) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","(1) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","128 <= device.limits.maxComputeInvocationsPerWorkgroup","128 <= device.limits.maxComputeWorkgroupSizeX","8240 <= device.limits.maxComputeWorkgroupStorageSize","has(device.adapterInfo, \"subgroupMatrixConfigs\") and subgroupMatrixConfigAvailable(\"f16\", \"f32\", 16, 16, 16)","matrixSubgroupWidth > 0","attrs.alpha >= -340282346638528859811704183484516925440 and attrs.alpha <= 340282346638528859811704183484516925440 and (attrs.alpha <= -0.000000000000000000000000000000000000000000001401298464324817 or attrs.alpha >= 0.000000000000000000000000000000000000000000001401298464324817)","not present.C or (attrs.beta >= -340282346638528859811704183484516925440 and attrs.beta <= 340282346638528859811704183484516925440 and (attrs.beta <= -0.000000000000000000000000000000000000000000001401298464324817 or attrs.beta >= 0.000000000000000000000000000000000000000000001401298464324817))"],"requires":{"features":["shader-f16","subgroups","chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs":[{"componentType":"f16","resultComponentType":"f32","M":16,"N":16,"K":16}]},"derive":{"M":"gemmM","N":"gemmN","K":"gemmK","matrixM":16,"matrixN":16,"matrixK":16,"operandScalar":"\"f16\"","accumulatorScalar":"\"f32\"","outputScalar":"dtypes.T","matrixAOffset":0,"matrixBOffset":0,"matrixARowStride":"1 if transAFlag else gemmK","matrixAKStride":"gemmM if transAFlag else 1","matrixBKStride":"1 if transBFlag else gemmN","matrixBColStride":"gemmK if transBFlag else 1","matrixYStride":"gemmN","matrixYColumnOffset":0,"matrixAlpha":"attrs.alpha if has(attrs, \"alpha\") else 1","matrixBiasMode":"\"none\" if not present.C else \"scalar\" if scalarBiasOk else \"row\"","matrixEpilogue":"\"activation\"","matrixBeta":"attrs.beta if has(attrs, \"beta\") else 1","gemmActivation":"activationName","gemmActAlpha":"activationAlpha","gemmActBeta":"activationBeta"},"passes":[{"id":"main","name":"SubgroupMatrix16x16x16","shader":"matrix-shaped-projection-gemm.wgsl.jinja","bindings":[{"arg":"A","name":"a","elementType":"f16"},{"arg":"B","name":"b","elementType":"f16"},{"arg":"C","name":"bias","elementType":"f16","when":"present.C"},{"arg":"Y","name":"y","elementType":"f16"}],"dispatch":{"x":"ceilDiv(N, 32)","y":"ceilDiv(M, 32)","z":"1"}}]},{"id":"subgroup_matrix_16x16x16_m_bias","priority":-1000,"demoteWhen":["true"],"when":["baseContract","attrs.alpha != 0","not present.C or attrs.beta != 0","tensorDtypes.A == \"float16\" and tensorDtypes.B == \"float16\" and tensorDtypes.Y == \"float16\"","tensorDtypes.C == \"float16\" and (columnBiasOk or matrixBiasOk)","(gemmM) > 0 and (gemmN) > 0 and (gemmK) > 0","ceilDiv((gemmM), 32) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv((gemmN), 32) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","(1) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","128 <= device.limits.maxComputeInvocationsPerWorkgroup","128 <= device.limits.maxComputeWorkgroupSizeX","8240 <= device.limits.maxComputeWorkgroupStorageSize","has(device.adapterInfo, \"subgroupMatrixConfigs\") and subgroupMatrixConfigAvailable(\"f16\", \"f32\", 16, 16, 16)","matrixSubgroupWidth > 0","attrs.alpha >= -340282346638528859811704183484516925440 and attrs.alpha <= 340282346638528859811704183484516925440 and (attrs.alpha <= -0.000000000000000000000000000000000000000000001401298464324817 or attrs.alpha >= 0.000000000000000000000000000000000000000000001401298464324817)","not present.C or (attrs.beta >= -340282346638528859811704183484516925440 and attrs.beta <= 340282346638528859811704183484516925440 and (attrs.beta <= -0.000000000000000000000000000000000000000000001401298464324817 or attrs.beta >= 0.000000000000000000000000000000000000000000001401298464324817))"],"requires":{"features":["shader-f16","subgroups","chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs":[{"componentType":"f16","resultComponentType":"f32","M":16,"N":16,"K":16}]},"derive":{"M":"gemmM","N":"gemmN","K":"gemmK","matrixM":16,"matrixN":16,"matrixK":16,"operandScalar":"\"f16\"","accumulatorScalar":"\"f32\"","outputScalar":"dtypes.T","matrixAOffset":0,"matrixBOffset":0,"matrixARowStride":"1 if transAFlag else gemmK","matrixAKStride":"gemmM if transAFlag else 1","matrixBKStride":"1 if transBFlag else gemmN","matrixBColStride":"gemmK if transBFlag else 1","matrixYStride":"gemmN","matrixYColumnOffset":0,"matrixAlpha":"attrs.alpha if has(attrs, \"alpha\") else 1","matrixBiasMode":"\"column\" if columnBiasOk else \"matrix\"","matrixEpilogue":"\"activation\"","matrixBeta":"attrs.beta if has(attrs, \"beta\") else 1","gemmActivation":"activationName","gemmActAlpha":"activationAlpha","gemmActBeta":"activationBeta"},"passes":[{"id":"main","name":"SubgroupMatrix16x16x16","shader":"matrix-shaped-projection-gemm.wgsl.jinja","bindings":[{"arg":"A","name":"a","elementType":"f16"},{"arg":"B","name":"b","elementType":"f16"},{"arg":"C","name":"bias","elementType":"f16","when":"present.C"},{"arg":"Y","name":"y","elementType":"f16"}],"dispatch":{"x":"ceilDiv(N, 32)","y":"ceilDiv(M, 32)","z":"1"}}]}],"tunables":{"VEC4_SPLITK_TARGET_WORKGROUPS":{"default":512},"VEC4_TALL_TILE_MIN_BLOCKS":{"default":64}}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351{% set exactIntegerPartialsValue = false %}{% set preparedNValue = 0 %}{{ env.wgsl.resourceDeclarations }}{% set kTileValue = kTile %}{% set blockRowsValue = blockRows if blockRows is defined else 128 %}{% set blockColsValue = 64 %}{% set outputScalarValue = "f32" %}{% set accumulatorScalarValue = "f32" %}{% set workgroupColsValue = 16 %}{% set workgroupRowsValue = 16 %}{% set laneCount = 256 %}{% set threadRows = (blockRowsValue / workgroupRowsValue)|int %}{% set threadColVectors = 1 %}{% set threadCols = 4 %}{% set aVectorCount = (blockRowsValue * kTileValue / (4 * laneCount))|int %}{% set bVectorCount = (kTileValue * blockColsValue / (4 * laneCount))|int %}{% set physicalTransposedBValue = physicalTransposedB if physicalTransposedB is defined else false %}{% set vec4WordTilesValue = env.device.adapterInfo.vendor == "qualcomm" and (env.device.adapterInfo.architecture == "adreno-6xx" or env.device.adapterInfo.architecture == "adreno-7xx") %}{% set vec4BTileValue = ((vec4BTile if vec4BTile is defined else false) or vec4WordTilesValue) and not physicalTransposedBValue %}{% set transposedVec4BTileValue = vec4WordTilesValue and physicalTransposedBValue %}{% set physicalTransposedAValue = physicalTransposedA if physicalTransposedA is defined else false %}{% set batchStridesValue = false %}{% set splitKValue = splitK if splitK is defined else 1 %}{% set kPerSplitValue = kPerSplit if kPerSplit is defined else 0 %}{% set outputEpilogueValue = outputEpilogue | default("none") %}{% set accName = "acc" %}{% set biasModeValue = biasMode | default("row") %}{% set biasBetaValue = biasBeta is defined and biasBeta %}{% set raggedShapeValue = false %}
// High-intensity matrix multiplication:// Y[M,N] = alpha * A[M,K] @ B[K,N].// A may be stored physically as [K,M], and B as [N,K]; a [N,K] B keeps vec4// K loads and transposes only while staging the tile in workgroup memory.//// Unless the shape is ragged, both inputs and the output are four-wide along// their contiguous dimension.// The output-tile geometry and BK are selected from the shape and device's// workgroup-storage limit. f16 operands stay packed in global and workgroup// memory, then widen at the FMA so accumulation remains f32.const K: u32 = {{ K }}u;const N: u32 = {{ N }}u;{% if (not physicalTransposedAValue or physicalTransposedBValue) and not raggedShapeValue %}const K_V4: u32 = K / 4u;{% endif %}const N_V4: u32 = N / 4u;const BK: u32 = {{ kTileValue }}u;const BM: u32 = {{ blockRowsValue }}u;const BN: u32 = {{ blockColsValue }}u;const TM: u32 = {{ threadRows }}u;const TN: u32 = {{ threadCols }}u;{% if splitKValue > 1 %}const KPS: u32 = {{ kPerSplitValue }}u;{% endif %}{% if outputEpilogueValue == "fastgelu" %}
fn tanh_safe(x: f32) -> f32 { // tanh rounds to its saturated value for these tails in f32. Return that // value directly, including for infinite input, before invoking the builtin. if (x > 10.0) { return 1.0; } if (x < -10.0) { return -1.0; } // For tiny |x|, return x directly to preserve its sign and magnitude without // relying on backend-specific builtin behavior near zero. if (x > -1.0e-4 && x < 1.0e-4) { return x; } return tanh(x);}
fn gelu_tanh(v: f32) -> f32 { return 0.5 * v * (1.0 + tanh_safe(0.7978845608028654 * (v + 0.044715 * v * v * v)));}
fn output_epilogue(v: vec4<f32>) -> vec4<f32> { return vec4<f32>(gelu_tanh(v.x), gelu_tanh(v.y), gelu_tanh(v.z), gelu_tanh(v.w));}{% elif outputEpilogueValue == "activation" %}
{% set actMode = gemmActivation | default("") %}{% set actA = gemmActAlpha | default(0.0) %}{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "" %} return v;{% elif mode == "Relu" %} let bits = bitcast<u32>(v); return bitcast<f32>(select(0u, bits, (bits & 0x80000000u) == 0u || (bits & 0x7fffffffu) > 0x7f800000u));{% elif mode == "Clip" %} return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %} return select(v * f32({{ alpha }}), v, v >= 0.0);{% elif mode == "Sigmoid" %} return 1.0 / (1.0 + exp(-v));{% elif mode == "Tanh" %} // tanh is already +/-1 to f32 precision at the clamp bounds. Clamping before // the builtin preserves that saturated result for larger accumulators. return tanh(clamp(v, -10.0, 10.0));{% elif mode == "HardSigmoid" %} return clamp(f32({{ alpha }}) * v + f32({{ beta }}), 0.0, 1.0);{% elif mode == "QuickGelu" %}{% if alpha == 1 %} // alpha == 1 is SiLU: the multiply folds away (the spelling yolov8-class detectors emit). return v * (1.0 / (1.0 + exp(-v)));{% else %} return v * (1.0 / (1.0 + exp(-(f32({{ alpha }}) * v))));{% endif %}{% elif mode == "Elu" %} return select(f32({{ alpha }}) * (exp(v) - 1.0), v, v >= 0.0);{% elif mode == "ThresholdedRelu" %} return select(0.0, v, v > f32({{ alpha }}));{% elif mode == "Softplus" %} // log(1 + exp(v)) spelled overflow-safe: max(v, 0) + log(1 + exp(-|v|)). return max(v, 0.0) + log(1.0 + exp(-abs(v)));{% elif mode == "Erf" %} // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7), the same polynomial the standalone // Erf/Gelu kernels use, so a fused and an unfused graph agree to f32 rounding. let a = abs(v); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return sign(v) * (1.0 - poly * exp(-a * a));{% elif mode == "Gelu" and alpha == 0 %} // ONNX Gelu, erf form: 0.5 * v * (1 + erf(v / sqrt(2))); activation_params[0] == 0. let u = v * 0.70710678118654752; let a = abs(u); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return 0.5 * v * (1.0 + sign(u) * (1.0 - poly * exp(-a * a)));{% elif mode == "Gelu" or mode == "FastGelu" %} // tanh approximation (ONNX Gelu approximate="tanh" arrives as activation_params[0] != 0; // com.microsoft.FastGelu always). tanh saturates to +/-1 well inside the clamp. let inner = v * (0.035677408136300125 * v * v + 0.7978845608028654); return v * (0.5 + 0.5 * tanh(clamp(inner, -10.0, 10.0)));{% else %} return v * clamp(v * 0.16666666666666666 + 0.5, 0.0, 1.0);{% endif %}}{% endmacro %}{{ fused_act_fn(actMode, actA, actB) }}
fn output_epilogue(v: vec4<f32>) -> vec4<f32> { return vec4<f32>(fused_act(v.x), fused_act(v.y), fused_act(v.z), fused_act(v.w));}{% endif %}
// A is loaded and consumed four K values at a time. Keeping that packing in// workgroup memory reduces A-side shared-memory instructions and inner-loop// control without changing the four scalar FMA operations or their order.var<workgroup> tileA: array<array<vec4<{{ scalar }}>, BK / 4u>, BM>;{% if vec4BTileValue %}var<workgroup> tileB: array<vec4<{{ scalar }}>, BK * (BN / 4u)>;{% elif transposedVec4BTileValue %}// B keeps its four-wide K words: tileB[k / 4][n].var<workgroup> tileB: array<array<vec4<{{ scalar }}>, BN>, BK / 4u>;{% else %}var<workgroup> tileB: array<array<{{ scalar }}, BN + 1u>, BK>;{% endif %}
@compute @workgroup_size({{ workgroupColsValue }}, {{ workgroupRowsValue }}, 1)fn main( @builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) { let M = params.M;{% if physicalTransposedAValue and not raggedShapeValue %} let M_V4 = M >> 2u;{% endif %} let li = lid.y * {{ workgroupColsValue }}u + lid.x; let mBase = wg.y * BM; let nBase = wg.x * BN;{% if splitKValue > 1 %} let kSplitBase = wg.z * KPS; let ySplit = wg.z * M * N_V4;{% endif %}{% set aOff = "" %}{% set bOff = "" %}{% set yOff = "yBatch + " if batchStridesValue else ("ySplit + " if splitKValue > 1 else "") %}
{% for i in range(threadRows) %}{% for j in range(threadColVectors) %} var acc{{ i }}_{{ j }} = vec4<{{ accumulatorScalarValue }}>(0.0);{% endfor %}{% endfor %}
{% if splitKValue > 1 %} for (var kBase: u32 = kSplitBase; kBase < kSplitBase + KPS; kBase = kBase + BK) {{% else %} for (var kBase: u32 = 0u; kBase < K; kBase = kBase + BK) {{% endif %}{% if physicalTransposedAValue %}{% set aBlockCount = ((blockRowsValue / 4) * (kTileValue / 4))|int %}{% for ab in range(((aBlockCount + laneCount - 1) / laneCount)|int) %} // A stored [K, M]: a 4x4 block is four M-contiguous words at consecutive K, // transposed in registers into four packed K words of the tile. let aBlock{{ ab }} = li + {{ ab * laneCount }}u; if (aBlock{{ ab }} < {{ aBlockCount }}u) { let aRowV4_{{ ab }} = aBlock{{ ab }} / (BK / 4u); let aColV4_{{ ab }} = aBlock{{ ab }} % (BK / 4u); let am4_{{ ab }} = mBase / 4u + aRowV4_{{ ab }}; var ar0_{{ ab }} = vec4<{{ scalar }}>({{ scalar }}(0)); var ar1_{{ ab }} = vec4<{{ scalar }}>({{ scalar }}(0)); var ar2_{{ ab }} = vec4<{{ scalar }}>({{ scalar }}(0)); var ar3_{{ ab }} = vec4<{{ scalar }}>({{ scalar }}(0)); if (am4_{{ ab }} < M_V4) { let ak{{ ab }} = kBase + aColV4_{{ ab }} * 4u; ar0_{{ ab }} = a[{{ aOff }}(ak{{ ab }} + 0u) * M_V4 + am4_{{ ab }}]; ar1_{{ ab }} = a[{{ aOff }}(ak{{ ab }} + 1u) * M_V4 + am4_{{ ab }}]; ar2_{{ ab }} = a[{{ aOff }}(ak{{ ab }} + 2u) * M_V4 + am4_{{ ab }}]; ar3_{{ ab }} = a[{{ aOff }}(ak{{ ab }} + 3u) * M_V4 + am4_{{ ab }}]; } tileA[aRowV4_{{ ab }} * 4u + 0u][aColV4_{{ ab }}] = vec4<{{ scalar }}>(ar0_{{ ab }}.x, ar1_{{ ab }}.x, ar2_{{ ab }}.x, ar3_{{ ab }}.x); tileA[aRowV4_{{ ab }} * 4u + 1u][aColV4_{{ ab }}] = vec4<{{ scalar }}>(ar0_{{ ab }}.y, ar1_{{ ab }}.y, ar2_{{ ab }}.y, ar3_{{ ab }}.y); tileA[aRowV4_{{ ab }} * 4u + 2u][aColV4_{{ ab }}] = vec4<{{ scalar }}>(ar0_{{ ab }}.z, ar1_{{ ab }}.z, ar2_{{ ab }}.z, ar3_{{ ab }}.z); tileA[aRowV4_{{ ab }} * 4u + 3u][aColV4_{{ ab }}] = vec4<{{ scalar }}>(ar0_{{ ab }}.w, ar1_{{ ab }}.w, ar2_{{ ab }}.w, ar3_{{ ab }}.w); }{% endfor %}{% else %}{% for av in range(aVectorCount) %} let aVector{{ av }} = li + {{ av * laneCount }}u; let aRow{{ av }} = aVector{{ av }} / (BK / 4u); let aColV4_{{ av }} = aVector{{ av }} % (BK / 4u); let am{{ av }} = mBase + aRow{{ av }}; var av4_{{ av }} = vec4<{{ scalar }}>({{ scalar }}(0)); if (am{{ av }} < M) { av4_{{ av }} = a[{{ aOff }}am{{ av }} * K_V4 + kBase / 4u + aColV4_{{ av }}]; } tileA[aRow{{ av }}][aColV4_{{ av }}] = av4_{{ av }};{% endfor %}{% endif %}{% for bv in range(bVectorCount) %} let bVector{{ bv }} = li + {{ bv * laneCount }}u;{% if physicalTransposedBValue %} let bNRow{{ bv }} = bVector{{ bv }} / (BK / 4u); let bKColV4_{{ bv }} = bVector{{ bv }} % (BK / 4u); let bn{{ bv }} = nBase + bNRow{{ bv }}; var bv4_{{ bv }} = vec4<{{ scalar }}>({{ scalar }}(0)); if (bn{{ bv }} < N) { bv4_{{ bv }} = b[{{ bOff }}bn{{ bv }} * K_V4 + kBase / 4u + bKColV4_{{ bv }}]; }{% if transposedVec4BTileValue %} tileB[bKColV4_{{ bv }}][bNRow{{ bv }}] = bv4_{{ bv }};{% else %} tileB[bKColV4_{{ bv }} * 4u + 0u][bNRow{{ bv }}] = bv4_{{ bv }}.x; tileB[bKColV4_{{ bv }} * 4u + 1u][bNRow{{ bv }}] = bv4_{{ bv }}.y; tileB[bKColV4_{{ bv }} * 4u + 2u][bNRow{{ bv }}] = bv4_{{ bv }}.z; tileB[bKColV4_{{ bv }} * 4u + 3u][bNRow{{ bv }}] = bv4_{{ bv }}.w;{% endif %}{% else %} let bRow{{ bv }} = bVector{{ bv }} / (BN / 4u); let bColV4_{{ bv }} = bVector{{ bv }} % (BN / 4u); let bn{{ bv }} = nBase + bColV4_{{ bv }} * 4u; var bv4_{{ bv }} = vec4<{{ scalar }}>({{ scalar }}(0)); if (bn{{ bv }} < {{ (preparedNValue ~ "u") if exactIntegerPartialsValue and preparedNValue != N else "N" }}) { bv4_{{ bv }} = b[{{ bOff }}(kBase + bRow{{ bv }}) * {{ "B_N_V4" if exactIntegerPartialsValue else "N_V4" }} + bn{{ bv }} / 4u]; }{% if vec4BTileValue %} tileB[bRow{{ bv }} * (BN / 4u) + bColV4_{{ bv }}] = bv4_{{ bv }};{% else %} tileB[bRow{{ bv }}][bColV4_{{ bv }} * 4u + 0u] = bv4_{{ bv }}.x; tileB[bRow{{ bv }}][bColV4_{{ bv }} * 4u + 1u] = bv4_{{ bv }}.y; tileB[bRow{{ bv }}][bColV4_{{ bv }} * 4u + 2u] = bv4_{{ bv }}.z; tileB[bRow{{ bv }}][bColV4_{{ bv }} * 4u + 3u] = bv4_{{ bv }}.w;{% endif %}{% endif %}{% endfor %} workgroupBarrier();
let aRow = lid.y * TM;{% if vec4BTileValue %} let bCol4 = lid.x * {{ threadColVectors }}u; for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) { let kk = kv * 4u;{% for j in range(threadColVectors) %} let bv0_{{ j }} = vec4<{{ accumulatorScalarValue }}>(tileB[(kk + 0u) * (BN / 4u) + bCol4 + {{ j }}u]); let bv1_{{ j }} = vec4<{{ accumulatorScalarValue }}>(tileB[(kk + 1u) * (BN / 4u) + bCol4 + {{ j }}u]); let bv2_{{ j }} = vec4<{{ accumulatorScalarValue }}>(tileB[(kk + 2u) * (BN / 4u) + bCol4 + {{ j }}u]); let bv3_{{ j }} = vec4<{{ accumulatorScalarValue }}>(tileB[(kk + 3u) * (BN / 4u) + bCol4 + {{ j }}u]);{% endfor %}{% for i in range(threadRows) %} let av{{ i }} = tileA[aRow + {{ i }}u][kv];{% for j in range(threadColVectors) %} {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.x)) * bv0_{{ j }}; {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.y)) * bv1_{{ j }}; {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.z)) * bv2_{{ j }}; {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.w)) * bv3_{{ j }};{% endfor %}{% endfor %} }{% else %} let bCol = lid.x * TN; for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {{% if transposedVec4BTileValue %}{% set widen = "vec4<f32>" %}{% set widenClose = "" %} // Four columns' K words; component c of each is K row kv * 4 + c.{% for j in range(threadColVectors) %} let bw0_{{ j }} = tileB[kv][bCol + {{ j * 4 + 0 }}u]; let bw1_{{ j }} = tileB[kv][bCol + {{ j * 4 + 1 }}u]; let bw2_{{ j }} = tileB[kv][bCol + {{ j * 4 + 2 }}u]; let bw3_{{ j }} = tileB[kv][bCol + {{ j * 4 + 3 }}u]; let bv0_{{ j }} = {{ widen }}(bw0_{{ j }}.x, bw1_{{ j }}.x, bw2_{{ j }}.x, bw3_{{ j }}.x){{ widenClose }}; let bv1_{{ j }} = {{ widen }}(bw0_{{ j }}.y, bw1_{{ j }}.y, bw2_{{ j }}.y, bw3_{{ j }}.y){{ widenClose }}; let bv2_{{ j }} = {{ widen }}(bw0_{{ j }}.z, bw1_{{ j }}.z, bw2_{{ j }}.z, bw3_{{ j }}.z){{ widenClose }}; let bv3_{{ j }} = {{ widen }}(bw0_{{ j }}.w, bw1_{{ j }}.w, bw2_{{ j }}.w, bw3_{{ j }}.w){{ widenClose }};{% endfor %}{% else %} let kk = kv * 4u;{% for j in range(threadColVectors) %} let bv0_{{ j }} = vec4<{{ accumulatorScalarValue }}>( {{ accumulatorScalarValue }}(tileB[kk + 0u][bCol + {{ j * 4 + 0 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 0u][bCol + {{ j * 4 + 1 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 0u][bCol + {{ j * 4 + 2 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 0u][bCol + {{ j * 4 + 3 }}u]) ); let bv1_{{ j }} = vec4<{{ accumulatorScalarValue }}>( {{ accumulatorScalarValue }}(tileB[kk + 1u][bCol + {{ j * 4 + 0 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 1u][bCol + {{ j * 4 + 1 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 1u][bCol + {{ j * 4 + 2 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 1u][bCol + {{ j * 4 + 3 }}u]) ); let bv2_{{ j }} = vec4<{{ accumulatorScalarValue }}>( {{ accumulatorScalarValue }}(tileB[kk + 2u][bCol + {{ j * 4 + 0 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 2u][bCol + {{ j * 4 + 1 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 2u][bCol + {{ j * 4 + 2 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 2u][bCol + {{ j * 4 + 3 }}u]) ); let bv3_{{ j }} = vec4<{{ accumulatorScalarValue }}>( {{ accumulatorScalarValue }}(tileB[kk + 3u][bCol + {{ j * 4 + 0 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 3u][bCol + {{ j * 4 + 1 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 3u][bCol + {{ j * 4 + 2 }}u]), {{ accumulatorScalarValue }}(tileB[kk + 3u][bCol + {{ j * 4 + 3 }}u]) );{% endfor %}{% endif %}{% for i in range(threadRows) %} let av{{ i }} = tileA[aRow + {{ i }}u][kv];{% for j in range(threadColVectors) %} {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.x)) * bv0_{{ j }}; {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.y)) * bv1_{{ j }}; {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.z)) * bv2_{{ j }}; {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.w)) * bv3_{{ j }};{% endfor %}{% endfor %} }{% endif %} workgroupBarrier(); }
let m0 = mBase + lid.y * TM;{% for j in range(threadColVectors) %} let n{{ j }} = nBase + lid.x * TN + {{ j * 4 }}u;{% endfor %}{% for i in range(threadRows) %}{% for j in range(threadColVectors) %} if (m0 + {{ i }}u < M && n{{ j }} < N) { y[{{ yOff }}(m0 + {{ i }}u) * N_V4 + n{{ j }} / 4u] = vec4<{{ outputScalarValue }}>({% if outputEpilogueValue != "none" %}output_epilogue({% endif %}select( vec4<f32>(acc{{ i }}_{{ j }}) * vec4<f32>(params.alpha), vec4<f32>(0.0), params.alpha == 0.0 ){% if hasBias is defined and hasBias %}{% if biasModeValue == "scalar" %}{% set biasWord = "vec4<f32>(f32(bias[0u]))" %}{% elif biasModeValue == "column" %}{% set biasWord = "vec4<f32>(f32(bias[m0 + " ~ i ~ "u]))" %}{% elif biasModeValue == "matrix" %}{% set biasWord = "vec4<f32>(bias[(m0 + " ~ i ~ "u) * N_V4 + n" ~ j ~ " / 4u])" %}{% else %}{% set biasWord = "vec4<f32>(bias[n" ~ j ~ " / 4u])" %}{% endif %} + {% if biasBetaValue %}select({{ biasWord }} * vec4<f32>(params.beta), vec4<f32>(0.0), params.beta == 0.0){% else %}{{ biasWord }}{% endif %}{% endif %}{% if outputEpilogueValue != "none" %}){% endif %}); }{% endfor %}{% endfor %}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243{% set WIDTH = matrixSubgroupWidth | default(32) %}{% set GROUPS = (128 / WIDTH) | int %}{% set OWNED = (WIDTH / 32) | int %}{% set STAGE_K = 32 %}{% set CELLS_PER_THREAD = 8 %}enable subgroups;enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{{ env.wgsl.resourceDeclarations }}const M: u32 = {{ M }}u;const N: u32 = {{ N }}u;const K: u32 = {{ K }}u;const TILE_M: u32 = {{ matrixM * 2 }}u;const TILE_N: u32 = {{ matrixN * 2 }}u;const TILE_K: u32 = {{ STAGE_K }}u;var<workgroup> tileA: array<{{ operandScalar }}, {{ matrixM * 2 * STAGE_K }}>;var<workgroup> tileB: array<{{ operandScalar }}, {{ STAGE_K * matrixN * 2 }}>;var<workgroup> tileC: array<{{ accumulatorScalar }}, {{ matrixM * 2 * matrixN * 2 }}>;
{% if (hasActivation | default(false)) %}{% set actMode = gemmActivation | default("") %}{% set actA = gemmActAlpha | default(0.0) %}{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "" %} return v;{% elif mode == "Relu" %} let bits = bitcast<u32>(v); return bitcast<f32>(select(0u, bits, (bits & 0x80000000u) == 0u || (bits & 0x7fffffffu) > 0x7f800000u));{% elif mode == "Clip" %} return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %} return select(v * f32({{ alpha }}), v, v >= 0.0);{% elif mode == "Sigmoid" %} return 1.0 / (1.0 + exp(-v));{% elif mode == "Tanh" %} // tanh is already +/-1 to f32 precision at the clamp bounds. Clamping before // the builtin preserves that saturated result for larger accumulators. return tanh(clamp(v, -10.0, 10.0));{% elif mode == "HardSigmoid" %} return clamp(f32({{ alpha }}) * v + f32({{ beta }}), 0.0, 1.0);{% elif mode == "QuickGelu" %}{% if alpha == 1 %} // alpha == 1 is SiLU: the multiply folds away (the spelling yolov8-class detectors emit). return v * (1.0 / (1.0 + exp(-v)));{% else %} return v * (1.0 / (1.0 + exp(-(f32({{ alpha }}) * v))));{% endif %}{% elif mode == "Elu" %} return select(f32({{ alpha }}) * (exp(v) - 1.0), v, v >= 0.0);{% elif mode == "ThresholdedRelu" %} return select(0.0, v, v > f32({{ alpha }}));{% elif mode == "Softplus" %} // log(1 + exp(v)) spelled overflow-safe: max(v, 0) + log(1 + exp(-|v|)). return max(v, 0.0) + log(1.0 + exp(-abs(v)));{% elif mode == "Erf" %} // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7), the same polynomial the standalone // Erf/Gelu kernels use, so a fused and an unfused graph agree to f32 rounding. let a = abs(v); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return sign(v) * (1.0 - poly * exp(-a * a));{% elif mode == "Gelu" and alpha == 0 %} // ONNX Gelu, erf form: 0.5 * v * (1 + erf(v / sqrt(2))); activation_params[0] == 0. let u = v * 0.70710678118654752; let a = abs(u); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return 0.5 * v * (1.0 + sign(u) * (1.0 - poly * exp(-a * a)));{% elif mode == "Gelu" or mode == "FastGelu" %} // tanh approximation (ONNX Gelu approximate="tanh" arrives as activation_params[0] != 0; // com.microsoft.FastGelu always). tanh saturates to +/-1 well inside the clamp. let inner = v * (0.035677408136300125 * v * v + 0.7978845608028654); return v * (0.5 + 0.5 * tanh(clamp(inner, -10.0, 10.0)));{% else %} return v * clamp(v * 0.16666666666666666 + 0.5, 0.0, 1.0);{% endif %}}{% endmacro %}{{ fused_act_fn(actMode, actA, actB) }}{% endif %}{% macro shapedLoadA( row, k, supertonicPartial=matrixSupertonicPartial | default(false), qatGrouped=matrixQatGrouped | default(false), aOffset=matrixAOffset | default(none), aRowStride=matrixARowStride | default(none), aKStride=matrixAKStride | default(none), batch1=matrixBatch1 | default(none), aBatch0Stride=matrixABatch0Stride | default(none), aBatch1Stride=matrixABatch1Stride | default(none)) %}a[{{ aOffset }}u + {{ row }} * {{ aRowStride }}u + {{ k }} * {{ aKStride }}u]{%endmacro %}{% macro shapedLoadB( k, col, bOffset=matrixBOffset | default(none), repeatB=matrixRepeatB | default(none), bKStride=matrixBKStride | default(none), bColStride=matrixBColStride | default(none), batch1=matrixBatch1 | default(none), bBatch0Stride=matrixBBatch0Stride | default(none), bBatch1Stride=matrixBBatch1Stride | default(none)) %}b[{{ bOffset }}u + {{ k }} * {{ bKStride }}u + {{ col }} * {{ bColStride }}u]{%endmacro %}{% macro shapedWrite( value, row, col, beta=matrixBeta | default(none), groups=matrixGroups | default(none), qatGrouped=matrixQatGrouped | default(false), yStride=matrixYStride | default(none), yColumnOffset=matrixYColumnOffset | default(none), batch1=matrixBatch1 | default(none), yBatch1Stride=matrixYBatch1Stride | default(none), yBatchStride=matrixYBatchStride | default(none)) %}{ var result = f32({{ matrixAlpha }}) * f32({{ value }});{% if matrixBiasMode != "none" %} result += f32({{ beta }}) * f32(bias[{% if matrixBiasMode == "row" %}{{ col }}{% elif matrixBiasMode == "column" %}{{ row }}{% elif matrixBiasMode == "matrix" %}{{ row }} * N + {{ col }}{% else %}0u{% endif %}]);{% endif %}{% if (matrixEpilogue == "activation" and (hasActivation | default(false))) %} result = fused_act(result);{% endif %}
y[{{ row }} * {{ yStride }}u + {{ col }} + {{ yColumnOffset }}u] = {{ outputScalar }}(result);}{% endmacro %}fn loadTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) { for (var flat = tid; flat < TILE_M * TILE_K; flat += 128u) { let row = rowBase + flat / TILE_K; let k = kBase + flat % TILE_K; var value = {{ operandScalar }}(0); if (row < M && k < K) { value = {{ operandScalar }}({{ shapedLoadA("row", "k") }}); } tileA[flat] = value; } for (var flat = tid; flat < TILE_K * TILE_N; flat += 128u) { let k = kBase + flat / TILE_N; let col = colBase + flat % TILE_N; var value = {{ operandScalar }}(0); if (k < K && col < N) { value = {{ operandScalar }}({{ shapedLoadB("k", "col") }}); } tileB[flat] = value; }}
// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}@compute @workgroup_size(128, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32) { let rowBase = wid.y * TILE_M; let colBase = wid.x * TILE_N; let role = claimMatrixSubgroupRole(width, {{ WIDTH }}u); let nativeTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u); if (nativeTopology) {{% for slot in range(OWNED) %} let tile{{ slot }} = role + {{ slot * GROUPS }}u; let row{{ slot }} = (tile{{ slot }} / 2u) * {{ matrixM }}u; let col{{ slot }} = (tile{{ slot }} % 2u) * {{ matrixN }}u; var acc{{ slot }}: subgroup_matrix_result<{{ accumulatorScalar }}, {{ matrixN }}, {{ matrixM }}>;{% endfor %} for (var kk = 0u; kk < K; kk += TILE_K) { loadTiles(rowBase, colBase, kk, tid); workgroupBarrier(); for (var step = 0u; step < TILE_K; step += {{ matrixK }}u) {{% for slot in range(OWNED) %} let left{{ slot }} = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, {{ matrixK }}, {{ matrixM }}>, row_major>( &tileA, row{{ slot }} * TILE_K + step, TILE_K); let right{{ slot }} = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, {{ matrixN }}, {{ matrixK }}>, row_major>( &tileB, step * TILE_N + col{{ slot }}, TILE_N); acc{{ slot }} = subgroupMatrixMultiplyAccumulate(left{{ slot }}, right{{ slot }}, acc{{ slot }});{% endfor %} } workgroupBarrier(); }{% for slot in range(OWNED) %} subgroupMatrixStore<row_major>(&tileC, row{{ slot }} * TILE_N + col{{ slot }}, acc{{ slot }}, TILE_N);{% endfor %} workgroupBarrier(); for (var flat = tid; flat < TILE_M * TILE_N; flat += 128u) { let r = rowBase + flat / TILE_N; let c = colBase + flat % TILE_N; if (r < M && c < N) { {{ shapedWrite("tileC[flat]", "r", "c") }} } } } else { var acc: array<{{ accumulatorScalar }}, {{ CELLS_PER_THREAD }}>; for (var kk = 0u; kk < K; kk += TILE_K) { loadTiles(rowBase, colBase, kk, tid); workgroupBarrier(); for (var cell = 0u; cell < {{ CELLS_PER_THREAD }}u; cell += 1u) { let flat = tid + cell * 128u; let row = flat / TILE_N; let col = flat % TILE_N; if (flat < TILE_M * TILE_N) { for (var k = 0u; k < TILE_K; k += 1u) { acc[cell] = fma({{ accumulatorScalar }}(tileA[row * TILE_K + k]), {{ accumulatorScalar }}(tileB[k * TILE_N + col]), acc[cell]); } } } workgroupBarrier(); } for (var cell = 0u; cell < {{ CELLS_PER_THREAD }}u; cell += 1u) { let flat = tid + cell * 128u; let row = rowBase + flat / TILE_N; let col = colBase + flat % TILE_N; if (flat < TILE_M * TILE_N && row < M && col < N) { {{ shapedWrite("acc[cell]", "row", "col") }} } } }}123456789101112131415161718192021222324252627282930{"name": "com.microsoft.FusedGemm","id": "_com_microsoft_fusedgemm_webgpu_ac387d4","version": 1,"license": "Apache-2.0","backend": { "type": "webgpu" },"digest": {"algorithm": "sha256","files": {"bench.json": "wb8UHX4mLph1fuImZI56hUkFg3rsazdLNuDl69XrKdM=","gemm-epilogue-tiled-reg.wgsl.jinja": "lMuXvRGDi2ewxkuPmUdHQQwp46J1QsijBld8kMQ82Fs=","gemm-subgroup-matrix.wgsl.jinja": "/9hULxzHaNrsh+k8LTpfcn9BkWpPDgrsRNoAdJifeuo=","gemv-contiguous.wgsl.jinja": "v/6jGn6BLOYSNbQfSYtfqC5z1bn6ojH2jDUhkcsPNj8=","manifest.json": "5+uq+536S5OmN3Z2XrFcoSh/0OxBDK3ZsMir51yKylA=","test.json": "jCRrQy0G/cGcrv8OOtYJb3iamPxJgLHxnFk7q7EyoUY="}},"provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },"webgpu": {"manifestSpec": "2.1","variants": {"gemv_plain": ["gemv-contiguous.wgsl.jinja"],"gemv_bias": ["gemv-contiguous.wgsl.jinja"],"sgmat_bias": ["gemm-subgroup-matrix.wgsl.jinja"],"sgmat": ["gemm-subgroup-matrix.wgsl.jinja"],"tiled_reg_bias": ["gemm-epilogue-tiled-reg.wgsl.jinja"],"tiled_reg": ["gemm-epilogue-tiled-reg.wgsl.jinja"]}}}1{"name":"com.microsoft.FusedGemm","id":"_com_microsoft_fusedgemm_webgpu_66182db","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"bench.json":"tIjIJIxZ2m+qt12Bi5wlTKR/n87MipxVlGtUT96uMWE=","fusedgemm-native16-packed-register.wgsl.jinja":"pgnX7STBci3Xj3B63PDxO9rkzwABoZImnc5bSPnGgQQ=","gemm-epilogue-tiled-reg.wgsl.jinja":"vdkwpsHux4EA92XYQwMlL2IZcKqZu69XxosZsLGLZJ0=","gemm-subgroup-matrix.wgsl.jinja":"u63qPb9xnuFo7gNCA4cNJT3U46STNY+ti3uvdyXGyEA=","gemv-contiguous.wgsl.jinja":"3FgAl53GJgQEaFJqrO8QgDAmwFegZ3zVRn/+fDzMjJw=","manifest.json":"EW8AH9aXki8A6jYRb40+LzeHio7YAj7cJ00P0wYe+Ik=","matmul-notrans-vec4-tiled-reg.wgsl.jinja":"7i81UFBS773mjzRCOFlDgF+ferLq24KM9i7ljENO1zg=","matrix-shaped-projection-gemm.wgsl.jinja":"MBVUPsfY74fBIm2lI26FOj30wgkk3TWQiQtFqfmALy4=","reduce-axis0-splitk-combine.wgsl.jinja":"4V3mJj5spJimTnS/25P6w+vEnpZ6y8NgUAvlHev8x1c=","test.json":"CC6tMQ8EWOICGZg0EHvn8uHrFin8uFBlVF3N9rbO670="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197// 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 outputEpilogueValue = outputEpilogue | default("none") %}{% set biasIndex = "col / BIAS_COLS" if (biasPerRow is defined and biasPerRow) else "col % BIAS_COLS" %}{% set yv = "" %}{% set vy = "" %}{{ 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 %}{% if outputEpilogueValue == "fastgelu" %}
fn tanh_safe(x: f32) -> f32 { // tanh rounds to its saturated value for these tails in f32. Return that // value directly, including for infinite input, before invoking the builtin. if (x > 10.0) { return 1.0; } if (x < -10.0) { return -1.0; } // For tiny |x|, return x directly to preserve its sign and magnitude without // relying on backend-specific builtin behavior near zero. if (x > -1.0e-4 && x < 1.0e-4) { return x; } return tanh(x);}
fn gelu_tanh(v: f32) -> f32 { return 0.5 * v * (1.0 + tanh_safe(0.7978845608028654 * (v + 0.044715 * v * v * v)));}{% elif outputEpilogueValue == "activation" %}
{% set actMode = gemmActivation | default("") %}{% set actA = gemmActAlpha | default(0.0) %}{% set actB = gemmActBeta | default(0.0) %}{% macro fused_act_fn(mode, alpha, beta) %}fn fused_act(v: f32) -> f32 {{% if mode == "" %} return v;{% elif mode == "Relu" %} let bits = bitcast<u32>(v); return bitcast<f32>(select(0u, bits, (bits & 0x80000000u) == 0u || (bits & 0x7fffffffu) > 0x7f800000u));{% elif mode == "Clip" %} return clamp(v, f32({{ alpha }}), f32({{ beta }}));{% elif mode == "LeakyRelu" %} return select(v * f32({{ alpha }}), v, v >= 0.0);{% elif mode == "Sigmoid" %} return 1.0 / (1.0 + exp(-v));{% elif mode == "Tanh" %} // tanh is already +/-1 to f32 precision at the clamp bounds. Clamping before // the builtin preserves that saturated result for larger accumulators. return tanh(clamp(v, -10.0, 10.0));{% elif mode == "HardSigmoid" %} return clamp(f32({{ alpha }}) * v + f32({{ beta }}), 0.0, 1.0);{% elif mode == "QuickGelu" %}{% if alpha == 1 %} // alpha == 1 is SiLU: the multiply folds away (the spelling yolov8-class detectors emit). return v * (1.0 / (1.0 + exp(-v)));{% else %} return v * (1.0 / (1.0 + exp(-(f32({{ alpha }}) * v))));{% endif %}{% elif mode == "Elu" %} return select(f32({{ alpha }}) * (exp(v) - 1.0), v, v >= 0.0);{% elif mode == "ThresholdedRelu" %} return select(0.0, v, v > f32({{ alpha }}));{% elif mode == "Softplus" %} // log(1 + exp(v)) spelled overflow-safe: max(v, 0) + log(1 + exp(-|v|)). return max(v, 0.0) + log(1.0 + exp(-abs(v)));{% elif mode == "Erf" %} // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7), the same polynomial the standalone // Erf/Gelu kernels use, so a fused and an unfused graph agree to f32 rounding. let a = abs(v); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return sign(v) * (1.0 - poly * exp(-a * a));{% elif mode == "Gelu" and alpha == 0 %} // ONNX Gelu, erf form: 0.5 * v * (1 + erf(v / sqrt(2))); activation_params[0] == 0. let u = v * 0.70710678118654752; let a = abs(u); let t = 1.0 / (1.0 + 0.3275911 * a); let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return 0.5 * v * (1.0 + sign(u) * (1.0 - poly * exp(-a * a)));{% elif mode == "Gelu" or mode == "FastGelu" %} // tanh approximation (ONNX Gelu approximate="tanh" arrives as activation_params[0] != 0; // com.microsoft.FastGelu always). tanh saturates to +/-1 well inside the clamp. let inner = v * (0.035677408136300125 * v * v + 0.7978845608028654); return v * (0.5 + 0.5 * tanh(clamp(inner, -10.0, 10.0)));{% else %} return v * clamp(v * 0.16666666666666666 + 0.5, 0.0, 1.0);{% endif %}}{% endmacro %}{{ fused_act_fn(actMode, actA, actB) }}{% endif %}
const WG: u32 = {{ workgroupSize }}u;const SPLIT: u32 = {{ split }}u;{% if addBias %}const BIAS_COLS: u32 = {{ biasCols }}u;{% endif %}{% 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 addBias %} total = total + select(f32(bias[{{ biasIndex }}]) * params.beta, 0.0, params.beta == 0.0);{% endif %}{% if outputEpilogueValue == "fastgelu" %} total = gelu_tanh(total);{% elif outputEpilogueValue == "activation" %} total = fused_act(total);{% 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 %} y[col] = total;{% endif %}{% endif %} }}README.md+30-15
build/webgpu/bench.json+441
build/webgpu/fusedgemm-native16-packed-register.wgsl.jinjaAdded+360
build/webgpu/gemm-epilogue-tiled-reg.wgsl.jinja+14-5
build/webgpu/gemm-subgroup-matrix.wgsl.jinja+171-46
build/webgpu/gemv-contiguous.wgsl.jinja+61-11
build/webgpu/manifest.json+1-311
build/webgpu/matmul-notrans-vec4-tiled-reg.wgsl.jinjaAdded+351
build/webgpu/matrix-shaped-projection-gemm.wgsl.jinjaAdded+243
build/webgpu/metadata.json+1-30
build/webgpu/reduce-axis0-splitk-combine.wgsl.jinjaAdded+197
build/webgpu/test.json