File size: 13,928 Bytes
3d17c9b
ef3074d
3d17c9b
ef3074d
 
 
 
3d17c9b
ef3074d
 
 
 
 
 
 
 
 
 
bfc5ea0
 
 
 
 
ef3074d
 
929af3e
ef3074d
929af3e
bfc5ea0
929af3e
 
 
ef3074d
 
 
929af3e
ef3074d
929af3e
ef3074d
 
 
 
 
 
 
 
 
929af3e
 
ef3074d
 
 
 
 
 
 
 
 
929af3e
 
 
 
bfc5ea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
929af3e
ef3074d
 
bfc5ea0
ef3074d
 
 
bfc5ea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3074d
 
 
929af3e
bfc5ea0
929af3e
 
bfc5ea0
 
929af3e
ef3074d
 
929af3e
ef3074d
 
 
 
 
bfc5ea0
 
 
 
 
 
 
 
 
 
 
 
 
 
ef3074d
 
 
 
 
 
 
bfc5ea0
ef3074d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
---
library_name: kernels
license: apache-2.0
tags:
- kernel
- webgpu
- wgsl
---
# com.microsoft.MatMulNBits

`com.microsoft`  ·  ONNX Runtime contrib operator  ·  contrib since_version 1

## Description

Matrix multiplication with `B` block-quantized along K and dequantized as `(code - zero_point) * scale`. Each power-of-two `block_size` group has a scale and optional zero point; optional bias is added afterward. Two-, four-, and eight-bit codes are packed low-first, and `A` may have rank 2 or 3. This package supports standard unpacked zero points with the same dtype as `A`. Deprecated `g_idx`, prepacked weights, and bfloat16 tensors are not implemented.

See the [ONNX Runtime `MatMulNBits` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.MatMulNBits) for the reference semantics.

## Differences from the ONNX Runtime spec

- Input `g_idx`: The deprecated group-index input is not implemented by this inference package.
- Attribute `weight_prepacked`: Prepacked weight layouts are not accepted; `B` must use the public bit-packed uint8 layout.

## Inputs

| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
| --- | --- | --- | --- | --- | --- | --- |
| `aT` | `A` | `T1` | — | — | Float input matrix, not quantized. Rank 2 has shape `(M, K)` and rank 3 has shape `(batch, sequence, K)`; only the last axis is the reduction axis and the leading axes fold into the row count, so the ordinary activation needs no surrounding Reshape. | required |
| `bT` | `B` | `uint8` | `3` | — | Bit-packed uint8 weight matrix of shape `(N, k_blocks, blob_size)`, where `k_blocks = ceil(K / block_size)` and `blob_size = block_size * bits / 8`. Codes are packed low-first along K. The kernels read the uint8 data directly as 32-bit words, four bytes each, so no repacking is needed. | required |
| `scalesT` | `scales` | `T1` | `2` | — | Per-block dequantization scale factors of shape `(N, k_blocks)`, with the same dtype as `A`. | required |
| `zeroPointsT` | `zero_points` | `T3` | `2` | — | Standard unpacked per-block zero points with shape `(N, k_blocks)` and the same dtype as `A`. Omission uses `2^(bits - 1)`. | optional |
| `biasT` | `bias` | `T1` | `1` | — | Optional bias vector of shape `[N]` added to the output. | optional |

## Outputs

| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
| --- | --- | --- | --- | --- | --- | --- |
| `yT` | `Y` | `T1` | same as `aT` | derived | Result of A multiplied by the dequantized weight matrix, with optional bias, same dtype and rank as A: the leading axes of A with a trailing N. | required |

## Attributes

Attributes and default values (overridable per request):

| Attribute | Default | Description |
| --- | --- | --- |
| `K` | — | Input feature dimension of the weight matrix. |
| `N` | — | Output feature dimension of the weight matrix. |
| `accuracy_level` | `0` | Minimum internal accuracy level: 0 (unset), 1 (float32), 2 (float16), 3 (bfloat16), or 4 (int8). |
| `bits` | `4` | Bit width used to quantize B; this package supports 2, 4, and 8. |
| `block_size` | — | Power-of-two quantization block size along K; it must be at least 16. |

## Type constraints

| Variable | Allowed dtypes |
| --- | --- |
| `T1` | `float32`, `float16` |
| `T3` | `float32`, `float16` |

## Implementation variants

One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.

- `gemv_clusters` — Four subgroup-owned 32-lane clusters accumulate two output columns each, loading two packed words per lane. Complete 32-wide subgroups reduce without workgroup memory or barriers; if the subgroups found at run time differ, a general path that works for any subgroup size is used.
- `prefill_q4_block_scale_wide` — Runs the exact raw-code 4-bit products on 128 x 64 tiles of eight subgroups, reusing each staged weight block across twice the rows.
- `prefill_q4_block_scale_splitk` — Splits underfilled exact 4-bit products along block-aligned K slices: f16 activations times the raw codes on subgroup matrices, each block folded into float32 sums times its scale (minus scale x zero x the row's block sum), float32 partials summed and biased once by a combine pass.
- `prefill_q4_block_scale` — Multiplies f16 activations by raw 4-bit codes on subgroup matrices with exact products, folding each quantization block into float32 sums times its per-column scale; zero points subtract scale x zero x the row's block sum. Products are exact for every operand range, so no pass is needed to check value ranges and no temporary buffer is used.
- `prefill_q4_block_scale_f32_splitk` — For `accuracy_level` 2 to 4 with f32 storage, splits underfilled 4-bit products along block-aligned K slices: rows as a plane of halves and a plane of remainders times a power of two, both multiplied by the raw codes on subgroup matrices and folded per block times its scale; a combine pass sums, rescales and biases.
- `prefill_q4_block_scale_f32` — For `accuracy_level` 2 to 4 with f32 storage: a split pass writes each row as halves plus half remainders times a power of two (about 22 bits; values far below the row peak lose precision); both multiply the raw codes into one float32 matrix per block, folded times its scale (minus scale x zero x the block row sum).
- `prefill_native16_packed_64x64`, `prefill_native16_packed_128x128` — Multiplies f16 activations by inline-decoded 2- or 4-bit weights with f32 accumulation. Each workgroup checks whether its decoded weights fit half precision safely; if not, they are dequantized in f32, otherwise packed half tiles are used. Converts each output to half once. Not used for `accuracy_level` 1, or for 4-bit weights at `accuracy_level` 0.
- `prefill_native16_packed_splitk` — Splits underfilled 2- or 4-bit products along K, stores f32 partials for padded rows, then combines and biases once. Each workgroup checks decoded-weight range and uses f32 dequantization when packed half operands are unsafe. Not used for `accuracy_level` 1, or for 4-bit weights at `accuracy_level` 0.
- `prefill_native16_split_f32` — Explicit `accuracy_level=2` Q4 path for f32 storage. Row-scaled activation and weight high/low half pairs form three products with f32 accumulation, omitting low×low. Half operand precision and range apply: residuals may underflow and decoded weights may overflow. This path does not implement exact f32 contraction.
- `gemv` — Packed-weight GEMV with workgroup size bounded by the available K vectors and reported subgroup geometry. With the WGSL `subgroup_id` feature, subgroup IDs compact the partial totals; otherwise partials are reduced through a workgroup-memory array indexed by local invocation. Folded grids balance their columns to avoid excessive padding.
- `prefill_sgmat_packed` — Float32 rows of whole 64-row blocks against 4-bit weights in blocks of 32: the shared subgroup-matrix GEMM reads the rows straight from storage and decodes each lane's half block of codes into a double-buffered float32 tile as `(code - 8) * scale`, with consecutive workgroups covering groups of row tiles.
- `prefill_sgmat_packed_splitk` — `prefill_sgmat_packed` over K slices when its output tiles underfill the device: each slice writes float32 partials and a combine pass sums them in slice order.
- `prefill_sgmat_splitk` — The subgroup-matrix prefill over K slices when its output tiles underfill the device: each slice folds its 32-wide K tiles into float32 partials, and a combine pass sums them in slice order and adds the bias.
- `prefill_tiled_reg_vec4_splitk` — Register-blocked prefill with vec4 activation loads and split-K f32 partials. Subgroup geometry selects the weight order and packed-word reuse. Complete reduction tiles omit redundant K bounds.
- `prefill_tiled_reg_vec4` — Register-blocked prefill with `vec4` activation loads. Reported subgroup width redistributes a fixed output tile across invocation rows and columns. Geometry selects row tiles, weight order and packed-word reuse within workgroup limits. Some 2-bit f16 cases use `BK=16`; others use `BK=32`. Complete tiles omit K bounds.
- `prefill_tiled_reg` — Register-blocked prefill with scalar activation loads. Row fill and subgroup geometry select the micro-tile and weight order. Quant-block alignment selects packed-word reuse. Complete reduction tiles omit redundant K bounds; partial tiles check them.

## Device requirements

Some implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.

## Files

- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)
- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)
- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/test.json) — correctness cases
- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/bench.json) — benchmark cases
- [`gemm-subgroup-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/gemm-subgroup-matrix.wgsl.jinja)
- [`matmul-native16-splitk-reduce.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-native16-splitk-reduce.wgsl.jinja)
- [`matmul-nbits-dp4a-quantize.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-dp4a-quantize.wgsl.jinja)
- [`matmul-nbits-gemv-clusters.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-gemv-clusters.wgsl.jinja)
- [`matmul-nbits-gemv-q4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-gemv-q4.wgsl.jinja)
- [`matmul-nbits-q4-dp4a-prefill.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-dp4a-prefill.wgsl.jinja)
- [`matmul-nbits-q4-native16-packed.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-native16-packed.wgsl.jinja)
- [`matmul-nbits-q4-prefill-tile4x4.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-prefill-tile4x4.wgsl.jinja)
- [`matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-prefill-tiled-reg.wgsl.jinja)
- [`matmul-nbits-q4-prefill-tiled.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-prefill-tiled.wgsl.jinja)
- [`matmul-nbits-q4-range-guarded.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-range-guarded.wgsl.jinja)
- [`matmul-nbits-q4-sgmat.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-q4-sgmat.wgsl.jinja)
- [`matmul-nbits-split-f32-rows.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits-split-f32-rows.wgsl.jinja)
- [`matmul-nbits.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/matmul-nbits.wgsl.jinja)
- [`q4-block-scale.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/q4-block-scale.wgsl.jinja)
- [`reduce-axis0-splitk-combine.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.MatMulNBits/blob/v1/build/webgpu/reduce-axis0-splitk-combine.wgsl.jinja)

## Use with `@huggingface/kernels`

```sh
npm 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`.

```js
import { getKernel } from "@huggingface/kernels";

const kernel = await getKernel("webgpu-kernels/com.microsoft.MatMulNBits", { version: 1 });

const aTData = Float32Array.of(
  0.14603463, 0.12950113, 0.10649598, 0.085161425, 0.07283477, 0.07489503, 0.093901455,
  0.12914494, 0.17667694, 0.22981437, 0.28005305, 0.31826597, 0.3360224, 0.32684615,
  0.28723875, 0.21732353, 0.12101746, 0.005700612, -0.11857925, -0.24026643, -0.34767178,
  -0.4303828, -0.4805244, -0.4937053, -0.46952623, -0.41158408, -0.3269733, -0.22535284,
  -0.11770318, -0.01494011, 0.07343123, 0.1404443, 0.18243429, 0.19933969,
);
const bTData = Uint8Array.of(
  16, 50, 84, 118, 152, 186, 220, 254, 33, 0, 0, 0, 0, 0, 0, 0, 255, 238, 221, 204, 187,
  170, 153, 136, 240, 0, 0, 0, 0, 0, 0, 0,
);
const scalesTData = Float32Array.of(0.04, 0.08, 0.06, 0.12);

const { yT } = await kernel({
  aT: { data: aTData, shape: [2, 17] },
  bT: { data: bTData, shape: [2, 2, 8] },
  scalesT: { data: scalesTData, shape: [2, 2] },
}, {
  attrs: { K: 17, N: 2, block_size: 16 },
});
console.log({ yT });
```