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 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;Bmust 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— Foraccuracy_level2 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— Foraccuracy_level2 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 foraccuracy_level1, or for 4-bit weights ataccuracy_level0.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 foraccuracy_level1, or for 4-bit weights ataccuracy_level0.prefill_native16_split_f32— Explicitaccuracy_level=2Q4 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 WGSLsubgroup_idfeature, 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_packedover 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 withvec4activation 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 useBK=16; others useBK=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— kernel metadata (id, file digests, manifest spec, provenance)manifest.json— the op contract (source of truth)test.json— correctness casesbench.json— benchmark casesgemm-subgroup-matrix.wgsl.jinjamatmul-native16-splitk-reduce.wgsl.jinjamatmul-nbits-dp4a-quantize.wgsl.jinjamatmul-nbits-gemv-clusters.wgsl.jinjamatmul-nbits-gemv-q4.wgsl.jinjamatmul-nbits-q4-dp4a-prefill.wgsl.jinjamatmul-nbits-q4-native16-packed.wgsl.jinjamatmul-nbits-q4-prefill-tile4x4.wgsl.jinjamatmul-nbits-q4-prefill-tiled-reg.wgsl.jinjamatmul-nbits-q4-prefill-tiled.wgsl.jinjamatmul-nbits-q4-range-guarded.wgsl.jinjamatmul-nbits-q4-sgmat.wgsl.jinjamatmul-nbits-split-f32-rows.wgsl.jinjamatmul-nbits.wgsl.jinjaq4-block-scale.wgsl.jinjareduce-axis0-splitk-combine.wgsl.jinja
Use with @huggingface/kernels
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.
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 });
- Downloads last month
- -
Requires WebGPU support. See the compatibility table.