Xenova HF Staff commited on
Commit
aa658d4
·
verified ·
1 Parent(s): d8aeb25

sync 4385228f788d

Browse files
README.md CHANGED
@@ -51,54 +51,62 @@ Default values (overridable per request):
51
 
52
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
53
 
54
- - `broadcast_transb_tiled_reg` — Register-blocked broadcast product with physically transposed B. Reuses the shared batch-addressing tile, keeps f32 accumulation, and preserves scalar K order for f16. Low tile count and excessive padding demote this otherwise correct path.
55
- - `broadcast_transb_subgroup_matrix_f16` — Broadcast transposed-B product using a supported 8x8x8 subgroup-matrix configuration with f32 accumulation. Logical shapes and physical B strides share the existing matrix engine; insufficient output tiles or excessive padding retain the generic tile.
56
- - `broadcast_transb_subgroup_matrix_f32` — Broadcast transposed-B product using a supported 8x8x8 subgroup-matrix configuration with f32 accumulation. Logical shapes and physical B strides share the existing matrix engine; insufficient output tiles or excessive padding retain the generic tile.
57
- - `subgroup_matrix_transbatch_b_f16` — Aligned rank-3 transBatchB product with sufficient reduction depth and output tiles to amortize subgroup-matrix staging.
58
- - `subgroup_matrix_transbatch_b_f32` — Aligned rank-3 transBatchB product with sufficient reduction depth and output tiles to amortize subgroup-matrix staging.
59
  - `m1_gemv_vec4` — Vector-by-matrix specialization for a single output row: each workgroup owns 32 consecutive vec4 column groups and partitions the reduction across the workgroup's second dimension. The accumulator stays float32 for both tensor types.
60
  - `rank2_band_vec4_splitk` — Splits the vec4 band's K axis across up to sixteen workgroups. Each range writes an f32 partial band with alpha applied, and a combine pass sums the partials.
61
- - `rank2_band_vec4` — Few-row band for a rank-2 product without transposes. Each lane owns one vec4 column group and one accumulator per row, so every B word feeds all 2 to 16 rows; alpha is applied at the store.
62
- - `rank2_band_vec4_f32_preferred` — Few-row band for a rank-2 product without transposes. Each lane owns one vec4 column group and one accumulator per row, so every B word feeds all 2 to 16 rows; alpha is applied at the store.
63
  - `subgroup_matrix_splitk` — Partitions the K reduction of small-M rank-2 products across subgroup-matrix workgroups, then combines float32 partials that already include alpha.
64
- - `subgroup_matrix` — Subgroup-matrix `Y = alpha * op(A) @ op(B)` over dense batches with float32 accumulation. An output width that is not a multiple of the 64-wide column tile switches the trailing tile to guarded addressing: its B columns clamp to N - 1 and its stores drop every column at or past N. Yields the shape when the padded column ratio exceeds its tunable ceiling.
65
- - `plain_rank2_tiled_reg` — Register-blocked rank-2 `Y = alpha * A @ B` specialization for non-transposed inputs on tiers without subgroup-matrix support.
66
  - `transbatch_b_tiled_reg` — Register-blocked logical rank3 product with an interleaved physical B batch axis.
 
67
 
68
  ## Device requirements
69
 
70
- Some implementation variants require `subgroup-matrix` and `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.
71
 
72
  ## Files
73
 
74
- - [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)
75
- - [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)
76
- - [`test.json`](build/webgpu/test.json) — correctness cases
77
- - [`bench.json`](build/webgpu/bench.json) — benchmark cases
78
- - [`fused-matmul-subgroup-matrix.wgsl.jinja`](build/webgpu/fused-matmul-subgroup-matrix.wgsl.jinja)
79
- - [`matmul-band-vec4.wgsl.jinja`](build/webgpu/matmul-band-vec4.wgsl.jinja)
80
- - [`matmul-subgroup-matrix-ext.wgsl.jinja`](build/webgpu/matmul-subgroup-matrix-ext.wgsl.jinja)
81
- - [`matmul-tiled-general-reg.wgsl.jinja`](build/webgpu/matmul-tiled-general-reg.wgsl.jinja)
82
- - [`matmul-tiled-general.wgsl.jinja`](build/webgpu/matmul-tiled-general.wgsl.jinja)
83
- - [`matmul-vector-matrix-vec4.wgsl.jinja`](build/webgpu/matmul-vector-matrix-vec4.wgsl.jinja)
84
- - [`reduce-axis0-splitk-combine.wgsl.jinja`](build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja)
 
 
 
85
 
86
  ## Use with `@huggingface/kernels`
87
 
88
  ```sh
89
- npm install --save-exact @huggingface/kernels@0.0.1-preview.3
90
  ```
91
 
 
 
92
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
93
 
94
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
95
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
96
 
97
- Replace each `*Data` placeholder with a typed array containing the corresponding input data.
98
-
99
  ```js
100
  import { getKernel } from "@huggingface/kernels";
101
 
102
  const kernel = await getKernel("webgpu-kernels/com.microsoft.FusedMatMul", { version: 1 });
 
 
 
 
103
  const { Y } = await kernel({ A: { data: AData, shape: [3] }, B: { data: BData, shape: [3] } });
 
104
  ```
 
51
 
52
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
53
 
54
+ - `native16_packed_shared_b_64x64`, `native16_packed_shared_b_128x128`, `native16_packed_shared_b_64x128` — Multiplies contiguous half rows by shared rank-two weights, accumulating in float32 and applying alpha before one half output conversion.
55
+ - `native16_batched_gemm` — Batched half products on the general subgroup-matrix GEMM: a 2 x 2 subgroup grid owns 64 x 64 output tiles, staging each operand as stored, with no transpose copy (transposed operands load column-major fragments), accumulating in float32 and applying any alpha scale before one half conversion. Broadcast batch dimensions read with zero strides.
56
+ - `tiled_reg` — Register-blocked `Y = alpha * A @ B` where no subgroup-matrix variant applies: plain rank-2 products, rank-4 A against a rank-2 or rank-3 B, and broadcast products with physically transposed B. Keeps f32 accumulation and preserves scalar K order for f16 transposed B; with few tiles or heavy padding, the transposed-B form is tried after other variants.
57
+ - `broadcast_transb_subgroup_matrix` — Broadcast transposed-B product using a supported 8x8x8 subgroup-matrix configuration with f32 accumulation. Logical shapes and physical B strides share the generic matrix engine; insufficient output tiles or excessive padding retain the generic tile.
58
+ - `subgroup_matrix_transbatch_b` — Aligned rank-3 transBatchB product with sufficient reduction depth and output tiles to amortize subgroup-matrix staging.
59
  - `m1_gemv_vec4` — Vector-by-matrix specialization for a single output row: each workgroup owns 32 consecutive vec4 column groups and partitions the reduction across the workgroup's second dimension. The accumulator stays float32 for both tensor types.
60
  - `rank2_band_vec4_splitk` — Splits the vec4 band's K axis across up to sixteen workgroups. Each range writes an f32 partial band with alpha applied, and a combine pass sums the partials.
61
+ - `rank2_band_vec4`, `rank2_band_vec4_f32_preferred` — Few-row kernel for a rank-2 product without transposes. Each lane owns one vec4 column group and one accumulator per row, so every B word feeds all 2 to 16 rows; alpha is applied at the store. `_f32_preferred` is the same kernel, tried first for f32 unless the product has both many rows and a deep K.
 
62
  - `subgroup_matrix_splitk` — Partitions the K reduction of small-M rank-2 products across subgroup-matrix workgroups, then combines float32 partials that already include alpha.
63
+ - `subgroup_matrix_direct_b_partial_k` — Reads complete 8×8 right-hand fragments directly from storage. The final partial reduction stage pads both operands in workgroup memory, preserving the last valid dot-product terms.
64
+ - `subgroup_matrix` — Subgroup-matrix `Y = alpha * op(A) @ op(B)` over dense batches with float32 accumulation. An output width that is not a multiple of the 64-wide column tile switches the trailing tile to guarded addressing: its B columns clamp to N - 1 and its stores drop every column at or past N. Yields the shape when padding N to whole column tiles exceeds its limit.
65
  - `transbatch_b_tiled_reg` — Register-blocked logical rank3 product with an interleaved physical B batch axis.
66
+ - `subgroup_matrix_16x16x16_plain` — Experimental `16x16x16` half-precision subgroup matrices with `f32` accumulation. The `alpha` scale is 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.
67
 
68
  ## Device requirements
69
 
70
+ Some implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.
71
 
72
  ## Files
73
 
74
+ - [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)
75
+ - [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)
76
+ - [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/test.json) — correctness cases
77
+ - [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/bench.json) — benchmark cases
78
+ - [`contrib-native16-packed.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/contrib-native16-packed.wgsl.jinja)
79
+ - [`fused-matmul-subgroup-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/fused-matmul-subgroup-matrix.wgsl.jinja)
80
+ - [`matmul-band-vec4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/matmul-band-vec4.wgsl.jinja)
81
+ - [`matmul-subgroup-matrix-ext.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/matmul-subgroup-matrix-ext.wgsl.jinja)
82
+ - [`matmul-tiled-general-reg.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/matmul-tiled-general-reg.wgsl.jinja)
83
+ - [`matmul-tiled-general.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/matmul-tiled-general.wgsl.jinja)
84
+ - [`matmul-vector-matrix-vec4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/matmul-vector-matrix-vec4.wgsl.jinja)
85
+ - [`matrix-shaped-projection-gemm.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/matrix-shaped-projection-gemm.wgsl.jinja)
86
+ - [`reduce-axis0-splitk-combine.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja)
87
+ - [`subgroup-matrix-gemm.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.FusedMatMul/blob/v1/build/webgpu/subgroup-matrix-gemm.wgsl.jinja)
88
 
89
  ## Use with `@huggingface/kernels`
90
 
91
  ```sh
92
+ npm install --save-exact @huggingface/kernels@0.0.1-preview.4
93
  ```
94
 
95
+ Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.
96
+
97
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
98
 
99
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
100
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
101
 
 
 
102
  ```js
103
  import { getKernel } from "@huggingface/kernels";
104
 
105
  const kernel = await getKernel("webgpu-kernels/com.microsoft.FusedMatMul", { version: 1 });
106
+
107
+ const AData = Float32Array.of(0, 1, 2);
108
+ const BData = Float32Array.of(0, 1, 2);
109
+
110
  const { Y } = await kernel({ A: { data: AData, shape: [3] }, B: { data: BData, shape: [3] } });
111
+ console.log({ Y });
112
  ```
build/webgpu/bench.json CHANGED
@@ -134,6 +134,42 @@
134
  "outputs": { "Y": { "shape": [512, 500], "dtype": "float16" } },
135
  "bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * 512 * 500 * 2048" }] }
136
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  {
138
  "name": "fusedmatmul-f16-unaligned-k2050-512x2050x512-cliff",
139
  "preset": "smoke",
@@ -335,9 +371,7 @@
335
  },
336
  {
337
  "name": "fusedmatmul-f32-decode-gemv-m1-k4096-n4096-alpha-half",
338
- "provenance": {
339
- "notes": "A 1x4096 by 4096x4096 decode GEMV with alpha=0.5 exercises the single-row route with a baked non-unit output multiplier."
340
- },
341
  "preset": "stress",
342
  "attrs": { "alpha": 0.5 },
343
  "vars": { "dtype": "float32", "M": 1, "K": 4096, "N": 4096 },
@@ -788,6 +822,321 @@
788
  "provenance": {
789
  "notes": "Profitability-boundary probe for output tile count and padded arithmetic, with a shared transposed B matrix."
790
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791
  }
792
  ]
793
  }
 
134
  "outputs": { "Y": { "shape": [512, 500], "dtype": "float16" } },
135
  "bench": { "primary": true, "metrics": [{ "type": "gflops", "value": "2 * 512 * 500 * 2048" }] }
136
  },
137
+ {
138
+ "name": "fusedmatmul-f16-four-half-m64-k2048-n260",
139
+ "preset": "stress",
140
+ "attrs": { "alpha": 1 },
141
+ "vars": { "M": 64, "K": 2048, "N": 260 },
142
+ "inputs": {
143
+ "A": { "shape": [64, 2048], "dtype": "float16", "dist": "normal", "seed": 650, "scale": 0.1 },
144
+ "B": { "shape": [2048, 260], "dtype": "float16", "dist": "normal", "seed": 651, "scale": 0.1 }
145
+ },
146
+ "outputs": { "Y": { "shape": [64, 260], "dtype": "float16" } },
147
+ "bench": { "metrics": [{ "type": "gflops", "value": "2 * 64 * 2048 * 260" }] }
148
+ },
149
+ {
150
+ "name": "fusedmatmul-f16-four-half-m257-k1032-n516",
151
+ "preset": "stress",
152
+ "attrs": { "alpha": -0.5 },
153
+ "vars": { "M": 257, "K": 1032, "N": 516 },
154
+ "inputs": {
155
+ "A": { "shape": [257, 1032], "dtype": "float16", "dist": "normal", "seed": 652, "scale": 0.1 },
156
+ "B": { "shape": [1032, 516], "dtype": "float16", "dist": "normal", "seed": 653, "scale": 0.1 }
157
+ },
158
+ "outputs": { "Y": { "shape": [257, 516], "dtype": "float16" } },
159
+ "bench": { "metrics": [{ "type": "gflops", "value": "2 * 257 * 1032 * 516" }] }
160
+ },
161
+ {
162
+ "name": "fusedmatmul-f16-four-half-m512-k2048-n1020",
163
+ "preset": "stress",
164
+ "attrs": { "alpha": 1 },
165
+ "vars": { "M": 512, "K": 2048, "N": 1020 },
166
+ "inputs": {
167
+ "A": { "shape": [512, 2048], "dtype": "float16", "dist": "normal", "seed": 654, "scale": 0.1 },
168
+ "B": { "shape": [2048, 1020], "dtype": "float16", "dist": "normal", "seed": 655, "scale": 0.1 }
169
+ },
170
+ "outputs": { "Y": { "shape": [512, 1020], "dtype": "float16" } },
171
+ "bench": { "metrics": [{ "type": "gflops", "value": "2 * 512 * 2048 * 1020" }] }
172
+ },
173
  {
174
  "name": "fusedmatmul-f16-unaligned-k2050-512x2050x512-cliff",
175
  "preset": "smoke",
 
371
  },
372
  {
373
  "name": "fusedmatmul-f32-decode-gemv-m1-k4096-n4096-alpha-half",
374
+ "provenance": { "notes": "A 1x4096 by 4096x4096 float32 decode GEMV with alpha=0.5; the metric is bandwidth." },
 
 
375
  "preset": "stress",
376
  "attrs": { "alpha": 0.5 },
377
  "vars": { "dtype": "float32", "M": 1, "K": 4096, "N": 4096 },
 
822
  "provenance": {
823
  "notes": "Profitability-boundary probe for output tile count and padded arithmetic, with a shared transposed B matrix."
824
  }
825
+ },
826
+ {
827
+ "name": "fusedmatmul-packed-shared-b-prefill-m512-k2560-n4096",
828
+ "preset": "model",
829
+ "attrs": { "alpha": 1, "transB": 1 },
830
+ "inputs": {
831
+ "A": { "dtype": "float16", "shape": [1, 512, 2560], "dist": "normal", "seed": 420, "scale": 0.125 },
832
+ "B": { "dtype": "float16", "shape": [4096, 2560], "dist": "normal", "seed": 421, "scale": 0.125 }
833
+ },
834
+ "outputs": { "Y": { "dtype": "float16", "shape": [1, 512, 4096] } },
835
+ "bench": {
836
+ "primary": true,
837
+ "metrics": [{ "type": "gflops", "value": "2 * numel(shapes.Y) * dim(shapes.A, ranks.A - 1)" }]
838
+ },
839
+ "provenance": {
840
+ "source": "Shared dense transposed-weight projection at a model prefill geometry.",
841
+ "notes": "Rank-three half-precision activations [1, 512, 2560] against one shared transposed weight [4096, 2560]."
842
+ }
843
+ },
844
+ {
845
+ "name": "fusedmatmul-packed-rectangle-grid127-m128-k512-n16256-tb0",
846
+ "preset": "stress",
847
+ "attrs": { "alpha": 1, "transB": 0 },
848
+ "inputs": {
849
+ "A": { "dtype": "float16", "shape": [128, 512], "dist": "normal", "seed": 1920, "scale": 0.125 },
850
+ "B": { "dtype": "float16", "shape": [512, 16256], "dist": "normal", "seed": 1922, "scale": 0.125 }
851
+ },
852
+ "outputs": { "Y": { "dtype": "float16", "shape": [128, 16256] } },
853
+ "bench": {
854
+ "primary": true,
855
+ "metrics": [{ "type": "gflops", "value": "2 * numel(shapes.Y) * dim(shapes.A, ranks.A - 1)" }]
856
+ },
857
+ "provenance": {
858
+ "source": "Seeded dense half-precision products at several output shapes.",
859
+ "notes": "Half-precision rank-two products over several output shapes (128 x 16256 to 2048 x 2048), K from 512 to 2560, with B untransposed or transposed."
860
+ }
861
+ },
862
+ {
863
+ "name": "fusedmatmul-packed-rectangle-grid128-m512-k2560-n4096-tb1",
864
+ "preset": "stress",
865
+ "attrs": { "alpha": 1, "transB": 1 },
866
+ "inputs": {
867
+ "A": { "dtype": "float16", "shape": [512, 2560], "dist": "normal", "seed": 1921, "scale": 0.125 },
868
+ "B": { "dtype": "float16", "shape": [4096, 2560], "dist": "normal", "seed": 1923, "scale": 0.125 }
869
+ },
870
+ "outputs": { "Y": { "dtype": "float16", "shape": [512, 4096] } },
871
+ "bench": {
872
+ "primary": true,
873
+ "metrics": [{ "type": "gflops", "value": "2 * numel(shapes.Y) * dim(shapes.A, ranks.A - 1)" }]
874
+ },
875
+ "provenance": {
876
+ "source": "Seeded dense half-precision products at several output shapes.",
877
+ "notes": "Half-precision rank-two products over several output shapes (128 x 16256 to 2048 x 2048), K from 512 to 2560, with B untransposed or transposed."
878
+ }
879
+ },
880
+ {
881
+ "name": "fusedmatmul-packed-rectangle-grid192-m768-k2048-n4096-tb0",
882
+ "preset": "stress",
883
+ "attrs": { "alpha": 1, "transB": 0 },
884
+ "inputs": {
885
+ "A": { "dtype": "float16", "shape": [768, 2048], "dist": "normal", "seed": 1920, "scale": 0.125 },
886
+ "B": { "dtype": "float16", "shape": [2048, 4096], "dist": "normal", "seed": 1922, "scale": 0.125 }
887
+ },
888
+ "outputs": { "Y": { "dtype": "float16", "shape": [768, 4096] } },
889
+ "bench": {
890
+ "primary": true,
891
+ "metrics": [{ "type": "gflops", "value": "2 * numel(shapes.Y) * dim(shapes.A, ranks.A - 1)" }]
892
+ },
893
+ "provenance": {
894
+ "source": "Seeded dense half-precision products at several output shapes.",
895
+ "notes": "Half-precision rank-two products over several output shapes (128 x 16256 to 2048 x 2048), K from 512 to 2560, with B untransposed or transposed."
896
+ }
897
+ },
898
+ {
899
+ "name": "fusedmatmul-packed-rectangle-grid255-m1920-k512-n2176-tb1",
900
+ "preset": "stress",
901
+ "attrs": { "alpha": 1, "transB": 1 },
902
+ "inputs": {
903
+ "A": { "dtype": "float16", "shape": [1920, 512], "dist": "normal", "seed": 1921, "scale": 0.125 },
904
+ "B": { "dtype": "float16", "shape": [2176, 512], "dist": "normal", "seed": 1923, "scale": 0.125 }
905
+ },
906
+ "outputs": { "Y": { "dtype": "float16", "shape": [1920, 2176] } },
907
+ "bench": {
908
+ "primary": true,
909
+ "metrics": [{ "type": "gflops", "value": "2 * numel(shapes.Y) * dim(shapes.A, ranks.A - 1)" }]
910
+ },
911
+ "provenance": {
912
+ "source": "Seeded dense half-precision products at several output shapes.",
913
+ "notes": "Half-precision rank-two products over several output shapes (128 x 16256 to 2048 x 2048), K from 512 to 2560, with B untransposed or transposed."
914
+ }
915
+ },
916
+ {
917
+ "name": "fusedmatmul-packed-rectangle-grid256-m2048-k2048-n2048-tb0",
918
+ "preset": "stress",
919
+ "attrs": { "alpha": 1, "transB": 0 },
920
+ "inputs": {
921
+ "A": { "dtype": "float16", "shape": [2048, 2048], "dist": "normal", "seed": 1920, "scale": 0.125 },
922
+ "B": { "dtype": "float16", "shape": [2048, 2048], "dist": "normal", "seed": 1922, "scale": 0.125 }
923
+ },
924
+ "outputs": { "Y": { "dtype": "float16", "shape": [2048, 2048] } },
925
+ "bench": {
926
+ "primary": true,
927
+ "metrics": [{ "type": "gflops", "value": "2 * numel(shapes.Y) * dim(shapes.A, ranks.A - 1)" }]
928
+ },
929
+ "provenance": {
930
+ "source": "Seeded dense half-precision products at several output shapes.",
931
+ "notes": "Half-precision rank-two products over several output shapes (128 x 16256 to 2048 x 2048), K from 512 to 2560, with B untransposed or transposed."
932
+ }
933
+ },
934
+ {
935
+ "name": "round6-band-boundary-m8-k4096-n4096",
936
+ "preset": "model",
937
+ "attrs": { "alpha": 0.5 },
938
+ "inputs": {
939
+ "A": { "dtype": "float32", "shape": [8, 4096], "dist": "normal", "seed": 31001, "scale": 0.1 },
940
+ "B": { "dtype": "float32", "shape": [4096, 4096], "dist": "normal", "seed": 31002, "scale": 0.1 }
941
+ },
942
+ "outputs": { "Y": { "dtype": "float32", "shape": [8, 4096], "dist": "empty" } },
943
+ "bench": { "metrics": [{ "type": "gflops", "value": 268435456 }] },
944
+ "provenance": {
945
+ "source": "Synthetic thin float32 projection boundary case.",
946
+ "notes": "A float32 [8,4096] x [4096,4096] product with seeded inputs."
947
+ }
948
+ },
949
+ {
950
+ "name": "round6-band-boundary-m16-k4096-n4096",
951
+ "preset": "model",
952
+ "attrs": { "alpha": 0.5 },
953
+ "inputs": {
954
+ "A": { "dtype": "float32", "shape": [16, 4096], "dist": "normal", "seed": 31003, "scale": 0.1 },
955
+ "B": { "dtype": "float32", "shape": [4096, 4096], "dist": "normal", "seed": 31004, "scale": 0.1 }
956
+ },
957
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 4096], "dist": "empty" } },
958
+ "bench": { "metrics": [{ "type": "gflops", "value": 536870912 }] },
959
+ "provenance": {
960
+ "source": "Synthetic thin float32 projection boundary case.",
961
+ "notes": "A float32 [16,4096] x [4096,4096] product with seeded inputs."
962
+ }
963
+ },
964
+ {
965
+ "name": "round6-band-boundary-m32-k8192-n4096",
966
+ "preset": "model",
967
+ "attrs": { "alpha": 0.5 },
968
+ "inputs": {
969
+ "A": { "dtype": "float32", "shape": [32, 8192], "dist": "normal", "seed": 31005, "scale": 0.1 },
970
+ "B": { "dtype": "float32", "shape": [8192, 4096], "dist": "normal", "seed": 31006, "scale": 0.1 }
971
+ },
972
+ "outputs": { "Y": { "dtype": "float32", "shape": [32, 4096], "dist": "empty" } },
973
+ "bench": { "metrics": [{ "type": "gflops", "value": 2147483648 }] },
974
+ "provenance": {
975
+ "source": "Synthetic thin float32 projection boundary case.",
976
+ "notes": "A float32 [32,8192] x [8192,4096] product with seeded inputs."
977
+ }
978
+ },
979
+ {
980
+ "name": "round6-band-boundary-m16-k8192-n2048",
981
+ "preset": "model",
982
+ "attrs": { "alpha": 0.5 },
983
+ "inputs": {
984
+ "A": { "dtype": "float32", "shape": [16, 8192], "dist": "normal", "seed": 31007, "scale": 0.1 },
985
+ "B": { "dtype": "float32", "shape": [8192, 2048], "dist": "normal", "seed": 31008, "scale": 0.1 }
986
+ },
987
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 2048], "dist": "empty" } },
988
+ "bench": { "metrics": [{ "type": "gflops", "value": 536870912 }] },
989
+ "provenance": {
990
+ "source": "Synthetic thin float32 projection boundary case.",
991
+ "notes": "A float32 [16,8192] x [8192,2048] product with seeded inputs."
992
+ }
993
+ },
994
+ {
995
+ "name": "round6-band-boundary-m16-k8192-n3072",
996
+ "preset": "model",
997
+ "attrs": { "alpha": 0.5 },
998
+ "inputs": {
999
+ "A": { "dtype": "float32", "shape": [16, 8192], "dist": "normal", "seed": 31009, "scale": 0.1 },
1000
+ "B": { "dtype": "float32", "shape": [8192, 3072], "dist": "normal", "seed": 31010, "scale": 0.1 }
1001
+ },
1002
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 3072], "dist": "empty" } },
1003
+ "bench": { "metrics": [{ "type": "gflops", "value": 805306368 }] },
1004
+ "provenance": {
1005
+ "source": "Synthetic thin float32 projection boundary case.",
1006
+ "notes": "A float32 [16,8192] x [8192,3072] product with seeded inputs."
1007
+ }
1008
+ },
1009
+ {
1010
+ "name": "round6-band-boundary-m8-k8192-n6144",
1011
+ "preset": "model",
1012
+ "attrs": { "alpha": 0.5 },
1013
+ "inputs": {
1014
+ "A": { "dtype": "float32", "shape": [8, 8192], "dist": "normal", "seed": 31011, "scale": 0.1 },
1015
+ "B": { "dtype": "float32", "shape": [8192, 6144], "dist": "normal", "seed": 31012, "scale": 0.1 }
1016
+ },
1017
+ "outputs": { "Y": { "dtype": "float32", "shape": [8, 6144], "dist": "empty" } },
1018
+ "bench": { "metrics": [{ "type": "gflops", "value": 805306368 }] },
1019
+ "provenance": {
1020
+ "source": "Synthetic thin float32 projection boundary case.",
1021
+ "notes": "A float32 [8,8192] x [8192,6144] product with seeded inputs."
1022
+ }
1023
+ },
1024
+ {
1025
+ "name": "round6-band-boundary-m16-k8192-n6144",
1026
+ "preset": "model",
1027
+ "attrs": { "alpha": 0.5 },
1028
+ "inputs": {
1029
+ "A": { "dtype": "float32", "shape": [16, 8192], "dist": "normal", "seed": 31013, "scale": 0.1 },
1030
+ "B": { "dtype": "float32", "shape": [8192, 6144], "dist": "normal", "seed": 31014, "scale": 0.1 }
1031
+ },
1032
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 6144], "dist": "empty" } },
1033
+ "bench": { "metrics": [{ "type": "gflops", "value": 1610612736 }] },
1034
+ "provenance": {
1035
+ "source": "Synthetic thin float32 projection boundary case.",
1036
+ "notes": "A float32 [16,8192] x [8192,6144] product with seeded inputs."
1037
+ }
1038
+ },
1039
+ {
1040
+ "name": "round6-band-boundary-m16-k4096-n3072",
1041
+ "preset": "model",
1042
+ "attrs": { "alpha": 0.5 },
1043
+ "inputs": {
1044
+ "A": { "dtype": "float32", "shape": [16, 4096], "dist": "normal", "seed": 31015, "scale": 0.1 },
1045
+ "B": { "dtype": "float32", "shape": [4096, 3072], "dist": "normal", "seed": 31016, "scale": 0.1 }
1046
+ },
1047
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 3072], "dist": "empty" } },
1048
+ "bench": { "metrics": [{ "type": "gflops", "value": 402653184 }] },
1049
+ "provenance": {
1050
+ "source": "Synthetic thin float32 projection boundary case.",
1051
+ "notes": "A float32 [16,4096] x [4096,3072] product with seeded inputs."
1052
+ }
1053
+ },
1054
+ {
1055
+ "name": "round6-band-boundary-m16-k4095-n4096",
1056
+ "preset": "model",
1057
+ "attrs": { "alpha": 0.5 },
1058
+ "inputs": {
1059
+ "A": { "dtype": "float32", "shape": [16, 4095], "dist": "normal", "seed": 31017, "scale": 0.1 },
1060
+ "B": { "dtype": "float32", "shape": [4095, 4096], "dist": "normal", "seed": 31018, "scale": 0.1 }
1061
+ },
1062
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 4096], "dist": "empty" } },
1063
+ "bench": { "metrics": [{ "type": "gflops", "value": 536739840 }] },
1064
+ "provenance": {
1065
+ "source": "Synthetic thin float32 projection boundary case.",
1066
+ "notes": "A float32 [16,4095] x [4095,4096] product with seeded inputs."
1067
+ }
1068
+ },
1069
+ {
1070
+ "name": "round6-band-boundary-m16-k8192-n4100",
1071
+ "preset": "model",
1072
+ "attrs": { "alpha": 0.5 },
1073
+ "inputs": {
1074
+ "A": { "dtype": "float32", "shape": [16, 8192], "dist": "normal", "seed": 31019, "scale": 0.1 },
1075
+ "B": { "dtype": "float32", "shape": [8192, 4100], "dist": "normal", "seed": 31020, "scale": 0.1 }
1076
+ },
1077
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 4100], "dist": "empty" } },
1078
+ "bench": { "metrics": [{ "type": "gflops", "value": 1074790400 }] },
1079
+ "provenance": {
1080
+ "source": "Synthetic thin float32 projection boundary case.",
1081
+ "notes": "A float32 [16,8192] x [8192,4100] product with seeded inputs."
1082
+ }
1083
+ },
1084
+ {
1085
+ "name": "round6-band-replay-safe-m16-k8192-n3968",
1086
+ "preset": "model",
1087
+ "attrs": { "alpha": 0.5 },
1088
+ "inputs": {
1089
+ "A": { "dtype": "float32", "shape": [16, 8192], "dist": "normal", "seed": 31101, "scale": 0.1 },
1090
+ "B": { "dtype": "float32", "shape": [8192, 3968], "dist": "normal", "seed": 31102, "scale": 0.1 }
1091
+ },
1092
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 3968], "dist": "empty" } },
1093
+ "bench": { "metrics": [{ "type": "gflops", "value": 1040187392 }] },
1094
+ "provenance": {
1095
+ "source": "Synthetic thin float32 projection boundary case.",
1096
+ "notes": "A float32 [16,8192] x [8192,3968] product with seeded inputs."
1097
+ }
1098
+ },
1099
+ {
1100
+ "name": "round6-band-replay-safe-m16-k8192-n3200",
1101
+ "preset": "model",
1102
+ "attrs": { "alpha": 0.5 },
1103
+ "inputs": {
1104
+ "A": { "dtype": "float32", "shape": [16, 8192], "dist": "normal", "seed": 31103, "scale": 0.1 },
1105
+ "B": { "dtype": "float32", "shape": [8192, 3200], "dist": "normal", "seed": 31104, "scale": 0.1 }
1106
+ },
1107
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 3200], "dist": "empty" } },
1108
+ "bench": { "metrics": [{ "type": "gflops", "value": 838860800 }] },
1109
+ "provenance": {
1110
+ "source": "Synthetic thin float32 projection boundary case.",
1111
+ "notes": "A float32 [16,8192] x [8192,3200] product with seeded inputs."
1112
+ }
1113
+ },
1114
+ {
1115
+ "name": "round6-band-replay-safe-m16-k8160-n4096",
1116
+ "preset": "model",
1117
+ "attrs": { "alpha": 0.5 },
1118
+ "inputs": {
1119
+ "A": { "dtype": "float32", "shape": [16, 8160], "dist": "normal", "seed": 31111, "scale": 0.1 },
1120
+ "B": { "dtype": "float32", "shape": [8160, 4096], "dist": "normal", "seed": 31112, "scale": 0.1 }
1121
+ },
1122
+ "outputs": { "Y": { "dtype": "float32", "shape": [16, 4096], "dist": "empty" } },
1123
+ "bench": { "metrics": [{ "type": "gflops", "value": 1069547520 }] },
1124
+ "provenance": {
1125
+ "source": "Synthetic thin float32 projection boundary case.",
1126
+ "notes": "A float32 [16,8160] x [8160,4096] product with seeded inputs."
1127
+ }
1128
+ },
1129
+ {
1130
+ "name": "fusedmatmul-f16-even-k-257x1026x520",
1131
+ "preset": "stress",
1132
+ "attrs": { "alpha": -0.5 },
1133
+ "vars": { "M": 257, "K": 1026, "N": 520 },
1134
+ "inputs": {
1135
+ "A": { "shape": [257, 1026], "dtype": "float16", "dist": "normal", "seed": 604, "scale": 0.1 },
1136
+ "B": { "shape": [1026, 520], "dtype": "float16", "dist": "normal", "seed": 605, "scale": 0.1 }
1137
+ },
1138
+ "outputs": { "Y": { "shape": [257, 520], "dtype": "float16" } },
1139
+ "bench": { "metrics": [{ "type": "gflops", "value": "2 * 257 * 1026 * 520" }] }
1140
  }
1141
  ]
1142
  }
build/webgpu/contrib-native16-packed.wgsl.jinja ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set registerFourColumnTail = N % 8 == 4 -%}
2
+ {%- if registerFourColumnTail %}
3
+ {% macro registerPackedBPrelude() %}
4
+ fn loadHalf4(k: u32, col: u32) -> vec4<u32> {
5
+ let at = (k * N + col) / 4u;
6
+ var upper = vec2<u32>(0u);
7
+ if (col + 4u < N) { upper = b[at + 1u]; }
8
+ return vec4<u32>(b[at], upper);
9
+ }
10
+ fn storeHalf4(row: u32, col: u32, packed: vec4<u32>) {
11
+ let at = (row * N + col) / 4u;
12
+ y[at] = packed.xy;
13
+ if (col + 4u < N) { y[at + 1u] = packed.zw; }
14
+ }
15
+ {% endmacro %}
16
+ {% macro registerLoadPackedB(column, reduction) %}loadHalf4({{ reduction }}, {{ column }}){% endmacro %}
17
+ {%- elif K % 8 != 0 %}
18
+ {% set registerPartialKPairs = true %}
19
+ {% macro registerBeforeEntryPoint() %}
20
+ fn loadHalfPairs(row: u32, k: u32) -> vec4<u32> {
21
+ let at = row * (K / 2u) + k / 2u;
22
+ if (k + 7u < K) {
23
+ return vec4<u32>(a[at], a[at + 1u], a[at + 2u], a[at + 3u]);
24
+ }
25
+ return vec4<u32>({% for pair in range(4) %}{% if 2 * pair < K % 8 %}a[at + {{ pair }}u]{% else %}0u{% endif %}{{ ", " if pair < 3 else "" }}{% endfor %});
26
+ }
27
+ {% endmacro %}
28
+ {% macro registerLoadPackedA(row, k) %}loadHalfPairs({{ row }}, {{ k }}){% endmacro %}
29
+ {%- endif -%}
30
+ {% set RESULT_SCRATCH_WORDS = 256 %}{%- set PAIRED_SWIGLU = false -%}
31
+ {%- set TA = false -%}
32
+ {%- set TB = registerTransposeB | default(false) -%}
33
+ {%- set BM = registerTileM -%}
34
+ {%- set BN = registerTileN -%}
35
+ {%- set BK = registerTileK -%}
36
+ {%- set PAD = registerSharedPad | default(0) -%}
37
+ {%- set FR = (BM / 32) | int -%}
38
+ {%- set FC = (BN / 32) | int -%}
39
+ {%- set ACOLS = BM if TA else BK -%}
40
+ {%- set AROWS = BK if TA else BM -%}
41
+ {%- set ASTRIDE = ((ACOLS + PAD) / 8) | int -%}
42
+ {%- set BSTRIDE = (((BK if TB else BN) + PAD) / 8) | int -%}
43
+ {%- set AWORDS = ((AROWS * (ACOLS + PAD)) / 8) | int -%}
44
+ {%- set BWORDS = (((BN if TB else BK) * ((BK if TB else BN) + PAD)) / 8) | int -%}
45
+ {%- set ASIZE = max(AWORDS, RESULT_SCRATCH_WORDS) -%}
46
+ {%- set OUT_SLOTS = ((BM * BN) / 8 / 128) | int -%}
47
+ {%- set PREFETCH = registerPrefetch | default(false) -%}
48
+ {%- set SPLIT_K = false -%}
49
+ {%- macro coordinates(name) -%}
50
+ {% if name == "a" %}
51
+ let row = rowBase + flat / {{ (BK / 8) | int }}u;
52
+ let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;
53
+ {% elif TB %}
54
+ let col = colBase + flat / {{ (BK / 8) | int }}u;
55
+ let k = kBase + (flat % {{ (BK / 8) | int }}u) * 8u;
56
+ {% else %}
57
+ let k = kBase + flat / {{ (BN / 8) | int }}u;
58
+ let col = colBase + (flat % {{ (BN / 8) | int }}u) * 8u;
59
+ {% endif %}
60
+ {%- endmacro -%}
61
+ {%- macro guard(name) -%}
62
+ {%- if name == "a" and registerPartialKPairs | default(false) -%}row < M && k < K
63
+ {%- elif name == "a" -%}row < M && k + 7u < K
64
+ {%- elif TB -%}col < N && k + 7u < K
65
+ {%- elif registerFourColumnTail | default(false) -%}k < K && col < N
66
+ {%- else -%}k < K && col + 7u < N{%- endif -%}
67
+ {%- endmacro -%}
68
+ {%- macro address(name) -%}
69
+ {%- if name == "a" -%}({{ "k * M + row" if TA else "row * K + k" }}) / 8u
70
+ {%- else -%}
71
+ ({{ "col * K + k" if TB else "k * N + col" }}) / 8u
72
+ {%- endif -%}
73
+ {%- endmacro -%}
74
+ {%- macro shared_index(name) -%}
75
+ {%- set PAYLOAD = ((ACOLS if name == "a" else BK if TB else BN) / 8) | int -%}
76
+ {%- set STRIDE = ASTRIDE if name == "a" else BSTRIDE -%}
77
+ (flat / {{ PAYLOAD }}u) * {{ STRIDE }}u + flat % {{ PAYLOAD }}u
78
+ {%- endmacro -%}
79
+ {%- macro result(value, column) -%}
80
+ f16(params.alpha * {{ value }})
81
+ {%- endmacro -%}
82
+ {%- macro output_address() -%}
83
+ (row * N + col) / 8u
84
+ {%- endmacro -%}
85
+ {%- macro half_output_guard() -%}
86
+ row < M && {{ "col < N" if registerFourColumnTail | default(false) else "col + 7u < N" }}
87
+ {%- endmacro -%}
88
+ {%- macro store_half_result() -%}
89
+ {% if registerFourColumnTail | default(false) %}storeHalf4(row, col, {{ pack_result("values") }});{% else %}y[{{ output_address() }}] = {{ pack_result("values") }};{% endif %}
90
+ {%- endmacro -%}
91
+ {%- macro pack_result(source) -%}
92
+ vec4<u32>(
93
+ {% for pair in range(4) %}
94
+ 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 "" }}
95
+ {% endfor %}
96
+ )
97
+ {%- endmacro -%}
98
+ {%- macro load_left_fragment(r, step) %}
99
+ let left{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>(
100
+ &tileA, subgroupRow * {{ ASTRIDE }}u + {{ r * 16 * ASTRIDE + (step / 8) | int }}u, {{ ASTRIDE }}u);
101
+ {%- endmacro -%}
102
+ {%- macro load_right_fragment(c, step) %}
103
+ {% if TB %}
104
+ let right{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, col_major>(
105
+ &tileB, subgroupCol * {{ BSTRIDE }}u + {{ c * 16 * BSTRIDE + (step / 8) | int }}u, {{ BSTRIDE }}u);
106
+ {%- else %}
107
+ let right{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, row_major>(
108
+ &tileB, subgroupCol / 8u + {{ step * BSTRIDE + c * 2 }}u, {{ BSTRIDE }}u);
109
+ {%- endif %}
110
+ {%- endmacro -%}
111
+ {%- macro multiply_fragment(r, c) %}
112
+ acc{{ r }}_{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ r }}, right{{ c }}, acc{{ r }}_{{ c }});
113
+ {%- endmacro -%}
114
+ enable subgroups;
115
+ enable chromium_experimental_subgroup_matrix;
116
+ diagnostic(off, chromium.subgroup_matrix_uniformity);
117
+ {% if registerPackedBPrelude is defined %}
118
+ {{ registerPackedBPrelude() }}{% endif %}{{ env.wgsl.resourceDeclarations }}
119
+ const N: u32 = {{ N }}u;
120
+ const K: u32 = {{ K }}u;
121
+ const TILE_M: u32 = {{ BM }}u;
122
+ const TILE_N: u32 = {{ BN }}u;
123
+ const TILE_K: u32 = {{ BK }}u;
124
+ var<workgroup> tileA: array<vec4<u32>, {{ ASIZE }}>;
125
+ var<workgroup> tileB: array<vec4<u32>, {{ BWORDS }}>;
126
+
127
+ fn loadTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) {
128
+ let M = params.M;
129
+ {% for name in ["a", "b"] %}
130
+ {% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}
131
+ for (var flat = tid; flat < {{ WORDS }}u; flat += 128u) {
132
+ {{ coordinates(name) }}
133
+ var value = vec4<u32>(0u);
134
+ {% if name == "b" and registerLoadPackedB is defined %}
135
+ if ({{ guard(name) }}) {
136
+ value = {{ registerLoadPackedB("col", "k") }};
137
+ }
138
+ {% elif name == "a" and not TA and registerLoadPackedA is defined %}
139
+ if ({{ guard(name) }}) {
140
+ value = {{ registerLoadPackedA("row", "k") }};
141
+ }
142
+ {% else %} if ({{ guard(name) }}) { value = {{ name }}[{{ address(name) }}]; }
143
+ {% endif %}
144
+ tile{{ "A" if name == "a" else "B" }}[{{ shared_index(name) }}] = value;
145
+ }
146
+ {% endfor %}
147
+ }
148
+
149
+ {% if PREFETCH %}
150
+ struct PrefetchedTiles {
151
+ a: array<vec4<u32>, {{ ((BM * BK / 8 + 127) / 128) | int }}>,
152
+ b: array<vec4<u32>, {{ ((BK * (2 * BN if PAIRED_SWIGLU else BN) / 8 + 127) / 128) | int }}>,
153
+ };
154
+ fn prefetchTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32) -> PrefetchedTiles {
155
+ let M = params.M;
156
+ var values: PrefetchedTiles;
157
+ {% for name in ["a", "b"] %}
158
+ {% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}
159
+ {% for slot in range(((WORDS + 127) / 128) | int) %}
160
+ {
161
+ let flat = tid + {{ slot * 128 }}u;
162
+ if (flat < {{ WORDS }}u) {
163
+ {{ coordinates(name) }}
164
+ {% if name == "b" and registerLoadPackedB is defined %}
165
+ if ({{ guard(name) }}) {
166
+ values.b[{{ slot }}] = {{ registerLoadPackedB("col", "k") }};
167
+ }
168
+ {% elif name == "a" and not TA and registerLoadPackedA is defined %}
169
+ if ({{ guard(name) }}) {
170
+ values.a[{{ slot }}] = {{ registerLoadPackedA("row", "k") }};
171
+ }
172
+ {% else %} if ({{ guard(name) }}) { values.{{ name }}[{{ slot }}] = {{ name }}[{{ address(name) }}]; }
173
+ {% endif %}
174
+ }
175
+ }
176
+ {% endfor %}
177
+ {% endfor %}
178
+ return values;
179
+ }
180
+ fn stagePrefetchedTiles(values: PrefetchedTiles, tid: u32) {
181
+ {% for name in ["a", "b"] %}
182
+ {% set WORDS = ((BM * BK if name == "a" else BK * (2 * BN if PAIRED_SWIGLU else BN)) / 8) | int %}
183
+ {% for slot in range(((WORDS + 127) / 128) | int) %}
184
+ {
185
+ let flat = tid + {{ slot * 128 }}u;
186
+ if (flat < {{ WORDS }}u) {
187
+ tile{{ "A" if name == "a" else "B" }}[{{ shared_index(name) }}] = values.{{ name }}[{{ slot }}];
188
+ }
189
+ }
190
+ {% endfor %}
191
+ {% endfor %}
192
+ }
193
+ {% endif %}
194
+
195
+ fn readA(row: u32, k: u32) -> f32 {
196
+ let word = tileA[row * {{ ASTRIDE }}u + k / 8u];
197
+ return f32(bitcast<vec2<f16>>(word[(k % 8u) / 2u])[k % 2u]);
198
+ }
199
+ fn readB(k: u32, col: u32) -> f32 {
200
+ let contiguous = {{ "k" if TB else "col" }};
201
+ let word = tileB[{{ "col" if TB else "k" }} * {{ BSTRIDE }}u + contiguous / 8u];
202
+ return f32(bitcast<vec2<f16>>(word[(contiguous % 8u) / 2u])[contiguous % 2u]);
203
+ }
204
+
205
+ // A subgroup owns one matrix tile only after its actual population and the
206
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
207
+ // the role; local invocation IDs only publish the workgroup-wide decision.
208
+ var<workgroup> matrixRoleCount: atomic<u32>;
209
+ var<workgroup> matrixRejected: atomic<u32>;
210
+ var<workgroup> matrixAccepted: u32;
211
+
212
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
213
+ // WGSL initializes workgroup variables to zero before this entry point.
214
+ let population = subgroupBallot(true);
215
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
216
+ + countOneBits(population.z) + countOneBits(population.w);
217
+ var claimed = 0u;
218
+ if (subgroupElect()) {
219
+ claimed = atomicAdd(&matrixRoleCount, 1u);
220
+ if (width != requiredWidth || populationCount != requiredWidth) {
221
+ atomicStore(&matrixRejected, 1u);
222
+ }
223
+ }
224
+ // Reconverge every invocation before broadcasting the elected claim.
225
+ workgroupBarrier();
226
+ return subgroupBroadcastFirst(claimed);
227
+ }
228
+
229
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
230
+ if (localIndex == 0u) {
231
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
232
+ && atomicLoad(&matrixRoleCount) == bankCount);
233
+ }
234
+ // The uniform load both publishes the leader's decision and gives the
235
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
236
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
237
+ }
238
+ {% if registerBeforeEntryPoint is defined %}{{ registerBeforeEntryPoint() }}{% endif %}@compute @workgroup_size(128, 1, 1)
239
+ fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32,
240
+ @builtin(subgroup_size) width: u32, @builtin(subgroup_invocation_id) lane: u32) {
241
+ let M = params.M;
242
+ let rowBase = wid.y * TILE_M;
243
+ let colBase = wid.x * TILE_N;
244
+ let role = min(claimMatrixSubgroupRole(width, 32u), 3u);
245
+ let nativeTopology = matrixTopologyAccepted(tid, 4u);
246
+ if (nativeTopology) {
247
+ let subgroupRow = (role / 2u) * {{ FR * 16 }}u;
248
+ let subgroupCol = (role % 2u) * {{ FC * 16 }}u;
249
+ {% for r in range(FR) %}
250
+ {% for c in range(FC) %}
251
+ var acc{{ r }}_{{ c }}: subgroup_matrix_result<f32, 16, 16>;
252
+ {% endfor %}
253
+ {% endfor %}
254
+ {% if PREFETCH %}
255
+ var nextTiles = prefetchTiles(rowBase, colBase, {{ "beginK" if SPLIT_K else "0u" }}, tid);
256
+ {% endif %}
257
+ for (var kk = {{ "beginK" if SPLIT_K else "0u" }}; kk < {{ "endK" if SPLIT_K else "K" }}; kk += TILE_K) {
258
+ {% if PREFETCH %}
259
+ stagePrefetchedTiles(nextTiles, tid);
260
+ {% else %}
261
+ loadTiles(rowBase, colBase, kk, tid);
262
+ {% endif %}
263
+ workgroupBarrier();
264
+ {% if PREFETCH %}
265
+ if (kk + TILE_K < {{ "endK" if SPLIT_K else "K" }}) { nextTiles = prefetchTiles(rowBase, colBase, kk + TILE_K, tid); }
266
+ {% endif %}
267
+ {% for step in range(0, BK, 16) %}
268
+ {
269
+ {% for r in range(FR) %}
270
+ {{ load_left_fragment(r, step) }}
271
+ {% endfor %}
272
+ {% for c in range(FC) %}
273
+ {{ load_right_fragment(c, step) }}
274
+ {% endfor %}
275
+ {% for r in range(FR) %}
276
+ {% for c in range(FC) %}
277
+ {{ multiply_fragment(r, c) }}
278
+ {% endfor %}
279
+ {% endfor %}
280
+ }
281
+ {% endfor %}
282
+ workgroupBarrier();
283
+ }
284
+ let scratchBase = role * 64u;
285
+ {% for r in range(FR) %}
286
+ {% for c in range(FC) %}
287
+ {
288
+ subgroupMatrixStore<row_major>(&tileA, scratchBase, acc{{ r }}_{{ c }}, 4u);
289
+ workgroupBarrier();
290
+ let row = rowBase + subgroupRow + {{ r * 16 }}u + lane / 2u;
291
+ let col = colBase + subgroupCol + {{ c * 16 }}u + (lane % 2u) * 8u;
292
+ if ({{ half_output_guard() }}) {
293
+ let first = bitcast<vec4<f32>>(tileA[scratchBase + lane * 2u]);
294
+ let second = bitcast<vec4<f32>>(tileA[scratchBase + lane * 2u + 1u]);
295
+ let values = array<f32, 8>(first.x, first.y, first.z, first.w, second.x, second.y, second.z, second.w);
296
+ {{ store_half_result() }}
297
+ }
298
+ workgroupBarrier();
299
+ }
300
+ {% endfor %}
301
+ {% endfor %}
302
+ } else {
303
+ for (var slot = 0u; slot < {{ OUT_SLOTS }}u; slot += 1u) {
304
+ let flat = tid + slot * 128u;
305
+ let tileRow = flat / {{ (BN / 8) | int }}u;
306
+ let tileCol = (flat % {{ (BN / 8) | int }}u) * 8u;
307
+ var acc: array<f32, 8>;
308
+ {% for component in range(8) %} acc[{{ component }}] = 0.0;
309
+ {% endfor %} for (var kk = {{ "beginK" if SPLIT_K else "0u" }}; kk < {{ "endK" if SPLIT_K else "K" }}; kk += TILE_K) {
310
+ loadTiles(rowBase, colBase, kk, tid);
311
+ workgroupBarrier();
312
+ for (var k = 0u; k < TILE_K; k += 1u) {
313
+ let left = readA(tileRow, k);
314
+ for (var component = 0u; component < 8u; component += 1u) {
315
+ acc[component] = fma(left, readB(k, tileCol + component), acc[component]);
316
+ }
317
+ }
318
+ workgroupBarrier();
319
+ }
320
+ let row = rowBase + tileRow;
321
+ let col = colBase + tileCol;
322
+ if ({{ half_output_guard() }}) {
323
+ let values = array<f32, 8>(
324
+ {% for component in range(8) %}
325
+ acc[{{ component }}u]{{ "," if component != 7 else "" }}
326
+ {% endfor %}
327
+ );
328
+ {{ store_half_result() }}
329
+ }
330
+ }
331
+ }
332
+ }
build/webgpu/fused-matmul-subgroup-matrix.wgsl.jinja CHANGED
@@ -1,15 +1,21 @@
 
1
  // com.microsoft.FusedMatMul subgroup-matrix specialization: Y = alpha * op(A) @ op(B).
2
  // transA and transB transpose the corresponding matrix operand on load.
3
  // Dense batches map through workgroup_id.z, and M-tail rows are guarded by row_limit.
4
  // The row count M arrives per call in `params.M`, so one pipeline serves every M;
5
  // K, N and the batch layout compile in.
6
- // A K % 32 == 0 gate keeps the reduction loop whole; N is free of the 64-wide column
7
- // tile because nTailSafe clamps the trailing tile's B columns to N - 1 and guards
8
- // every store on col < N. Both operands stage through workgroup memory, so
 
 
 
 
9
  // subgroupMatrixLoad only ever reads the full tile_A/tile_B arrays and never sees a
10
  // partial 8x8 tile at any M or N. The clamp is not interchangeable with a zero fill:
11
  // an out-of-bounds subgroupMatrixLoad resets to offset 0 and returns a different
12
  // valid tile, and a duplicated real column keeps the discarded accumulators finite.
 
13
  // The batch is required to match between A and B (no broadcast) because a_base and
14
  // b_base both index by the same workgroup_id.z.
15
  enable subgroups;
@@ -46,12 +52,12 @@ var<workgroup> tile_A: array<{{ operandScalar }}, 32 * 32>;
46
  var<workgroup> tile_B: array<{{ operandScalar }}, 64 * 32>;
47
  var<workgroup> scratch: array<array<array<{{ accScalar }}, 64>, 4>, 4>;
48
 
49
- fn loadSHMA(a_base: u32, tile_base: u32, k_idx: u32, row: u32, c_idx: u32) {
50
  let a_global = tile_base + row;
51
  let col = c_idx * 8u;
52
  for (var col_offset = 0u; col_offset < 8u; col_offset = col_offset + 1u) {
53
  let k = k_idx + col + col_offset;
54
- if (a_global < params.M) {
55
  {% if transA %}
56
  // op(A) = A^T: A stored [.., K, M], so op(A)[a_global, k] = A[k, a_global].
57
  tile_A[row * TILE_K + col + col_offset] = {{ operandScalar }}(a[a_base + k * params.M + a_global]);
@@ -75,6 +81,12 @@ fn loadSHMB(b_base: u32, tile_base: u32, k_idx: u32, row: u32, c_idx: u32) {
75
  let col = c_idx * 16u;
76
  for (var i = 0u; i < 16u; i = i + 1u) {
77
  let k = k_idx + col + i;
 
 
 
 
 
 
78
  {% if transB %}
79
  // op(B) = B^T: B stored [.., N, K], so op(B)[k, b_col] = B[b_col, k].
80
  tile_B[row * TILE_K + col + i] = {{ operandScalar }}(b[b_base + b_col * K + k]);
@@ -110,13 +122,76 @@ fn storeOutput(offset: u32{% if N_TAIL %}, col_base: u32{% endif %}, row: u32, c
110
  }
111
  }
112
 
113
- @compute @workgroup_size(128, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
114
- fn main(
115
- @builtin(workgroup_id) workgroup_id: vec3<u32>,
116
- @builtin(local_invocation_index) local_idx: u32,
117
- @builtin(subgroup_invocation_id) sg_id: u32,
118
- @builtin(subgroup_size) sg_size: u32
119
- ) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  let M = params.M;
121
  {% if not transBatchA %}
122
  let A_BATCH_STRIDE = M * K;
@@ -129,59 +204,67 @@ fn main(
129
  let a_global_base = workgroup_id.y * TILE_ROWS;
130
  let b_global_base = workgroup_id.x * TILE_COLS;
131
 
132
- let subtile_id = local_idx / sg_size;
133
  let subtile_idx = subtile_id / 2u;
134
  let subtile_idy = subtile_id % 2u;
135
  let base_A = subtile_idy * SUB_ROWS;
136
  let base_B = subtile_idx * SUB_COLS;
137
 
138
- var matC00: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
139
- var matC01: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
140
- var matC02: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
141
- var matC03: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
142
- var matC10: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
143
- var matC11: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
144
- var matC12: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
145
- var matC13: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
146
-
147
- for (var kidx = 0u; kidx < K; kidx = kidx + TILE_K) {
148
- loadSHMA(a_base, a_global_base, kidx, local_idx / 4u, local_idx % 4u);
149
- loadSHMB(b_base, b_global_base, kidx, local_idx / 2u, local_idx % 2u);
 
 
150
  workgroupBarrier();
151
 
152
- for (var step = 0u; step < TILE_K; step = step + 8u) {
 
153
  {% set directInputs = false %}
154
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
155
  {% for r in range(2) %}
156
- var matA{{ r }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&{{ "w" if directInputs else "tile_A" }}, matrix_a_offset{% if r > 0 %} + 8u * {{ "K" if directInputs else "TILE_K" }}{% endif %}, {{ "K" if directInputs else "TILE_K" }});
157
  {% endfor %}
158
 
159
- let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
 
160
  {% for c in range(4) %}
161
- var matB{{ c }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, col_major>(&{{ "xm" if directInputs else "tile_B" }}, matrix_b_offset{% if c > 0 %} + {{ c * 8 }}u * TILE_K{% endif %}, {{ "N" if directInputs else "TILE_K" }});
162
  {% endfor %}
163
 
164
- matC00 = subgroupMatrixMultiplyAccumulate(matA0, matB0, matC00);
165
- matC01 = subgroupMatrixMultiplyAccumulate(matA0, matB1, matC01);
166
- matC02 = subgroupMatrixMultiplyAccumulate(matA0, matB2, matC02);
167
- matC03 = subgroupMatrixMultiplyAccumulate(matA0, matB3, matC03);
168
- matC10 = subgroupMatrixMultiplyAccumulate(matA1, matB0, matC10);
169
- matC11 = subgroupMatrixMultiplyAccumulate(matA1, matB1, matC11);
170
- matC12 = subgroupMatrixMultiplyAccumulate(matA1, matB2, matC12);
171
- matC13 = subgroupMatrixMultiplyAccumulate(matA1, matB3, matC13);
172
  }
173
  workgroupBarrier();
174
- }
 
 
 
 
 
175
 
176
  // The four scratch banks are reused across the two row-groups, and each is written
177
  // by a collective subgroupMatrixStore then read across lanes by storeOutput. Barriers
178
  // give the reads visibility of the store and stop the second row-group's store from
179
  // clobbering the first's still-in-flight readback when a partial final M-tile
180
  // diverges storeOutput's guard. Without both barriers the last valid row can be corrupted.
181
- subgroupMatrixStore<row_major>(&scratch[subtile_id][0], 0u, matC00, 8u);
182
- subgroupMatrixStore<row_major>(&scratch[subtile_id][1], 0u, matC01, 8u);
183
- subgroupMatrixStore<row_major>(&scratch[subtile_id][2], 0u, matC02, 8u);
184
- subgroupMatrixStore<row_major>(&scratch[subtile_id][3], 0u, matC03, 8u);
185
  workgroupBarrier();
186
  let row = sg_id / 4u;
187
  let col = (sg_id % 4u) * 2u;
@@ -193,12 +276,34 @@ fn main(
193
  storeOutput(matrix_c_offset{% if N_TAIL %}, col_base{% endif %}, row, col, subtile_id, row_limit);
194
  workgroupBarrier();
195
 
196
- subgroupMatrixStore<row_major>(&scratch[subtile_id][0], 0u, matC10, 8u);
197
- subgroupMatrixStore<row_major>(&scratch[subtile_id][1], 0u, matC11, 8u);
198
- subgroupMatrixStore<row_major>(&scratch[subtile_id][2], 0u, matC12, 8u);
199
- subgroupMatrixStore<row_major>(&scratch[subtile_id][3], 0u, matC13, 8u);
200
  workgroupBarrier();
201
  matrix_c_offset = matrix_c_offset + 8u * N;
202
  row_limit = i32(M) - i32(a_global_base + base_A + 8u);
203
  storeOutput(matrix_c_offset{% if N_TAIL %}, col_base{% endif %}, row, col, subtile_id, row_limit);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  }
 
 
 
1
+ {% set directRight = directRightFullStages | default(false) %}
2
  // com.microsoft.FusedMatMul subgroup-matrix specialization: Y = alpha * op(A) @ op(B).
3
  // transA and transB transpose the corresponding matrix operand on load.
4
  // Dense batches map through workgroup_id.z, and M-tail rows are guarded by row_limit.
5
  // The row count M arrives per call in `params.M`, so one pipeline serves every M;
6
  // K, N and the batch layout compile in.
7
+ {% if directRight %}
8
+ // Complete reduction stages read B directly. The trailing stage pads both operands
9
+ // so every subgroup load addresses a full 8x8 fragment.
10
+ {% else %}
11
+ // The kernel is used only when K % 32 == 0, so the reduction loop has no tail; N is free of the
12
+ // 64-wide column tile because the trailing tile's B columns are clamped to N - 1 and every
13
+ // store is guarded on col < N. Both operands stage through workgroup memory, so
14
  // subgroupMatrixLoad only ever reads the full tile_A/tile_B arrays and never sees a
15
  // partial 8x8 tile at any M or N. The clamp is not interchangeable with a zero fill:
16
  // an out-of-bounds subgroupMatrixLoad resets to offset 0 and returns a different
17
  // valid tile, and a duplicated real column keeps the discarded accumulators finite.
18
+ {% endif %}
19
  // The batch is required to match between A and B (no broadcast) because a_base and
20
  // b_base both index by the same workgroup_id.z.
21
  enable subgroups;
 
52
  var<workgroup> tile_B: array<{{ operandScalar }}, 64 * 32>;
53
  var<workgroup> scratch: array<array<array<{{ accScalar }}, 64>, 4>, 4>;
54
 
55
+ fn loadSHMA(a_base: u32, tile_base: u32, k_idx: u32, row: u32, c_idx: u32{% if directRight %}, partial: bool{% endif %}) {
56
  let a_global = tile_base + row;
57
  let col = c_idx * 8u;
58
  for (var col_offset = 0u; col_offset < 8u; col_offset = col_offset + 1u) {
59
  let k = k_idx + col + col_offset;
60
+ if (a_global < params.M{% if directRight %} && (!partial || k < K){% endif %}) {
61
  {% if transA %}
62
  // op(A) = A^T: A stored [.., K, M], so op(A)[a_global, k] = A[k, a_global].
63
  tile_A[row * TILE_K + col + col_offset] = {{ operandScalar }}(a[a_base + k * params.M + a_global]);
 
81
  let col = c_idx * 16u;
82
  for (var i = 0u; i < 16u; i = i + 1u) {
83
  let k = k_idx + col + i;
84
+ {% if directRight %}
85
+ if (k >= K) {
86
+ tile_B[row * TILE_K + col + i] = {{ operandScalar }}(0.0);
87
+ continue;
88
+ }
89
+ {% endif %}
90
  {% if transB %}
91
  // op(B) = B^T: B stored [.., N, K], so op(B)[k, b_col] = B[b_col, k].
92
  tile_B[row * TILE_K + col + i] = {{ operandScalar }}(b[b_base + b_col * K + k]);
 
122
  }
123
  }
124
 
125
+ // A subgroup owns one matrix tile only after its actual population and the
126
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
127
+ // the role; local invocation IDs only publish the workgroup-wide decision.
128
+ var<workgroup> matrixRoleCount: atomic<u32>;
129
+ var<workgroup> matrixRejected: atomic<u32>;
130
+ var<workgroup> matrixAccepted: u32;
131
+
132
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
133
+ // WGSL initializes workgroup variables to zero before this entry point.
134
+ let population = subgroupBallot(true);
135
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
136
+ + countOneBits(population.z) + countOneBits(population.w);
137
+ var claimed = 0u;
138
+ if (subgroupElect()) {
139
+ claimed = atomicAdd(&matrixRoleCount, 1u);
140
+ if (width != requiredWidth || populationCount != requiredWidth) {
141
+ atomicStore(&matrixRejected, 1u);
142
+ }
143
+ }
144
+ // Reconverge every invocation before broadcasting the elected claim.
145
+ workgroupBarrier();
146
+ return subgroupBroadcastFirst(claimed);
147
+ }
148
+
149
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
150
+ if (localIndex == 0u) {
151
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
152
+ && atomicLoad(&matrixRoleCount) == bankCount);
153
+ }
154
+ // The uniform load both publishes the leader's decision and gives the
155
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
156
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
157
+ }
158
+ // The portable arm owns two result components per logical 32-invocation group.
159
+ // Staging casts, 8-wide K steps, barriers and the epilogue match the
160
+ // subgroup-matrix arm.
161
+ var<private> matrixSoftwareLane: u32;
162
+
163
+ fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,
164
+ acc: vec2<f32>) -> vec2<f32> {
165
+ var value = acc;
166
+ for (var k = 0u; k < 8u; k += 1u) {
167
+ value = fma(vec2<f32>(lhs[k]), rhs[k], value);
168
+ }
169
+ return value;
170
+ }
171
+
172
+ {% 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 %}
173
+
174
+ {% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}
175
+ {% if kind == "left" %}array<f32, 8>(
176
+ {% 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 "" }}
177
+ {% endfor %})
178
+ {% else %}array<vec2<f32>, 8>(
179
+ {% for k in range(8) %}vec2<f32>(
180
+ {% 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 "" }}
181
+ {% endfor %}){{ "," if k < 7 else "" }}
182
+ {% endfor %})
183
+ {% endif %}{% endif %}{% endmacro %}
184
+
185
+ {% 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 %}
186
+
187
+ {% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{
188
+ let matrixPointer = {{ pointer }};
189
+ let matrixValue = {{ value }};
190
+ {% 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" }};
191
+ {% endfor %}}{% endif %}{% endmacro %}
192
+
193
+ {% macro matrixKernelBody(matrixSoftware) %}
194
+
195
  let M = params.M;
196
  {% if not transBatchA %}
197
  let A_BATCH_STRIDE = M * K;
 
204
  let a_global_base = workgroup_id.y * TILE_ROWS;
205
  let b_global_base = workgroup_id.x * TILE_COLS;
206
 
207
+ let subtile_id = matrixRole;
208
  let subtile_idx = subtile_id / 2u;
209
  let subtile_idy = subtile_id % 2u;
210
  let base_A = subtile_idy * SUB_ROWS;
211
  let base_B = subtile_idx * SUB_COLS;
212
 
213
+ var matC00: {{ matrixType(matrixSoftware, "result", accScalar) }};
214
+ var matC01: {{ matrixType(matrixSoftware, "result", accScalar) }};
215
+ var matC02: {{ matrixType(matrixSoftware, "result", accScalar) }};
216
+ var matC03: {{ matrixType(matrixSoftware, "result", accScalar) }};
217
+ var matC10: {{ matrixType(matrixSoftware, "result", accScalar) }};
218
+ var matC11: {{ matrixType(matrixSoftware, "result", accScalar) }};
219
+ var matC12: {{ matrixType(matrixSoftware, "result", accScalar) }};
220
+ var matC13: {{ matrixType(matrixSoftware, "result", accScalar) }};
221
+
222
+ {% macro contractionStage(kBase, steps, partial=false) %}
223
+ loadSHMA(a_base, a_global_base, {{ kBase }}, local_idx / 4u, local_idx % 4u{% if directRight %}, {{ "true" if partial else "false" }}{% endif %});
224
+ {% if partial or not directRight %}
225
+ loadSHMB(b_base, b_global_base, {{ kBase }}, local_idx / 2u, local_idx % 2u);
226
+ {% endif %}
227
  workgroupBarrier();
228
 
229
+ for (var step = 0u; step < {{ steps }}; step = step + 8u) {
230
+ {% set matrixRightStorage = "b" if directRight and not partial else "" %}
231
  {% set directInputs = false %}
232
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
233
  {% for r in range(2) %}
234
+ var matA{{ r }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ ("w" if directInputs else "tile_A"), ("matrix_a_offset" ~ (" + 8u * " ~ ("K" if directInputs else "TILE_K") if r > 0 else "")), "K" if directInputs else "TILE_K") }};
235
  {% endfor %}
236
 
237
+ {% set storageB = matrixRightStorage | default("xm" if directInputs else "") %}
238
+ let matrix_b_offset = {% if storageB %}b_base + (kidx + step) * N + b_global_base + subtile_idx * SUB_COLS{% else %}subtile_idx * SUB_COLS * TILE_K + step{% endif %};
239
  {% for c in range(4) %}
240
+ var matB{{ c }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {% set stepBPointer %}&{{ storageB if storageB else "tile_B" }}{% endset %}{{ matrixLoad(matrixSoftware, "right", operandScalar, ("row_major" if storageB else "col_major"), stepBPointer, ("matrix_b_offset" ~ (" + " ~ (c * 8) ~ "u" ~ (" * TILE_K" if not storageB else "") if c > 0 else "")), "N" if storageB else "TILE_K") }};
241
  {% endfor %}
242
 
243
+ matC00 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB0", "matC00") }};
244
+ matC01 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB1", "matC01") }};
245
+ matC02 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB2", "matC02") }};
246
+ matC03 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB3", "matC03") }};
247
+ matC10 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB0", "matC10") }};
248
+ matC11 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB1", "matC11") }};
249
+ matC12 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB2", "matC12") }};
250
+ matC13 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB3", "matC13") }};
251
  }
252
  workgroupBarrier();
253
+ {% endmacro %}
254
+ for (var kidx = 0u; kidx < {% if directRight %}{{ K - K % 32 }}u{% else %}K{% endif %}; kidx = kidx + TILE_K) {
255
+ {{ contractionStage("kidx", "TILE_K") }} }
256
+ {% if directRight %}
257
+ {{ contractionStage((K - K % 32) ~ "u", (K % 32) ~ "u", true) }}
258
+ {% endif %}
259
 
260
  // The four scratch banks are reused across the two row-groups, and each is written
261
  // by a collective subgroupMatrixStore then read across lanes by storeOutput. Barriers
262
  // give the reads visibility of the store and stop the second row-group's store from
263
  // clobbering the first's still-in-flight readback when a partial final M-tile
264
  // diverges storeOutput's guard. Without both barriers the last valid row can be corrupted.
265
+ {% for c in range(4) %}
266
+ {{ matrixStore(matrixSoftware, "row_major", "&scratch[subtile_id][" ~ c ~ "]", "0u", "matC0" ~ c, "8u") | indent(2, true) }}
267
+ {% endfor %}
 
268
  workgroupBarrier();
269
  let row = sg_id / 4u;
270
  let col = (sg_id % 4u) * 2u;
 
276
  storeOutput(matrix_c_offset{% if N_TAIL %}, col_base{% endif %}, row, col, subtile_id, row_limit);
277
  workgroupBarrier();
278
 
279
+ {% for c in range(4) %}
280
+ {{ matrixStore(matrixSoftware, "row_major", "&scratch[subtile_id][" ~ c ~ "]", "0u", "matC1" ~ c, "8u") | indent(2, true) }}
281
+ {% endfor %}
 
282
  workgroupBarrier();
283
  matrix_c_offset = matrix_c_offset + 8u * N;
284
  row_limit = i32(M) - i32(a_global_base + base_A + 8u);
285
  storeOutput(matrix_c_offset{% if N_TAIL %}, col_base{% endif %}, row, col, subtile_id, row_limit);
286
+
287
+ {% endmacro %}
288
+ {% macro matrix_topology_entry(workgroupSize, bankCount, workgroupName, laneName) %}
289
+ @compute @workgroup_size({{ workgroupSize }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
290
+ fn main(
291
+ @builtin(workgroup_id) {{ workgroupName }}: vec3<u32>,
292
+ @builtin(local_invocation_index) local_idx: u32,
293
+ @builtin(subgroup_size) matrixPhysicalWidth: u32,
294
+ @builtin(subgroup_invocation_id) matrixPhysicalLane: u32
295
+ ) {
296
+ let matrixRole = claimMatrixSubgroupRole(matrixPhysicalWidth, 32u);
297
+ let matrixAcceptedHere = matrixTopologyAccepted(local_idx, {{ bankCount }});
298
+ matrixSoftwareLane = local_idx % 32u;
299
+ if (matrixAcceptedHere) {
300
+ let {{ laneName }} = matrixPhysicalLane;
301
+ {{ matrixKernelBody(false) }}
302
+ } else {
303
+ let matrixRole = local_idx / 32u;
304
+ let {{ laneName }} = local_idx % 32u;
305
+ {{ matrixKernelBody(true) }}
306
+ }
307
  }
308
+ {% endmacro %}
309
+ {{ matrix_topology_entry("128", "128u / 32u", "workgroup_id", "sg_id") }}
build/webgpu/manifest.json CHANGED
The diff for this file is too large to render. See raw diff
 
build/webgpu/matmul-subgroup-matrix-ext.wgsl.jinja CHANGED
@@ -1,6 +1,8 @@
1
  // Subgroup-matrix matmul over row-major, batch-outermost operands, with alpha,
2
  // dense/broadcast batching and guarded K/N tails under `generalAddressing`, and
3
  // an optional fused bias on the direct dense path that omits it.
 
 
4
  enable subgroups;
5
  {% if pinSubgroupSize32 %}
6
  enable subgroup_size_control;
@@ -8,17 +10,19 @@ enable subgroup_size_control;
8
  enable chromium_experimental_subgroup_matrix;
9
  diagnostic(off, chromium.subgroup_matrix_uniformity);
10
 
 
11
  {{ env.wgsl.resourceDeclarations }}
12
  {% set operandScalar = fScalar %}
 
13
  {% set accScalar = "f32" %}
14
  {% set GENERAL = true %}
15
  {% set TAIL = tailSafe is defined and tailSafe %}
16
  {% set SPLIT_K = splitK if splitK is defined else 1 %}
17
  {% set OUT = outputBuffer if outputBuffer is defined else "c" %}
18
  {% set OUT_SCALAR = outScalar if outScalar is defined else T %}
19
- {% set STATIC_M = M is defined %}
20
- {% set ROWS = "M" if STATIC_M else "params.M" %}
21
- {% set ROW_TEST = "a_global < M" if STATIC_M else "row_in" %}
22
  {% set aDims = (aShape | default([])) if STATIC_M else (aBatchShape | default([])) %}
23
  {% set kPerSplit = kPerSplit | default(0) %}
24
  {% set aR = aRank %}
@@ -32,9 +36,6 @@ diagnostic(off, chromium.subgroup_matrix_uniformity);
32
  {% set bNStride = bShape[bR-2] if bTransposed is defined and bTransposed else 1 %}
33
  {% if bStorageStrides is defined %}{% set bKStride = bStorageStrides[bR-2] %}{% set bNStride = bStorageStrides[bR-1] %}{% endif %}
34
 
35
- {% if STATIC_M %}
36
- const M: u32 = {{ M }}u;
37
- {% endif %}
38
  const K: u32 = {{ K }}u;
39
  const N: u32 = {{ N }}u;
40
  const BATCH_COUNT: u32 = {{ batchCount if batchCount is defined else 1 }}u;
@@ -49,9 +50,6 @@ const B_N_STRIDE: u32 = {{ bNStride }}u;
49
  {% if TAIL %}const K_FULL: u32 = (K / 32u) * 32u;
50
  {% endif %}
51
  const ALPHA: f32 = f32({{ alpha }});
52
- {% if STATIC_M %}
53
- const C_BATCH_STRIDE: u32 = M * N;
54
- {% endif %}
55
  const TILE_COLS: u32 = 64u;
56
  const TILE_ROWS: u32 = 32u;
57
  const TILE_K: u32 = 32u;
@@ -64,24 +62,14 @@ var<workgroup> scratch: array<array<array<{{ accScalar }}, 64>, 4>, 4>;
64
 
65
  fn loadSHMA(a_base: u32, tile_base: u32, k_idx: u32, row: u32, c_idx: u32) {
66
  let a_global = tile_base + row;
67
- {% if not STATIC_M %}
68
  let row_in = a_global < params.M;
69
- {% endif %}
70
  let col = c_idx * 8u;
71
  for (var col_offset = 0u; col_offset < 8u; col_offset = col_offset + 1u) {
72
  let k = k_idx + col + col_offset;
73
  if ({{ ROW_TEST }}) {
74
- {% if operandScalar == "f16" %}
75
- tile_A[row * TILE_K + col + col_offset] = f16(a[a_base + a_global * A_M_STRIDE + k * A_K_STRIDE]);
76
- {% else %}
77
- tile_A[row * TILE_K + col + col_offset] = f32(a[a_base + a_global * A_M_STRIDE + k * A_K_STRIDE]);
78
- {% endif %}
79
  } else {
80
- {% if operandScalar == "f16" %}
81
- tile_A[row * TILE_K + col + col_offset] = 0.0h;
82
- {% else %}
83
- tile_A[row * TILE_K + col + col_offset] = 0.0;
84
- {% endif %}
85
  }
86
  }
87
  }
@@ -109,13 +97,9 @@ fn loadSHMB(b_base: u32, tile_base: u32, k_idx: u32, row: u32, c_idx: u32) {
109
  let k = k_idx + col + i;
110
  {% if TAIL %}
111
  let b_safe = min(b_col, N - 1u);
112
- tile_B[row * TILE_K + col + i] = {{ operandScalar }}(b[b_base + k * B_K_STRIDE + b_safe * B_N_STRIDE]);
113
- {% else %}
114
- {% if operandScalar == "f16" %}
115
- tile_B[row * TILE_K + col + i] = f16(b[b_base + k * B_K_STRIDE + b_col * B_N_STRIDE]);
116
  {% else %}
117
- tile_B[row * TILE_K + col + i] = f32(b[b_base + k * B_K_STRIDE + b_col * B_N_STRIDE]);
118
- {% endif %}
119
  {% endif %}
120
  }
121
  }
@@ -127,9 +111,9 @@ fn loadSHMBKTail(b_base: u32, tile_base: u32, k_idx: u32, row: u32, c_idx: u32)
127
  for (var i = 0u; i < 16u; i = i + 1u) {
128
  let k = k_idx + col + i;
129
  if (k < K) {
130
- tile_B[row * TILE_K + col + i] = {{ operandScalar }}(b[b_base + k * B_K_STRIDE + b_col * B_N_STRIDE]);
131
  } else {
132
- tile_B[row * TILE_K + col + i] = {{ operandScalar }}(0);
133
  }
134
  }
135
  }
@@ -144,14 +128,14 @@ fn storeOutput(offset: u32{% if needsColBase %}, col_base: u32{% endif %}, row:
144
  if (col_base + col + {{ block * 8 }}u < N) {
145
  {% endif %}
146
  {{ OUT }}[offset + row * N + col + {{ block * 8 }}u] = {{ OUT_SCALAR }}(
147
- ALPHA * scratch[src_slot][{{ block }}][row * 8u + col]
148
  );
149
  {% if TAIL %}
150
  }
151
  if (col_base + col2 + {{ block * 8 }}u < N) {
152
  {% endif %}
153
  {{ OUT }}[offset + row * N + col2 + {{ block * 8 }}u] = {{ OUT_SCALAR }}(
154
- ALPHA * scratch[src_slot][{{ block }}][row * 8u + col2]
155
  );
156
  {% if TAIL %}
157
  }
@@ -160,22 +144,82 @@ fn storeOutput(offset: u32{% if needsColBase %}, col_base: u32{% endif %}, row:
160
  }
161
  }
162
 
163
- @compute @workgroup_size(128, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
164
- fn main(
165
- @builtin(workgroup_id) workgroup_id: vec3<u32>,
166
- @builtin(num_workgroups) num_wg: vec3<u32>,
167
- @builtin(local_invocation_index) local_idx: u32,
168
- @builtin(subgroup_invocation_id) sg_id: u32,
169
- @builtin(subgroup_size) sg_size: u32
170
- ) {
171
- {% if not STATIC_M %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  // The row count arrives per call; the strides it scales are formed here.
173
  let M = params.M;
174
  let C_BATCH_STRIDE = M * N;
175
- {% endif %}
176
  let b_global_base = workgroup_id.x * TILE_COLS;
177
 
178
- let subtile_id = local_idx / sg_size;
179
  let subtile_idx = subtile_id / 2u;
180
  let subtile_idy = subtile_id % 2u;
181
  let base_A = subtile_idy * SUB_ROWS;
@@ -244,14 +288,14 @@ fn main(
244
  let c_base = batch * C_BATCH_STRIDE;
245
  {% endif %}
246
 
247
- var matC00: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
248
- var matC01: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
249
- var matC02: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
250
- var matC03: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
251
- var matC10: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
252
- var matC11: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
253
- var matC12: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
254
- var matC13: subgroup_matrix_result<{{ accScalar }}, 8, 8>;
255
 
256
  {% if SPLIT_K > 1 %}
257
  let k_begin = split_id * K_PER_SPLIT;
@@ -268,22 +312,23 @@ fn main(
268
  {% set directInputs = false %}
269
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
270
  {% for r in range(2) %}
271
- var matA{{ r }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&{{ "w" if directInputs else "tile_A" }}, matrix_a_offset{% if r > 0 %} + 8u * {{ "K" if directInputs else "TILE_K" }}{% endif %}, {{ "K" if directInputs else "TILE_K" }});
272
  {% endfor %}
273
 
 
274
  let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
275
  {% for c in range(4) %}
276
- var matB{{ c }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, col_major>(&{{ "xm" if directInputs else "tile_B" }}, matrix_b_offset{% if c > 0 %} + {{ c * 8 }}u * TILE_K{% endif %}, {{ "N" if directInputs else "TILE_K" }});
277
  {% endfor %}
278
 
279
- matC00 = subgroupMatrixMultiplyAccumulate(matA0, matB0, matC00);
280
- matC01 = subgroupMatrixMultiplyAccumulate(matA0, matB1, matC01);
281
- matC02 = subgroupMatrixMultiplyAccumulate(matA0, matB2, matC02);
282
- matC03 = subgroupMatrixMultiplyAccumulate(matA0, matB3, matC03);
283
- matC10 = subgroupMatrixMultiplyAccumulate(matA1, matB0, matC10);
284
- matC11 = subgroupMatrixMultiplyAccumulate(matA1, matB1, matC11);
285
- matC12 = subgroupMatrixMultiplyAccumulate(matA1, matB2, matC12);
286
- matC13 = subgroupMatrixMultiplyAccumulate(matA1, matB3, matC13);
287
  }
288
  workgroupBarrier();
289
  }
@@ -297,22 +342,23 @@ fn main(
297
  {% set directInputs = false %}
298
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
299
  {% for r in range(2) %}
300
- var matA{{ r }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&{{ "w" if directInputs else "tile_A" }}, matrix_a_offset{% if r > 0 %} + 8u * {{ "K" if directInputs else "TILE_K" }}{% endif %}, {{ "K" if directInputs else "TILE_K" }});
301
  {% endfor %}
302
 
 
303
  let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
304
  {% for c in range(4) %}
305
- var matB{{ c }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, col_major>(&{{ "xm" if directInputs else "tile_B" }}, matrix_b_offset{% if c > 0 %} + {{ c * 8 }}u * TILE_K{% endif %}, {{ "N" if directInputs else "TILE_K" }});
306
  {% endfor %}
307
 
308
- matC00 = subgroupMatrixMultiplyAccumulate(matA0, matB0, matC00);
309
- matC01 = subgroupMatrixMultiplyAccumulate(matA0, matB1, matC01);
310
- matC02 = subgroupMatrixMultiplyAccumulate(matA0, matB2, matC02);
311
- matC03 = subgroupMatrixMultiplyAccumulate(matA0, matB3, matC03);
312
- matC10 = subgroupMatrixMultiplyAccumulate(matA1, matB0, matC10);
313
- matC11 = subgroupMatrixMultiplyAccumulate(matA1, matB1, matC11);
314
- matC12 = subgroupMatrixMultiplyAccumulate(matA1, matB2, matC12);
315
- matC13 = subgroupMatrixMultiplyAccumulate(matA1, matB3, matC13);
316
  }
317
  workgroupBarrier();
318
  }
@@ -323,10 +369,9 @@ fn main(
323
  // give the reads visibility of the store AND stop the second row-group's store from
324
  // clobbering the first's still-in-flight readback when a partial final M-tile
325
  // diverges storeOutput's guard. Without both barriers the last valid row can be corrupted.
326
- subgroupMatrixStore<row_major>(&scratch[subtile_id][0], 0u, matC00, 8u);
327
- subgroupMatrixStore<row_major>(&scratch[subtile_id][1], 0u, matC01, 8u);
328
- subgroupMatrixStore<row_major>(&scratch[subtile_id][2], 0u, matC02, 8u);
329
- subgroupMatrixStore<row_major>(&scratch[subtile_id][3], 0u, matC03, 8u);
330
  workgroupBarrier();
331
  let row = sg_id / 4u;
332
  let col = (sg_id % 4u) * 2u;
@@ -336,10 +381,9 @@ fn main(
336
  storeOutput(matrix_c_offset{% if needsColBase %}, col_base{% endif %}, row, col, subtile_id, row_limit);
337
  workgroupBarrier();
338
 
339
- subgroupMatrixStore<row_major>(&scratch[subtile_id][0], 0u, matC10, 8u);
340
- subgroupMatrixStore<row_major>(&scratch[subtile_id][1], 0u, matC11, 8u);
341
- subgroupMatrixStore<row_major>(&scratch[subtile_id][2], 0u, matC12, 8u);
342
- subgroupMatrixStore<row_major>(&scratch[subtile_id][3], 0u, matC13, 8u);
343
  workgroupBarrier();
344
  matrix_c_offset = matrix_c_offset + 8u * N;
345
  row_limit = i32(M) - i32(a_global_base + base_A + 8u);
@@ -354,4 +398,24 @@ fn main(
354
  // reaches this barrier together.
355
  workgroupBarrier();
356
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  }
 
1
  // Subgroup-matrix matmul over row-major, batch-outermost operands, with alpha,
2
  // dense/broadcast batching and guarded K/N tails under `generalAddressing`, and
3
  // an optional fused bias on the direct dense path that omits it.
4
+ {% set matmulExtScratchRef = "scratch" %}
5
+ {% set matmulExtTileBRef = "tile_B" %}
6
  enable subgroups;
7
  {% if pinSubgroupSize32 %}
8
  enable subgroup_size_control;
 
10
  enable chromium_experimental_subgroup_matrix;
11
  diagnostic(off, chromium.subgroup_matrix_uniformity);
12
 
13
+
14
  {{ env.wgsl.resourceDeclarations }}
15
  {% set operandScalar = fScalar %}
16
+ {% set operandZero = "0.0h" if operandScalar == "f16" else "0.0" %}
17
  {% set accScalar = "f32" %}
18
  {% set GENERAL = true %}
19
  {% set TAIL = tailSafe is defined and tailSafe %}
20
  {% set SPLIT_K = splitK if splitK is defined else 1 %}
21
  {% set OUT = outputBuffer if outputBuffer is defined else "c" %}
22
  {% set OUT_SCALAR = outScalar if outScalar is defined else T %}
23
+ {% set STATIC_M = false %}
24
+ {% set ROWS = "params.M" %}
25
+ {% set ROW_TEST = "row_in" %}
26
  {% set aDims = (aShape | default([])) if STATIC_M else (aBatchShape | default([])) %}
27
  {% set kPerSplit = kPerSplit | default(0) %}
28
  {% set aR = aRank %}
 
36
  {% set bNStride = bShape[bR-2] if bTransposed is defined and bTransposed else 1 %}
37
  {% if bStorageStrides is defined %}{% set bKStride = bStorageStrides[bR-2] %}{% set bNStride = bStorageStrides[bR-1] %}{% endif %}
38
 
 
 
 
39
  const K: u32 = {{ K }}u;
40
  const N: u32 = {{ N }}u;
41
  const BATCH_COUNT: u32 = {{ batchCount if batchCount is defined else 1 }}u;
 
50
  {% if TAIL %}const K_FULL: u32 = (K / 32u) * 32u;
51
  {% endif %}
52
  const ALPHA: f32 = f32({{ alpha }});
 
 
 
53
  const TILE_COLS: u32 = 64u;
54
  const TILE_ROWS: u32 = 32u;
55
  const TILE_K: u32 = 32u;
 
62
 
63
  fn loadSHMA(a_base: u32, tile_base: u32, k_idx: u32, row: u32, c_idx: u32) {
64
  let a_global = tile_base + row;
 
65
  let row_in = a_global < params.M;
 
66
  let col = c_idx * 8u;
67
  for (var col_offset = 0u; col_offset < 8u; col_offset = col_offset + 1u) {
68
  let k = k_idx + col + col_offset;
69
  if ({{ ROW_TEST }}) {
70
+ tile_A[row * TILE_K + col + col_offset] = {{ operandScalar }}(a[a_base + a_global * A_M_STRIDE + k * A_K_STRIDE]);
 
 
 
 
71
  } else {
72
+ tile_A[row * TILE_K + col + col_offset] = {{ operandZero }};
 
 
 
 
73
  }
74
  }
75
  }
 
97
  let k = k_idx + col + i;
98
  {% if TAIL %}
99
  let b_safe = min(b_col, N - 1u);
100
+ {{ matmulExtTileBRef }}[row * TILE_K + col + i] = {{ operandScalar }}(b[b_base + k * B_K_STRIDE + b_safe * B_N_STRIDE]);
 
 
 
101
  {% else %}
102
+ tile_B[row * TILE_K + col + i] = {{ operandScalar }}(b[b_base + k * B_K_STRIDE + b_col * B_N_STRIDE]);
 
103
  {% endif %}
104
  }
105
  }
 
111
  for (var i = 0u; i < 16u; i = i + 1u) {
112
  let k = k_idx + col + i;
113
  if (k < K) {
114
+ {{ matmulExtTileBRef }}[row * TILE_K + col + i] = {{ operandScalar }}(b[b_base + k * B_K_STRIDE + b_col * B_N_STRIDE]);
115
  } else {
116
+ {{ matmulExtTileBRef }}[row * TILE_K + col + i] = {{ operandScalar }}(0);
117
  }
118
  }
119
  }
 
128
  if (col_base + col + {{ block * 8 }}u < N) {
129
  {% endif %}
130
  {{ OUT }}[offset + row * N + col + {{ block * 8 }}u] = {{ OUT_SCALAR }}(
131
+ ALPHA * {{ matmulExtScratchRef }}[src_slot][{{ block }}][row * 8u + col]
132
  );
133
  {% if TAIL %}
134
  }
135
  if (col_base + col2 + {{ block * 8 }}u < N) {
136
  {% endif %}
137
  {{ OUT }}[offset + row * N + col2 + {{ block * 8 }}u] = {{ OUT_SCALAR }}(
138
+ ALPHA * {{ matmulExtScratchRef }}[src_slot][{{ block }}][row * 8u + col2]
139
  );
140
  {% if TAIL %}
141
  }
 
144
  }
145
  }
146
 
147
+ // A subgroup owns one matrix tile only after its actual population and the
148
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
149
+ // the role; local invocation IDs only publish the workgroup-wide decision.
150
+ var<workgroup> matrixRoleCount: atomic<u32>;
151
+ var<workgroup> matrixRejected: atomic<u32>;
152
+ var<workgroup> matrixAccepted: u32;
153
+
154
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
155
+ // WGSL initializes workgroup variables to zero before this entry point.
156
+ let population = subgroupBallot(true);
157
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
158
+ + countOneBits(population.z) + countOneBits(population.w);
159
+ var claimed = 0u;
160
+ if (subgroupElect()) {
161
+ claimed = atomicAdd(&matrixRoleCount, 1u);
162
+ if (width != requiredWidth || populationCount != requiredWidth) {
163
+ atomicStore(&matrixRejected, 1u);
164
+ }
165
+ }
166
+ // Reconverge every invocation before broadcasting the elected claim.
167
+ workgroupBarrier();
168
+ return subgroupBroadcastFirst(claimed);
169
+ }
170
+
171
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
172
+ if (localIndex == 0u) {
173
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
174
+ && atomicLoad(&matrixRoleCount) == bankCount);
175
+ }
176
+ // The uniform load both publishes the leader's decision and gives the
177
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
178
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
179
+ }
180
+ // The portable arm owns two result components per logical 32-invocation group.
181
+ // Staging casts, 8-wide K steps, barriers and the epilogue match the
182
+ // subgroup-matrix arm.
183
+ var<private> matrixSoftwareLane: u32;
184
+
185
+ fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,
186
+ acc: vec2<f32>) -> vec2<f32> {
187
+ var value = acc;
188
+ for (var k = 0u; k < 8u; k += 1u) {
189
+ value = fma(vec2<f32>(lhs[k]), rhs[k], value);
190
+ }
191
+ return value;
192
+ }
193
+
194
+ {% 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 %}
195
+
196
+ {% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}
197
+ {% if kind == "left" %}array<f32, 8>(
198
+ {% 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 "" }}
199
+ {% endfor %})
200
+ {% else %}array<vec2<f32>, 8>(
201
+ {% for k in range(8) %}vec2<f32>(
202
+ {% 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 "" }}
203
+ {% endfor %}){{ "," if k < 7 else "" }}
204
+ {% endfor %})
205
+ {% endif %}{% endif %}{% endmacro %}
206
+
207
+ {% 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 %}
208
+
209
+ {% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{
210
+ let matrixPointer = {{ pointer }};
211
+ let matrixValue = {{ value }};
212
+ {% 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" }};
213
+ {% endfor %}}{% endif %}{% endmacro %}
214
+
215
+ {% macro matrixKernelBody(matrixSoftware) %}
216
+
217
  // The row count arrives per call; the strides it scales are formed here.
218
  let M = params.M;
219
  let C_BATCH_STRIDE = M * N;
 
220
  let b_global_base = workgroup_id.x * TILE_COLS;
221
 
222
+ let subtile_id = matrixRole;
223
  let subtile_idx = subtile_id / 2u;
224
  let subtile_idy = subtile_id % 2u;
225
  let base_A = subtile_idy * SUB_ROWS;
 
288
  let c_base = batch * C_BATCH_STRIDE;
289
  {% endif %}
290
 
291
+ var matC00: {{ matrixType(matrixSoftware, "result", accScalar) }};
292
+ var matC01: {{ matrixType(matrixSoftware, "result", accScalar) }};
293
+ var matC02: {{ matrixType(matrixSoftware, "result", accScalar) }};
294
+ var matC03: {{ matrixType(matrixSoftware, "result", accScalar) }};
295
+ var matC10: {{ matrixType(matrixSoftware, "result", accScalar) }};
296
+ var matC11: {{ matrixType(matrixSoftware, "result", accScalar) }};
297
+ var matC12: {{ matrixType(matrixSoftware, "result", accScalar) }};
298
+ var matC13: {{ matrixType(matrixSoftware, "result", accScalar) }};
299
 
300
  {% if SPLIT_K > 1 %}
301
  let k_begin = split_id * K_PER_SPLIT;
 
312
  {% set directInputs = false %}
313
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
314
  {% for r in range(2) %}
315
+ var matA{{ r }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ ("w" if directInputs else "tile_A"), ("matrix_a_offset" ~ (" + 8u * " ~ ("K" if directInputs else "TILE_K") if r > 0 else "")), "K" if directInputs else "TILE_K") }};
316
  {% endfor %}
317
 
318
+ {% set storageB = "" %}
319
  let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
320
  {% for c in range(4) %}
321
+ var matB{{ c }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {% set stepBPointer %}&{{ storageB if storageB else "tile_B" }}{% endset %}{{ matrixLoad(matrixSoftware, "right", operandScalar, ("row_major" if storageB else "col_major"), stepBPointer, ("matrix_b_offset" ~ (" + " ~ (c * 8) ~ "u" ~ (" * TILE_K" if not storageB else "") if c > 0 else "")), "N" if storageB else "TILE_K") }};
322
  {% endfor %}
323
 
324
+ matC00 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB0", "matC00") }};
325
+ matC01 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB1", "matC01") }};
326
+ matC02 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB2", "matC02") }};
327
+ matC03 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB3", "matC03") }};
328
+ matC10 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB0", "matC10") }};
329
+ matC11 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB1", "matC11") }};
330
+ matC12 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB2", "matC12") }};
331
+ matC13 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB3", "matC13") }};
332
  }
333
  workgroupBarrier();
334
  }
 
342
  {% set directInputs = false %}
343
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
344
  {% for r in range(2) %}
345
+ var matA{{ r }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ ("w" if directInputs else "tile_A"), ("matrix_a_offset" ~ (" + 8u * " ~ ("K" if directInputs else "TILE_K") if r > 0 else "")), "K" if directInputs else "TILE_K") }};
346
  {% endfor %}
347
 
348
+ {% set storageB = "" %}
349
  let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
350
  {% for c in range(4) %}
351
+ var matB{{ c }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {% set stepBPointer %}&{{ storageB if storageB else "tile_B" }}{% endset %}{{ matrixLoad(matrixSoftware, "right", operandScalar, ("row_major" if storageB else "col_major"), stepBPointer, ("matrix_b_offset" ~ (" + " ~ (c * 8) ~ "u" ~ (" * TILE_K" if not storageB else "") if c > 0 else "")), "N" if storageB else "TILE_K") }};
352
  {% endfor %}
353
 
354
+ matC00 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB0", "matC00") }};
355
+ matC01 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB1", "matC01") }};
356
+ matC02 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB2", "matC02") }};
357
+ matC03 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB3", "matC03") }};
358
+ matC10 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB0", "matC10") }};
359
+ matC11 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB1", "matC11") }};
360
+ matC12 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB2", "matC12") }};
361
+ matC13 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB3", "matC13") }};
362
  }
363
  workgroupBarrier();
364
  }
 
369
  // give the reads visibility of the store AND stop the second row-group's store from
370
  // clobbering the first's still-in-flight readback when a partial final M-tile
371
  // diverges storeOutput's guard. Without both barriers the last valid row can be corrupted.
372
+ {% for c in range(4) %}
373
+ {{ matrixStore(matrixSoftware, "row_major", "&" ~ matmulExtScratchRef ~ "[subtile_id][" ~ c ~ "]", "0u", "matC0" ~ c, "8u") | indent(4, true) }}
374
+ {% endfor %}
 
375
  workgroupBarrier();
376
  let row = sg_id / 4u;
377
  let col = (sg_id % 4u) * 2u;
 
381
  storeOutput(matrix_c_offset{% if needsColBase %}, col_base{% endif %}, row, col, subtile_id, row_limit);
382
  workgroupBarrier();
383
 
384
+ {% for c in range(4) %}
385
+ {{ matrixStore(matrixSoftware, "row_major", "&" ~ matmulExtScratchRef ~ "[subtile_id][" ~ c ~ "]", "0u", "matC1" ~ c, "8u") | indent(4, true) }}
386
+ {% endfor %}
 
387
  workgroupBarrier();
388
  matrix_c_offset = matrix_c_offset + 8u * N;
389
  row_limit = i32(M) - i32(a_global_base + base_A + 8u);
 
398
  // reaches this barrier together.
399
  workgroupBarrier();
400
  }
401
+
402
+ {% endmacro %}
403
+ @compute @workgroup_size(128, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
404
+ fn main(
405
+ @builtin(workgroup_id) workgroup_id: vec3<u32>,
406
+ @builtin(num_workgroups) num_wg: vec3<u32>,
407
+ @builtin(local_invocation_index) local_idx: u32,
408
+ @builtin(subgroup_invocation_id) sg_id: u32,
409
+ @builtin(subgroup_size) sg_size: u32
410
+ ) {
411
+ let matrixRole = claimMatrixSubgroupRole(sg_size, 32u);
412
+ let matrixAcceptedHere = matrixTopologyAccepted(local_idx, 128u / 32u);
413
+ matrixSoftwareLane = local_idx % 32u;
414
+ if (matrixAcceptedHere) {
415
+ {{ matrixKernelBody(false) }}
416
+ } else {
417
+ let matrixRole = local_idx / 32u;
418
+ let sg_id = local_idx % 32u;
419
+ {{ matrixKernelBody(true) }}
420
+ }
421
  }
build/webgpu/matmul-tiled-general-reg.wgsl.jinja CHANGED
@@ -1,7 +1,7 @@
1
  {{ env.wgsl.resourceDeclarations }}
2
 
3
- // Register-blocked MatMul for the no-subgroup-matrix
4
- // tier: Y = alpha * A @ B. It retains the bounds-checked addressing and
5
  // batch-broadcast of the general kernel, and its transposed-batch-A layout.
6
  // A retains its matrix-axis order; B may transpose its matrix axes.
7
  // 1-D operands use other variants.
@@ -37,7 +37,6 @@
37
  {% endif %}
38
  {% set accT = scalar if is_int else "f32" %}
39
  {% set outScalar = outScalar if outScalar is defined else scalar %}
40
- {% set splitK = splitK if splitK is defined else 1 %}
41
  {% if scalar == "f16" %}
42
  // f16 operands stay packed in workgroup memory and widen on shared load;
43
  // accumulation remains f32.
@@ -59,19 +58,23 @@ const B_N_STRIDE: u32 = {{ bNStride }}u;
59
  // per-thread accumulator footprint of an 8x8 micro-tile.
60
  {% set microTile = 4 %}
61
  {% set lanes = 16 %}
 
 
 
62
  const BK: u32 = {{ kTile }}u;
63
  const BM: u32 = {{ registerTile }}u;
64
  const BN: u32 = {{ registerTile }}u;
65
  const TM: u32 = {{ microTile }}u; // per-thread micro-tile rows
66
  const TN: u32 = {{ microTile }}u; // per-thread micro-tile cols
67
- {% if splitK > 1 %}
68
- const SPLIT_K: u32 = {{ splitK }}u;
69
- const K_PER_SPLIT: u32 = {{ kPerSplit }}u;
70
-
71
- {% endif %}
72
  const K_VECS: u32 = BK / 4u;
73
  var<workgroup> tileA: array<array<vec4<{{ tileT }}>, K_VECS>, BM>; // A[m][k/4]
 
 
 
 
 
74
  var<workgroup> tileB: array<array<vec4<{{ tileT }}>, K_VECS>, BN>; // B[n][k/4]
 
75
  {% set hasBatchCoord = namespace(value=false) %}
76
  {% for i in range(batchRank) %}
77
  {% set axis = batchRank - 1 - i %}
@@ -97,12 +100,8 @@ fn main(
97
  let li = lid.y * {{ lanes }}u + lid.x;
98
 
99
  let zOut = wg.z;
100
- {% if splitK > 1 %}
101
- let splitId = wg.z % SPLIT_K;
102
- {% else %}
103
  {% if hasBatchCoord.value %}
104
  var zTmp = wg.z;
105
- {% endif %}
106
  {% endif %}
107
  var aBatchOff: u32 = 0u;
108
  var bBatchOff: u32 = 0u;
@@ -130,20 +129,13 @@ fn main(
130
  {% endfor %}
131
 
132
  var acc: array<{{ accT }}, TM * TN>; // [ti*TN + tj] for the TMxTN micro-tile
 
133
  for (var i: u32 = 0u; i < TM * TN; i = i + 1u) { acc[i] = {{ accT }}(0); }
 
134
 
135
- {% if splitK > 1 %}
136
- let kStart = splitId * K_PER_SPLIT;
137
- let numTiles = K_PER_SPLIT / BK;
138
- {% else %}
139
  let numTiles = (K + BK - 1u) / BK;
140
- {% endif %}
141
  for (var kt: u32 = 0u; kt < numTiles; kt = kt + 1u) {
142
- {% if splitK > 1 %}
143
- let kBase = kStart + kt * BK;
144
- {% else %}
145
  let kBase = kt * BK;
146
- {% endif %}
147
  // Cooperative load: one vector word per lane per pass. A's lanes walk K, which
148
  // it stores contiguously; B's walk N, which it stores contiguously.
149
  for (var idx: u32 = li; idx < BM * K_VECS; idx = idx + {{ lanes * lanes }}u) {
@@ -172,18 +164,54 @@ fn main(
172
  if (bk + {{ component }}u < K) { bWord[{{ component }}u] = {{ tileT }}(b[bColOff + (bk + {{ component }}u) * B_K_STRIDE]); }
173
  {% endfor %}
174
  }
 
 
 
 
 
 
175
  tileB[bc][br4] = bWord;
 
176
  }
177
  workgroupBarrier();
178
- {% set regT = accT %}{% filter indent(4, true) %}
 
 
179
  {% set regAccumulator = "acc" %}
 
 
 
 
 
 
180
  let aRow = lid.y * TM;
181
- let bCol = lid.x * TN;
 
182
  for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  var av: array<vec4<{{ regT }}>, TM>;
184
  var bv: array<vec4<{{ regT }}>, TN>;
185
- for (var i: u32 = 0u; i < TM; i = i + 1u) { av[i] = vec4<{{ regT }}>(tileA[aRow + i][kv]); }
186
- for (var j: u32 = 0u; j < TN; j = j + 1u) { bv[j] = vec4<{{ regT }}>(tileB[bCol + j][kv]); }
187
  for (var i: u32 = 0u; i < TM; i = i + 1u) {
188
  for (var j: u32 = 0u; j < TN; j = j + 1u) {
189
  {% if regSequentialK is defined and regSequentialK %}
@@ -195,22 +223,33 @@ for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {
195
  {% endif %}
196
  }
197
  }
198
- }
 
199
  {% endfilter %}
200
  workgroupBarrier();
201
  }
202
 
203
  let rowBase = zOut * M * N;
204
  let m0 = mBase + lid.y * TM;
205
- let n0 = nBase + lid.x * TN;
 
 
 
 
 
 
 
 
 
206
  for (var ti: u32 = 0u; ti < TM; ti = ti + 1u) {
207
  let m = m0 + ti;
208
  if (m >= M) { continue; }
209
  for (var tj: u32 = 0u; tj < TN; tj = tj + 1u) {
210
- let n = n0 + tj;
211
  if (n < N) {
212
  y[rowBase + m * N + n] = {{ outScalar }}(ALPHA * acc[ti * TN + tj]);
213
  }
214
  }
215
  }
 
216
  }
 
1
  {{ env.wgsl.resourceDeclarations }}
2
 
3
+ // Register-blocked MatMul for devices without subgroup
4
+ // matrices: Y = alpha * A @ B. It retains the bounds-checked addressing and
5
  // batch-broadcast of the general kernel, and its transposed-batch-A layout.
6
  // A retains its matrix-axis order; B may transpose its matrix axes.
7
  // 1-D operands use other variants.
 
37
  {% endif %}
38
  {% set accT = scalar if is_int else "f32" %}
39
  {% set outScalar = outScalar if outScalar is defined else scalar %}
 
40
  {% if scalar == "f16" %}
41
  // f16 operands stay packed in workgroup memory and widen on shared load;
42
  // accumulation remains f32.
 
58
  // per-thread accumulator footprint of an 8x8 micro-tile.
59
  {% set microTile = 4 %}
60
  {% set lanes = 16 %}
61
+ {% set bColumnStride = lanes if kTile > 4 else 0 %}
62
+ {% set bHalfWords = bColumnStride and tileT != "f16" and tiledRegBHalfWords %}
63
+ {% set bColumnStep = bColumnStride if bColumnStride else 1 %}
64
  const BK: u32 = {{ kTile }}u;
65
  const BM: u32 = {{ registerTile }}u;
66
  const BN: u32 = {{ registerTile }}u;
67
  const TM: u32 = {{ microTile }}u; // per-thread micro-tile rows
68
  const TN: u32 = {{ microTile }}u; // per-thread micro-tile cols
 
 
 
 
 
69
  const K_VECS: u32 = BK / 4u;
70
  var<workgroup> tileA: array<array<vec4<{{ tileT }}>, K_VECS>, BM>; // A[m][k/4]
71
+ {% if bHalfWords %}
72
+ var<workgroup> tileB: array<array<vec2<{{ tileT }}>, BN>, 2u * K_VECS>; // B[k/2][n]
73
+ {% elif bColumnStride %}
74
+ var<workgroup> tileB: array<array<vec4<{{ tileT }}>, BN>, K_VECS>; // B[k/4][n]
75
+ {% else %}
76
  var<workgroup> tileB: array<array<vec4<{{ tileT }}>, K_VECS>, BN>; // B[n][k/4]
77
+ {% endif %}
78
  {% set hasBatchCoord = namespace(value=false) %}
79
  {% for i in range(batchRank) %}
80
  {% set axis = batchRank - 1 - i %}
 
100
  let li = lid.y * {{ lanes }}u + lid.x;
101
 
102
  let zOut = wg.z;
 
 
 
103
  {% if hasBatchCoord.value %}
104
  var zTmp = wg.z;
 
105
  {% endif %}
106
  var aBatchOff: u32 = 0u;
107
  var bBatchOff: u32 = 0u;
 
129
  {% endfor %}
130
 
131
  var acc: array<{{ accT }}, TM * TN>; // [ti*TN + tj] for the TMxTN micro-tile
132
+ {% if not tiledRegUnrolledMicroTile %}
133
  for (var i: u32 = 0u; i < TM * TN; i = i + 1u) { acc[i] = {{ accT }}(0); }
134
+ {% endif %}
135
 
 
 
 
 
136
  let numTiles = (K + BK - 1u) / BK;
 
137
  for (var kt: u32 = 0u; kt < numTiles; kt = kt + 1u) {
 
 
 
138
  let kBase = kt * BK;
 
139
  // Cooperative load: one vector word per lane per pass. A's lanes walk K, which
140
  // it stores contiguously; B's walk N, which it stores contiguously.
141
  for (var idx: u32 = li; idx < BM * K_VECS; idx = idx + {{ lanes * lanes }}u) {
 
164
  if (bk + {{ component }}u < K) { bWord[{{ component }}u] = {{ tileT }}(b[bColOff + (bk + {{ component }}u) * B_K_STRIDE]); }
165
  {% endfor %}
166
  }
167
+ {% if bHalfWords %}
168
+ tileB[2u * br4][bc] = bWord.xy;
169
+ tileB[2u * br4 + 1u][bc] = bWord.zw;
170
+ {% elif bColumnStride %}
171
+ tileB[br4][bc] = bWord;
172
+ {% else %}
173
  tileB[bc][br4] = bWord;
174
+ {% endif %}
175
  }
176
  workgroupBarrier();
177
+ {% set regT = accT %}{% set regColumnStride = bColumnStride %}{% set regBHalfWords = bHalfWords %}
178
+ {% set regUnroll = microTile if tiledRegUnrolledMicroTile else 0 %}
179
+ {% filter indent(4, true) %}
180
  {% set regAccumulator = "acc" %}
181
+ {% set regColumnStride = regColumnStride | default(0) %}
182
+ {% set regUnroll = regUnroll | default(0) %}
183
+ {% set regStaticK = 0 %}
184
+ {% macro regKAddress(literalKv, scale=1, offset=0) %}{% if regStaticK %}{{ scale * literalKv + offset }}u{% else %}{% if scale != 1 %}{{ scale }}u * {% endif %}kv{% if offset %} + {{ offset }}u{% endif %}{% endif %}{% endmacro %}
185
+ {% macro regARead(row, literalKv) %}{% set aK = regKAddress(literalKv) %}vec4<{{ regT }}>(tileA[{{ row }}][{{ aK }}]){% endmacro %}
186
+ {% macro regBRead(column, literalKv) %}{% if regColumnStride and (regBHalfWords | default(false)) %}vec4<{{ regT }}>(tileB[{{ regKAddress(literalKv, 2) }}][{{ column }}], tileB[{{ regKAddress(literalKv, 2, 1) }}][{{ column }}]){% else %}{% set bK = regKAddress(literalKv) %}{% set regBWord = ("tileB[" ~ bK ~ "][" ~ column ~ "]") if regColumnStride else ("tileB[" ~ column ~ "][" ~ bK ~ "]") %}vec4<{{ regT }}>({{ regBWord }}){% endif %}{% endmacro %}
187
  let aRow = lid.y * TM;
188
+ let bCol = lid.x{% if not regColumnStride %} * TN{% endif %};
189
+ {% for literalKv in range(regStaticK // 4 if regStaticK else 1) %}
190
  for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {
191
+ {% if regUnroll %}
192
+ {% for i in range(regUnroll) %}
193
+ let a{{ i }} = {{ regARead("aRow + " ~ i ~ "u", literalKv) }};
194
+ {% endfor %}
195
+ {% for j in range(regUnroll) %}
196
+ let b{{ j }} = {{ regBRead("bCol + " ~ (j * regColumnStride if regColumnStride else j) ~ "u", literalKv) }};
197
+ {% endfor %}
198
+ {% for i in range(regUnroll) %}
199
+ {% for j in range(regUnroll) %}
200
+ {% set regSlot = regAccumulator ~ "[" ~ (i * regUnroll + j) ~ "u]" %}
201
+ {% if regSequentialK is defined and regSequentialK %}
202
+ {% for component in range(4) %}
203
+ {{ regSlot }} = {{ regSlot }} + a{{ i }}[{{ component }}] * b{{ j }}[{{ component }}];
204
+ {% endfor %}
205
+ {% else %}
206
+ {{ regSlot }} = {{ regSlot }} + dot(a{{ i }}, b{{ j }});
207
+ {% endif %}
208
+ {% endfor %}
209
+ {% endfor %}
210
+ {% else %}
211
  var av: array<vec4<{{ regT }}>, TM>;
212
  var bv: array<vec4<{{ regT }}>, TN>;
213
+ for (var i: u32 = 0u; i < TM; i = i + 1u) { av[i] = {{ regARead("aRow + i", literalKv) }}; }
214
+ for (var j: u32 = 0u; j < TN; j = j + 1u) { bv[j] = {{ regBRead(("bCol + j * " ~ regColumnStride ~ "u") if regColumnStride else "bCol + j", literalKv) }}; }
215
  for (var i: u32 = 0u; i < TM; i = i + 1u) {
216
  for (var j: u32 = 0u; j < TN; j = j + 1u) {
217
  {% if regSequentialK is defined and regSequentialK %}
 
223
  {% endif %}
224
  }
225
  }
226
+ {% endif %}
227
+ }{% endfor %}
228
  {% endfilter %}
229
  workgroupBarrier();
230
  }
231
 
232
  let rowBase = zOut * M * N;
233
  let m0 = mBase + lid.y * TM;
234
+ let n0 = nBase + lid.x{% if not bColumnStride %} * TN{% endif %};
235
+ {% if tiledRegUnrolledMicroTile %}
236
+ {% for i in range(microTile) %}
237
+ if (m0 + {{ i }}u < M) {
238
+ {% for j in range(microTile) %}
239
+ if (n0 + {{ j * bColumnStep }}u < N) { y[rowBase + (m0 + {{ i }}u) * N + n0 + {{ j * bColumnStep }}u] = {{ outScalar }}(ALPHA * acc[{{ i * microTile + j }}u]); }
240
+ {% endfor %}
241
+ }
242
+ {% endfor %}
243
+ {% else %}
244
  for (var ti: u32 = 0u; ti < TM; ti = ti + 1u) {
245
  let m = m0 + ti;
246
  if (m >= M) { continue; }
247
  for (var tj: u32 = 0u; tj < TN; tj = tj + 1u) {
248
+ let n = n0 + tj{% if bColumnStride %} * {{ bColumnStride }}u{% endif %};
249
  if (n < N) {
250
  y[rowBase + m * N + n] = {{ outScalar }}(ALPHA * acc[ti * TN + tj]);
251
  }
252
  }
253
  }
254
+ {% endif %}
255
  }
build/webgpu/matmul-tiled-general.wgsl.jinja CHANGED
@@ -18,16 +18,19 @@
18
  * [d1, ..., dR-2, d0, dR-1]. Stored axis zero becomes the M axis, the final K
19
  * axis is unchanged, and the remaining axes form the batch. This stride
20
  * permutation composes with the ordinary last-two-axis transpose. */
21
- {% set STATIC_M = true %}
22
  {% set aDims = aShape if aShape is defined else (aBatchShape | default([])) %}
23
  {% set aTailStride = namespace(v=1) %}
24
- {% for j in range(1, aR) %}{% set aTailStride.v = aTailStride.v * aShape[j] %}{% endfor %}{% set bTailStride = namespace(v=1) %}
 
25
  {% for j in range(1, bR) %}{% set bTailStride.v = bTailStride.v * bShape[j] %}{% endfor %}
 
26
  {% if aVec %}{% set M = 1 %}{% set K = aShape[0] %}
27
  {% elif transBatchA and transA %}{% set M = aShape[aR-1] %}{% set K = aShape[0] %}
28
  {% elif transBatchA %}{% set M = aShape[0] %}{% set K = aShape[aR-1] %}
29
  {% elif transA %}{% set M = aShape[aR-1] %}{% set K = aShape[aR-2] %}
30
  {% else %}{% set M = aShape[aR-2] %}{% set K = aShape[aR-1] %}{% endif %}
 
31
  {% if bVec %}{% set N = 1 %}
32
  {% elif transBatchB and transB %}{% set N = bShape[0] %}
33
  {% elif transB %}{% set N = bShape[bR-2] %}
@@ -46,7 +49,9 @@
46
  {% set is_int = (scalar == "i32" or scalar == "u32") %}
47
  {% set accT = scalar if is_int else "f32" %}
48
  {% set tileT = scalar if scalar == "f16" else accT %}
 
49
  const M: u32 = {{ M }}u;
 
50
  const K: u32 = {{ K }}u;
51
  const N: u32 = {{ N }}u;
52
  const A_M_STRIDE: u32 = {{ aMStride }}u;
@@ -83,6 +88,9 @@ fn main(
83
  @builtin(workgroup_id) wg: vec3<u32>,
84
  @builtin(local_invocation_id) lid: vec3<u32>
85
  ) {
 
 
 
86
  let mBase = wg.y * BM;
87
  let nBase = wg.x * BN;
88
  let li = lid.y * {{ lanes }}u + lid.x;
@@ -113,7 +121,7 @@ fn main(
113
  let c{{ axis }} = zTmp % {{ outDim }}u;
114
  {% endif %}
115
  zTmp = zTmp / {{ outDim }}u;
116
- {% if aStride.v != 0 %} aBatchOff = aBatchOff + c{{ axis }} * {{ aStride.v }}u;
117
  {% endif %}
118
  {% if bStride.v != 0 %} bBatchOff = bBatchOff + c{{ axis }} * {{ bStride.v }}u;
119
  {% endif %}
 
18
  * [d1, ..., dR-2, d0, dR-1]. Stored axis zero becomes the M axis, the final K
19
  * axis is unchanged, and the remaining axes form the batch. This stride
20
  * permutation composes with the ordinary last-two-axis transpose. */
21
+ {% set STATIC_M = aShape is defined %}
22
  {% set aDims = aShape if aShape is defined else (aBatchShape | default([])) %}
23
  {% set aTailStride = namespace(v=1) %}
24
+ {% if aShape is defined %}{% for j in range(1, aR) %}{% set aTailStride.v = aTailStride.v * aShape[j] %}{% endfor %}{% endif %}
25
+ {% set bTailStride = namespace(v=1) %}
26
  {% for j in range(1, bR) %}{% set bTailStride.v = bTailStride.v * bShape[j] %}{% endfor %}
27
+ {% if aShape is defined %}
28
  {% if aVec %}{% set M = 1 %}{% set K = aShape[0] %}
29
  {% elif transBatchA and transA %}{% set M = aShape[aR-1] %}{% set K = aShape[0] %}
30
  {% elif transBatchA %}{% set M = aShape[0] %}{% set K = aShape[aR-1] %}
31
  {% elif transA %}{% set M = aShape[aR-1] %}{% set K = aShape[aR-2] %}
32
  {% else %}{% set M = aShape[aR-2] %}{% set K = aShape[aR-1] %}{% endif %}
33
+ {% endif %}
34
  {% if bVec %}{% set N = 1 %}
35
  {% elif transBatchB and transB %}{% set N = bShape[0] %}
36
  {% elif transB %}{% set N = bShape[bR-2] %}
 
49
  {% set is_int = (scalar == "i32" or scalar == "u32") %}
50
  {% set accT = scalar if is_int else "f32" %}
51
  {% set tileT = scalar if scalar == "f16" else accT %}
52
+ {% if STATIC_M %}
53
  const M: u32 = {{ M }}u;
54
+ {% endif %}
55
  const K: u32 = {{ K }}u;
56
  const N: u32 = {{ N }}u;
57
  const A_M_STRIDE: u32 = {{ aMStride }}u;
 
88
  @builtin(workgroup_id) wg: vec3<u32>,
89
  @builtin(local_invocation_id) lid: vec3<u32>
90
  ) {
91
+ {% if not STATIC_M %}
92
+ let M = params.M;
93
+ {% endif %}
94
  let mBase = wg.y * BM;
95
  let nBase = wg.x * BN;
96
  let li = lid.y * {{ lanes }}u + lid.x;
 
121
  let c{{ axis }} = zTmp % {{ outDim }}u;
122
  {% endif %}
123
  zTmp = zTmp / {{ outDim }}u;
124
+ {% if aStride.v != 0 %} aBatchOff = aBatchOff + c{{ axis }} * {% if STATIC_M %}{{ aStride.v }}u{% else %}{% if aStride.v != 1 %}{{ aStride.v }}u * {% endif %}M * K{% endif %};
125
  {% endif %}
126
  {% if bStride.v != 0 %} bBatchOff = bBatchOff + c{{ axis }} * {{ bStride.v }}u;
127
  {% endif %}
build/webgpu/matmul-vector-matrix-vec4.wgsl.jinja CHANGED
@@ -1,7 +1,7 @@
1
  // GEMV specialization for y[N] = a[K] @ B[K, N]. Each workgroup owns 32
2
  // consecutive vec4 column groups, or 128 output columns.
3
  {{ env.wgsl.resourceDeclarations }}
4
- {% set OUT = outputBuffer if outputBuffer is defined else "c" %}
5
 
6
  const LANES: u32 = {{ gemvLanes }}u;
7
  // SLICES partitions the K reduction across the workgroup's second dimension.
 
1
  // GEMV specialization for y[N] = a[K] @ B[K, N]. Each workgroup owns 32
2
  // consecutive vec4 column groups, or 128 output columns.
3
  {{ env.wgsl.resourceDeclarations }}
4
+ {% set OUT = "c" %}
5
 
6
  const LANES: u32 = {{ gemvLanes }}u;
7
  // SLICES partitions the K reduction across the workgroup's second dimension.
build/webgpu/matrix-shaped-projection-gemm.wgsl.jinja ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% set WIDTH = matrixSubgroupWidth | default(32) %}
2
+ {% set GROUPS = (128 / WIDTH) | int %}
3
+ {% set OWNED = (WIDTH / 32) | int %}
4
+ {% set STAGE_K = 32 %}
5
+ {% set CELLS_PER_THREAD = 8 %}
6
+ enable subgroups;
7
+ enable chromium_experimental_subgroup_matrix;
8
+ diagnostic(off, chromium.subgroup_matrix_uniformity);
9
+ {{ env.wgsl.resourceDeclarations }}
10
+ const M: u32 = {{ M }}u;
11
+ const N: u32 = {{ N }}u;
12
+ const K: u32 = {{ K }}u;
13
+ const TILE_M: u32 = {{ matrixM * 2 }}u;
14
+ const TILE_N: u32 = {{ matrixN * 2 }}u;
15
+ const TILE_K: u32 = {{ STAGE_K }}u;
16
+ var<workgroup> tileA: array<{{ operandScalar }}, {{ matrixM * 2 * STAGE_K }}>;
17
+ var<workgroup> tileB: array<{{ operandScalar }}, {{ STAGE_K * matrixN * 2 }}>;
18
+ var<workgroup> tileC: array<{{ accumulatorScalar }}, {{ matrixM * 2 * matrixN * 2 }}>;
19
+
20
+ {% macro shapedLoadA(
21
+ row,
22
+ k,
23
+ supertonicPartial=matrixSupertonicPartial | default(false),
24
+ qatGrouped=matrixQatGrouped | default(false),
25
+ aOffset=matrixAOffset | default(none),
26
+ aRowStride=matrixARowStride | default(none),
27
+ aKStride=matrixAKStride | default(none),
28
+ batch1=matrixBatch1 | default(none),
29
+ aBatch0Stride=matrixABatch0Stride | default(none),
30
+ aBatch1Stride=matrixABatch1Stride | default(none)
31
+ ) %}a[{{ aOffset }}u + {{ row }} * {{ aRowStride }}u + {{ k }} * {{ aKStride }}u{%
32
+ if matrixBatched %} + (batch / {{ batch1 }}u) * {{ aBatch0Stride }}u + (batch % {{ batch1 }}u) * {{ aBatch1Stride }}u{%
33
+ endif %}]{%
34
+ endmacro %}
35
+ {% macro shapedLoadB(
36
+ k,
37
+ col,
38
+ bOffset=matrixBOffset | default(none),
39
+ repeatB=matrixRepeatB | default(none),
40
+ bKStride=matrixBKStride | default(none),
41
+ bColStride=matrixBColStride | default(none),
42
+ batch1=matrixBatch1 | default(none),
43
+ bBatch0Stride=matrixBBatch0Stride | default(none),
44
+ bBatch1Stride=matrixBBatch1Stride | default(none)
45
+ ) %}b[{{ bOffset }}u + {{ k }} * {{ bKStride }}u + {{ col }} * {{ bColStride }}u{%
46
+ if matrixBatched %} + (batch / {{ batch1 }}u) * {{ bBatch0Stride }}u + (batch % {{ batch1 }}u) * {{ bBatch1Stride }}u{%
47
+ endif %}]{%
48
+ endmacro %}
49
+ {% macro shapedWrite(
50
+ value,
51
+ row,
52
+ col,
53
+ beta=matrixBeta | default(none),
54
+ groups=matrixGroups | default(none),
55
+ qatGrouped=matrixQatGrouped | default(false),
56
+ yStride=matrixYStride | default(none),
57
+ yColumnOffset=matrixYColumnOffset | default(none),
58
+ batch1=matrixBatch1 | default(none),
59
+ yBatch1Stride=matrixYBatch1Stride | default(none),
60
+ yBatchStride=matrixYBatchStride | default(none)
61
+ ) %}
62
+ {
63
+ var result = f32({{ matrixAlpha }}) * f32({{ value }});
64
+
65
+
66
+ y[{{ row }} * {{ yStride }}u + {{ col }} + {{ yColumnOffset }}u{% if matrixBatched %} + batch * {{ yBatchStride }}u{% endif %}] = {{ outputScalar }}(result);
67
+ }
68
+ {% endmacro %}
69
+ fn loadTiles(rowBase: u32, colBase: u32, kBase: u32, tid: u32{% if matrixBatched %}, batch: u32{% endif %}) {
70
+ for (var flat = tid; flat < TILE_M * TILE_K; flat += 128u) {
71
+ let row = rowBase + flat / TILE_K;
72
+ let k = kBase + flat % TILE_K;
73
+ var value = {{ operandScalar }}(0);
74
+ if (row < M && k < K) { value = {{ operandScalar }}({{ shapedLoadA("row", "k") }}); }
75
+ tileA[flat] = value;
76
+ }
77
+ for (var flat = tid; flat < TILE_K * TILE_N; flat += 128u) {
78
+ let k = kBase + flat / TILE_N;
79
+ let col = colBase + flat % TILE_N;
80
+ var value = {{ operandScalar }}(0);
81
+ if (k < K && col < N) { value = {{ operandScalar }}({{ shapedLoadB("k", "col") }}); }
82
+ tileB[flat] = value;
83
+ }
84
+ }
85
+
86
+ // A subgroup owns one matrix tile only after its actual population and the
87
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
88
+ // the role; local invocation IDs only publish the workgroup-wide decision.
89
+ var<workgroup> matrixRoleCount: atomic<u32>;
90
+ var<workgroup> matrixRejected: atomic<u32>;
91
+ var<workgroup> matrixAccepted: u32;
92
+
93
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
94
+ // WGSL initializes workgroup variables to zero before this entry point.
95
+ let population = subgroupBallot(true);
96
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
97
+ + countOneBits(population.z) + countOneBits(population.w);
98
+ var claimed = 0u;
99
+ if (subgroupElect()) {
100
+ claimed = atomicAdd(&matrixRoleCount, 1u);
101
+ if (width != requiredWidth || populationCount != requiredWidth) {
102
+ atomicStore(&matrixRejected, 1u);
103
+ }
104
+ }
105
+ // Reconverge every invocation before broadcasting the elected claim.
106
+ workgroupBarrier();
107
+ return subgroupBroadcastFirst(claimed);
108
+ }
109
+
110
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
111
+ if (localIndex == 0u) {
112
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
113
+ && atomicLoad(&matrixRoleCount) == bankCount);
114
+ }
115
+ // The uniform load both publishes the leader's decision and gives the
116
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
117
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
118
+ }
119
+ @compute @workgroup_size(128, 1, 1)
120
+ fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32,
121
+ @builtin(subgroup_size) width: u32) {
122
+ {% if matrixBatched %} let batch = wid.z;
123
+ {% endif %} let rowBase = wid.y * TILE_M;
124
+ let colBase = wid.x * TILE_N; let role = claimMatrixSubgroupRole(width, {{ WIDTH }}u);
125
+ let nativeTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u);
126
+ if (nativeTopology) {
127
+ {% for slot in range(OWNED) %}
128
+ let tile{{ slot }} = role + {{ slot * GROUPS }}u;
129
+ let row{{ slot }} = (tile{{ slot }} / 2u) * {{ matrixM }}u;
130
+ let col{{ slot }} = (tile{{ slot }} % 2u) * {{ matrixN }}u;
131
+ var acc{{ slot }}: subgroup_matrix_result<{{ accumulatorScalar }}, {{ matrixN }}, {{ matrixM }}>;
132
+ {% endfor %}
133
+ for (var kk = 0u; kk < K; kk += TILE_K) {
134
+ loadTiles(rowBase, colBase, kk, tid{% if matrixBatched %}, batch{% endif %});
135
+ workgroupBarrier();
136
+ for (var step = 0u; step < TILE_K; step += {{ matrixK }}u) {
137
+ {% for slot in range(OWNED) %}
138
+ let left{{ slot }} = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, {{ matrixK }}, {{ matrixM }}>, row_major>(
139
+ &tileA, row{{ slot }} * TILE_K + step, TILE_K);
140
+ let right{{ slot }} = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, {{ matrixN }}, {{ matrixK }}>, row_major>(
141
+ &tileB, step * TILE_N + col{{ slot }}, TILE_N);
142
+ acc{{ slot }} = subgroupMatrixMultiplyAccumulate(left{{ slot }}, right{{ slot }}, acc{{ slot }});
143
+ {% endfor %}
144
+ }
145
+ workgroupBarrier();
146
+ }
147
+ {% for slot in range(OWNED) %}
148
+ subgroupMatrixStore<row_major>(&tileC, row{{ slot }} * TILE_N + col{{ slot }}, acc{{ slot }}, TILE_N);
149
+ {% endfor %}
150
+ workgroupBarrier();
151
+ for (var flat = tid; flat < TILE_M * TILE_N; flat += 128u) {
152
+ let r = rowBase + flat / TILE_N;
153
+ let c = colBase + flat % TILE_N;
154
+ if (r < M && c < N) { {{ shapedWrite("tileC[flat]", "r", "c") }} }
155
+ }
156
+ } else {
157
+ var acc: array<{{ accumulatorScalar }}, {{ CELLS_PER_THREAD }}>;
158
+ for (var kk = 0u; kk < K; kk += TILE_K) {
159
+ loadTiles(rowBase, colBase, kk, tid{% if matrixBatched %}, batch{% endif %});
160
+ workgroupBarrier();
161
+ for (var cell = 0u; cell < {{ CELLS_PER_THREAD }}u; cell += 1u) {
162
+ let flat = tid + cell * 128u;
163
+ let row = flat / TILE_N;
164
+ let col = flat % TILE_N;
165
+ if (flat < TILE_M * TILE_N) {
166
+ for (var k = 0u; k < TILE_K; k += 1u) {
167
+ acc[cell] = fma({{ accumulatorScalar }}(tileA[row * TILE_K + k]),
168
+ {{ accumulatorScalar }}(tileB[k * TILE_N + col]), acc[cell]); }
169
+ }
170
+ }
171
+ workgroupBarrier();
172
+ }
173
+ for (var cell = 0u; cell < {{ CELLS_PER_THREAD }}u; cell += 1u) {
174
+ let flat = tid + cell * 128u;
175
+ let row = rowBase + flat / TILE_N;
176
+ let col = colBase + flat % TILE_N;
177
+ if (flat < TILE_M * TILE_N && row < M && col < N) { {{ shapedWrite("acc[cell]", "row", "col") }} }
178
+ }
179
+ }
180
+ }
build/webgpu/metadata.json CHANGED
@@ -1,45 +1 @@
1
- {
2
- "name": "com.microsoft.FusedMatMul",
3
- "id": "_com_microsoft_fusedmatmul_webgpu_17d6f48",
4
- "version": 1,
5
- "license": "Apache-2.0",
6
- "backend": { "type": "webgpu" },
7
- "digest": {
8
- "algorithm": "sha256",
9
- "files": {
10
- "bench.json": "hPORMosjCjoEdszLuJCkanMmm8j/WxJFR8aS4bZRdWw=",
11
- "fused-matmul-subgroup-matrix.wgsl.jinja": "idFWg6H0GgKnO1AG8WFLO2rXeN4cqOwW+V9dJii9Fn4=",
12
- "manifest.json": "epnZxQxVo55octrjWqNWM/cs0DsR74Cz59XvUB+MyOI=",
13
- "matmul-band-vec4.wgsl.jinja": "LKAs6A++OJF0ZEEM4JITZmKXkr/wo9gd5qrR3zDZy1g=",
14
- "matmul-subgroup-matrix-ext.wgsl.jinja": "MGpbY/2ZIE3EEnG0SmKB74zCrPmVGbnNBSw9Ml81+7c=",
15
- "matmul-tiled-general-reg.wgsl.jinja": "DGpeWkL4fuu22CI4+Yw3/QD2NON89wCggbotpFNWobE=",
16
- "matmul-tiled-general.wgsl.jinja": "j+8KKAFZDVh9M3zNFxJCU4ihsiLgI0KxpE9CD8TqF6Q=",
17
- "matmul-vector-matrix-vec4.wgsl.jinja": "Qiv2AO8MWj1BAoPLMCH98oXBasrQYFWFh/IUhdhZp5I=",
18
- "reduce-axis0-splitk-combine.wgsl.jinja": "Zf7tz8nrapi2KMZIbv8cT2f4pliJoJHj4iwS4hc/6ms=",
19
- "test.json": "LCHLBZTTSQFp/nqb55OJuX7oiL59ThEfHhocijVk5DE="
20
- }
21
- },
22
- "provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },
23
- "webgpu": {
24
- "manifestSpec": "2.1",
25
- "variants": {
26
- "broadcast_transb_tiled_reg": ["matmul-tiled-general-reg.wgsl.jinja"],
27
- "broadcast_transb_subgroup_matrix_f16": ["matmul-subgroup-matrix-ext.wgsl.jinja"],
28
- "broadcast_transb_subgroup_matrix_f32": ["matmul-subgroup-matrix-ext.wgsl.jinja"],
29
- "subgroup_matrix_transbatch_b_f16": ["matmul-subgroup-matrix-ext.wgsl.jinja"],
30
- "subgroup_matrix_transbatch_b_f32": ["matmul-subgroup-matrix-ext.wgsl.jinja"],
31
- "m1_gemv_vec4": ["matmul-vector-matrix-vec4.wgsl.jinja"],
32
- "rank2_band_vec4_splitk": ["matmul-band-vec4.wgsl.jinja", "reduce-axis0-splitk-combine.wgsl.jinja"],
33
- "rank2_band_vec4": ["matmul-band-vec4.wgsl.jinja"],
34
- "rank2_band_vec4_f32_preferred": ["matmul-band-vec4.wgsl.jinja"],
35
- "subgroup_matrix_splitk": ["matmul-subgroup-matrix-ext.wgsl.jinja", "reduce-axis0-splitk-combine.wgsl.jinja"],
36
- "subgroup_matrix_tail_broadcast": ["matmul-subgroup-matrix-ext.wgsl.jinja"],
37
- "subgroup_matrix": ["fused-matmul-subgroup-matrix.wgsl.jinja"],
38
- "broadcast_rank4_tiled_reg": ["matmul-tiled-general-reg.wgsl.jinja"],
39
- "plain_rank2_tiled_reg": ["matmul-tiled-general-reg.wgsl.jinja"],
40
- "transbatch_a_tiled_reg": ["matmul-tiled-general-reg.wgsl.jinja"],
41
- "tiled": ["matmul-tiled-general.wgsl.jinja"],
42
- "transbatch_b_tiled_reg": ["matmul-tiled-general-reg.wgsl.jinja"]
43
- }
44
- }
45
- }
 
1
+ {"name":"com.microsoft.FusedMatMul","id":"_com_microsoft_fusedmatmul_webgpu_c30f54e","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"bench.json":"AbRTB8YVpnIc2Rlo/e9e7r/LDWQJqbvYbW4xNiskY9g=","contrib-native16-packed.wgsl.jinja":"E5vMlmcAX8F+HMfvqXSJ19SDRe9TZ+lwFr9AIaO7+cA=","fused-matmul-subgroup-matrix.wgsl.jinja":"e7b7GmizBDX/G1OJ3HD968VcRW9Scoi2dhs8o8Qa6R8=","manifest.json":"Jqb5yx2dbzI4X2kbcoM0AdJYkFtFq+KXukWl6mmBuRA=","matmul-band-vec4.wgsl.jinja":"LKAs6A++OJF0ZEEM4JITZmKXkr/wo9gd5qrR3zDZy1g=","matmul-subgroup-matrix-ext.wgsl.jinja":"0T4ifXSTxTvo1t3OCUTSYm6d3baodqVYgNSE5/+unoo=","matmul-tiled-general-reg.wgsl.jinja":"FgODBs3fBtZIfYpuknJ+7k9sH9w6uqsm/2eUrqxF1kg=","matmul-tiled-general.wgsl.jinja":"rdiUrQefHlrrcdQGXAuZyqkrZPMnZx7BXg7fpMzEnLo=","matmul-vector-matrix-vec4.wgsl.jinja":"+Uk5FXKVfVEb9N04PytJ4xd/UHoMJjvT2BzE3O6OU44=","matrix-shaped-projection-gemm.wgsl.jinja":"tLZxgqzjLr2TwaO7E08rldKoroDhT22SBGs9JD17XWc=","reduce-axis0-splitk-combine.wgsl.jinja":"wOlms7ZUiBjREWqLuaEy8spVx+N1SAdB3jDdh3c9+2U=","subgroup-matrix-gemm.wgsl.jinja":"y7KQ6EjkKnYIvr8Bl3Td03ohm+YJRUikJe1pdhxV690=","test.json":"l/D837UlZurGGThWjrhU1TQC9TDBM28xNJXccfcJ3jM="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja CHANGED
@@ -1,10 +1,24 @@
1
  // Pass 2 of the split-K column-wise reduction. One invocation per output column
2
  // folds the segment partials and applies the selected reduction's final step.
3
- // Segments are folded in ascending order for deterministic results. This order
4
- // differs from the single-pass reduction but remains within the f32 tolerance.
5
  {% set yv = "f16(" if outputF16 else "" %}
6
  {% set vy = ")" if outputF16 else "" %}
7
  {{ env.wgsl.resourceDeclarations }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  {% macro wgsl_minmax_identity(name, op, scalar="f32") %}
9
  /* Exact {{ op }} reduction identity. WGSL rejects infinity during constant
10
  * evaluation, so an f32 identity is constructed from its IEEE-754 bits. */
@@ -80,7 +94,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>,
80
  {% if op == "l2" %}
81
  y[col] = {{ yv }}sqrt(total){{ vy }};
82
  {% elif op == "logsum" %}
83
- y[col] = {{ yv }}log(total){{ vy }};
84
  {% elif op == "mean" %}
85
  y[col] = {{ yv }}total / f32(params.rows){{ vy }};
86
  {% else %}
 
1
  // Pass 2 of the split-K column-wise reduction. One invocation per output column
2
  // folds the segment partials and applies the selected reduction's final step.
3
+ // Segments are folded in ascending order for deterministic results.
 
4
  {% set yv = "f16(" if outputF16 else "" %}
5
  {% set vy = ")" if outputF16 else "" %}
6
  {{ env.wgsl.resourceDeclarations }}
7
+ {% if op == "logsum" %}
8
+
9
+ // log() returns an indeterminate value outside (0, inf), so the IEEE results
10
+ // for the logarithm of a sum are chosen explicitly: a negative or NaN sum gives
11
+ // NaN, a zero sum gives -inf, and +inf stays +inf. The sum is classified by its
12
+ // bits because a value != value test may be folded away, and the special values
13
+ // are built from those bits because a constant infinity or NaN does not compile.
14
+ fn log_of_sum(total: f32) -> f32 {
15
+ let bits = bitcast<u32>(total);
16
+ let magnitude = bits & 0x7fffffffu;
17
+ let defined = select(log(total), total, magnitude == 0x7f800000u);
18
+ let zero_or_defined = select(defined, bitcast<f32>(bits | 0xff800000u), magnitude == 0u);
19
+ return select(zero_or_defined, bitcast<f32>(bits | 0x7fc00000u), magnitude > 0x7f800000u || bits > 0x80000000u);
20
+ }
21
+ {% endif %}
22
  {% macro wgsl_minmax_identity(name, op, scalar="f32") %}
23
  /* Exact {{ op }} reduction identity. WGSL rejects infinity during constant
24
  * evaluation, so an f32 identity is constructed from its IEEE-754 bits. */
 
94
  {% if op == "l2" %}
95
  y[col] = {{ yv }}sqrt(total){{ vy }};
96
  {% elif op == "logsum" %}
97
+ y[col] = {{ yv }}log_of_sum(total){{ vy }};
98
  {% elif op == "mean" %}
99
  y[col] = {{ yv }}total / f32(params.rows){{ vy }};
100
  {% else %}
build/webgpu/subgroup-matrix-gemm.wgsl.jinja ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set F16 = true -%}
2
+ {%- set EPW = 8 -%}
3
+ {%- set FK = 16 -%}
4
+ {%- set VT = "f16" -%}
5
+ {%- set ACC = "f32" -%}
6
+ {%- set SR = 2 -%}
7
+ {%- set SC = 2 -%}
8
+ {%- set FR = 2 -%}
9
+ {%- set FC = 2 -%}
10
+ {%- set BK = 32 -%}
11
+ {%- set PAD = 8 -%}
12
+ {%- set AM = sgGemmAMajor -%}
13
+ {%- set BMJ = sgGemmBMajor -%}
14
+ {%- set TM = 64 -%}
15
+ {%- set TN = 64 -%}
16
+ {%- set T = 128 -%}
17
+ {%- set A_ROWS = TM if AM == "row" else BK -%}
18
+ {%- set A_LEN = BK if AM == "row" else TM -%}
19
+ {%- set B_ROWS = BK if BMJ == "row" else TN -%}
20
+ {%- set B_LEN = TN if BMJ == "row" else BK -%}
21
+ {%- set ASTRIDE = ((A_LEN + PAD) / EPW) | int -%}
22
+ {%- set BSTRIDE = ((B_LEN + PAD) / EPW) | int -%}
23
+ {%- set A_SLOTS = 2 -%}
24
+ {%- set B_SLOTS = 2 -%}
25
+ {%- set SCRATCH = 512 -%}
26
+ {%- set A_SIZE = max(A_ROWS * ASTRIDE, SCRATCH) -%}
27
+ {%- set AOFF = "aBase + " -%}
28
+ {%- set BOFF = "bBase + " -%}
29
+ {%- set YOFF = "yBase + " -%}
30
+ {%- set GUARD_KA = not F16 or sgGemmK % BK != 0 -%}
31
+ {%- macro stage_load(name, kb) -%}
32
+ {%- set LEN = A_LEN if name == "a" else B_LEN -%}
33
+ {%- set SLOTS = A_SLOTS if name == "a" else B_SLOTS -%}
34
+ {%- for s in range(SLOTS) %}
35
+ {
36
+ let flat = tid + {{ s * T }}u;
37
+ let r = flat / {{ (LEN / EPW) | int }}u;
38
+ let c = (flat % {{ (LEN / EPW) | int }}u) * {{ EPW }}u;
39
+ {%- if name == "a" and AM == "row" %}
40
+ if (rowBase + r < M{% if GUARD_KA %} && {{ kb }} + c < K{% endif %}) { next{{ name | upper }}{{ s }} = a[({{ AOFF }}(rowBase + r) * K + {{ kb }} + c) / {{ EPW }}u]; } else { next{{ name | upper }}{{ s }} = vec4<u32>(); }
41
+ {%- elif name == "a" %}
42
+ if ({{ kb }} + r < K && rowBase + c < M) { next{{ name | upper }}{{ s }} = a[({{ AOFF }}({{ kb }} + r) * M + rowBase + c) / {{ EPW }}u]; } else { next{{ name | upper }}{{ s }} = vec4<u32>(); }
43
+ {%- elif BMJ == "row" %}
44
+ if ({{ kb }} + r < K && colBase + c < N) { next{{ name | upper }}{{ s }} = b[({{ BOFF }}({{ kb }} + r) * N + colBase + c) / {{ EPW }}u]; } else { next{{ name | upper }}{{ s }} = vec4<u32>(); }
45
+ {%- else %}
46
+ if (colBase + r < N && {{ kb }} + c < K) { next{{ name | upper }}{{ s }} = b[({{ BOFF }}(colBase + r) * K + {{ kb }} + c) / {{ EPW }}u]; } else { next{{ name | upper }}{{ s }} = vec4<u32>(); }
47
+ {%- endif %}
48
+ }
49
+ {%- endfor %}
50
+ {%- endmacro -%}
51
+ {%- macro stage_store(name) -%}
52
+ {%- set LEN = A_LEN if name == "a" else B_LEN -%}
53
+ {%- set SLOTS = A_SLOTS if name == "a" else B_SLOTS -%}
54
+ {%- set STRIDE = ASTRIDE if name == "a" else BSTRIDE -%}
55
+ {%- for s in range(SLOTS) %}
56
+ tile{{ name | upper }}[((tid + {{ s * T }}u) / {{ (LEN / EPW) | int }}u) * {{ STRIDE }}u + (tid + {{ s * T }}u) % {{ (LEN / EPW) | int }}u] = next{{ name | upper }}{{ s }};
57
+ {%- endfor %}
58
+ {%- endmacro -%}
59
+ {%- macro load_left(r, step) -%}
60
+ {%- if AM == "row" -%}
61
+ subgroupMatrixLoad<subgroup_matrix_left<{{ VT }}, {{ FK }}, 16>, row_major>(&tileA, subRow * {{ ASTRIDE }}u + {{ r * 16 * ASTRIDE + step * 2 }}u, {{ ASTRIDE }}u)
62
+ {%- else -%}
63
+ subgroupMatrixLoad<subgroup_matrix_left<{{ VT }}, {{ FK }}, 16>, col_major>(&tileA, subRow / {{ EPW }}u + {{ step * FK * ASTRIDE + ((r * 16 / EPW) | int) }}u, {{ ASTRIDE }}u)
64
+ {%- endif -%}
65
+ {%- endmacro -%}
66
+ {%- macro load_right(c, step) -%}
67
+ {%- if BMJ == "row" -%}
68
+ subgroupMatrixLoad<subgroup_matrix_right<{{ VT }}, 16, {{ FK }}>, row_major>(&tileB, subCol / {{ EPW }}u + {{ step * FK * BSTRIDE + ((c * 16 / EPW) | int) }}u, {{ BSTRIDE }}u)
69
+ {%- else -%}
70
+ subgroupMatrixLoad<subgroup_matrix_right<{{ VT }}, 16, {{ FK }}>, col_major>(&tileB, subCol * {{ BSTRIDE }}u + {{ c * 16 * BSTRIDE + step * 2 }}u, {{ BSTRIDE }}u)
71
+ {%- endif -%}
72
+ {%- endmacro -%}
73
+ {%- macro half_word(lo, hi) -%}
74
+ vec4<u32>(bitcast<u32>(vec2<f16>({{ lo }}.xy * params.alpha)), bitcast<u32>(vec2<f16>({{ lo }}.zw * params.alpha)), bitcast<u32>(vec2<f16>({{ hi }}.xy * params.alpha)), bitcast<u32>(vec2<f16>({{ hi }}.zw * params.alpha)))
75
+ {%- endmacro -%}
76
+ enable subgroups;
77
+ enable chromium_experimental_subgroup_matrix;
78
+ diagnostic(off, chromium.subgroup_matrix_uniformity);
79
+ {{ env.wgsl.resourceDeclarations }}
80
+ const N: u32 = {{ sgGemmN }}u;
81
+ const K: u32 = {{ sgGemmK }}u;
82
+ // vec4 elements give each tile a 16-byte base, which eight-bit matrix loads need.
83
+ var<workgroup> tileA: array<vec4<u32>, {{ A_SIZE }}>;
84
+ var<workgroup> tileB: array<vec4<u32>, {{ B_ROWS * BSTRIDE }}>;
85
+ // A subgroup owns one matrix tile only after its actual population and the
86
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
87
+ // the role; local invocation IDs only publish the workgroup-wide decision.
88
+ var<workgroup> matrixRoleCount: atomic<u32>;
89
+ var<workgroup> matrixRejected: atomic<u32>;
90
+ var<workgroup> matrixAccepted: u32;
91
+
92
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
93
+ // WGSL initializes workgroup variables to zero before this entry point.
94
+ let population = subgroupBallot(true);
95
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
96
+ + countOneBits(population.z) + countOneBits(population.w);
97
+ var claimed = 0u;
98
+ if (subgroupElect()) {
99
+ claimed = atomicAdd(&matrixRoleCount, 1u);
100
+ if (width != requiredWidth || populationCount != requiredWidth) {
101
+ atomicStore(&matrixRejected, 1u);
102
+ }
103
+ }
104
+ // Reconverge every invocation before broadcasting the elected claim.
105
+ workgroupBarrier();
106
+ return subgroupBroadcastFirst(claimed);
107
+ }
108
+
109
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
110
+ if (localIndex == 0u) {
111
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
112
+ && atomicLoad(&matrixRoleCount) == bankCount);
113
+ }
114
+ // The uniform load both publishes the leader's decision and gives the
115
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
116
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
117
+ }
118
+
119
+ fn halfA(e: u32) -> f32 {
120
+ return f32(bitcast<vec2<f16>>(a[e / 8u][(e % 8u) / 2u])[e % 2u]);
121
+ }
122
+ fn halfB(e: u32) -> f32 {
123
+ return f32(bitcast<vec2<f16>>(b[e / 8u][(e % 8u) / 2u])[e % 2u]);
124
+ }
125
+
126
+ @compute @workgroup_size({{ T }}, 1, 1)
127
+ fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32,
128
+ @builtin(subgroup_size) width: u32, @builtin(subgroup_invocation_id) lane: u32) {
129
+ let M = params.M;
130
+ let batchOuter = wid.z / params.batchInner;
131
+ let batchInner = wid.z - batchOuter * params.batchInner;
132
+ let aBase = batchOuter * params.aStrideOuter + batchInner * params.aStrideInner;
133
+ let bBase = batchOuter * params.bStrideOuter + batchInner * params.bStrideInner;
134
+ let yBase = wid.z * M * N;
135
+ let rowBase = wid.y * {{ TM }}u;
136
+ let colBase = wid.x * {{ TN }}u;
137
+ let role = min(claimMatrixSubgroupRole(width, 32u), {{ SR * SC - 1 }}u);
138
+ if (matrixTopologyAccepted(tid, {{ SR * SC }}u)) {
139
+ let subRow = (role / {{ SC }}u) * {{ FR * 16 }}u;
140
+ let subCol = (role % {{ SC }}u) * {{ FC * 16 }}u;
141
+ {% for s in range(A_SLOTS) %}
142
+ var nextA{{ s }}: vec4<u32>;
143
+ {% endfor %}
144
+ {% for s in range(B_SLOTS) %}
145
+ var nextB{{ s }}: vec4<u32>;
146
+ {% endfor %}
147
+ {{ stage_load("a", "0u") }}
148
+ {{ stage_load("b", "0u") }}
149
+ {% for r in range(FR) %}{% for c in range(FC) %}
150
+ var acc{{ r }}_{{ c }}: subgroup_matrix_result<{{ ACC }}, 16, 16>;
151
+ {% endfor %}{% endfor %}
152
+ for (var kk = 0u; kk < K; kk += {{ BK }}u) {
153
+ {{ stage_store("a") }}
154
+ {{ stage_store("b") }}
155
+ workgroupBarrier();
156
+ // Issue the next slice's global loads before this slice's multiplies.
157
+ if (kk + {{ BK }}u < K) {
158
+ {{ stage_load("a", "kk + " ~ BK ~ "u") }}
159
+ {{ stage_load("b", "kk + " ~ BK ~ "u") }}
160
+ }
161
+ {% for step in range((BK / FK) | int) %}
162
+ {
163
+ {% for r in range(FR) %}
164
+ let left{{ r }} = {{ load_left(r, step) }};
165
+ {% endfor %}
166
+ {% for c in range(FC) %}
167
+ let right{{ c }} = {{ load_right(c, step) }};
168
+ {% endfor %}
169
+ {% for r in range(FR) %}{% for c in range(FC) %}
170
+ acc{{ r }}_{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ r }}, right{{ c }}, acc{{ r }}_{{ c }});
171
+ {% endfor %}{% endfor %}
172
+ }
173
+ {% endfor %}
174
+ workgroupBarrier();
175
+ }
176
+ // One row of fragments at a time goes through a per-subgroup scratch block so each lane
177
+ // writes whole 16-byte vectors with row/column guards, corrections and conversion.
178
+ let scratch = role * {{ 64 * FC }}u;
179
+ {% for r in range(FR) %}
180
+ {% for c in range(FC) %}
181
+ subgroupMatrixStore<row_major>(&tileA, scratch + {{ 4 * c }}u, acc{{ r }}_{{ c }}, {{ 4 * FC }}u);
182
+ {% endfor %}
183
+ workgroupBarrier();
184
+ for (var j = 0u; j < {{ FC }}u; j++) {
185
+ // Lane-run v covers 8 output columns: scratch row v / {{ 2 * FC }}, words 2 * (v % {{ 2 * FC }}) .. + 1.
186
+ let v = j * 32u + lane;
187
+ let row = rowBase + subRow + {{ 16 * r }}u + v / {{ 2 * FC }}u;
188
+ let col = colBase + subCol + (v % {{ 2 * FC }}u) * 8u;
189
+ if (row < M && col < N) {
190
+ let w = scratch + (v / {{ 2 * FC }}u) * {{ 4 * FC }}u + (v % {{ 2 * FC }}u) * 2u;
191
+ let lo = bitcast<vec4<f32>>(tileA[w]);
192
+ let hi = bitcast<vec4<f32>>(tileA[w + 1u]);
193
+ y[({{ YOFF }}row * N + col) / 8u] = {{ half_word("lo", "hi") }};
194
+ }
195
+ }
196
+ workgroupBarrier();
197
+ {% endfor %}
198
+ } else {
199
+ // Portable fallback when the subgroup topology check fails.
200
+ for (var run = tid; run < {{ (TM * TN / 8) | int }}u; run += {{ T }}u) {
201
+ let row = rowBase + run / {{ (TN / 8) | int }}u;
202
+ let col = colBase + (run % {{ (TN / 8) | int }}u) * 8u;
203
+ if (row < M && col < N) {
204
+ var lo = vec4<f32>();
205
+ var hi = vec4<f32>();
206
+ for (var k = 0u; k < K; k++) {
207
+ let av = halfA({{ AOFF }}{{ "row * K + k" if AM == "row" else "k * M + row" }});
208
+ {% for j in range(8) %}
209
+ {{ "lo" if j < 4 else "hi" }}[{{ j % 4 }}] += av * halfB({{ BOFF }}{{ "k * N + col + " ~ j ~ "u" if BMJ == "row" else "(col + " ~ j ~ "u) * K + k" }});
210
+ {% endfor %}
211
+ }
212
+ y[({{ YOFF }}row * N + col) / 8u] = {{ half_word("lo", "hi") }};
213
+ }
214
+ }
215
+ }
216
+ }
build/webgpu/test.json CHANGED
The diff for this file is too large to render. See raw diff