Xenova HF Staff commited on
Commit
e3d1c2d
·
verified ·
1 Parent(s): 6dc5ac4

sync 4385228f788d

Browse files
README.md CHANGED
@@ -12,19 +12,37 @@ tags:
12
 
13
  ## Description
14
 
15
- Quantized mixture of experts over float32 activations and raw uint8-packed integer expert weights. The package implements 4- and 8-bit symmetric dequantization, ReLU, and interleaved SwiGLU for rank-2 or rank-3 input. Routing uses the softmax over the selected top-k logits with `router_weights` absent. Biases, explicit zero points, FC3, sparse mixing, provider-prepacked layouts, and FP4/FP8 modes are not implemented.
16
 
17
  See the [ONNX Runtime `QMoE` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.QMoE) for the reference semantics.
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  ## Inputs
20
 
21
  | Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
22
  | --- | --- | --- | --- | --- | --- | --- |
23
  | `inputT` | `input` | `T` | — | — | Token activations of shape `(num_tokens, hidden_size)` or `(batch_size, sequence_length, hidden_size)`. | required |
24
  | `routerT` | `router_probs` | `T` | `2` | — | Routing logits of shape `(num_tokens, num_experts)`, where `num_tokens` is the product of the leading input dimensions. | required |
25
- | `fc1T` | `fc1_experts_weights` | `T1` | `3` | — | Raw packed FC1 weights of shape `(num_experts, fusion_size * inter_size, hidden_size / pack_size)`, where `fusion_size` is 2 only for interleaved SwiGLU and `pack_size` is 2 for 4-bit or 1 for 8-bit weights. | required |
26
  | `fc1ScalesT` | `fc1_scales` | `T2` | — | — | Required FC1 dequantization scales: rank 2 `(num_experts, fusion_size * inter_size)` for column-wise quantization, or rank 3 with a trailing `hidden_size / block_size` axis. | required |
27
- | `fc2T` | `fc2_experts_weights` | `T1` | `3` | — | Raw packed FC2 weights of shape `(num_experts, hidden_size, inter_size / pack_size)`. | required |
28
  | `fc2ScalesT` | `fc2_scales` | `T2` | — | — | Required FC2 dequantization scales: rank 2 `(num_experts, hidden_size)` for column-wise quantization, or rank 3 with a trailing `inter_size / block_size` axis. | required |
29
 
30
  ## Outputs
@@ -43,9 +61,9 @@ Attributes and default values (overridable per request):
43
  | `activation_beta` | `0` | Beta added to the SwiGLU linear branch; the exact standard default is 0. |
44
  | `activation_type` | `"relu"` | Activation applied after FC1. This package supports `relu` and `swiglu`; the exact standard default is `relu`. |
45
  | `block_size` | — | Optional quantization block size along the reduction dimension. Omission selects column-wise scaling; a supplied value must be a power of two of at least 16 and divide both `hidden_size` and `inter_size`. |
46
- | `expert_weight_bits` | `4` | Integer expert-weight bit width. This package supports 4 and 8; the exact standard default is 4. |
47
  | `k` | `1` | Number of experts selected per token; the exact standard default is 1. |
48
- | `normalize_routing_weights` | `0` | Accepted values are 0 and 1. With the separate `router_weights` input omitted, routing applies a softmax over the selected top-k logits for either value; the attribute only distinguishes the unsupported separate-weight path. |
49
  | `quant_type` | `"int"` | Quantization family. This package supports only the exact standard default `int`. |
50
  | `swiglu_fusion` | `0` | SwiGLU packing mode. ReLU uses the exact standard default 0; supported SwiGLU interleaves gate/up FC1 rows with value 1. |
51
  | `swiglu_limit` | — | Optional SwiGLU clamp limit. Omission means no finite clamp. |
@@ -64,54 +82,66 @@ Attributes and default values (overridable per request):
64
 
65
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
66
 
67
- - `quant_grouped_sgmat_routed` — Expert-grouped f32 matrix multiplication with per-invocation routing slots and reuse of the input tile for output publication. The larger operand/output footprint determines workgroup storage admission from device limits.
 
 
 
68
 
69
  ## Device requirements
70
 
71
- 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.
72
 
73
  ## Files
74
 
75
- - [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)
76
- - [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)
77
- - [`test.json`](build/webgpu/test.json) — correctness cases
78
- - [`bench.json`](build/webgpu/bench.json) — benchmark cases
79
- - [`expert-group-slots.wgsl.jinja`](build/webgpu/expert-group-slots.wgsl.jinja)
80
- - [`expert-slot-mix.wgsl.jinja`](build/webgpu/expert-slot-mix.wgsl.jinja)
81
- - [`qmoe-fc1-activation-gemv.wgsl.jinja`](build/webgpu/qmoe-fc1-activation-gemv.wgsl.jinja)
82
- - [`qmoe-fc1-activation-grouped-sgmat.wgsl.jinja`](build/webgpu/qmoe-fc1-activation-grouped-sgmat.wgsl.jinja)
83
- - [`qmoe-fc1-activation-grouped.wgsl.jinja`](build/webgpu/qmoe-fc1-activation-grouped.wgsl.jinja)
84
- - [`qmoe-fc1-activation-stage.wgsl.jinja`](build/webgpu/qmoe-fc1-activation-stage.wgsl.jinja)
85
- - [`qmoe-output-gemv.wgsl.jinja`](build/webgpu/qmoe-output-gemv.wgsl.jinja)
86
- - [`qmoe-output-grouped-sgmat.wgsl.jinja`](build/webgpu/qmoe-output-grouped-sgmat.wgsl.jinja)
87
- - [`qmoe-output-grouped.wgsl.jinja`](build/webgpu/qmoe-output-grouped.wgsl.jinja)
88
- - [`qmoe-output-stage.wgsl.jinja`](build/webgpu/qmoe-output-stage.wgsl.jinja)
89
- - [`qmoe-output-zero-inter.wgsl.jinja`](build/webgpu/qmoe-output-zero-inter.wgsl.jinja)
90
- - [`qmoe-route-stage.wgsl.jinja`](build/webgpu/qmoe-route-stage.wgsl.jinja)
91
 
92
  ## Use with `@huggingface/kernels`
93
 
94
  ```sh
95
- npm install --save-exact @huggingface/kernels@0.0.1-preview.3
96
  ```
97
 
 
 
98
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
99
 
100
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
101
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
102
 
103
- Replace each `*Data` placeholder with a typed array containing the corresponding input data.
104
-
105
  ```js
106
  import { getKernel } from "@huggingface/kernels";
107
 
108
  const kernel = await getKernel("webgpu-kernels/com.microsoft.QMoE", { version: 1 });
 
 
 
 
 
 
 
 
109
  const { outputT } = await kernel({
110
- inputT: { data: inputTData, shape: [2, 2, 4] },
111
- routerT: { data: routerTData, shape: [4, 2] },
112
- fc1T: { data: fc1TData, shape: [2, 4, 2] },
113
- fc1ScalesT: { data: fc1ScalesTData, shape: [2, 4] },
114
- fc2T: { data: fc2TData, shape: [2, 4, 2] },
115
- fc2ScalesT: { data: fc2ScalesTData, shape: [2, 4] },
116
  });
 
117
  ```
 
12
 
13
  ## Description
14
 
15
+ Quantized mixture of experts over float32 activations and uint8-packed integer expert weights. The package implements 2-, 4- and 8-bit symmetric dequantization, ReLU, and interleaved SwiGLU for rank-2 or rank-3 input. With `router_weights` absent, default routing uses full-expert softmax probabilities; `normalize_routing_weights=1` renormalizes the selected top-k experts. A NaN router logit propagates NaN to that token's output when probabilities are computed from the logits. Biases, explicit zero points, FC3, sparse mixing, provider-prepacked layouts, and FP4/FP8 modes are not implemented.
16
 
17
  See the [ONNX Runtime `QMoE` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.QMoE) for the reference semantics.
18
 
19
+ ## Differences from the ONNX Runtime spec
20
+
21
+ - Attribute `accuracy_level`: The accuracy hint is not implemented; dequantization and accumulation always use float32.
22
+ - Attribute `fc1_expert_weight_bits`: Per-projection bit-width overrides are not implemented; FC1 uses the common expert_weight_bits attribute.
23
+ - Attribute `fc2_expert_weight_bits`: Per-projection bit-width overrides are not implemented; FC2 uses the common expert_weight_bits attribute.
24
+ - Attribute `fc3_expert_weight_bits`: The separate FC3 projection and its bit-width override are not implemented.
25
+ - Input `fc1_experts_bias`, input `fc2_experts_bias`: Expert biases are unsupported by this package.
26
+ - Input `fc3_experts_weights`: The separate FC3 projection used by unfused SwiGLU is not implemented; supported SwiGLU graphs use interleaved FC1 weights.
27
+ - Input `fc3_scales`: The omitted FC3 projection has no scale input in this package.
28
+ - Input `fc3_experts_bias`: The omitted FC3 projection has no bias input in this package.
29
+ - Input `fc1_zero_points`, input `fc2_zero_points`: Only the standard implicit midpoint zero point 2^(expert_weight_bits - 1) is implemented.
30
+ - Input `fc3_zero_points`: The omitted FC3 projection and explicit zero points are not implemented.
31
+ - Input `router_weights`: Selection and aggregation both use router_probs; separate aggregation weights are not implemented.
32
+ - Input `fc1_global_scale`, input `fc2_global_scale`: FP4 and FP8 expert-weight modes are not implemented.
33
+ - Input `fc1_act_scale`, input `fc2_act_scale`: FP8 activation modes are not implemented.
34
+ - Input `fc1_act_block_scale`, input `fc2_act_block_scale`: Block-scaled FP8 activation modes are not implemented.
35
+ - Input `fc1ScalesT` (ONNX `fc1_scales`), input `fc2ScalesT` (ONNX `fc2_scales`): Integer expert weights require explicit dequantization scales in this package.
36
+
37
  ## Inputs
38
 
39
  | Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
40
  | --- | --- | --- | --- | --- | --- | --- |
41
  | `inputT` | `input` | `T` | — | — | Token activations of shape `(num_tokens, hidden_size)` or `(batch_size, sequence_length, hidden_size)`. | required |
42
  | `routerT` | `router_probs` | `T` | `2` | — | Routing logits of shape `(num_tokens, num_experts)`, where `num_tokens` is the product of the leading input dimensions. | required |
43
+ | `fc1T` | `fc1_experts_weights` | `T1` | `3` | — | Raw packed FC1 weights of shape `(num_experts, fusion_size * inter_size, hidden_size / pack_size)`, where `fusion_size` is 2 only for interleaved SwiGLU and `pack_size` is `8 / expert_weight_bits` weights. | required |
44
  | `fc1ScalesT` | `fc1_scales` | `T2` | — | — | Required FC1 dequantization scales: rank 2 `(num_experts, fusion_size * inter_size)` for column-wise quantization, or rank 3 with a trailing `hidden_size / block_size` axis. | required |
45
+ | `fc2T` | `fc2_experts_weights` | `T1` | `3` | — | Raw packed FC2 weights of shape `(num_experts, hidden_size, inter_size / pack_size)`. The pack size is `8 / expert_weight_bits`. | required |
46
  | `fc2ScalesT` | `fc2_scales` | `T2` | — | — | Required FC2 dequantization scales: rank 2 `(num_experts, hidden_size)` for column-wise quantization, or rank 3 with a trailing `inter_size / block_size` axis. | required |
47
 
48
  ## Outputs
 
61
  | `activation_beta` | `0` | Beta added to the SwiGLU linear branch; the exact standard default is 0. |
62
  | `activation_type` | `"relu"` | Activation applied after FC1. This package supports `relu` and `swiglu`; the exact standard default is `relu`. |
63
  | `block_size` | — | Optional quantization block size along the reduction dimension. Omission selects column-wise scaling; a supplied value must be a power of two of at least 16 and divide both `hidden_size` and `inter_size`. |
64
+ | `expert_weight_bits` | `4` | Integer expert-weight bit width. This package supports 2, 4 and 8; the exact standard default is 4. |
65
  | `k` | `1` | Number of experts selected per token; the exact standard default is 1. |
66
+ | `normalize_routing_weights` | `0` | With `router_weights` absent, omitted/default 0 uses the softmax denominator over all experts, so selected weights may sum to less than 1 (including k=1). Value 1 normalizes over the selected top-k logits. This matches ONNX Runtime's WebGPU provider; set 1 for selected-only normalization. ONNX Runtime's CPU provider normalizes over the selected experts for either value. |
67
  | `quant_type` | `"int"` | Quantization family. This package supports only the exact standard default `int`. |
68
  | `swiglu_fusion` | `0` | SwiGLU packing mode. ReLU uses the exact standard default 0; supported SwiGLU interleaves gate/up FC1 rows with value 1. |
69
  | `swiglu_limit` | — | Optional SwiGLU clamp limit. Omission means no finite clamp. |
 
82
 
83
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
84
 
85
+ - `quant_grouped_sgmat_routed` — Expert-grouped f32 matrix multiplication with per-invocation routing slots and reuse of the input tile's workgroup memory to stage the output. The larger of the operand and output tiles must fit the device's workgroup storage limit.
86
+ - `quant_grouped_vector_routed` — Aligned eight-bit expert-grouped float32 tiles read four widened weight codes through a vector view. This preserves quantization, accumulation and tensor storage while reducing separate scalar weight loads. Unaligned rows use scalar views.
87
+ - `quant_grouped_routed` — Portable expert-grouped float32 tiles reuse dequantized weights. Register rows follow routed density; register columns and shared-weight layout follow the subgroup width and column tile size. Without subgroups, 8-bit weights use scalar fused multiply-add accumulation.
88
+ - `quant_gemv_routed` — Cooperative float32 row reductions use four aligned integer codes per lane when the advertised subgroup width covers the logical lane group, and paired codes otherwise. Odd 8-bit reduction tails use scalar access.
89
 
90
  ## Device requirements
91
 
92
+ Some implementation variants require `subgroup-matrix` and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.
93
 
94
  ## Files
95
 
96
+ - [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)
97
+ - [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)
98
+ - [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/test.json) — correctness cases
99
+ - [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/bench.json) — benchmark cases
100
+ - [`expert-group-slots.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/expert-group-slots.wgsl.jinja)
101
+ - [`expert-slot-mix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/expert-slot-mix.wgsl.jinja)
102
+ - [`qmoe-fc1-activation-gemv.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-fc1-activation-gemv.wgsl.jinja)
103
+ - [`qmoe-fc1-activation-grouped-sgmat.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-fc1-activation-grouped-sgmat.wgsl.jinja)
104
+ - [`qmoe-fc1-activation-grouped.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-fc1-activation-grouped.wgsl.jinja)
105
+ - [`qmoe-fc1-activation-stage.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-fc1-activation-stage.wgsl.jinja)
106
+ - [`qmoe-output-gemv.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-output-gemv.wgsl.jinja)
107
+ - [`qmoe-output-grouped-sgmat.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-output-grouped-sgmat.wgsl.jinja)
108
+ - [`qmoe-output-grouped.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-output-grouped.wgsl.jinja)
109
+ - [`qmoe-output-stage.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-output-stage.wgsl.jinja)
110
+ - [`qmoe-output-zero-inter.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-output-zero-inter.wgsl.jinja)
111
+ - [`qmoe-route-stage.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QMoE/blob/v1/build/webgpu/qmoe-route-stage.wgsl.jinja)
112
 
113
  ## Use with `@huggingface/kernels`
114
 
115
  ```sh
116
+ npm install --save-exact @huggingface/kernels@0.0.1-preview.4
117
  ```
118
 
119
+ Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.
120
+
121
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
122
 
123
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
124
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
125
 
 
 
126
  ```js
127
  import { getKernel } from "@huggingface/kernels";
128
 
129
  const kernel = await getKernel("webgpu-kernels/com.microsoft.QMoE", { version: 1 });
130
+
131
+ const inputTData = Float32Array.of(1, 1, 2, 2, 3, 3);
132
+ const routerTData = Float32Array.of(1000, 999, 998, 997, -1000, -999, -998, -997, 1000, 1000, 1000, 1000);
133
+ const fc1TData = new Uint8Array(8).fill(170);
134
+ const fc1ScalesTData = new Float32Array(8).fill(1);
135
+ const fc2TData = Uint8Array.of(170, 204, 170, 204, 170, 204, 170, 204);
136
+ const fc2ScalesTData = new Float32Array(8).fill(1);
137
+
138
  const { outputT } = await kernel({
139
+ inputT: { data: inputTData, shape: [1, 3, 2] },
140
+ routerT: { data: routerTData, shape: [3, 4] },
141
+ fc1T: { data: fc1TData, shape: [4, 2, 1] },
142
+ fc1ScalesT: { data: fc1ScalesTData, shape: [4, 2] },
143
+ fc2T: { data: fc2TData, shape: [4, 2, 1] },
144
+ fc2ScalesT: { data: fc2ScalesTData, shape: [4, 2] },
145
  });
146
+ console.log({ outputT });
147
  ```
build/webgpu/bench.json CHANGED
@@ -1,11 +1,5 @@
1
  {
2
- "tunableSpace": {
3
- "workgroupSize": [64, 128, 256],
4
- "groupThreads": [8, 16],
5
- "groupRegM": [1, 2, 4],
6
- "groupRegN": [1, 2, 4],
7
- "groupTileK": [8, 16, 32]
8
- },
9
  "cases": [
10
  {
11
  "name": "qmoe-q4-relu-t32-h64-e4-i32",
@@ -108,7 +102,7 @@
108
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 3 * args.hidden * args.inter * args.bits / 2" }]
109
  },
110
  "provenance": {
111
- "notes": "The bandwidth metric counts the selected experts' three quantized weight matrices at `bits/2` bytes per logical weight in the bound storage layout."
112
  }
113
  },
114
  {
@@ -143,7 +137,7 @@
143
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 3 * args.hidden * args.inter * args.bits / 2" }]
144
  },
145
  "provenance": {
146
- "notes": "The bandwidth metric counts the selected experts' three quantized weight matrices at `bits/2` bytes per logical weight in the bound storage layout."
147
  }
148
  },
149
  {
@@ -179,7 +173,7 @@
179
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 3 * args.hidden * args.inter * args.bits / 2" }]
180
  },
181
  "provenance": {
182
- "notes": "The bandwidth metric counts the selected experts' three quantized weight matrices at `bits/2` bytes per logical weight in the bound storage layout."
183
  }
184
  },
185
  {
@@ -214,7 +208,7 @@
214
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 3 * args.hidden * args.inter * args.bits / 2" }]
215
  },
216
  "provenance": {
217
- "notes": "The bandwidth metric counts the selected experts' three quantized weight matrices at `bits/2` bytes per logical weight in the bound storage layout."
218
  }
219
  },
220
  {
@@ -248,7 +242,7 @@
248
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 2 * args.hidden * args.inter * args.bits / 2" }]
249
  },
250
  "provenance": {
251
- "notes": "The bandwidth metric counts the selected expert's two quantized weight matrices at `bits/2` bytes per logical weight in the bound storage layout."
252
  }
253
  },
254
  {
@@ -453,7 +447,7 @@
453
  "name": "qmoe-q4-qwen3-moe-prefill-t256-h2048-e64-k8-i768",
454
  "preset": "model",
455
  "provenance": {
456
- "notes": "Qwen3-MoE class defaults at a 256-token prefill chunk; 2048 routed slots clear the grouped schedule's slot floor for 64 experts."
457
  },
458
  "vars": { "tokens": 256, "hidden": 2048, "experts": 64, "inter": 768, "topK": 8 },
459
  "attrs": { "activation_type": "swiglu", "swiglu_fusion": 1, "k": 8 },
@@ -687,6 +681,200 @@
687
  "bench": {
688
  "metrics": [{ "type": "gflops", "value": "2 * args.tokens * args.topK * args.hidden * args.inter * 3" }]
689
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
690
  }
691
  ]
692
  }
 
1
  {
2
+ "tunableSpace": { "groupRegM": [2, 4], "groupRegN": [2, 4] },
 
 
 
 
 
 
3
  "cases": [
4
  {
5
  "name": "qmoe-q4-relu-t32-h64-e4-i32",
 
102
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 3 * args.hidden * args.inter * args.bits / 2" }]
103
  },
104
  "provenance": {
105
+ "notes": "The bandwidth metric counts the selected experts' three quantized weight matrices at `bits/2` bytes per logical weight."
106
  }
107
  },
108
  {
 
137
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 3 * args.hidden * args.inter * args.bits / 2" }]
138
  },
139
  "provenance": {
140
+ "notes": "The bandwidth metric counts the selected experts' three quantized weight matrices at `bits/2` bytes per logical weight."
141
  }
142
  },
143
  {
 
173
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 3 * args.hidden * args.inter * args.bits / 2" }]
174
  },
175
  "provenance": {
176
+ "notes": "The bandwidth metric counts the selected experts' three quantized weight matrices at `bits/2` bytes per logical weight."
177
  }
178
  },
179
  {
 
208
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 3 * args.hidden * args.inter * args.bits / 2" }]
209
  },
210
  "provenance": {
211
+ "notes": "The bandwidth metric counts the selected experts' three quantized weight matrices at `bits/2` bytes per logical weight."
212
  }
213
  },
214
  {
 
242
  "metrics": [{ "type": "bandwidth", "value": "args.topK * 2 * args.hidden * args.inter * args.bits / 2" }]
243
  },
244
  "provenance": {
245
+ "notes": "The bandwidth metric counts the selected expert's two quantized weight matrices at `bits/2` bytes per logical weight."
246
  }
247
  },
248
  {
 
447
  "name": "qmoe-q4-qwen3-moe-prefill-t256-h2048-e64-k8-i768",
448
  "preset": "model",
449
  "provenance": {
450
+ "notes": "Qwen3-MoE class defaults at a 256-token prefill chunk: top-8 routing gives 2048 routed slots over 64 experts."
451
  },
452
  "vars": { "tokens": 256, "hidden": 2048, "experts": 64, "inter": 768, "topK": 8 },
453
  "attrs": { "activation_type": "swiglu", "swiglu_fusion": 1, "k": 8 },
 
681
  "bench": {
682
  "metrics": [{ "type": "gflops", "value": "2 * args.tokens * args.topK * args.hidden * args.inter * 3" }]
683
  }
684
+ },
685
+ {
686
+ "name": "qmoe-q8-swiglu-t128-h1024-e8-k2-i1024-prefill-colwise",
687
+ "preset": "stress",
688
+ "vars": { "tokens": 128, "hidden": 1024, "experts": 8, "inter": 1024, "topK": 2, "bits": 8 },
689
+ "attrs": { "activation_type": "swiglu", "swiglu_fusion": 1, "k": 2, "expert_weight_bits": 8, "block_size": 0 },
690
+ "tunables": { "workgroupSize": 128, "decodeLanes": 32, "decodeMinLaneTrips": 4 },
691
+ "tunableSpace": { "groupRegM": [2, 4], "groupRegN": [2, 4], "groupTileK": [8, 16] },
692
+ "inputs": {
693
+ "inputT": { "shape": [128, 1024], "dtype": "float32", "dist": "normal", "seed": 500, "scale": 0.2 },
694
+ "routerT": { "shape": [128, 8], "dtype": "float32", "dist": "normal", "seed": 501, "scale": 0.5 },
695
+ "fc1T": { "shape": [8, 2048, 1024], "dtype": "uint8", "dist": "uniform", "seed": 502, "min": 0, "max": 255 },
696
+ "fc1ScalesT": {
697
+ "shape": [8, 2048],
698
+ "dtype": "float32",
699
+ "dist": "uniform",
700
+ "seed": 503,
701
+ "min": 0.0003125,
702
+ "max": 0.003125
703
+ },
704
+ "fc2T": { "shape": [8, 1024, 1024], "dtype": "uint8", "dist": "uniform", "seed": 504, "min": 0, "max": 255 },
705
+ "fc2ScalesT": {
706
+ "shape": [8, 1024],
707
+ "dtype": "float32",
708
+ "dist": "uniform",
709
+ "seed": 505,
710
+ "min": 0.0003125,
711
+ "max": 0.003125
712
+ }
713
+ },
714
+ "outputs": { "outputT": { "shape": [128, 1024], "dtype": "float32" } },
715
+ "bench": {
716
+ "metrics": [{ "type": "gflops", "value": "2 * args.tokens * args.topK * args.hidden * args.inter * 3" }]
717
+ },
718
+ "provenance": {
719
+ "notes": "Eight-bit expert weights with per-output-row quantization scales; 128 tokens routed top-2 over 8 experts (256 routed slots), hidden and intermediate size 1024."
720
+ }
721
+ },
722
+ {
723
+ "name": "qmoe-q8-swiglu-t48-h1024-e8-k2-i1024-prefill-blockwise",
724
+ "preset": "stress",
725
+ "vars": { "tokens": 48, "hidden": 1024, "experts": 8, "inter": 1024, "topK": 2, "bits": 8 },
726
+ "attrs": { "activation_type": "swiglu", "swiglu_fusion": 1, "k": 2, "expert_weight_bits": 8, "block_size": 32 },
727
+ "tunables": { "workgroupSize": 128, "decodeLanes": 32, "decodeMinLaneTrips": 4 },
728
+ "tunableSpace": { "groupRegM": [2, 4], "groupRegN": [2, 4], "groupTileK": [8, 16] },
729
+ "inputs": {
730
+ "inputT": { "shape": [48, 1024], "dtype": "float32", "dist": "normal", "seed": 500, "scale": 0.2 },
731
+ "routerT": { "shape": [48, 8], "dtype": "float32", "dist": "normal", "seed": 501, "scale": 0.5 },
732
+ "fc1T": { "shape": [8, 2048, 1024], "dtype": "uint8", "dist": "uniform", "seed": 502, "min": 0, "max": 255 },
733
+ "fc1ScalesT": {
734
+ "shape": [8, 2048, 32],
735
+ "dtype": "float32",
736
+ "dist": "uniform",
737
+ "seed": 503,
738
+ "min": 0.0003125,
739
+ "max": 0.003125
740
+ },
741
+ "fc2T": { "shape": [8, 1024, 1024], "dtype": "uint8", "dist": "uniform", "seed": 504, "min": 0, "max": 255 },
742
+ "fc2ScalesT": {
743
+ "shape": [8, 1024, 32],
744
+ "dtype": "float32",
745
+ "dist": "uniform",
746
+ "seed": 505,
747
+ "min": 0.0003125,
748
+ "max": 0.003125
749
+ }
750
+ },
751
+ "outputs": { "outputT": { "shape": [48, 1024], "dtype": "float32" } },
752
+ "bench": {
753
+ "metrics": [{ "type": "gflops", "value": "2 * args.tokens * args.topK * args.hidden * args.inter * 3" }]
754
+ },
755
+ "provenance": {
756
+ "notes": "Eight-bit expert weights with per-block quantization scales (32-wide blocks); 48 tokens routed top-2 over 8 experts (96 routed slots), hidden and intermediate size 1024."
757
+ }
758
+ },
759
+ {
760
+ "name": "int2-swiglu-t1-h512-i512-e2-k2",
761
+ "attrs": {
762
+ "expert_weight_bits": 2,
763
+ "k": 2,
764
+ "activation_type": "swiglu",
765
+ "swiglu_fusion": 1,
766
+ "normalize_routing_weights": 0
767
+ },
768
+ "inputs": {
769
+ "inputT": {
770
+ "dtype": "float32",
771
+ "shape": [1, 512],
772
+ "data": { "kind": "cycle", "values": [-0.375, 0.125, 0.625, -0.25, 0.5, 0.0625, -0.125] }
773
+ },
774
+ "routerT": { "dtype": "float32", "shape": [1, 2], "data": { "kind": "cycle", "values": [-1.0, -0.125] } },
775
+ "fc1T": {
776
+ "dtype": "uint8",
777
+ "shape": [2, 1024, 128],
778
+ "data": { "kind": "cycle", "values": [0, 85, 170, 255, 27, 228, 57, 198, 18, 109, 147, 225, 75] }
779
+ },
780
+ "fc2T": {
781
+ "dtype": "uint8",
782
+ "shape": [2, 512, 128],
783
+ "data": { "kind": "cycle", "values": [255, 0, 170, 85, 108, 177, 39, 216, 54, 141, 99] }
784
+ },
785
+ "fc1ScalesT": {
786
+ "dtype": "float32",
787
+ "shape": [2, 1024],
788
+ "data": { "kind": "cycle", "values": [0.03125, 0.046875, 0.0625] }
789
+ },
790
+ "fc2ScalesT": {
791
+ "dtype": "float32",
792
+ "shape": [2, 512],
793
+ "data": { "kind": "cycle", "values": [0.03125, 0.046875, 0.0625] }
794
+ }
795
+ },
796
+ "outputs": { "outputT": { "dtype": "float32", "shape": [1, 512] } },
797
+ "preset": "edge"
798
+ },
799
+ {
800
+ "name": "int2-swiglu-t16-h512-i512-e2-k2",
801
+ "attrs": {
802
+ "expert_weight_bits": 2,
803
+ "k": 2,
804
+ "activation_type": "swiglu",
805
+ "swiglu_fusion": 1,
806
+ "normalize_routing_weights": 0
807
+ },
808
+ "inputs": {
809
+ "inputT": {
810
+ "dtype": "float32",
811
+ "shape": [16, 512],
812
+ "data": { "kind": "cycle", "values": [-0.375, 0.125, 0.625, -0.25, 0.5, 0.0625, -0.125] }
813
+ },
814
+ "routerT": { "dtype": "float32", "shape": [16, 2], "data": { "kind": "cycle", "values": [-1.0, -0.125] } },
815
+ "fc1T": {
816
+ "dtype": "uint8",
817
+ "shape": [2, 1024, 128],
818
+ "data": { "kind": "cycle", "values": [0, 85, 170, 255, 27, 228, 57, 198, 18, 109, 147, 225, 75] }
819
+ },
820
+ "fc2T": {
821
+ "dtype": "uint8",
822
+ "shape": [2, 512, 128],
823
+ "data": { "kind": "cycle", "values": [255, 0, 170, 85, 108, 177, 39, 216, 54, 141, 99] }
824
+ },
825
+ "fc1ScalesT": {
826
+ "dtype": "float32",
827
+ "shape": [2, 1024],
828
+ "data": { "kind": "cycle", "values": [0.03125, 0.046875, 0.0625] }
829
+ },
830
+ "fc2ScalesT": {
831
+ "dtype": "float32",
832
+ "shape": [2, 512],
833
+ "data": { "kind": "cycle", "values": [0.03125, 0.046875, 0.0625] }
834
+ }
835
+ },
836
+ "outputs": { "outputT": { "dtype": "float32", "shape": [16, 512] } },
837
+ "preset": "edge"
838
+ },
839
+ {
840
+ "name": "int2-swiglu-t128-h512-i512-e2-k2",
841
+ "attrs": {
842
+ "expert_weight_bits": 2,
843
+ "k": 2,
844
+ "activation_type": "swiglu",
845
+ "swiglu_fusion": 1,
846
+ "normalize_routing_weights": 0
847
+ },
848
+ "inputs": {
849
+ "inputT": {
850
+ "dtype": "float32",
851
+ "shape": [128, 512],
852
+ "data": { "kind": "cycle", "values": [-0.375, 0.125, 0.625, -0.25, 0.5, 0.0625, -0.125] }
853
+ },
854
+ "routerT": { "dtype": "float32", "shape": [128, 2], "data": { "kind": "cycle", "values": [-1.0, -0.125] } },
855
+ "fc1T": {
856
+ "dtype": "uint8",
857
+ "shape": [2, 1024, 128],
858
+ "data": { "kind": "cycle", "values": [0, 85, 170, 255, 27, 228, 57, 198, 18, 109, 147, 225, 75] }
859
+ },
860
+ "fc2T": {
861
+ "dtype": "uint8",
862
+ "shape": [2, 512, 128],
863
+ "data": { "kind": "cycle", "values": [255, 0, 170, 85, 108, 177, 39, 216, 54, 141, 99] }
864
+ },
865
+ "fc1ScalesT": {
866
+ "dtype": "float32",
867
+ "shape": [2, 1024],
868
+ "data": { "kind": "cycle", "values": [0.03125, 0.046875, 0.0625] }
869
+ },
870
+ "fc2ScalesT": {
871
+ "dtype": "float32",
872
+ "shape": [2, 512],
873
+ "data": { "kind": "cycle", "values": [0.03125, 0.046875, 0.0625] }
874
+ }
875
+ },
876
+ "outputs": { "outputT": { "dtype": "float32", "shape": [128, 512] } },
877
+ "preset": "edge"
878
  }
879
  ]
880
  }
build/webgpu/expert-slot-mix.wgsl.jinja CHANGED
@@ -1,8 +1,9 @@
1
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
- let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}
 
6
  {{ env.wgsl.resourceDeclarations }}
7
 
8
  // Routed sum for the grouped schedule. The grouped FC2 stage produces one projected row per
 
1
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
+ let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
6
+ {% endmacro %}
7
  {{ env.wgsl.resourceDeclarations }}
8
 
9
  // Routed sum for the grouped schedule. The grouped FC2 stage produces one projected row per
build/webgpu/manifest.json CHANGED
@@ -1,460 +1 @@
1
- {
2
- "domain": "com.microsoft",
3
- "name": "QMoE",
4
- "sinceVersion": 1,
5
- "inputs": {
6
- "inputT": { "onnx": "input", "dtype": "T" },
7
- "routerT": { "onnx": "router_probs", "dtype": "T", "rank": 2 },
8
- "fc1T": { "onnx": "fc1_experts_weights", "dtype": "T1", "rank": 3 },
9
- "fc1ScalesT": { "onnx": "fc1_scales", "dtype": "T2" },
10
- "fc2T": { "onnx": "fc2_experts_weights", "dtype": "T1", "rank": 3 },
11
- "fc2ScalesT": { "onnx": "fc2_scales", "dtype": "T2" }
12
- },
13
- "outputs": { "outputT": { "onnx": "output", "dtype": "T", "shape": "shapes.inputT" } },
14
- "attributes": {
15
- "activation_alpha": { "default": 1 },
16
- "activation_beta": { "default": 0 },
17
- "activation_type": { "default": "relu" },
18
- "expert_weight_bits": { "default": 4 },
19
- "k": { "default": 1 },
20
- "normalize_routing_weights": { "default": 0 },
21
- "quant_type": { "default": "int" },
22
- "swiglu_fusion": { "default": 0 },
23
- "use_sparse_mixer": { "default": 0 },
24
- "weights_prepacked": { "default": -1 },
25
- "block_size": {},
26
- "swiglu_limit": {}
27
- },
28
- "attributeConstraints": {
29
- "activation_type": { "values": ["relu", "swiglu"] },
30
- "expert_weight_bits": { "values": [4, 8] },
31
- "normalize_routing_weights": { "values": [0, 1] },
32
- "quant_type": { "values": ["int"] },
33
- "swiglu_fusion": { "values": [0, 1] },
34
- "use_sparse_mixer": { "values": [0] },
35
- "weights_prepacked": { "values": [-1, 0] }
36
- },
37
- "typeConstraints": { "T": ["float32"], "T1": ["uint8"], "T2": ["float32"] },
38
- "tunables": {
39
- "workgroupSize": { "default": 64 },
40
- "decodeLanes": { "default": 32 },
41
- "decodeBlockTarget": { "default": 1024 },
42
- "decodeMinLaneTrips": { "default": 4 },
43
- "groupThreads": { "default": 8 },
44
- "groupRegM": { "default": 4 },
45
- "groupRegN": { "default": 4 },
46
- "groupTileK": { "default": 16 },
47
- "groupRouteWorkgroup": { "default": 256 }
48
- },
49
- "derive": {
50
- "deviceWorkgroupCap": "min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)",
51
- "wave32Adapter": "has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 32 and device.adapterInfo.subgroupMaxSize == 32",
52
- "canPinSubgroupSize32": "device.features.has(\"subgroups\") and device.features.has(\"subgroup-size-control\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize <= 32 and device.adapterInfo.subgroupMaxSize >= 32",
53
- "pinSubgroupSize32": "canPinSubgroupSize32 and not wave32Adapter",
54
- "wave32Effective": "wave32Adapter or pinSubgroupSize32",
55
- "groupTileK": "tunables.groupTileK",
56
- "groupThreads": "tunables.groupThreads",
57
- "regM": "tunables.groupRegM",
58
- "regN": "tunables.groupRegN",
59
- "groupRouteWorkgroup": "tunables.groupRouteWorkgroup",
60
- "groupTileM": "tunables.groupThreads * tunables.groupRegM",
61
- "groupTileN": "tunables.groupThreads * tunables.groupRegN",
62
- "groupTileKVec": "ceilDiv(tunables.groupTileK, 4)",
63
- "groupThreadCount": "tunables.groupThreads * tunables.groupThreads",
64
- "groupSharedBytes": "(groupTileM * tunables.groupTileK + 2 * groupTileN * tunables.groupTileK + groupTileM) * 4",
65
- "topK": "attrs.k",
66
- "activationType": "attrs.activation_type",
67
- "workgroupSizeOk": "tunables.workgroupSize >= 1 and tunables.workgroupSize <= deviceWorkgroupCap",
68
- "decodeLanesOk": "tunables.decodeLanes >= 1 and tunables.decodeLanes <= tunables.workgroupSize and tunables.workgroupSize % tunables.decodeLanes == 0",
69
- "decodeRows": "max(1, tunables.workgroupSize / max(1, tunables.decodeLanes))",
70
- "decodeDeviceOk": "workgroupSizeOk and decodeLanesOk and tunables.decodeLanes <= device.limits.maxComputeWorkgroupSizeX and decodeRows <= device.limits.maxComputeWorkgroupSizeY and tunables.workgroupSize * 8 <= device.limits.maxComputeWorkgroupStorageSize",
71
- "fc1Rows": "dim(shapes.fc1T, 1)",
72
- "hasSwigluLimit": "has(attrs, \"swiglu_limit\")",
73
- "swigluLimit": "attrs.swiglu_limit if has(attrs, \"swiglu_limit\") else 0",
74
- "workgroupSize": "tunables.workgroupSize",
75
- "hiddenSize": "dim(shapes.inputT, ranks.inputT - 1)",
76
- "numTokens": "numel(shapes.inputT) / max(1, hiddenSize)",
77
- "weightBits": "attrs.expert_weight_bits",
78
- "quantBlockSize": "attrs.block_size if has(attrs, \"block_size\") else 0",
79
- "packSize": "2 if weightBits == 4 else 1",
80
- "quantMidpoint": "8 if weightBits == 4 else 128",
81
- "fusionSize": "2 if attrs.activation_type == \"swiglu\" and attrs.swiglu_fusion == 1 else 1",
82
- "interSize": "dim(shapes.fc1T, 1) / fusionSize",
83
- "fc1PackedCols": "dim(shapes.fc1T, 2)",
84
- "fc2PackedCols": "dim(shapes.fc2T, 2)",
85
- "colWiseScales": "quantBlockSize == 0",
86
- "fc1ScaleBlocks": "1 if colWiseScales else hiddenSize / max(1, quantBlockSize)",
87
- "fc2ScaleBlocks": "1 if colWiseScales else interSize / max(1, quantBlockSize)",
88
- "activationSupported": "(attrs.activation_type == \"relu\" and attrs.swiglu_fusion == 0) or (attrs.activation_type == \"swiglu\" and attrs.swiglu_fusion == 1)",
89
- "routingModeSupported": "attrs.normalize_routing_weights == 0 or attrs.normalize_routing_weights == 1",
90
- "rawWeightLayout": "attrs.weights_prepacked == -1 or attrs.weights_prepacked == 0",
91
- "inputOutputShapeOk": "((ranks.inputT == 2 and ranks.outputT == 2 and dim(shapes.outputT, 0) == dim(shapes.inputT, 0) and dim(shapes.outputT, 1) == dim(shapes.inputT, 1)) or (ranks.inputT == 3 and ranks.outputT == 3 and dim(shapes.outputT, 0) == dim(shapes.inputT, 0) and dim(shapes.outputT, 1) == dim(shapes.inputT, 1) and dim(shapes.outputT, 2) == dim(shapes.inputT, 2))) and hiddenSize > 0",
92
- "quantBlockSizeOk": "colWiseScales or (quantBlockSize >= 16 and pow2ceil(quantBlockSize) == quantBlockSize and hiddenSize % quantBlockSize == 0 and interSize % quantBlockSize == 0)",
93
- "quantScalesOk": "tensorDtypes.fc1ScalesT == \"float32\" and tensorDtypes.fc2ScalesT == \"float32\" and dim(shapes.fc1ScalesT, 0) == dim(shapes.routerT, 1) and dim(shapes.fc2ScalesT, 0) == dim(shapes.routerT, 1) and dim(shapes.fc1ScalesT, 1) == dim(shapes.fc1T, 1) and dim(shapes.fc2ScalesT, 1) == hiddenSize and ((ranks.fc1ScalesT == 2 and ranks.fc2ScalesT == 2) if colWiseScales else (ranks.fc1ScalesT == 3 and ranks.fc2ScalesT == 3 and dim(shapes.fc1ScalesT, 2) == fc1ScaleBlocks and dim(shapes.fc2ScalesT, 2) == fc2ScaleBlocks))",
94
- "quantShapeOk": "inputOutputShapeOk and ranks.routerT == 2 and ranks.fc1T == 3 and ranks.fc2T == 3 and dim(shapes.routerT, 0) == numTokens and dim(shapes.fc1T, 0) == dim(shapes.routerT, 1) and dim(shapes.fc2T, 0) == dim(shapes.routerT, 1) and dim(shapes.fc1T, 1) % fusionSize == 0 and dim(shapes.fc2T, 1) == hiddenSize and dim(shapes.fc1T, 2) * packSize == hiddenSize and dim(shapes.fc2T, 2) * packSize == interSize and quantBlockSizeOk and quantScalesOk",
95
- "quantContract": "activationSupported and routingModeSupported and rawWeightLayout and quantShapeOk and topK >= 1 and topK <= dim(shapes.routerT, 1)",
96
- "hiddenChunkFits": "topK * interSize * 4 <= device.limits.maxStorageBufferBindingSize and topK * interSize * 4 <= device.limits.maxBufferSize",
97
- "hiddenChunkTokens": "numTokens if interSize == 0 else min(numTokens, max(1, floor(min(device.limits.maxStorageBufferBindingSize, device.limits.maxBufferSize) / (topK * interSize * 4))))",
98
- "hiddenChunkCount": "max(1, ceilDiv(numTokens, max(1, hiddenChunkTokens)))",
99
- "routeScratchBytes": "numTokens * topK * 4",
100
- "routedScratchFits": "routeScratchBytes <= device.limits.maxStorageBufferBindingSize and routeScratchBytes <= device.limits.maxBufferSize",
101
- "groupSlots": "hiddenChunkTokens * topK",
102
- "groupMaxTiles": "ceilDiv(groupSlots, max(1, groupTileM)) + dim(shapes.routerT, 1)",
103
- "groupSlotOutBytes": "hiddenChunkTokens * topK * hiddenSize * 4",
104
- "groupedDeviceOk": "groupThreadCount <= device.limits.maxComputeInvocationsPerWorkgroup and tunables.groupThreads <= device.limits.maxComputeWorkgroupSizeX and tunables.groupThreads <= device.limits.maxComputeWorkgroupSizeY and tunables.groupRouteWorkgroup <= deviceWorkgroupCap and groupSharedBytes <= device.limits.maxComputeWorkgroupStorageSize and dim(shapes.routerT, 1) * 8 <= device.limits.maxComputeWorkgroupStorageSize and tunables.groupTileK % 4 == 0",
105
- "groupedDispatchOk": "groupMaxTiles <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(interSize, max(1, groupTileN)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(hiddenSize, max(1, groupTileN)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)",
106
- "groupSlotOutFits": "groupSlotOutBytes <= device.limits.maxStorageBufferBindingSize and groupSlotOutBytes <= device.limits.maxBufferSize",
107
- "groupedShapeOk": "numTokens * topK * 4 >= groupTileM * dim(shapes.routerT, 1)",
108
- "groupedContract": "quantContract and workgroupSizeOk and hiddenChunkFits and routedScratchFits and interSize > 0 and groupedDeviceOk and groupedDispatchOk and groupSlotOutFits and groupedShapeOk",
109
- "sgmatWorkgroup": "128",
110
- "sgmatSubgroups": "4",
111
- "sgmatRowSubtiles": "2",
112
- "sgmatTileCols": "64",
113
- "groupedSgmatStageElements": "max(groupTileM * 32, sgmatSubgroups * 4 * 64)",
114
- "groupedSgmatSharedBytes": "(groupedSgmatStageElements + sgmatTileCols * 32) * 4",
115
- "groupedSgmatOk": "groupedContract and groupTileM == 32 and interSize % 32 == 0 and groupedSgmatSharedBytes <= device.limits.maxComputeWorkgroupStorageSize and ceilDiv(hiddenSize, sgmatTileCols) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and hiddenSize % 32 == 0",
116
- "decodeDispatchOk": "ceilDiv(interSize, decodeRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(hiddenSize, decodeRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and hiddenChunkTokens * topK <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)",
117
- "decodeLaneDepth": "min(hiddenSize, interSize) / max(1, tunables.decodeLanes)",
118
- "decodeDepthOk": "decodeLaneDepth >= tunables.decodeMinLaneTrips",
119
- "splitFc1Blocks": "ceilDiv(numTokens * topK * interSize, max(1, tunables.workgroupSize))",
120
- "decodeOccupancyOk": "splitFc1Blocks <= tunables.decodeBlockTarget",
121
- "decodeContract": "quantContract and decodeDeviceOk and decodeDispatchOk and hiddenChunkFits and routedScratchFits and interSize > 0 and decodeDepthOk and (decodeOccupancyOk or not groupedContract)",
122
- "hidden": "hiddenSize",
123
- "experts": "dim(shapes.routerT, 1)",
124
- "inter": "interSize"
125
- },
126
- "bindings": {
127
- "output": { "arg": "outputT", "elementType": "f32" },
128
- "router_probs": { "arg": "routerT", "elementType": "f32" },
129
- "route_expert": { "scratch": "routeExpert", "elementType": "u32" },
130
- "route_mix": { "scratch": "routeMix", "elementType": "f32" },
131
- "route_expert_u32": {
132
- "scratch": "routeExpert",
133
- "name": "route_expert",
134
- "buffer": "read-only-storage",
135
- "elementType": "u32"
136
- },
137
- "slot_list": { "scratch": "slotList", "elementType": "u32" },
138
- "tile_meta": { "scratch": "tileMeta", "elementType": "u32" },
139
- "params_route": { "name": "params", "struct": [{ "name": "tokenCount", "type": "u32", "value": "numTokens" }] },
140
- "params": {
141
- "struct": [
142
- { "name": "tokenOffset", "type": "u32", "value": "repeat.chunk * hiddenChunkTokens" },
143
- {
144
- "name": "tokenCount",
145
- "type": "u32",
146
- "value": "min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens)"
147
- }
148
- ]
149
- },
150
- "input": { "arg": "inputT", "elementType": "f32" },
151
- "slot_list_u32": { "scratch": "slotList", "name": "slot_list", "buffer": "read-only-storage", "elementType": "u32" },
152
- "tile_meta_u32": { "scratch": "tileMeta", "name": "tile_meta", "buffer": "read-only-storage", "elementType": "u32" },
153
- "fc1_experts_weights": { "arg": "fc1T", "elementType": "u32" },
154
- "fc1_scales": { "arg": "fc1ScalesT", "elementType": "f32" },
155
- "hidden_act": { "scratch": "hiddenAct", "elementType": "f32" },
156
- "params__uniform": {
157
- "name": "params",
158
- "struct": [
159
- { "name": "activationAlpha", "type": "f32", "value": "attrs.activation_alpha" },
160
- { "name": "activationBeta", "type": "f32", "value": "attrs.activation_beta" },
161
- { "name": "tokenOffset", "type": "u32", "value": "repeat.chunk * hiddenChunkTokens" }
162
- ]
163
- },
164
- "hidden_act_f32": {
165
- "scratch": "hiddenAct",
166
- "name": "hidden_act",
167
- "buffer": "read-only-storage",
168
- "elementType": "f32"
169
- },
170
- "fc2_experts_weights": { "arg": "fc2T", "elementType": "u32" },
171
- "fc2_scales": { "arg": "fc2ScalesT", "elementType": "f32" },
172
- "slot_out": { "scratch": "slotOut", "elementType": "f32" },
173
- "slot_out_f32": { "scratch": "slotOut", "name": "slot_out", "buffer": "read-only-storage", "elementType": "f32" },
174
- "route_mix_f32": { "scratch": "routeMix", "name": "route_mix", "buffer": "read-only-storage", "elementType": "f32" }
175
- },
176
- "variants": [
177
- {
178
- "id": "quant_zero_inter",
179
- "priority": 20,
180
- "when": ["quantContract", "workgroupSizeOk", "interSize == 0"],
181
- "passes": [
182
- {
183
- "id": "output_stage",
184
- "name": "QMoE.OutputStageZeroInter",
185
- "shader": "qmoe-output-zero-inter.wgsl.jinja",
186
- "derive": { "outputElementCount": "numel(shapes.outputT)" },
187
- "bindings": ["output"],
188
- "dispatch": {
189
- "x": "min(ceilDiv((numel(shapes.outputT)), (workgroupSize)), 65535)",
190
- "y": "ceilDiv(ceilDiv((numel(shapes.outputT)), (workgroupSize)), 65535)",
191
- "z": 1
192
- }
193
- }
194
- ]
195
- },
196
- {
197
- "id": "quant_grouped_sgmat_routed",
198
- "priority": 32,
199
- "when": ["groupedSgmatOk", "wave32Effective"],
200
- "requires": {
201
- "features": ["subgroups", "chromium-experimental-subgroup-matrix"],
202
- "subgroupMatrixConfigs": [{ "componentType": "f32", "resultComponentType": "f32", "M": 8, "N": 8, "K": 8 }]
203
- },
204
- "intermediates": [
205
- { "id": "routeExpert", "dtype": "uint32", "shape": "[numTokens * topK]" },
206
- { "id": "routeMix", "dtype": "float32", "shape": "[numTokens * topK]" },
207
- { "id": "hiddenAct", "dtype": "float32", "shape": "[hiddenChunkTokens * topK * interSize]" },
208
- { "id": "slotList", "dtype": "uint32", "shape": "[max(1, groupSlots)]" },
209
- { "id": "tileMeta", "dtype": "uint32", "shape": "[1 + 3 * groupMaxTiles]" },
210
- { "id": "slotOut", "dtype": "float32", "shape": "[max(1, hiddenChunkTokens * topK * hiddenSize)]" }
211
- ],
212
- "passes": [
213
- {
214
- "id": "route_stage",
215
- "name": "QMoE.RouteStage",
216
- "shader": "qmoe-route-stage.wgsl.jinja",
217
- "bindings": ["router_probs", "route_expert", "route_mix", "params_route"],
218
- "dispatch": {
219
- "x": "min(ceilDiv((numTokens), (workgroupSize)), 65535)",
220
- "y": "ceilDiv(ceilDiv((numTokens), (workgroupSize)), 65535)",
221
- "z": 1
222
- }
223
- },
224
- {
225
- "id": "token_chunks",
226
- "repeat": { "count": "hiddenChunkCount", "index": "chunk" },
227
- "passes": [
228
- {
229
- "id": "group_stage",
230
- "name": "QMoE.GroupStage",
231
- "shader": "expert-group-slots.wgsl.jinja",
232
- "bindings": ["route_expert_u32", "slot_list", "tile_meta", "params"],
233
- "dispatch": { "x": 1 }
234
- },
235
- {
236
- "id": "fc1_activation_stage",
237
- "name": "QMoE.FC1ActivationStageGroupedSgmat",
238
- "shader": "qmoe-fc1-activation-grouped-sgmat.wgsl.jinja",
239
- "bindings": ["input", "slot_list_u32", "tile_meta_u32", "fc1_experts_weights", "fc1_scales", "hidden_act", "params__uniform"],
240
- "dispatch": { "x": "groupMaxTiles", "y": "ceilDiv(interSize * fusionSize, sgmatTileCols)" }
241
- },
242
- {
243
- "id": "output_stage",
244
- "name": "QMoE.OutputStageGroupedSgmat",
245
- "shader": "qmoe-output-grouped-sgmat.wgsl.jinja",
246
- "bindings": ["hidden_act_f32", "slot_list_u32", "tile_meta_u32", "fc2_experts_weights", "fc2_scales", "slot_out"],
247
- "dispatch": { "x": "groupMaxTiles", "y": "ceilDiv(hiddenSize, sgmatTileCols)" }
248
- },
249
- {
250
- "id": "mix_stage",
251
- "name": "QMoE.MixStage",
252
- "shader": "expert-slot-mix.wgsl.jinja",
253
- "bindings": ["slot_out_f32", "route_mix_f32", "output", "params"],
254
- "dispatch": {
255
- "x": "min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)",
256
- "y": "ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)",
257
- "z": 1
258
- }
259
- }
260
- ]
261
- }
262
- ]
263
- },
264
- {
265
- "id": "quant_grouped_routed",
266
- "priority": 30,
267
- "when": ["groupedContract"],
268
- "intermediates": [
269
- { "id": "routeExpert", "dtype": "uint32", "shape": "[numTokens * topK]" },
270
- { "id": "routeMix", "dtype": "float32", "shape": "[numTokens * topK]" },
271
- { "id": "hiddenAct", "dtype": "float32", "shape": "[hiddenChunkTokens * topK * interSize]" },
272
- { "id": "slotList", "dtype": "uint32", "shape": "[max(1, groupSlots)]" },
273
- { "id": "tileMeta", "dtype": "uint32", "shape": "[1 + 3 * groupMaxTiles]" },
274
- { "id": "slotOut", "dtype": "float32", "shape": "[max(1, hiddenChunkTokens * topK * hiddenSize)]" }
275
- ],
276
- "passes": [
277
- {
278
- "id": "route_stage",
279
- "name": "QMoE.RouteStage",
280
- "shader": "qmoe-route-stage.wgsl.jinja",
281
- "bindings": ["router_probs", "route_expert", "route_mix", "params_route"],
282
- "dispatch": {
283
- "x": "min(ceilDiv((numTokens), (workgroupSize)), 65535)",
284
- "y": "ceilDiv(ceilDiv((numTokens), (workgroupSize)), 65535)",
285
- "z": 1
286
- }
287
- },
288
- {
289
- "id": "token_chunks",
290
- "repeat": { "count": "hiddenChunkCount", "index": "chunk" },
291
- "passes": [
292
- {
293
- "id": "group_stage",
294
- "name": "QMoE.GroupStage",
295
- "shader": "expert-group-slots.wgsl.jinja",
296
- "bindings": ["route_expert_u32", "slot_list", "tile_meta", "params"],
297
- "dispatch": { "x": 1 }
298
- },
299
- {
300
- "id": "fc1_activation_stage",
301
- "name": "QMoE.FC1ActivationStageGrouped",
302
- "shader": "qmoe-fc1-activation-grouped.wgsl.jinja",
303
- "bindings": ["input", "slot_list_u32", "tile_meta_u32", "fc1_experts_weights", "fc1_scales", "hidden_act", "params__uniform"],
304
- "dispatch": { "x": "groupMaxTiles", "y": "ceilDiv(interSize, groupTileN)" }
305
- },
306
- {
307
- "id": "output_stage",
308
- "name": "QMoE.OutputStageGrouped",
309
- "shader": "qmoe-output-grouped.wgsl.jinja",
310
- "bindings": ["hidden_act_f32", "slot_list_u32", "tile_meta_u32", "fc2_experts_weights", "fc2_scales", "slot_out"],
311
- "dispatch": { "x": "groupMaxTiles", "y": "ceilDiv(hiddenSize, groupTileN)" }
312
- },
313
- {
314
- "id": "mix_stage",
315
- "name": "QMoE.MixStage",
316
- "shader": "expert-slot-mix.wgsl.jinja",
317
- "bindings": ["slot_out_f32", "route_mix_f32", "output", "params"],
318
- "dispatch": {
319
- "x": "min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)",
320
- "y": "ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)",
321
- "z": 1
322
- }
323
- }
324
- ]
325
- }
326
- ]
327
- },
328
- {
329
- "id": "quant_gemv_routed",
330
- "priority": 20,
331
- "when": ["decodeContract"],
332
- "derive": { "decodeLanes": "tunables.decodeLanes" },
333
- "intermediates": [
334
- { "id": "routeExpert", "dtype": "uint32", "shape": "[numTokens * topK]" },
335
- { "id": "routeMix", "dtype": "float32", "shape": "[numTokens * topK]" },
336
- { "id": "hiddenAct", "dtype": "float32", "shape": "[hiddenChunkTokens * topK * interSize]" }
337
- ],
338
- "passes": [
339
- {
340
- "id": "route_stage",
341
- "name": "QMoE.RouteStage",
342
- "shader": "qmoe-route-stage.wgsl.jinja",
343
- "bindings": ["router_probs", "route_expert", "route_mix", "params_route"],
344
- "dispatch": {
345
- "x": "min(ceilDiv((numTokens), (workgroupSize)), 65535)",
346
- "y": "ceilDiv(ceilDiv((numTokens), (workgroupSize)), 65535)",
347
- "z": 1
348
- }
349
- },
350
- {
351
- "id": "token_chunks",
352
- "repeat": { "count": "hiddenChunkCount", "index": "chunk" },
353
- "passes": [
354
- {
355
- "id": "fc1_activation_stage",
356
- "name": "QMoE.FC1ActivationStageGemv",
357
- "shader": "qmoe-fc1-activation-gemv.wgsl.jinja",
358
- "bindings": ["input", "route_expert_u32", "fc1_experts_weights", "fc1_scales", "hidden_act", "params__uniform"],
359
- "dispatch": {
360
- "x": "ceilDiv(interSize, decodeRows)",
361
- "y": "min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * topK"
362
- }
363
- },
364
- {
365
- "id": "output_stage",
366
- "name": "QMoE.OutputStageGemv",
367
- "shader": "qmoe-output-gemv.wgsl.jinja",
368
- "bindings": [
369
- "hidden_act_f32",
370
- "route_expert_u32",
371
- "route_mix_f32",
372
- "fc2_experts_weights",
373
- "fc2_scales",
374
- "output",
375
- {
376
- "name": "params",
377
- "struct": [{ "name": "tokenOffset", "type": "u32", "value": "repeat.chunk * hiddenChunkTokens" }]
378
- }
379
- ],
380
- "dispatch": {
381
- "x": "ceilDiv(hiddenSize, decodeRows)",
382
- "y": "min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens)"
383
- }
384
- }
385
- ]
386
- }
387
- ]
388
- },
389
- {
390
- "id": "quant_split_routed",
391
- "priority": 10,
392
- "when": ["quantContract", "workgroupSizeOk", "hiddenChunkFits", "routedScratchFits", "interSize > 0"],
393
- "intermediates": [
394
- { "id": "routeExpert", "dtype": "uint32", "shape": "[numTokens * topK]" },
395
- { "id": "routeMix", "dtype": "float32", "shape": "[numTokens * topK]" },
396
- { "id": "hiddenAct", "dtype": "float32", "shape": "[hiddenChunkTokens * topK * interSize]" }
397
- ],
398
- "passes": [
399
- {
400
- "id": "route_stage",
401
- "name": "QMoE.RouteStage",
402
- "shader": "qmoe-route-stage.wgsl.jinja",
403
- "bindings": ["router_probs", "route_expert", "route_mix", "params_route"],
404
- "dispatch": {
405
- "x": "min(ceilDiv((numTokens), (workgroupSize)), 65535)",
406
- "y": "ceilDiv(ceilDiv((numTokens), (workgroupSize)), 65535)",
407
- "z": 1
408
- }
409
- },
410
- {
411
- "id": "token_chunks",
412
- "repeat": { "count": "hiddenChunkCount", "index": "chunk" },
413
- "passes": [
414
- {
415
- "id": "fc1_activation_stage",
416
- "name": "QMoE.FC1ActivationStage",
417
- "shader": "qmoe-fc1-activation-stage.wgsl.jinja",
418
- "bindings": [
419
- "input",
420
- "route_expert_u32",
421
- "fc1_experts_weights",
422
- "fc1_scales",
423
- "hidden_act",
424
- {
425
- "name": "params",
426
- "struct": [
427
- { "name": "activationAlpha", "type": "f32", "value": "attrs.activation_alpha" },
428
- { "name": "activationBeta", "type": "f32", "value": "attrs.activation_beta" },
429
- { "name": "tokenOffset", "type": "u32", "value": "repeat.chunk * hiddenChunkTokens" },
430
- {
431
- "name": "tokenCount",
432
- "type": "u32",
433
- "value": "min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens)"
434
- }
435
- ]
436
- }
437
- ],
438
- "dispatch": {
439
- "x": "min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * topK * interSize), (workgroupSize)), 65535)",
440
- "y": "ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * topK * interSize), (workgroupSize)), 65535)",
441
- "z": 1
442
- }
443
- },
444
- {
445
- "id": "output_stage",
446
- "name": "QMoE.OutputStage",
447
- "shader": "qmoe-output-stage.wgsl.jinja",
448
- "bindings": ["hidden_act_f32", "route_expert_u32", "route_mix_f32", "fc2_experts_weights", "fc2_scales", "output", "params"],
449
- "dispatch": {
450
- "x": "min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)",
451
- "y": "ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)",
452
- "z": 1
453
- }
454
- }
455
- ]
456
- }
457
- ]
458
- }
459
- ]
460
- }
 
1
+ {"domain":"com.microsoft","name":"QMoE","sinceVersion":1,"inputs":{"inputT":{"onnx":"input","dtype":"T"},"routerT":{"onnx":"router_probs","dtype":"T","rank":2},"fc1T":{"onnx":"fc1_experts_weights","dtype":"T1","rank":3},"fc1ScalesT":{"onnx":"fc1_scales","dtype":"T2"},"fc2T":{"onnx":"fc2_experts_weights","dtype":"T1","rank":3},"fc2ScalesT":{"onnx":"fc2_scales","dtype":"T2"}},"outputs":{"outputT":{"onnx":"output","dtype":"T","shape":"shapes.inputT"}},"attributes":{"activation_alpha":{"default":1},"activation_beta":{"default":0},"activation_type":{"default":"relu"},"expert_weight_bits":{"default":4},"k":{"default":1},"normalize_routing_weights":{"default":0},"quant_type":{"default":"int"},"swiglu_fusion":{"default":0},"use_sparse_mixer":{"default":0},"weights_prepacked":{"default":-1},"block_size":{},"swiglu_limit":{}},"attributeConstraints":{"activation_type":{"values":["relu","swiglu"]},"expert_weight_bits":{"values":[2,4,8]},"normalize_routing_weights":{"values":[0,1]},"quant_type":{"values":["int"]},"swiglu_fusion":{"values":[0,1]},"use_sparse_mixer":{"values":[0]},"weights_prepacked":{"values":[-1,0]}},"typeConstraints":{"T":["float32"],"T1":["uint8"],"T2":["float32"]},"tunables":{"workgroupSize":{"default":64},"decodeLanes":{"default":32},"decodeBlockTarget":{"default":1024},"decodeMinLaneTrips":{"default":4},"groupThreads":{"default":8},"groupRegM":{"default":4},"groupRegN":{"default":4},"groupTileK":{"default":16},"groupRouteWorkgroup":{"default":256}},"derive":{"deviceWorkgroupCap":"min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)","wave32Adapter":"has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 32 and device.adapterInfo.subgroupMaxSize == 32","subgroupsWave32":"device.features.has(\"subgroups\") and wave32Adapter","canPinSubgroupSize32":"device.features.has(\"subgroups\") and device.features.has(\"subgroup-size-control\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize <= 32 and device.adapterInfo.subgroupMaxSize >= 32","pinSubgroupSize32":"canPinSubgroupSize32 and not wave32Adapter","wave32Effective":"wave32Adapter or pinSubgroupSize32","nvidiaAdapter":"has(device.adapterInfo, \"vendor\") and device.adapterInfo.vendor == \"nvidia\"","groupThreads":"tunables.groupThreads","groupRouteWorkgroup":"tunables.groupRouteWorkgroup","groupThreadCount":"tunables.groupThreads * tunables.groupThreads","explicitSubgroupMinSize":"(16 if device.adapterInfo.subgroupMinSize == 8 else device.adapterInfo.subgroupMinSize) if has(device.adapterInfo, \"subgroupMinSize\") else 0","topK":"attrs.k","activationType":"attrs.activation_type","workgroupSizeOk":"tunables.workgroupSize >= 1 and tunables.workgroupSize <= deviceWorkgroupCap","decodeLanesOk":"tunables.decodeLanes >= 1 and tunables.decodeLanes <= tunables.workgroupSize and tunables.workgroupSize % tunables.decodeLanes == 0","decodeRows":"max(1, tunables.workgroupSize / max(1, tunables.decodeLanes))","decodeDeviceOk":"workgroupSizeOk and decodeLanesOk and tunables.decodeLanes <= device.limits.maxComputeWorkgroupSizeX and decodeRows <= device.limits.maxComputeWorkgroupSizeY and tunables.workgroupSize * 8 <= device.limits.maxComputeWorkgroupStorageSize","fc1Rows":"dim(shapes.fc1T, 1)","hasSwigluLimit":"has(attrs, \"swiglu_limit\")","swigluLimit":"attrs.swiglu_limit if has(attrs, \"swiglu_limit\") else 0","workgroupSize":"tunables.workgroupSize","subgroupMatrixTopologyBytes":"3 * 16","groupedWave32Schedule":"subgroupsWave32 and device.features.has(\"chromium-experimental-subgroup-matrix\") and subgroupMatrixConfigAvailable(\"i8\", \"i32\", 16, 16, 32) and not subgroupMatrixConfigAvailable(\"f32\", \"f32\", 8, 8, 8)","expertF32Schedule":"groupedWave32Schedule","groupTileK":"32 if expertF32Schedule else tunables.groupTileK","groupTileKVec":"ceilDiv(groupTileK, 4)","hiddenSize":"dim(shapes.inputT, ranks.inputT - 1)","groupDensityDivisor":"max(1, hiddenSize * dim(shapes.routerT, 1) * tunables.groupThreads)","groupDensityRegM":"min(tunables.groupRegM, max(1, pow2ceil(ceilDiv(numel(shapes.inputT) * attrs.k, groupDensityDivisor))))","regM":"tunables.groupRegM if device.features.has(\"chromium-experimental-subgroup-matrix\") else groupDensityRegM","groupTileM":"tunables.groupThreads * regM","numTokens":"numel(shapes.inputT) / max(1, hiddenSize)","weightBits":"attrs.expert_weight_bits","quantBlockSize":"attrs.block_size if has(attrs, \"block_size\") else 0","packSize":"8 / weightBits","quantMidpoint":"pow(2, weightBits - 1)","fusionSize":"2 if attrs.activation_type == \"swiglu\" and attrs.swiglu_fusion == 1 else 1","regN":"min(tunables.groupRegN, max(1, floor(device.adapterInfo.subgroupMinSize / max(1, regM * fusionSize)))) if device.features.has(\"subgroups\") and not device.features.has(\"chromium-experimental-subgroup-matrix\") and has(device.adapterInfo, \"subgroupMinSize\") and device.adapterInfo.subgroupMinSize > 0 else tunables.groupRegN","groupTileN":"groupThreads * regN","groupSharedBytes":"(groupTileM * groupTileK + 2 * groupTileN * groupTileK + groupTileM) * 4","interSize":"dim(shapes.fc1T, 1) / fusionSize","fc1PackedCols":"dim(shapes.fc1T, 2)","fc2PackedCols":"dim(shapes.fc2T, 2)","colWiseScales":"quantBlockSize == 0","fc1ScaleBlocks":"1 if colWiseScales else hiddenSize / max(1, quantBlockSize)","fc2ScaleBlocks":"1 if colWiseScales else interSize / max(1, quantBlockSize)","activationSupported":"(attrs.activation_type == \"relu\" and attrs.swiglu_fusion == 0) or (attrs.activation_type == \"swiglu\" and attrs.swiglu_fusion == 1)","routingModeSupported":"attrs.normalize_routing_weights == 0 or attrs.normalize_routing_weights == 1","normalizeRoutingWeights":"attrs.normalize_routing_weights == 1","rawWeightLayout":"attrs.weights_prepacked == -1 or attrs.weights_prepacked == 0","inputOutputShapeOk":"((ranks.inputT == 2 and ranks.outputT == 2 and dim(shapes.outputT, 0) == dim(shapes.inputT, 0) and dim(shapes.outputT, 1) == dim(shapes.inputT, 1)) or (ranks.inputT == 3 and ranks.outputT == 3 and dim(shapes.outputT, 0) == dim(shapes.inputT, 0) and dim(shapes.outputT, 1) == dim(shapes.inputT, 1) and dim(shapes.outputT, 2) == dim(shapes.inputT, 2))) and hiddenSize > 0","quantBlockSizeOk":"colWiseScales or (quantBlockSize >= 16 and pow2ceil(quantBlockSize) == quantBlockSize and hiddenSize % quantBlockSize == 0 and interSize % quantBlockSize == 0)","quantScalesOk":"tensorDtypes.fc1ScalesT == \"float32\" and tensorDtypes.fc2ScalesT == \"float32\" and dim(shapes.fc1ScalesT, 0) == dim(shapes.routerT, 1) and dim(shapes.fc2ScalesT, 0) == dim(shapes.routerT, 1) and dim(shapes.fc1ScalesT, 1) == dim(shapes.fc1T, 1) and dim(shapes.fc2ScalesT, 1) == hiddenSize and ((ranks.fc1ScalesT == 2 and ranks.fc2ScalesT == 2) if colWiseScales else (ranks.fc1ScalesT == 3 and ranks.fc2ScalesT == 3 and dim(shapes.fc1ScalesT, 2) == fc1ScaleBlocks and dim(shapes.fc2ScalesT, 2) == fc2ScaleBlocks))","quantShapeOk":"inputOutputShapeOk and ranks.routerT == 2 and ranks.fc1T == 3 and ranks.fc2T == 3 and dim(shapes.routerT, 0) == numTokens and dim(shapes.fc1T, 0) == dim(shapes.routerT, 1) and dim(shapes.fc2T, 0) == dim(shapes.routerT, 1) and dim(shapes.fc1T, 1) % fusionSize == 0 and dim(shapes.fc2T, 1) == hiddenSize and dim(shapes.fc1T, 2) * packSize == hiddenSize and dim(shapes.fc2T, 2) * packSize == interSize and quantBlockSizeOk and quantScalesOk","quantContract":"activationSupported and routingModeSupported and rawWeightLayout and quantShapeOk and floor(topK) == topK and topK >= 1 and topK <= dim(shapes.routerT, 1)","hiddenChunkFits":"topK * interSize * 4 <= device.limits.maxStorageBufferBindingSize and topK * interSize * 4 <= device.limits.maxBufferSize","hiddenChunkTokens":"numTokens if interSize == 0 else min(numTokens, max(1, floor(min(device.limits.maxStorageBufferBindingSize, device.limits.maxBufferSize) / (topK * interSize * 4))))","hiddenChunkCount":"max(1, ceilDiv(numTokens, max(1, hiddenChunkTokens)))","routeScratchBytes":"numTokens * topK * 4","routedScratchFits":"routeScratchBytes <= device.limits.maxStorageBufferBindingSize and routeScratchBytes <= device.limits.maxBufferSize","groupSlots":"hiddenChunkTokens * topK","groupMaxTiles":"ceilDiv(groupSlots, max(1, groupTileM)) + dim(shapes.routerT, 1)","groupSlotOutBytes":"hiddenChunkTokens * topK * hiddenSize * 4","groupedDeviceOk":"groupThreadCount <= device.limits.maxComputeInvocationsPerWorkgroup and tunables.groupThreads <= device.limits.maxComputeWorkgroupSizeX and tunables.groupThreads <= device.limits.maxComputeWorkgroupSizeY and tunables.groupRouteWorkgroup <= deviceWorkgroupCap and groupSharedBytes <= device.limits.maxComputeWorkgroupStorageSize and dim(shapes.routerT, 1) * 8 <= device.limits.maxComputeWorkgroupStorageSize and groupTileK % 4 == 0","groupedDispatchOk":"groupMaxTiles <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(interSize, max(1, groupTileN)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(hiddenSize, max(1, groupTileN)) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","groupSlotOutFits":"groupSlotOutBytes <= device.limits.maxStorageBufferBindingSize and groupSlotOutBytes <= device.limits.maxBufferSize","groupedShapeOk":"numTokens * topK * 4 >= tunables.groupThreads * tunables.groupRegM * dim(shapes.routerT, 1)","groupedContract":"quantContract and workgroupSizeOk and hiddenChunkFits and routedScratchFits and interSize > 0 and groupedDeviceOk and groupedDispatchOk and groupSlotOutFits and groupedShapeOk","sgmatSubgroups":"4","sgmatTileCols":"64","groupedSgmatStageElements":"max(groupTileM * 32, sgmatSubgroups * 4 * 64)","groupedSgmatSharedBytes":"((groupedSgmatStageElements + sgmatTileCols * 32) * 4) + subgroupMatrixTopologyBytes","groupedSgmatOk":"groupedContract and groupTileM == 32 and interSize % 32 == 0 and groupedSgmatSharedBytes <= device.limits.maxComputeWorkgroupStorageSize and ceilDiv(hiddenSize, sgmatTileCols) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and hiddenSize % 32 == 0","decodeDispatchOk":"ceilDiv(interSize, decodeRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(hiddenSize, decodeRows) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and hiddenChunkTokens * topK <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","decodeLaneDepth":"min(hiddenSize, interSize) / max(1, tunables.decodeLanes)","decodeDepthOk":"decodeLaneDepth >= tunables.decodeMinLaneTrips","splitFc1Blocks":"ceilDiv(numTokens * topK * interSize, max(1, tunables.workgroupSize))","decodeOccupancyOk":"splitFc1Blocks <= tunables.decodeBlockTarget","decodeContract":"quantContract and decodeDeviceOk and decodeDispatchOk and hiddenChunkFits and routedScratchFits and interSize > 0 and decodeDepthOk and (decodeOccupancyOk or not groupedContract)","hidden":"hiddenSize","experts":"dim(shapes.routerT, 1)","inter":"interSize","gemvVec4":"weightBits <= 4 and hiddenSize % 4 == 0 and interSize % 4 == 0 and device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and device.adapterInfo.subgroupMinSize >= tunables.decodeLanes","groupVectorAligned":"weightBits == 8 and hiddenSize % 4 == 0 and interSize % 4 == 0","packedWeights":false,"routeParallelLanes":"min(pow2ceil(experts), pow2ceil(deviceWorkgroupCap + 1) / 2, pow2ceil(max(1, floor((device.limits.maxComputeWorkgroupStorageSize - 8 * topK - 4) / 8)) + 1) / 2)","parallelRoute":"numTokens == 1 and topK > 1 and routeParallelLanes >= 2 and 8 * (routeParallelLanes + topK) + 4 <= device.limits.maxComputeWorkgroupStorageSize","groupedF32MatrixAvailable":"device.features.has(\"chromium-experimental-subgroup-matrix\") and subgroupMatrixConfigAvailable(\"f32\", \"f32\", 8, 8, 8)","groupUnadaptedMaxTiles":"ceilDiv(groupSlots, max(1, tunables.groupThreads * tunables.groupRegM)) + experts","groupUnadaptedGrid":"groupUnadaptedMaxTiles * ceilDiv(interSize, max(1, groupThreads * tunables.groupRegN))","groupDensityMaxTiles":"ceilDiv(groupSlots, max(1, tunables.groupThreads * groupDensityRegM)) + experts","groupDensityFits":"groupDensityMaxTiles <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and (1 + 3 * groupDensityMaxTiles) * 4 <= min(device.limits.maxStorageBufferBindingSize, device.limits.maxBufferSize)","groupAdaptiveMeasuredTier":"nvidiaAdapter and has(device.adapterInfo, \"architecture\") and device.adapterInfo.architecture == \"blackwell\" and subgroupsWave32 and device.features.has(\"chromium-experimental-subgroup-matrix\") and not groupedF32MatrixAvailable and subgroupMatrixConfigAvailable(\"i8\", \"i32\", 16, 16, 32)","groupAdaptiveRows":"groupAdaptiveMeasuredTier and groupUnadaptedGrid < 512 and groupDensityFits","groupPortableRegM":"groupDensityRegM if groupAdaptiveRows else regM","groupWeightLaneInterleaved":"nvidiaAdapter and has(device.adapterInfo, \"architecture\") and device.adapterInfo.architecture == \"blackwell\"","expertQ4Vec4Candidate":"expertF32Schedule and weightBits == 4 and hiddenSize % 8 == 0 and interSize % 8 == 0","expertWeightElement":"\"u32\"","expertQ4Vec4":"false"},"bindings":{"output":{"arg":"outputT","elementType":"f32"},"router_probs":{"arg":"routerT","elementType":"f32"},"route_expert":{"scratch":"routeExpert","elementType":"u32"},"route_mix":{"scratch":"routeMix","elementType":"f32"},"route_expert_u32":{"scratch":"routeExpert","name":"route_expert","buffer":"read-only-storage","elementType":"u32"},"slot_list":{"scratch":"slotList","elementType":"u32"},"tile_meta":{"scratch":"tileMeta","elementType":"u32"},"params_route":{"name":"params","struct":[{"name":"tokenCount","type":"u32","value":"numTokens"}]},"params":{"struct":[{"name":"tokenOffset","type":"u32","value":"repeat.chunk * hiddenChunkTokens"},{"name":"tokenCount","type":"u32","value":"min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens)"}]},"input":{"arg":"inputT","elementType":"f32"},"slot_list_u32":{"scratch":"slotList","name":"slot_list","buffer":"read-only-storage","elementType":"u32"},"tile_meta_u32":{"scratch":"tileMeta","name":"tile_meta","buffer":"read-only-storage","elementType":"u32"},"fc1_experts_weights":{"arg":"fc1T","elementType":"$expertWeightElement"},"fc1_scales":{"arg":"fc1ScalesT","elementType":"f32"},"hidden_act":{"scratch":"hiddenAct","elementType":"f32"},"params__uniform":{"name":"params","struct":[{"name":"activationAlpha","type":"f32","value":"attrs.activation_alpha"},{"name":"activationBeta","type":"f32","value":"attrs.activation_beta"},{"name":"tokenOffset","type":"u32","value":"repeat.chunk * hiddenChunkTokens"}]},"hidden_act_f32":{"scratch":"hiddenAct","name":"hidden_act","buffer":"read-only-storage","elementType":"f32"},"fc2_experts_weights":{"arg":"fc2T","elementType":"$expertWeightElement"},"fc2_scales":{"arg":"fc2ScalesT","elementType":"f32"},"slot_out":{"scratch":"slotOut","elementType":"f32"},"slot_out_f32":{"scratch":"slotOut","name":"slot_out","buffer":"read-only-storage","elementType":"f32"},"route_mix_f32":{"scratch":"routeMix","name":"route_mix","buffer":"read-only-storage","elementType":"f32"},"fc1_experts_weights_vec4":{"arg":"fc1T","name":"fc1_experts_weights","elementType":"vec4<u32>"},"fc2_experts_weights_vec4":{"arg":"fc2T","name":"fc2_experts_weights","elementType":"vec4<u32>"}},"variants":[{"id":"quant_zero_inter","priority":20,"when":["quantContract","workgroupSizeOk","interSize == 0"],"passes":[{"id":"output_stage","name":"QMoE.OutputStageZeroInter","shader":"qmoe-output-zero-inter.wgsl.jinja","derive":{"outputElementCount":"numel(shapes.outputT)"},"bindings":["output"],"dispatch":{"x":"min(ceilDiv((numel(shapes.outputT)), (workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((numel(shapes.outputT)), (workgroupSize)), 65535)","z":1}}]},{"id":"quant_grouped_sgmat_routed","priority":32,"when":["groupedSgmatOk","wave32Effective"],"requires":{"features":["subgroups","chromium-experimental-subgroup-matrix"],"subgroupMatrixConfigs":[{"componentType":"f32","resultComponentType":"f32","M":8,"N":8,"K":8}]},"intermediates":[{"id":"routeExpert","dtype":"uint32","shape":"[numTokens * topK]"},{"id":"routeMix","dtype":"float32","shape":"[numTokens * topK]"},{"id":"hiddenAct","dtype":"float32","shape":"[hiddenChunkTokens * topK * interSize]"},{"id":"slotList","dtype":"uint32","shape":"[max(1, groupSlots)]"},{"id":"tileMeta","dtype":"uint32","shape":"[1 + 3 * groupMaxTiles]"},{"id":"slotOut","dtype":"float32","shape":"[max(1, hiddenChunkTokens * topK * hiddenSize)]"}],"passes":[{"id":"route_stage","name":"QMoE.RouteStage","shader":"qmoe-route-stage.wgsl.jinja","bindings":["router_probs","route_expert","route_mix","params_route"],"dispatch":{"x":"min(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","z":1}},{"id":"token_chunks","repeat":{"count":"hiddenChunkCount","index":"chunk"},"passes":[{"id":"group_stage","name":"QMoE.GroupStage","shader":"expert-group-slots.wgsl.jinja","bindings":["route_expert_u32","slot_list","tile_meta","params"],"dispatch":{"x":1}},{"id":"fc1_activation_stage","name":"QMoE.FC1ActivationStageGroupedSgmat","shader":"qmoe-fc1-activation-grouped-sgmat.wgsl.jinja","bindings":["input","slot_list_u32","tile_meta_u32","fc1_experts_weights","fc1_scales","hidden_act","params__uniform"],"dispatch":{"x":"groupMaxTiles","y":"ceilDiv(interSize * fusionSize, sgmatTileCols)"}},{"id":"output_stage","name":"QMoE.OutputStageGroupedSgmat","shader":"qmoe-output-grouped-sgmat.wgsl.jinja","bindings":["hidden_act_f32","slot_list_u32","tile_meta_u32","fc2_experts_weights","fc2_scales","slot_out"],"dispatch":{"x":"groupMaxTiles","y":"ceilDiv(hiddenSize, sgmatTileCols)"}},{"id":"mix_stage","name":"QMoE.MixStage","shader":"expert-slot-mix.wgsl.jinja","bindings":["slot_out_f32","route_mix_f32","output","params"],"dispatch":{"x":"min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)","z":1}}]}],"derive":{"sgmatWorkgroup":"128","sgmatRowSubtiles":"2"}},{"id":"quant_grouped_vector_routed","priority":31,"when":["groupedContract","groupVectorAligned"],"intermediates":[{"id":"routeExpert","dtype":"uint32","shape":"[numTokens * topK]"},{"id":"routeMix","dtype":"float32","shape":"[numTokens * topK]"},{"id":"hiddenAct","dtype":"float32","shape":"[hiddenChunkTokens * topK * interSize]"},{"id":"slotList","dtype":"uint32","shape":"[max(1, groupSlots)]"},{"id":"tileMeta","dtype":"uint32","shape":"[1 + 3 * groupMaxTiles]"},{"id":"slotOut","dtype":"float32","shape":"[max(1, hiddenChunkTokens * topK * hiddenSize)]"}],"passes":[{"id":"route_stage","name":"QMoE.RouteStage","shader":"qmoe-route-stage.wgsl.jinja","bindings":["router_probs","route_expert","route_mix","params_route"],"dispatch":{"x":"min(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","z":1}},{"id":"token_chunks","repeat":{"count":"hiddenChunkCount","index":"chunk"},"passes":[{"id":"group_stage","name":"QMoE.GroupStage","shader":"expert-group-slots.wgsl.jinja","bindings":["route_expert_u32","slot_list","tile_meta","params"],"dispatch":{"x":1}},{"id":"fc1_activation_stage","name":"QMoE.FC1ActivationStageGroupedVector","shader":"qmoe-fc1-activation-grouped.wgsl.jinja","bindings":["input","slot_list_u32","tile_meta_u32","fc1_experts_weights_vec4","fc1_scales","hidden_act","params__uniform"],"dispatch":{"x":"groupMaxTiles","y":"ceilDiv(interSize, groupTileN)"}},{"id":"output_stage","name":"QMoE.OutputStageGroupedVector","shader":"qmoe-output-grouped.wgsl.jinja","bindings":["hidden_act_f32","slot_list_u32","tile_meta_u32","fc2_experts_weights_vec4","fc2_scales","slot_out"],"dispatch":{"x":"groupMaxTiles","y":"ceilDiv(hiddenSize, groupTileN)"}},{"id":"mix_stage","name":"QMoE.MixStage","shader":"expert-slot-mix.wgsl.jinja","bindings":["slot_out_f32","route_mix_f32","output","params"],"dispatch":{"x":"min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)","z":1}}]}],"derive":{"expertQ4Vec4":"expertQ4Vec4Candidate","regM":"groupPortableRegM","groupTileM":"tunables.groupThreads * regM","groupSharedBytes":"(groupTileM * groupTileK + 2 * groupTileN * groupTileK + groupTileM) * 4","groupMaxTiles":"ceilDiv(groupSlots, max(1, groupTileM)) + experts","weightVectorTransport":"true","scalarQuantAccum":"weightBits == 8 and not device.features.has(\"subgroups\")","groupWeightKMajor":"device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and device.adapterInfo.subgroupMinSize >= groupThreads * tunables.groupRegN","qmoeGroupedPin":"explicitSubgroupMinSize if device.features.has(\"subgroups\") and device.features.has(\"subgroup-size-control\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize > 0 and device.adapterInfo.subgroupMinSize < device.adapterInfo.subgroupMaxSize and explicitSubgroupMinSize <= device.adapterInfo.subgroupMaxSize and groupThreadCount % explicitSubgroupMinSize == 0 and groupThreadCount <= device.limits.maxComputeWorkgroupSizeX and regM == tunables.groupRegM and weightBits <= 4 else 0"}},{"id":"quant_grouped_routed","priority":30,"when":["groupedContract"],"intermediates":[{"id":"routeExpert","dtype":"uint32","shape":"[numTokens * topK]"},{"id":"routeMix","dtype":"float32","shape":"[numTokens * topK]"},{"id":"hiddenAct","dtype":"float32","shape":"[hiddenChunkTokens * topK * interSize]"},{"id":"slotList","dtype":"uint32","shape":"[max(1, groupSlots)]"},{"id":"tileMeta","dtype":"uint32","shape":"[1 + 3 * groupMaxTiles]"},{"id":"slotOut","dtype":"float32","shape":"[max(1, hiddenChunkTokens * topK * hiddenSize)]"}],"passes":[{"id":"route_stage","name":"QMoE.RouteStage","shader":"qmoe-route-stage.wgsl.jinja","bindings":["router_probs","route_expert","route_mix","params_route"],"dispatch":{"x":"min(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","z":1}},{"id":"token_chunks","repeat":{"count":"hiddenChunkCount","index":"chunk"},"passes":[{"id":"group_stage","name":"QMoE.GroupStage","shader":"expert-group-slots.wgsl.jinja","bindings":["route_expert_u32","slot_list","tile_meta","params"],"dispatch":{"x":1}},{"id":"fc1_activation_stage","name":"QMoE.FC1ActivationStageGrouped","shader":"qmoe-fc1-activation-grouped.wgsl.jinja","bindings":["input","slot_list_u32","tile_meta_u32","fc1_experts_weights","fc1_scales","hidden_act","params__uniform"],"dispatch":{"x":"groupMaxTiles","y":"ceilDiv(interSize, groupTileN)"}},{"id":"output_stage","name":"QMoE.OutputStageGrouped","shader":"qmoe-output-grouped.wgsl.jinja","bindings":["hidden_act_f32","slot_list_u32","tile_meta_u32","fc2_experts_weights","fc2_scales","slot_out"],"dispatch":{"x":"groupMaxTiles","y":"ceilDiv(hiddenSize, groupTileN)"}},{"id":"mix_stage","name":"QMoE.MixStage","shader":"expert-slot-mix.wgsl.jinja","bindings":["slot_out_f32","route_mix_f32","output","params"],"dispatch":{"x":"min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)","z":1}}]}],"derive":{"expertQ4Vec4":"expertQ4Vec4Candidate","regM":"groupPortableRegM","groupTileM":"tunables.groupThreads * regM","groupSharedBytes":"(groupTileM * groupTileK + 2 * groupTileN * groupTileK + groupTileM) * 4","groupMaxTiles":"ceilDiv(groupSlots, max(1, groupTileM)) + experts","weightVectorTransport":"expertQ4Vec4 or false","scalarQuantAccum":"weightBits == 8 and not device.features.has(\"subgroups\")","groupWeightKMajor":"device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and device.adapterInfo.subgroupMinSize >= groupThreads * tunables.groupRegN","qmoeGroupedPin":"explicitSubgroupMinSize if device.features.has(\"subgroups\") and device.features.has(\"subgroup-size-control\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize > 0 and device.adapterInfo.subgroupMinSize < device.adapterInfo.subgroupMaxSize and explicitSubgroupMinSize <= device.adapterInfo.subgroupMaxSize and groupThreadCount % explicitSubgroupMinSize == 0 and groupThreadCount <= device.limits.maxComputeWorkgroupSizeX and regM == tunables.groupRegM and weightBits <= 4 else 0","expertWeightElement":"\"vec4<u32>\" if expertQ4Vec4 else \"u32\""}},{"id":"quant_gemv_routed","priority":20,"when":["decodeContract"],"derive":{"decodeLanes":"tunables.decodeLanes"},"intermediates":[{"id":"routeExpert","dtype":"uint32","shape":"[numTokens * topK]"},{"id":"routeMix","dtype":"float32","shape":"[numTokens * topK]"},{"id":"hiddenAct","dtype":"float32","shape":"[hiddenChunkTokens * topK * interSize]"}],"passes":[{"id":"route_stage","name":"QMoE.RouteStage","shader":"qmoe-route-stage.wgsl.jinja","bindings":["router_probs","route_expert","route_mix","params_route"],"dispatch":{"x":"min(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","z":1}},{"id":"token_chunks","repeat":{"count":"hiddenChunkCount","index":"chunk"},"passes":[{"id":"fc1_activation_stage","name":"QMoE.FC1ActivationStageGemv","shader":"qmoe-fc1-activation-gemv.wgsl.jinja","bindings":["input","route_expert_u32","fc1_experts_weights","fc1_scales","hidden_act","params__uniform"],"dispatch":{"x":"ceilDiv(interSize, decodeRows)","y":"min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * topK"}},{"id":"output_stage","name":"QMoE.OutputStageGemv","shader":"qmoe-output-gemv.wgsl.jinja","bindings":["hidden_act_f32","route_expert_u32","route_mix_f32","fc2_experts_weights","fc2_scales","output",{"name":"params","struct":[{"name":"tokenOffset","type":"u32","value":"repeat.chunk * hiddenChunkTokens"}]}],"dispatch":{"x":"ceilDiv(hiddenSize, decodeRows)","y":"min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens)"}}]}]},{"id":"quant_split_routed","priority":10,"when":["quantContract","workgroupSizeOk","hiddenChunkFits","routedScratchFits","interSize > 0"],"intermediates":[{"id":"routeExpert","dtype":"uint32","shape":"[numTokens * topK]"},{"id":"routeMix","dtype":"float32","shape":"[numTokens * topK]"},{"id":"hiddenAct","dtype":"float32","shape":"[hiddenChunkTokens * topK * interSize]"}],"passes":[{"id":"route_stage","name":"QMoE.RouteStage","shader":"qmoe-route-stage.wgsl.jinja","bindings":["router_probs","route_expert","route_mix","params_route"],"dispatch":{"x":"min(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((numTokens * routeParallelLanes if parallelRoute else numTokens), (routeParallelLanes if parallelRoute else workgroupSize)), 65535)","z":1}},{"id":"token_chunks","repeat":{"count":"hiddenChunkCount","index":"chunk"},"passes":[{"id":"fc1_activation_stage","name":"QMoE.FC1ActivationStage","shader":"qmoe-fc1-activation-stage.wgsl.jinja","derive":{"protectDotDifference":"weightBits == 8 and activationType == \"swiglu\""},"bindings":["input","route_expert_u32","fc1_experts_weights","fc1_scales","hidden_act",{"name":"params","struct":[{"name":"activationAlpha","type":"f32","value":"attrs.activation_alpha"},{"name":"activationBeta","type":"f32","value":"attrs.activation_beta"},{"name":"tokenOffset","type":"u32","value":"repeat.chunk * hiddenChunkTokens"},{"name":"tokenCount","type":"u32","value":"min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens)"}]}],"dispatch":{"x":"min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * topK * interSize), (workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * topK * interSize), (workgroupSize)), 65535)","z":1}},{"id":"output_stage","name":"QMoE.OutputStage","shader":"qmoe-output-stage.wgsl.jinja","bindings":["hidden_act_f32","route_expert_u32","route_mix_f32","fc2_experts_weights","fc2_scales","output","params"],"dispatch":{"x":"min(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)","y":"ceilDiv(ceilDiv((min(hiddenChunkTokens, numTokens - repeat.chunk * hiddenChunkTokens) * hiddenSize), (workgroupSize)), 65535)","z":1}}]}]}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/webgpu/metadata.json CHANGED
@@ -1,38 +1 @@
1
- {
2
- "name": "com.microsoft.QMoE",
3
- "id": "_com_microsoft_qmoe_webgpu_58337b0",
4
- "version": 1,
5
- "license": "Apache-2.0",
6
- "backend": { "type": "webgpu" },
7
- "digest": {
8
- "algorithm": "sha256",
9
- "files": {
10
- "bench.json": "YuXSEWa4U+6Ek0E0ZkIeDrzqQ672IelokTilKJuKHf0=",
11
- "expert-group-slots.wgsl.jinja": "Ta+3H2FA1qRRzksdkwgKLZiO+AokmuM+B9JVN8cv1EQ=",
12
- "expert-slot-mix.wgsl.jinja": "VwX7A1f2r+lxMzG/I5r0KUpGr0Y5gW/CrI/wdwx0Ah4=",
13
- "manifest.json": "9eXT25hIM0qWJhCsJjnAodd/OgG9+nO+AvuscEpzk5U=",
14
- "qmoe-fc1-activation-gemv.wgsl.jinja": "ZYXWDSbc10LldI8RICBHK6Z/9qrrXbuYfLpVnsa0ON4=",
15
- "qmoe-fc1-activation-grouped-sgmat.wgsl.jinja": "emJWdN2BOxm610l2YstemK7OkegF96pKvhnpRSNQ5LY=",
16
- "qmoe-fc1-activation-grouped.wgsl.jinja": "TXmpZXCGJhq/T26VJpnp9OcBu14jg4oJCnAvnqY7uF4=",
17
- "qmoe-fc1-activation-stage.wgsl.jinja": "zpkM+RhDGOwHtlQBDa6k30BgDLJl2MzkCQDH1+fEFGk=",
18
- "qmoe-output-gemv.wgsl.jinja": "aB5licSktZYGWKyHBnL+K4a7ogTZCG5b0IewORHZTVs=",
19
- "qmoe-output-grouped-sgmat.wgsl.jinja": "NZocGQlY7dInufxtEwMxylKXDqspt3MyJqUftZ/M6Uk=",
20
- "qmoe-output-grouped.wgsl.jinja": "P7AAth2FTgq4p67WQpt6rWMdWs5PsAEn0HURW44wIRQ=",
21
- "qmoe-output-stage.wgsl.jinja": "x1VLEwM3N45620tcpvbRcD94PSrt/gxDUjXsYBDQJAw=",
22
- "qmoe-output-zero-inter.wgsl.jinja": "6jHYpVxU5+9WMflhwMste4v17hq7WWA1BDDS4q4DLS4=",
23
- "qmoe-route-stage.wgsl.jinja": "wi5Q1NwN1ZugT/otZryovayihC1gP6EdLO9yw1skhtc=",
24
- "test.json": "6Rt3peYHm7WQraXPO0uYfIdb8VlBXwFwgy9pAvQwiac="
25
- }
26
- },
27
- "provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },
28
- "webgpu": {
29
- "manifestSpec": "2.1",
30
- "variants": {
31
- "quant_zero_inter": ["qmoe-output-zero-inter.wgsl.jinja"],
32
- "quant_grouped_sgmat_routed": ["expert-group-slots.wgsl.jinja", "expert-slot-mix.wgsl.jinja", "qmoe-fc1-activation-grouped-sgmat.wgsl.jinja", "qmoe-output-grouped-sgmat.wgsl.jinja", "qmoe-route-stage.wgsl.jinja"],
33
- "quant_grouped_routed": ["expert-group-slots.wgsl.jinja", "expert-slot-mix.wgsl.jinja", "qmoe-fc1-activation-grouped.wgsl.jinja", "qmoe-output-grouped.wgsl.jinja", "qmoe-route-stage.wgsl.jinja"],
34
- "quant_gemv_routed": ["qmoe-fc1-activation-gemv.wgsl.jinja", "qmoe-output-gemv.wgsl.jinja", "qmoe-route-stage.wgsl.jinja"],
35
- "quant_split_routed": ["qmoe-fc1-activation-stage.wgsl.jinja", "qmoe-output-stage.wgsl.jinja", "qmoe-route-stage.wgsl.jinja"]
36
- }
37
- }
38
- }
 
1
+ {"name":"com.microsoft.QMoE","id":"_com_microsoft_qmoe_webgpu_32c9c0b","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"bench.json":"wnAtLeGmpaXAc1VMOv9TiYeAtKKvu9kH/MaNDZj8q0o=","expert-group-slots.wgsl.jinja":"Ta+3H2FA1qRRzksdkwgKLZiO+AokmuM+B9JVN8cv1EQ=","expert-slot-mix.wgsl.jinja":"lhY7Tb3YL+NnoQ9UP/M+ee8I7VVQccOVciYGDuosDeU=","manifest.json":"cQlkpFxovLpBl5b0BuXIx0uKsewUe3AdOShv7snqpX4=","qmoe-fc1-activation-gemv.wgsl.jinja":"Jw5P/Dd33B4PiHJM3hXZz9W2EwxZU/aytDiP9oi7q5o=","qmoe-fc1-activation-grouped-sgmat.wgsl.jinja":"EtoObrcFQngMRJUogR61reufzRIRp+Se8WEWTgNSP4I=","qmoe-fc1-activation-grouped.wgsl.jinja":"RG4hLr6qYQakog99GjBrekL1LDR6uPwsKJCOybW+Y2c=","qmoe-fc1-activation-stage.wgsl.jinja":"BOrH4OMis66LwRYXjQRVOd0XHUx/qYD7IykmwZMsSOI=","qmoe-output-gemv.wgsl.jinja":"b7Lo6uMRwge6UlOOFILHGMjFu56Dt4i5UNJLJeG9XpY=","qmoe-output-grouped-sgmat.wgsl.jinja":"ARwyon1EDI78dPsLOzL+ohgMWeOyxEnmci85deZN6hI=","qmoe-output-grouped.wgsl.jinja":"h8Q0CGBYDHjslzhXVkdj0PwLydXVmuQG8IJo/Qt2cjk=","qmoe-output-stage.wgsl.jinja":"SAi3qDB32vgo7sIAyqWAjW8FB1+pubP7Qrvpq3yztjg=","qmoe-output-zero-inter.wgsl.jinja":"6jHYpVxU5+9WMflhwMste4v17hq7WWA1BDDS4q4DLS4=","qmoe-route-stage.wgsl.jinja":"rd8HO8TlteGRnHwJ6GUlo+QLWukTQJw5yT16xQN6j4Y=","test.json":"ZJWb/l91I8pRWiIGSj86lUmSaYJ4kx/GV1RITU/vcug="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/webgpu/qmoe-fc1-activation-gemv.wgsl.jinja CHANGED
@@ -10,29 +10,34 @@ const TOP_K: u32 = {{ topK }}u;
10
  // reduction, which is LANES times the invocations for the same arithmetic.
11
  const LANES: u32 = {{ decodeLanes }}u;
12
  const ROWS: u32 = {{ decodeRows }}u;
 
 
 
 
 
 
13
  {% set qw = "fc1" %}
14
  {% set qwRows = "FC1_ROWS" %}
15
  {% set qwPackedCols = fc1PackedCols %}
16
  {% set qwBlocks = fc1ScaleBlocks %}
17
- // Quantized expert weights use unsigned codes offset by 2^(bits-1), so a
18
- // weight is (code - MIDPOINT) * scale. Four-bit codes are packed low-nibble
19
- // first along the reduction axis, two codes per stored word.
20
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
21
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
22
  {% if not colWiseScales %}
23
- // Block-wise scales ({{ qw }}_scales rank 3): one scale per QUANT_BLOCK columns of the reduction
24
- // axis. Column-wise scales (block_size 0) are the rank-2 single-scale-per-row case below.
25
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
26
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
27
  {% endif %}
28
 
 
 
29
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
30
  let base = expert * {{ qwRows }} + row;
31
- {% if packSize == 2 %}
32
- let word = {{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col / 2u];
33
- let code = f32((word >> ((col & 1u) * 4u)) & 15u);
34
  {% else %}
35
- let code = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col] & 255u);
36
  {% endif %}
37
  {% if not colWiseScales %}
38
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
@@ -40,17 +45,18 @@ fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
40
  return (code - MIDPOINT) * {{ qw }}_scales[base];
41
  {% endif %}
42
  }
43
- // Decode two consecutive reduction-axis codes together. Four-bit codes share a
44
- // stored word; eight-bit codes occupy adjacent words.
45
  fn {{ qw }}_weight_pair(expert: u32, row: u32, col: u32) -> vec2<f32> {
46
  let base = expert * {{ qwRows }} + row;
47
- {% if packSize == 2 %}
48
- let word = {{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col / 2u];
49
- let lo = f32(word & 15u) - MIDPOINT;
50
- let hi = f32((word >> 4u) & 15u) - MIDPOINT;
 
51
  {% else %}
52
- let lo = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col] & 255u) - MIDPOINT;
53
- let hi = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col + 1u] & 255u) - MIDPOINT;
54
  {% endif %}
55
  {% if not colWiseScales %}
56
  return vec2<f32>(lo * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK],
@@ -60,6 +66,33 @@ fn {{ qw }}_weight_pair(expert: u32, row: u32, col: u32) -> vec2<f32> {
60
  return vec2<f32>(lo * scale, hi * scale);
61
  {% endif %}
62
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  {% if activationType == "swiglu" %}
65
  fn activate(gate_in: f32, up_in: f32) -> f32 {
@@ -117,6 +150,24 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
117
  {% endif %}
118
  if (in_range) {
119
  let expert = route_expert[token * TOP_K + local_slot % TOP_K];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  // Two reduction columns per step: at 4 bits they are one stored word.
121
  for (var c = lane * 2u; c + 1u < HIDDEN; c = c + LANES * 2u) {
122
  let x0 = f32(input[token * HIDDEN + c]);
@@ -142,6 +193,7 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
142
  gate = gate + x * fc1_weight(expert, i, h);
143
  {% endif %}
144
  }
 
145
  }
146
 
147
  let slot = lid.y * LANES + lane;
 
10
  // reduction, which is LANES times the invocations for the same arithmetic.
11
  const LANES: u32 = {{ decodeLanes }}u;
12
  const ROWS: u32 = {{ decodeRows }}u;
13
+ {% if gemvVec4 %}
14
+ {% set needsWeightVec4 = true %}
15
+ {% set weightVec4Only = true %}
16
+ {% else %}
17
+ {% set needsWeightPair = true %}
18
+ {% endif %}
19
  {% set qw = "fc1" %}
20
  {% set qwRows = "FC1_ROWS" %}
21
  {% set qwPackedCols = fc1PackedCols %}
22
  {% set qwBlocks = fc1ScaleBlocks %}
23
+ // Integer codes use the implicit midpoint 2^(bits-1) and low-first packing
24
+ // along each reduction row. Tensor bytes may use widened or packed transport.
 
25
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
26
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
27
  {% if not colWiseScales %}
 
 
28
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
29
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
30
  {% endif %}
31
 
32
+ {% macro weight_byte(index) %}{{ qw }}_experts_weights[{{ index }}]{% endmacro %}
33
+ {% if weightVec4Only is not defined %}
34
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
35
  let base = expert * {{ qwRows }} + row;
36
+ {% if packSize > 1 %}
37
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / " ~ packSize ~ "u") }};
38
+ let code = f32((word >> ((col % {{ packSize }}u) * {{ weightBits }}u)) & {{ 2 ** weightBits - 1 }}u);
39
  {% else %}
40
+ let code = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col") }} & 255u);
41
  {% endif %}
42
  {% if not colWiseScales %}
43
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
45
  return (code - MIDPOINT) * {{ qw }}_scales[base];
46
  {% endif %}
47
  }
48
+ {% endif %}
49
+ {% if needsWeightPair is defined %}
50
  fn {{ qw }}_weight_pair(expert: u32, row: u32, col: u32) -> vec2<f32> {
51
  let base = expert * {{ qwRows }} + row;
52
+ {% if packSize > 1 %}
53
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / " ~ packSize ~ "u") }};
54
+ let shift = (col % {{ packSize }}u) * {{ weightBits }}u;
55
+ let lo = f32((word >> shift) & {{ 2 ** weightBits - 1 }}u) - MIDPOINT;
56
+ let hi = f32((word >> (shift + {{ weightBits }}u)) & {{ 2 ** weightBits - 1 }}u) - MIDPOINT;
57
  {% else %}
58
+ let lo = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col") }} & 255u) - MIDPOINT;
59
+ let hi = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col + 1u") }} & 255u) - MIDPOINT;
60
  {% endif %}
61
  {% if not colWiseScales %}
62
  return vec2<f32>(lo * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK],
 
66
  return vec2<f32>(lo * scale, hi * scale);
67
  {% endif %}
68
  }
69
+ {% endif %}
70
+ {% if needsWeightVec4 is defined %}
71
+ // Aligned four-code groups share a scale: block sizes are multiples of sixteen.
72
+ fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
73
+ let base = expert * {{ qwRows }} + row;
74
+ {% if packSize == 4 %}
75
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / 4u") }};
76
+ let codes = vec4<f32>((vec4<u32>(word) >> vec4<u32>(0u, 2u, 4u, 6u)) & vec4<u32>(3u));
77
+ {% elif packSize == 2 %}
78
+ let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
79
+ let w0 = {{ weight_byte("pair") }};
80
+ let w1 = {{ weight_byte("pair + 1u") }};
81
+ let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
82
+ f32(w1 & 15u), f32((w1 >> 4u) & 15u));
83
+ {% else %}
84
+ let word = base * {{ qw | upper }}_PACKED_COLS + col;
85
+ let codes = vec4<f32>(f32({{ weight_byte("word") }} & 255u), f32({{ weight_byte("word + 1u") }} & 255u),
86
+ f32({{ weight_byte("word + 2u") }} & 255u), f32({{ weight_byte("word + 3u") }} & 255u));
87
+ {% endif %}
88
+ {% if not colWiseScales %}
89
+ let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
90
+ {% else %}
91
+ let scale = {{ qw }}_scales[base];
92
+ {% endif %}
93
+ return (codes - vec4<f32>(MIDPOINT)) * scale;
94
+ }
95
+ {% endif %}
96
 
97
  {% if activationType == "swiglu" %}
98
  fn activate(gate_in: f32, up_in: f32) -> f32 {
 
150
  {% endif %}
151
  if (in_range) {
152
  let expert = route_expert[token * TOP_K + local_slot % TOP_K];
153
+ {% if gemvVec4 %}
154
+ for (var c = lane * 4u; c + 3u < HIDDEN; c = c + LANES * 4u) {
155
+ let x = vec4<f32>(
156
+ {% for v in range(4) %}
157
+ f32(input[token * HIDDEN + c + {{ v }}u]){{ ',' if v < 3 else '' }}
158
+ {% endfor %}
159
+ );
160
+ {% if activationType == "swiglu" %}
161
+ let g = fc1_weight_vec4(expert, i * 2u, c);
162
+ let u = fc1_weight_vec4(expert, i * 2u + 1u, c);
163
+ gate = gate + x.x * g.x + x.y * g.y + x.z * g.z + x.w * g.w;
164
+ up = up + x.x * u.x + x.y * u.y + x.z * u.z + x.w * u.w;
165
+ {% else %}
166
+ let g = fc1_weight_vec4(expert, i, c);
167
+ gate = gate + x.x * g.x + x.y * g.y + x.z * g.z + x.w * g.w;
168
+ {% endif %}
169
+ }
170
+ {% else %}
171
  // Two reduction columns per step: at 4 bits they are one stored word.
172
  for (var c = lane * 2u; c + 1u < HIDDEN; c = c + LANES * 2u) {
173
  let x0 = f32(input[token * HIDDEN + c]);
 
193
  gate = gate + x * fc1_weight(expert, i, h);
194
  {% endif %}
195
  }
196
+ {% endif %}
197
  }
198
 
199
  let slot = lid.y * LANES + lane;
build/webgpu/qmoe-fc1-activation-grouped-sgmat.wgsl.jinja CHANGED
@@ -30,33 +30,32 @@ const FUSION: u32 = {{ 2 if isSwiglu else 1 }}u;
30
  {% set qwRows = "FC1_ROWS" %}
31
  {% set qwPackedCols = fc1PackedCols %}
32
  {% set qwBlocks = fc1ScaleBlocks %}
33
- // Quantized expert weights use unsigned codes offset by 2^(bits-1), so a
34
- // weight is (code - MIDPOINT) * scale. Four-bit codes are packed low-nibble
35
- // first along the reduction axis, two codes per stored word.
36
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
37
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
38
  {% if not colWiseScales %}
39
- // Block-wise scales ({{ qw }}_scales rank 3): one scale per QUANT_BLOCK columns of the reduction
40
- // axis. Column-wise scales (block_size 0) are the rank-2 single-scale-per-row case below.
41
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
42
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
43
  {% endif %}
44
 
45
- // Decode the four-code group consumed by the staging loop. The aligned codes
46
- // share one quantization scale: blocks are powers of two of at least 16, and
47
- // this helper requires `col` to be a multiple of four.
48
  fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
49
  let base = expert * {{ qwRows }} + row;
50
- {% if packSize == 2 %}
 
 
 
51
  let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
52
- let w0 = {{ qw }}_experts_weights[pair];
53
- let w1 = {{ qw }}_experts_weights[pair + 1u];
54
  let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
55
  f32(w1 & 15u), f32((w1 >> 4u) & 15u));
56
  {% else %}
57
  let word = base * {{ qw | upper }}_PACKED_COLS + col;
58
- let codes = vec4<f32>(f32({{ qw }}_experts_weights[word] & 255u), f32({{ qw }}_experts_weights[word + 1u] & 255u),
59
- f32({{ qw }}_experts_weights[word + 2u] & 255u), f32({{ qw }}_experts_weights[word + 3u] & 255u));
60
  {% endif %}
61
  {% if not colWiseScales %}
62
  let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
@@ -126,13 +125,77 @@ fn loadSHMB(expert: u32, weight_base: u32, k_idx: u32, row: u32, c_idx: u32) {
126
  }
127
  }
128
 
129
- @compute @workgroup_size({{ sgmatWorkgroup }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
130
- fn main(
131
- @builtin(workgroup_id) wid: vec3<u32>,
132
- @builtin(local_invocation_index) local_idx: u32,
133
- @builtin(subgroup_invocation_id) sg_id: u32,
134
- @builtin(subgroup_size) sg_size: u32
135
- ) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  let tile = wid.x;
137
  if (tile >= tile_meta[0]) {
138
  return;
@@ -144,7 +207,7 @@ fn main(
144
 
145
  let a_slot = select(0u, slot_list[slice_base + local_idx / 4u], local_idx / 4u < rows);
146
 
147
- let subtile_id = local_idx / sg_size;
148
  let subtile_idx = subtile_id / {{ sgmatRowSubtiles }}u;
149
  let subtile_idy = subtile_id % {{ sgmatRowSubtiles }}u;
150
  let base_A = subtile_idy * SUB_ROWS;
@@ -152,7 +215,7 @@ fn main(
152
 
153
  {% for row in [0, 1] %}
154
  {% for col in [0, 1, 2, 3] %}
155
- var matC{{ row }}{{ col }}: subgroup_matrix_result<f32, 8, 8>;
156
  {% endfor %}
157
  {% endfor %}
158
 
@@ -166,22 +229,23 @@ fn main(
166
  {% set directInputs = false %}
167
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
168
  {% for r in range(2) %}
169
- 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" }});
170
  {% endfor %}
171
 
 
172
  let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
173
  {% for c in range(4) %}
174
- 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" }});
175
  {% endfor %}
176
 
177
- matC00 = subgroupMatrixMultiplyAccumulate(matA0, matB0, matC00);
178
- matC01 = subgroupMatrixMultiplyAccumulate(matA0, matB1, matC01);
179
- matC02 = subgroupMatrixMultiplyAccumulate(matA0, matB2, matC02);
180
- matC03 = subgroupMatrixMultiplyAccumulate(matA0, matB3, matC03);
181
- matC10 = subgroupMatrixMultiplyAccumulate(matA1, matB0, matC10);
182
- matC11 = subgroupMatrixMultiplyAccumulate(matA1, matB1, matC11);
183
- matC12 = subgroupMatrixMultiplyAccumulate(matA1, matB2, matC12);
184
- matC13 = subgroupMatrixMultiplyAccumulate(matA1, matB3, matC13);
185
  }
186
  workgroupBarrier();
187
  }
@@ -197,7 +261,7 @@ fn main(
197
  // The scratch banks are shared by both row groups, so the readback is fenced on both
198
  // sides of each collective store.
199
  {% for c in [0, 1, 2, 3] %}
200
- subgroupMatrixStore<row_major>(&tile_A, (subtile_id * 4u + {{ c }}u) * 64u, matC{{ group }}{{ c }}, 8u);
201
  {% endfor %}
202
  workgroupBarrier();
203
  {
@@ -228,4 +292,27 @@ fn main(
228
  }
229
  workgroupBarrier();
230
  {% endfor %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  }
 
30
  {% set qwRows = "FC1_ROWS" %}
31
  {% set qwPackedCols = fc1PackedCols %}
32
  {% set qwBlocks = fc1ScaleBlocks %}
33
+ // Integer codes use the implicit midpoint 2^(bits-1) and low-first packing
34
+ // along each reduction row. Tensor bytes may use widened or packed transport.
 
35
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
36
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
37
  {% if not colWiseScales %}
 
 
38
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
39
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
40
  {% endif %}
41
 
42
+ {% macro weight_byte(index) %}{{ qw }}_experts_weights[{{ index }}]{% endmacro %}
43
+ // Aligned four-code groups share a scale: block sizes are multiples of sixteen.
 
44
  fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
45
  let base = expert * {{ qwRows }} + row;
46
+ {% if packSize == 4 %}
47
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / 4u") }};
48
+ let codes = vec4<f32>((vec4<u32>(word) >> vec4<u32>(0u, 2u, 4u, 6u)) & vec4<u32>(3u));
49
+ {% elif packSize == 2 %}
50
  let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
51
+ let w0 = {{ weight_byte("pair") }};
52
+ let w1 = {{ weight_byte("pair + 1u") }};
53
  let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
54
  f32(w1 & 15u), f32((w1 >> 4u) & 15u));
55
  {% else %}
56
  let word = base * {{ qw | upper }}_PACKED_COLS + col;
57
+ let codes = vec4<f32>(f32({{ weight_byte("word") }} & 255u), f32({{ weight_byte("word + 1u") }} & 255u),
58
+ f32({{ weight_byte("word + 2u") }} & 255u), f32({{ weight_byte("word + 3u") }} & 255u));
59
  {% endif %}
60
  {% if not colWiseScales %}
61
  let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
125
  }
126
  }
127
 
128
+ {% set accScalar = "f32" %}
129
+ // A subgroup owns one matrix tile only after its actual population and the
130
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
131
+ // the role; local invocation IDs only publish the workgroup-wide decision.
132
+ var<workgroup> matrixRoleCount: atomic<u32>;
133
+ var<workgroup> matrixRejected: atomic<u32>;
134
+ var<workgroup> matrixAccepted: u32;
135
+
136
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
137
+ // WGSL initializes workgroup variables to zero before this entry point.
138
+ let population = subgroupBallot(true);
139
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
140
+ + countOneBits(population.z) + countOneBits(population.w);
141
+ var claimed = 0u;
142
+ if (subgroupElect()) {
143
+ claimed = atomicAdd(&matrixRoleCount, 1u);
144
+ if (width != requiredWidth || populationCount != requiredWidth) {
145
+ atomicStore(&matrixRejected, 1u);
146
+ }
147
+ }
148
+ // Reconverge every invocation before broadcasting the elected claim.
149
+ workgroupBarrier();
150
+ return subgroupBroadcastFirst(claimed);
151
+ }
152
+
153
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
154
+ if (localIndex == 0u) {
155
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
156
+ && atomicLoad(&matrixRoleCount) == bankCount);
157
+ }
158
+ // The uniform load both publishes the leader's decision and gives the
159
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
160
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
161
+ }
162
+ // The portable arm owns two result components per logical 32-invocation group.
163
+ // Staging casts, 8-wide K steps, barriers and the epilogue match the
164
+ // subgroup-matrix arm.
165
+ var<private> matrixSoftwareLane: u32;
166
+
167
+ fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,
168
+ acc: vec2<f32>) -> vec2<f32> {
169
+ var value = acc;
170
+ for (var k = 0u; k < 8u; k += 1u) {
171
+ value = fma(vec2<f32>(lhs[k]), rhs[k], value);
172
+ }
173
+ return value;
174
+ }
175
+
176
+ {% 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 %}
177
+
178
+ {% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}
179
+ {% if kind == "left" %}array<f32, 8>(
180
+ {% 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 "" }}
181
+ {% endfor %})
182
+ {% else %}array<vec2<f32>, 8>(
183
+ {% for k in range(8) %}vec2<f32>(
184
+ {% 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 "" }}
185
+ {% endfor %}){{ "," if k < 7 else "" }}
186
+ {% endfor %})
187
+ {% endif %}{% endif %}{% endmacro %}
188
+
189
+ {% 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 %}
190
+
191
+ {% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{
192
+ let matrixPointer = {{ pointer }};
193
+ let matrixValue = {{ value }};
194
+ {% 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" }};
195
+ {% endfor %}}{% endif %}{% endmacro %}
196
+
197
+ {% macro matrixKernelBody(matrixSoftware) %}
198
+
199
  let tile = wid.x;
200
  if (tile >= tile_meta[0]) {
201
  return;
 
207
 
208
  let a_slot = select(0u, slot_list[slice_base + local_idx / 4u], local_idx / 4u < rows);
209
 
210
+ let subtile_id = matrixRole;
211
  let subtile_idx = subtile_id / {{ sgmatRowSubtiles }}u;
212
  let subtile_idy = subtile_id % {{ sgmatRowSubtiles }}u;
213
  let base_A = subtile_idy * SUB_ROWS;
 
215
 
216
  {% for row in [0, 1] %}
217
  {% for col in [0, 1, 2, 3] %}
218
+ var matC{{ row }}{{ col }}: {{ matrixType(matrixSoftware, "result", "f32") }};
219
  {% endfor %}
220
  {% endfor %}
221
 
 
229
  {% set directInputs = false %}
230
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
231
  {% for r in range(2) %}
232
+ 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") }};
233
  {% endfor %}
234
 
235
+ {% set storageB = "" %}
236
  let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
237
  {% for c in range(4) %}
238
+ 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") }};
239
  {% endfor %}
240
 
241
+ matC00 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB0", "matC00") }};
242
+ matC01 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB1", "matC01") }};
243
+ matC02 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB2", "matC02") }};
244
+ matC03 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB3", "matC03") }};
245
+ matC10 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB0", "matC10") }};
246
+ matC11 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB1", "matC11") }};
247
+ matC12 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB2", "matC12") }};
248
+ matC13 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB3", "matC13") }};
249
  }
250
  workgroupBarrier();
251
  }
 
261
  // The scratch banks are shared by both row groups, so the readback is fenced on both
262
  // sides of each collective store.
263
  {% for c in [0, 1, 2, 3] %}
264
+ {{ matrixStore(matrixSoftware, "row_major", "&tile_A", "(subtile_id * 4u + " ~ (c) ~ "u) * 64u", "matC" ~ (group) ~ (c), "8u") }}
265
  {% endfor %}
266
  workgroupBarrier();
267
  {
 
292
  }
293
  workgroupBarrier();
294
  {% endfor %}
295
+
296
+ {% endmacro %}
297
+ {% macro matrix_topology_dispatch(groupSize, withSubgroupLane) %}
298
+ let matrixRole = claimMatrixSubgroupRole(matrixPhysicalWidth, 32u);
299
+ let matrixAcceptedHere = matrixTopologyAccepted(local_idx, {{ groupSize }} / 32u);
300
+ matrixSoftwareLane = local_idx % 32u;
301
+ if (matrixAcceptedHere) {
302
+ let sg_id = matrixPhysicalLane;
303
+ {{ matrixKernelBody(false) }}
304
+ } else {
305
+ let matrixRole = local_idx / 32u;
306
+ let sg_id = local_idx % 32u;
307
+ {{ matrixKernelBody(true) }}
308
+ }
309
+ {%- endmacro -%}
310
+ @compute @workgroup_size({{ sgmatWorkgroup }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
311
+ fn main(
312
+ @builtin(workgroup_id) wid: vec3<u32>,
313
+ @builtin(local_invocation_index) local_idx: u32,
314
+ @builtin(subgroup_size) matrixPhysicalWidth: u32,
315
+ @builtin(subgroup_invocation_id) matrixPhysicalLane: u32
316
+ ) {
317
+ {{ matrix_topology_dispatch(sgmatWorkgroup ~ "u", true) }}
318
  }
build/webgpu/qmoe-fc1-activation-grouped.wgsl.jinja CHANGED
@@ -1,3 +1,7 @@
 
 
 
 
1
  {{ env.wgsl.resourceDeclarations }}
2
 
3
  // com.microsoft.QMoE, expert-grouped FC1 + activation stage.
@@ -15,29 +19,30 @@ const THREADS_SIDE: u32 = {{ groupThreads }}u;
15
  const THREADS: u32 = THREADS_SIDE * THREADS_SIDE;
16
  {% set isSwiglu = activationType == "swiglu" %}
17
  {% set primaryRow = "col * 2u" if isSwiglu else "col" %}
 
 
18
  {% set qw = "fc1" %}
19
  {% set qwRows = "FC1_ROWS" %}
20
  {% set qwPackedCols = fc1PackedCols %}
21
  {% set qwBlocks = fc1ScaleBlocks %}
22
- // Quantized expert weights use unsigned codes offset by 2^(bits-1), so a
23
- // weight is (code - MIDPOINT) * scale. Four-bit codes are packed low-nibble
24
- // first along the reduction axis, two codes per stored word.
25
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
26
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
27
  {% if not colWiseScales %}
28
- // Block-wise scales ({{ qw }}_scales rank 3): one scale per QUANT_BLOCK columns of the reduction
29
- // axis. Column-wise scales (block_size 0) are the rank-2 single-scale-per-row case below.
30
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
31
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
32
  {% endif %}
33
 
 
 
34
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
35
  let base = expert * {{ qwRows }} + row;
36
- {% if packSize == 2 %}
37
- let word = {{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col / 2u];
38
- let code = f32((word >> ((col & 1u) * 4u)) & 15u);
39
  {% else %}
40
- let code = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col] & 255u);
41
  {% endif %}
42
  {% if not colWiseScales %}
43
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
@@ -45,21 +50,27 @@ fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
45
  return (code - MIDPOINT) * {{ qw }}_scales[base];
46
  {% endif %}
47
  }
48
- // Decode the four-code group consumed by the staging loop. The aligned codes
49
- // share one quantization scale: blocks are powers of two of at least 16, and
50
- // this helper requires `col` to be a multiple of four.
51
  fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
52
  let base = expert * {{ qwRows }} + row;
53
- {% if packSize == 2 %}
 
 
 
54
  let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
55
- let w0 = {{ qw }}_experts_weights[pair];
56
- let w1 = {{ qw }}_experts_weights[pair + 1u];
57
  let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
58
  f32(w1 & 15u), f32((w1 >> 4u) & 15u));
59
  {% else %}
60
  let word = base * {{ qw | upper }}_PACKED_COLS + col;
61
- let codes = vec4<f32>(f32({{ qw }}_experts_weights[word] & 255u), f32({{ qw }}_experts_weights[word + 1u] & 255u),
62
- f32({{ qw }}_experts_weights[word + 2u] & 255u), f32({{ qw }}_experts_weights[word + 3u] & 255u));
 
 
 
 
63
  {% endif %}
64
  {% if not colWiseScales %}
65
  let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
@@ -68,6 +79,7 @@ fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
68
  {% endif %}
69
  return (codes - vec4<f32>(MIDPOINT)) * scale;
70
  }
 
71
 
72
  {% if activationType == "swiglu" %}
73
  fn activate(gate_in: f32, up_in: f32) -> f32 {
@@ -89,7 +101,12 @@ fn activate(value: f32) -> f32 {
89
  {% endif %}
90
 
91
  const KVEC: u32 = {{ groupTileKVec }}u;
92
- {% macro stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, guarded, bLoadVec4="", b2LoadVec4="", aLoadVec4="") %}
 
 
 
 
 
93
  for (var idx = tid; idx < MTILE * KVEC; idx = idx + THREADS) {
94
  let m = idx / KVEC;
95
  let kb = (idx % KVEC) * 4u;
@@ -106,9 +123,51 @@ const KVEC: u32 = {{ groupTileKVec }}u;
106
  {% endif %}
107
  a_tile[idx] = a_vec;
108
  }
109
- for (var idx = tid; idx < NTILE * KVEC; idx = idx + THREADS) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  let n = idx / KVEC;
111
  let kb = (idx % KVEC) * 4u;
 
112
  let col = n_base + n;
113
  {% if guarded %}
114
  let col_live = col < {{ nExtent }};
@@ -136,19 +195,22 @@ const KVEC: u32 = {{ groupTileKVec }}u;
136
  }
137
  {% endfor %}
138
  {% endif %}
139
- b_tile[idx] = b_vec;
140
  {% if b2Load %}
141
- b2_tile[idx] = b2_vec;
142
  {% endif %}
143
- }{% endmacro %}
144
 
145
- {% macro group_tile_loop(aLoad, bLoad, b2Load, kExtent, nExtent, regM, regN, bLoadVec4="", b2LoadVec4="", aLoadVec4="") %}
146
  {% for r in range(regM) %}
147
  {% for c in range(regN) %}
148
  var acc_{{ r }}_{{ c }} = 0.0;
149
  {% if b2Load %}
150
  var acc2_{{ r }}_{{ c }} = 0.0;
151
  {% endif %}
 
 
 
152
  {% endfor %}
153
  {% endfor %}
154
 
@@ -165,32 +227,67 @@ const KVEC: u32 = {{ groupTileKVec }}u;
165
  break;
166
  }
167
  if (n_full && k_base + KTILE <= {{ kExtent }}) {
168
- {{ stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, false, bLoadVec4, b2LoadVec4, aLoadVec4) }}
169
  } else {
170
- {{ stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, true) }}
171
  }
172
  workgroupBarrier();
173
 
 
 
 
 
 
 
 
 
 
174
  for (var kv = 0u; kv < KVEC; kv = kv + 1u) {
 
175
  {% for r in range(regM) %}
176
  let a{{ r }} = a_tile[(lid.y * {{ regM }}u + {{ r }}u) * KVEC + kv];
177
  {% endfor %}
178
- {% for c in range(regN) %}
179
- let b{{ c }} = b_tile[(lid.x * {{ regN }}u + {{ c }}u) * KVEC + kv];
 
 
 
 
 
180
  {% if b2Load %}
181
- let s{{ c }} = b2_tile[(lid.x * {{ regN }}u + {{ c }}u) * KVEC + kv];
182
  {% endif %}
183
  {% endfor %}
184
  {% for r in range(regM) %}
185
  {% for c in range(regN) %}
186
- acc_{{ r }}_{{ c }} = acc_{{ r }}_{{ c }} + dot(a{{ r }}, b{{ c }});
 
 
 
 
 
 
187
  {% if b2Load %}
188
- acc2_{{ r }}_{{ c }} = acc2_{{ r }}_{{ c }} + dot(a{{ r }}, s{{ c }});
 
 
 
 
 
 
189
  {% endif %}
190
  {% endfor %}
191
  {% endfor %}
192
  }
193
- // Orders this step's tile reads before the next step overwrites them.
 
 
 
 
 
 
 
 
194
  workgroupBarrier();
195
  k_base = k_base + KTILE;
196
  }{% endmacro %}
@@ -201,9 +298,18 @@ var<workgroup> b_tile: array<vec4<f32>, {{ groupTileN * groupTileKVec }}>;
201
  var<workgroup> b2_tile: array<vec4<f32>, {{ groupTileN * groupTileKVec }}>;
202
  {% endif %}
203
 
 
 
 
 
 
 
 
 
204
  @compute @workgroup_size(THREADS_SIDE, THREADS_SIDE, 1)
205
  fn main(@builtin(workgroup_id) wid: vec3<u32>,
206
  @builtin(local_invocation_id) lid: vec3<u32>) {
 
207
  let tile = wid.x;
208
  if (tile >= tile_meta[0]) {
209
  return;
@@ -224,7 +330,7 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
224
  "fc1_weight(expert, col * 2u + 1u, k_base + k)" if isSwiglu else "",
225
  "HIDDEN", "INTER", regM, regN,
226
  "fc1_weight_vec4(expert, " ~ primaryRow ~ ", k_base + kb)",
227
- "fc1_weight_vec4(expert, col * 2u + 1u, k_base + kb)" if isSwiglu else "") }}
228
 
229
  {% for r in range(regM) %}
230
  {% for c in range(regN) %}
 
1
+ {% if qmoeGroupedPin > 0 %}
2
+ enable subgroups;
3
+ enable subgroup_size_control;
4
+ {% endif %}
5
  {{ env.wgsl.resourceDeclarations }}
6
 
7
  // com.microsoft.QMoE, expert-grouped FC1 + activation stage.
 
19
  const THREADS: u32 = THREADS_SIDE * THREADS_SIDE;
20
  {% set isSwiglu = activationType == "swiglu" %}
21
  {% set primaryRow = "col * 2u" if isSwiglu else "col" %}
22
+ {% if not expertQ4Vec4 or not groupWeightKMajor or not (groupWeightLaneInterleaved | default(false)) %}{% set needsWeightVec4 = true %}{% endif %}
23
+ {% set vectorWeights = weightVectorTransport | default(false) %}
24
  {% set qw = "fc1" %}
25
  {% set qwRows = "FC1_ROWS" %}
26
  {% set qwPackedCols = fc1PackedCols %}
27
  {% set qwBlocks = fc1ScaleBlocks %}
28
+ // Integer codes use the implicit midpoint 2^(bits-1) and low-first packing
29
+ // along each reduction row. Tensor bytes may use widened or packed transport.
 
30
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
31
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
32
  {% if not colWiseScales %}
 
 
33
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
34
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
35
  {% endif %}
36
 
37
+ {% set vectorWeights = vectorWeights is defined and vectorWeights %}
38
+ {% macro weight_byte(index) %}{% if vectorWeights %}{{ qw }}_experts_weights[({{ index }}) / 4u][({{ index }}) & 3u]{% else %}{{ qw }}_experts_weights[{{ index }}]{% endif %}{% endmacro %}
39
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
40
  let base = expert * {{ qwRows }} + row;
41
+ {% if packSize > 1 %}
42
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / " ~ packSize ~ "u") }};
43
+ let code = f32((word >> ((col % {{ packSize }}u) * {{ weightBits }}u)) & {{ 2 ** weightBits - 1 }}u);
44
  {% else %}
45
+ let code = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col") }} & 255u);
46
  {% endif %}
47
  {% if not colWiseScales %}
48
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
50
  return (code - MIDPOINT) * {{ qw }}_scales[base];
51
  {% endif %}
52
  }
53
+ {% if needsWeightVec4 is defined %}
54
+ // Aligned four-code groups share a scale: block sizes are multiples of sixteen.
 
55
  fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
56
  let base = expert * {{ qwRows }} + row;
57
+ {% if packSize == 4 %}
58
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / 4u") }};
59
+ let codes = vec4<f32>((vec4<u32>(word) >> vec4<u32>(0u, 2u, 4u, 6u)) & vec4<u32>(3u));
60
+ {% elif packSize == 2 %}
61
  let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
62
+ let w0 = {{ weight_byte("pair") }};
63
+ let w1 = {{ weight_byte("pair + 1u") }};
64
  let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
65
  f32(w1 & 15u), f32((w1 >> 4u) & 15u));
66
  {% else %}
67
  let word = base * {{ qw | upper }}_PACKED_COLS + col;
68
+ {% if vectorWeights %}
69
+ let codes = vec4<f32>({{ qw }}_experts_weights[word / 4u] & vec4<u32>(255u));
70
+ {% else %}
71
+ let codes = vec4<f32>(f32({{ weight_byte("word") }} & 255u), f32({{ weight_byte("word + 1u") }} & 255u),
72
+ f32({{ weight_byte("word + 2u") }} & 255u), f32({{ weight_byte("word + 3u") }} & 255u));
73
+ {% endif %}
74
  {% endif %}
75
  {% if not colWiseScales %}
76
  let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
79
  {% endif %}
80
  return (codes - vec4<f32>(MIDPOINT)) * scale;
81
  }
82
+ {% endif %}
83
 
84
  {% if activationType == "swiglu" %}
85
  fn activate(gate_in: f32, up_in: f32) -> f32 {
 
101
  {% endif %}
102
 
103
  const KVEC: u32 = {{ groupTileKVec }}u;
104
+ {% macro stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, guarded, bLoadVec4="", b2LoadVec4="", aLoadVec4="", bKMajor=false, bLaneInterleaved=false, regN=1, staticK=false, bStageInterleaved=false, packedStreams=[]) %}{% set bStoreIndex =
105
+ "idx" if bStageInterleaved and bKMajor and bLaneInterleaved else
106
+ ("(idx % KVEC) * NTILE + n / " ~ regN ~ "u + (n % " ~ regN ~ "u) * " ~ ((groupTileN / regN) | int) ~ "u")
107
+ if bKMajor and bLaneInterleaved and regN > 1
108
+ else ("(idx % KVEC) * NTILE + idx / KVEC" if bKMajor else "idx")
109
+ %}
110
  for (var idx = tid; idx < MTILE * KVEC; idx = idx + THREADS) {
111
  let m = idx / KVEC;
112
  let kb = (idx % KVEC) * 4u;
 
123
  {% endif %}
124
  a_tile[idx] = a_vec;
125
  }
126
+ {% if packedStreams and not guarded and bKMajor and bLaneInterleaved %}
127
+ // Stage columns in shared-memory lane order for contiguous constant-K stores.
128
+ for (var slot = tid; slot < NTILE; slot = slot + THREADS) {
129
+ let local_col = (slot % THREADS_SIDE) * {{ regN }}u + slot / THREADS_SIDE;
130
+ let col = n_base + local_col;
131
+ {% if packedStreams[0].packing == "word32" %}
132
+ {% for stream in packedStreams %}
133
+ let {{ stream.prefix }}_packed = {{ stream.buffer }}[col * ({{ kExtent }} / 32u) + k_base / 32u];
134
+ let {{ stream.prefix }}_scale = f32({{ stream.scales }}[col * {{ stream.scaleBlocks }} + k_base / {{ stream.quantBlock }}]);
135
+ {% endfor %}
136
+ {% for chunk in range(8) %}
137
+ {% for stream in packedStreams %}
138
+ let {{ stream.prefix }}_word{{ chunk }} = {{ stream.prefix }}_packed[{{ (chunk / 2) | int }}] >> {{ (chunk % 2) * 16 }}u;
139
+ let {{ stream.prefix }}_values{{ chunk }} = (vec4<f32>((vec4<u32>({{ stream.prefix }}_word{{ chunk }}) >> vec4<u32>(0u, 4u, 8u, 12u)) & vec4<u32>({{ stream.mask }})) - vec4<f32>({{ stream.zero }})) * {{ stream.prefix }}_scale;
140
+ {{ stream.destination }}[{{ chunk }}u * NTILE + slot] = {{ stream.prefix }}_values{{ chunk }};
141
+ {% endfor %}
142
+ {% endfor %}
143
+ {% else %}
144
+ {% for block in range(groupTileK // 8) %}
145
+ {% for stream in packedStreams %}
146
+ let {{ stream.prefix }}_row{{ block }} = expert * {{ stream.rows }} + {{ stream.row }};
147
+ let {{ stream.prefix }}_packed{{ block }} = {{ stream.buffer }}[{{ stream.prefix }}_row{{ block }} * {{ stream.packedCols // 4 }}u + (k_base + {{ block * 8 }}u) / 8u];
148
+ let {{ stream.prefix }}_scale{{ block }} = {{ stream.scales }}[{{ stream.prefix }}_row{{ block }}{% if not stream.columnScales %} * {{ stream.scaleBlocks }}u + (k_base + {{ block * 8 }}u) / {{ stream.quantBlock }}{% endif %}];
149
+ {% for chunk in range(2) %}
150
+ {% if stream.packing == "word8" %}
151
+ let {{ stream.prefix }}_codes{{ block }}_{{ chunk }} = (vec4<u32>({{ stream.prefix }}_packed{{ block }}) >> vec4<u32>({{ chunk * 16 }}u, {{ chunk * 16 + 4 }}u, {{ chunk * 16 + 8 }}u, {{ chunk * 16 + 12 }}u)) & vec4<u32>(15u);
152
+ {% else %}
153
+ let {{ stream.prefix }}_bytes{{ block }}_{{ chunk }} = {{ stream.prefix }}_packed{{ block }}.{{ 'xy' if chunk == 0 else 'zw' }};
154
+ let {{ stream.prefix }}_codes{{ block }}_{{ chunk }} = vec4<u32>({{ stream.prefix }}_bytes{{ block }}_{{ chunk }}.x, {{ stream.prefix }}_bytes{{ block }}_{{ chunk }}.x >> 4u, {{ stream.prefix }}_bytes{{ block }}_{{ chunk }}.y, {{ stream.prefix }}_bytes{{ block }}_{{ chunk }}.y >> 4u) & vec4<u32>(15u);
155
+ {% endif %}
156
+ {{ stream.destination }}[{{ block * 2 + chunk }}u * NTILE + slot] = (vec4<f32>({{ stream.prefix }}_codes{{ block }}_{{ chunk }}) - vec4<f32>({{ stream.zero }})) * {{ stream.prefix }}_scale{{ block }};
157
+ {% endfor %}
158
+ {% endfor %}
159
+ {% endfor %}
160
+ {% endif %}
161
+ }
162
+ {% else %} for (var idx = tid; idx < NTILE * KVEC; idx = idx + THREADS) {
163
+ {% if bStageInterleaved and bKMajor and bLaneInterleaved %}
164
+ let slot = idx % NTILE;
165
+ let n = (slot % THREADS_SIDE) * {{ regN }}u + slot / THREADS_SIDE;
166
+ let kb = (idx / NTILE) * 4u;
167
+ {% else %}
168
  let n = idx / KVEC;
169
  let kb = (idx % KVEC) * 4u;
170
+ {% endif %}
171
  let col = n_base + n;
172
  {% if guarded %}
173
  let col_live = col < {{ nExtent }};
 
195
  }
196
  {% endfor %}
197
  {% endif %}
198
+ b_tile[{{ bStoreIndex }}] = b_vec;
199
  {% if b2Load %}
200
+ b2_tile[{{ bStoreIndex }}] = b2_vec;
201
  {% endif %}
202
+ }{% endif %}{% endmacro %}
203
 
204
+ {% macro group_tile_loop(aLoad, bLoad, b2Load, kExtent, nExtent, regM, regN, bLoadVec4="", b2LoadVec4="", aLoadVec4="", scalarFma=false, bKMajor=false, bLaneInterleaved=false, staticK=false, bStageInterleaved=false, packedStreams=[], foldStage=false, refinePair=false) %}{% set foldStage = foldStage or refinePair %}{% set accum2 = "chunk2" if refinePair else "acc2" %}{% set accum = "chunk" if foldStage else "acc" %}
205
  {% for r in range(regM) %}
206
  {% for c in range(regN) %}
207
  var acc_{{ r }}_{{ c }} = 0.0;
208
  {% if b2Load %}
209
  var acc2_{{ r }}_{{ c }} = 0.0;
210
  {% endif %}
211
+ {% if refinePair %}{% for stream in ["", "2"] %}
212
+ var mass{{ stream }}_{{ r }}_{{ c }} = 0.0;
213
+ {% endfor %}{% endif %}
214
  {% endfor %}
215
  {% endfor %}
216
 
 
227
  break;
228
  }
229
  if (n_full && k_base + KTILE <= {{ kExtent }}) {
230
+ {{ stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, false, bLoadVec4, b2LoadVec4, aLoadVec4, bKMajor, bLaneInterleaved, regN, staticK, bStageInterleaved, packedStreams) }}
231
  } else {
232
+ {{ stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, true, bKMajor=bKMajor, bLaneInterleaved=bLaneInterleaved, regN=regN, staticK=staticK, bStageInterleaved=bStageInterleaved, packedStreams=packedStreams) }}
233
  }
234
  workgroupBarrier();
235
 
236
+ {% if foldStage %}{% for r in range(regM) %}{% for c in range(regN) %}
237
+ var chunk_{{ r }}_{{ c }} = 0.0;
238
+ {% if refinePair %} var chunk2_{{ r }}_{{ c }} = 0.0;
239
+ {% endif %}
240
+ {% endfor %}{% endfor %}{% endif %}{% for staticKv in (range(groupTileKVec) if staticK else [-1]) %}
241
+ {% if staticK %}
242
+ {
243
+ const kv: u32 = {{ staticKv }}u;
244
+ {% else %}
245
  for (var kv = 0u; kv < KVEC; kv = kv + 1u) {
246
+ {% endif %}
247
  {% for r in range(regM) %}
248
  let a{{ r }} = a_tile[(lid.y * {{ regM }}u + {{ r }}u) * KVEC + kv];
249
  {% endfor %}
250
+ {% for c in range(regN) %}{% set bReadIndex =
251
+ ("kv * NTILE + lid.x + " ~ ((c * groupTileN / regN) | int) ~ "u")
252
+ if bKMajor and bLaneInterleaved and regN > 1
253
+ else (("kv * NTILE + lid.x * " ~ regN ~ "u + " ~ c ~ "u") if bKMajor
254
+ else ("(lid.x * " ~ regN ~ "u + " ~ c ~ "u) * KVEC + kv"))
255
+ %}
256
+ let b{{ c }} = b_tile[{{ bReadIndex }}];
257
  {% if b2Load %}
258
+ let s{{ c }} = b2_tile[{{ bReadIndex }}];
259
  {% endif %}
260
  {% endfor %}
261
  {% for r in range(regM) %}
262
  {% for c in range(regN) %}
263
+ {% if scalarFma %}
264
+ {% for component in ['x', 'y', 'z', 'w'] %}
265
+ {{ accum }}_{{ r }}_{{ c }} = fma(a{{ r }}.{{ component }}, b{{ c }}.{{ component }}, {{ accum }}_{{ r }}_{{ c }});
266
+ {% endfor %}
267
+ {% else %}
268
+ {{ accum }}_{{ r }}_{{ c }} = {{ accum }}_{{ r }}_{{ c }} + dot(a{{ r }}, b{{ c }});
269
+ {% endif %}
270
  {% if b2Load %}
271
+ {% if scalarFma %}
272
+ {% for component in ['x', 'y', 'z', 'w'] %}
273
+ {{ accum2 }}_{{ r }}_{{ c }} = fma(a{{ r }}.{{ component }}, s{{ c }}.{{ component }}, {{ accum2 }}_{{ r }}_{{ c }});
274
+ {% endfor %}
275
+ {% else %}
276
+ {{ accum2 }}_{{ r }}_{{ c }} = {{ accum2 }}_{{ r }}_{{ c }} + dot(a{{ r }}, s{{ c }});
277
+ {% endif %}
278
  {% endif %}
279
  {% endfor %}
280
  {% endfor %}
281
  }
282
+ {% endfor %}
283
+ {% if foldStage %}{% for r in range(regM) %}{% for c in range(regN) %}
284
+ {% if refinePair %}{% for stream in ["", "2"] %}{% set id = stream ~ "_" ~ r ~ "_" ~ c %}
285
+ mass{{ id }} += abs(chunk{{ id }});
286
+ acc{{ id }} += chunk{{ id }};
287
+ {% endfor %}{% else %}
288
+ acc_{{ r }}_{{ c }} += chunk_{{ r }}_{{ c }};
289
+ {% endif %}
290
+ {% endfor %}{% endfor %}{% endif %} // Orders this step's tile reads before the next step overwrites them.
291
  workgroupBarrier();
292
  k_base = k_base + KTILE;
293
  }{% endmacro %}
 
298
  var<workgroup> b2_tile: array<vec4<f32>, {{ groupTileN * groupTileKVec }}>;
299
  {% endif %}
300
 
301
+ {% set groupSubgroupSize = qmoeGroupedPin %}
302
+ {% set groupSubgroupSize = groupSubgroupSize | default(0) %}
303
+ {% if groupSubgroupSize > 0 %}
304
+ @compute @workgroup_size(THREADS, 1, 1) @subgroup_size({{ groupSubgroupSize }})
305
+ fn main(@builtin(workgroup_id) wid: vec3<u32>,
306
+ @builtin(local_invocation_index) local_index: u32) {
307
+ let lid = vec3<u32>(local_index % THREADS_SIDE, local_index / THREADS_SIDE, 0u);
308
+ {% else %}
309
  @compute @workgroup_size(THREADS_SIDE, THREADS_SIDE, 1)
310
  fn main(@builtin(workgroup_id) wid: vec3<u32>,
311
  @builtin(local_invocation_id) lid: vec3<u32>) {
312
+ {% endif %}
313
  let tile = wid.x;
314
  if (tile >= tile_meta[0]) {
315
  return;
 
330
  "fc1_weight(expert, col * 2u + 1u, k_base + k)" if isSwiglu else "",
331
  "HIDDEN", "INTER", regM, regN,
332
  "fc1_weight_vec4(expert, " ~ primaryRow ~ ", k_base + kb)",
333
+ "fc1_weight_vec4(expert, col * 2u + 1u, k_base + kb)" if isSwiglu else "", "", (expertF32Schedule or scalarQuantAccum), bKMajor=groupWeightKMajor, bLaneInterleaved=groupWeightLaneInterleaved | default(false), staticK=expertF32Schedule, bStageInterleaved=expertF32Schedule, packedStreams=([{'packing':('word8' if packedWeights else 'byte8'),'prefix':'gate','buffer':'fc1_experts_weights','scales':'fc1_scales','rows':'FC1_ROWS','row':primaryRow,'packedCols':fc1PackedCols,'scaleBlocks':fc1ScaleBlocks,'destination':'b_tile','columnScales':colWiseScales,'quantBlock':'QUANT_BLOCK','zero':'MIDPOINT'}] + ([{'packing':('word8' if packedWeights else 'byte8'),'prefix':'up','buffer':'fc1_experts_weights','scales':'fc1_scales','rows':'FC1_ROWS','row':'col * 2u + 1u','packedCols':fc1PackedCols,'scaleBlocks':fc1ScaleBlocks,'destination':'b2_tile','columnScales':colWiseScales,'quantBlock':'QUANT_BLOCK','zero':'MIDPOINT'}] if isSwiglu else []) if expertQ4Vec4 else [])) }}
334
 
335
  {% for r in range(regM) %}
336
  {% for c in range(regN) %}
build/webgpu/qmoe-fc1-activation-stage.wgsl.jinja CHANGED
@@ -1,29 +1,77 @@
1
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
- let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}
 
6
  {{ env.wgsl.resourceDeclarations }}
7
- {% set dotType = "f32" %}
 
8
  // Retain product and addition residuals across a dot product. Explicit fma
9
  // boundaries preserve the addition error transform under reassociation.
10
  struct DotAccumulator {
11
  hi: {{ dotType }},
12
  lo: {{ dotType }},
13
  }
14
- fn dot_accumulate(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  let product = fma(a, b, {{ dotType }}(0.0));
16
- let productError = fma(a, b, -product);
17
- let sum = fma(acc.hi, {{ dotType }}(1.0), product);
18
- let bv = fma({{ dotType }}(-1.0), acc.hi, sum);
 
 
 
 
 
 
 
 
 
 
 
 
19
  let av = fma({{ dotType }}(-1.0), bv, sum);
20
  let ae = fma({{ dotType }}(-1.0), av, acc.hi);
21
  let be = fma({{ dotType }}(-1.0), bv, product);
22
  let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);
23
- let hi = fma(sum, {{ dotType }}(1.0), error);
24
- return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));
25
- }
26
- fn dot_value(acc: DotAccumulator) -> {{ dotType }} {
 
 
 
 
 
 
 
 
 
 
27
  return fma(acc.hi, {{ dotType }}(1.0), acc.lo);
28
  }
29
 
@@ -42,25 +90,23 @@ const TOP_K: u32 = {{ topK }}u;
42
  {% set qwRows = "FC1_ROWS" %}
43
  {% set qwPackedCols = fc1PackedCols %}
44
  {% set qwBlocks = fc1ScaleBlocks %}
45
- // Quantized expert weights use unsigned codes offset by 2^(bits-1), so a
46
- // weight is (code - MIDPOINT) * scale. Four-bit codes are packed low-nibble
47
- // first along the reduction axis, two codes per stored word.
48
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
49
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
50
  {% if not colWiseScales %}
51
- // Block-wise scales ({{ qw }}_scales rank 3): one scale per QUANT_BLOCK columns of the reduction
52
- // axis. Column-wise scales (block_size 0) are the rank-2 single-scale-per-row case below.
53
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
54
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
55
  {% endif %}
56
 
 
57
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
58
  let base = expert * {{ qwRows }} + row;
59
- {% if packSize == 2 %}
60
- let word = {{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col / 2u];
61
- let code = f32((word >> ((col & 1u) * 4u)) & 15u);
62
  {% else %}
63
- let code = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col] & 255u);
64
  {% endif %}
65
  {% if not colWiseScales %}
66
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
1
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
+ let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
6
+ {% endmacro %}
7
  {{ env.wgsl.resourceDeclarations }}
8
+ {% set dotType = "f32" %}{% set protectDifference = protectDotDifference | default(false) %}{% set PROTECTED_SUM = (protectDotSum | default(false)) or protectDifference %}
9
+ {% set SELECT_NONFINITE = not PROTECTED_SUM and (dotSelectNonfinite | default(false)) and (dotGuardNonfinite | default(false)) %}
10
  // Retain product and addition residuals across a dot product. Explicit fma
11
  // boundaries preserve the addition error transform under reassociation.
12
  struct DotAccumulator {
13
  hi: {{ dotType }},
14
  lo: {{ dotType }},
15
  }
16
+ {% if PROTECTED_SUM %}
17
+ {% macro sum_error_function(name, type="f32", protectDifference=false) %}
18
+ {% set bitsType = type | replace("f32", "u32") %}
19
+ // Observing the rounded sum as bits preserves FastTwoSum on backends
20
+ // that otherwise reassociate its subtractions. Both signs of zero contribute zero.
21
+ fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {
22
+ let bits = bitcast<{{ bitsType }}>(x);
23
+ return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));
24
+ }
25
+ fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {
26
+ let swap = abs(a) < abs(b);
27
+ let larger = select(a, b, swap);
28
+ let smaller = select(b, a, swap);
29
+ {% if protectDifference %}
30
+ // Keep the rounded high-part difference observable before subtracting it
31
+ // from the smaller addend. Reassociation here erases the residual.
32
+ return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);
33
+ {% else %}
34
+ return smaller - ({{ name }}_rounded(sum) - larger);
35
+ {% endif %}
36
+ }
37
+ {% endmacro %}
38
+ {{ sum_error_function("dot_sum_error", dotType, protectDifference) }}
39
+ {% endif %}
40
+ {% macro dot_step(name, dotGuardNonfinite) %}fn {{ name }}(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {
41
  let product = fma(a, b, {{ dotType }}(0.0));
42
+ {% if dotGuardNonfinite | default(false) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);
43
+ {% if not SELECT_NONFINITE %} // Nonfinite sums retain ordinary f32 addition classes; Inf-Inf residuals
44
+ // must not poison a valid infinite dot accumulator.
45
+ if (!(abs(acc.hi) <= 3.4028234663852886e38) ||
46
+ !(abs(acc.lo) <= 3.4028234663852886e38) ||
47
+ !(abs(product) <= 3.4028234663852886e38) ||
48
+ !(abs(sum) <= 3.4028234663852886e38)) {
49
+ return DotAccumulator(sum, {{ dotType }}(0.0));
50
+ }
51
+ {% endif %}{% endif %} let productError = fma(a, b, -product);
52
+ {% if not (dotGuardNonfinite | default(false)) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);
53
+ {% endif %}{% if PROTECTED_SUM %}
54
+ let roundoff = dot_sum_error(acc.hi, product, sum);
55
+ let error = (acc.lo + roundoff) + productError;
56
+ {% else %} let bv = fma({{ dotType }}(-1.0), acc.hi, sum);
57
  let av = fma({{ dotType }}(-1.0), bv, sum);
58
  let ae = fma({{ dotType }}(-1.0), av, acc.hi);
59
  let be = fma({{ dotType }}(-1.0), bv, product);
60
  let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);
61
+ {% endif %}{% if PROTECTED_SUM %}
62
+ // Carry the residual to the end of the dot. Renormalizing each step can
63
+ // round a recovered product bit out of the low word on relaxed backends.
64
+ return DotAccumulator(sum, error);
65
+ {% else %} let hi = fma(sum, {{ dotType }}(1.0), error);
66
+ {% if SELECT_NONFINITE %} let sumValid = abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38;
67
+ let nextLo = fma(-1.0, fma(-1.0, sum, hi), error);
68
+ return DotAccumulator(select(sum, hi, sumValid), select(0.0, nextLo, sumValid && abs(hi) <= 3.4028234663852886e38));
69
+ {% else %}{% if dotGuardNonfinite | default(false) %} if (!(abs(hi) <= 3.4028234663852886e38)) {
70
+ return DotAccumulator(hi, {{ dotType }}(0.0));
71
+ }
72
+ {% endif %} return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));
73
+ {% endif %}{% endif %}}
74
+ {% endmacro %}{{ dot_step("dot_accumulate", dotGuardNonfinite | default(false)) }}fn dot_value(acc: DotAccumulator) -> {{ dotType }} {
75
  return fma(acc.hi, {{ dotType }}(1.0), acc.lo);
76
  }
77
 
 
90
  {% set qwRows = "FC1_ROWS" %}
91
  {% set qwPackedCols = fc1PackedCols %}
92
  {% set qwBlocks = fc1ScaleBlocks %}
93
+ // Integer codes use the implicit midpoint 2^(bits-1) and low-first packing
94
+ // along each reduction row. Tensor bytes may use widened or packed transport.
 
95
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
96
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
97
  {% if not colWiseScales %}
 
 
98
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
99
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
100
  {% endif %}
101
 
102
+ {% macro weight_byte(index) %}{{ qw }}_experts_weights[{{ index }}]{% endmacro %}
103
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
104
  let base = expert * {{ qwRows }} + row;
105
+ {% if packSize > 1 %}
106
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / " ~ packSize ~ "u") }};
107
+ let code = f32((word >> ((col % {{ packSize }}u) * {{ weightBits }}u)) & {{ 2 ** weightBits - 1 }}u);
108
  {% else %}
109
+ let code = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col") }} & 255u);
110
  {% endif %}
111
  {% if not colWiseScales %}
112
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
build/webgpu/qmoe-output-gemv.wgsl.jinja CHANGED
@@ -8,29 +8,34 @@ const TOP_K: u32 = {{ topK }}u;
8
  // LANES-wide cooperative reduction.
9
  const LANES: u32 = {{ decodeLanes }}u;
10
  const ROWS: u32 = {{ decodeRows }}u;
 
 
 
 
 
 
11
  {% set qw = "fc2" %}
12
  {% set qwRows = "HIDDEN" %}
13
  {% set qwPackedCols = fc2PackedCols %}
14
  {% set qwBlocks = fc2ScaleBlocks %}
15
- // Quantized expert weights use unsigned codes offset by 2^(bits-1), so a
16
- // weight is (code - MIDPOINT) * scale. Four-bit codes are packed low-nibble
17
- // first along the reduction axis, two codes per stored word.
18
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
19
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
20
  {% if not colWiseScales %}
21
- // Block-wise scales ({{ qw }}_scales rank 3): one scale per QUANT_BLOCK columns of the reduction
22
- // axis. Column-wise scales (block_size 0) are the rank-2 single-scale-per-row case below.
23
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
24
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
25
  {% endif %}
26
 
 
 
27
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
28
  let base = expert * {{ qwRows }} + row;
29
- {% if packSize == 2 %}
30
- let word = {{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col / 2u];
31
- let code = f32((word >> ((col & 1u) * 4u)) & 15u);
32
  {% else %}
33
- let code = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col] & 255u);
34
  {% endif %}
35
  {% if not colWiseScales %}
36
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
@@ -38,17 +43,18 @@ fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
38
  return (code - MIDPOINT) * {{ qw }}_scales[base];
39
  {% endif %}
40
  }
41
- // Decode two consecutive reduction-axis codes together. Four-bit codes share a
42
- // stored word; eight-bit codes occupy adjacent words.
43
  fn {{ qw }}_weight_pair(expert: u32, row: u32, col: u32) -> vec2<f32> {
44
  let base = expert * {{ qwRows }} + row;
45
- {% if packSize == 2 %}
46
- let word = {{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col / 2u];
47
- let lo = f32(word & 15u) - MIDPOINT;
48
- let hi = f32((word >> 4u) & 15u) - MIDPOINT;
 
49
  {% else %}
50
- let lo = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col] & 255u) - MIDPOINT;
51
- let hi = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col + 1u] & 255u) - MIDPOINT;
52
  {% endif %}
53
  {% if not colWiseScales %}
54
  return vec2<f32>(lo * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK],
@@ -58,6 +64,33 @@ fn {{ qw }}_weight_pair(expert: u32, row: u32, col: u32) -> vec2<f32> {
58
  return vec2<f32>(lo * scale, hi * scale);
59
  {% endif %}
60
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  {% macro rowlane_fold(arrays, lanes="LANES", lane="lane", slot="slot") %}
63
  var n = {{ lanes }};
@@ -92,6 +125,17 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
92
  let expert = route_expert[route_slot];
93
  let act_base = (local_token * TOP_K + j) * INTER;
94
  var part = 0.0;
 
 
 
 
 
 
 
 
 
 
 
95
  // Two reduction columns per step: at 4 bits they are one stored word.
96
  for (var c = lane * 2u; c + 1u < INTER; c = c + LANES * 2u) {
97
  let p = fc2_weight_pair(expert, out_col, c);
@@ -103,6 +147,7 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
103
  let i = INTER - 1u;
104
  part = part + hidden_act[act_base + i] * fc2_weight(expert, out_col, i);
105
  }
 
106
  acc = acc + part * route_mix[route_slot];
107
  }
108
  }
 
8
  // LANES-wide cooperative reduction.
9
  const LANES: u32 = {{ decodeLanes }}u;
10
  const ROWS: u32 = {{ decodeRows }}u;
11
+ {% if gemvVec4 %}
12
+ {% set needsWeightVec4 = true %}
13
+ {% set weightVec4Only = true %}
14
+ {% else %}
15
+ {% set needsWeightPair = true %}
16
+ {% endif %}
17
  {% set qw = "fc2" %}
18
  {% set qwRows = "HIDDEN" %}
19
  {% set qwPackedCols = fc2PackedCols %}
20
  {% set qwBlocks = fc2ScaleBlocks %}
21
+ // Integer codes use the implicit midpoint 2^(bits-1) and low-first packing
22
+ // along each reduction row. Tensor bytes may use widened or packed transport.
 
23
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
24
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
25
  {% if not colWiseScales %}
 
 
26
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
27
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
28
  {% endif %}
29
 
30
+ {% macro weight_byte(index) %}{{ qw }}_experts_weights[{{ index }}]{% endmacro %}
31
+ {% if weightVec4Only is not defined %}
32
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
33
  let base = expert * {{ qwRows }} + row;
34
+ {% if packSize > 1 %}
35
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / " ~ packSize ~ "u") }};
36
+ let code = f32((word >> ((col % {{ packSize }}u) * {{ weightBits }}u)) & {{ 2 ** weightBits - 1 }}u);
37
  {% else %}
38
+ let code = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col") }} & 255u);
39
  {% endif %}
40
  {% if not colWiseScales %}
41
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
43
  return (code - MIDPOINT) * {{ qw }}_scales[base];
44
  {% endif %}
45
  }
46
+ {% endif %}
47
+ {% if needsWeightPair is defined %}
48
  fn {{ qw }}_weight_pair(expert: u32, row: u32, col: u32) -> vec2<f32> {
49
  let base = expert * {{ qwRows }} + row;
50
+ {% if packSize > 1 %}
51
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / " ~ packSize ~ "u") }};
52
+ let shift = (col % {{ packSize }}u) * {{ weightBits }}u;
53
+ let lo = f32((word >> shift) & {{ 2 ** weightBits - 1 }}u) - MIDPOINT;
54
+ let hi = f32((word >> (shift + {{ weightBits }}u)) & {{ 2 ** weightBits - 1 }}u) - MIDPOINT;
55
  {% else %}
56
+ let lo = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col") }} & 255u) - MIDPOINT;
57
+ let hi = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col + 1u") }} & 255u) - MIDPOINT;
58
  {% endif %}
59
  {% if not colWiseScales %}
60
  return vec2<f32>(lo * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK],
 
64
  return vec2<f32>(lo * scale, hi * scale);
65
  {% endif %}
66
  }
67
+ {% endif %}
68
+ {% if needsWeightVec4 is defined %}
69
+ // Aligned four-code groups share a scale: block sizes are multiples of sixteen.
70
+ fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
71
+ let base = expert * {{ qwRows }} + row;
72
+ {% if packSize == 4 %}
73
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / 4u") }};
74
+ let codes = vec4<f32>((vec4<u32>(word) >> vec4<u32>(0u, 2u, 4u, 6u)) & vec4<u32>(3u));
75
+ {% elif packSize == 2 %}
76
+ let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
77
+ let w0 = {{ weight_byte("pair") }};
78
+ let w1 = {{ weight_byte("pair + 1u") }};
79
+ let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
80
+ f32(w1 & 15u), f32((w1 >> 4u) & 15u));
81
+ {% else %}
82
+ let word = base * {{ qw | upper }}_PACKED_COLS + col;
83
+ let codes = vec4<f32>(f32({{ weight_byte("word") }} & 255u), f32({{ weight_byte("word + 1u") }} & 255u),
84
+ f32({{ weight_byte("word + 2u") }} & 255u), f32({{ weight_byte("word + 3u") }} & 255u));
85
+ {% endif %}
86
+ {% if not colWiseScales %}
87
+ let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
88
+ {% else %}
89
+ let scale = {{ qw }}_scales[base];
90
+ {% endif %}
91
+ return (codes - vec4<f32>(MIDPOINT)) * scale;
92
+ }
93
+ {% endif %}
94
 
95
  {% macro rowlane_fold(arrays, lanes="LANES", lane="lane", slot="slot") %}
96
  var n = {{ lanes }};
 
125
  let expert = route_expert[route_slot];
126
  let act_base = (local_token * TOP_K + j) * INTER;
127
  var part = 0.0;
128
+ {% if gemvVec4 %}
129
+ for (var c = lane * 4u; c + 3u < INTER; c = c + LANES * 4u) {
130
+ let x = vec4<f32>(
131
+ {% for v in range(4) %}
132
+ f32(hidden_act[act_base + c + {{ v }}u]){{ ',' if v < 3 else '' }}
133
+ {% endfor %}
134
+ );
135
+ let p = fc2_weight_vec4(expert, out_col, c);
136
+ part = part + x.x * p.x + x.y * p.y + x.z * p.z + x.w * p.w;
137
+ }
138
+ {% else %}
139
  // Two reduction columns per step: at 4 bits they are one stored word.
140
  for (var c = lane * 2u; c + 1u < INTER; c = c + LANES * 2u) {
141
  let p = fc2_weight_pair(expert, out_col, c);
 
147
  let i = INTER - 1u;
148
  part = part + hidden_act[act_base + i] * fc2_weight(expert, out_col, i);
149
  }
150
+ {% endif %}
151
  acc = acc + part * route_mix[route_slot];
152
  }
153
  }
build/webgpu/qmoe-output-grouped-sgmat.wgsl.jinja CHANGED
@@ -24,33 +24,32 @@ const SUB_ROWS: u32 = 16u;
24
  {% set qwRows = "HIDDEN" %}
25
  {% set qwPackedCols = fc2PackedCols %}
26
  {% set qwBlocks = fc2ScaleBlocks %}
27
- // Quantized expert weights use unsigned codes offset by 2^(bits-1), so a
28
- // weight is (code - MIDPOINT) * scale. Four-bit codes are packed low-nibble
29
- // first along the reduction axis, two codes per stored word.
30
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
31
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
32
  {% if not colWiseScales %}
33
- // Block-wise scales ({{ qw }}_scales rank 3): one scale per QUANT_BLOCK columns of the reduction
34
- // axis. Column-wise scales (block_size 0) are the rank-2 single-scale-per-row case below.
35
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
36
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
37
  {% endif %}
38
 
39
- // Decode the four-code group consumed by the staging loop. The aligned codes
40
- // share one quantization scale: blocks are powers of two of at least 16, and
41
- // this helper requires `col` to be a multiple of four.
42
  fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
43
  let base = expert * {{ qwRows }} + row;
44
- {% if packSize == 2 %}
 
 
 
45
  let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
46
- let w0 = {{ qw }}_experts_weights[pair];
47
- let w1 = {{ qw }}_experts_weights[pair + 1u];
48
  let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
49
  f32(w1 & 15u), f32((w1 >> 4u) & 15u));
50
  {% else %}
51
  let word = base * {{ qw | upper }}_PACKED_COLS + col;
52
- let codes = vec4<f32>(f32({{ qw }}_experts_weights[word] & 255u), f32({{ qw }}_experts_weights[word + 1u] & 255u),
53
- f32({{ qw }}_experts_weights[word + 2u] & 255u), f32({{ qw }}_experts_weights[word + 3u] & 255u));
54
  {% endif %}
55
  {% if not colWiseScales %}
56
  let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
@@ -119,13 +118,77 @@ fn storeOutput(col_base: u32, row: u32, col: u32, src_slot: u32, row_base: u32,
119
  }
120
  }
121
 
122
- @compute @workgroup_size({{ sgmatWorkgroup }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
123
- fn main(
124
- @builtin(workgroup_id) wid: vec3<u32>,
125
- @builtin(local_invocation_index) local_idx: u32,
126
- @builtin(subgroup_invocation_id) sg_id: u32,
127
- @builtin(subgroup_size) sg_size: u32
128
- ) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  let tile = wid.x;
130
  if (tile >= tile_meta[0]) {
131
  return;
@@ -137,7 +200,7 @@ fn main(
137
 
138
  let a_slot = select(0u, slot_list[slice_base + local_idx / 4u], local_idx / 4u < rows);
139
 
140
- let subtile_id = local_idx / sg_size;
141
  let subtile_idx = subtile_id / {{ sgmatRowSubtiles }}u;
142
  let subtile_idy = subtile_id % {{ sgmatRowSubtiles }}u;
143
  let base_A = subtile_idy * SUB_ROWS;
@@ -145,7 +208,7 @@ fn main(
145
 
146
  {% for row in [0, 1] %}
147
  {% for col in [0, 1, 2, 3] %}
148
- var matC{{ row }}{{ col }}: subgroup_matrix_result<f32, 8, 8>;
149
  {% endfor %}
150
  {% endfor %}
151
 
@@ -159,22 +222,23 @@ fn main(
159
  {% set directInputs = false %}
160
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
161
  {% for r in range(2) %}
162
- 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" }});
163
  {% endfor %}
164
 
 
165
  let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
166
  {% for c in range(4) %}
167
- 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" }});
168
  {% endfor %}
169
 
170
- matC00 = subgroupMatrixMultiplyAccumulate(matA0, matB0, matC00);
171
- matC01 = subgroupMatrixMultiplyAccumulate(matA0, matB1, matC01);
172
- matC02 = subgroupMatrixMultiplyAccumulate(matA0, matB2, matC02);
173
- matC03 = subgroupMatrixMultiplyAccumulate(matA0, matB3, matC03);
174
- matC10 = subgroupMatrixMultiplyAccumulate(matA1, matB0, matC10);
175
- matC11 = subgroupMatrixMultiplyAccumulate(matA1, matB1, matC11);
176
- matC12 = subgroupMatrixMultiplyAccumulate(matA1, matB2, matC12);
177
- matC13 = subgroupMatrixMultiplyAccumulate(matA1, matB3, matC13);
178
  }
179
  workgroupBarrier();
180
  }
@@ -182,7 +246,7 @@ fn main(
182
  // Each scratch bank is written by a collective store and then read across lanes, and
183
  // the two row groups reuse the same banks, so both barriers are load-bearing.
184
  {% for col in [0, 1, 2, 3] %}
185
- subgroupMatrixStore<row_major>(&tile_A, (subtile_id * 4u + {{ col }}u) * 64u, matC0{{ col }}, 8u);
186
  {% endfor %}
187
  workgroupBarrier();
188
  let row = sg_id / 4u;
@@ -191,8 +255,31 @@ fn main(
191
  workgroupBarrier();
192
 
193
  {% for col in [0, 1, 2, 3] %}
194
- subgroupMatrixStore<row_major>(&tile_A, (subtile_id * 4u + {{ col }}u) * 64u, matC1{{ col }}, 8u);
195
  {% endfor %}
196
  workgroupBarrier();
197
  storeOutput(col_base + base_B, row, col, subtile_id, base_A + 8u, rows, slice_base);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  }
 
24
  {% set qwRows = "HIDDEN" %}
25
  {% set qwPackedCols = fc2PackedCols %}
26
  {% set qwBlocks = fc2ScaleBlocks %}
27
+ // Integer codes use the implicit midpoint 2^(bits-1) and low-first packing
28
+ // along each reduction row. Tensor bytes may use widened or packed transport.
 
29
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
30
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
31
  {% if not colWiseScales %}
 
 
32
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
33
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
34
  {% endif %}
35
 
36
+ {% macro weight_byte(index) %}{{ qw }}_experts_weights[{{ index }}]{% endmacro %}
37
+ // Aligned four-code groups share a scale: block sizes are multiples of sixteen.
 
38
  fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
39
  let base = expert * {{ qwRows }} + row;
40
+ {% if packSize == 4 %}
41
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / 4u") }};
42
+ let codes = vec4<f32>((vec4<u32>(word) >> vec4<u32>(0u, 2u, 4u, 6u)) & vec4<u32>(3u));
43
+ {% elif packSize == 2 %}
44
  let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
45
+ let w0 = {{ weight_byte("pair") }};
46
+ let w1 = {{ weight_byte("pair + 1u") }};
47
  let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
48
  f32(w1 & 15u), f32((w1 >> 4u) & 15u));
49
  {% else %}
50
  let word = base * {{ qw | upper }}_PACKED_COLS + col;
51
+ let codes = vec4<f32>(f32({{ weight_byte("word") }} & 255u), f32({{ weight_byte("word + 1u") }} & 255u),
52
+ f32({{ weight_byte("word + 2u") }} & 255u), f32({{ weight_byte("word + 3u") }} & 255u));
53
  {% endif %}
54
  {% if not colWiseScales %}
55
  let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
118
  }
119
  }
120
 
121
+ {% set accScalar = "f32" %}
122
+ // A subgroup owns one matrix tile only after its actual population and the
123
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
124
+ // the role; local invocation IDs only publish the workgroup-wide decision.
125
+ var<workgroup> matrixRoleCount: atomic<u32>;
126
+ var<workgroup> matrixRejected: atomic<u32>;
127
+ var<workgroup> matrixAccepted: u32;
128
+
129
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
130
+ // WGSL initializes workgroup variables to zero before this entry point.
131
+ let population = subgroupBallot(true);
132
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
133
+ + countOneBits(population.z) + countOneBits(population.w);
134
+ var claimed = 0u;
135
+ if (subgroupElect()) {
136
+ claimed = atomicAdd(&matrixRoleCount, 1u);
137
+ if (width != requiredWidth || populationCount != requiredWidth) {
138
+ atomicStore(&matrixRejected, 1u);
139
+ }
140
+ }
141
+ // Reconverge every invocation before broadcasting the elected claim.
142
+ workgroupBarrier();
143
+ return subgroupBroadcastFirst(claimed);
144
+ }
145
+
146
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
147
+ if (localIndex == 0u) {
148
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
149
+ && atomicLoad(&matrixRoleCount) == bankCount);
150
+ }
151
+ // The uniform load both publishes the leader's decision and gives the
152
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
153
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
154
+ }
155
+ // The portable arm owns two result components per logical 32-invocation group.
156
+ // Staging casts, 8-wide K steps, barriers and the epilogue match the
157
+ // subgroup-matrix arm.
158
+ var<private> matrixSoftwareLane: u32;
159
+
160
+ fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,
161
+ acc: vec2<f32>) -> vec2<f32> {
162
+ var value = acc;
163
+ for (var k = 0u; k < 8u; k += 1u) {
164
+ value = fma(vec2<f32>(lhs[k]), rhs[k], value);
165
+ }
166
+ return value;
167
+ }
168
+
169
+ {% 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 %}
170
+
171
+ {% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}
172
+ {% if kind == "left" %}array<f32, 8>(
173
+ {% 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 "" }}
174
+ {% endfor %})
175
+ {% else %}array<vec2<f32>, 8>(
176
+ {% for k in range(8) %}vec2<f32>(
177
+ {% 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 "" }}
178
+ {% endfor %}){{ "," if k < 7 else "" }}
179
+ {% endfor %})
180
+ {% endif %}{% endif %}{% endmacro %}
181
+
182
+ {% 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 %}
183
+
184
+ {% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{
185
+ let matrixPointer = {{ pointer }};
186
+ let matrixValue = {{ value }};
187
+ {% 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" }};
188
+ {% endfor %}}{% endif %}{% endmacro %}
189
+
190
+ {% macro matrixKernelBody(matrixSoftware) %}
191
+
192
  let tile = wid.x;
193
  if (tile >= tile_meta[0]) {
194
  return;
 
200
 
201
  let a_slot = select(0u, slot_list[slice_base + local_idx / 4u], local_idx / 4u < rows);
202
 
203
+ let subtile_id = matrixRole;
204
  let subtile_idx = subtile_id / {{ sgmatRowSubtiles }}u;
205
  let subtile_idy = subtile_id % {{ sgmatRowSubtiles }}u;
206
  let base_A = subtile_idy * SUB_ROWS;
 
208
 
209
  {% for row in [0, 1] %}
210
  {% for col in [0, 1, 2, 3] %}
211
+ var matC{{ row }}{{ col }}: {{ matrixType(matrixSoftware, "result", "f32") }};
212
  {% endfor %}
213
  {% endfor %}
214
 
 
222
  {% set directInputs = false %}
223
  let matrix_a_offset = subtile_idy * SUB_ROWS * TILE_K + step;
224
  {% for r in range(2) %}
225
+ 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") }};
226
  {% endfor %}
227
 
228
+ {% set storageB = "" %}
229
  let matrix_b_offset = subtile_idx * SUB_COLS * TILE_K + step;
230
  {% for c in range(4) %}
231
+ 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") }};
232
  {% endfor %}
233
 
234
+ matC00 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB0", "matC00") }};
235
+ matC01 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB1", "matC01") }};
236
+ matC02 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB2", "matC02") }};
237
+ matC03 = {{ matrixMma(matrixSoftware, accScalar, "matA0", "matB3", "matC03") }};
238
+ matC10 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB0", "matC10") }};
239
+ matC11 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB1", "matC11") }};
240
+ matC12 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB2", "matC12") }};
241
+ matC13 = {{ matrixMma(matrixSoftware, accScalar, "matA1", "matB3", "matC13") }};
242
  }
243
  workgroupBarrier();
244
  }
 
246
  // Each scratch bank is written by a collective store and then read across lanes, and
247
  // the two row groups reuse the same banks, so both barriers are load-bearing.
248
  {% for col in [0, 1, 2, 3] %}
249
+ {{ matrixStore(matrixSoftware, "row_major", "&tile_A", "(subtile_id * 4u + " ~ (col) ~ "u) * 64u", "matC0" ~ (col), "8u") }}
250
  {% endfor %}
251
  workgroupBarrier();
252
  let row = sg_id / 4u;
 
255
  workgroupBarrier();
256
 
257
  {% for col in [0, 1, 2, 3] %}
258
+ {{ matrixStore(matrixSoftware, "row_major", "&tile_A", "(subtile_id * 4u + " ~ (col) ~ "u) * 64u", "matC1" ~ (col), "8u") }}
259
  {% endfor %}
260
  workgroupBarrier();
261
  storeOutput(col_base + base_B, row, col, subtile_id, base_A + 8u, rows, slice_base);
262
+
263
+ {% endmacro %}
264
+ {% macro matrix_topology_dispatch(groupSize, withSubgroupLane) %}
265
+ let matrixRole = claimMatrixSubgroupRole(matrixPhysicalWidth, 32u);
266
+ let matrixAcceptedHere = matrixTopologyAccepted(local_idx, {{ groupSize }} / 32u);
267
+ matrixSoftwareLane = local_idx % 32u;
268
+ if (matrixAcceptedHere) {
269
+ let sg_id = matrixPhysicalLane;
270
+ {{ matrixKernelBody(false) }}
271
+ } else {
272
+ let matrixRole = local_idx / 32u;
273
+ let sg_id = local_idx % 32u;
274
+ {{ matrixKernelBody(true) }}
275
+ }
276
+ {%- endmacro -%}
277
+ @compute @workgroup_size({{ sgmatWorkgroup }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
278
+ fn main(
279
+ @builtin(workgroup_id) wid: vec3<u32>,
280
+ @builtin(local_invocation_index) local_idx: u32,
281
+ @builtin(subgroup_size) matrixPhysicalWidth: u32,
282
+ @builtin(subgroup_invocation_id) matrixPhysicalLane: u32
283
+ ) {
284
+ {{ matrix_topology_dispatch(sgmatWorkgroup ~ "u", true) }}
285
  }
build/webgpu/qmoe-output-grouped.wgsl.jinja CHANGED
@@ -1,3 +1,7 @@
 
 
 
 
1
  {{ env.wgsl.resourceDeclarations }}
2
 
3
  // com.microsoft.QMoE, expert-grouped FC2 stage, sharing the tile loop with the grouped FC1
@@ -13,29 +17,30 @@ const NTILE: u32 = {{ groupTileN }}u;
13
  const KTILE: u32 = {{ groupTileK }}u;
14
  const THREADS_SIDE: u32 = {{ groupThreads }}u;
15
  const THREADS: u32 = THREADS_SIDE * THREADS_SIDE;
 
 
16
  {% set qw = "fc2" %}
17
  {% set qwRows = "HIDDEN" %}
18
  {% set qwPackedCols = fc2PackedCols %}
19
  {% set qwBlocks = fc2ScaleBlocks %}
20
- // Quantized expert weights use unsigned codes offset by 2^(bits-1), so a
21
- // weight is (code - MIDPOINT) * scale. Four-bit codes are packed low-nibble
22
- // first along the reduction axis, two codes per stored word.
23
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
24
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
25
  {% if not colWiseScales %}
26
- // Block-wise scales ({{ qw }}_scales rank 3): one scale per QUANT_BLOCK columns of the reduction
27
- // axis. Column-wise scales (block_size 0) are the rank-2 single-scale-per-row case below.
28
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
29
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
30
  {% endif %}
31
 
 
 
32
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
33
  let base = expert * {{ qwRows }} + row;
34
- {% if packSize == 2 %}
35
- let word = {{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col / 2u];
36
- let code = f32((word >> ((col & 1u) * 4u)) & 15u);
37
  {% else %}
38
- let code = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col] & 255u);
39
  {% endif %}
40
  {% if not colWiseScales %}
41
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
@@ -43,21 +48,27 @@ fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
43
  return (code - MIDPOINT) * {{ qw }}_scales[base];
44
  {% endif %}
45
  }
46
- // Decode the four-code group consumed by the staging loop. The aligned codes
47
- // share one quantization scale: blocks are powers of two of at least 16, and
48
- // this helper requires `col` to be a multiple of four.
49
  fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
50
  let base = expert * {{ qwRows }} + row;
51
- {% if packSize == 2 %}
 
 
 
52
  let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
53
- let w0 = {{ qw }}_experts_weights[pair];
54
- let w1 = {{ qw }}_experts_weights[pair + 1u];
55
  let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
56
  f32(w1 & 15u), f32((w1 >> 4u) & 15u));
57
  {% else %}
58
  let word = base * {{ qw | upper }}_PACKED_COLS + col;
59
- let codes = vec4<f32>(f32({{ qw }}_experts_weights[word] & 255u), f32({{ qw }}_experts_weights[word + 1u] & 255u),
60
- f32({{ qw }}_experts_weights[word + 2u] & 255u), f32({{ qw }}_experts_weights[word + 3u] & 255u));
 
 
 
 
61
  {% endif %}
62
  {% if not colWiseScales %}
63
  let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
@@ -66,9 +77,15 @@ fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
66
  {% endif %}
67
  return (codes - vec4<f32>(MIDPOINT)) * scale;
68
  }
 
69
 
70
  const KVEC: u32 = {{ groupTileKVec }}u;
71
- {% macro stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, guarded, bLoadVec4="", b2LoadVec4="", aLoadVec4="") %}
 
 
 
 
 
72
  for (var idx = tid; idx < MTILE * KVEC; idx = idx + THREADS) {
73
  let m = idx / KVEC;
74
  let kb = (idx % KVEC) * 4u;
@@ -85,9 +102,51 @@ const KVEC: u32 = {{ groupTileKVec }}u;
85
  {% endif %}
86
  a_tile[idx] = a_vec;
87
  }
88
- for (var idx = tid; idx < NTILE * KVEC; idx = idx + THREADS) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  let n = idx / KVEC;
90
  let kb = (idx % KVEC) * 4u;
 
91
  let col = n_base + n;
92
  {% if guarded %}
93
  let col_live = col < {{ nExtent }};
@@ -115,16 +174,22 @@ const KVEC: u32 = {{ groupTileKVec }}u;
115
  }
116
  {% endfor %}
117
  {% endif %}
118
- b_tile[idx] = b_vec;
119
  {% if b2Load %}
120
- b2_tile[idx] = b2_vec;
121
  {% endif %}
122
- }{% endmacro %}
123
 
124
- {% macro group_tile_loop(aLoad, bLoad, b2Load, kExtent, nExtent, regM, regN, bLoadVec4="", b2LoadVec4="", aLoadVec4="") %}
125
  {% for r in range(regM) %}
126
  {% for c in range(regN) %}
127
  var acc_{{ r }}_{{ c }} = 0.0;
 
 
 
 
 
 
128
  {% endfor %}
129
  {% endfor %}
130
 
@@ -141,26 +206,67 @@ const KVEC: u32 = {{ groupTileKVec }}u;
141
  break;
142
  }
143
  if (n_full && k_base + KTILE <= {{ kExtent }}) {
144
- {{ stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, false, bLoadVec4, b2LoadVec4, aLoadVec4) }}
145
  } else {
146
- {{ stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, true) }}
147
  }
148
  workgroupBarrier();
149
 
 
 
 
 
 
 
 
 
 
150
  for (var kv = 0u; kv < KVEC; kv = kv + 1u) {
 
151
  {% for r in range(regM) %}
152
  let a{{ r }} = a_tile[(lid.y * {{ regM }}u + {{ r }}u) * KVEC + kv];
153
  {% endfor %}
154
- {% for c in range(regN) %}
155
- let b{{ c }} = b_tile[(lid.x * {{ regN }}u + {{ c }}u) * KVEC + kv];
 
 
 
 
 
 
 
 
156
  {% endfor %}
157
  {% for r in range(regM) %}
158
  {% for c in range(regN) %}
159
- acc_{{ r }}_{{ c }} = acc_{{ r }}_{{ c }} + dot(a{{ r }}, b{{ c }});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  {% endfor %}
161
  {% endfor %}
162
  }
163
- // Orders this step's tile reads before the next step overwrites them.
 
 
 
 
 
 
 
 
164
  workgroupBarrier();
165
  k_base = k_base + KTILE;
166
  }{% endmacro %}
@@ -168,9 +274,18 @@ var<workgroup> row_slot: array<u32, {{ groupTileM }}>;
168
  var<workgroup> a_tile: array<vec4<f32>, {{ groupTileM * groupTileKVec }}>;
169
  var<workgroup> b_tile: array<vec4<f32>, {{ groupTileN * groupTileKVec }}>;
170
 
 
 
 
 
 
 
 
 
171
  @compute @workgroup_size(THREADS_SIDE, THREADS_SIDE, 1)
172
  fn main(@builtin(workgroup_id) wid: vec3<u32>,
173
  @builtin(local_invocation_id) lid: vec3<u32>) {
 
174
  let tile = wid.x;
175
  if (tile >= tile_meta[0]) {
176
  return;
@@ -189,7 +304,7 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
189
  {{ group_tile_loop("hidden_act[row_slot[m] * INTER + k_base + k]",
190
  "fc2_weight(expert, col, k_base + k)",
191
  "", "INTER", "HIDDEN", regM, regN,
192
- "fc2_weight_vec4(expert, col, k_base + kb)") }}
193
 
194
  {% for r in range(regM) %}
195
  {% for c in range(regN) %}
 
1
+ {% if qmoeGroupedPin > 0 %}
2
+ enable subgroups;
3
+ enable subgroup_size_control;
4
+ {% endif %}
5
  {{ env.wgsl.resourceDeclarations }}
6
 
7
  // com.microsoft.QMoE, expert-grouped FC2 stage, sharing the tile loop with the grouped FC1
 
17
  const KTILE: u32 = {{ groupTileK }}u;
18
  const THREADS_SIDE: u32 = {{ groupThreads }}u;
19
  const THREADS: u32 = THREADS_SIDE * THREADS_SIDE;
20
+ {% if not expertQ4Vec4 or not groupWeightKMajor or not (groupWeightLaneInterleaved | default(false)) %}{% set needsWeightVec4 = true %}{% endif %}
21
+ {% set vectorWeights = weightVectorTransport | default(false) %}
22
  {% set qw = "fc2" %}
23
  {% set qwRows = "HIDDEN" %}
24
  {% set qwPackedCols = fc2PackedCols %}
25
  {% set qwBlocks = fc2ScaleBlocks %}
26
+ // Integer codes use the implicit midpoint 2^(bits-1) and low-first packing
27
+ // along each reduction row. Tensor bytes may use widened or packed transport.
 
28
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
29
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
30
  {% if not colWiseScales %}
 
 
31
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
32
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
33
  {% endif %}
34
 
35
+ {% set vectorWeights = vectorWeights is defined and vectorWeights %}
36
+ {% macro weight_byte(index) %}{% if vectorWeights %}{{ qw }}_experts_weights[({{ index }}) / 4u][({{ index }}) & 3u]{% else %}{{ qw }}_experts_weights[{{ index }}]{% endif %}{% endmacro %}
37
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
38
  let base = expert * {{ qwRows }} + row;
39
+ {% if packSize > 1 %}
40
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / " ~ packSize ~ "u") }};
41
+ let code = f32((word >> ((col % {{ packSize }}u) * {{ weightBits }}u)) & {{ 2 ** weightBits - 1 }}u);
42
  {% else %}
43
+ let code = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col") }} & 255u);
44
  {% endif %}
45
  {% if not colWiseScales %}
46
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
48
  return (code - MIDPOINT) * {{ qw }}_scales[base];
49
  {% endif %}
50
  }
51
+ {% if needsWeightVec4 is defined %}
52
+ // Aligned four-code groups share a scale: block sizes are multiples of sixteen.
 
53
  fn {{ qw }}_weight_vec4(expert: u32, row: u32, col: u32) -> vec4<f32> {
54
  let base = expert * {{ qwRows }} + row;
55
+ {% if packSize == 4 %}
56
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / 4u") }};
57
+ let codes = vec4<f32>((vec4<u32>(word) >> vec4<u32>(0u, 2u, 4u, 6u)) & vec4<u32>(3u));
58
+ {% elif packSize == 2 %}
59
  let pair = base * {{ qw | upper }}_PACKED_COLS + col / 2u;
60
+ let w0 = {{ weight_byte("pair") }};
61
+ let w1 = {{ weight_byte("pair + 1u") }};
62
  let codes = vec4<f32>(f32(w0 & 15u), f32((w0 >> 4u) & 15u),
63
  f32(w1 & 15u), f32((w1 >> 4u) & 15u));
64
  {% else %}
65
  let word = base * {{ qw | upper }}_PACKED_COLS + col;
66
+ {% if vectorWeights %}
67
+ let codes = vec4<f32>({{ qw }}_experts_weights[word / 4u] & vec4<u32>(255u));
68
+ {% else %}
69
+ let codes = vec4<f32>(f32({{ weight_byte("word") }} & 255u), f32({{ weight_byte("word + 1u") }} & 255u),
70
+ f32({{ weight_byte("word + 2u") }} & 255u), f32({{ weight_byte("word + 3u") }} & 255u));
71
+ {% endif %}
72
  {% endif %}
73
  {% if not colWiseScales %}
74
  let scale = {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
77
  {% endif %}
78
  return (codes - vec4<f32>(MIDPOINT)) * scale;
79
  }
80
+ {% endif %}
81
 
82
  const KVEC: u32 = {{ groupTileKVec }}u;
83
+ {% macro stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, guarded, bLoadVec4="", b2LoadVec4="", aLoadVec4="", bKMajor=false, bLaneInterleaved=false, regN=1, staticK=false, bStageInterleaved=false, packedStreams=[]) %}{% set bStoreIndex =
84
+ "idx" if bStageInterleaved and bKMajor and bLaneInterleaved else
85
+ ("(idx % KVEC) * NTILE + n / " ~ regN ~ "u + (n % " ~ regN ~ "u) * " ~ ((groupTileN / regN) | int) ~ "u")
86
+ if bKMajor and bLaneInterleaved and regN > 1
87
+ else ("(idx % KVEC) * NTILE + idx / KVEC" if bKMajor else "idx")
88
+ %}
89
  for (var idx = tid; idx < MTILE * KVEC; idx = idx + THREADS) {
90
  let m = idx / KVEC;
91
  let kb = (idx % KVEC) * 4u;
 
102
  {% endif %}
103
  a_tile[idx] = a_vec;
104
  }
105
+ {% if packedStreams and not guarded and bKMajor and bLaneInterleaved %}
106
+ // Stage columns in shared-memory lane order for contiguous constant-K stores.
107
+ for (var slot = tid; slot < NTILE; slot = slot + THREADS) {
108
+ let local_col = (slot % THREADS_SIDE) * {{ regN }}u + slot / THREADS_SIDE;
109
+ let col = n_base + local_col;
110
+ {% if packedStreams[0].packing == "word32" %}
111
+ {% for stream in packedStreams %}
112
+ let {{ stream.prefix }}_packed = {{ stream.buffer }}[col * ({{ kExtent }} / 32u) + k_base / 32u];
113
+ let {{ stream.prefix }}_scale = f32({{ stream.scales }}[col * {{ stream.scaleBlocks }} + k_base / {{ stream.quantBlock }}]);
114
+ {% endfor %}
115
+ {% for chunk in range(8) %}
116
+ {% for stream in packedStreams %}
117
+ let {{ stream.prefix }}_word{{ chunk }} = {{ stream.prefix }}_packed[{{ (chunk / 2) | int }}] >> {{ (chunk % 2) * 16 }}u;
118
+ let {{ stream.prefix }}_values{{ chunk }} = (vec4<f32>((vec4<u32>({{ stream.prefix }}_word{{ chunk }}) >> vec4<u32>(0u, 4u, 8u, 12u)) & vec4<u32>({{ stream.mask }})) - vec4<f32>({{ stream.zero }})) * {{ stream.prefix }}_scale;
119
+ {{ stream.destination }}[{{ chunk }}u * NTILE + slot] = {{ stream.prefix }}_values{{ chunk }};
120
+ {% endfor %}
121
+ {% endfor %}
122
+ {% else %}
123
+ {% for block in range(groupTileK // 8) %}
124
+ {% for stream in packedStreams %}
125
+ let {{ stream.prefix }}_row{{ block }} = expert * {{ stream.rows }} + {{ stream.row }};
126
+ let {{ stream.prefix }}_packed{{ block }} = {{ stream.buffer }}[{{ stream.prefix }}_row{{ block }} * {{ stream.packedCols // 4 }}u + (k_base + {{ block * 8 }}u) / 8u];
127
+ let {{ stream.prefix }}_scale{{ block }} = {{ stream.scales }}[{{ stream.prefix }}_row{{ block }}{% if not stream.columnScales %} * {{ stream.scaleBlocks }}u + (k_base + {{ block * 8 }}u) / {{ stream.quantBlock }}{% endif %}];
128
+ {% for chunk in range(2) %}
129
+ {% if stream.packing == "word8" %}
130
+ let {{ stream.prefix }}_codes{{ block }}_{{ chunk }} = (vec4<u32>({{ stream.prefix }}_packed{{ block }}) >> vec4<u32>({{ chunk * 16 }}u, {{ chunk * 16 + 4 }}u, {{ chunk * 16 + 8 }}u, {{ chunk * 16 + 12 }}u)) & vec4<u32>(15u);
131
+ {% else %}
132
+ let {{ stream.prefix }}_bytes{{ block }}_{{ chunk }} = {{ stream.prefix }}_packed{{ block }}.{{ 'xy' if chunk == 0 else 'zw' }};
133
+ let {{ stream.prefix }}_codes{{ block }}_{{ chunk }} = vec4<u32>({{ stream.prefix }}_bytes{{ block }}_{{ chunk }}.x, {{ stream.prefix }}_bytes{{ block }}_{{ chunk }}.x >> 4u, {{ stream.prefix }}_bytes{{ block }}_{{ chunk }}.y, {{ stream.prefix }}_bytes{{ block }}_{{ chunk }}.y >> 4u) & vec4<u32>(15u);
134
+ {% endif %}
135
+ {{ stream.destination }}[{{ block * 2 + chunk }}u * NTILE + slot] = (vec4<f32>({{ stream.prefix }}_codes{{ block }}_{{ chunk }}) - vec4<f32>({{ stream.zero }})) * {{ stream.prefix }}_scale{{ block }};
136
+ {% endfor %}
137
+ {% endfor %}
138
+ {% endfor %}
139
+ {% endif %}
140
+ }
141
+ {% else %} for (var idx = tid; idx < NTILE * KVEC; idx = idx + THREADS) {
142
+ {% if bStageInterleaved and bKMajor and bLaneInterleaved %}
143
+ let slot = idx % NTILE;
144
+ let n = (slot % THREADS_SIDE) * {{ regN }}u + slot / THREADS_SIDE;
145
+ let kb = (idx / NTILE) * 4u;
146
+ {% else %}
147
  let n = idx / KVEC;
148
  let kb = (idx % KVEC) * 4u;
149
+ {% endif %}
150
  let col = n_base + n;
151
  {% if guarded %}
152
  let col_live = col < {{ nExtent }};
 
174
  }
175
  {% endfor %}
176
  {% endif %}
177
+ b_tile[{{ bStoreIndex }}] = b_vec;
178
  {% if b2Load %}
179
+ b2_tile[{{ bStoreIndex }}] = b2_vec;
180
  {% endif %}
181
+ }{% endif %}{% endmacro %}
182
 
183
+ {% macro group_tile_loop(aLoad, bLoad, b2Load, kExtent, nExtent, regM, regN, bLoadVec4="", b2LoadVec4="", aLoadVec4="", scalarFma=false, bKMajor=false, bLaneInterleaved=false, staticK=false, bStageInterleaved=false, packedStreams=[], foldStage=false, refinePair=false) %}{% set foldStage = foldStage or refinePair %}{% set accum2 = "chunk2" if refinePair else "acc2" %}{% set accum = "chunk" if foldStage else "acc" %}
184
  {% for r in range(regM) %}
185
  {% for c in range(regN) %}
186
  var acc_{{ r }}_{{ c }} = 0.0;
187
+ {% if b2Load %}
188
+ var acc2_{{ r }}_{{ c }} = 0.0;
189
+ {% endif %}
190
+ {% if refinePair %}{% for stream in ["", "2"] %}
191
+ var mass{{ stream }}_{{ r }}_{{ c }} = 0.0;
192
+ {% endfor %}{% endif %}
193
  {% endfor %}
194
  {% endfor %}
195
 
 
206
  break;
207
  }
208
  if (n_full && k_base + KTILE <= {{ kExtent }}) {
209
+ {{ stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, false, bLoadVec4, b2LoadVec4, aLoadVec4, bKMajor, bLaneInterleaved, regN, staticK, bStageInterleaved, packedStreams) }}
210
  } else {
211
+ {{ stage_group_tiles(aLoad, bLoad, b2Load, kExtent, nExtent, true, bKMajor=bKMajor, bLaneInterleaved=bLaneInterleaved, regN=regN, staticK=staticK, bStageInterleaved=bStageInterleaved, packedStreams=packedStreams) }}
212
  }
213
  workgroupBarrier();
214
 
215
+ {% if foldStage %}{% for r in range(regM) %}{% for c in range(regN) %}
216
+ var chunk_{{ r }}_{{ c }} = 0.0;
217
+ {% if refinePair %} var chunk2_{{ r }}_{{ c }} = 0.0;
218
+ {% endif %}
219
+ {% endfor %}{% endfor %}{% endif %}{% for staticKv in (range(groupTileKVec) if staticK else [-1]) %}
220
+ {% if staticK %}
221
+ {
222
+ const kv: u32 = {{ staticKv }}u;
223
+ {% else %}
224
  for (var kv = 0u; kv < KVEC; kv = kv + 1u) {
225
+ {% endif %}
226
  {% for r in range(regM) %}
227
  let a{{ r }} = a_tile[(lid.y * {{ regM }}u + {{ r }}u) * KVEC + kv];
228
  {% endfor %}
229
+ {% for c in range(regN) %}{% set bReadIndex =
230
+ ("kv * NTILE + lid.x + " ~ ((c * groupTileN / regN) | int) ~ "u")
231
+ if bKMajor and bLaneInterleaved and regN > 1
232
+ else (("kv * NTILE + lid.x * " ~ regN ~ "u + " ~ c ~ "u") if bKMajor
233
+ else ("(lid.x * " ~ regN ~ "u + " ~ c ~ "u) * KVEC + kv"))
234
+ %}
235
+ let b{{ c }} = b_tile[{{ bReadIndex }}];
236
+ {% if b2Load %}
237
+ let s{{ c }} = b2_tile[{{ bReadIndex }}];
238
+ {% endif %}
239
  {% endfor %}
240
  {% for r in range(regM) %}
241
  {% for c in range(regN) %}
242
+ {% if scalarFma %}
243
+ {% for component in ['x', 'y', 'z', 'w'] %}
244
+ {{ accum }}_{{ r }}_{{ c }} = fma(a{{ r }}.{{ component }}, b{{ c }}.{{ component }}, {{ accum }}_{{ r }}_{{ c }});
245
+ {% endfor %}
246
+ {% else %}
247
+ {{ accum }}_{{ r }}_{{ c }} = {{ accum }}_{{ r }}_{{ c }} + dot(a{{ r }}, b{{ c }});
248
+ {% endif %}
249
+ {% if b2Load %}
250
+ {% if scalarFma %}
251
+ {% for component in ['x', 'y', 'z', 'w'] %}
252
+ {{ accum2 }}_{{ r }}_{{ c }} = fma(a{{ r }}.{{ component }}, s{{ c }}.{{ component }}, {{ accum2 }}_{{ r }}_{{ c }});
253
+ {% endfor %}
254
+ {% else %}
255
+ {{ accum2 }}_{{ r }}_{{ c }} = {{ accum2 }}_{{ r }}_{{ c }} + dot(a{{ r }}, s{{ c }});
256
+ {% endif %}
257
+ {% endif %}
258
  {% endfor %}
259
  {% endfor %}
260
  }
261
+ {% endfor %}
262
+ {% if foldStage %}{% for r in range(regM) %}{% for c in range(regN) %}
263
+ {% if refinePair %}{% for stream in ["", "2"] %}{% set id = stream ~ "_" ~ r ~ "_" ~ c %}
264
+ mass{{ id }} += abs(chunk{{ id }});
265
+ acc{{ id }} += chunk{{ id }};
266
+ {% endfor %}{% else %}
267
+ acc_{{ r }}_{{ c }} += chunk_{{ r }}_{{ c }};
268
+ {% endif %}
269
+ {% endfor %}{% endfor %}{% endif %} // Orders this step's tile reads before the next step overwrites them.
270
  workgroupBarrier();
271
  k_base = k_base + KTILE;
272
  }{% endmacro %}
 
274
  var<workgroup> a_tile: array<vec4<f32>, {{ groupTileM * groupTileKVec }}>;
275
  var<workgroup> b_tile: array<vec4<f32>, {{ groupTileN * groupTileKVec }}>;
276
 
277
+ {% set groupSubgroupSize = qmoeGroupedPin %}
278
+ {% set groupSubgroupSize = groupSubgroupSize | default(0) %}
279
+ {% if groupSubgroupSize > 0 %}
280
+ @compute @workgroup_size(THREADS, 1, 1) @subgroup_size({{ groupSubgroupSize }})
281
+ fn main(@builtin(workgroup_id) wid: vec3<u32>,
282
+ @builtin(local_invocation_index) local_index: u32) {
283
+ let lid = vec3<u32>(local_index % THREADS_SIDE, local_index / THREADS_SIDE, 0u);
284
+ {% else %}
285
  @compute @workgroup_size(THREADS_SIDE, THREADS_SIDE, 1)
286
  fn main(@builtin(workgroup_id) wid: vec3<u32>,
287
  @builtin(local_invocation_id) lid: vec3<u32>) {
288
+ {% endif %}
289
  let tile = wid.x;
290
  if (tile >= tile_meta[0]) {
291
  return;
 
304
  {{ group_tile_loop("hidden_act[row_slot[m] * INTER + k_base + k]",
305
  "fc2_weight(expert, col, k_base + k)",
306
  "", "INTER", "HIDDEN", regM, regN,
307
+ "fc2_weight_vec4(expert, col, k_base + kb)", "", "", (expertF32Schedule or scalarQuantAccum), bKMajor=groupWeightKMajor, bLaneInterleaved=groupWeightLaneInterleaved | default(false), staticK=expertF32Schedule, bStageInterleaved=expertF32Schedule, packedStreams=([{'packing':('word8' if packedWeights else 'byte8'),'prefix':'out','buffer':'fc2_experts_weights','scales':'fc2_scales','rows':'HIDDEN','row':'col','packedCols':fc2PackedCols,'scaleBlocks':fc2ScaleBlocks,'destination':'b_tile','columnScales':colWiseScales,'quantBlock':'QUANT_BLOCK','zero':'MIDPOINT'}] if expertQ4Vec4 else [])) }}
308
 
309
  {% for r in range(regM) %}
310
  {% for c in range(regN) %}
build/webgpu/qmoe-output-stage.wgsl.jinja CHANGED
@@ -1,29 +1,41 @@
1
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
- let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}
 
6
  {{ env.wgsl.resourceDeclarations }}
7
- {% set dotType = "f32" %}
8
- // Retain product and addition residuals across a dot product. Explicit fma
9
  // boundaries preserve the addition error transform under reassociation.
10
  struct DotAccumulator {
11
  hi: {{ dotType }},
12
  lo: {{ dotType }},
13
  }
14
- fn dot_accumulate(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {
15
  let product = fma(a, b, {{ dotType }}(0.0));
16
- let productError = fma(a, b, -product);
17
- let sum = fma(acc.hi, {{ dotType }}(1.0), product);
18
- let bv = fma({{ dotType }}(-1.0), acc.hi, sum);
 
 
 
 
 
 
 
 
 
19
  let av = fma({{ dotType }}(-1.0), bv, sum);
20
  let ae = fma({{ dotType }}(-1.0), av, acc.hi);
21
  let be = fma({{ dotType }}(-1.0), bv, product);
22
  let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);
23
  let hi = fma(sum, {{ dotType }}(1.0), error);
24
- return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));
 
 
 
25
  }
26
- fn dot_value(acc: DotAccumulator) -> {{ dotType }} {
27
  return fma(acc.hi, {{ dotType }}(1.0), acc.lo);
28
  }
29
 
@@ -37,25 +49,23 @@ const TOP_K: u32 = {{ topK }}u;
37
  {% set qwRows = "HIDDEN" %}
38
  {% set qwPackedCols = fc2PackedCols %}
39
  {% set qwBlocks = fc2ScaleBlocks %}
40
- // Quantized expert weights use unsigned codes offset by 2^(bits-1), so a
41
- // weight is (code - MIDPOINT) * scale. Four-bit codes are packed low-nibble
42
- // first along the reduction axis, two codes per stored word.
43
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
44
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
45
  {% if not colWiseScales %}
46
- // Block-wise scales ({{ qw }}_scales rank 3): one scale per QUANT_BLOCK columns of the reduction
47
- // axis. Column-wise scales (block_size 0) are the rank-2 single-scale-per-row case below.
48
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
49
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
50
  {% endif %}
51
 
 
52
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
53
  let base = expert * {{ qwRows }} + row;
54
- {% if packSize == 2 %}
55
- let word = {{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col / 2u];
56
- let code = f32((word >> ((col & 1u) * 4u)) & 15u);
57
  {% else %}
58
- let code = f32({{ qw }}_experts_weights[base * {{ qw | upper }}_PACKED_COLS + col] & 255u);
59
  {% endif %}
60
  {% if not colWiseScales %}
61
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
 
1
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
+ let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
6
+ {% endmacro %}
7
  {{ env.wgsl.resourceDeclarations }}
8
+ {% set dotType = "f32" %}// Retain product and addition residuals across a dot product. Explicit fma
 
9
  // boundaries preserve the addition error transform under reassociation.
10
  struct DotAccumulator {
11
  hi: {{ dotType }},
12
  lo: {{ dotType }},
13
  }
14
+ {% macro dot_step(name, dotGuardNonfinite) %}fn {{ name }}(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {
15
  let product = fma(a, b, {{ dotType }}(0.0));
16
+ {% if dotGuardNonfinite | default(false) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);
17
+ // Nonfinite sums retain ordinary f32 addition classes; Inf-Inf residuals
18
+ // must not poison a valid infinite dot accumulator.
19
+ if (!(abs(acc.hi) <= 3.4028234663852886e38) ||
20
+ !(abs(acc.lo) <= 3.4028234663852886e38) ||
21
+ !(abs(product) <= 3.4028234663852886e38) ||
22
+ !(abs(sum) <= 3.4028234663852886e38)) {
23
+ return DotAccumulator(sum, {{ dotType }}(0.0));
24
+ }
25
+ {% endif %} let productError = fma(a, b, -product);
26
+ {% if not (dotGuardNonfinite | default(false)) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);
27
+ {% endif %} let bv = fma({{ dotType }}(-1.0), acc.hi, sum);
28
  let av = fma({{ dotType }}(-1.0), bv, sum);
29
  let ae = fma({{ dotType }}(-1.0), av, acc.hi);
30
  let be = fma({{ dotType }}(-1.0), bv, product);
31
  let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);
32
  let hi = fma(sum, {{ dotType }}(1.0), error);
33
+ {% if dotGuardNonfinite | default(false) %} if (!(abs(hi) <= 3.4028234663852886e38)) {
34
+ return DotAccumulator(hi, {{ dotType }}(0.0));
35
+ }
36
+ {% endif %} return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));
37
  }
38
+ {% endmacro %}{{ dot_step("dot_accumulate", dotGuardNonfinite | default(false)) }}fn dot_value(acc: DotAccumulator) -> {{ dotType }} {
39
  return fma(acc.hi, {{ dotType }}(1.0), acc.lo);
40
  }
41
 
 
49
  {% set qwRows = "HIDDEN" %}
50
  {% set qwPackedCols = fc2PackedCols %}
51
  {% set qwBlocks = fc2ScaleBlocks %}
52
+ // Integer codes use the implicit midpoint 2^(bits-1) and low-first packing
53
+ // along each reduction row. Tensor bytes may use widened or packed transport.
 
54
  const MIDPOINT: f32 = f32({{ quantMidpoint }});
55
  const {{ qw | upper }}_PACKED_COLS: u32 = {{ qwPackedCols }}u;
56
  {% if not colWiseScales %}
 
 
57
  const QUANT_BLOCK: u32 = {{ quantBlockSize }}u;
58
  const {{ qw | upper }}_BLOCKS: u32 = {{ qwBlocks }}u;
59
  {% endif %}
60
 
61
+ {% macro weight_byte(index) %}{{ qw }}_experts_weights[{{ index }}]{% endmacro %}
62
  fn {{ qw }}_weight(expert: u32, row: u32, col: u32) -> f32 {
63
  let base = expert * {{ qwRows }} + row;
64
+ {% if packSize > 1 %}
65
+ let word = {{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col / " ~ packSize ~ "u") }};
66
+ let code = f32((word >> ((col % {{ packSize }}u) * {{ weightBits }}u)) & {{ 2 ** weightBits - 1 }}u);
67
  {% else %}
68
+ let code = f32({{ weight_byte("base * " ~ (qw | upper) ~ "_PACKED_COLS + col") }} & 255u);
69
  {% endif %}
70
  {% if not colWiseScales %}
71
  return (code - MIDPOINT) * {{ qw }}_scales[base * {{ qw | upper }}_BLOCKS + col / QUANT_BLOCK];
build/webgpu/qmoe-route-stage.wgsl.jinja CHANGED
@@ -1,11 +1,181 @@
1
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
6
  if ({{ name }} >= {{ bound }}) {
7
  return;
8
- }{% endmacro %}
 
9
  {{ env.wgsl.resourceDeclarations }}
10
 
11
  const EXPERTS: u32 = {{ experts }}u;
@@ -13,7 +183,7 @@ const WG: u32 = {{ workgroupSize }}u;
13
  {% if topK > 1 %}
14
  const TOP_K: u32 = {{ topK }}u;
15
  // Serial top-K selection in O(TOP_K * EXPERTS), followed by a stable softmax
16
- // over the selected logits. Equal logits select the higher expert index.
17
  struct TopKRoute {
18
  experts: array<u32, TOP_K>,
19
  weights: array<f32, TOP_K>,
@@ -46,13 +216,30 @@ fn topk_route(token: u32) -> TopKRoute {
46
  result.weights[j] = best_weight;
47
  }
48
 
49
- // QMoE without a separate router_weights input always applies softmax over
50
- // the selected top-k logits, independently of normalize_routing_weights.
51
  let max_logit = result.weights[0];
 
 
 
 
 
 
 
 
 
 
52
  var sum = 0.0;
 
 
 
 
 
53
  for (var j = 0u; j < TOP_K; j = j + 1u) {
54
  result.weights[j] = exp(result.weights[j] - max_logit);
 
55
  sum = sum + result.weights[j];
 
56
  }
57
  if (sum != 0.0) {
58
  for (var j = 0u; j < TOP_K; j = j + 1u) {
@@ -79,6 +266,19 @@ fn top1_route(token: u32) -> Top1Route {
79
  best_weight = candidate;
80
  }
81
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  return result;
83
  }
84
  {% endif %}
@@ -89,7 +289,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
89
 
90
  {% if topK > 1 %}
91
  // Slot j of each token's TOP_K-wide run holds its j-th ranked expert and
92
- // that expert's softmax weight within the selected set.
93
  let route = topk_route(token);
94
  for (var j = 0u; j < TOP_K; j = j + 1u) {
95
  route_expert[token * TOP_K + j] = route.experts[j];
@@ -102,3 +302,5 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
102
  route_mix[token] = route.weight;
103
  {% endif %}
104
  }
 
 
 
1
+ {% if parallelRoute %}
2
+ // Single-token parallel selection preserves descending-index ties and serial
3
+ // softmax summation. Nonfinite logits retain the serial selection order.
4
+ {{ env.wgsl.resourceDeclarations }}
5
+ const EXPERTS: u32 = {{ experts }}u;
6
+ const TOP_K: u32 = {{ topK }}u;
7
+ const LANES: u32 = {{ routeParallelLanes }}u;
8
+ var<workgroup> candidate_values: array<f32, {{ routeParallelLanes }}>;
9
+ var<workgroup> candidate_indices: array<u32, {{ routeParallelLanes }}>;
10
+ var<workgroup> selected_indices: array<u32, {{ topK }}>;
11
+ var<workgroup> selected_values: array<f32, {{ topK }}>;
12
+
13
+ var<workgroup> nonfinite_logits: atomic<u32>;
14
+ // Serial top-K selection in O(TOP_K * EXPERTS), followed by a stable softmax
15
+ // with the requested denominator. Equal logits select the higher expert index.
16
+ struct TopKRoute {
17
+ experts: array<u32, TOP_K>,
18
+ weights: array<f32, TOP_K>,
19
+ }
20
+
21
+ fn topk_route(token: u32) -> TopKRoute {
22
+ var result: TopKRoute;
23
+ for (var j = 0u; j < TOP_K; j = j + 1u) {
24
+ // EXPERTS is the "nothing picked yet" sentinel; the contract keeps TOP_K <= EXPERTS, so
25
+ // every pass finds an untaken expert and no slot can keep it.
26
+ var best_expert = EXPERTS;
27
+ var best_weight = 0.0;
28
+ for (var e = 0u; e < EXPERTS; e = e + 1u) {
29
+ var taken = false;
30
+ for (var p = 0u; p < j; p = p + 1u) {
31
+ if (result.experts[p] == e) {
32
+ taken = true;
33
+ }
34
+ }
35
+ if (!taken) {
36
+ let candidate = router_probs[token * EXPERTS + e];
37
+ if (best_expert == EXPERTS || candidate > best_weight ||
38
+ (candidate == best_weight && e > best_expert)) {
39
+ best_expert = e;
40
+ best_weight = candidate;
41
+ }
42
+ }
43
+ }
44
+ result.experts[j] = best_expert;
45
+ result.weights[j] = best_weight;
46
+ }
47
+
48
+ // The selected maximum is also the full-expert maximum. Subtract it in both
49
+ // modes to keep large finite logits from overflowing exp().
50
+ let max_logit = result.weights[0];
51
+ // Classify before subtraction: an infinite selected maximum has no finite
52
+ // shifted-softmax value. Preserve the route's NaN policy explicitly.
53
+ let max_logit_bits = bitcast<u32>(max_logit);
54
+ if ((max_logit_bits & 0x7f800000u) == 0x7f800000u) {
55
+ let nan_weight = bitcast<f32>(max_logit_bits | 0x7fc00000u);
56
+ for (var j = 0u; j < TOP_K; j = j + 1u) {
57
+ result.weights[j] = nan_weight;
58
+ }
59
+ return result;
60
+ }
61
+ var sum = 0.0;
62
+ {% if not normalizeRoutingWeights %}
63
+ for (var e = 0u; e < EXPERTS; e = e + 1u) {
64
+ sum = sum + exp(router_probs[token * EXPERTS + e] - max_logit);
65
+ }
66
+ {% endif %}
67
+ for (var j = 0u; j < TOP_K; j = j + 1u) {
68
+ result.weights[j] = exp(result.weights[j] - max_logit);
69
+ {% if normalizeRoutingWeights %}
70
+ sum = sum + result.weights[j];
71
+ {% endif %}
72
+ }
73
+ if (sum != 0.0) {
74
+ for (var j = 0u; j < TOP_K; j = j + 1u) {
75
+ result.weights[j] = result.weights[j] / sum;
76
+ }
77
+ }
78
+ return result;
79
+ }
80
+
81
+ @compute @workgroup_size(LANES)
82
+ fn main(@builtin(local_invocation_index) lane: u32) {
83
+ if (params.tokenCount != 1u) {
84
+ return;
85
+ }
86
+ if (lane == 0u) {
87
+ atomicStore(&nonfinite_logits, 0u);
88
+ }
89
+ workgroupBarrier();
90
+ for (var expert = lane; expert < EXPERTS; expert += LANES) {
91
+ if ((bitcast<u32>(router_probs[expert]) & 0x7f800000u) == 0x7f800000u) {
92
+ atomicOr(&nonfinite_logits, 1u);
93
+ }
94
+ }
95
+ workgroupBarrier();
96
+ if (lane == 0u) {
97
+ candidate_indices[0] = atomicLoad(&nonfinite_logits);
98
+ }
99
+ if (workgroupUniformLoad(&candidate_indices[0]) != 0u) {
100
+ if (lane == 0u) {
101
+ let route = topk_route(0u);
102
+ for (var rank = 0u; rank < TOP_K; rank++) {
103
+ route_expert[rank] = route.experts[rank];
104
+ route_mix[rank] = route.weights[rank];
105
+ }
106
+ }
107
+ return;
108
+ }
109
+ for (var rank = 0u; rank < TOP_K; rank++) {
110
+ var best_index = EXPERTS;
111
+ var best_value = 0.0;
112
+ for (var expert = lane; expert < EXPERTS; expert += LANES) {
113
+ var taken = false;
114
+ for (var previous = 0u; previous < rank; previous++) {
115
+ taken = taken || selected_indices[previous] == expert;
116
+ }
117
+ if (!taken) {
118
+ let value = router_probs[expert];
119
+ if (best_index == EXPERTS || value > best_value ||
120
+ (value == best_value && expert > best_index)) {
121
+ best_index = expert;
122
+ best_value = value;
123
+ }
124
+ }
125
+ }
126
+ candidate_values[lane] = best_value;
127
+ candidate_indices[lane] = best_index;
128
+ workgroupBarrier();
129
+ for (var stride = LANES / 2u; stride > 0u; stride /= 2u) {
130
+ if (lane < stride) {
131
+ let other_index = candidate_indices[lane + stride];
132
+ let other_value = candidate_values[lane + stride];
133
+ let own_index = candidate_indices[lane];
134
+ let own_value = candidate_values[lane];
135
+ if (other_index < EXPERTS && (own_index == EXPERTS ||
136
+ other_value > own_value || (other_value == own_value && other_index > own_index))) {
137
+ candidate_indices[lane] = other_index;
138
+ candidate_values[lane] = other_value;
139
+ }
140
+ }
141
+ workgroupBarrier();
142
+ }
143
+ if (lane == 0u) {
144
+ selected_indices[rank] = candidate_indices[0];
145
+ selected_values[rank] = candidate_values[0];
146
+ }
147
+ workgroupBarrier();
148
+ }
149
+ if (lane == 0u) {
150
+ let maximum = selected_values[0];
151
+ var denominator = 0.0;
152
+ {% if not normalizeRoutingWeights %}
153
+ for (var expert = 0u; expert < EXPERTS; expert++) {
154
+ denominator += exp(router_probs[expert] - maximum);
155
+ }
156
+ {% endif %}
157
+ for (var rank = 0u; rank < TOP_K; rank++) {
158
+ selected_values[rank] = exp(selected_values[rank] - maximum);
159
+ {% if normalizeRoutingWeights %}
160
+ denominator += selected_values[rank];
161
+ {% endif %}
162
+ }
163
+ for (var rank = 0u; rank < TOP_K; rank++) {
164
+ route_expert[rank] = selected_indices[rank];
165
+ route_mix[rank] = select(selected_values[rank], selected_values[rank] / denominator, denominator != 0.0);
166
+ }
167
+ }
168
+ }
169
+ {% else %}
170
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
171
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
172
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
173
  // per-axis workgroup fold width.
174
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
175
  if ({{ name }} >= {{ bound }}) {
176
  return;
177
+ }
178
+ {% endmacro %}
179
  {{ env.wgsl.resourceDeclarations }}
180
 
181
  const EXPERTS: u32 = {{ experts }}u;
 
183
  {% if topK > 1 %}
184
  const TOP_K: u32 = {{ topK }}u;
185
  // Serial top-K selection in O(TOP_K * EXPERTS), followed by a stable softmax
186
+ // with the requested denominator. Equal logits select the higher expert index.
187
  struct TopKRoute {
188
  experts: array<u32, TOP_K>,
189
  weights: array<f32, TOP_K>,
 
216
  result.weights[j] = best_weight;
217
  }
218
 
219
+ // The selected maximum is also the full-expert maximum. Subtract it in both
220
+ // modes to keep large finite logits from overflowing exp().
221
  let max_logit = result.weights[0];
222
+ // Classify before subtraction: an infinite selected maximum has no finite
223
+ // shifted-softmax value. Preserve the route's NaN policy explicitly.
224
+ let max_logit_bits = bitcast<u32>(max_logit);
225
+ if ((max_logit_bits & 0x7f800000u) == 0x7f800000u) {
226
+ let nan_weight = bitcast<f32>(max_logit_bits | 0x7fc00000u);
227
+ for (var j = 0u; j < TOP_K; j = j + 1u) {
228
+ result.weights[j] = nan_weight;
229
+ }
230
+ return result;
231
+ }
232
  var sum = 0.0;
233
+ {% if not normalizeRoutingWeights %}
234
+ for (var e = 0u; e < EXPERTS; e = e + 1u) {
235
+ sum = sum + exp(router_probs[token * EXPERTS + e] - max_logit);
236
+ }
237
+ {% endif %}
238
  for (var j = 0u; j < TOP_K; j = j + 1u) {
239
  result.weights[j] = exp(result.weights[j] - max_logit);
240
+ {% if normalizeRoutingWeights %}
241
  sum = sum + result.weights[j];
242
+ {% endif %}
243
  }
244
  if (sum != 0.0) {
245
  for (var j = 0u; j < TOP_K; j = j + 1u) {
 
266
  best_weight = candidate;
267
  }
268
  }
269
+ // Normalized top-1 is one only when the selected logit is finite.
270
+ let best_weight_bits = bitcast<u32>(best_weight);
271
+ if ((best_weight_bits & 0x7f800000u) == 0x7f800000u) {
272
+ result.weight = bitcast<f32>(best_weight_bits | 0x7fc00000u);
273
+ return result;
274
+ }
275
+ {% if not normalizeRoutingWeights %}
276
+ var sum = 0.0;
277
+ for (var e = 0u; e < EXPERTS; e += 1u) {
278
+ sum = sum + exp(router_probs[token * EXPERTS + e] - best_weight);
279
+ }
280
+ result.weight = 1.0 / sum;
281
+ {% endif %}
282
  return result;
283
  }
284
  {% endif %}
 
289
 
290
  {% if topK > 1 %}
291
  // Slot j of each token's TOP_K-wide run holds its j-th ranked expert and
292
+ // that expert's softmax weight with the requested normalization.
293
  let route = topk_route(token);
294
  for (var j = 0u; j < TOP_K; j = j + 1u) {
295
  route_expert[token * TOP_K + j] = route.experts[j];
 
302
  route_mix[token] = route.weight;
303
  {% endif %}
304
  }
305
+
306
+ {% endif %}
build/webgpu/test.json CHANGED
The diff for this file is too large to render. See raw diff