sync 4385228f788d
Browse filesFiles changed (16)
- README.md+41-85
- build/webgpu/bench.json
- build/webgpu/conv-int-accumulate-spatial.wgsl.jinja+9-6
- build/webgpu/conv-int-im2col-spatial.wgsl.jinja+1-1
- build/webgpu/manifest.json
- build/webgpu/matrix-shaped-exact-precast.wgsl.jinjaAdded+398
- build/webgpu/metadata.json+1-115
- build/webgpu/qlinear-conv-im2col-nhwc.wgsl.jinja+6-3
- build/webgpu/qlinear-conv-nchw-x4.wgsl.jinja+91-62
- build/webgpu/qlinear-conv-nhwc-oc4.wgsl.jinja+94-63
- build/webgpu/qlinear-conv-requantize.wgsl.jinja+94-63
- build/webgpu/quant-dp4a-matmul.wgsl.jinja+92-63
- build/webgpu/quant-exact-matrix.wgsl.jinja+186-75
- build/webgpu/quant-exact-portable.wgsl.jinja+105-68
- build/webgpu/quant-weight-k-major.wgsl.jinja+6-3
- build/webgpu/test.json
62 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781794 unmodified lines18418518618762 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.## Device requirementsSome 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.## Files- [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)- [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](build/webgpu/test.json) — correctness cases- [`bench.json`](build/webgpu/bench.json) — benchmark cases- [`conv-int-accumulate-spatial.wgsl.jinja`](build/webgpu/conv-int-accumulate-spatial.wgsl.jinja)- [`conv-int-im2col-spatial.wgsl.jinja`](build/webgpu/conv-int-im2col-spatial.wgsl.jinja)- [`qlinear-conv-im2col-nhwc.wgsl.jinja`](build/webgpu/qlinear-conv-im2col-nhwc.wgsl.jinja)- [`qlinear-conv-nchw-x4.wgsl.jinja`](build/webgpu/qlinear-conv-nchw-x4.wgsl.jinja)- [`qlinear-conv-nhwc-oc4.wgsl.jinja`](build/webgpu/qlinear-conv-nhwc-oc4.wgsl.jinja)- [`qlinear-conv-requantize.wgsl.jinja`](build/webgpu/qlinear-conv-requantize.wgsl.jinja)- [`quant-dp4a-matmul.wgsl.jinja`](build/webgpu/quant-dp4a-matmul.wgsl.jinja)- [`quant-exact-matrix.wgsl.jinja`](build/webgpu/quant-exact-matrix.wgsl.jinja)- [`quant-exact-portable.wgsl.jinja`](build/webgpu/quant-exact-portable.wgsl.jinja)- [`quant-exact-prepare.wgsl.jinja`](build/webgpu/quant-exact-prepare.wgsl.jinja)- [`quant-weight-k-major.wgsl.jinja`](build/webgpu/quant-weight-k-major.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.3```Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.Replace each `*Data` placeholder with a typed array containing the corresponding input data.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.QLinearConv", { version: 1 });const { y } = await kernel({x: { data: xData, shape: [1, 1, 1, 1] },x_scale: { data: x_scaleData, shape: [1] },4 unmodified linesy_scale: { data: y_scaleData, shape: [1] },y_zero_point: { data: y_zero_pointData, shape: [1] },});```62 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331344 unmodified lines13914014114214362 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.- `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.## Device requirementsSome implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.## Files- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/test.json) — correctness cases- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/bench.json) — benchmark cases- [`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)- [`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)- [`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)- [`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)- [`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)- [`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)- [`qlinear-conv-requantize.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/qlinear-conv-requantize.wgsl.jinja)- [`quant-dp4a-matmul.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-dp4a-matmul.wgsl.jinja)- [`quant-exact-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-exact-matrix.wgsl.jinja)- [`quant-exact-portable.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-exact-portable.wgsl.jinja)- [`quant-exact-prepare.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.QLinearConv/blob/v1/build/webgpu/quant-exact-prepare.wgsl.jinja)- [`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)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.4```Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.QLinearConv", { version: 1 });const xData = Uint8Array.of(1);const x_scaleData = Float32Array.of(1);const x_zero_pointData = new Uint8Array(1);const wData = Int8Array.of(1, -1);const w_scaleData = Float32Array.of(1);const w_zero_pointData = new Int8Array(1);const y_scaleData = Float32Array.of(1e-20);const y_zero_pointData = Uint8Array.of(128);const { y } = await kernel({x: { data: xData, shape: [1, 1, 1, 1] },x_scale: { data: x_scaleData, shape: [1] },4 unmodified linesy_scale: { data: y_scaleData, shape: [1] },y_zero_point: { data: y_zero_pointData, shape: [1] },});console.log({ y });```
29 unmodified lines303132333435363738394041424344454647484911 unmodified lines6162636465666729 unmodified linesreturn 0;{% endif %}}{% endmacro %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}{{ env.wgsl.resourceDeclarations }}fn read_x(index: u32) -> i32 {{% if xUnsigned %}return i32(x[index]);{% else %}return x[index];{% endif %}}fn read_w(index: u32) -> i32 {11 unmodified lines@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, "index", guardInline=true) }}{% if channelsLast is defined and channelsLast %}let oc = index % params.outChannels;var t = index / params.outChannels;29 unmodified lines303132333435363738394041424344454647484950515211 unmodified lines6465666768697029 unmodified linesreturn 0;{% endif %}}{% endmacro %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}fn read_x(index: u32) -> i32 {{% if xUnsigned %}return i32(x[index]);{% else %}return x[index];{% endif %}}fn read_w(index: u32) -> i32 {11 unmodified lines@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, "index") }}{% if channelsLast is defined and channelsLast %}let oc = index % params.outChannels;var t = index / params.outChannels;
27 unmodified lines2829303132333427 unmodified lineslet iw = i32(ow * STRIDE_W + kw * DILATION_W) - PAD_LEFT;var {{ value }}: {{ bScalar if sampleScalar == "auto" else sampleScalar }} = {{ zero }}[0];if (ih >= 0 && ih < i32(params.inH) && iw >= 0 && iw < i32(params.inW)) {{{ 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 %}];}{% endmacro %}{{ spatial_constants() }}27 unmodified lines2829303132333427 unmodified lineslet iw = i32(ow * STRIDE_W + kw * DILATION_W) - PAD_LEFT;var {{ value }}: {{ bScalar if sampleScalar == "auto" else sampleScalar }} = {{ zero }}[0];if (ih >= 0 && ih < i32(params.inH) && iw >= 0 && iw < i32(params.inW)) {{{ value }} = {{ input }}[((batch * params.inChannels + ic) * params.inH + u32(ih)) * params.inW + u32(iw)];}{% endmacro %}{{ spatial_constants() }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398{% set WIDTH = matrixSubgroupWidth %}{% set GROUPS = (128 / WIDTH) | int %}{% set OWNED = (WIDTH / 32) | int %}{% set ROWS = 1 %}{% set COLS = 1 %}enable subgroups;enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: compute binary64-equivalent scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> { let low = a.x + b.x; let middle = a.y + b.y; let with_carry = middle + u32(low < a.x); return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}// The low word is the ordinary u32 product. Split at 16 bits so every// partial product and carry used to construct the high word fits in u32.fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> { let a_low = a & 0xffffu; let a_high = a >> 16u; let b_low = b & 0xffffu; let b_high = b >> 16u; let cross_low = a_high * b_low + ((a_low * b_low) >> 16u); let cross_high = a_low * b_high + (cross_low & 0xffffu); let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u); return vec2<u32>(a * b, high);}
fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> { if (shift == 0u) { return value; } if (shift > 96u) { return vec3<u32>(0u); }
let limbs = vec4<u32>(value, 0u); let word = shift >> 5u; let bits = shift & 31u; let middle = limbs[min(word + 1u, 3u)]; let high = limbs[min(word + 2u, 3u)]; var quotient = vec3<u32>(limbs[word], middle, high); if (bits != 0u) { quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits)); }
// The highest discarded bit is the guard. With the guard set, any lower set // bit rounds up; an exact midpoint rounds to the even quotient. let guard_word = (shift - 1u) >> 5u; let guard_bit = 1u << ((shift - 1u) & 31u); let discarded = limbs[guard_word]; let sticky = (discarded & (guard_bit - 1u)) != 0u || (guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u); if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) { quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u)); } return quotient;}fn quant_float_significand(bits: u32) -> u32 { return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);}fn quant_float_exponent(bits: u32) -> i32 { return max(1, i32((bits >> 23u) & 255u)) - 150;}fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 { if (acc == 0) { return 0; } let a_bits = bitcast<u32>(a_s); let b_bits = bitcast<u32>(b_s); let y_bits = bitcast<u32>(y_s); let a = quant_float_significand(a_bits); let b = quant_float_significand(b_bits); let denominator = quant_float_significand(y_bits); if (a == 0u || b == 0u) { return 0; } // The exact product of two 24-bit significands occupies at most 48 bits. let p0 = (a & 65535u) * (b & 65535u); let cross = (a >> 16u) * (b & 65535u) + (b >> 16u) * (a & 65535u); let product_low = p0 + (cross << 16u); let product_high = (a >> 16u) * (b >> 16u) + (cross >> 16u) + u32(product_low < p0); var input_bit = select(31 - i32(countLeadingZeros(product_low)), 63 - i32(countLeadingZeros(product_high)), product_high != 0u); var remainder = 0u; var significant_bits = 0u; var leading_exponent = 0; var significand = vec2<u32>(0u); // Long division generates the 53 bits of the binary64 multiplier. The // remainder fits in 25 bits, including its left shift. At most 24 leading // zero bits precede the first significant bit. loop { var incoming = 0u; if (input_bit >= 32) { incoming = (product_high >> u32(input_bit - 32)) & 1u; } else if (input_bit >= 0) { incoming = (product_low >> u32(input_bit)) & 1u; } remainder = (remainder << 1u) | incoming; let digit = u32(remainder >= denominator); if (digit != 0u) { remainder -= denominator; } if (significant_bits != 0u || digit != 0u) { if (significant_bits == 0u) { leading_exponent = input_bit; } significand = vec2<u32>((significand.x << 1u) | digit, (significand.y << 1u) | (significand.x >> 31u)); significant_bits++; } input_bit--; if (significant_bits == 53u) { break; } } let twice_remainder = remainder << 1u; if (twice_remainder > denominator || (twice_remainder == denominator && (significand.x & 1u) != 0u)) { let low = significand.x + 1u; significand = vec2<u32>(low, significand.y + u32(low == 0u)); } let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52; // abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's // significand by the exact accumulator into three little-endian u32 limbs. let magnitude = select(u32(acc), 0u - u32(acc), acc < 0); let low_product = quant_mul_u32(significand.x, magnitude); let high_product = quant_mul_u32(significand.y, magnitude); let middle = low_product.y + high_product.x; let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y)); var product_top = 31 - i32(countLeadingZeros(product.x)); if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); } if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); } if (product_top + scale_exponent >= 10) { return select(1024, -1024, acc < 0); } if (product_top + scale_exponent < -2) { return 0; } let product_shift = u32(max(0, product_top - 52)); let rounded_product = quant_u96_round_shift(product, product_shift); let result_exponent = scale_exponent + i32(product_shift); var rounded = rounded_product; if (result_exponent < 0) { rounded = quant_u96_round_shift(rounded_product, u32(-result_exponent)); } else { rounded.x <<= u32(result_exponent); } return select(i32(rounded.x), -i32(rounded.x), acc < 0);}
// Requantized results lie in [-1024, 1024]. The expansion helpers return this// marker at a binary64 boundary instead of resolving it themselves, so a// round_requantized call carries one binary64 resolver after inlining rather// than one per boundary exit.const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool { let magnitude = select(u32(acc), 0u - u32(acc), acc < 0); let significand = quant_float_significand(bitcast<u32>(scale)); let integer_bits = 32u - countLeadingZeros(magnitude) - countTrailingZeros(magnitude); let scale_bits = 32u - countLeadingZeros(significand) - countTrailingZeros(significand); return integer_bits + scale_bits <= 48u;}fn quant_normal_expansion_range(v: f32) -> bool { let exponent = (bitcast<u32>(v) >> 23u) & 255u; // Reserve two binary32 significands plus four carry/error bits above the // minimum normal exponent, so residual arithmetic avoids FTZ underflow. return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}
fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 { let estimate = numerator_hi / denominator; // Anything outside this range saturates after adding an 8-bit zero point; // returning early also keeps floor/i32 conversion away from Inf and overflow. if (estimate <= -1024.0) { return -1024; } if (estimate >= 1024.0) { return 1024; }
let lo = floor(estimate); let hi = lo + 1.0; let midpoint = lo + 0.5; let midpoint_hi = fma(midpoint, denominator, 0.0); if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; } let midpoint_lo = fma(midpoint, denominator, -midpoint_hi); // The high-word subtraction is exact for these similarly sized products // (Sterbenz); adding the residual difference therefore preserves its sign // even when the rounded high words straddle adjacent f32 values. let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo); // Resolve ambiguous expansion signs with binary64-equivalent arithmetic. // Six FMA/product tails and their additions fit within this conservative // 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding. if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; } if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) { if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; } } if (midpoint_delta < 0.0) { return i32(lo); } if (midpoint_delta > 0.0) { return i32(hi); } let half_lo = floor(lo * 0.5); let lo_is_even = lo - half_lo * 2.0 == 0.0; return i32(select(hi, lo, lo_is_even));}
// Multiplication by a power of two keeps every i32 bit in binary64. Round the// exact dyadic value directly, including INT_MIN, half-even ties and saturation.fn quant_round_power_two(acc: i32, exponent: i32) -> i32 { let magnitude = select(u32(acc), 0u - u32(acc), acc < 0); var rounded = 0u; if (exponent >= 0) { if (exponent >= 10) { return select(1024, -1024, acc < 0); } rounded = min(magnitude, 1024u >> u32(exponent)) << u32(exponent); } else { let shift = u32(-exponent); if (shift >= 32u) { return 0; } let whole = magnitude >> shift; let remainder = magnitude & ((1u << shift) - 1u); let half = 1u << (shift - 1u); rounded = min(1024u, whole + u32(remainder > half || (remainder == half && (whole & 1u) != 0u))); } return select(i32(rounded), -i32(rounded), acc < 0);}
// Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 { if (acc == 0) { return 0; } let a_bits = bitcast<u32>(a_s); let b_bits = bitcast<u32>(b_s); let y_bits = bitcast<u32>(y_s); 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) { let exponent = i32(a_bits >> 23u) + i32(b_bits >> 23u) - i32(y_bits >> 23u) - 127; return quant_round_power_two(acc, exponent); } let acc_f = f32(acc); // Every i32 high part aligned to 256 is exactly representable in f32. // Recover the conversion residual without an out-of-range i32(acc_f) // conversion when INT_MAX rounds up to 2^31. let acc_tail = fma(-1.0, acc_f - f32(acc & -256), f32(acc & 255)); // Equal b/y scales cancel exactly. Bypass their product and division so a // rounded intermediate cannot move a near-half value onto the tie. if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) { let direct_hi = fma(acc_f, a_s, 0.0); let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi)); if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; } return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc); }
// Keep the scale product as a two-float expansion. Its FMA residual preserves // which side of a rounding midpoint a near-half value occupies. let ab_hi = fma(a_s, b_s, 0.0); let ab_lo = fma(a_s, b_s, -ab_hi); if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; } let product_hi = fma(acc_f, ab_hi, 0.0); if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; } let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0); let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0); // Compare the expansion directly. Renormalizing it adds a cancelling // subtraction/addition chain that can erase the residual during lowering. let denominator_bits = bitcast<u32>(y_s); let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u; let dyadic_candidate = denominator_power_two && ab_lo == 0.0; return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);}
// A conservative binary32 error filter accepts only a result safely inside one// integer rounding bin. Ambiguous boundaries keep the full expansion/binary64// path; this is an exact-result shortcut, not an approximate quantization mode.fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 { if (acc == 0) { return 0; } let a_bits = bitcast<u32>(a_s); let b_bits = bitcast<u32>(b_s); let y_bits = bitcast<u32>(y_s); let ea = (a_bits >> 23u) & 255u; let eb = (b_bits >> 23u) & 255u; let ey = (y_bits >> 23u) & 255u; // Certify the range before arithmetic: overflow need not produce infinity. // Any nonzero i32 converts to a float with biased exponent <=158. These // scale-only bounds cover every accumulator and can be shared across lanes. // Reserve two significands plus carry bits above FTZ, and a factor of two // below overflow for products, division and the expansion midpoint product. // Every exit that needs the binary64 resolver falls through to its one call. if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u || min(ea, eb) == 0u || max(ea, eb) >= 255u || ea + eb < 180u || ea + eb > 347u || ey < 53u || ey > 242u || ea + eb > ey + 220u)) { let scale = fma(a_s, b_s, 0.0); let product = fma(f32(acc), scale, 0.0); let estimate = product / y_s; if (estimate <= -1024.0) { return -1024; } if (estimate >= 1024.0) { return 1024; } let nearest = round(estimate); // 32 binary32 unit roundoffs reserve room for the i32 conversion, two // products, quotient, and distance arithmetic, plus binary64 rounding. let margin = max(1.0, abs(estimate)) * 0x1p-19; if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); } var use_expansion = true;{% if device.adapterInfo.vendor != "apple" %} // The conversion, two products and division can put the estimate several // ulps across a midpoint. Allow eight unit roundoffs before relying on // float residuals. Exact power-of-two ratios retain their integer shortcut. if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) { let dyadic_scales = ((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; use_expansion = dyadic_scales; }{% endif %} if (use_expansion) { let rounded = round_requantized_precise(acc, a_s, b_s, y_s); if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; } } } return quant_round_binary64(acc, a_s, b_s, y_s);}const TILE_M: u32 = 32u;const TILE_N: u32 = 32u;const PADDED_K: u32 = {{ preparedK }}u;const PADDED_N: u32 = {{ preparedN }}u;var<workgroup> tileC: array<f32, 1024>;// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}@compute @workgroup_size(128, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32) { let rowBase = wid.y * TILE_M; let colBase = wid.x * TILE_N; let role = claimMatrixSubgroupRole(width, {{ WIDTH }}u); let nativeTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u); // As in the exact matrix path, every product and intermediate sum // remains an exactly representable f32 integer. 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 %}; 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 %}; let partialK = (16777216u / (max_a * max_b) / 32u) * 32u; var totals: array<i32, 8>; for (var partial = 0u; partial < params.K; partial += partialK) { let partialEnd = min(params.K, partial + partialK); if (nativeTopology) {{% for slot in range(OWNED) %} let bank{{ slot }} = role + {{ slot * GROUPS }}u; let bankRow{{ slot }} = (bank{{ slot }} / 2u) * 16u; let bankCol{{ slot }} = (bank{{ slot }} % 2u) * 16u;{% for r in range(ROWS) %}{% for c in range(COLS) %} var acc{{ slot }}{{ r }}{{ c }} = subgroup_matrix_result<f32, {{ matrixN }}, {{ matrixM }}>(0.0);{% endfor %}{% endfor %}{% endfor %} for (var kb = partial; kb < partialEnd; kb += {{ matrixK }}u) {{% for slot in range(OWNED) %}{% for r in range(ROWS) %} let left{{ slot }}{{ r }} = subgroupMatrixLoad<subgroup_matrix_left<f16, {{ matrixK }}, {{ matrixM }}>, row_major>( &a, (rowBase + bankRow{{ slot }} + {{ r * matrixM }}u) * PADDED_K + kb, PADDED_K);{% endfor %}{% for c in range(COLS) %} let right{{ slot }}{{ c }} = subgroupMatrixLoad<subgroup_matrix_right<f16, {{ matrixN }}, {{ matrixK }}>, row_major>( &b, {% if matrixBatchB %}wid.z * PADDED_K * PADDED_N + {% endif %}kb * PADDED_N + colBase + bankCol{{ slot }} + {{ c * matrixN }}u, PADDED_N);{% endfor %}{% for r in range(ROWS) %}{% for c in range(COLS) %} acc{{ slot }}{{ r }}{{ c }} = subgroupMatrixMultiplyAccumulate(left{{ slot }}{{ r }}, right{{ slot }}{{ c }}, acc{{ slot }}{{ r }}{{ c }});{% endfor %}{% endfor %}{% endfor %} }{% for slot in range(OWNED) %}{% for r in range(ROWS) %}{% for c in range(COLS) %} subgroupMatrixStore<row_major>(&tileC, (bankRow{{ slot }} + {{ r * matrixM }}u) * TILE_N + bankCol{{ slot }} + {{ c * matrixN }}u, acc{{ slot }}{{ r }}{{ c }}, TILE_N);{% endfor %}{% endfor %}{% endfor %} workgroupBarrier(); for (var cell = 0u; cell < 8u; cell++) { let flat = tid + cell * 128u; totals[cell] += i32(tileC[flat]); } workgroupBarrier(); } else { for (var cell = 0u; cell < 8u; cell++) { let flat = tid + cell * 128u; let row = rowBase + flat / TILE_N; let col = colBase + flat % TILE_N; var value = 0.0; for (var k = partial; k < partialEnd; k++) { value = fma(f32(a[row * PADDED_K + k]), f32(b[{% if matrixBatchB %}wid.z * PADDED_K * PADDED_N + {% endif %}k * PADDED_N + col]), value); } totals[cell] += i32(value); } } } for (var cell = 0u; cell < 8u; cell++) { let flat = tid + cell * 128u; let row = rowBase + flat / TILE_N; let col = colBase + flat % TILE_N; if (row < params.M && col < params.N) { let acc = totals[cell]{% if matrixHasBias %} + bias[{{ "row" if matrixBiasPerRow else "col" }}]{% endif %}; 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])); let q = clamp(rounded + i32(y_zero_point[0]), {{ qMin }}, {{ qMax }}); y[{% if matrixBatchB %}wid.z * params.yBatchStride + {% endif %}row * params.N + col] = {{ "u32(q)" if yUnsigned else "q" }}; } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115{"name": "com.microsoft.QLinearConv","id": "_com_microsoft_qlinearconv_webgpu_dd39e27","version": 1,"license": "Apache-2.0","backend": { "type": "webgpu" },"digest": {"algorithm": "sha256","files": {"bench.json": "deKtgF/RQc9YtJ6rKQbZOEn+82qQqbE7gvVAbfsCrHI=","conv-int-accumulate-spatial.wgsl.jinja": "ovvyaZB9d/pmohPYt0/x2NLB2wSWMJ0/eoBHcm4i/5E=","conv-int-im2col-spatial.wgsl.jinja": "23v1AQ7sYZnMKE7b32VbAbjutCCZnsMgXRkXYm4W6/k=","manifest.json": "TbaAnjGDWtUPENa228Ulfk4p2D8TYPRcs0oyPBIHGoI=","qlinear-conv-im2col-nhwc.wgsl.jinja": "CfKXjliMWapwWUjjAk3hY51R2rsx1Wcd4LkvdYUWe6I=","qlinear-conv-nchw-x4.wgsl.jinja": "CrFYcoL6MLszFVzk877uUZu6eMi7h6Wii63GJXWC+x0=","qlinear-conv-nhwc-oc4.wgsl.jinja": "rTj6WQWmCd0BMzMZJVk/ZssxIDh2HrUEOnuK/owJb3Q=","qlinear-conv-requantize.wgsl.jinja": "ElB8XipqRr6CjNjGakSOhsdsM/TezfpRQ2zyh+vENPQ=","quant-dp4a-matmul.wgsl.jinja": "jrfKZZQ/P2yDNDElA9IBQJIxU2p7yJzDjj+dt5D4u1E=","quant-exact-matrix.wgsl.jinja": "EFugcaUsDIAeUHx17xX66qV/fqfila1p8nlXQCG97Kw=","quant-exact-portable.wgsl.jinja": "Ym20X8RcLRzXP9DcQSwJBp4z8RRCBc+bwhrofGC2SBc=","quant-exact-prepare.wgsl.jinja": "hAWISxWqTkqc1z9PRAlaNnKqajQKc6sw6IVWfyYmHns=","quant-weight-k-major.wgsl.jinja": "B2sKfFD51YrInBxbg8bUKVtU8j/QHUgyoJ7QONaV7iE=","test.json": "Yi0vCMNVybIz6uyywnEE6TeUR5B22AzjXtgta2kOmK4="}},"provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },"webgpu": {"manifestSpec": "2.1","variants": {"spatial_nd2_scalar": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],"spatial_nd2_scalar_bias": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],"spatial_nd2_per_channel": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],"spatial_nd2_per_channel_bias": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],"spatial_nd3_scalar": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],"spatial_nd3_scalar_bias": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],"spatial_nd3_per_channel": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],"spatial_nd3_per_channel_bias": ["conv-int-accumulate-spatial.wgsl.jinja", "qlinear-conv-requantize.wgsl.jinja"],"nchw2d_columns_x4": ["qlinear-conv-nchw-x4.wgsl.jinja"],"nhwc2d_channels_x4": ["qlinear-conv-nhwc-oc4.wgsl.jinja"],"nhwc2d_depthwise_x4": ["qlinear-conv-nhwc-oc4.wgsl.jinja"],"nhwc2d_channels_x4_bias": ["qlinear-conv-nhwc-oc4.wgsl.jinja"],"nhwc2d_depthwise_x4_bias": ["qlinear-conv-nhwc-oc4.wgsl.jinja"],"dp4a_pointwise_nchw": ["quant-dp4a-matmul.wgsl.jinja"],"matrix_pointwise_nchw": ["quant-exact-matrix.wgsl.jinja"],"dp4a_im2col_nchw": ["conv-int-im2col-spatial.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"matrix_im2col_nchw": ["conv-int-im2col-spatial.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"dp4a_im2col_nchw_bias": ["conv-int-im2col-spatial.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja"],"matrix_im2col_nchw_bias": ["conv-int-im2col-spatial.wgsl.jinja", "quant-exact-matrix.wgsl.jinja"],"dp4a_pointwise_nhwc": ["quant-dp4a-matmul.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],"matrix_pointwise_nhwc": ["quant-exact-matrix.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],"dp4a_pointwise_nhwc_bias": ["quant-dp4a-matmul.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],"matrix_pointwise_nhwc_bias": ["quant-exact-matrix.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],"dp4a_im2col_nhwc": ["qlinear-conv-im2col-nhwc.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],"matrix_im2col_nhwc": ["qlinear-conv-im2col-nhwc.wgsl.jinja", "quant-exact-matrix.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],"dp4a_im2col_nhwc_bias": ["qlinear-conv-im2col-nhwc.wgsl.jinja", "quant-dp4a-matmul.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],"matrix_im2col_nhwc_bias": ["qlinear-conv-im2col-nhwc.wgsl.jinja", "quant-exact-matrix.wgsl.jinja", "quant-weight-k-major.wgsl.jinja"],"precast_f16_pointwise_nchw_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_pointwise_nchw_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_pointwise_nchw_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_pointwise_nchw_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_im2col_nchw_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_im2col_nchw_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_im2col_nchw_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_im2col_nchw_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_im2col_nchw_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_im2col_nchw_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_im2col_nchw_bias_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_im2col_nchw_bias_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_pointwise_nhwc_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_pointwise_nhwc_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_pointwise_nhwc_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_pointwise_nhwc_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_pointwise_nhwc_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_pointwise_nhwc_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_pointwise_nhwc_bias_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_pointwise_nhwc_bias_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_im2col_nhwc_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_im2col_nhwc_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_im2col_nhwc_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_im2col_nhwc_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_im2col_nhwc_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_im2col_nhwc_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f16_im2col_nhwc_bias_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f16_im2col_nhwc_bias_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_pointwise_nchw_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_pointwise_nchw_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_pointwise_nchw_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_pointwise_nchw_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_im2col_nchw_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_im2col_nchw_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_im2col_nchw_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_im2col_nchw_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_im2col_nchw_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_im2col_nchw_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_im2col_nchw_bias_row": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_im2col_nchw_bias_row": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_pointwise_nhwc_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_pointwise_nhwc_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_pointwise_nhwc_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_pointwise_nhwc_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_pointwise_nhwc_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_pointwise_nhwc_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_pointwise_nhwc_bias_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_pointwise_nhwc_bias_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_im2col_nhwc_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_im2col_nhwc_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_im2col_nhwc_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_im2col_nhwc_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_im2col_nhwc_bias_tensor": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_im2col_nhwc_bias_tensor": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"precast_f32_im2col_nhwc_bias_column": ["quant-exact-matrix.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"],"portable_f32_im2col_nhwc_bias_column": ["quant-exact-portable.wgsl.jinja", "quant-exact-prepare.wgsl.jinja"]}}}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"}}
10 unmodified lines1112131415161718192021227 unmodified lines3031323334353610 unmodified lines// giving each lane several stores in flight. When the input channel count is itself// a multiple of four a quadruple never crosses a kernel tap, and the gather is the// matching aligned vec4 load.{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}{{ env.wgsl.resourceDeclarations }}const WORDS_PER_LANE: u32 = {{ im2colWords }}u;7 unmodified lines@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, "lane", guardInline=true) }}let zp = x_zero_point[0];for (var i = 0u; i < WORDS_PER_LANE; i = i + 1u) {let word = lane + i * params.count;10 unmodified lines1112131415161718192021222324257 unmodified lines3334353637383910 unmodified lines// giving each lane several stores in flight. When the input channel count is itself// a multiple of four a quadruple never crosses a kernel tap, and the gather is the// matching aligned vec4 load.{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}const WORDS_PER_LANE: u32 = {{ im2colWords }}u;7 unmodified lines@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, "lane") }}let zp = x_zero_point[0];for (var i = 0u; i < WORDS_PER_LANE; i = i + 1u) {let word = lane + i * params.count;
5 unmodified lines67891011121314151617181 unmodified line2021222324252627282930313233343536373839404146 unmodified lines8889909192939495969798991001011028 unmodified lines11111211311411511610 unmodified lines1271281291301311321334 unmodified lines13813914014114214314414514614714814915015115215315415525 unmodified lines18118218318418518613 unmodified lines2002012022032042052062072082092102112122132142152161 unmodified line21821922022122222322412 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702715 unmodified linesreturn {{ buffer_name }}[0];{% endif %}}{% endmacro %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: reproduce the reference's binary64 scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {var q = value;var sticky = false;var guard = false;for (var bit = 0u; bit < shift; bit++) {sticky = sticky || guard;guard = (q.x & 1u) != 0u;q = quant_u96_shr(q);}if (guard && (sticky || (q.x & 1u) != 0u)) {q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));}return q;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);var operand = vec3<u32>(significand, 0u);var product = vec3<u32>(0u);loop {if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }magnitude >>= 1u;if (magnitude == 0u) { break; }operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));}var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}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 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Escalate ambiguous expansion signs instead of changing the tie tolerance.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);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); }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u) {return quant_round_binary64(acc, a_s, b_s, y_s);}let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }{% if device.adapterInfo.vendor != "apple" %}// A rounded half-integer estimate can hide which side the exact f32-scale// ratio lies on. Resolve that one-ulp neighborhood conservatively outside// the compact fast path; exact power-of-two ratios already have a cheap// and correct path in round_requantized_precise.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {let dyadic_scales = ((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;if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }}{% endif %}return round_requantized_precise(acc, a_s, b_s, y_s);}{{ quant_read_scalar_zero("x_zero", "x_zero_point", xUnsigned) }}5 unmodified lines6789101112131415161718191 unmodified line212223242526272829303132333435363738394041424344454647484950515253545556575859606162636446 unmodified lines1111121131141151161171181191201218 unmodified lines13013113213313413513613713813914010 unmodified lines1511521531541551561574 unmodified lines16216316416516616716816917017117217317417517617717817925 unmodified lines20520620720820921021113 unmodified lines2252262272282292302312322332342352362372382392402411 unmodified line24324424524624724824912 unmodified lines2622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993005 unmodified linesreturn {{ buffer_name }}[0];{% endif %}}{% endmacro %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: compute binary64-equivalent scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}// The low word is the ordinary u32 product. Split at 16 bits so every// partial product and carry used to construct the high word fits in u32.fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {let a_low = a & 0xffffu;let a_high = a >> 16u;let b_low = b & 0xffffu;let b_high = b >> 16u;let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);let cross_high = a_low * b_high + (cross_low & 0xffffu);let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);return vec2<u32>(a * b, high);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {if (shift == 0u) { return value; }if (shift > 96u) { return vec3<u32>(0u); }let limbs = vec4<u32>(value, 0u);let word = shift >> 5u;let bits = shift & 31u;let middle = limbs[min(word + 1u, 3u)];let high = limbs[min(word + 2u, 3u)];var quotient = vec3<u32>(limbs[word], middle, high);if (bits != 0u) {quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));}// The highest discarded bit is the guard. With the guard set, any lower set// bit rounds up; an exact midpoint rounds to the even quotient.let guard_word = (shift - 1u) >> 5u;let guard_bit = 1u << ((shift - 1u) & 31u);let discarded = limbs[guard_word];let sticky = (discarded & (guard_bit - 1u)) != 0u ||(guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));}return quotient;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);let low_product = quant_mul_u32(significand.x, magnitude);let high_product = quant_mul_u32(significand.y, magnitude);let middle = low_product.y + high_product.x;let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// Requantized results lie in [-1024, 1024]. The expansion helpers return this// marker at a binary64 boundary instead of resolving it themselves, so a// round_requantized call carries one binary64 resolver after inlining rather// than one per boundary exit.const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Resolve ambiguous expansion signs with binary64-equivalent arithmetic.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}// Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.// Every exit that needs the binary64 resolver falls through to its one call.if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u)) {let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }var use_expansion = true;{% if device.adapterInfo.vendor != "apple" %}// The conversion, two products and division can put the estimate several// ulps across a midpoint. Allow eight unit roundoffs before relying on// float residuals. Exact power-of-two ratios retain their integer shortcut.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {let dyadic_scales = ((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;use_expansion = dyadic_scales;}{% endif %}if (use_expansion) {let rounded = round_requantized_precise(acc, a_s, b_s, y_s);if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }}}return quant_round_binary64(acc, a_s, b_s, y_s);}{{ quant_read_scalar_zero("x_zero", "x_zero_point", xUnsigned) }}
12 unmodified lines13141516171819202122232425261 unmodified line2829303132333435363738394041424344454647484946 unmodified lines969798991001011021031041051061071081091108 unmodified lines11912012112212312410 unmodified lines1351361371381391401414 unmodified lines14614714814915015115215315415515615715815916016116216325 unmodified lines18919019119219319413 unmodified lines2082092102112122132142152162172182192202212222232241 unmodified line22622722822923023123212 unmodified lines24524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827950 unmodified lines33033133233333433533612 unmodified lines// grouped arm broadcasts one activation across the quadruple; the depthwise arm// (one input and one output channel per group) reads four adjacent activation// channels instead, which is the same contiguous run as the store.{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: reproduce the reference's binary64 scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {var q = value;var sticky = false;var guard = false;for (var bit = 0u; bit < shift; bit++) {sticky = sticky || guard;guard = (q.x & 1u) != 0u;q = quant_u96_shr(q);}if (guard && (sticky || (q.x & 1u) != 0u)) {q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));}return q;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);var operand = vec3<u32>(significand, 0u);var product = vec3<u32>(0u);loop {if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }magnitude >>= 1u;if (magnitude == 0u) { break; }operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));}var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}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 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Escalate ambiguous expansion signs instead of changing the tie tolerance.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);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); }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u) {return quant_round_binary64(acc, a_s, b_s, y_s);}let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }{% if device.adapterInfo.vendor != "apple" %}// A rounded half-integer estimate can hide which side the exact f32-scale// ratio lies on. Resolve that one-ulp neighborhood conservatively outside// the compact fast path; exact power-of-two ratios already have a cheap// and correct path in round_requantized_precise.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {let dyadic_scales = ((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;if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }}{% endif %}return round_requantized_precise(acc, a_s, b_s, y_s);}const OW_TILE: u32 = {{ owTile }}u;50 unmodified lines@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, "flat", guardInline=true) }}let ocb = flat % params.ocBlocks;var rest = flat / params.ocBlocks;let owg = rest % params.owGroups;12 unmodified lines13141516171819202122232425262728291 unmodified line313233343536373839404142434445464748495051525354555657585960616263646566676869707172737446 unmodified lines1211221231241251261271281291301318 unmodified lines14014114214314414514614714814915010 unmodified lines1611621631641651661674 unmodified lines17217317417517617717817918018118218318418518618718818925 unmodified lines21521621721821922022113 unmodified lines2352362372382392402412422432442452462472482492502511 unmodified line25325425525625725825912 unmodified lines27227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931050 unmodified lines36136236336436536636712 unmodified lines// grouped arm broadcasts one activation across the quadruple; the depthwise arm// (one input and one output channel per group) reads four adjacent activation// channels instead, which is the same contiguous run as the store.{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: compute binary64-equivalent scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}// The low word is the ordinary u32 product. Split at 16 bits so every// partial product and carry used to construct the high word fits in u32.fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {let a_low = a & 0xffffu;let a_high = a >> 16u;let b_low = b & 0xffffu;let b_high = b >> 16u;let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);let cross_high = a_low * b_high + (cross_low & 0xffffu);let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);return vec2<u32>(a * b, high);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {if (shift == 0u) { return value; }if (shift > 96u) { return vec3<u32>(0u); }let limbs = vec4<u32>(value, 0u);let word = shift >> 5u;let bits = shift & 31u;let middle = limbs[min(word + 1u, 3u)];let high = limbs[min(word + 2u, 3u)];var quotient = vec3<u32>(limbs[word], middle, high);if (bits != 0u) {quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));}// The highest discarded bit is the guard. With the guard set, any lower set// bit rounds up; an exact midpoint rounds to the even quotient.let guard_word = (shift - 1u) >> 5u;let guard_bit = 1u << ((shift - 1u) & 31u);let discarded = limbs[guard_word];let sticky = (discarded & (guard_bit - 1u)) != 0u ||(guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));}return quotient;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);let low_product = quant_mul_u32(significand.x, magnitude);let high_product = quant_mul_u32(significand.y, magnitude);let middle = low_product.y + high_product.x;let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// Requantized results lie in [-1024, 1024]. The expansion helpers return this// marker at a binary64 boundary instead of resolving it themselves, so a// round_requantized call carries one binary64 resolver after inlining rather// than one per boundary exit.const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Resolve ambiguous expansion signs with binary64-equivalent arithmetic.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}// Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.// Every exit that needs the binary64 resolver falls through to its one call.if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u)) {let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }var use_expansion = true;{% if device.adapterInfo.vendor != "apple" %}// The conversion, two products and division can put the estimate several// ulps across a midpoint. Allow eight unit roundoffs before relying on// float residuals. Exact power-of-two ratios retain their integer shortcut.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {let dyadic_scales = ((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;use_expansion = dyadic_scales;}{% endif %}if (use_expansion) {let rounded = round_requantized_precise(acc, a_s, b_s, y_s);if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }}}return quant_round_binary64(acc, a_s, b_s, y_s);}const OW_TILE: u32 = {{ owTile }}u;50 unmodified lines@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, "flat") }}let ocb = flat % params.ocBlocks;var rest = flat / params.ocBlocks;let owg = rest % params.owGroups;
5 unmodified lines6789101112131415161718191 unmodified line2122232425262728293031323334353637383940414246 unmodified lines89909192939495969798991001011021038 unmodified lines11211311411511611710 unmodified lines1281291301311321331344 unmodified lines13914014114214314414514614714814915015115215315415515625 unmodified lines18218318418518618713 unmodified lines2012022032042052062072082092102112122132142152162171 unmodified line21922022122222322422512 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712728 unmodified lines2812822832842852862875 unmodified linesreturn {{ buffer_name }}[0];{% endif %}}{% endmacro %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: reproduce the reference's binary64 scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {var q = value;var sticky = false;var guard = false;for (var bit = 0u; bit < shift; bit++) {sticky = sticky || guard;guard = (q.x & 1u) != 0u;q = quant_u96_shr(q);}if (guard && (sticky || (q.x & 1u) != 0u)) {q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));}return q;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);var operand = vec3<u32>(significand, 0u);var product = vec3<u32>(0u);loop {if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }magnitude >>= 1u;if (magnitude == 0u) { break; }operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));}var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}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 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Escalate ambiguous expansion signs instead of changing the tie tolerance.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);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); }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u) {return quant_round_binary64(acc, a_s, b_s, y_s);}let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }{% if device.adapterInfo.vendor != "apple" %}// A rounded half-integer estimate can hide which side the exact f32-scale// ratio lies on. Resolve that one-ulp neighborhood conservatively outside// the compact fast path; exact power-of-two ratios already have a cheap// and correct path in round_requantized_precise.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {let dyadic_scales = ((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;if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }}{% endif %}return round_requantized_precise(acc, a_s, b_s, y_s);}{{ quant_read_scalar_zero("read_y_zero", "y_zero_point", yUnsigned) }}8 unmodified lines@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, guardInline=true) }}{% if hasBias or wScalePerChannel %}let oc = (i / params.outImageSize) % params.outChannels;{% endif %}5 unmodified lines6789101112131415161718192021221 unmodified line242526272829303132333435363738394041424344454647484950515253545556575859606162636465666746 unmodified lines1141151161171181191201211221231248 unmodified lines13313413513613713813914014114214310 unmodified lines1541551561571581591604 unmodified lines16516616716816917017117217317417517617717817918018118225 unmodified lines20820921021121221321413 unmodified lines2282292302312322332342352362372382392402412422432441 unmodified line24624724824925025125212 unmodified lines2652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023038 unmodified lines3123133143153163173185 unmodified linesreturn {{ buffer_name }}[0];{% endif %}}{% endmacro %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: compute binary64-equivalent scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}// The low word is the ordinary u32 product. Split at 16 bits so every// partial product and carry used to construct the high word fits in u32.fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {let a_low = a & 0xffffu;let a_high = a >> 16u;let b_low = b & 0xffffu;let b_high = b >> 16u;let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);let cross_high = a_low * b_high + (cross_low & 0xffffu);let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);return vec2<u32>(a * b, high);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {if (shift == 0u) { return value; }if (shift > 96u) { return vec3<u32>(0u); }let limbs = vec4<u32>(value, 0u);let word = shift >> 5u;let bits = shift & 31u;let middle = limbs[min(word + 1u, 3u)];let high = limbs[min(word + 2u, 3u)];var quotient = vec3<u32>(limbs[word], middle, high);if (bits != 0u) {quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));}// The highest discarded bit is the guard. With the guard set, any lower set// bit rounds up; an exact midpoint rounds to the even quotient.let guard_word = (shift - 1u) >> 5u;let guard_bit = 1u << ((shift - 1u) & 31u);let discarded = limbs[guard_word];let sticky = (discarded & (guard_bit - 1u)) != 0u ||(guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));}return quotient;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);let low_product = quant_mul_u32(significand.x, magnitude);let high_product = quant_mul_u32(significand.y, magnitude);let middle = low_product.y + high_product.x;let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// Requantized results lie in [-1024, 1024]. The expansion helpers return this// marker at a binary64 boundary instead of resolving it themselves, so a// round_requantized call carries one binary64 resolver after inlining rather// than one per boundary exit.const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Resolve ambiguous expansion signs with binary64-equivalent arithmetic.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}// Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.// Every exit that needs the binary64 resolver falls through to its one call.if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u)) {let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }var use_expansion = true;{% if device.adapterInfo.vendor != "apple" %}// The conversion, two products and division can put the estimate several// ulps across a midpoint. Allow eight unit roundoffs before relying on// float residuals. Exact power-of-two ratios retain their integer shortcut.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {let dyadic_scales = ((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;use_expansion = dyadic_scales;}{% endif %}if (use_expansion) {let rounded = round_requantized_precise(acc, a_s, b_s, y_s);if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }}}return quant_round_binary64(acc, a_s, b_s, y_s);}{{ quant_read_scalar_zero("read_y_zero", "y_zero_point", yUnsigned) }}8 unmodified lines@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE) }}{% if hasBias or wScalePerChannel %}let oc = (i / params.outImageSize) % params.outChannels;{% endif %}
12339 unmodified lines434445464748491 unmodified line5152535455565758596061626364656667686970717246 unmodified lines1191201211221231241251261271281291301311321338 unmodified lines14214314414514614710 unmodified lines1581591601611621631644 unmodified lines16917017117217317417517617717817918018118218318418518625 unmodified lines21221321421521621713 unmodified lines2312322332342352362372382392402412422432442452462471 unmodified line24925025125225325425512 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013028 unmodified lines31131231331431531631765 unmodified lines383384385386387388389111 unmodified lines501502503504505506507{% macro quant_read_scalar_zero(fn_name, buffer_name, is_unsigned, present=true) %}fn {{ fn_name }}() -> i32 {{% if is_unsigned %}39 unmodified lines{% endif %}{{ env.wgsl.resourceDeclarations }}{% if requant != "none" %}// Rare-boundary fallback: reproduce the reference's binary64 scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {var q = value;var sticky = false;var guard = false;for (var bit = 0u; bit < shift; bit++) {sticky = sticky || guard;guard = (q.x & 1u) != 0u;q = quant_u96_shr(q);}if (guard && (sticky || (q.x & 1u) != 0u)) {q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));}return q;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);var operand = vec3<u32>(significand, 0u);var product = vec3<u32>(0u);loop {if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }magnitude >>= 1u;if (magnitude == 0u) { break; }operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));}var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}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 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Escalate ambiguous expansion signs instead of changing the tie tolerance.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);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); }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u) {return quant_round_binary64(acc, a_s, b_s, y_s);}let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }{% if device.adapterInfo.vendor != "apple" %}// A rounded half-integer estimate can hide which side the exact f32-scale// ratio lies on. Resolve that one-ulp neighborhood conservatively outside// the compact fast path; exact power-of-two ratios already have a cheap// and correct path in round_requantized_precise.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {let dyadic_scales = ((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;if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }}{% endif %}return round_requantized_precise(acc, a_s, b_s, y_s);}{% endif %}8 unmodified lines{% set needsBSum = true %}var<workgroup> a_tile: array<u32, A_TILE_WORDS>;var<workgroup> a_row_sum: array<atomic<i32>, TILE_M>;// Pack 4 widened A values into one u32 (byte 0 = lowest k).fn pack_a(v: vec4<{{ aScalar }}>) -> u32 {65 unmodified lines{% endif %}if (tid < TILE_M) {atomicStore(&a_row_sum[tid], 0);}workgroupBarrier();111 unmodified lineslet a3: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};let v = vec4<{{ aScalar }}>(a0, a1, a2, a3);packed = pack_a(v);atomicAdd(&a_row_sum[tid], sum4_a(v));}a_tile[tid * KT_WORDS] = packed;}123439 unmodified lines444546474849501 unmodified line525354555657585960616263646566676869707172737475767778798081828384858687888990919293949546 unmodified lines1421431441451461471481491501511528 unmodified lines16116216316416516616716816917017110 unmodified lines1821831841851861871884 unmodified lines19319419519619719819920020120220320420520620720820921025 unmodified lines23623723823924024124213 unmodified lines2562572582592602612622632642652662672682692702712721 unmodified line27427527627727827928012 unmodified lines2932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303318 unmodified lines34034134234334434534665 unmodified lines412413414415416417418111 unmodified lines530531532533534535536{% set ownRowSums = false -%}{% macro quant_read_scalar_zero(fn_name, buffer_name, is_unsigned, present=true) %}fn {{ fn_name }}() -> i32 {{% if is_unsigned %}39 unmodified lines{% endif %}{{ env.wgsl.resourceDeclarations }}{% if requant != "none" %}// Rare-boundary fallback: compute binary64-equivalent scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}// The low word is the ordinary u32 product. Split at 16 bits so every// partial product and carry used to construct the high word fits in u32.fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {let a_low = a & 0xffffu;let a_high = a >> 16u;let b_low = b & 0xffffu;let b_high = b >> 16u;let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);let cross_high = a_low * b_high + (cross_low & 0xffffu);let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);return vec2<u32>(a * b, high);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {if (shift == 0u) { return value; }if (shift > 96u) { return vec3<u32>(0u); }let limbs = vec4<u32>(value, 0u);let word = shift >> 5u;let bits = shift & 31u;let middle = limbs[min(word + 1u, 3u)];let high = limbs[min(word + 2u, 3u)];var quotient = vec3<u32>(limbs[word], middle, high);if (bits != 0u) {quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));}// The highest discarded bit is the guard. With the guard set, any lower set// bit rounds up; an exact midpoint rounds to the even quotient.let guard_word = (shift - 1u) >> 5u;let guard_bit = 1u << ((shift - 1u) & 31u);let discarded = limbs[guard_word];let sticky = (discarded & (guard_bit - 1u)) != 0u ||(guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));}return quotient;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);let low_product = quant_mul_u32(significand.x, magnitude);let high_product = quant_mul_u32(significand.y, magnitude);let middle = low_product.y + high_product.x;let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// Requantized results lie in [-1024, 1024]. The expansion helpers return this// marker at a binary64 boundary instead of resolving it themselves, so a// round_requantized call carries one binary64 resolver after inlining rather// than one per boundary exit.const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Resolve ambiguous expansion signs with binary64-equivalent arithmetic.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}// Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.// Every exit that needs the binary64 resolver falls through to its one call.if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u)) {let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }var use_expansion = true;{% if device.adapterInfo.vendor != "apple" %}// The conversion, two products and division can put the estimate several// ulps across a midpoint. Allow eight unit roundoffs before relying on// float residuals. Exact power-of-two ratios retain their integer shortcut.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {let dyadic_scales = ((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;use_expansion = dyadic_scales;}{% endif %}if (use_expansion) {let rounded = round_requantized_precise(acc, a_s, b_s, y_s);if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }}}return quant_round_binary64(acc, a_s, b_s, y_s);}{% endif %}8 unmodified lines{% set needsBSum = true %}var<workgroup> a_tile: array<u32, A_TILE_WORDS>;var<workgroup> a_row_sum: array<{{ "i32" if ownRowSums else "atomic<i32>" }}, TILE_M>;// Pack 4 widened A values into one u32 (byte 0 = lowest k).fn pack_a(v: vec4<{{ aScalar }}>) -> u32 {65 unmodified lines{% endif %}if (tid < TILE_M) {{{ "a_row_sum[tid] = 0;" if ownRowSums else "atomicStore(&a_row_sum[tid], 0);" }}}workgroupBarrier();111 unmodified lineslet a3: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};let v = vec4<{{ aScalar }}>(a0, a1, a2, a3);packed = pack_a(v);{{ "a_row_sum[tid] += dot4_packed(packed, 0x01010101u);" if ownRowSums else "atomicAdd(&a_row_sum[tid], sum4_a(v));" }}}a_tile[tid * KT_WORDS] = packed;}
6 unmodified lines789101112131 unmodified line1516171819202122232425262728293031323334353646 unmodified lines8384858687888990919293949596978 unmodified lines10610710810911011110 unmodified lines1221231241251261271284 unmodified lines13313413513613713813914014114214314414514614714814915025 unmodified lines17617717817918018113 unmodified lines1951961971981992002012022032042052062072082092102111 unmodified line21321421521621721821912 unmodified lines23223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526614 unmodified lines2812822832842852862872882892902912922932941 unmodified line29629729829930030130230330430530630720 unmodified lines3283293303313323333343353363373383393404 unmodified lines3453463473483493503517 unmodified lines35936036136236336436515 unmodified lines3813823833846 unmodified linesenable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: reproduce the reference's binary64 scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {var q = value;var sticky = false;var guard = false;for (var bit = 0u; bit < shift; bit++) {sticky = sticky || guard;guard = (q.x & 1u) != 0u;q = quant_u96_shr(q);}if (guard && (sticky || (q.x & 1u) != 0u)) {q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));}return q;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);var operand = vec3<u32>(significand, 0u);var product = vec3<u32>(0u);loop {if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }magnitude >>= 1u;if (magnitude == 0u) { break; }operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));}var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}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 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Escalate ambiguous expansion signs instead of changing the tie tolerance.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);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); }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u) {return quant_round_binary64(acc, a_s, b_s, y_s);}let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }{% if device.adapterInfo.vendor != "apple" %}// A rounded half-integer estimate can hide which side the exact f32-scale// ratio lies on. Resolve that one-ulp neighborhood conservatively outside// the compact fast path; exact power-of-two ratios already have a cheap// and correct path in round_requantized_precise.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {let dyadic_scales = ((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;if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }}{% endif %}return round_requantized_precise(acc, a_s, b_s, y_s);}// Adjusted byte integers fit exactly in f32. Each bounded f32 dot product14 unmodified lines{% endif %}{% endif %}@compute @workgroup_size({{ sgmatWorkgroup }}){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) wid: vec3<u32>,{% if not precastOperands or not matrixSubgroupId %}@builtin(local_invocation_index) tid: u32,{% endif %}@builtin(subgroup_invocation_id) lane: u32,@builtin(subgroup_id) subgroup_index: u32) {let subgroup = subgroup_index;let base_A = (subgroup % {{ sgmatRowGroups }}u) * 16u;let base_B = (subgroup / {{ sgmatRowGroups }}u) * 32u;let row = lane / 4u;1 unmodified line// Bound adjusted byte magnitudes from scalar zero points. A column-wise// B zero point keeps the full byte-difference bound for the whole tile.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 %};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 %};let partial_k = (16777216u / (max_a * max_b) / TILE_K) * TILE_K;var totals: array<i32, 16>;for (var partial = 0u; partial < params.K; partial += partial_k) {{% for r in range(2) %}{% for c in range(4) %}var matC{{ r }}{{ c }}: subgroup_matrix_result<f32, 8, 8>;{% endfor %}{% endfor %}let partial_end = min(params.K, partial + partial_k);for (var kb = partial; kb < partial_end; kb += TILE_K) {20 unmodified lines{% endif %}for (var step = 0u; step < TILE_K; step += 8u) {{% for r in range(2) %}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" }});{% endfor %}{% for c in range(4) %}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" }});{% endfor %}{% for r in range(2) %}{% for c in range(4) %}matC{{ r }}{{ c }} = subgroupMatrixMultiplyAccumulate(matA{{ r }}, matB{{ c }}, matC{{ r }}{{ c }});{% endfor %}{% endfor %}}{% if not precastOperands %}4 unmodified lines// The prepared operands need no staging barriers. Publish all eight// matrices together before converting the bounded partial to int32.{% for r in range(2) %}{% for c in range(4) %}subgroupMatrixStore<row_major>(&matrix_out, subgroup * 512u + {{ r * 256 + c * 64 }}u, matC{{ r }}{{ c }}, 8u);{% endfor %}{% endfor %}workgroupBarrier();{% for r in range(2) %}{% for c in range(4) %}{% for h in range(2) %}7 unmodified lines{% endif %}{% for r in range(2) %}{% for c in range(4) %}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);{% endfor %}workgroupBarrier();{% for c in range(4) %}{% for h in range(2) %}15 unmodified lines}}{% endfor %}{% endfor %}{% endfor %}}6 unmodified lines789101112131 unmodified line151617181920212223242526272829303132333435363738394041424344454647484950515253545556575846 unmodified lines1051061071081091101111121131141158 unmodified lines12412512612712812913013113213313410 unmodified lines1451461471481491501514 unmodified lines15615715815916016116216316416516616716816917017117217325 unmodified lines19920020120220320420513 unmodified lines2192202212222232242252262272282292302312322332342351 unmodified line23723823924024124224312 unmodified lines25625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329414 unmodified lines3093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843851 unmodified line38738838939039139239339439539639739820 unmodified lines4194204214224234244254264274284294304314 unmodified lines4364374384394404414427 unmodified lines45045145245345445545615 unmodified lines4724734744754764774784794804814824834844854864874884894904914924934944956 unmodified linesenable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{{ env.wgsl.resourceDeclarations }}// Rare-boundary fallback: compute binary64-equivalent scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}// The low word is the ordinary u32 product. Split at 16 bits so every// partial product and carry used to construct the high word fits in u32.fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {let a_low = a & 0xffffu;let a_high = a >> 16u;let b_low = b & 0xffffu;let b_high = b >> 16u;let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);let cross_high = a_low * b_high + (cross_low & 0xffffu);let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);return vec2<u32>(a * b, high);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {if (shift == 0u) { return value; }if (shift > 96u) { return vec3<u32>(0u); }let limbs = vec4<u32>(value, 0u);let word = shift >> 5u;let bits = shift & 31u;let middle = limbs[min(word + 1u, 3u)];let high = limbs[min(word + 2u, 3u)];var quotient = vec3<u32>(limbs[word], middle, high);if (bits != 0u) {quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));}// The highest discarded bit is the guard. With the guard set, any lower set// bit rounds up; an exact midpoint rounds to the even quotient.let guard_word = (shift - 1u) >> 5u;let guard_bit = 1u << ((shift - 1u) & 31u);let discarded = limbs[guard_word];let sticky = (discarded & (guard_bit - 1u)) != 0u ||(guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));}return quotient;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);let low_product = quant_mul_u32(significand.x, magnitude);let high_product = quant_mul_u32(significand.y, magnitude);let middle = low_product.y + high_product.x;let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// Requantized results lie in [-1024, 1024]. The expansion helpers return this// marker at a binary64 boundary instead of resolving it themselves, so a// round_requantized call carries one binary64 resolver after inlining rather// than one per boundary exit.const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Resolve ambiguous expansion signs with binary64-equivalent arithmetic.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}// Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.// Every exit that needs the binary64 resolver falls through to its one call.if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u)) {let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }var use_expansion = true;{% if device.adapterInfo.vendor != "apple" %}// The conversion, two products and division can put the estimate several// ulps across a midpoint. Allow eight unit roundoffs before relying on// float residuals. Exact power-of-two ratios retain their integer shortcut.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {let dyadic_scales = ((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;use_expansion = dyadic_scales;}{% endif %}if (use_expansion) {let rounded = round_requantized_precise(acc, a_s, b_s, y_s);if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }}}return quant_round_binary64(acc, a_s, b_s, y_s);}// Adjusted byte integers fit exactly in f32. Each bounded f32 dot product14 unmodified lines{% endif %}{% endif %}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {// WGSL initializes workgroup variables to zero before this entry point.let population = subgroupBallot(true);let populationCount = countOneBits(population.x) + countOneBits(population.y)+ countOneBits(population.z) + countOneBits(population.w);var claimed = 0u;if (subgroupElect()) {claimed = atomicAdd(&matrixRoleCount, 1u);if (width != requiredWidth || populationCount != requiredWidth) {atomicStore(&matrixRejected, 1u);}}// Reconverge every invocation before broadcasting the elected claim.workgroupBarrier();return subgroupBroadcastFirst(claimed);}fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {if (localIndex == 0u) {matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u&& atomicLoad(&matrixRoleCount) == bankCount);}// The uniform load both publishes the leader's decision and gives the// compiler a workgroup-uniform condition for the barrier-containing arms.return workgroupUniformLoad(&matrixAccepted) != 0u;}// The portable arm owns two result components per logical 32-invocation group.// Staging casts, 8-wide K steps, barriers and the epilogue match the// subgroup-matrix arm.var<private> matrixSoftwareLane: u32;fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,acc: vec2<f32>) -> vec2<f32> {var value = acc;for (var k = 0u; k < 8u; k += 1u) {value = fma(vec2<f32>(lhs[k]), rhs[k], value);}return value;}{% macro matrixType(software, kind, scalar) %}{% if software %}{% if kind == "left" %}array<f32, 8>{% elif kind == "right" %}array<vec2<f32>, 8>{% else %}vec2<{{ scalar }}>{% endif %}{% else %}subgroup_matrix_{{ kind }}<{{ scalar }}, 8, 8>{% endif %}{% endmacro %}{% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}{% if kind == "left" %}array<f32, 8>({% for k in range(8) %}f32((*({{ pointer }}))[({{ offset }}) + (matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u]){{ "," if k < 7 else "" }}{% endfor %}){% else %}array<vec2<f32>, 8>({% for k in range(8) %}vec2<f32>({% for h in range(2) %}f32((*({{ pointer }}))[({{ offset }}) + {{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u]){{ "," if h == 0 else "" }}{% endfor %}){{ "," if k < 7 else "" }}{% endfor %}){% endif %}{% endif %}{% endmacro %}{% macro matrixMma(software, scalar, lhs, rhs, acc) %}{% if not software %}subgroupMatrixMultiplyAccumulate({{ lhs }}, {{ rhs }}, {{ acc }}){% else %}vec2<{{ scalar }}>(matrixSoftwareMultiplyAccumulate({{ lhs }}, {{ rhs }}, vec2<f32>({{ acc }}))){% endif %}{% endmacro %}{% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{let matrixPointer = {{ pointer }};let matrixValue = {{ value }};{% for h in range(2) %} (*matrixPointer)[({{ offset }}) + {{ {"row_major": "(matrixSoftwareLane / 4u) * (" ~ stride ~ ") + (matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u", "col_major": "((matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u) * (" ~ stride ~ ") + matrixSoftwareLane / 4u"}[major] }}] = matrixValue.{{ "x" if h == 0 else "y" }};{% endfor %}}{% endif %}{% endmacro %}{% macro matrixKernelBody(matrixSoftware) %}let subgroup = matrixRole;let base_A = (subgroup % {{ sgmatRowGroups }}u) * 16u;let base_B = (subgroup / {{ sgmatRowGroups }}u) * 32u;let row = lane / 4u;1 unmodified line// Bound adjusted byte magnitudes from scalar zero points. A column-wise// B zero point keeps the full byte-difference bound for the whole tile.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 %};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 %};let partial_k = (16777216u / (max_a * max_b) / TILE_K) * TILE_K;var totals: array<i32, 16>;for (var partial = 0u; partial < params.K; partial += partial_k) {{% for r in range(2) %}{% for c in range(4) %}var matC{{ r }}{{ c }}: {{ matrixType(matrixSoftware, "result", "f32") }};{% endfor %}{% endfor %}let partial_end = min(params.K, partial + partial_k);for (var kb = partial; kb < partial_end; kb += TILE_K) {20 unmodified lines{% endif %}for (var step = 0u; step < TILE_K; step += 8u) {{% for r in range(2) %}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") }};{% endfor %}{% for c in range(4) %}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") }};{% endfor %}{% for r in range(2) %}{% for c in range(4) %}matC{{ r }}{{ c }} = {{ matrixMma(matrixSoftware, "f32", "matA" ~ (r), "matB" ~ (c), "matC" ~ (r) ~ (c)) }};{% endfor %}{% endfor %}}{% if not precastOperands %}4 unmodified lines// The prepared operands need no staging barriers. Publish all eight// matrices together before converting the bounded partial to int32.{% for r in range(2) %}{% for c in range(4) %}{{ matrixStore(matrixSoftware, "row_major", "&matrix_out", "subgroup * 512u + " ~ (r * 256 + c * 64) ~ "u", "matC" ~ (r) ~ (c), "8u") }}{% endfor %}{% endfor %}workgroupBarrier();{% for r in range(2) %}{% for c in range(4) %}{% for h in range(2) %}7 unmodified lines{% endif %}{% for r in range(2) %}{% for c in range(4) %}{% 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") }}{% endfor %}workgroupBarrier();{% for c in range(4) %}{% for h in range(2) %}15 unmodified lines}}{% endfor %}{% endfor %}{% endfor %}{% endmacro %}@compute @workgroup_size({{ sgmatWorkgroup }}){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) wid: vec3<u32>,@builtin(local_invocation_index) tid: u32,@builtin(subgroup_size) matrixPhysicalWidth: u32,@builtin(subgroup_invocation_id) matrixPhysicalLane: u32) {let matrixRole = claimMatrixSubgroupRole(matrixPhysicalWidth, 32u);let matrixAcceptedHere = matrixTopologyAccepted(tid, {{ sgmatWorkgroup }}u / 32u);matrixSoftwareLane = tid % 32u;if (matrixAcceptedHere) {let lane = matrixPhysicalLane;{{ matrixKernelBody(false) }}} else {let matrixRole = tid / 32u;let lane = tid % 32u;{{ matrixKernelBody(true) }}}}
1234561 unmodified line89101112131415161718192021222324252627282946 unmodified lines7677787980818283848586878889908 unmodified lines9910010110210310410 unmodified lines1151161171181191201214 unmodified lines12612712812913013113213313413513613713813914014114214325 unmodified lines16917017117217317413 unmodified lines1881891901911921931941951961971981992002012022032041 unmodified line20620720820921021121212 unmodified lines22522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026127 unmodified lines28929029129229329429529629729829930030130230330430515 unmodified lines32132232332432532629 unmodified lines35635735835936036136213 unmodified lines376377378379380381382383384385{% set integerStoreRow = matrixScalePerRow or (matrixHasBias and matrixBiasPerRow) %}{% set integerStoreColumn = (requantize and bScalePerColumn) or (matrixHasBias and not matrixBiasPerRow) %}// Rare-boundary fallback: reproduce the reference's binary64 scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}fn quant_u96_shr(a: vec3<u32>) -> vec3<u32> {return vec3<u32>((a.x >> 1u) | (a.y << 31u), (a.y >> 1u) | (a.z << 31u), a.z >> 1u);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {var q = value;var sticky = false;var guard = false;for (var bit = 0u; bit < shift; bit++) {sticky = sticky || guard;guard = (q.x & 1u) != 0u;q = quant_u96_shr(q);}if (guard && (sticky || (q.x & 1u) != 0u)) {q = quant_u96_add(q, vec3<u32>(1u, 0u, 0u));}return q;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.var magnitude = select(u32(acc), 0u - u32(acc), acc < 0);var operand = vec3<u32>(significand, 0u);var product = vec3<u32>(0u);loop {if ((magnitude & 1u) != 0u) { product = quant_u96_add(product, operand); }magnitude >>= 1u;if (magnitude == 0u) { break; }operand = vec3<u32>(operand.x << 1u, (operand.y << 1u) | (operand.x >> 31u), (operand.z << 1u) | (operand.y >> 31u));}var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}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 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Escalate ambiguous expansion signs instead of changing the tie tolerance.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 reference rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return quant_round_binary64(acc, a_s, b_s, y_s); }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return quant_round_binary64(acc, a_s, b_s, y_s); }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc, a_s, b_s, y_s);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);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); }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return quant_round_binary64(acc, a_s, b_s, y_s); }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc, a_s, b_s, y_s);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.if (((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u) {return quant_round_binary64(acc, a_s, b_s, y_s);}let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }{% if device.adapterInfo.vendor != "apple" %}// A rounded half-integer estimate can hide which side the exact f32-scale// ratio lies on. Resolve that one-ulp neighborhood conservatively outside// the compact fast path; exact power-of-two ratios already have a cheap// and correct path in round_requantized_precise.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-24) {let dyadic_scales = ((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;if (!dyadic_scales) { return quant_round_binary64(acc, a_s, b_s, y_s); }}{% endif %}return round_requantized_precise(acc, a_s, b_s, y_s);}// Both integer-output and requantizing consumers share the vector GEMM body.// Its callback stores scalar outputs so padded operands also cover column tails.fn store_integer_result(value: i32, output_index: u32{% if integerStoreColumn %}, column: u32{% endif %}{% if integerStoreRow %}, row: u32{% endif %}) {27 unmodified lines{% set aVectorCount = (blockRowsValue * kTileValue / (4 * laneCount))|int %}{% set bVectorCount = (kTileValue * blockColsValue / (4 * laneCount))|int %}{% set batchStridesValue = false %}// High-intensity matrix multiplication for the large, untransposed layout:// Y[M,N] = alpha * A[M,K] @ B[K,N].// B may alternatively be stored physically as [N,K]; that mode retains vec4// K loads and transposes only while staging the tile in workgroup memory.//// Both inputs and the output are four-wide along their contiguous dimension.// The output-tile geometry and BK are selected from the shape and device's// workgroup-storage limit. f16 operands stay packed in global and workgroup// memory, then widen at the FMA so accumulation remains f32.const M: u32 = {{ M }}u;const K: u32 = {{ K }}u;const N: u32 = {{ N }}u;const K_V4: u32 = K / 4u;15 unmodified lines@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>) {let li = lid.y * {{ workgroupColsValue }}u + lid.x;let mBase = wg.y * BM;let nBase = wg.x * BN;29 unmodified lineslet bColV4_{{ bv }} = bVector{{ bv }} % (BN / 4u);let bn{{ bv }} = nBase + bColV4_{{ bv }} * 4u;var bv4_{{ bv }} = vec4<{{ scalar }}>({{ scalar }}(0));if (bn{{ bv }} < N) {bv4_{{ bv }} = b[{{ bOff }}(kBase + bRow{{ bv }}) * {{ "B_N_V4" if exactIntegerPartialsValue else "N_V4" }} + bn{{ bv }} / 4u];}tileB[bRow{{ bv }} * (BN / 4u) + bColV4_{{ bv }}] = bv4_{{ bv }};13 unmodified lines{% for i in range(threadRows) %}let av{{ i }} = tileA[aRow + {{ i }}u][kv];{% for j in range(threadColVectors) %}acc{{ i }}_{{ j }} = acc{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.x)) * bv0_{{ j }};acc{{ i }}_{{ j }} = acc{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.y)) * bv1_{{ j }};acc{{ i }}_{{ j }} = acc{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.z)) * bv2_{{ j }};acc{{ i }}_{{ j }} = acc{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.w)) * bv3_{{ j }};{% endfor %}{% endfor %}}1234561 unmodified line8910111213141516171819202122232425262728293031323334353637383940414243444546474849505146 unmodified lines98991001011021031041051061071088 unmodified lines11711811912012112212312412512612710 unmodified lines1381391401411421431444 unmodified lines14915015115215315415515615715815916016116216316416516625 unmodified lines19219319419519619719813 unmodified lines2122132142152162172182192202212222232242252262272281 unmodified line23023123223323423523612 unmodified lines24925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929027 unmodified lines31831932032132232332432532632732832933033133233333433533633733833915 unmodified lines35535635735835936036136236329 unmodified lines39339439539639739839913 unmodified lines413414415416417418419420421422{% set integerStoreRow = matrixScalePerRow or (matrixHasBias and matrixBiasPerRow) %}{% set integerStoreColumn = (requantize and bScalePerColumn) or (matrixHasBias and not matrixBiasPerRow) %}// Rare-boundary fallback: compute binary64-equivalent scale division// and accumulator product using integer significands; no f64 feature required.fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {let low = a.x + b.x;1 unmodified linelet with_carry = middle + u32(low < a.x);return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));}// The low word is the ordinary u32 product. Split at 16 bits so every// partial product and carry used to construct the high word fits in u32.fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {let a_low = a & 0xffffu;let a_high = a >> 16u;let b_low = b & 0xffffu;let b_high = b >> 16u;let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);let cross_high = a_low * b_high + (cross_low & 0xffffu);let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);return vec2<u32>(a * b, high);}fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {if (shift == 0u) { return value; }if (shift > 96u) { return vec3<u32>(0u); }let limbs = vec4<u32>(value, 0u);let word = shift >> 5u;let bits = shift & 31u;let middle = limbs[min(word + 1u, 3u)];let high = limbs[min(word + 2u, 3u)];var quotient = vec3<u32>(limbs[word], middle, high);if (bits != 0u) {quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));}// The highest discarded bit is the guard. With the guard set, any lower set// bit rounds up; an exact midpoint rounds to the even quotient.let guard_word = (shift - 1u) >> 5u;let guard_bit = 1u << ((shift - 1u) & 31u);let discarded = limbs[guard_word];let sticky = (discarded & (guard_bit - 1u)) != 0u ||(guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));}return quotient;}fn quant_float_significand(bits: u32) -> u32 {return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);46 unmodified lineslet scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's// significand by the exact accumulator into three little-endian u32 limbs.let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);let low_product = quant_mul_u32(significand.x, magnitude);let high_product = quant_mul_u32(significand.y, magnitude);let middle = low_product.y + high_product.x;let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));var product_top = 31 - i32(countLeadingZeros(product.x));if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }8 unmodified linesreturn select(i32(rounded.x), -i32(rounded.x), acc < 0);}// Requantized results lie in [-1024, 1024]. The expansion helpers return this// marker at a binary64 boundary instead of resolving it themselves, so a// round_requantized call carries one binary64 resolver after inlining rather// than one per boundary exit.const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;// A power-of-two division and an exactly represented <=48-bit product need// no binary64 boundary resolver. This includes ordinary dyadic quantization.fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {10 unmodified linesreturn exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;}fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {let estimate = numerator_hi / denominator;// Anything outside this range saturates after adding an 8-bit zero point;// returning early also keeps floor/i32 conversion away from Inf and overflow.4 unmodified lineslet hi = lo + 1.0;let midpoint = lo + 0.5;let midpoint_hi = fma(midpoint, denominator, 0.0);if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);// The high-word subtraction is exact for these similarly sized products// (Sterbenz); adding the residual difference therefore preserves its sign// even when the rounded high words straddle adjacent f32 values.let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);// Resolve ambiguous expansion signs with binary64-equivalent arithmetic.// Six FMA/product tails and their additions fit within this conservative// 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }}if (midpoint_delta < 0.0) {return i32(lo);25 unmodified linesreturn select(i32(rounded), -i32(rounded), acc < 0);}// Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {if (acc == 0) { return 0; }let a_bits = bitcast<u32>(a_s);13 unmodified linesif (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {let direct_hi = fma(acc_f, a_s, 0.0);let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);}// Keep the scale product as a two-float expansion. Its FMA residual preserves// which side of a rounding midpoint a near-half value occupies.let ab_hi = fma(a_s, b_s, 0.0);let ab_lo = fma(a_s, b_s, -ab_hi);if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }let product_hi = fma(acc_f, ab_hi, 0.0);if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);// Compare the expansion directly. Renormalizing it adds a cancelling1 unmodified linelet denominator_bits = bitcast<u32>(y_s);let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;let dyadic_candidate = denominator_power_two && ab_lo == 0.0;return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);}// A conservative binary32 error filter accepts only a result safely inside one12 unmodified lines// scale-only bounds cover every accumulator and can be shared across lanes.// Reserve two significands plus carry bits above FTZ, and a factor of two// below overflow for products, division and the expansion midpoint product.// Every exit that needs the binary64 resolver falls through to its one call.if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||min(ea, eb) == 0u || max(ea, eb) >= 255u ||ea + eb < 180u || ea + eb > 347u ||ey < 53u || ey > 242u || ea + eb > ey + 220u)) {let scale = fma(a_s, b_s, 0.0);let product = fma(f32(acc), scale, 0.0);let estimate = product / y_s;if (estimate <= -1024.0) { return -1024; }if (estimate >= 1024.0) { return 1024; }let nearest = round(estimate);// 32 binary32 unit roundoffs reserve room for the i32 conversion, two// products, quotient, and distance arithmetic, plus binary64 rounding.let margin = max(1.0, abs(estimate)) * 0x1p-19;if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }var use_expansion = true;{% if device.adapterInfo.vendor != "apple" %}// The conversion, two products and division can put the estimate several// ulps across a midpoint. Allow eight unit roundoffs before relying on// float residuals. Exact power-of-two ratios retain their integer shortcut.if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {let dyadic_scales = ((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;use_expansion = dyadic_scales;}{% endif %}if (use_expansion) {let rounded = round_requantized_precise(acc, a_s, b_s, y_s);if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }}}return quant_round_binary64(acc, a_s, b_s, y_s);}// Both integer-output and requantizing consumers share the vector GEMM body.// Its callback stores scalar outputs so padded operands also cover column tails.fn store_integer_result(value: i32, output_index: u32{% if integerStoreColumn %}, column: u32{% endif %}{% if integerStoreRow %}, row: u32{% endif %}) {27 unmodified lines{% set aVectorCount = (blockRowsValue * kTileValue / (4 * laneCount))|int %}{% set bVectorCount = (kTileValue * blockColsValue / (4 * laneCount))|int %}{% set batchStridesValue = false %}{% set STATIC_M = M is defined %}{% set accName = "acc" %}// High-intensity matrix multiplication:// Y[M,N] = alpha * A[M,K] @ B[K,N].// A may be stored physically as [K,M], and B as [N,K]; a [N,K] B keeps vec4// K loads and transposes only while staging the tile in workgroup memory.//// Unless the shape is ragged, both inputs and the output are four-wide along// their contiguous dimension.// The output-tile geometry and BK are selected from the shape and device's// workgroup-storage limit. f16 operands stay packed in global and workgroup// memory, then widen at the FMA so accumulation remains f32.{% if M is defined %}const M: u32 = {{ M }}u;{% endif %}const K: u32 = {{ K }}u;const N: u32 = {{ N }}u;const K_V4: u32 = K / 4u;15 unmodified lines@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>) {{% if not STATIC_M %}let M = params.M;{% endif %}let li = lid.y * {{ workgroupColsValue }}u + lid.x;let mBase = wg.y * BM;let nBase = wg.x * BN;29 unmodified lineslet bColV4_{{ bv }} = bVector{{ bv }} % (BN / 4u);let bn{{ bv }} = nBase + bColV4_{{ bv }} * 4u;var bv4_{{ bv }} = vec4<{{ scalar }}>({{ scalar }}(0));if (bn{{ bv }} < {{ (preparedNValue ~ "u") if exactIntegerPartialsValue and preparedNValue != N else "N" }}) {bv4_{{ bv }} = b[{{ bOff }}(kBase + bRow{{ bv }}) * {{ "B_N_V4" if exactIntegerPartialsValue else "N_V4" }} + bn{{ bv }} / 4u];}tileB[bRow{{ bv }} * (BN / 4u) + bColV4_{{ bv }}] = bv4_{{ bv }};13 unmodified lines{% for i in range(threadRows) %}let av{{ i }} = tileA[aRow + {{ i }}u][kv];{% for j in range(threadColVectors) %}{{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.x)) * bv0_{{ j }};{{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.y)) * bv1_{{ j }};{{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.z)) * bv2_{{ j }};{{ accName }}{{ i }}_{{ j }} = {{ accName }}{{ i }}_{{ j }} + vec4<{{ accumulatorScalarValue }}>({{ accumulatorScalarValue }}(av{{ i }}.w)) * bv3_{{ j }};{% endfor %}{% endfor %}}
11 unmodified lines1213141516171819202122232425262728293011 unmodified lines// the fastest axis of a channels-last activation. Rows past the source K hold the// weight zero point, so padded lanes contribute exactly zero to// `(a - a_zero) * (b - b_zero)` while the GEMM keeps its aligned vec4 A path.{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}{{ env.wgsl.resourceDeclarations }}{{ quant_read_column_zero("read_w_zero", "w_zero_point", false, per_column=wZeroPerChannel, param_name="oc", return_type=wScalar) }}@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, "flat", guardInline=true) }}// Neighbouring invocations cover neighbouring output channels, so both the// K-major store and the requantization that later reads column `oc` stay// contiguous.11 unmodified lines1213141516171819202122232425262728293031323311 unmodified lines// the fastest axis of a channels-last activation. Rows past the source K hold the// weight zero point, so padded lanes contribute exactly zero to// `(a - a_zero) * (b - b_zero)` while the GEMM keeps its aligned vec4 A path.{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}{{ quant_read_column_zero("read_w_zero", "w_zero_point", false, per_column=wZeroPerChannel, param_name="oc", return_type=wScalar) }}@compute @workgroup_size({{ tunables.WORKGROUP_SIZE }})fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(tunables.WORKGROUP_SIZE, "flat") }}// Neighbouring invocations cover neighbouring output channels, so both the// K-major store and the requantization that later reads column `oc` stay// contiguous.
README.md+41-85
build/webgpu/bench.json
build/webgpu/conv-int-accumulate-spatial.wgsl.jinja+9-6
build/webgpu/conv-int-im2col-spatial.wgsl.jinja+1-1
build/webgpu/manifest.json
build/webgpu/matrix-shaped-exact-precast.wgsl.jinjaAdded+398
build/webgpu/metadata.json+1-115
build/webgpu/qlinear-conv-im2col-nhwc.wgsl.jinja+6-3
build/webgpu/qlinear-conv-nchw-x4.wgsl.jinja+91-62
build/webgpu/qlinear-conv-nhwc-oc4.wgsl.jinja+94-63
build/webgpu/qlinear-conv-requantize.wgsl.jinja+94-63
build/webgpu/quant-dp4a-matmul.wgsl.jinja+92-63
build/webgpu/quant-exact-matrix.wgsl.jinja+186-75
build/webgpu/quant-exact-portable.wgsl.jinja+105-68
build/webgpu/quant-weight-k-major.wgsl.jinja+6-3
build/webgpu/test.json