Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 85 additions & 5 deletions packages/runntime/bench/kernels/matmul.ab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,35 @@ function quant(name: string, t: number, e: number, k: number, o: number, bits: 8
};
}

/** [m, k] × a whole quantW weight [k, n]. */
/** [m, k] × a whole quantW weight [k, n], with an optional bias [n], addend
* [m, n] and activation. */
function quantWhole(
name: string,
m: number,
k: number,
n: number,
bits: 8 | 4,
groupSize: number,
opts: { dtype?: Float; bias?: boolean; addend?: boolean; act?: Act } = {},
): AbCase {
const { dtype = 'f32' } = opts;
return {
name,
needs: dtype === 'f16' ? ['shader-f16'] : [],
build: (version) => {
const a = randMat(version, m, k);
const a = randMat(version, m, k, dtype);
const { w, scales } = quantWeight(version, 1, k, n, bits, groupSize);
return () => version.lib.matmul(a, w, { scales, bits, groupSize });
const bias = opts.bias ? randMat(version, 1, n, dtype) : undefined;
const addend = opts.addend ? randMat(version, m, n, dtype) : undefined;
return () =>
version.lib.matmul(a, w, {
scales,
bits,
groupSize,
bias,
addend,
activation: opts.act,
});
},
};
}
Expand Down Expand Up @@ -172,15 +186,81 @@ abSuite('matmul', [
noSg(mm('tiledVec4, MiniLM qkv bucket 16 [16,384]×[384,1152]', 16, 384, 1152, { bias: true })),
noSg(mm('plain, m = 4 [4,384]×[384,1152]', 4, 384, 1152)),

// Quantized weights, privacy-filter MoE expert.
// Quantized weights, privacy-filter MoE expert: matmulQuantW whatever m.
quant('quantW int8, privacy-filter expert [32,640]×[640,640]', 32, 16, 640, 640, 8),
quant('quantW int4, privacy-filter expert [32,640]×[640,640]', 32, 16, 640, 640, 4),
quant('quantW int8, decode [1,640]×[640,640]', 1, 16, 640, 640, 8),

// Quantized weights, whole: the tiled route from 8 rows, plain below.
// Quantized weights, whole: the tiled route from 48·1024 outputs (m · n),
// matmulQuantW below.
quantWhole('quantW int4 whole, q|k projection [256,1024]×[1024,2304]', 256, 1024, 2304, 4, 32),
quantWhole('quantW int8 whole, per channel [256,2048]×[2048,1024]', 256, 2048, 1024, 8, 2048),
quantWhole(
'quantW int8 whole f16 + bias, MiniLM qkv 256 tokens [256,384]×[384,1152]',
256,
384,
1152,
8,
32,
{
dtype: 'f16',
bias: true,
},
),
quantWhole('quantW int4 whole, decode [1,1024]×[1024,2304]', 1, 1024, 2304, 4, 32),
quantWhole(
'quantW int8 whole f16 + bias, MiniLM qkv 16 tokens [16,384]×[384,1152]',
16,
384,
1152,
8,
32,
{
dtype: 'f16',
bias: true,
},
),
quantWhole(
'quantW int4 whole f16 + gelu, MiniLM fc1 16 tokens [16,384]×[384,1536]',
16,
384,
1536,
4,
32,
{
dtype: 'f16',
bias: true,
act: 'gelu',
},
),
quantWhole(
'quantW int8 whole f16 + addend, MiniLM fc2 16 tokens [16,1536]×[1536,384]',
16,
1536,
384,
8,
32,
{
dtype: 'f16',
bias: true,
addend: true,
},
),
quantWhole(
'quantW int8 whole f16 + bias, LLM decode [1,2048]×[2048,2048]',
1,
2048,
2048,
8,
64,
{
dtype: 'f16',
bias: true,
},
),
// matmulQuantW: fewer than 32 rows on a wide N, past 48·1024 outputs.
quantWhole('quantW int8 whole, wide decode [1,2048]×[2048,65536]', 1, 2048, 65536, 8, 32),
quantWhole('quantW int8 whole, LLM MLP 4 rows [4,4096]×[4096,14336]', 4, 4096, 14336, 8, 32),

// matmulGather: one expert per row.
gather('matmulGather f32, privacy-filter [64,640], 16 experts', 64, 16, 640, 640),
Expand Down
60 changes: 29 additions & 31 deletions packages/runntime/src/core/gpu/dispatch/matmul.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,17 @@ export const matmulSpec = defineSpec({
},
});

/** From this many output values (M·N) a whole quantW weight takes
* matmulQuantTiled. Below it the tiled kernel has too few 32×32 tiles to fill
* the GPU, and matmulQuantW, which splits K across lanes, is faster. Measured
* on an Apple M4 Pro for N from 384 to 2048. */
const QUANT_TILED_MIN_OUTPUTS = 48 * 1024;

/** And from this many rows, one full row tile of matmulQuantTiled. With fewer
* a wide N alone passes QUANT_TILED_MIN_OUTPUTS, and each tile computes
* mostly empty rows: [1,2048]×[2048,131072] is 4.8× slower tiled. */
const QUANT_TILED_MIN_ROWS = 32;

export const matmulQuantWSpec = defineSpec({
attrs: (p) => {
const [baseRow, scaleBase, bits, groupSize, hasBias, hasAdd, act] = p.attrs as [
Expand All @@ -164,16 +175,14 @@ export const matmulQuantWSpec = defineSpec({
const [m, k] = node.pending!.inputs[0]!.shape.dims as [number, number];
const n = node.shape.dims![1]!;
const rows = node.pending!.inputs[1]!.shape.dims![0]!;
const epilogue = attrs.hasBias + attrs.hasAdd + attrs.act > 0;
// A whole weight goes to the tiled kernel from 8 rows, and always for an
// f16 input or an epilogue, which the plain kernel lacks. Expert views
// stay on the plain kernel.
// Expert views stay on matmulQuantW whatever m.
const tiled =
attrs.baseRow === 0 &&
attrs.scaleBase === 0 &&
rows === k &&
matmulQuantTiledEligible(k, n, attrs.groupSize) &&
(node.shape.dtype === 'f16' || epilogue || m >= MATMUL_TILED_MIN_M);
m >= QUANT_TILED_MIN_ROWS &&
m * n >= QUANT_TILED_MIN_OUTPUTS &&

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With wide N a single row already passes m·n ≥ 48·1024, so few-row calls land on the 32-row tile again. [1,2048]×[2048,131072] takes 6505 µs tiled vs 1362 on matmulQuantW, [4,4096]×[4096,14336] 1522 vs 474. On N 384–1536 the threshold is right. Maybe also require m >= 32? That fits every case I measured.

matmulQuantTiledEligible(k, n, attrs.groupSize);
return {
k,
n,
Expand All @@ -188,41 +197,30 @@ export const matmulQuantWSpec = defineSpec({
pipeline: (root, dtype, cfg) =>
cfg.tiled
? createMatmulQuantTiledPipeline(root, cfg, elemFor(dtype))
: createMatmulQuantWPipeline(root, cfg),
: createMatmulQuantWPipeline(root, cfg, elemFor(dtype)),
encode: ({ node, attrs, cfg, pipeline, inputs, out, ctx }) => {
const m = node.pending!.inputs[0]!.shape.dims![0]!;
const dtype = node.shape.dtype;
const elem = elemFor(dtype);
const addendAt = attrs.hasBias === 1 ? 4 : 3;
const buffers = {
a: narrowFloat(inputs[0]!, dtype),
w: narrow(inputs[1]!, 'u32'),
scales: narrow(inputs[2]!, 'f32'),
bias: attrs.hasBias === 1 ? narrowFloat(inputs[3]!, dtype) : undefined,
addend: attrs.hasAdd === 1 ? narrowFloat(inputs[addendAt]!, dtype) : undefined,
out: narrowFloat(out, dtype),
};
if (cfg.tiled) {
const addendAt = attrs.hasBias === 1 ? 4 : 3;
return [
matmulQuantTiledHandle(
ctx.root,
pipeline,
m,
cfg.n,
{
a: narrowFloat(inputs[0]!, dtype),
w: narrow(inputs[1]!, 'u32'),
scales: narrow(inputs[2]!, 'f32'),
bias: attrs.hasBias === 1 ? narrowFloat(inputs[3]!, dtype) : undefined,
addend: attrs.hasAdd === 1 ? narrowFloat(inputs[addendAt]!, dtype) : undefined,
out: narrowFloat(out, dtype),
},
elemFor(dtype),
),
];
return [matmulQuantTiledHandle(ctx.root, pipeline, m, cfg.n, buffers, elem)];
}
return [
matmulQuantWHandle(
ctx.root,
pipeline,
{ m, n: cfg.n, baseRow: attrs.baseRow, scaleBase: attrs.scaleBase },
{
a: narrow(inputs[0]!, 'f32'),
w: narrow(inputs[1]!, 'u32'),
scales: narrow(inputs[2]!, 'f32'),
out: narrow(out, 'f32'),
},
buffers,
elem,
),
];
},
Expand Down
9 changes: 7 additions & 2 deletions packages/runntime/src/core/graph/ops/matmul.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ export function matmul(a: Value, b: Value, opts: MatmulOpts = {}): Value {
}

/** matmul's quantW path. The result takes a's dtype. An f16 a, a bias, an
* addend or an activation need the tiled kernel: the whole weight (baseRow
* and scaleBase 0) and a shape it supports. */
* addend or an activation need the whole weight (baseRow and scaleBase 0)
* and a shape the tiled kernel supports, since large inputs take it. */
function matmulQuantW(
a: Value,
w: Value,
Expand Down Expand Up @@ -147,6 +147,11 @@ function matmulQuantW(
}
if (!Number.isInteger(scaleBase) || scaleBase < 0)
throw new Error(`matmul: bad scaleBase ${scaleBase}`);
if (scaleBase % 4 !== 0) {
throw new Error(
`matmul: scaleBase ${scaleBase} must be a multiple of 4 — scales are read as vec4`,
);
}
const { bias, addend, activation } = opts;
const whole = baseRow === 0 && scaleBase === 0 && r === k;
if (whole && scales.shape.elems !== (k / groupSize) * n) {
Expand Down
38 changes: 10 additions & 28 deletions packages/runntime/src/core/kernels/matmul/matmulQuantTiled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,16 @@

import tgpu, { d, std } from 'typegpu';
import type { TgpuRoot } from 'typegpu';
import {
type F32Buffer,
type FloatBuffer,
type KernelHandle,
makeHandle,
type U32Buffer,
} from '../common.ts';
import { type KernelHandle, makeHandle } from '../common.ts';
import { cachedBindGroup, cachedUniform } from '../../gpu/dispatchCache.ts';
import { activationFor, actSlot } from '../activations.ts';
import { type Elem, F32_ELEM } from '../elem.ts';
import { columnWord, deqRow } from '../quantCommon.ts';
import {
columnWord,
deqRow,
type MatmulQuantBuffers,
type MatmulQuantCfg,
} from '../quantCommon.ts';

const Dims = d.struct({ m: d.u32 });

Expand Down Expand Up @@ -59,17 +58,7 @@ export function matmulQuantTiledEligible(k: number, n: number, groupSize: number
return k % BK === 0 && n % 4 === 0 && groupSize % 4 === 0 && k % groupSize === 0;
}

export interface MatmulQuantTiledCfg {
k: number;
n: number;
bits: number;
groupSize: number;
hasBias: number;
hasAdd: number;
act?: number;
}

function makeMatmulQuantTiledKernel(cfg: MatmulQuantTiledCfg, elem: Elem) {
function makeMatmulQuantTiledKernel(cfg: MatmulQuantCfg, elem: Elem) {
const { k, n, bits, groupSize, hasBias, hasAdd } = cfg;
const layout = layoutFor(elem);
const storeVec4 = elem.vec4;
Expand Down Expand Up @@ -184,7 +173,7 @@ function makeMatmulQuantTiledKernel(cfg: MatmulQuantTiledCfg, elem: Elem) {
/** One pipeline per dtype, K, N, bits, group size, epilogue and activation. */
export function createMatmulQuantTiledPipeline(
root: TgpuRoot,
cfg: MatmulQuantTiledCfg,
cfg: MatmulQuantCfg,
elem: Elem = F32_ELEM,
) {
return root
Expand All @@ -198,14 +187,7 @@ export function matmulQuantTiledHandle(
pipeline: ReturnType<typeof createMatmulQuantTiledPipeline>,
m: number,
n: number,
buffers: {
a: FloatBuffer;
w: U32Buffer;
scales: F32Buffer;
out: FloatBuffer;
bias?: FloatBuffer;
addend?: FloatBuffer;
},
buffers: MatmulQuantBuffers,
elem: Elem = F32_ELEM,
): KernelHandle {
const dims = cachedUniform(root, Dims, { m });
Expand Down
Loading
Loading