Xenova HF Staff commited on
Commit
155c41d
·
verified ·
1 Parent(s): 3eb68da

sync 4385228f788d

Browse files
README.md CHANGED
@@ -63,117 +63,72 @@ Attributes and default values (overridable per request):
63
 
64
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
65
 
66
- - `nchw2d_columns_x4` — Channel-first 2-D route without integer dot-product support: one invocation folds four adjacent output columns into a vec4 accumulator for up to four output channels, so each weight load serves sixteen products.
 
67
  - `dp4a_pointwise_nchw` — Channel-first 1x1 route: the convolution is exactly one integer GEMM whose A operand is the weight and whose B operand is the activation image, so the shared packed integer dot-product core runs with no materialized column matrix.
68
  - `matrix_pointwise_nchw` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
69
- - `dp4a_im2col_nchw` — Channel-first route that materializes the column matrix in `(ic, kh, kw)` order and hands it to the shared packed integer dot-product core as the B operand, with the weight as A.
70
  - `matrix_im2col_nchw` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
71
- - `dp4a_im2col_nchw_bias` — Channel-first route that materializes the column matrix in `(ic, kh, kw)` order and hands it to the shared packed integer dot-product core as the B operand, with the weight as A. A pre-quantized int32 bias is added per output channel before requantization.
72
- - `matrix_im2col_nchw_bias` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
73
- - `dp4a_pointwise_nhwc` — Channels-last 1x1 route: the activation is already the GEMM's row-major A operand, so only the weight is reordered into K-major `(kh, kw, ic)` columns for the shared packed integer dot-product core, whose output rows land as the channels-last image.
74
  - `matrix_pointwise_nhwc` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
75
- - `dp4a_pointwise_nhwc_bias` — Channels-last 1x1 route: the activation is already the GEMM's row-major A operand, so only the weight is reordered into K-major `(kh, kw, ic)` columns for the shared packed integer dot-product core, whose output rows land as the channels-last image. A pre-quantized int32 bias is added per output channel before requantization.
76
- - `matrix_pointwise_nhwc_bias` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
77
- - `dp4a_im2col_nhwc` — Channels-last general route: the activation is already the GEMM's row-major A operand, so only the weight is reordered into K-major `(kh, kw, ic)` columns for the shared packed integer dot-product core, whose output rows land as the channels-last image.
78
  - `matrix_im2col_nhwc` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
79
- - `dp4a_im2col_nhwc_bias` — Channels-last general route: the activation is already the GEMM's row-major A operand, so only the weight is reordered into K-major `(kh, kw, ic)` columns for the shared packed integer dot-product core, whose output rows land as the channels-last image. A pre-quantized int32 bias is added per output channel before requantization.
80
- - `matrix_im2col_nhwc_bias` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
81
- - `precast_f16_pointwise_nchw_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
82
- - `portable_f16_pointwise_nchw_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
83
- - `precast_f16_pointwise_nchw_row` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
84
- - `portable_f16_pointwise_nchw_row` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
85
- - `precast_f16_im2col_nchw_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
86
- - `portable_f16_im2col_nchw_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
87
- - `precast_f16_im2col_nchw_row` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
88
- - `portable_f16_im2col_nchw_row` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
89
- - `precast_f16_im2col_nchw_bias_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
90
- - `portable_f16_im2col_nchw_bias_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
91
- - `precast_f16_im2col_nchw_bias_row` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
92
- - `portable_f16_im2col_nchw_bias_row` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
93
- - `precast_f16_pointwise_nhwc_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
94
- - `portable_f16_pointwise_nhwc_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
95
- - `precast_f16_pointwise_nhwc_column` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
96
- - `portable_f16_pointwise_nhwc_column` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
97
- - `precast_f16_pointwise_nhwc_bias_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
98
- - `portable_f16_pointwise_nhwc_bias_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
99
- - `precast_f16_pointwise_nhwc_bias_column` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
100
- - `portable_f16_pointwise_nhwc_bias_column` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
101
- - `precast_f16_im2col_nhwc_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
102
- - `portable_f16_im2col_nhwc_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
103
- - `precast_f16_im2col_nhwc_column` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
104
- - `portable_f16_im2col_nhwc_column` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
105
- - `precast_f16_im2col_nhwc_bias_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
106
- - `portable_f16_im2col_nhwc_bias_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
107
- - `precast_f16_im2col_nhwc_bias_column` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
108
- - `portable_f16_im2col_nhwc_bias_column` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
109
- - `precast_f32_pointwise_nchw_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
110
- - `portable_f32_pointwise_nchw_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
111
- - `precast_f32_pointwise_nchw_row` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
112
- - `portable_f32_pointwise_nchw_row` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
113
- - `precast_f32_im2col_nchw_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
114
- - `portable_f32_im2col_nchw_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
115
- - `precast_f32_im2col_nchw_row` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
116
- - `portable_f32_im2col_nchw_row` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
117
- - `precast_f32_im2col_nchw_bias_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
118
- - `portable_f32_im2col_nchw_bias_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
119
- - `precast_f32_im2col_nchw_bias_row` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
120
- - `portable_f32_im2col_nchw_bias_row` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
121
- - `precast_f32_pointwise_nhwc_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
122
- - `portable_f32_pointwise_nhwc_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
123
- - `precast_f32_pointwise_nhwc_column` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
124
- - `portable_f32_pointwise_nhwc_column` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
125
- - `precast_f32_pointwise_nhwc_bias_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
126
- - `portable_f32_pointwise_nhwc_bias_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
127
- - `precast_f32_pointwise_nhwc_bias_column` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
128
- - `portable_f32_pointwise_nhwc_bias_column` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
129
- - `precast_f32_im2col_nhwc_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
130
- - `portable_f32_im2col_nhwc_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
131
- - `precast_f32_im2col_nhwc_column` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
132
- - `portable_f32_im2col_nhwc_column` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
133
- - `precast_f32_im2col_nhwc_bias_tensor` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
134
- - `portable_f32_im2col_nhwc_bias_tensor` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
135
- - `precast_f32_im2col_nhwc_bias_column` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both component tiers use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use the other routes.
136
- - `portable_f32_im2col_nhwc_bias_column` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
137
 
138
  ## Device requirements
139
 
140
- Some implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.
141
 
142
  ## Files
143
 
144
- - [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)
145
- - [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)
146
- - [`test.json`](build/webgpu/test.json) — correctness cases
147
- - [`bench.json`](build/webgpu/bench.json) — benchmark cases
148
- - [`conv-int-accumulate-spatial.wgsl.jinja`](build/webgpu/conv-int-accumulate-spatial.wgsl.jinja)
149
- - [`conv-int-im2col-spatial.wgsl.jinja`](build/webgpu/conv-int-im2col-spatial.wgsl.jinja)
150
- - [`qlinear-conv-im2col-nhwc.wgsl.jinja`](build/webgpu/qlinear-conv-im2col-nhwc.wgsl.jinja)
151
- - [`qlinear-conv-nchw-x4.wgsl.jinja`](build/webgpu/qlinear-conv-nchw-x4.wgsl.jinja)
152
- - [`qlinear-conv-nhwc-oc4.wgsl.jinja`](build/webgpu/qlinear-conv-nhwc-oc4.wgsl.jinja)
153
- - [`qlinear-conv-requantize.wgsl.jinja`](build/webgpu/qlinear-conv-requantize.wgsl.jinja)
154
- - [`quant-dp4a-matmul.wgsl.jinja`](build/webgpu/quant-dp4a-matmul.wgsl.jinja)
155
- - [`quant-exact-matrix.wgsl.jinja`](build/webgpu/quant-exact-matrix.wgsl.jinja)
156
- - [`quant-exact-portable.wgsl.jinja`](build/webgpu/quant-exact-portable.wgsl.jinja)
157
- - [`quant-exact-prepare.wgsl.jinja`](build/webgpu/quant-exact-prepare.wgsl.jinja)
158
- - [`quant-weight-k-major.wgsl.jinja`](build/webgpu/quant-weight-k-major.wgsl.jinja)
 
159
 
160
  ## Use with `@huggingface/kernels`
161
 
162
  ```sh
163
- npm install --save-exact @huggingface/kernels@0.0.1-preview.3
164
  ```
165
 
 
 
166
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
167
 
168
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
169
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
170
 
171
- Replace each `*Data` placeholder with a typed array containing the corresponding input data.
172
-
173
  ```js
174
  import { getKernel } from "@huggingface/kernels";
175
 
176
  const kernel = await getKernel("webgpu-kernels/com.microsoft.QLinearConv", { version: 1 });
 
 
 
 
 
 
 
 
 
 
177
  const { y } = await kernel({
178
  x: { data: xData, shape: [1, 1, 1, 1] },
179
  x_scale: { data: x_scaleData, shape: [1] },
@@ -184,4 +139,5 @@ const { y } = await kernel({
184
  y_scale: { data: y_scaleData, shape: [1] },
185
  y_zero_point: { data: y_zero_pointData, shape: [1] },
186
  });
 
187
  ```
 
63
 
64
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
65
 
66
+ - `nchw2d_columns_x4` — Channel-first 2-D variant without integer dot-product support: one invocation folds four adjacent output columns into a vec4 accumulator for up to four output channels, so each weight load serves sixteen products.
67
+ - `nhwc2d_x4` — Channels-last 2-D variant: one invocation folds a tile of output columns for four adjacent output channels, either grouped (each group's channels a multiple of four) or depthwise, with an optional pre-quantized int32 bias.
68
  - `dp4a_pointwise_nchw` — Channel-first 1x1 route: the convolution is exactly one integer GEMM whose A operand is the weight and whose B operand is the activation image, so the shared packed integer dot-product core runs with no materialized column matrix.
69
  - `matrix_pointwise_nchw` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
70
+ - `dp4a_im2col_nchw` — Channel-first route that materializes the column matrix in `(ic, kh, kw)` order and hands it to the shared packed integer dot-product core as the B operand, with the weight as A. An optional pre-quantized int32 bias is added per output channel before requantization.
71
  - `matrix_im2col_nchw` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
72
+ - `dp4a_pointwise_nhwc` — Channels-last 1x1 route: the activation is already the GEMM's row-major A operand, so only the weight is reordered into K-major `(kh, kw, ic)` columns for the shared packed integer dot-product core, whose output rows land as the channels-last image. An optional pre-quantized int32 bias is added per output channel before requantization.
 
 
73
  - `matrix_pointwise_nhwc` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
74
+ - `dp4a_im2col_nhwc` — Channels-last general route: an im2col pass gathers the activation into a `(kh, kw, ic)` column matrix padded in K to a multiple of four, with padding taps holding the input zero point. The weight is reordered into K-major columns for the shared packed integer dot-product core. An optional int32 bias is added per output channel before requantization.
 
 
75
  - `matrix_im2col_nhwc` — Exact subgroup-matrix convolution using the same operand preparation. Bounded f32 partial dots preserve byte-integer products; int32 partial accumulation, optional bias and compensated requantization preserve output quantization. Small grids and short contractions use the packed integer kernels.
76
+ - `precast_f16` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both the `f16` and `f32` operand versions use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use other variants.
77
+ - `portable_f16` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
78
+ - `precast_f32` — Fuse spatial sampling, weight layout and exact byte centering into padded matrix operands. Both the `f16` and `f32` operand versions use bounded `f32` partial dots and `int32` totals before compensated requantization; `f16` exactly represents `[-255, 255]`. Tiles follow device limits, and small workloads use other variants.
79
+ - `portable_f32` — Reuse fused exact byte preparation with a portable vector GEMM. Each workgroup computes a device-bounded tile with bounded exact f32 partial dots, int32 totals, optional per-channel bias and compensated requantization. Exact f16 operand storage is used when supported; f32 requires no optional arithmetic features.
80
+ - `subgroup_matrix_16x16x16_precast` — `16x16x16` subgroup matrices consume exact centered byte values stored in f16. Bounded f32 partial dots become wrapping int32 totals before bias and compensated requantization. If the subgroups are not laid out as expected, a fallback path in the same kernel does the same arithmetic without subgroup matrices.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  ## Device requirements
83
 
84
+ Some implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.
85
 
86
  ## Files
87
 
88
+ - [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)
89
+ - [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)
90
+ - [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/test.json) — correctness cases
91
+ - [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/bench.json) — benchmark cases
92
+ - [`conv-int-accumulate-spatial.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/conv-int-accumulate-spatial.wgsl.jinja)
93
+ - [`conv-int-im2col-spatial.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/conv-int-im2col-spatial.wgsl.jinja)
94
+ - [`matrix-shaped-exact-precast.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/matrix-shaped-exact-precast.wgsl.jinja)
95
+ - [`qlinear-conv-im2col-nhwc.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/qlinear-conv-im2col-nhwc.wgsl.jinja)
96
+ - [`qlinear-conv-nchw-x4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/qlinear-conv-nchw-x4.wgsl.jinja)
97
+ - [`qlinear-conv-nhwc-oc4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/qlinear-conv-nhwc-oc4.wgsl.jinja)
98
+ - [`qlinear-conv-requantize.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/qlinear-conv-requantize.wgsl.jinja)
99
+ - [`quant-dp4a-matmul.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-dp4a-matmul.wgsl.jinja)
100
+ - [`quant-exact-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-exact-matrix.wgsl.jinja)
101
+ - [`quant-exact-portable.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-exact-portable.wgsl.jinja)
102
+ - [`quant-exact-prepare.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-exact-prepare.wgsl.jinja)
103
+ - [`quant-weight-k-major.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-weight-k-major.wgsl.jinja)
104
 
105
  ## Use with `@huggingface/kernels`
106
 
107
  ```sh
108
+ npm install --save-exact @huggingface/kernels@0.0.1-preview.4
109
  ```
110
 
111
+ Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.
112
+
113
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
114
 
115
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
116
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
117
 
 
 
118
  ```js
119
  import { getKernel } from "@huggingface/kernels";
120
 
121
  const kernel = await getKernel("webgpu-kernels/com.microsoft.QLinearConv", { version: 1 });
122
+
123
+ const xData = Uint8Array.of(1);
124
+ const x_scaleData = Float32Array.of(1);
125
+ const x_zero_pointData = new Uint8Array(1);
126
+ const wData = Int8Array.of(1, -1);
127
+ const w_scaleData = Float32Array.of(1);
128
+ const w_zero_pointData = new Int8Array(1);
129
+ const y_scaleData = Float32Array.of(1e-20);
130
+ const y_zero_pointData = Uint8Array.of(128);
131
+
132
  const { y } = await kernel({
133
  x: { data: xData, shape: [1, 1, 1, 1] },
134
  x_scale: { data: x_scaleData, shape: [1] },
 
139
  y_scale: { data: y_scaleData, shape: [1] },
140
  y_zero_point: { data: y_zero_pointData, shape: [1] },
141
  });
142
+ console.log({ y });
143
  ```
build/webgpu/bench.json CHANGED
The diff for this file is too large to render. See raw diff
 
build/webgpu/conv-int-accumulate-spatial.wgsl.jinja CHANGED
@@ -30,20 +30,23 @@ fn {{ fn_name }}({% if per_column %}{{ param_name }}: u32{% endif %}) -> {{ retu
30
  return 0;
31
  {% endif %}
32
  }{% endmacro %}
33
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
34
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
35
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
36
  // per-axis workgroup fold width.
37
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
38
- if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}
 
 
 
39
  {{ env.wgsl.resourceDeclarations }}
40
 
41
  fn read_x(index: u32) -> i32 {
42
- {% if xUnsigned %}
43
  return i32(x[index]);
44
- {% else %}
45
  return x[index];
46
- {% endif %}
47
  }
48
 
49
  fn read_w(index: u32) -> i32 {
@@ -61,7 +64,7 @@ fn read_w(index: u32) -> i32 {
61
 
62
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
63
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
64
- {{ flat_index_2d(tunables.WORKGROUP_SIZE, "index", guardInline=true) }}
65
  {% if channelsLast is defined and channelsLast %}
66
  let oc = index % params.outChannels;
67
  var t = index / params.outChannels;
 
30
  return 0;
31
  {% endif %}
32
  }{% endmacro %}
33
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
34
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
35
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
36
  // per-axis workgroup fold width.
37
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
38
+ if ({{ name }} >= {{ bound }}) {
39
+ return;
40
+ }
41
+ {% endmacro %}
42
  {{ env.wgsl.resourceDeclarations }}
43
 
44
  fn read_x(index: u32) -> i32 {
45
+ {% if xUnsigned %}
46
  return i32(x[index]);
47
+ {% else %}
48
  return x[index];
49
+ {% endif %}
50
  }
51
 
52
  fn read_w(index: u32) -> i32 {
 
64
 
65
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
66
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
67
+ {{ flat_index_2d(tunables.WORKGROUP_SIZE, "index") }}
68
  {% if channelsLast is defined and channelsLast %}
69
  let oc = index % params.outChannels;
70
  var t = index / params.outChannels;
build/webgpu/conv-int-im2col-spatial.wgsl.jinja CHANGED
@@ -28,7 +28,7 @@ const PAD_LEFT: i32 = {{ padLeftSpec }};
28
  let iw = i32(ow * STRIDE_W + kw * DILATION_W) - PAD_LEFT;
29
  var {{ value }}: {{ bScalar if sampleScalar == "auto" else sampleScalar }} = {{ zero }}[0];
30
  if (ih >= 0 && ih < i32(params.inH) && iw >= 0 && iw < i32(params.inW)) {
31
- {{ value }} = {{ input }}[{% if sampleChannelsLast is defined and sampleChannelsLast %}((batch * params.inH + u32(ih)) * params.inW + u32(iw)) * params.inChannels + ic{% else %}((batch * params.inChannels + ic) * params.inH + u32(ih)) * params.inW + u32(iw){% endif %}];
32
  }
33
  {% endmacro %}
34
  {{ spatial_constants() }}
 
28
  let iw = i32(ow * STRIDE_W + kw * DILATION_W) - PAD_LEFT;
29
  var {{ value }}: {{ bScalar if sampleScalar == "auto" else sampleScalar }} = {{ zero }}[0];
30
  if (ih >= 0 && ih < i32(params.inH) && iw >= 0 && iw < i32(params.inW)) {
31
+ {{ value }} = {{ input }}[((batch * params.inChannels + ic) * params.inH + u32(ih)) * params.inW + u32(iw)];
32
  }
33
  {% endmacro %}
34
  {{ spatial_constants() }}
build/webgpu/manifest.json CHANGED
The diff for this file is too large to render. See raw diff
 
build/webgpu/matrix-shaped-exact-precast.wgsl.jinja ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% set WIDTH = matrixSubgroupWidth %}
2
+ {% set GROUPS = (128 / WIDTH) | int %}
3
+ {% set OWNED = (WIDTH / 32) | int %}
4
+ {% set ROWS = 1 %}
5
+ {% set COLS = 1 %}
6
+ enable subgroups;
7
+ enable chromium_experimental_subgroup_matrix;
8
+ diagnostic(off, chromium.subgroup_matrix_uniformity);
9
+ {{ env.wgsl.resourceDeclarations }}
10
+ // Rare-boundary fallback: compute binary64-equivalent scale division
11
+ // and accumulator product using integer significands; no f64 feature required.
12
+ fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
13
+ let low = a.x + b.x;
14
+ let middle = a.y + b.y;
15
+ let with_carry = middle + u32(low < a.x);
16
+ return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
17
+ }
18
+ // The low word is the ordinary u32 product. Split at 16 bits so every
19
+ // partial product and carry used to construct the high word fits in u32.
20
+ fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {
21
+ let a_low = a & 0xffffu;
22
+ let a_high = a >> 16u;
23
+ let b_low = b & 0xffffu;
24
+ let b_high = b >> 16u;
25
+ let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);
26
+ let cross_high = a_low * b_high + (cross_low & 0xffffu);
27
+ let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);
28
+ return vec2<u32>(a * b, high);
29
+ }
30
+
31
+ fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
32
+ if (shift == 0u) { return value; }
33
+ if (shift > 96u) { return vec3<u32>(0u); }
34
+
35
+ let limbs = vec4<u32>(value, 0u);
36
+ let word = shift >> 5u;
37
+ let bits = shift & 31u;
38
+ let middle = limbs[min(word + 1u, 3u)];
39
+ let high = limbs[min(word + 2u, 3u)];
40
+ var quotient = vec3<u32>(limbs[word], middle, high);
41
+ if (bits != 0u) {
42
+ quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));
43
+ }
44
+
45
+ // The highest discarded bit is the guard. With the guard set, any lower set
46
+ // bit rounds up; an exact midpoint rounds to the even quotient.
47
+ let guard_word = (shift - 1u) >> 5u;
48
+ let guard_bit = 1u << ((shift - 1u) & 31u);
49
+ let discarded = limbs[guard_word];
50
+ let sticky = (discarded & (guard_bit - 1u)) != 0u ||
51
+ (guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);
52
+ if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {
53
+ quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));
54
+ }
55
+ return quotient;
56
+ }
57
+ fn quant_float_significand(bits: u32) -> u32 {
58
+ return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
59
+ }
60
+ fn quant_float_exponent(bits: u32) -> i32 {
61
+ return max(1, i32((bits >> 23u) & 255u)) - 150;
62
+ }
63
+ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
64
+ if (acc == 0) { return 0; }
65
+ let a_bits = bitcast<u32>(a_s);
66
+ let b_bits = bitcast<u32>(b_s);
67
+ let y_bits = bitcast<u32>(y_s);
68
+ let a = quant_float_significand(a_bits);
69
+ let b = quant_float_significand(b_bits);
70
+ let denominator = quant_float_significand(y_bits);
71
+ if (a == 0u || b == 0u) { return 0; }
72
+ // The exact product of two 24-bit significands occupies at most 48 bits.
73
+ let p0 = (a & 65535u) * (b & 65535u);
74
+ let cross = (a >> 16u) * (b & 65535u) + (b >> 16u) * (a & 65535u);
75
+ let product_low = p0 + (cross << 16u);
76
+ let product_high = (a >> 16u) * (b >> 16u) + (cross >> 16u) + u32(product_low < p0);
77
+ var input_bit = select(31 - i32(countLeadingZeros(product_low)), 63 - i32(countLeadingZeros(product_high)), product_high != 0u);
78
+ var remainder = 0u;
79
+ var significant_bits = 0u;
80
+ var leading_exponent = 0;
81
+ var significand = vec2<u32>(0u);
82
+ // Long division generates the 53 bits of the binary64 multiplier. The
83
+ // remainder fits in 25 bits, including its left shift. At most 24 leading
84
+ // zero bits precede the first significant bit.
85
+ loop {
86
+ var incoming = 0u;
87
+ if (input_bit >= 32) { incoming = (product_high >> u32(input_bit - 32)) & 1u; }
88
+ else if (input_bit >= 0) { incoming = (product_low >> u32(input_bit)) & 1u; }
89
+ remainder = (remainder << 1u) | incoming;
90
+ let digit = u32(remainder >= denominator);
91
+ if (digit != 0u) { remainder -= denominator; }
92
+ if (significant_bits != 0u || digit != 0u) {
93
+ if (significant_bits == 0u) { leading_exponent = input_bit; }
94
+ significand = vec2<u32>((significand.x << 1u) | digit, (significand.y << 1u) | (significand.x >> 31u));
95
+ significant_bits++;
96
+ }
97
+ input_bit--;
98
+ if (significant_bits == 53u) { break; }
99
+ }
100
+ let twice_remainder = remainder << 1u;
101
+ if (twice_remainder > denominator || (twice_remainder == denominator && (significand.x & 1u) != 0u)) {
102
+ let low = significand.x + 1u;
103
+ significand = vec2<u32>(low, significand.y + u32(low == 0u));
104
+ }
105
+ let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
106
+ // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
107
+ // significand by the exact accumulator into three little-endian u32 limbs.
108
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
109
+ let low_product = quant_mul_u32(significand.x, magnitude);
110
+ let high_product = quant_mul_u32(significand.y, magnitude);
111
+ let middle = low_product.y + high_product.x;
112
+ let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));
113
+ var product_top = 31 - i32(countLeadingZeros(product.x));
114
+ if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
115
+ if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
116
+ if (product_top + scale_exponent >= 10) { return select(1024, -1024, acc < 0); }
117
+ if (product_top + scale_exponent < -2) { return 0; }
118
+ let product_shift = u32(max(0, product_top - 52));
119
+ let rounded_product = quant_u96_round_shift(product, product_shift);
120
+ let result_exponent = scale_exponent + i32(product_shift);
121
+ var rounded = rounded_product;
122
+ if (result_exponent < 0) { rounded = quant_u96_round_shift(rounded_product, u32(-result_exponent)); }
123
+ else { rounded.x <<= u32(result_exponent); }
124
+ return select(i32(rounded.x), -i32(rounded.x), acc < 0);
125
+ }
126
+
127
+ // Requantized results lie in [-1024, 1024]. The expansion helpers return this
128
+ // marker at a binary64 boundary instead of resolving it themselves, so a
129
+ // round_requantized call carries one binary64 resolver after inlining rather
130
+ // than one per boundary exit.
131
+ const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;
132
+ // A power-of-two division and an exactly represented <=48-bit product need
133
+ // no binary64 boundary resolver. This includes ordinary dyadic quantization.
134
+ fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
135
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
136
+ let significand = quant_float_significand(bitcast<u32>(scale));
137
+ let integer_bits = 32u - countLeadingZeros(magnitude) - countTrailingZeros(magnitude);
138
+ let scale_bits = 32u - countLeadingZeros(significand) - countTrailingZeros(significand);
139
+ return integer_bits + scale_bits <= 48u;
140
+ }
141
+ fn quant_normal_expansion_range(v: f32) -> bool {
142
+ let exponent = (bitcast<u32>(v) >> 23u) & 255u;
143
+ // Reserve two binary32 significands plus four carry/error bits above the
144
+ // minimum normal exponent, so residual arithmetic avoids FTZ underflow.
145
+ return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
146
+ }
147
+
148
+ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {
149
+ let estimate = numerator_hi / denominator;
150
+ // Anything outside this range saturates after adding an 8-bit zero point;
151
+ // returning early also keeps floor/i32 conversion away from Inf and overflow.
152
+ if (estimate <= -1024.0) { return -1024; }
153
+ if (estimate >= 1024.0) { return 1024; }
154
+
155
+ let lo = floor(estimate);
156
+ let hi = lo + 1.0;
157
+ let midpoint = lo + 0.5;
158
+ let midpoint_hi = fma(midpoint, denominator, 0.0);
159
+ if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
160
+ let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
161
+ // The high-word subtraction is exact for these similarly sized products
162
+ // (Sterbenz); adding the residual difference therefore preserves its sign
163
+ // even when the rounded high words straddle adjacent f32 values.
164
+ let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
165
+ // Resolve ambiguous expansion signs with binary64-equivalent arithmetic.
166
+ // Six FMA/product tails and their additions fit within this conservative
167
+ // 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.
168
+ if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
169
+ if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
170
+ if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }
171
+ }
172
+ if (midpoint_delta < 0.0) {
173
+ return i32(lo);
174
+ }
175
+ if (midpoint_delta > 0.0) {
176
+ return i32(hi);
177
+ }
178
+ let half_lo = floor(lo * 0.5);
179
+ let lo_is_even = lo - half_lo * 2.0 == 0.0;
180
+ return i32(select(hi, lo, lo_is_even));
181
+ }
182
+
183
+ // Multiplication by a power of two keeps every i32 bit in binary64. Round the
184
+ // exact dyadic value directly, including INT_MIN, half-even ties and saturation.
185
+ fn quant_round_power_two(acc: i32, exponent: i32) -> i32 {
186
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
187
+ var rounded = 0u;
188
+ if (exponent >= 0) {
189
+ if (exponent >= 10) { return select(1024, -1024, acc < 0); }
190
+ rounded = min(magnitude, 1024u >> u32(exponent)) << u32(exponent);
191
+ } else {
192
+ let shift = u32(-exponent);
193
+ if (shift >= 32u) { return 0; }
194
+ let whole = magnitude >> shift;
195
+ let remainder = magnitude & ((1u << shift) - 1u);
196
+ let half = 1u << (shift - 1u);
197
+ rounded = min(1024u, whole + u32(remainder > half || (remainder == half && (whole & 1u) != 0u)));
198
+ }
199
+ return select(i32(rounded), -i32(rounded), acc < 0);
200
+ }
201
+
202
+ // Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.
203
+ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
204
+ if (acc == 0) { return 0; }
205
+ let a_bits = bitcast<u32>(a_s);
206
+ let b_bits = bitcast<u32>(b_s);
207
+ let y_bits = bitcast<u32>(y_s);
208
+ if (((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u && min(a_bits, min(b_bits, y_bits)) != 0u && max(a_bits, max(b_bits, y_bits)) < 0x7f800000u) {
209
+ let exponent = i32(a_bits >> 23u) + i32(b_bits >> 23u) - i32(y_bits >> 23u) - 127;
210
+ return quant_round_power_two(acc, exponent);
211
+ }
212
+ let acc_f = f32(acc);
213
+ // Every i32 high part aligned to 256 is exactly representable in f32.
214
+ // Recover the conversion residual without an out-of-range i32(acc_f)
215
+ // conversion when INT_MAX rounds up to 2^31.
216
+ let acc_tail = fma(-1.0, acc_f - f32(acc & -256), f32(acc & 255));
217
+ // Equal b/y scales cancel exactly. Bypass their product and division so a
218
+ // rounded intermediate cannot move a near-half value onto the tie.
219
+ if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
220
+ let direct_hi = fma(acc_f, a_s, 0.0);
221
+ let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
222
+ if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }
223
+ return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);
224
+ }
225
+
226
+ // Keep the scale product as a two-float expansion. Its FMA residual preserves
227
+ // which side of a rounding midpoint a near-half value occupies.
228
+ let ab_hi = fma(a_s, b_s, 0.0);
229
+ let ab_lo = fma(a_s, b_s, -ab_hi);
230
+ if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }
231
+ let product_hi = fma(acc_f, ab_hi, 0.0);
232
+ if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }
233
+ let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
234
+ let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
235
+ // Compare the expansion directly. Renormalizing it adds a cancelling
236
+ // subtraction/addition chain that can erase the residual during lowering.
237
+ let denominator_bits = bitcast<u32>(y_s);
238
+ let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
239
+ let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
240
+ return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);
241
+ }
242
+
243
+ // A conservative binary32 error filter accepts only a result safely inside one
244
+ // integer rounding bin. Ambiguous boundaries keep the full expansion/binary64
245
+ // path; this is an exact-result shortcut, not an approximate quantization mode.
246
+ fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
247
+ if (acc == 0) { return 0; }
248
+ let a_bits = bitcast<u32>(a_s);
249
+ let b_bits = bitcast<u32>(b_s);
250
+ let y_bits = bitcast<u32>(y_s);
251
+ let ea = (a_bits >> 23u) & 255u;
252
+ let eb = (b_bits >> 23u) & 255u;
253
+ let ey = (y_bits >> 23u) & 255u;
254
+ // Certify the range before arithmetic: overflow need not produce infinity.
255
+ // Any nonzero i32 converts to a float with biased exponent <=158. These
256
+ // scale-only bounds cover every accumulator and can be shared across lanes.
257
+ // Reserve two significands plus carry bits above FTZ, and a factor of two
258
+ // below overflow for products, division and the expansion midpoint product.
259
+ // Every exit that needs the binary64 resolver falls through to its one call.
260
+ if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
261
+ min(ea, eb) == 0u || max(ea, eb) >= 255u ||
262
+ ea + eb < 180u || ea + eb > 347u ||
263
+ ey < 53u || ey > 242u || ea + eb > ey + 220u)) {
264
+ let scale = fma(a_s, b_s, 0.0);
265
+ let product = fma(f32(acc), scale, 0.0);
266
+ let estimate = product / y_s;
267
+ if (estimate <= -1024.0) { return -1024; }
268
+ if (estimate >= 1024.0) { return 1024; }
269
+ let nearest = round(estimate);
270
+ // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
271
+ // products, quotient, and distance arithmetic, plus binary64 rounding.
272
+ let margin = max(1.0, abs(estimate)) * 0x1p-19;
273
+ if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
274
+ var use_expansion = true;
275
+ {% if device.adapterInfo.vendor != "apple" %}
276
+ // The conversion, two products and division can put the estimate several
277
+ // ulps across a midpoint. Allow eight unit roundoffs before relying on
278
+ // float residuals. Exact power-of-two ratios retain their integer shortcut.
279
+ if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {
280
+ let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
281
+ min(a_bits, min(b_bits, y_bits)) != 0u &&
282
+ max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
283
+ use_expansion = dyadic_scales;
284
+ }
285
+ {% endif %}
286
+ if (use_expansion) {
287
+ let rounded = round_requantized_precise(acc, a_s, b_s, y_s);
288
+ if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }
289
+ }
290
+ }
291
+ return quant_round_binary64(acc, a_s, b_s, y_s);
292
+ }
293
+ const TILE_M: u32 = 32u;
294
+ const TILE_N: u32 = 32u;
295
+ const PADDED_K: u32 = {{ preparedK }}u;
296
+ const PADDED_N: u32 = {{ preparedN }}u;
297
+ var<workgroup> tileC: array<f32, 1024>;
298
+ // A subgroup owns one matrix tile only after its actual population and the
299
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
300
+ // the role; local invocation IDs only publish the workgroup-wide decision.
301
+ var<workgroup> matrixRoleCount: atomic<u32>;
302
+ var<workgroup> matrixRejected: atomic<u32>;
303
+ var<workgroup> matrixAccepted: u32;
304
+
305
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
306
+ // WGSL initializes workgroup variables to zero before this entry point.
307
+ let population = subgroupBallot(true);
308
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
309
+ + countOneBits(population.z) + countOneBits(population.w);
310
+ var claimed = 0u;
311
+ if (subgroupElect()) {
312
+ claimed = atomicAdd(&matrixRoleCount, 1u);
313
+ if (width != requiredWidth || populationCount != requiredWidth) {
314
+ atomicStore(&matrixRejected, 1u);
315
+ }
316
+ }
317
+ // Reconverge every invocation before broadcasting the elected claim.
318
+ workgroupBarrier();
319
+ return subgroupBroadcastFirst(claimed);
320
+ }
321
+
322
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
323
+ if (localIndex == 0u) {
324
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
325
+ && atomicLoad(&matrixRoleCount) == bankCount);
326
+ }
327
+ // The uniform load both publishes the leader's decision and gives the
328
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
329
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
330
+ }
331
+ @compute @workgroup_size(128, 1, 1)
332
+ fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32,
333
+ @builtin(subgroup_size) width: u32) {
334
+ let rowBase = wid.y * TILE_M;
335
+ let colBase = wid.x * TILE_N;
336
+ let role = claimMatrixSubgroupRole(width, {{ WIDTH }}u);
337
+ let nativeTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u);
338
+ // As in the exact matrix path, every product and intermediate sum
339
+ // remains an exactly representable f32 integer.
340
+ let max_a = {% if matrixZeroPerRow %}255u{% else %}u32(max(abs({{ 0 if aUnsigned else (0 - 128) }} - i32(a_zero_point[0])), abs({{ 255 if aUnsigned else 127 }} - i32(a_zero_point[0])))){% endif %};
341
+ let max_b = {% if not bZeroPerColumn %}u32(max(abs({{ 0 if bUnsigned else (0 - 128) }} - i32(b_zero_point[0])), abs({{ 255 if bUnsigned else 127 }} - i32(b_zero_point[0])))){% else %}255u{% endif %};
342
+ let partialK = (16777216u / (max_a * max_b) / 32u) * 32u;
343
+ var totals: array<i32, 8>;
344
+ for (var partial = 0u; partial < params.K; partial += partialK) {
345
+ let partialEnd = min(params.K, partial + partialK);
346
+ if (nativeTopology) {
347
+ {% for slot in range(OWNED) %}
348
+ let bank{{ slot }} = role + {{ slot * GROUPS }}u;
349
+ let bankRow{{ slot }} = (bank{{ slot }} / 2u) * 16u;
350
+ let bankCol{{ slot }} = (bank{{ slot }} % 2u) * 16u;
351
+ {% for r in range(ROWS) %}{% for c in range(COLS) %}
352
+ var acc{{ slot }}{{ r }}{{ c }} = subgroup_matrix_result<f32, {{ matrixN }}, {{ matrixM }}>(0.0);
353
+ {% endfor %}{% endfor %}{% endfor %}
354
+ for (var kb = partial; kb < partialEnd; kb += {{ matrixK }}u) {
355
+ {% for slot in range(OWNED) %}{% for r in range(ROWS) %}
356
+ let left{{ slot }}{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<f16, {{ matrixK }}, {{ matrixM }}>, row_major>(
357
+ &a, (rowBase + bankRow{{ slot }} + {{ r * matrixM }}u) * PADDED_K + kb, PADDED_K);
358
+ {% endfor %}{% for c in range(COLS) %}
359
+ let right{{ slot }}{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, {{ matrixN }}, {{ matrixK }}>, row_major>(
360
+ &b, {% if matrixBatchB %}wid.z * PADDED_K * PADDED_N + {% endif %}kb * PADDED_N + colBase + bankCol{{ slot }} + {{ c * matrixN }}u, PADDED_N);
361
+ {% endfor %}{% for r in range(ROWS) %}{% for c in range(COLS) %}
362
+ acc{{ slot }}{{ r }}{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ slot }}{{ r }}, right{{ slot }}{{ c }}, acc{{ slot }}{{ r }}{{ c }});
363
+ {% endfor %}{% endfor %}{% endfor %}
364
+ }
365
+ {% for slot in range(OWNED) %}{% for r in range(ROWS) %}{% for c in range(COLS) %}
366
+ subgroupMatrixStore<row_major>(&tileC, (bankRow{{ slot }} + {{ r * matrixM }}u) * TILE_N + bankCol{{ slot }} + {{ c * matrixN }}u, acc{{ slot }}{{ r }}{{ c }}, TILE_N);
367
+ {% endfor %}{% endfor %}{% endfor %}
368
+ workgroupBarrier();
369
+ for (var cell = 0u; cell < 8u; cell++) {
370
+ let flat = tid + cell * 128u;
371
+ totals[cell] += i32(tileC[flat]);
372
+ }
373
+ workgroupBarrier();
374
+ } else {
375
+ for (var cell = 0u; cell < 8u; cell++) {
376
+ let flat = tid + cell * 128u;
377
+ let row = rowBase + flat / TILE_N;
378
+ let col = colBase + flat % TILE_N;
379
+ var value = 0.0;
380
+ for (var k = partial; k < partialEnd; k++) {
381
+ value = fma(f32(a[row * PADDED_K + k]), f32(b[{% if matrixBatchB %}wid.z * PADDED_K * PADDED_N + {% endif %}k * PADDED_N + col]), value);
382
+ }
383
+ totals[cell] += i32(value);
384
+ }
385
+ }
386
+ }
387
+ for (var cell = 0u; cell < 8u; cell++) {
388
+ let flat = tid + cell * 128u;
389
+ let row = rowBase + flat / TILE_N;
390
+ let col = colBase + flat % TILE_N;
391
+ if (row < params.M && col < params.N) {
392
+ let acc = totals[cell]{% if matrixHasBias %} + bias[{{ "row" if matrixBiasPerRow else "col" }}]{% endif %};
393
+ let rounded = round_requantized(acc, f32(a_scale[0]), f32(b_scale[{{ "row" if matrixScalePerRow else ("col" if bScalePerColumn else "0") }}]), f32(y_scale[0]));
394
+ let q = clamp(rounded + i32(y_zero_point[0]), {{ qMin }}, {{ qMax }});
395
+ y[{% if matrixBatchB %}wid.z * params.yBatchStride + {% endif %}row * params.N + col] = {{ "u32(q)" if yUnsigned else "q" }};
396
+ }
397
+ }
398
+ }
build/webgpu/metadata.json CHANGED
@@ -1,115 +1 @@
1
- {
2
- "name": "com.microsoft.QLinearConv",
3
- "id": "_com_microsoft_qlinearconv_webgpu_dd39e27",
4
- "version": 1,
5
- "license": "Apache-2.0",
6
- "backend": { "type": "webgpu" },
7
- "digest": {
8
- "algorithm": "sha256",
9
- "files": {
10
- "bench.json": "deKtgF/RQc9YtJ6rKQbZOEn+82qQqbE7gvVAbfsCrHI=",
11
- "conv-int-accumulate-spatial.wgsl.jinja": "ovvyaZB9d/pmohPYt0/x2NLB2wSWMJ0/eoBHcm4i/5E=",
12
- "conv-int-im2col-spatial.wgsl.jinja": "23v1AQ7sYZnMKE7b32VbAbjutCCZnsMgXRkXYm4W6/k=",
13
- "manifest.json": "TbaAnjGDWtUPENa228Ulfk4p2D8TYPRcs0oyPBIHGoI=",
14
- "qlinear-conv-im2col-nhwc.wgsl.jinja": "CfKXjliMWapwWUjjAk3hY51R2rsx1Wcd4LkvdYUWe6I=",
15
- "qlinear-conv-nchw-x4.wgsl.jinja": "CrFYcoL6MLszFVzk877uUZu6eMi7h6Wii63GJXWC+x0=",
16
- "qlinear-conv-nhwc-oc4.wgsl.jinja": "rTj6WQWmCd0BMzMZJVk/ZssxIDh2HrUEOnuK/owJb3Q=",
17
- "qlinear-conv-requantize.wgsl.jinja": "ElB8XipqRr6CjNjGakSOhsdsM/TezfpRQ2zyh+vENPQ=",
18
- "quant-dp4a-matmul.wgsl.jinja": "jrfKZZQ/P2yDNDElA9IBQJIxU2p7yJzDjj+dt5D4u1E=",
19
- "quant-exact-matrix.wgsl.jinja": "EFugcaUsDIAeUHx17xX66qV/fqfila1p8nlXQCG97Kw=",
20
- "quant-exact-portable.wgsl.jinja": "Ym20X8RcLRzXP9DcQSwJBp4z8RRCBc+bwhrofGC2SBc=",
21
- "quant-exact-prepare.wgsl.jinja": "hAWISxWqTkqc1z9PRAlaNnKqajQKc6sw6IVWfyYmHns=",
22
- "quant-weight-k-major.wgsl.jinja": "B2sKfFD51YrInBxbg8bUKVtU8j/QHUgyoJ7QONaV7iE=",
23
- "test.json": "Yi0vCMNVybIz6uyywnEE6TeUR5B22AzjXtgta2kOmK4="
24
- }
25
- },
26
- "provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },
27
- "webgpu": {
28
- "manifestSpec": "2.1",
29
- "variants": {
30
- "spatial_nd2_scalar": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],
31
- "spatial_nd2_scalar_bias": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],
32
- "spatial_nd2_per_channel": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],
33
- "spatial_nd2_per_channel_bias": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],
34
- "spatial_nd3_scalar": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],
35
- "spatial_nd3_scalar_bias": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],
36
- "spatial_nd3_per_channel": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],
37
- "spatial_nd3_per_channel_bias": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],
38
- "nchw2d_columns_x4": ["qlinear-conv-nchw-x4.wgsl.jinja"],
39
- "nhwc2d_channels_x4": ["qlinear-conv-nhwc-oc4.wgsl.jinja"],
40
- "nhwc2d_depthwise_x4": ["qlinear-conv-nhwc-oc4.wgsl.jinja"],
41
- "nhwc2d_channels_x4_bias": ["qlinear-conv-nhwc-oc4.wgsl.jinja"],
42
- "nhwc2d_depthwise_x4_bias": ["qlinear-conv-nhwc-oc4.wgsl.jinja"],
43
- "dp4a_pointwise_nchw": ["quant-dp4a-matmul.wgsl.jinja"],
44
- "matrix_pointwise_nchw": ["quant-exact-matrix.wgsl.jinja"],
45
- "dp4a_im2col_nchw": ["conv-int-im2col-spatial.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],
46
- "matrix_im2col_nchw": ["conv-int-im2col-spatial.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],
47
- "dp4a_im2col_nchw_bias": ["conv-int-im2col-spatial.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],
48
- "matrix_im2col_nchw_bias": ["conv-int-im2col-spatial.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],
49
- "dp4a_pointwise_nhwc": ["quant-dp4a-matmul.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],
50
- "matrix_pointwise_nhwc": ["quant-exact-matrix.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],
51
- "dp4a_pointwise_nhwc_bias": ["quant-dp4a-matmul.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],
52
- "matrix_pointwise_nhwc_bias": ["quant-exact-matrix.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],
53
- "dp4a_im2col_nhwc": ["qlinear-conv-im2col-nhwc.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],
54
- "matrix_im2col_nhwc": ["qlinear-conv-im2col-nhwc.wgsl.jinja", "quant-exact-matrix.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],
55
- "dp4a_im2col_nhwc_bias": ["qlinear-conv-im2col-nhwc.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],
56
- "matrix_im2col_nhwc_bias": ["qlinear-conv-im2col-nhwc.wgsl.jinja", "quant-exact-matrix.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],
57
- "precast_f16_pointwise_nchw_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
58
- "portable_f16_pointwise_nchw_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
59
- "precast_f16_pointwise_nchw_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
60
- "portable_f16_pointwise_nchw_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
61
- "precast_f16_im2col_nchw_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
62
- "portable_f16_im2col_nchw_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
63
- "precast_f16_im2col_nchw_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
64
- "portable_f16_im2col_nchw_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
65
- "precast_f16_im2col_nchw_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
66
- "portable_f16_im2col_nchw_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
67
- "precast_f16_im2col_nchw_bias_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
68
- "portable_f16_im2col_nchw_bias_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
69
- "precast_f16_pointwise_nhwc_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
70
- "portable_f16_pointwise_nhwc_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
71
- "precast_f16_pointwise_nhwc_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
72
- "portable_f16_pointwise_nhwc_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
73
- "precast_f16_pointwise_nhwc_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
74
- "portable_f16_pointwise_nhwc_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
75
- "precast_f16_pointwise_nhwc_bias_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
76
- "portable_f16_pointwise_nhwc_bias_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
77
- "precast_f16_im2col_nhwc_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
78
- "portable_f16_im2col_nhwc_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
79
- "precast_f16_im2col_nhwc_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
80
- "portable_f16_im2col_nhwc_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
81
- "precast_f16_im2col_nhwc_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
82
- "portable_f16_im2col_nhwc_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
83
- "precast_f16_im2col_nhwc_bias_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
84
- "portable_f16_im2col_nhwc_bias_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
85
- "precast_f32_pointwise_nchw_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
86
- "portable_f32_pointwise_nchw_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
87
- "precast_f32_pointwise_nchw_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
88
- "portable_f32_pointwise_nchw_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
89
- "precast_f32_im2col_nchw_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
90
- "portable_f32_im2col_nchw_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
91
- "precast_f32_im2col_nchw_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
92
- "portable_f32_im2col_nchw_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
93
- "precast_f32_im2col_nchw_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
94
- "portable_f32_im2col_nchw_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
95
- "precast_f32_im2col_nchw_bias_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
96
- "portable_f32_im2col_nchw_bias_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
97
- "precast_f32_pointwise_nhwc_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
98
- "portable_f32_pointwise_nhwc_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
99
- "precast_f32_pointwise_nhwc_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
100
- "portable_f32_pointwise_nhwc_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
101
- "precast_f32_pointwise_nhwc_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
102
- "portable_f32_pointwise_nhwc_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
103
- "precast_f32_pointwise_nhwc_bias_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
104
- "portable_f32_pointwise_nhwc_bias_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
105
- "precast_f32_im2col_nhwc_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
106
- "portable_f32_im2col_nhwc_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
107
- "precast_f32_im2col_nhwc_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
108
- "portable_f32_im2col_nhwc_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
109
- "precast_f32_im2col_nhwc_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
110
- "portable_f32_im2col_nhwc_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
111
- "precast_f32_im2col_nhwc_bias_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],
112
- "portable_f32_im2col_nhwc_bias_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"]
113
- }
114
- }
115
- }
 
1
+ {"name":"com.microsoft.QLinearConv","id":"_com_microsoft_qlinearconv_webgpu_348a320","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"bench.json":"bclLFEoi1uK1WtAIaO9qqIafwRZzXEmJWEEw0lguMXc=","conv-int-accumulate-spatial.wgsl.jinja":"GyQEbYtk9HH6f4F+0Fg/sLVArL2tCZyK/JfnHlN5tFU=","conv-int-im2col-spatial.wgsl.jinja":"oQVl48cgROS+B8kvjQSoSzn+EnhxYDOzchFmNNGwvB0=","manifest.json":"ccF4QES2pftzIvYWmHK9KncVq52AmOh4hSKIeeURsow=","matrix-shaped-exact-precast.wgsl.jinja":"Sknf9tjji7VgLVIAJAQU53tZ6q187Ss1xps+pESN7AA=","qlinear-conv-im2col-nhwc.wgsl.jinja":"3AZpTr4KqfHVicL6ao+F0tc9+BwirDzRRL7gPT5SPls=","qlinear-conv-nchw-x4.wgsl.jinja":"0hfZXr6ORkSYsLFo9JVZWWFzlmIWDmEjk4ppH0nyfGA=","qlinear-conv-nhwc-oc4.wgsl.jinja":"hMU0jQ1l+Slqwtzm+eNVyXxNZ0zVvx+j4k4Sm1GmZYE=","qlinear-conv-requantize.wgsl.jinja":"0yfafDT7K7IGzKEkc50XZNThG4nWUTeMZrPs7cX36G4=","quant-dp4a-matmul.wgsl.jinja":"AAguqc7bZ1VxU5kgTVRfeJGt82k/+2IDPyww/MQbNB4=","quant-exact-matrix.wgsl.jinja":"+3Lpr4VhoQdc8hp5Nav4MTI4TjrHJzo1oq32EJ1HAE4=","quant-exact-portable.wgsl.jinja":"sk4jUi2poGLPCwm8BBiGWaC9+xfHVU57r8gBwu41zPU=","quant-exact-prepare.wgsl.jinja":"hAWISxWqTkqc1z9PRAlaNnKqajQKc6sw6IVWfyYmHns=","quant-weight-k-major.wgsl.jinja":"umZW8yAZCZgxUDnmwyzifS5lXv45S88eQbdqjY9NWrw=","test.json":"q1Y/i6YvxbaOIJ4qEJYrzf9FcAFUYnbbVy/q1zOYcjs="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/webgpu/qlinear-conv-im2col-nhwc.wgsl.jinja CHANGED
@@ -11,12 +11,15 @@
11
  // giving each lane several stores in flight. When the input channel count is itself
12
  // a multiple of four a quadruple never crosses a kernel tap, and the gather is the
13
  // matching aligned vec4 load.
14
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
15
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
16
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
17
  // per-axis workgroup fold width.
18
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
19
- if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}
 
 
 
20
  {{ env.wgsl.resourceDeclarations }}
21
 
22
  const WORDS_PER_LANE: u32 = {{ im2colWords }}u;
@@ -30,7 +33,7 @@ const PAD_LEFT: i32 = {{ padLeftSpec }};
30
 
31
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
32
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
33
- {{ flat_index_2d(tunables.WORKGROUP_SIZE, "lane", guardInline=true) }}
34
  let zp = x_zero_point[0];
35
  for (var i = 0u; i < WORDS_PER_LANE; i = i + 1u) {
36
  let word = lane + i * params.count;
 
11
  // giving each lane several stores in flight. When the input channel count is itself
12
  // a multiple of four a quadruple never crosses a kernel tap, and the gather is the
13
  // matching aligned vec4 load.
14
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
15
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
16
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
17
  // per-axis workgroup fold width.
18
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
19
+ if ({{ name }} >= {{ bound }}) {
20
+ return;
21
+ }
22
+ {% endmacro %}
23
  {{ env.wgsl.resourceDeclarations }}
24
 
25
  const WORDS_PER_LANE: u32 = {{ im2colWords }}u;
 
33
 
34
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
35
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
36
+ {{ flat_index_2d(tunables.WORKGROUP_SIZE, "lane") }}
37
  let zp = x_zero_point[0];
38
  for (var i = 0u; i < WORDS_PER_LANE; i = i + 1u) {
39
  let word = lane + i * params.count;
build/webgpu/qlinear-conv-nchw-x4.wgsl.jinja CHANGED
@@ -6,13 +6,14 @@ fn {{ fn_name }}() -> i32 {
6
  return {{ buffer_name }}[0];
7
  {% endif %}
8
  }{% endmacro %}
9
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
10
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
11
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
12
  // per-axis workgroup fold width.
13
- let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}
 
14
  {{ env.wgsl.resourceDeclarations }}
15
- // Rare-boundary fallback: reproduce the reference's binary64 scale division
16
  // and accumulator product using integer significands; no f64 feature required.
17
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
18
  let low = a.x + b.x;
@@ -20,22 +21,44 @@ fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
20
  let with_carry = middle + u32(low < a.x);
21
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
22
  }
23
- fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {
24
- return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);
 
 
 
 
 
 
 
 
 
25
  }
 
26
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
27
- var q = value;
28
- var sticky = false;
29
- var guard = false;
30
- for (var bit = 0u; bit < shift; bit++) {
31
- sticky = sticky || guard;
32
- guard = (q.x & 1u) != 0u;
33
- q = quant_u96_shr(q);
 
 
 
 
34
  }
35
- if (guard && (sticky || (q.x & 1u) != 0u)) {
36
- q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));
 
 
 
 
 
 
 
 
37
  }
38
- return q;
39
  }
40
  fn quant_float_significand(bits: u32) -> u32 {
41
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
@@ -88,15 +111,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
88
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
89
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
90
  // significand by the exact accumulator into three little-endian u32 limbs.
91
- var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
92
- var operand = vec3<u32>(significand, 0u);
93
- var product = vec3<u32>(0u);
94
- loop {
95
- if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }
96
- magnitude >>= 1u;
97
- if (magnitude == 0u) { break; }
98
- operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));
99
- }
100
  var product_top = 31 - i32(countLeadingZeros(product.x));
101
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
102
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
@@ -111,6 +130,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
111
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
112
  }
113
 
 
 
 
 
 
114
  // A power-of-two division and an exactly represented <=48-bit product need
115
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
116
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
@@ -127,7 +151,7 @@ fn quant_normal_expansion_range(v: f32) -> bool {
127
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
128
  }
129
 
130
- fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
131
  let estimate = numerator_hi / denominator;
132
  // Anything outside this range saturates after adding an 8-bit zero point;
133
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
@@ -138,18 +162,18 @@ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32,
138
  let hi = lo + 1.0;
139
  let midpoint = lo + 0.5;
140
  let midpoint_hi = fma(midpoint, denominator, 0.0);
141
- if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
142
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
143
  // The high-word subtraction is exact for these similarly sized products
144
  // (Sterbenz); adding the residual difference therefore preserves its sign
145
  // even when the rounded high words straddle adjacent f32 values.
146
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
147
- // Escalate ambiguous expansion signs instead of changing the tie tolerance.
148
  // Six FMA/product tails and their additions fit within this conservative
149
- // 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.
150
- if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
151
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
152
- if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
153
  }
154
  if (midpoint_delta < 0.0) {
155
  return i32(lo);
@@ -181,6 +205,7 @@ fn quant_round_power_two(acc: i32, exponent: i32) -> i32 {
181
  return select(i32(rounded), -i32(rounded), acc < 0);
182
  }
183
 
 
184
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
185
  if (acc == 0) { return 0; }
186
  let a_bits = bitcast<u32>(a_s);
@@ -200,17 +225,17 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
200
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
201
  let direct_hi = fma(acc_f, a_s, 0.0);
202
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
203
- if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
204
- return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);
205
  }
206
 
207
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
208
  // which side of a rounding midpoint a near-half value occupies.
209
  let ab_hi = fma(a_s, b_s, 0.0);
210
  let ab_lo = fma(a_s, b_s, -ab_hi);
211
- if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return quant_round_binary64(acc, a_s, b_s, y_s); }
212
  let product_hi = fma(acc_f, ab_hi, 0.0);
213
- if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
214
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
215
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
216
  // Compare the expansion directly. Renormalizing it adds a cancelling
@@ -218,7 +243,7 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
218
  let denominator_bits = bitcast<u32>(y_s);
219
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
220
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
221
- return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);
222
  }
223
 
224
  // A conservative binary32 error filter accepts only a result safely inside one
@@ -237,35 +262,39 @@ fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
237
  // scale-only bounds cover every accumulator and can be shared across lanes.
238
  // Reserve two significands plus carry bits above FTZ, and a factor of two
239
  // below overflow for products, division and the expansion midpoint product.
240
- if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
241
- min(ea, eb) == 0u || max(ea, eb) >= 255u ||
242
- ea + eb < 180u || ea + eb > 347u ||
243
- ey < 53u || ey > 242u || ea + eb > ey + 220u) {
244
- return quant_round_binary64(acc, a_s, b_s, y_s);
245
- }
246
- let scale = fma(a_s, b_s, 0.0);
247
- let product = fma(f32(acc), scale, 0.0);
248
- let estimate = product / y_s;
249
- if (estimate <= -1024.0) { return -1024; }
250
- if (estimate >= 1024.0) { return 1024; }
251
- let nearest = round(estimate);
252
- // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
253
- // products, quotient, and distance arithmetic, plus binary64 rounding.
254
- let margin = max(1.0, abs(estimate)) * 0x1p-19;
255
- if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
256
  {% if device.adapterInfo.vendor != "apple" %}
257
- // A rounded half-integer estimate can hide which side the exact f32-scale
258
- // ratio lies on. Resolve that one-ulp neighborhood conservatively outside
259
- // the compact fast path; exact power-of-two ratios already have a cheap
260
- // and correct path in round_requantized_precise.
261
- if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {
262
- let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
263
- min(a_bits, min(b_bits, y_bits)) != 0u &&
264
- max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
265
- if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }
266
- }
267
  {% endif %}
268
- return round_requantized_precise(acc, a_s, b_s, y_s);
 
 
 
 
 
269
  }
270
 
271
  {{ quant_read_scalar_zero("x_zero", "x_zero_point", xUnsigned) }}
 
6
  return {{ buffer_name }}[0];
7
  {% endif %}
8
  }{% endmacro %}
9
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
10
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
11
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
12
  // per-axis workgroup fold width.
13
+ let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
14
+ {% endmacro %}
15
  {{ env.wgsl.resourceDeclarations }}
16
+ // Rare-boundary fallback: compute binary64-equivalent scale division
17
  // and accumulator product using integer significands; no f64 feature required.
18
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
19
  let low = a.x + b.x;
 
21
  let with_carry = middle + u32(low < a.x);
22
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
23
  }
24
+ // The low word is the ordinary u32 product. Split at 16 bits so every
25
+ // partial product and carry used to construct the high word fits in u32.
26
+ fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {
27
+ let a_low = a & 0xffffu;
28
+ let a_high = a >> 16u;
29
+ let b_low = b & 0xffffu;
30
+ let b_high = b >> 16u;
31
+ let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);
32
+ let cross_high = a_low * b_high + (cross_low & 0xffffu);
33
+ let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);
34
+ return vec2<u32>(a * b, high);
35
  }
36
+
37
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
38
+ if (shift == 0u) { return value; }
39
+ if (shift > 96u) { return vec3<u32>(0u); }
40
+
41
+ let limbs = vec4<u32>(value, 0u);
42
+ let word = shift >> 5u;
43
+ let bits = shift & 31u;
44
+ let middle = limbs[min(word + 1u, 3u)];
45
+ let high = limbs[min(word + 2u, 3u)];
46
+ var quotient = vec3<u32>(limbs[word], middle, high);
47
+ if (bits != 0u) {
48
+ quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));
49
  }
50
+
51
+ // The highest discarded bit is the guard. With the guard set, any lower set
52
+ // bit rounds up; an exact midpoint rounds to the even quotient.
53
+ let guard_word = (shift - 1u) >> 5u;
54
+ let guard_bit = 1u << ((shift - 1u) & 31u);
55
+ let discarded = limbs[guard_word];
56
+ let sticky = (discarded & (guard_bit - 1u)) != 0u ||
57
+ (guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);
58
+ if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {
59
+ quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));
60
  }
61
+ return quotient;
62
  }
63
  fn quant_float_significand(bits: u32) -> u32 {
64
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
 
111
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
112
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
113
  // significand by the exact accumulator into three little-endian u32 limbs.
114
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
115
+ let low_product = quant_mul_u32(significand.x, magnitude);
116
+ let high_product = quant_mul_u32(significand.y, magnitude);
117
+ let middle = low_product.y + high_product.x;
118
+ let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));
 
 
 
 
119
  var product_top = 31 - i32(countLeadingZeros(product.x));
120
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
121
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
 
130
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
131
  }
132
 
133
+ // Requantized results lie in [-1024, 1024]. The expansion helpers return this
134
+ // marker at a binary64 boundary instead of resolving it themselves, so a
135
+ // round_requantized call carries one binary64 resolver after inlining rather
136
+ // than one per boundary exit.
137
+ const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;
138
  // A power-of-two division and an exactly represented <=48-bit product need
139
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
140
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
 
151
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
152
  }
153
 
154
+ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {
155
  let estimate = numerator_hi / denominator;
156
  // Anything outside this range saturates after adding an 8-bit zero point;
157
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
 
162
  let hi = lo + 1.0;
163
  let midpoint = lo + 0.5;
164
  let midpoint_hi = fma(midpoint, denominator, 0.0);
165
+ if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
166
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
167
  // The high-word subtraction is exact for these similarly sized products
168
  // (Sterbenz); adding the residual difference therefore preserves its sign
169
  // even when the rounded high words straddle adjacent f32 values.
170
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
171
+ // Resolve ambiguous expansion signs with binary64-equivalent arithmetic.
172
  // Six FMA/product tails and their additions fit within this conservative
173
+ // 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.
174
+ if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
175
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
176
+ if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }
177
  }
178
  if (midpoint_delta < 0.0) {
179
  return i32(lo);
 
205
  return select(i32(rounded), -i32(rounded), acc < 0);
206
  }
207
 
208
+ // Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.
209
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
210
  if (acc == 0) { return 0; }
211
  let a_bits = bitcast<u32>(a_s);
 
225
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
226
  let direct_hi = fma(acc_f, a_s, 0.0);
227
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
228
+ if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }
229
+ return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);
230
  }
231
 
232
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
233
  // which side of a rounding midpoint a near-half value occupies.
234
  let ab_hi = fma(a_s, b_s, 0.0);
235
  let ab_lo = fma(a_s, b_s, -ab_hi);
236
+ if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }
237
  let product_hi = fma(acc_f, ab_hi, 0.0);
238
+ if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }
239
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
240
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
241
  // Compare the expansion directly. Renormalizing it adds a cancelling
 
243
  let denominator_bits = bitcast<u32>(y_s);
244
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
245
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
246
+ return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);
247
  }
248
 
249
  // A conservative binary32 error filter accepts only a result safely inside one
 
262
  // scale-only bounds cover every accumulator and can be shared across lanes.
263
  // Reserve two significands plus carry bits above FTZ, and a factor of two
264
  // below overflow for products, division and the expansion midpoint product.
265
+ // Every exit that needs the binary64 resolver falls through to its one call.
266
+ if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
267
+ min(ea, eb) == 0u || max(ea, eb) >= 255u ||
268
+ ea + eb < 180u || ea + eb > 347u ||
269
+ ey < 53u || ey > 242u || ea + eb > ey + 220u)) {
270
+ let scale = fma(a_s, b_s, 0.0);
271
+ let product = fma(f32(acc), scale, 0.0);
272
+ let estimate = product / y_s;
273
+ if (estimate <= -1024.0) { return -1024; }
274
+ if (estimate >= 1024.0) { return 1024; }
275
+ let nearest = round(estimate);
276
+ // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
277
+ // products, quotient, and distance arithmetic, plus binary64 rounding.
278
+ let margin = max(1.0, abs(estimate)) * 0x1p-19;
279
+ if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
280
+ var use_expansion = true;
281
  {% if device.adapterInfo.vendor != "apple" %}
282
+ // The conversion, two products and division can put the estimate several
283
+ // ulps across a midpoint. Allow eight unit roundoffs before relying on
284
+ // float residuals. Exact power-of-two ratios retain their integer shortcut.
285
+ if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {
286
+ let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
287
+ min(a_bits, min(b_bits, y_bits)) != 0u &&
288
+ max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
289
+ use_expansion = dyadic_scales;
290
+ }
 
291
  {% endif %}
292
+ if (use_expansion) {
293
+ let rounded = round_requantized_precise(acc, a_s, b_s, y_s);
294
+ if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }
295
+ }
296
+ }
297
+ return quant_round_binary64(acc, a_s, b_s, y_s);
298
  }
299
 
300
  {{ quant_read_scalar_zero("x_zero", "x_zero_point", xUnsigned) }}
build/webgpu/qlinear-conv-nhwc-oc4.wgsl.jinja CHANGED
@@ -13,14 +13,17 @@ fn {{ fn_name }}() -> i32 {
13
  // grouped arm broadcasts one activation across the quadruple; the depthwise arm
14
  // (one input and one output channel per group) reads four adjacent activation
15
  // channels instead, which is the same contiguous run as the store.
16
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
17
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
18
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
19
  // per-axis workgroup fold width.
20
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
21
- if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}
 
 
 
22
  {{ env.wgsl.resourceDeclarations }}
23
- // Rare-boundary fallback: reproduce the reference's binary64 scale division
24
  // and accumulator product using integer significands; no f64 feature required.
25
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
26
  let low = a.x + b.x;
@@ -28,22 +31,44 @@ fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
28
  let with_carry = middle + u32(low < a.x);
29
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
30
  }
31
- fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {
32
- return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);
 
 
 
 
 
 
 
 
 
33
  }
 
34
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
35
- var q = value;
36
- var sticky = false;
37
- var guard = false;
38
- for (var bit = 0u; bit < shift; bit++) {
39
- sticky = sticky || guard;
40
- guard = (q.x & 1u) != 0u;
41
- q = quant_u96_shr(q);
 
 
 
 
42
  }
43
- if (guard && (sticky || (q.x & 1u) != 0u)) {
44
- q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));
 
 
 
 
 
 
 
 
45
  }
46
- return q;
47
  }
48
  fn quant_float_significand(bits: u32) -> u32 {
49
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
@@ -96,15 +121,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
96
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
97
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
98
  // significand by the exact accumulator into three little-endian u32 limbs.
99
- var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
100
- var operand = vec3<u32>(significand, 0u);
101
- var product = vec3<u32>(0u);
102
- loop {
103
- if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }
104
- magnitude >>= 1u;
105
- if (magnitude == 0u) { break; }
106
- operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));
107
- }
108
  var product_top = 31 - i32(countLeadingZeros(product.x));
109
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
110
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
@@ -119,6 +140,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
119
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
120
  }
121
 
 
 
 
 
 
122
  // A power-of-two division and an exactly represented <=48-bit product need
123
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
124
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
@@ -135,7 +161,7 @@ fn quant_normal_expansion_range(v: f32) -> bool {
135
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
136
  }
137
 
138
- fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
139
  let estimate = numerator_hi / denominator;
140
  // Anything outside this range saturates after adding an 8-bit zero point;
141
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
@@ -146,18 +172,18 @@ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32,
146
  let hi = lo + 1.0;
147
  let midpoint = lo + 0.5;
148
  let midpoint_hi = fma(midpoint, denominator, 0.0);
149
- if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
150
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
151
  // The high-word subtraction is exact for these similarly sized products
152
  // (Sterbenz); adding the residual difference therefore preserves its sign
153
  // even when the rounded high words straddle adjacent f32 values.
154
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
155
- // Escalate ambiguous expansion signs instead of changing the tie tolerance.
156
  // Six FMA/product tails and their additions fit within this conservative
157
- // 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.
158
- if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
159
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
160
- if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
161
  }
162
  if (midpoint_delta < 0.0) {
163
  return i32(lo);
@@ -189,6 +215,7 @@ fn quant_round_power_two(acc: i32, exponent: i32) -> i32 {
189
  return select(i32(rounded), -i32(rounded), acc < 0);
190
  }
191
 
 
192
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
193
  if (acc == 0) { return 0; }
194
  let a_bits = bitcast<u32>(a_s);
@@ -208,17 +235,17 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
208
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
209
  let direct_hi = fma(acc_f, a_s, 0.0);
210
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
211
- if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
212
- return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);
213
  }
214
 
215
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
216
  // which side of a rounding midpoint a near-half value occupies.
217
  let ab_hi = fma(a_s, b_s, 0.0);
218
  let ab_lo = fma(a_s, b_s, -ab_hi);
219
- if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return quant_round_binary64(acc, a_s, b_s, y_s); }
220
  let product_hi = fma(acc_f, ab_hi, 0.0);
221
- if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
222
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
223
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
224
  // Compare the expansion directly. Renormalizing it adds a cancelling
@@ -226,7 +253,7 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
226
  let denominator_bits = bitcast<u32>(y_s);
227
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
228
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
229
- return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);
230
  }
231
 
232
  // A conservative binary32 error filter accepts only a result safely inside one
@@ -245,35 +272,39 @@ fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
245
  // scale-only bounds cover every accumulator and can be shared across lanes.
246
  // Reserve two significands plus carry bits above FTZ, and a factor of two
247
  // below overflow for products, division and the expansion midpoint product.
248
- if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
249
- min(ea, eb) == 0u || max(ea, eb) >= 255u ||
250
- ea + eb < 180u || ea + eb > 347u ||
251
- ey < 53u || ey > 242u || ea + eb > ey + 220u) {
252
- return quant_round_binary64(acc, a_s, b_s, y_s);
253
- }
254
- let scale = fma(a_s, b_s, 0.0);
255
- let product = fma(f32(acc), scale, 0.0);
256
- let estimate = product / y_s;
257
- if (estimate <= -1024.0) { return -1024; }
258
- if (estimate >= 1024.0) { return 1024; }
259
- let nearest = round(estimate);
260
- // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
261
- // products, quotient, and distance arithmetic, plus binary64 rounding.
262
- let margin = max(1.0, abs(estimate)) * 0x1p-19;
263
- if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
264
  {% if device.adapterInfo.vendor != "apple" %}
265
- // A rounded half-integer estimate can hide which side the exact f32-scale
266
- // ratio lies on. Resolve that one-ulp neighborhood conservatively outside
267
- // the compact fast path; exact power-of-two ratios already have a cheap
268
- // and correct path in round_requantized_precise.
269
- if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {
270
- let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
271
- min(a_bits, min(b_bits, y_bits)) != 0u &&
272
- max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
273
- if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }
274
- }
275
  {% endif %}
276
- return round_requantized_precise(acc, a_s, b_s, y_s);
 
 
 
 
 
277
  }
278
 
279
  const OW_TILE: u32 = {{ owTile }}u;
@@ -330,7 +361,7 @@ fn write_y(i: u32, value: i32) {
330
 
331
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
332
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
333
- {{ flat_index_2d(tunables.WORKGROUP_SIZE, "flat", guardInline=true) }}
334
  let ocb = flat % params.ocBlocks;
335
  var rest = flat / params.ocBlocks;
336
  let owg = rest % params.owGroups;
 
13
  // grouped arm broadcasts one activation across the quadruple; the depthwise arm
14
  // (one input and one output channel per group) reads four adjacent activation
15
  // channels instead, which is the same contiguous run as the store.
16
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
17
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
18
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
19
  // per-axis workgroup fold width.
20
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
21
+ if ({{ name }} >= {{ bound }}) {
22
+ return;
23
+ }
24
+ {% endmacro %}
25
  {{ env.wgsl.resourceDeclarations }}
26
+ // Rare-boundary fallback: compute binary64-equivalent scale division
27
  // and accumulator product using integer significands; no f64 feature required.
28
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
29
  let low = a.x + b.x;
 
31
  let with_carry = middle + u32(low < a.x);
32
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
33
  }
34
+ // The low word is the ordinary u32 product. Split at 16 bits so every
35
+ // partial product and carry used to construct the high word fits in u32.
36
+ fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {
37
+ let a_low = a & 0xffffu;
38
+ let a_high = a >> 16u;
39
+ let b_low = b & 0xffffu;
40
+ let b_high = b >> 16u;
41
+ let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);
42
+ let cross_high = a_low * b_high + (cross_low & 0xffffu);
43
+ let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);
44
+ return vec2<u32>(a * b, high);
45
  }
46
+
47
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
48
+ if (shift == 0u) { return value; }
49
+ if (shift > 96u) { return vec3<u32>(0u); }
50
+
51
+ let limbs = vec4<u32>(value, 0u);
52
+ let word = shift >> 5u;
53
+ let bits = shift & 31u;
54
+ let middle = limbs[min(word + 1u, 3u)];
55
+ let high = limbs[min(word + 2u, 3u)];
56
+ var quotient = vec3<u32>(limbs[word], middle, high);
57
+ if (bits != 0u) {
58
+ quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));
59
  }
60
+
61
+ // The highest discarded bit is the guard. With the guard set, any lower set
62
+ // bit rounds up; an exact midpoint rounds to the even quotient.
63
+ let guard_word = (shift - 1u) >> 5u;
64
+ let guard_bit = 1u << ((shift - 1u) & 31u);
65
+ let discarded = limbs[guard_word];
66
+ let sticky = (discarded & (guard_bit - 1u)) != 0u ||
67
+ (guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);
68
+ if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {
69
+ quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));
70
  }
71
+ return quotient;
72
  }
73
  fn quant_float_significand(bits: u32) -> u32 {
74
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
 
121
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
122
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
123
  // significand by the exact accumulator into three little-endian u32 limbs.
124
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
125
+ let low_product = quant_mul_u32(significand.x, magnitude);
126
+ let high_product = quant_mul_u32(significand.y, magnitude);
127
+ let middle = low_product.y + high_product.x;
128
+ let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));
 
 
 
 
129
  var product_top = 31 - i32(countLeadingZeros(product.x));
130
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
131
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
 
140
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
141
  }
142
 
143
+ // Requantized results lie in [-1024, 1024]. The expansion helpers return this
144
+ // marker at a binary64 boundary instead of resolving it themselves, so a
145
+ // round_requantized call carries one binary64 resolver after inlining rather
146
+ // than one per boundary exit.
147
+ const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;
148
  // A power-of-two division and an exactly represented <=48-bit product need
149
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
150
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
 
161
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
162
  }
163
 
164
+ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {
165
  let estimate = numerator_hi / denominator;
166
  // Anything outside this range saturates after adding an 8-bit zero point;
167
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
 
172
  let hi = lo + 1.0;
173
  let midpoint = lo + 0.5;
174
  let midpoint_hi = fma(midpoint, denominator, 0.0);
175
+ if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
176
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
177
  // The high-word subtraction is exact for these similarly sized products
178
  // (Sterbenz); adding the residual difference therefore preserves its sign
179
  // even when the rounded high words straddle adjacent f32 values.
180
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
181
+ // Resolve ambiguous expansion signs with binary64-equivalent arithmetic.
182
  // Six FMA/product tails and their additions fit within this conservative
183
+ // 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.
184
+ if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
185
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
186
+ if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }
187
  }
188
  if (midpoint_delta < 0.0) {
189
  return i32(lo);
 
215
  return select(i32(rounded), -i32(rounded), acc < 0);
216
  }
217
 
218
+ // Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.
219
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
220
  if (acc == 0) { return 0; }
221
  let a_bits = bitcast<u32>(a_s);
 
235
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
236
  let direct_hi = fma(acc_f, a_s, 0.0);
237
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
238
+ if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }
239
+ return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);
240
  }
241
 
242
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
243
  // which side of a rounding midpoint a near-half value occupies.
244
  let ab_hi = fma(a_s, b_s, 0.0);
245
  let ab_lo = fma(a_s, b_s, -ab_hi);
246
+ if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }
247
  let product_hi = fma(acc_f, ab_hi, 0.0);
248
+ if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }
249
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
250
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
251
  // Compare the expansion directly. Renormalizing it adds a cancelling
 
253
  let denominator_bits = bitcast<u32>(y_s);
254
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
255
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
256
+ return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);
257
  }
258
 
259
  // A conservative binary32 error filter accepts only a result safely inside one
 
272
  // scale-only bounds cover every accumulator and can be shared across lanes.
273
  // Reserve two significands plus carry bits above FTZ, and a factor of two
274
  // below overflow for products, division and the expansion midpoint product.
275
+ // Every exit that needs the binary64 resolver falls through to its one call.
276
+ if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
277
+ min(ea, eb) == 0u || max(ea, eb) >= 255u ||
278
+ ea + eb < 180u || ea + eb > 347u ||
279
+ ey < 53u || ey > 242u || ea + eb > ey + 220u)) {
280
+ let scale = fma(a_s, b_s, 0.0);
281
+ let product = fma(f32(acc), scale, 0.0);
282
+ let estimate = product / y_s;
283
+ if (estimate <= -1024.0) { return -1024; }
284
+ if (estimate >= 1024.0) { return 1024; }
285
+ let nearest = round(estimate);
286
+ // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
287
+ // products, quotient, and distance arithmetic, plus binary64 rounding.
288
+ let margin = max(1.0, abs(estimate)) * 0x1p-19;
289
+ if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
290
+ var use_expansion = true;
291
  {% if device.adapterInfo.vendor != "apple" %}
292
+ // The conversion, two products and division can put the estimate several
293
+ // ulps across a midpoint. Allow eight unit roundoffs before relying on
294
+ // float residuals. Exact power-of-two ratios retain their integer shortcut.
295
+ if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {
296
+ let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
297
+ min(a_bits, min(b_bits, y_bits)) != 0u &&
298
+ max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
299
+ use_expansion = dyadic_scales;
300
+ }
 
301
  {% endif %}
302
+ if (use_expansion) {
303
+ let rounded = round_requantized_precise(acc, a_s, b_s, y_s);
304
+ if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }
305
+ }
306
+ }
307
+ return quant_round_binary64(acc, a_s, b_s, y_s);
308
  }
309
 
310
  const OW_TILE: u32 = {{ owTile }}u;
 
361
 
362
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
363
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
364
+ {{ flat_index_2d(tunables.WORKGROUP_SIZE, "flat") }}
365
  let ocb = flat % params.ocBlocks;
366
  var rest = flat / params.ocBlocks;
367
  let owg = rest % params.owGroups;
build/webgpu/qlinear-conv-requantize.wgsl.jinja CHANGED
@@ -6,14 +6,17 @@ fn {{ fn_name }}() -> i32 {
6
  return {{ buffer_name }}[0];
7
  {% endif %}
8
  }{% endmacro %}
9
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
10
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
11
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
12
  // per-axis workgroup fold width.
13
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
14
- if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}
 
 
 
15
  {{ env.wgsl.resourceDeclarations }}
16
- // Rare-boundary fallback: reproduce the reference's binary64 scale division
17
  // and accumulator product using integer significands; no f64 feature required.
18
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
19
  let low = a.x + b.x;
@@ -21,22 +24,44 @@ fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
21
  let with_carry = middle + u32(low < a.x);
22
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
23
  }
24
- fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {
25
- return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);
 
 
 
 
 
 
 
 
 
26
  }
 
27
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
28
- var q = value;
29
- var sticky = false;
30
- var guard = false;
31
- for (var bit = 0u; bit < shift; bit++) {
32
- sticky = sticky || guard;
33
- guard = (q.x & 1u) != 0u;
34
- q = quant_u96_shr(q);
 
 
 
 
35
  }
36
- if (guard && (sticky || (q.x & 1u) != 0u)) {
37
- q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));
 
 
 
 
 
 
 
 
38
  }
39
- return q;
40
  }
41
  fn quant_float_significand(bits: u32) -> u32 {
42
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
@@ -89,15 +114,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
89
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
90
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
91
  // significand by the exact accumulator into three little-endian u32 limbs.
92
- var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
93
- var operand = vec3<u32>(significand, 0u);
94
- var product = vec3<u32>(0u);
95
- loop {
96
- if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }
97
- magnitude >>= 1u;
98
- if (magnitude == 0u) { break; }
99
- operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));
100
- }
101
  var product_top = 31 - i32(countLeadingZeros(product.x));
102
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
103
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
@@ -112,6 +133,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
112
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
113
  }
114
 
 
 
 
 
 
115
  // A power-of-two division and an exactly represented <=48-bit product need
116
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
117
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
@@ -128,7 +154,7 @@ fn quant_normal_expansion_range(v: f32) -> bool {
128
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
129
  }
130
 
131
- fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
132
  let estimate = numerator_hi / denominator;
133
  // Anything outside this range saturates after adding an 8-bit zero point;
134
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
@@ -139,18 +165,18 @@ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32,
139
  let hi = lo + 1.0;
140
  let midpoint = lo + 0.5;
141
  let midpoint_hi = fma(midpoint, denominator, 0.0);
142
- if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
143
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
144
  // The high-word subtraction is exact for these similarly sized products
145
  // (Sterbenz); adding the residual difference therefore preserves its sign
146
  // even when the rounded high words straddle adjacent f32 values.
147
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
148
- // Escalate ambiguous expansion signs instead of changing the tie tolerance.
149
  // Six FMA/product tails and their additions fit within this conservative
150
- // 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.
151
- if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
152
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
153
- if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
154
  }
155
  if (midpoint_delta < 0.0) {
156
  return i32(lo);
@@ -182,6 +208,7 @@ fn quant_round_power_two(acc: i32, exponent: i32) -> i32 {
182
  return select(i32(rounded), -i32(rounded), acc < 0);
183
  }
184
 
 
185
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
186
  if (acc == 0) { return 0; }
187
  let a_bits = bitcast<u32>(a_s);
@@ -201,17 +228,17 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
201
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
202
  let direct_hi = fma(acc_f, a_s, 0.0);
203
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
204
- if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
205
- return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);
206
  }
207
 
208
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
209
  // which side of a rounding midpoint a near-half value occupies.
210
  let ab_hi = fma(a_s, b_s, 0.0);
211
  let ab_lo = fma(a_s, b_s, -ab_hi);
212
- if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return quant_round_binary64(acc, a_s, b_s, y_s); }
213
  let product_hi = fma(acc_f, ab_hi, 0.0);
214
- if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
215
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
216
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
217
  // Compare the expansion directly. Renormalizing it adds a cancelling
@@ -219,7 +246,7 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
219
  let denominator_bits = bitcast<u32>(y_s);
220
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
221
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
222
- return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);
223
  }
224
 
225
  // A conservative binary32 error filter accepts only a result safely inside one
@@ -238,35 +265,39 @@ fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
238
  // scale-only bounds cover every accumulator and can be shared across lanes.
239
  // Reserve two significands plus carry bits above FTZ, and a factor of two
240
  // below overflow for products, division and the expansion midpoint product.
241
- if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
242
- min(ea, eb) == 0u || max(ea, eb) >= 255u ||
243
- ea + eb < 180u || ea + eb > 347u ||
244
- ey < 53u || ey > 242u || ea + eb > ey + 220u) {
245
- return quant_round_binary64(acc, a_s, b_s, y_s);
246
- }
247
- let scale = fma(a_s, b_s, 0.0);
248
- let product = fma(f32(acc), scale, 0.0);
249
- let estimate = product / y_s;
250
- if (estimate <= -1024.0) { return -1024; }
251
- if (estimate >= 1024.0) { return 1024; }
252
- let nearest = round(estimate);
253
- // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
254
- // products, quotient, and distance arithmetic, plus binary64 rounding.
255
- let margin = max(1.0, abs(estimate)) * 0x1p-19;
256
- if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
257
  {% if device.adapterInfo.vendor != "apple" %}
258
- // A rounded half-integer estimate can hide which side the exact f32-scale
259
- // ratio lies on. Resolve that one-ulp neighborhood conservatively outside
260
- // the compact fast path; exact power-of-two ratios already have a cheap
261
- // and correct path in round_requantized_precise.
262
- if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {
263
- let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
264
- min(a_bits, min(b_bits, y_bits)) != 0u &&
265
- max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
266
- if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }
267
- }
268
  {% endif %}
269
- return round_requantized_precise(acc, a_s, b_s, y_s);
 
 
 
 
 
270
  }
271
 
272
  {{ quant_read_scalar_zero("read_y_zero", "y_zero_point", yUnsigned) }}
@@ -281,7 +312,7 @@ fn write_y(index: u32, value: i32) {
281
 
282
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
283
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
284
- {{ flat_index_2d(tunables.WORKGROUP_SIZE, guardInline=true) }}
285
  {% if hasBias or wScalePerChannel %}
286
  let oc = (i / params.outImageSize) % params.outChannels;
287
  {% endif %}
 
6
  return {{ buffer_name }}[0];
7
  {% endif %}
8
  }{% endmacro %}
9
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
10
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
11
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
12
  // per-axis workgroup fold width.
13
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
14
+ if ({{ name }} >= {{ bound }}) {
15
+ return;
16
+ }
17
+ {% endmacro %}
18
  {{ env.wgsl.resourceDeclarations }}
19
+ // Rare-boundary fallback: compute binary64-equivalent scale division
20
  // and accumulator product using integer significands; no f64 feature required.
21
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
22
  let low = a.x + b.x;
 
24
  let with_carry = middle + u32(low < a.x);
25
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
26
  }
27
+ // The low word is the ordinary u32 product. Split at 16 bits so every
28
+ // partial product and carry used to construct the high word fits in u32.
29
+ fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {
30
+ let a_low = a & 0xffffu;
31
+ let a_high = a >> 16u;
32
+ let b_low = b & 0xffffu;
33
+ let b_high = b >> 16u;
34
+ let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);
35
+ let cross_high = a_low * b_high + (cross_low & 0xffffu);
36
+ let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);
37
+ return vec2<u32>(a * b, high);
38
  }
39
+
40
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
41
+ if (shift == 0u) { return value; }
42
+ if (shift > 96u) { return vec3<u32>(0u); }
43
+
44
+ let limbs = vec4<u32>(value, 0u);
45
+ let word = shift >> 5u;
46
+ let bits = shift & 31u;
47
+ let middle = limbs[min(word + 1u, 3u)];
48
+ let high = limbs[min(word + 2u, 3u)];
49
+ var quotient = vec3<u32>(limbs[word], middle, high);
50
+ if (bits != 0u) {
51
+ quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));
52
  }
53
+
54
+ // The highest discarded bit is the guard. With the guard set, any lower set
55
+ // bit rounds up; an exact midpoint rounds to the even quotient.
56
+ let guard_word = (shift - 1u) >> 5u;
57
+ let guard_bit = 1u << ((shift - 1u) & 31u);
58
+ let discarded = limbs[guard_word];
59
+ let sticky = (discarded & (guard_bit - 1u)) != 0u ||
60
+ (guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);
61
+ if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {
62
+ quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));
63
  }
64
+ return quotient;
65
  }
66
  fn quant_float_significand(bits: u32) -> u32 {
67
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
 
114
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
115
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
116
  // significand by the exact accumulator into three little-endian u32 limbs.
117
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
118
+ let low_product = quant_mul_u32(significand.x, magnitude);
119
+ let high_product = quant_mul_u32(significand.y, magnitude);
120
+ let middle = low_product.y + high_product.x;
121
+ let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));
 
 
 
 
122
  var product_top = 31 - i32(countLeadingZeros(product.x));
123
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
124
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
 
133
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
134
  }
135
 
136
+ // Requantized results lie in [-1024, 1024]. The expansion helpers return this
137
+ // marker at a binary64 boundary instead of resolving it themselves, so a
138
+ // round_requantized call carries one binary64 resolver after inlining rather
139
+ // than one per boundary exit.
140
+ const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;
141
  // A power-of-two division and an exactly represented <=48-bit product need
142
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
143
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
 
154
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
155
  }
156
 
157
+ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {
158
  let estimate = numerator_hi / denominator;
159
  // Anything outside this range saturates after adding an 8-bit zero point;
160
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
 
165
  let hi = lo + 1.0;
166
  let midpoint = lo + 0.5;
167
  let midpoint_hi = fma(midpoint, denominator, 0.0);
168
+ if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
169
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
170
  // The high-word subtraction is exact for these similarly sized products
171
  // (Sterbenz); adding the residual difference therefore preserves its sign
172
  // even when the rounded high words straddle adjacent f32 values.
173
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
174
+ // Resolve ambiguous expansion signs with binary64-equivalent arithmetic.
175
  // Six FMA/product tails and their additions fit within this conservative
176
+ // 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.
177
+ if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
178
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
179
+ if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }
180
  }
181
  if (midpoint_delta < 0.0) {
182
  return i32(lo);
 
208
  return select(i32(rounded), -i32(rounded), acc < 0);
209
  }
210
 
211
+ // Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.
212
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
213
  if (acc == 0) { return 0; }
214
  let a_bits = bitcast<u32>(a_s);
 
228
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
229
  let direct_hi = fma(acc_f, a_s, 0.0);
230
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
231
+ if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }
232
+ return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);
233
  }
234
 
235
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
236
  // which side of a rounding midpoint a near-half value occupies.
237
  let ab_hi = fma(a_s, b_s, 0.0);
238
  let ab_lo = fma(a_s, b_s, -ab_hi);
239
+ if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }
240
  let product_hi = fma(acc_f, ab_hi, 0.0);
241
+ if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }
242
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
243
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
244
  // Compare the expansion directly. Renormalizing it adds a cancelling
 
246
  let denominator_bits = bitcast<u32>(y_s);
247
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
248
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
249
+ return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);
250
  }
251
 
252
  // A conservative binary32 error filter accepts only a result safely inside one
 
265
  // scale-only bounds cover every accumulator and can be shared across lanes.
266
  // Reserve two significands plus carry bits above FTZ, and a factor of two
267
  // below overflow for products, division and the expansion midpoint product.
268
+ // Every exit that needs the binary64 resolver falls through to its one call.
269
+ if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
270
+ min(ea, eb) == 0u || max(ea, eb) >= 255u ||
271
+ ea + eb < 180u || ea + eb > 347u ||
272
+ ey < 53u || ey > 242u || ea + eb > ey + 220u)) {
273
+ let scale = fma(a_s, b_s, 0.0);
274
+ let product = fma(f32(acc), scale, 0.0);
275
+ let estimate = product / y_s;
276
+ if (estimate <= -1024.0) { return -1024; }
277
+ if (estimate >= 1024.0) { return 1024; }
278
+ let nearest = round(estimate);
279
+ // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
280
+ // products, quotient, and distance arithmetic, plus binary64 rounding.
281
+ let margin = max(1.0, abs(estimate)) * 0x1p-19;
282
+ if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
283
+ var use_expansion = true;
284
  {% if device.adapterInfo.vendor != "apple" %}
285
+ // The conversion, two products and division can put the estimate several
286
+ // ulps across a midpoint. Allow eight unit roundoffs before relying on
287
+ // float residuals. Exact power-of-two ratios retain their integer shortcut.
288
+ if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {
289
+ let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
290
+ min(a_bits, min(b_bits, y_bits)) != 0u &&
291
+ max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
292
+ use_expansion = dyadic_scales;
293
+ }
 
294
  {% endif %}
295
+ if (use_expansion) {
296
+ let rounded = round_requantized_precise(acc, a_s, b_s, y_s);
297
+ if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }
298
+ }
299
+ }
300
+ return quant_round_binary64(acc, a_s, b_s, y_s);
301
  }
302
 
303
  {{ quant_read_scalar_zero("read_y_zero", "y_zero_point", yUnsigned) }}
 
312
 
313
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
314
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
315
+ {{ flat_index_2d(tunables.WORKGROUP_SIZE) }}
316
  {% if hasBias or wScalePerChannel %}
317
  let oc = (i / params.outImageSize) % params.outChannels;
318
  {% endif %}
build/webgpu/quant-dp4a-matmul.wgsl.jinja CHANGED
@@ -1,3 +1,4 @@
 
1
  {% macro quant_read_scalar_zero(fn_name, buffer_name, is_unsigned, present=true) %}
2
  fn {{ fn_name }}() -> i32 {
3
  {% if is_unsigned %}
@@ -43,7 +44,7 @@ fn {{ fn_name }}({% if per_column %}{{ param_name }}: u32{% endif %}) -> {{ retu
43
  {% endif %}
44
  {{ env.wgsl.resourceDeclarations }}
45
  {% if requant != "none" %}
46
- // Rare-boundary fallback: reproduce the reference's binary64 scale division
47
  // and accumulator product using integer significands; no f64 feature required.
48
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
49
  let low = a.x + b.x;
@@ -51,22 +52,44 @@ fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
51
  let with_carry = middle + u32(low < a.x);
52
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
53
  }
54
- fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {
55
- return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);
 
 
 
 
 
 
 
 
 
56
  }
 
57
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
58
- var q = value;
59
- var sticky = false;
60
- var guard = false;
61
- for (var bit = 0u; bit < shift; bit++) {
62
- sticky = sticky || guard;
63
- guard = (q.x & 1u) != 0u;
64
- q = quant_u96_shr(q);
 
 
 
 
65
  }
66
- if (guard && (sticky || (q.x & 1u) != 0u)) {
67
- q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));
 
 
 
 
 
 
 
 
68
  }
69
- return q;
70
  }
71
  fn quant_float_significand(bits: u32) -> u32 {
72
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
@@ -119,15 +142,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
119
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
120
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
121
  // significand by the exact accumulator into three little-endian u32 limbs.
122
- var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
123
- var operand = vec3<u32>(significand, 0u);
124
- var product = vec3<u32>(0u);
125
- loop {
126
- if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }
127
- magnitude >>= 1u;
128
- if (magnitude == 0u) { break; }
129
- operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));
130
- }
131
  var product_top = 31 - i32(countLeadingZeros(product.x));
132
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
133
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
@@ -142,6 +161,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
142
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
143
  }
144
 
 
 
 
 
 
145
  // A power-of-two division and an exactly represented <=48-bit product need
146
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
147
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
@@ -158,7 +182,7 @@ fn quant_normal_expansion_range(v: f32) -> bool {
158
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
159
  }
160
 
161
- fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
162
  let estimate = numerator_hi / denominator;
163
  // Anything outside this range saturates after adding an 8-bit zero point;
164
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
@@ -169,18 +193,18 @@ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32,
169
  let hi = lo + 1.0;
170
  let midpoint = lo + 0.5;
171
  let midpoint_hi = fma(midpoint, denominator, 0.0);
172
- if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
173
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
174
  // The high-word subtraction is exact for these similarly sized products
175
  // (Sterbenz); adding the residual difference therefore preserves its sign
176
  // even when the rounded high words straddle adjacent f32 values.
177
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
178
- // Escalate ambiguous expansion signs instead of changing the tie tolerance.
179
  // Six FMA/product tails and their additions fit within this conservative
180
- // 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.
181
- if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
182
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
183
- if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
184
  }
185
  if (midpoint_delta < 0.0) {
186
  return i32(lo);
@@ -212,6 +236,7 @@ fn quant_round_power_two(acc: i32, exponent: i32) -> i32 {
212
  return select(i32(rounded), -i32(rounded), acc < 0);
213
  }
214
 
 
215
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
216
  if (acc == 0) { return 0; }
217
  let a_bits = bitcast<u32>(a_s);
@@ -231,17 +256,17 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
231
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
232
  let direct_hi = fma(acc_f, a_s, 0.0);
233
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
234
- if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
235
- return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);
236
  }
237
 
238
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
239
  // which side of a rounding midpoint a near-half value occupies.
240
  let ab_hi = fma(a_s, b_s, 0.0);
241
  let ab_lo = fma(a_s, b_s, -ab_hi);
242
- if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return quant_round_binary64(acc, a_s, b_s, y_s); }
243
  let product_hi = fma(acc_f, ab_hi, 0.0);
244
- if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
245
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
246
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
247
  // Compare the expansion directly. Renormalizing it adds a cancelling
@@ -249,7 +274,7 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
249
  let denominator_bits = bitcast<u32>(y_s);
250
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
251
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
252
- return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);
253
  }
254
 
255
  // A conservative binary32 error filter accepts only a result safely inside one
@@ -268,35 +293,39 @@ fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
268
  // scale-only bounds cover every accumulator and can be shared across lanes.
269
  // Reserve two significands plus carry bits above FTZ, and a factor of two
270
  // below overflow for products, division and the expansion midpoint product.
271
- if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
272
- min(ea, eb) == 0u || max(ea, eb) >= 255u ||
273
- ea + eb < 180u || ea + eb > 347u ||
274
- ey < 53u || ey > 242u || ea + eb > ey + 220u) {
275
- return quant_round_binary64(acc, a_s, b_s, y_s);
276
- }
277
- let scale = fma(a_s, b_s, 0.0);
278
- let product = fma(f32(acc), scale, 0.0);
279
- let estimate = product / y_s;
280
- if (estimate <= -1024.0) { return -1024; }
281
- if (estimate >= 1024.0) { return 1024; }
282
- let nearest = round(estimate);
283
- // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
284
- // products, quotient, and distance arithmetic, plus binary64 rounding.
285
- let margin = max(1.0, abs(estimate)) * 0x1p-19;
286
- if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
287
  {% if device.adapterInfo.vendor != "apple" %}
288
- // A rounded half-integer estimate can hide which side the exact f32-scale
289
- // ratio lies on. Resolve that one-ulp neighborhood conservatively outside
290
- // the compact fast path; exact power-of-two ratios already have a cheap
291
- // and correct path in round_requantized_precise.
292
- if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {
293
- let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
294
- min(a_bits, min(b_bits, y_bits)) != 0u &&
295
- max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
296
- if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }
297
- }
298
  {% endif %}
299
- return round_requantized_precise(acc, a_s, b_s, y_s);
 
 
 
 
 
300
  }
301
  {% endif %}
302
 
@@ -311,7 +340,7 @@ const GEMV_K_UNROLL: u32 = {{ GEMV_UNROLL }}u;
311
 
312
  {% set needsBSum = true %}
313
  var<workgroup> a_tile: array<u32, A_TILE_WORDS>;
314
- var<workgroup> a_row_sum: array<atomic<i32>, TILE_M>;
315
 
316
  // Pack 4 widened A values into one u32 (byte 0 = lowest k).
317
  fn pack_a(v: vec4<{{ aScalar }}>) -> u32 {
@@ -383,7 +412,7 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
383
  {% endif %}
384
 
385
  if (tid < TILE_M) {
386
- atomicStore(&a_row_sum[tid], 0);
387
  }
388
  workgroupBarrier();
389
 
@@ -501,7 +530,7 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
501
  let a3: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};
502
  let v = vec4<{{ aScalar }}>(a0, a1, a2, a3);
503
  packed = pack_a(v);
504
- atomicAdd(&a_row_sum[tid], sum4_a(v));
505
  }
506
  a_tile[tid * KT_WORDS] = packed;
507
  }
 
1
+ {% set ownRowSums = false -%}
2
  {% macro quant_read_scalar_zero(fn_name, buffer_name, is_unsigned, present=true) %}
3
  fn {{ fn_name }}() -> i32 {
4
  {% if is_unsigned %}
 
44
  {% endif %}
45
  {{ env.wgsl.resourceDeclarations }}
46
  {% if requant != "none" %}
47
+ // Rare-boundary fallback: compute binary64-equivalent scale division
48
  // and accumulator product using integer significands; no f64 feature required.
49
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
50
  let low = a.x + b.x;
 
52
  let with_carry = middle + u32(low < a.x);
53
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
54
  }
55
+ // The low word is the ordinary u32 product. Split at 16 bits so every
56
+ // partial product and carry used to construct the high word fits in u32.
57
+ fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {
58
+ let a_low = a & 0xffffu;
59
+ let a_high = a >> 16u;
60
+ let b_low = b & 0xffffu;
61
+ let b_high = b >> 16u;
62
+ let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);
63
+ let cross_high = a_low * b_high + (cross_low & 0xffffu);
64
+ let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);
65
+ return vec2<u32>(a * b, high);
66
  }
67
+
68
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
69
+ if (shift == 0u) { return value; }
70
+ if (shift > 96u) { return vec3<u32>(0u); }
71
+
72
+ let limbs = vec4<u32>(value, 0u);
73
+ let word = shift >> 5u;
74
+ let bits = shift & 31u;
75
+ let middle = limbs[min(word + 1u, 3u)];
76
+ let high = limbs[min(word + 2u, 3u)];
77
+ var quotient = vec3<u32>(limbs[word], middle, high);
78
+ if (bits != 0u) {
79
+ quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));
80
  }
81
+
82
+ // The highest discarded bit is the guard. With the guard set, any lower set
83
+ // bit rounds up; an exact midpoint rounds to the even quotient.
84
+ let guard_word = (shift - 1u) >> 5u;
85
+ let guard_bit = 1u << ((shift - 1u) & 31u);
86
+ let discarded = limbs[guard_word];
87
+ let sticky = (discarded & (guard_bit - 1u)) != 0u ||
88
+ (guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);
89
+ if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {
90
+ quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));
91
  }
92
+ return quotient;
93
  }
94
  fn quant_float_significand(bits: u32) -> u32 {
95
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
 
142
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
143
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
144
  // significand by the exact accumulator into three little-endian u32 limbs.
145
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
146
+ let low_product = quant_mul_u32(significand.x, magnitude);
147
+ let high_product = quant_mul_u32(significand.y, magnitude);
148
+ let middle = low_product.y + high_product.x;
149
+ let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));
 
 
 
 
150
  var product_top = 31 - i32(countLeadingZeros(product.x));
151
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
152
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
 
161
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
162
  }
163
 
164
+ // Requantized results lie in [-1024, 1024]. The expansion helpers return this
165
+ // marker at a binary64 boundary instead of resolving it themselves, so a
166
+ // round_requantized call carries one binary64 resolver after inlining rather
167
+ // than one per boundary exit.
168
+ const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;
169
  // A power-of-two division and an exactly represented <=48-bit product need
170
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
171
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
 
182
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
183
  }
184
 
185
+ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {
186
  let estimate = numerator_hi / denominator;
187
  // Anything outside this range saturates after adding an 8-bit zero point;
188
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
 
193
  let hi = lo + 1.0;
194
  let midpoint = lo + 0.5;
195
  let midpoint_hi = fma(midpoint, denominator, 0.0);
196
+ if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
197
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
198
  // The high-word subtraction is exact for these similarly sized products
199
  // (Sterbenz); adding the residual difference therefore preserves its sign
200
  // even when the rounded high words straddle adjacent f32 values.
201
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
202
+ // Resolve ambiguous expansion signs with binary64-equivalent arithmetic.
203
  // Six FMA/product tails and their additions fit within this conservative
204
+ // 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.
205
+ if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
206
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
207
+ if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }
208
  }
209
  if (midpoint_delta < 0.0) {
210
  return i32(lo);
 
236
  return select(i32(rounded), -i32(rounded), acc < 0);
237
  }
238
 
239
+ // Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.
240
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
241
  if (acc == 0) { return 0; }
242
  let a_bits = bitcast<u32>(a_s);
 
256
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
257
  let direct_hi = fma(acc_f, a_s, 0.0);
258
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
259
+ if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }
260
+ return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);
261
  }
262
 
263
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
264
  // which side of a rounding midpoint a near-half value occupies.
265
  let ab_hi = fma(a_s, b_s, 0.0);
266
  let ab_lo = fma(a_s, b_s, -ab_hi);
267
+ if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }
268
  let product_hi = fma(acc_f, ab_hi, 0.0);
269
+ if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }
270
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
271
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
272
  // Compare the expansion directly. Renormalizing it adds a cancelling
 
274
  let denominator_bits = bitcast<u32>(y_s);
275
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
276
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
277
+ return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);
278
  }
279
 
280
  // A conservative binary32 error filter accepts only a result safely inside one
 
293
  // scale-only bounds cover every accumulator and can be shared across lanes.
294
  // Reserve two significands plus carry bits above FTZ, and a factor of two
295
  // below overflow for products, division and the expansion midpoint product.
296
+ // Every exit that needs the binary64 resolver falls through to its one call.
297
+ if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
298
+ min(ea, eb) == 0u || max(ea, eb) >= 255u ||
299
+ ea + eb < 180u || ea + eb > 347u ||
300
+ ey < 53u || ey > 242u || ea + eb > ey + 220u)) {
301
+ let scale = fma(a_s, b_s, 0.0);
302
+ let product = fma(f32(acc), scale, 0.0);
303
+ let estimate = product / y_s;
304
+ if (estimate <= -1024.0) { return -1024; }
305
+ if (estimate >= 1024.0) { return 1024; }
306
+ let nearest = round(estimate);
307
+ // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
308
+ // products, quotient, and distance arithmetic, plus binary64 rounding.
309
+ let margin = max(1.0, abs(estimate)) * 0x1p-19;
310
+ if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
311
+ var use_expansion = true;
312
  {% if device.adapterInfo.vendor != "apple" %}
313
+ // The conversion, two products and division can put the estimate several
314
+ // ulps across a midpoint. Allow eight unit roundoffs before relying on
315
+ // float residuals. Exact power-of-two ratios retain their integer shortcut.
316
+ if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {
317
+ let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
318
+ min(a_bits, min(b_bits, y_bits)) != 0u &&
319
+ max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
320
+ use_expansion = dyadic_scales;
321
+ }
 
322
  {% endif %}
323
+ if (use_expansion) {
324
+ let rounded = round_requantized_precise(acc, a_s, b_s, y_s);
325
+ if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }
326
+ }
327
+ }
328
+ return quant_round_binary64(acc, a_s, b_s, y_s);
329
  }
330
  {% endif %}
331
 
 
340
 
341
  {% set needsBSum = true %}
342
  var<workgroup> a_tile: array<u32, A_TILE_WORDS>;
343
+ var<workgroup> a_row_sum: array<{{ "i32" if ownRowSums else "atomic<i32>" }}, TILE_M>;
344
 
345
  // Pack 4 widened A values into one u32 (byte 0 = lowest k).
346
  fn pack_a(v: vec4<{{ aScalar }}>) -> u32 {
 
412
  {% endif %}
413
 
414
  if (tid < TILE_M) {
415
+ {{ "a_row_sum[tid] = 0;" if ownRowSums else "atomicStore(&a_row_sum[tid], 0);" }}
416
  }
417
  workgroupBarrier();
418
 
 
530
  let a3: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};
531
  let v = vec4<{{ aScalar }}>(a0, a1, a2, a3);
532
  packed = pack_a(v);
533
+ {{ "a_row_sum[tid] += dot4_packed(packed, 0x01010101u);" if ownRowSums else "atomicAdd(&a_row_sum[tid], sum4_a(v));" }}
534
  }
535
  a_tile[tid * KT_WORDS] = packed;
536
  }
build/webgpu/quant-exact-matrix.wgsl.jinja CHANGED
@@ -7,7 +7,7 @@ enable subgroup_size_control;
7
  enable chromium_experimental_subgroup_matrix;
8
  diagnostic(off, chromium.subgroup_matrix_uniformity);
9
  {{ env.wgsl.resourceDeclarations }}
10
- // Rare-boundary fallback: reproduce the reference's binary64 scale division
11
  // and accumulator product using integer significands; no f64 feature required.
12
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
13
  let low = a.x + b.x;
@@ -15,22 +15,44 @@ fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
15
  let with_carry = middle + u32(low < a.x);
16
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
17
  }
18
- fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {
19
- return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);
 
 
 
 
 
 
 
 
 
20
  }
 
21
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
22
- var q = value;
23
- var sticky = false;
24
- var guard = false;
25
- for (var bit = 0u; bit < shift; bit++) {
26
- sticky = sticky || guard;
27
- guard = (q.x & 1u) != 0u;
28
- q = quant_u96_shr(q);
 
 
 
 
29
  }
30
- if (guard && (sticky || (q.x & 1u) != 0u)) {
31
- q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));
 
 
 
 
 
 
 
 
32
  }
33
- return q;
34
  }
35
  fn quant_float_significand(bits: u32) -> u32 {
36
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
@@ -83,15 +105,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
83
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
84
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
85
  // significand by the exact accumulator into three little-endian u32 limbs.
86
- var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
87
- var operand = vec3<u32>(significand, 0u);
88
- var product = vec3<u32>(0u);
89
- loop {
90
- if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }
91
- magnitude >>= 1u;
92
- if (magnitude == 0u) { break; }
93
- operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));
94
- }
95
  var product_top = 31 - i32(countLeadingZeros(product.x));
96
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
97
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
@@ -106,6 +124,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
106
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
107
  }
108
 
 
 
 
 
 
109
  // A power-of-two division and an exactly represented <=48-bit product need
110
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
111
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
@@ -122,7 +145,7 @@ fn quant_normal_expansion_range(v: f32) -> bool {
122
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
123
  }
124
 
125
- fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
126
  let estimate = numerator_hi / denominator;
127
  // Anything outside this range saturates after adding an 8-bit zero point;
128
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
@@ -133,18 +156,18 @@ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32,
133
  let hi = lo + 1.0;
134
  let midpoint = lo + 0.5;
135
  let midpoint_hi = fma(midpoint, denominator, 0.0);
136
- if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
137
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
138
  // The high-word subtraction is exact for these similarly sized products
139
  // (Sterbenz); adding the residual difference therefore preserves its sign
140
  // even when the rounded high words straddle adjacent f32 values.
141
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
142
- // Escalate ambiguous expansion signs instead of changing the tie tolerance.
143
  // Six FMA/product tails and their additions fit within this conservative
144
- // 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.
145
- if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
146
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
147
- if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
148
  }
149
  if (midpoint_delta < 0.0) {
150
  return i32(lo);
@@ -176,6 +199,7 @@ fn quant_round_power_two(acc: i32, exponent: i32) -> i32 {
176
  return select(i32(rounded), -i32(rounded), acc < 0);
177
  }
178
 
 
179
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
180
  if (acc == 0) { return 0; }
181
  let a_bits = bitcast<u32>(a_s);
@@ -195,17 +219,17 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
195
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
196
  let direct_hi = fma(acc_f, a_s, 0.0);
197
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
198
- if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
199
- return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);
200
  }
201
 
202
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
203
  // which side of a rounding midpoint a near-half value occupies.
204
  let ab_hi = fma(a_s, b_s, 0.0);
205
  let ab_lo = fma(a_s, b_s, -ab_hi);
206
- if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return quant_round_binary64(acc, a_s, b_s, y_s); }
207
  let product_hi = fma(acc_f, ab_hi, 0.0);
208
- if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
209
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
210
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
211
  // Compare the expansion directly. Renormalizing it adds a cancelling
@@ -213,7 +237,7 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
213
  let denominator_bits = bitcast<u32>(y_s);
214
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
215
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
216
- return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);
217
  }
218
 
219
  // A conservative binary32 error filter accepts only a result safely inside one
@@ -232,35 +256,39 @@ fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
232
  // scale-only bounds cover every accumulator and can be shared across lanes.
233
  // Reserve two significands plus carry bits above FTZ, and a factor of two
234
  // below overflow for products, division and the expansion midpoint product.
235
- if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
236
- min(ea, eb) == 0u || max(ea, eb) >= 255u ||
237
- ea + eb < 180u || ea + eb > 347u ||
238
- ey < 53u || ey > 242u || ea + eb > ey + 220u) {
239
- return quant_round_binary64(acc, a_s, b_s, y_s);
240
- }
241
- let scale = fma(a_s, b_s, 0.0);
242
- let product = fma(f32(acc), scale, 0.0);
243
- let estimate = product / y_s;
244
- if (estimate <= -1024.0) { return -1024; }
245
- if (estimate >= 1024.0) { return 1024; }
246
- let nearest = round(estimate);
247
- // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
248
- // products, quotient, and distance arithmetic, plus binary64 rounding.
249
- let margin = max(1.0, abs(estimate)) * 0x1p-19;
250
- if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
251
  {% if device.adapterInfo.vendor != "apple" %}
252
- // A rounded half-integer estimate can hide which side the exact f32-scale
253
- // ratio lies on. Resolve that one-ulp neighborhood conservatively outside
254
- // the compact fast path; exact power-of-two ratios already have a cheap
255
- // and correct path in round_requantized_precise.
256
- if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {
257
- let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
258
- min(a_bits, min(b_bits, y_bits)) != 0u &&
259
- max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
260
- if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }
261
- }
262
  {% endif %}
263
- return round_requantized_precise(acc, a_s, b_s, y_s);
 
 
 
 
 
264
  }
265
 
266
  // Adjusted byte integers fit exactly in f32. Each bounded f32 dot product
@@ -281,14 +309,77 @@ var<workgroup> scratch: array<array<array<f32, 64>, 4>, {{ sgmatSubgroups }}>;
281
  {% endif %}
282
  {% endif %}
283
 
284
- @compute @workgroup_size({{ sgmatWorkgroup }}){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
285
- fn main(@builtin(workgroup_id) wid: vec3<u32>,
286
- {% if not precastOperands or not matrixSubgroupId %}
287
- @builtin(local_invocation_index) tid: u32,
288
- {% endif %}
289
- @builtin(subgroup_invocation_id) lane: u32,
290
- @builtin(subgroup_id) subgroup_index: u32) {
291
- let subgroup = subgroup_index;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  let base_A = (subgroup % {{ sgmatRowGroups }}u) * 16u;
293
  let base_B = (subgroup / {{ sgmatRowGroups }}u) * 32u;
294
  let row = lane / 4u;
@@ -296,12 +387,12 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
296
  // Bound adjusted byte magnitudes from scalar zero points. A column-wise
297
  // B zero point keeps the full byte-difference bound for the whole tile.
298
  let max_a = {% if matrixZeroPerRow %}255u{% else %}u32(max(abs({{ 0 if aUnsigned else (0 - 128) }} - i32(a_zero_point[0])), abs({{ 255 if aUnsigned else 127 }} - i32(a_zero_point[0])))){% endif %};
299
- let max_b = {% if hasBZero and not bZeroPerColumn %}u32(max(abs({{ 0 if bUnsigned else (0 - 128) }} - i32(b_zero_point[0])), abs({{ 255 if bUnsigned else 127 }} - i32(b_zero_point[0])))){% else %}{{ 255 if hasBZero or bUnsigned else 128 }}u{% endif %};
300
  let partial_k = (16777216u / (max_a * max_b) / TILE_K) * TILE_K;
301
  var totals: array<i32, 16>;
302
  for (var partial = 0u; partial < params.K; partial += partial_k) {
303
  {% for r in range(2) %}{% for c in range(4) %}
304
- var matC{{ r }}{{ c }}: subgroup_matrix_result<f32, 8, 8>;
305
  {% endfor %}{% endfor %}
306
  let partial_end = min(params.K, partial + partial_k);
307
  for (var kb = partial; kb < partial_end; kb += TILE_K) {
@@ -328,13 +419,13 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
328
  {% endif %}
329
  for (var step = 0u; step < TILE_K; step += 8u) {
330
  {% for r in range(2) %}
331
- let matA{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<{{ precastScalar if precastOperands else "f32" }}, 8, 8>, row_major>(&{{ "a" if precastOperands else "tile_A" }}, {% if precastOperands %}(wid.y * TILE_M + base_A + {{ r * 8 }}u) * PADDED_K + kb + step{% else %}(base_A + {{ r * 8 }}u) * TILE_K + step{% endif %}, {{ "PADDED_K" if precastOperands else "TILE_K" }});
332
  {% endfor %}
333
  {% for c in range(4) %}
334
- let matB{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<{{ precastScalar if precastOperands else "f32" }}, 8, 8>, row_major>(&{{ "b" if precastOperands else "tile_B" }}, {% if precastOperands %}{% if matrixBatchB %}wid.z * PADDED_K * PADDED_N + {% endif %}(kb + step) * PADDED_N + wid.x * TILE_N + base_B + {{ c * 8 }}u{% else %}step * TILE_N + base_B + {{ c * 8 }}u{% endif %}, {{ "PADDED_N" if precastOperands else "TILE_N" }});
335
  {% endfor %}
336
  {% for r in range(2) %}{% for c in range(4) %}
337
- matC{{ r }}{{ c }} = subgroupMatrixMultiplyAccumulate(matA{{ r }}, matB{{ c }}, matC{{ r }}{{ c }});
338
  {% endfor %}{% endfor %}
339
  }
340
  {% if not precastOperands %}
@@ -345,7 +436,7 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
345
  // The prepared operands need no staging barriers. Publish all eight
346
  // matrices together before converting the bounded partial to int32.
347
  {% for r in range(2) %}{% for c in range(4) %}
348
- subgroupMatrixStore<row_major>(&matrix_out, subgroup * 512u + {{ r * 256 + c * 64 }}u, matC{{ r }}{{ c }}, 8u);
349
  {% endfor %}{% endfor %}
350
  workgroupBarrier();
351
  {% for r in range(2) %}{% for c in range(4) %}{% for h in range(2) %}
@@ -359,7 +450,7 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
359
  {% endif %}
360
  {% for r in range(2) %}
361
  {% for c in range(4) %}
362
- subgroupMatrixStore<row_major>({% if sgmatReuseStaging %}&tile_A{% else %}&scratch[subgroup][{{ c }}]{% endif %}, {% if sgmatReuseStaging %}subgroup * 256u + {{ c * 64 }}u{% else %}0u{% endif %}, matC{{ r }}{{ c }}, 8u);
363
  {% endfor %}
364
  workgroupBarrier();
365
  {% for c in range(4) %}{% for h in range(2) %}
@@ -381,4 +472,24 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>,
381
  }
382
  }
383
  {% endfor %}{% endfor %}{% endfor %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  }
 
7
  enable chromium_experimental_subgroup_matrix;
8
  diagnostic(off, chromium.subgroup_matrix_uniformity);
9
  {{ env.wgsl.resourceDeclarations }}
10
+ // Rare-boundary fallback: compute binary64-equivalent scale division
11
  // and accumulator product using integer significands; no f64 feature required.
12
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
13
  let low = a.x + b.x;
 
15
  let with_carry = middle + u32(low < a.x);
16
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
17
  }
18
+ // The low word is the ordinary u32 product. Split at 16 bits so every
19
+ // partial product and carry used to construct the high word fits in u32.
20
+ fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {
21
+ let a_low = a & 0xffffu;
22
+ let a_high = a >> 16u;
23
+ let b_low = b & 0xffffu;
24
+ let b_high = b >> 16u;
25
+ let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);
26
+ let cross_high = a_low * b_high + (cross_low & 0xffffu);
27
+ let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);
28
+ return vec2<u32>(a * b, high);
29
  }
30
+
31
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
32
+ if (shift == 0u) { return value; }
33
+ if (shift > 96u) { return vec3<u32>(0u); }
34
+
35
+ let limbs = vec4<u32>(value, 0u);
36
+ let word = shift >> 5u;
37
+ let bits = shift & 31u;
38
+ let middle = limbs[min(word + 1u, 3u)];
39
+ let high = limbs[min(word + 2u, 3u)];
40
+ var quotient = vec3<u32>(limbs[word], middle, high);
41
+ if (bits != 0u) {
42
+ quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));
43
  }
44
+
45
+ // The highest discarded bit is the guard. With the guard set, any lower set
46
+ // bit rounds up; an exact midpoint rounds to the even quotient.
47
+ let guard_word = (shift - 1u) >> 5u;
48
+ let guard_bit = 1u << ((shift - 1u) & 31u);
49
+ let discarded = limbs[guard_word];
50
+ let sticky = (discarded & (guard_bit - 1u)) != 0u ||
51
+ (guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);
52
+ if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {
53
+ quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));
54
  }
55
+ return quotient;
56
  }
57
  fn quant_float_significand(bits: u32) -> u32 {
58
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
 
105
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
106
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
107
  // significand by the exact accumulator into three little-endian u32 limbs.
108
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
109
+ let low_product = quant_mul_u32(significand.x, magnitude);
110
+ let high_product = quant_mul_u32(significand.y, magnitude);
111
+ let middle = low_product.y + high_product.x;
112
+ let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));
 
 
 
 
113
  var product_top = 31 - i32(countLeadingZeros(product.x));
114
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
115
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
 
124
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
125
  }
126
 
127
+ // Requantized results lie in [-1024, 1024]. The expansion helpers return this
128
+ // marker at a binary64 boundary instead of resolving it themselves, so a
129
+ // round_requantized call carries one binary64 resolver after inlining rather
130
+ // than one per boundary exit.
131
+ const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;
132
  // A power-of-two division and an exactly represented <=48-bit product need
133
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
134
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
 
145
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
146
  }
147
 
148
+ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {
149
  let estimate = numerator_hi / denominator;
150
  // Anything outside this range saturates after adding an 8-bit zero point;
151
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
 
156
  let hi = lo + 1.0;
157
  let midpoint = lo + 0.5;
158
  let midpoint_hi = fma(midpoint, denominator, 0.0);
159
+ if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
160
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
161
  // The high-word subtraction is exact for these similarly sized products
162
  // (Sterbenz); adding the residual difference therefore preserves its sign
163
  // even when the rounded high words straddle adjacent f32 values.
164
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
165
+ // Resolve ambiguous expansion signs with binary64-equivalent arithmetic.
166
  // Six FMA/product tails and their additions fit within this conservative
167
+ // 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.
168
+ if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
169
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
170
+ if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }
171
  }
172
  if (midpoint_delta < 0.0) {
173
  return i32(lo);
 
199
  return select(i32(rounded), -i32(rounded), acc < 0);
200
  }
201
 
202
+ // Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.
203
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
204
  if (acc == 0) { return 0; }
205
  let a_bits = bitcast<u32>(a_s);
 
219
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
220
  let direct_hi = fma(acc_f, a_s, 0.0);
221
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
222
+ if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }
223
+ return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);
224
  }
225
 
226
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
227
  // which side of a rounding midpoint a near-half value occupies.
228
  let ab_hi = fma(a_s, b_s, 0.0);
229
  let ab_lo = fma(a_s, b_s, -ab_hi);
230
+ if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }
231
  let product_hi = fma(acc_f, ab_hi, 0.0);
232
+ if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }
233
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
234
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
235
  // Compare the expansion directly. Renormalizing it adds a cancelling
 
237
  let denominator_bits = bitcast<u32>(y_s);
238
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
239
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
240
+ return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);
241
  }
242
 
243
  // A conservative binary32 error filter accepts only a result safely inside one
 
256
  // scale-only bounds cover every accumulator and can be shared across lanes.
257
  // Reserve two significands plus carry bits above FTZ, and a factor of two
258
  // below overflow for products, division and the expansion midpoint product.
259
+ // Every exit that needs the binary64 resolver falls through to its one call.
260
+ if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
261
+ min(ea, eb) == 0u || max(ea, eb) >= 255u ||
262
+ ea + eb < 180u || ea + eb > 347u ||
263
+ ey < 53u || ey > 242u || ea + eb > ey + 220u)) {
264
+ let scale = fma(a_s, b_s, 0.0);
265
+ let product = fma(f32(acc), scale, 0.0);
266
+ let estimate = product / y_s;
267
+ if (estimate <= -1024.0) { return -1024; }
268
+ if (estimate >= 1024.0) { return 1024; }
269
+ let nearest = round(estimate);
270
+ // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
271
+ // products, quotient, and distance arithmetic, plus binary64 rounding.
272
+ let margin = max(1.0, abs(estimate)) * 0x1p-19;
273
+ if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
274
+ var use_expansion = true;
275
  {% if device.adapterInfo.vendor != "apple" %}
276
+ // The conversion, two products and division can put the estimate several
277
+ // ulps across a midpoint. Allow eight unit roundoffs before relying on
278
+ // float residuals. Exact power-of-two ratios retain their integer shortcut.
279
+ if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {
280
+ let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
281
+ min(a_bits, min(b_bits, y_bits)) != 0u &&
282
+ max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
283
+ use_expansion = dyadic_scales;
284
+ }
 
285
  {% endif %}
286
+ if (use_expansion) {
287
+ let rounded = round_requantized_precise(acc, a_s, b_s, y_s);
288
+ if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }
289
+ }
290
+ }
291
+ return quant_round_binary64(acc, a_s, b_s, y_s);
292
  }
293
 
294
  // Adjusted byte integers fit exactly in f32. Each bounded f32 dot product
 
309
  {% endif %}
310
  {% endif %}
311
 
312
+ // A subgroup owns one matrix tile only after its actual population and the
313
+ // workgroup-wide bank count are proven. The elected subgroup leader claims
314
+ // the role; local invocation IDs only publish the workgroup-wide decision.
315
+ var<workgroup> matrixRoleCount: atomic<u32>;
316
+ var<workgroup> matrixRejected: atomic<u32>;
317
+ var<workgroup> matrixAccepted: u32;
318
+
319
+ fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
320
+ // WGSL initializes workgroup variables to zero before this entry point.
321
+ let population = subgroupBallot(true);
322
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
323
+ + countOneBits(population.z) + countOneBits(population.w);
324
+ var claimed = 0u;
325
+ if (subgroupElect()) {
326
+ claimed = atomicAdd(&matrixRoleCount, 1u);
327
+ if (width != requiredWidth || populationCount != requiredWidth) {
328
+ atomicStore(&matrixRejected, 1u);
329
+ }
330
+ }
331
+ // Reconverge every invocation before broadcasting the elected claim.
332
+ workgroupBarrier();
333
+ return subgroupBroadcastFirst(claimed);
334
+ }
335
+
336
+ fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
337
+ if (localIndex == 0u) {
338
+ matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
339
+ && atomicLoad(&matrixRoleCount) == bankCount);
340
+ }
341
+ // The uniform load both publishes the leader's decision and gives the
342
+ // compiler a workgroup-uniform condition for the barrier-containing arms.
343
+ return workgroupUniformLoad(&matrixAccepted) != 0u;
344
+ }
345
+ // The portable arm owns two result components per logical 32-invocation group.
346
+ // Staging casts, 8-wide K steps, barriers and the epilogue match the
347
+ // subgroup-matrix arm.
348
+ var<private> matrixSoftwareLane: u32;
349
+
350
+ fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,
351
+ acc: vec2<f32>) -> vec2<f32> {
352
+ var value = acc;
353
+ for (var k = 0u; k < 8u; k += 1u) {
354
+ value = fma(vec2<f32>(lhs[k]), rhs[k], value);
355
+ }
356
+ return value;
357
+ }
358
+
359
+ {% 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 %}
360
+
361
+ {% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}
362
+ {% if kind == "left" %}array<f32, 8>(
363
+ {% for k in range(8) %}f32((*({{ pointer }}))[({{ offset }}) + (matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u]){{ "," if k < 7 else "" }}
364
+ {% endfor %})
365
+ {% else %}array<vec2<f32>, 8>(
366
+ {% for k in range(8) %}vec2<f32>(
367
+ {% for h in range(2) %}f32((*({{ pointer }}))[({{ offset }}) + {{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u]){{ "," if h == 0 else "" }}
368
+ {% endfor %}){{ "," if k < 7 else "" }}
369
+ {% endfor %})
370
+ {% endif %}{% endif %}{% endmacro %}
371
+
372
+ {% 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 %}
373
+
374
+ {% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{
375
+ let matrixPointer = {{ pointer }};
376
+ let matrixValue = {{ value }};
377
+ {% 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" }};
378
+ {% endfor %}}{% endif %}{% endmacro %}
379
+
380
+ {% macro matrixKernelBody(matrixSoftware) %}
381
+
382
+ let subgroup = matrixRole;
383
  let base_A = (subgroup % {{ sgmatRowGroups }}u) * 16u;
384
  let base_B = (subgroup / {{ sgmatRowGroups }}u) * 32u;
385
  let row = lane / 4u;
 
387
  // Bound adjusted byte magnitudes from scalar zero points. A column-wise
388
  // B zero point keeps the full byte-difference bound for the whole tile.
389
  let max_a = {% if matrixZeroPerRow %}255u{% else %}u32(max(abs({{ 0 if aUnsigned else (0 - 128) }} - i32(a_zero_point[0])), abs({{ 255 if aUnsigned else 127 }} - i32(a_zero_point[0])))){% endif %};
390
+ let max_b = {% if not bZeroPerColumn %}u32(max(abs({{ 0 if bUnsigned else (0 - 128) }} - i32(b_zero_point[0])), abs({{ 255 if bUnsigned else 127 }} - i32(b_zero_point[0])))){% else %}{{ 255 }}u{% endif %};
391
  let partial_k = (16777216u / (max_a * max_b) / TILE_K) * TILE_K;
392
  var totals: array<i32, 16>;
393
  for (var partial = 0u; partial < params.K; partial += partial_k) {
394
  {% for r in range(2) %}{% for c in range(4) %}
395
+ var matC{{ r }}{{ c }}: {{ matrixType(matrixSoftware, "result", "f32") }};
396
  {% endfor %}{% endfor %}
397
  let partial_end = min(params.K, partial + partial_k);
398
  for (var kb = partial; kb < partial_end; kb += TILE_K) {
 
419
  {% endif %}
420
  for (var step = 0u; step < TILE_K; step += 8u) {
421
  {% for r in range(2) %}
422
+ let matA{{ r }} = {% set quantExactAOffset %}{% if precastOperands %}(wid.y * TILE_M + base_A + {{ r * 8 }}u) * PADDED_K + kb + step{% else %}(base_A + {{ r * 8 }}u) * TILE_K + step{% endif %}{% endset %}{{ matrixLoad(matrixSoftware, "left", precastScalar if precastOperands else "f32", "row_major", "&" ~ ("a" if precastOperands else "tile_A"), quantExactAOffset, "PADDED_K" if precastOperands else "TILE_K") }};
423
  {% endfor %}
424
  {% for c in range(4) %}
425
+ let matB{{ c }} = {% set quantExactBOffset %}{% if precastOperands %}{% if matrixBatchB %}wid.z * PADDED_K * PADDED_N + {% endif %}(kb + step) * PADDED_N + wid.x * TILE_N + base_B + {{ c * 8 }}u{% else %}step * TILE_N + base_B + {{ c * 8 }}u{% endif %}{% endset %}{{ matrixLoad(matrixSoftware, "right", precastScalar if precastOperands else "f32", "row_major", "&" ~ ("b" if precastOperands else "tile_B"), quantExactBOffset, "PADDED_N" if precastOperands else "TILE_N") }};
426
  {% endfor %}
427
  {% for r in range(2) %}{% for c in range(4) %}
428
+ matC{{ r }}{{ c }} = {{ matrixMma(matrixSoftware, "f32", "matA" ~ (r), "matB" ~ (c), "matC" ~ (r) ~ (c)) }};
429
  {% endfor %}{% endfor %}
430
  }
431
  {% if not precastOperands %}
 
436
  // The prepared operands need no staging barriers. Publish all eight
437
  // matrices together before converting the bounded partial to int32.
438
  {% for r in range(2) %}{% for c in range(4) %}
439
+ {{ matrixStore(matrixSoftware, "row_major", "&matrix_out", "subgroup * 512u + " ~ (r * 256 + c * 64) ~ "u", "matC" ~ (r) ~ (c), "8u") }}
440
  {% endfor %}{% endfor %}
441
  workgroupBarrier();
442
  {% for r in range(2) %}{% for c in range(4) %}{% for h in range(2) %}
 
450
  {% endif %}
451
  {% for r in range(2) %}
452
  {% for c in range(4) %}
453
+ {% set quantExactStorePointer %}{% if sgmatReuseStaging %}&tile_A{% else %}&scratch[subgroup][{{ c }}]{% endif %}{% endset %}{% set quantExactStoreOffset %}{% if sgmatReuseStaging %}subgroup * 256u + {{ c * 64 }}u{% else %}0u{% endif %}{% endset %}{{ matrixStore(matrixSoftware, "row_major", quantExactStorePointer, quantExactStoreOffset, "matC" ~ (r) ~ (c), "8u") }}
454
  {% endfor %}
455
  workgroupBarrier();
456
  {% for c in range(4) %}{% for h in range(2) %}
 
472
  }
473
  }
474
  {% endfor %}{% endfor %}{% endfor %}
475
+
476
+ {% endmacro %}
477
+ @compute @workgroup_size({{ sgmatWorkgroup }}){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
478
+ fn main(
479
+ @builtin(workgroup_id) wid: vec3<u32>,
480
+ @builtin(local_invocation_index) tid: u32,
481
+ @builtin(subgroup_size) matrixPhysicalWidth: u32,
482
+ @builtin(subgroup_invocation_id) matrixPhysicalLane: u32
483
+ ) {
484
+ let matrixRole = claimMatrixSubgroupRole(matrixPhysicalWidth, 32u);
485
+ let matrixAcceptedHere = matrixTopologyAccepted(tid, {{ sgmatWorkgroup }}u / 32u);
486
+ matrixSoftwareLane = tid % 32u;
487
+ if (matrixAcceptedHere) {
488
+ let lane = matrixPhysicalLane;
489
+ {{ matrixKernelBody(false) }}
490
+ } else {
491
+ let matrixRole = tid / 32u;
492
+ let lane = tid % 32u;
493
+ {{ matrixKernelBody(true) }}
494
+ }
495
  }
build/webgpu/quant-exact-portable.wgsl.jinja CHANGED
@@ -1,6 +1,6 @@
1
  {% set integerStoreRow = matrixScalePerRow or (matrixHasBias and matrixBiasPerRow) %}
2
  {% set integerStoreColumn = (requantize and bScalePerColumn) or (matrixHasBias and not matrixBiasPerRow) %}
3
- // Rare-boundary fallback: reproduce the reference's binary64 scale division
4
  // and accumulator product using integer significands; no f64 feature required.
5
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
6
  let low = a.x + b.x;
@@ -8,22 +8,44 @@ fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
8
  let with_carry = middle + u32(low < a.x);
9
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
10
  }
11
- fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {
12
- return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);
 
 
 
 
 
 
 
 
 
13
  }
 
14
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
15
- var q = value;
16
- var sticky = false;
17
- var guard = false;
18
- for (var bit = 0u; bit < shift; bit++) {
19
- sticky = sticky || guard;
20
- guard = (q.x & 1u) != 0u;
21
- q = quant_u96_shr(q);
 
 
 
 
22
  }
23
- if (guard && (sticky || (q.x & 1u) != 0u)) {
24
- q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));
 
 
 
 
 
 
 
 
25
  }
26
- return q;
27
  }
28
  fn quant_float_significand(bits: u32) -> u32 {
29
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
@@ -76,15 +98,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
76
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
77
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
78
  // significand by the exact accumulator into three little-endian u32 limbs.
79
- var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
80
- var operand = vec3<u32>(significand, 0u);
81
- var product = vec3<u32>(0u);
82
- loop {
83
- if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }
84
- magnitude >>= 1u;
85
- if (magnitude == 0u) { break; }
86
- operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));
87
- }
88
  var product_top = 31 - i32(countLeadingZeros(product.x));
89
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
90
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
@@ -99,6 +117,11 @@ fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
99
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
100
  }
101
 
 
 
 
 
 
102
  // A power-of-two division and an exactly represented <=48-bit product need
103
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
104
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
@@ -115,7 +138,7 @@ fn quant_normal_expansion_range(v: f32) -> bool {
115
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
116
  }
117
 
118
- fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
119
  let estimate = numerator_hi / denominator;
120
  // Anything outside this range saturates after adding an 8-bit zero point;
121
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
@@ -126,18 +149,18 @@ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32,
126
  let hi = lo + 1.0;
127
  let midpoint = lo + 0.5;
128
  let midpoint_hi = fma(midpoint, denominator, 0.0);
129
- if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
130
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
131
  // The high-word subtraction is exact for these similarly sized products
132
  // (Sterbenz); adding the residual difference therefore preserves its sign
133
  // even when the rounded high words straddle adjacent f32 values.
134
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
135
- // Escalate ambiguous expansion signs instead of changing the tie tolerance.
136
  // Six FMA/product tails and their additions fit within this conservative
137
- // 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.
138
- if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }
139
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
140
- if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
141
  }
142
  if (midpoint_delta < 0.0) {
143
  return i32(lo);
@@ -169,6 +192,7 @@ fn quant_round_power_two(acc: i32, exponent: i32) -> i32 {
169
  return select(i32(rounded), -i32(rounded), acc < 0);
170
  }
171
 
 
172
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
173
  if (acc == 0) { return 0; }
174
  let a_bits = bitcast<u32>(a_s);
@@ -188,17 +212,17 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
188
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
189
  let direct_hi = fma(acc_f, a_s, 0.0);
190
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
191
- if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
192
- return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);
193
  }
194
 
195
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
196
  // which side of a rounding midpoint a near-half value occupies.
197
  let ab_hi = fma(a_s, b_s, 0.0);
198
  let ab_lo = fma(a_s, b_s, -ab_hi);
199
- if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return quant_round_binary64(acc, a_s, b_s, y_s); }
200
  let product_hi = fma(acc_f, ab_hi, 0.0);
201
- if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }
202
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
203
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
204
  // Compare the expansion directly. Renormalizing it adds a cancelling
@@ -206,7 +230,7 @@ fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
206
  let denominator_bits = bitcast<u32>(y_s);
207
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
208
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
209
- return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);
210
  }
211
 
212
  // A conservative binary32 error filter accepts only a result safely inside one
@@ -225,37 +249,42 @@ fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
225
  // scale-only bounds cover every accumulator and can be shared across lanes.
226
  // Reserve two significands plus carry bits above FTZ, and a factor of two
227
  // below overflow for products, division and the expansion midpoint product.
228
- if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
229
- min(ea, eb) == 0u || max(ea, eb) >= 255u ||
230
- ea + eb < 180u || ea + eb > 347u ||
231
- ey < 53u || ey > 242u || ea + eb > ey + 220u) {
232
- return quant_round_binary64(acc, a_s, b_s, y_s);
233
- }
234
- let scale = fma(a_s, b_s, 0.0);
235
- let product = fma(f32(acc), scale, 0.0);
236
- let estimate = product / y_s;
237
- if (estimate <= -1024.0) { return -1024; }
238
- if (estimate >= 1024.0) { return 1024; }
239
- let nearest = round(estimate);
240
- // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
241
- // products, quotient, and distance arithmetic, plus binary64 rounding.
242
- let margin = max(1.0, abs(estimate)) * 0x1p-19;
243
- if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
244
  {% if device.adapterInfo.vendor != "apple" %}
245
- // A rounded half-integer estimate can hide which side the exact f32-scale
246
- // ratio lies on. Resolve that one-ulp neighborhood conservatively outside
247
- // the compact fast path; exact power-of-two ratios already have a cheap
248
- // and correct path in round_requantized_precise.
249
- if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {
250
- let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
251
- min(a_bits, min(b_bits, y_bits)) != 0u &&
252
- max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
253
- if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }
254
- }
255
  {% endif %}
256
- return round_requantized_precise(acc, a_s, b_s, y_s);
 
 
 
 
 
257
  }
258
 
 
259
  // Both integer-output and requantizing consumers share the vector GEMM body.
260
  // Its callback stores scalar outputs so padded operands also cover column tails.
261
  fn store_integer_result(value: i32, output_index: u32{% if integerStoreColumn %}, column: u32{% endif %}{% if integerStoreRow %}, row: u32{% endif %}) {
@@ -289,17 +318,22 @@ fn store_integer_result(value: i32, output_index: u32{% if integerStoreColumn %}
289
  {% set aVectorCount = (blockRowsValue * kTileValue / (4 * laneCount))|int %}
290
  {% set bVectorCount = (kTileValue * blockColsValue / (4 * laneCount))|int %}
291
  {% set batchStridesValue = false %}
 
 
292
 
293
- // High-intensity matrix multiplication for the large, untransposed layout:
294
  // Y[M,N] = alpha * A[M,K] @ B[K,N].
295
- // B may alternatively be stored physically as [N,K]; that mode retains vec4
296
  // K loads and transposes only while staging the tile in workgroup memory.
297
  //
298
- // Both inputs and the output are four-wide along their contiguous dimension.
 
299
  // The output-tile geometry and BK are selected from the shape and device's
300
  // workgroup-storage limit. f16 operands stay packed in global and workgroup
301
  // memory, then widen at the FMA so accumulation remains f32.
 
302
  const M: u32 = {{ M }}u;
 
303
  const K: u32 = {{ K }}u;
304
  const N: u32 = {{ N }}u;
305
  const K_V4: u32 = K / 4u;
@@ -321,6 +355,9 @@ fn main(
321
  @builtin(workgroup_id) wg: vec3<u32>,
322
  @builtin(local_invocation_id) lid: vec3<u32>
323
  ) {
 
 
 
324
  let li = lid.y * {{ workgroupColsValue }}u + lid.x;
325
  let mBase = wg.y * BM;
326
  let nBase = wg.x * BN;
@@ -356,7 +393,7 @@ fn main(
356
  let bColV4_{{ bv }} = bVector{{ bv }} % (BN / 4u);
357
  let bn{{ bv }} = nBase + bColV4_{{ bv }} * 4u;
358
  var bv4_{{ bv }} = vec4<{{ scalar }}>({{ scalar }}(0));
359
- if (bn{{ bv }} < N) {
360
  bv4_{{ bv }} = b[{{ bOff }}(kBase + bRow{{ bv }}) * {{ "B_N_V4" if exactIntegerPartialsValue else "N_V4" }} + bn{{ bv }} / 4u];
361
  }
362
  tileB[bRow{{ bv }} * (BN / 4u) + bColV4_{{ bv }}] = bv4_{{ bv }};
@@ -376,10 +413,10 @@ fn main(
376
  {% for i in range(threadRows) %}
377
  let av{{ i }} = tileA[aRow + {{ i }}u][kv];
378
  {% for j in range(threadColVectors) %}
379
- acc{{ i }}_{{ j }} = acc{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.x)) * bv0_{{ j }};
380
- acc{{ i }}_{{ j }} = acc{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.y)) * bv1_{{ j }};
381
- acc{{ i }}_{{ j }} = acc{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.z)) * bv2_{{ j }};
382
- acc{{ i }}_{{ j }} = acc{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.w)) * bv3_{{ j }};
383
  {% endfor %}
384
  {% endfor %}
385
  }
 
1
  {% set integerStoreRow = matrixScalePerRow or (matrixHasBias and matrixBiasPerRow) %}
2
  {% set integerStoreColumn = (requantize and bScalePerColumn) or (matrixHasBias and not matrixBiasPerRow) %}
3
+ // Rare-boundary fallback: compute binary64-equivalent scale division
4
  // and accumulator product using integer significands; no f64 feature required.
5
  fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
6
  let low = a.x + b.x;
 
8
  let with_carry = middle + u32(low < a.x);
9
  return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
10
  }
11
+ // The low word is the ordinary u32 product. Split at 16 bits so every
12
+ // partial product and carry used to construct the high word fits in u32.
13
+ fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {
14
+ let a_low = a & 0xffffu;
15
+ let a_high = a >> 16u;
16
+ let b_low = b & 0xffffu;
17
+ let b_high = b >> 16u;
18
+ let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);
19
+ let cross_high = a_low * b_high + (cross_low & 0xffffu);
20
+ let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);
21
+ return vec2<u32>(a * b, high);
22
  }
23
+
24
  fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
25
+ if (shift == 0u) { return value; }
26
+ if (shift > 96u) { return vec3<u32>(0u); }
27
+
28
+ let limbs = vec4<u32>(value, 0u);
29
+ let word = shift >> 5u;
30
+ let bits = shift & 31u;
31
+ let middle = limbs[min(word + 1u, 3u)];
32
+ let high = limbs[min(word + 2u, 3u)];
33
+ var quotient = vec3<u32>(limbs[word], middle, high);
34
+ if (bits != 0u) {
35
+ quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));
36
  }
37
+
38
+ // The highest discarded bit is the guard. With the guard set, any lower set
39
+ // bit rounds up; an exact midpoint rounds to the even quotient.
40
+ let guard_word = (shift - 1u) >> 5u;
41
+ let guard_bit = 1u << ((shift - 1u) & 31u);
42
+ let discarded = limbs[guard_word];
43
+ let sticky = (discarded & (guard_bit - 1u)) != 0u ||
44
+ (guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);
45
+ if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {
46
+ quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));
47
  }
48
+ return quotient;
49
  }
50
  fn quant_float_significand(bits: u32) -> u32 {
51
  return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
 
98
  let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
99
  // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
100
  // significand by the exact accumulator into three little-endian u32 limbs.
101
+ let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
102
+ let low_product = quant_mul_u32(significand.x, magnitude);
103
+ let high_product = quant_mul_u32(significand.y, magnitude);
104
+ let middle = low_product.y + high_product.x;
105
+ let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));
 
 
 
 
106
  var product_top = 31 - i32(countLeadingZeros(product.x));
107
  if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
108
  if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
 
117
  return select(i32(rounded.x), -i32(rounded.x), acc < 0);
118
  }
119
 
120
+ // Requantized results lie in [-1024, 1024]. The expansion helpers return this
121
+ // marker at a binary64 boundary instead of resolving it themselves, so a
122
+ // round_requantized call carries one binary64 resolver after inlining rather
123
+ // than one per boundary exit.
124
+ const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;
125
  // A power-of-two division and an exactly represented <=48-bit product need
126
  // no binary64 boundary resolver. This includes ordinary dyadic quantization.
127
  fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
 
138
  return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
139
  }
140
 
141
+ fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {
142
  let estimate = numerator_hi / denominator;
143
  // Anything outside this range saturates after adding an 8-bit zero point;
144
  // returning early also keeps floor/i32 conversion away from Inf and overflow.
 
149
  let hi = lo + 1.0;
150
  let midpoint = lo + 0.5;
151
  let midpoint_hi = fma(midpoint, denominator, 0.0);
152
+ if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
153
  let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
154
  // The high-word subtraction is exact for these similarly sized products
155
  // (Sterbenz); adding the residual difference therefore preserves its sign
156
  // even when the rounded high words straddle adjacent f32 values.
157
  let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
158
+ // Resolve ambiguous expansion signs with binary64-equivalent arithmetic.
159
  // Six FMA/product tails and their additions fit within this conservative
160
+ // 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.
161
+ if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
162
  if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
163
+ if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }
164
  }
165
  if (midpoint_delta < 0.0) {
166
  return i32(lo);
 
192
  return select(i32(rounded), -i32(rounded), acc < 0);
193
  }
194
 
195
+ // Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.
196
  fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
197
  if (acc == 0) { return 0; }
198
  let a_bits = bitcast<u32>(a_s);
 
212
  if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
213
  let direct_hi = fma(acc_f, a_s, 0.0);
214
  let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
215
+ if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }
216
+ return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);
217
  }
218
 
219
  // Keep the scale product as a two-float expansion. Its FMA residual preserves
220
  // which side of a rounding midpoint a near-half value occupies.
221
  let ab_hi = fma(a_s, b_s, 0.0);
222
  let ab_lo = fma(a_s, b_s, -ab_hi);
223
+ if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }
224
  let product_hi = fma(acc_f, ab_hi, 0.0);
225
+ if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }
226
  let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
227
  let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
228
  // Compare the expansion directly. Renormalizing it adds a cancelling
 
230
  let denominator_bits = bitcast<u32>(y_s);
231
  let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
232
  let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
233
+ return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);
234
  }
235
 
236
  // A conservative binary32 error filter accepts only a result safely inside one
 
249
  // scale-only bounds cover every accumulator and can be shared across lanes.
250
  // Reserve two significands plus carry bits above FTZ, and a factor of two
251
  // below overflow for products, division and the expansion midpoint product.
252
+ // Every exit that needs the binary64 resolver falls through to its one call.
253
+ if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
254
+ min(ea, eb) == 0u || max(ea, eb) >= 255u ||
255
+ ea + eb < 180u || ea + eb > 347u ||
256
+ ey < 53u || ey > 242u || ea + eb > ey + 220u)) {
257
+ let scale = fma(a_s, b_s, 0.0);
258
+ let product = fma(f32(acc), scale, 0.0);
259
+ let estimate = product / y_s;
260
+ if (estimate <= -1024.0) { return -1024; }
261
+ if (estimate >= 1024.0) { return 1024; }
262
+ let nearest = round(estimate);
263
+ // 32 binary32 unit roundoffs reserve room for the i32 conversion, two
264
+ // products, quotient, and distance arithmetic, plus binary64 rounding.
265
+ let margin = max(1.0, abs(estimate)) * 0x1p-19;
266
+ if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
267
+ var use_expansion = true;
268
  {% if device.adapterInfo.vendor != "apple" %}
269
+ // The conversion, two products and division can put the estimate several
270
+ // ulps across a midpoint. Allow eight unit roundoffs before relying on
271
+ // float residuals. Exact power-of-two ratios retain their integer shortcut.
272
+ if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {
273
+ let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
274
+ min(a_bits, min(b_bits, y_bits)) != 0u &&
275
+ max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
276
+ use_expansion = dyadic_scales;
277
+ }
 
278
  {% endif %}
279
+ if (use_expansion) {
280
+ let rounded = round_requantized_precise(acc, a_s, b_s, y_s);
281
+ if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }
282
+ }
283
+ }
284
+ return quant_round_binary64(acc, a_s, b_s, y_s);
285
  }
286
 
287
+
288
  // Both integer-output and requantizing consumers share the vector GEMM body.
289
  // Its callback stores scalar outputs so padded operands also cover column tails.
290
  fn store_integer_result(value: i32, output_index: u32{% if integerStoreColumn %}, column: u32{% endif %}{% if integerStoreRow %}, row: u32{% endif %}) {
 
318
  {% set aVectorCount = (blockRowsValue * kTileValue / (4 * laneCount))|int %}
319
  {% set bVectorCount = (kTileValue * blockColsValue / (4 * laneCount))|int %}
320
  {% set batchStridesValue = false %}
321
+ {% set STATIC_M = M is defined %}
322
+ {% set accName = "acc" %}
323
 
324
+ // High-intensity matrix multiplication:
325
  // Y[M,N] = alpha * A[M,K] @ B[K,N].
326
+ // A may be stored physically as [K,M], and B as [N,K]; a [N,K] B keeps vec4
327
  // K loads and transposes only while staging the tile in workgroup memory.
328
  //
329
+ // Unless the shape is ragged, both inputs and the output are four-wide along
330
+ // their contiguous dimension.
331
  // The output-tile geometry and BK are selected from the shape and device's
332
  // workgroup-storage limit. f16 operands stay packed in global and workgroup
333
  // memory, then widen at the FMA so accumulation remains f32.
334
+ {% if M is defined %}
335
  const M: u32 = {{ M }}u;
336
+ {% endif %}
337
  const K: u32 = {{ K }}u;
338
  const N: u32 = {{ N }}u;
339
  const K_V4: u32 = K / 4u;
 
355
  @builtin(workgroup_id) wg: vec3<u32>,
356
  @builtin(local_invocation_id) lid: vec3<u32>
357
  ) {
358
+ {% if not STATIC_M %}
359
+ let M = params.M;
360
+ {% endif %}
361
  let li = lid.y * {{ workgroupColsValue }}u + lid.x;
362
  let mBase = wg.y * BM;
363
  let nBase = wg.x * BN;
 
393
  let bColV4_{{ bv }} = bVector{{ bv }} % (BN / 4u);
394
  let bn{{ bv }} = nBase + bColV4_{{ bv }} * 4u;
395
  var bv4_{{ bv }} = vec4<{{ scalar }}>({{ scalar }}(0));
396
+ if (bn{{ bv }} < {{ (preparedNValue ~ "u") if exactIntegerPartialsValue and preparedNValue != N else "N" }}) {
397
  bv4_{{ bv }} = b[{{ bOff }}(kBase + bRow{{ bv }}) * {{ "B_N_V4" if exactIntegerPartialsValue else "N_V4" }} + bn{{ bv }} / 4u];
398
  }
399
  tileB[bRow{{ bv }} * (BN / 4u) + bColV4_{{ bv }}] = bv4_{{ bv }};
 
413
  {% for i in range(threadRows) %}
414
  let av{{ i }} = tileA[aRow + {{ i }}u][kv];
415
  {% for j in range(threadColVectors) %}
416
+ {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.x)) * bv0_{{ j }};
417
+ {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.y)) * bv1_{{ j }};
418
+ {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.z)) * bv2_{{ j }};
419
+ {{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.w)) * bv3_{{ j }};
420
  {% endfor %}
421
  {% endfor %}
422
  }
build/webgpu/quant-weight-k-major.wgsl.jinja CHANGED
@@ -12,19 +12,22 @@ fn {{ fn_name }}({% if per_column %}{{ param_name }}: u32{% endif %}) -> {{ retu
12
  // the fastest axis of a channels-last activation. Rows past the source K hold the
13
  // weight zero point, so padded lanes contribute exactly zero to
14
  // `(a - a_zero) * (b - b_zero)` while the GEMM keeps its aligned vec4 A path.
15
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
16
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
17
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
18
  // per-axis workgroup fold width.
19
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
20
- if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}
 
 
 
21
  {{ env.wgsl.resourceDeclarations }}
22
 
23
  {{ quant_read_column_zero("read_w_zero", "w_zero_point", false, per_column=wZeroPerChannel, param_name="oc", return_type=wScalar) }}
24
 
25
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
26
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
27
- {{ flat_index_2d(tunables.WORKGROUP_SIZE, "flat", guardInline=true) }}
28
  // Neighbouring invocations cover neighbouring output channels, so both the
29
  // K-major store and the requantization that later reads column `oc` stay
30
  // contiguous.
 
12
  // the fastest axis of a channels-last activation. Rows past the source K hold the
13
  // weight zero point, so padded lanes contribute exactly zero to
14
  // `(a - a_zero) * (b - b_zero)` while the GEMM keeps its aligned vec4 A path.
15
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
16
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
17
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
18
  // per-axis workgroup fold width.
19
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
20
+ if ({{ name }} >= {{ bound }}) {
21
+ return;
22
+ }
23
+ {% endmacro %}
24
  {{ env.wgsl.resourceDeclarations }}
25
 
26
  {{ quant_read_column_zero("read_w_zero", "w_zero_point", false, per_column=wZeroPerChannel, param_name="oc", return_type=wScalar) }}
27
 
28
  @compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})
29
  fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
30
+ {{ flat_index_2d(tunables.WORKGROUP_SIZE, "flat") }}
31
  // Neighbouring invocations cover neighbouring output channels, so both the
32
  // K-major store and the requantization that later reads column `oc` stay
33
  // contiguous.
build/webgpu/test.json CHANGED
The diff for this file is too large to render. See raw diff