Inference kernels
gpu.inferenceSource() returns the bundled Metal source from
compiler/runtime/inference.metal. Compile the required entry point with gpu.kernel
and bind buffers in the order below. These are baseline float32 inference
building blocks; they do not load a model or implement an entire architecture.
Cooperative quantized matvec entry points distribute each row across a SIMD
group. Attention and RMS norm still use scalar inner loops; these primitives
do not imply a particular end-to-end model throughput.
All floating-point buffers contain packed IEEE float32, suitable for
math.f32From, math.f32Alloc, math.f32Get, and math.f32To.
shape buffers contain unsigned 32-bit integers in native little-endian order.
Build each shape word with int.toBytes() and append its four bytes to a
byte[] before uploading. Parameters are packed float32 buffers. Shapes and
parameters are device buffers, not Metal function constants.
Dispatch one-dimensional grids with the thread counts specified below.
Additional threads are ignored. The caller must provide valid buffer sizes;
raw Metal pointers carry no lengths. Dimensions and flattened element counts
must fit uint32; dispatch thread counts must fit a nonnegative int. Dependent dispatches must execute in order; a GPU batch may provide that
ordering without a host wait between kernels. Do not overlap writable buffers with inputs unless allowed below.
Quantized matrix-vector multiplication
Entry points: quantMatvecQ8_0, quantMatvecQ4_K, quantMatvecQ5_K,
quantMatvecQ6_K. Dispatch rows threads.
For accelerated rows, use mvQ8_0, mvQ4_K, mvQ5_K, mvQ6_K and
dispatch rows × 32 threads. These entries retain the same buffers, shape,
64-bit offset and zero/default stride below, but use a 32-lane SIMD group per
row and a SIMD reduction. They match llama-rad’s metal.source() names.
The original quantMatvecQ* entries remain compatible and dispatch rows
threads. Do not substitute names without updating the dispatch count.
The cooperative entries require a 32-lane SIMD width and threadgroups whose
size is a multiple of 32 (the Apple Metal runtime dispatch satisfies this).
Keep rows × 32 within the signed int dispatch limit. K formats decode eight
values per lane per block; Q8_0 distributes blocks between lanes. Scales are
loaded once per lane/block rather than per decoded element.
| Binding | Buffer |
|---|---|
| 0 | Raw GGUF quantized weight bytes |
| 1 | Input activations: columns float32 values |
| 2 | Output: rows float32 values |
| 3 | Shape: [rows, columns, offsetLow32, offsetHigh32, rowStrideBytes] |
The offset is a 64-bit byte offset into the uploaded weight buffer. A zero row stride means tightly packed rows; otherwise the stride must be at least the encoded row length. Dimensions must contain complete quantization blocks:
| Format | Elements per block | Bytes per block |
|---|---|---|
| Q8_0 | 32 | 34 |
| Q4_K | 256 | 144 |
| Q5_K | 256 | 176 |
| Q6_K | 256 | 210 |
The formats match the CPU math.dotQ* kernels. Scales are little-endian f16;
Q8_0 uses signed bytes, Q4_K/Q5_K use their packed per-group scale/minimum
fields, and Q6_K combines low/high quant bits with signed per-group scales.
Accumulation uses float32. GPU/CPU reduction order and fused operations may
produce small floating-point differences. Invalid block dimensions or too-small
strides leave outputs untouched; validate configurations on the host.
RMS normalization
Entry point rmsNorm; dispatch rows × dim threads.
| Binding | Buffer |
|---|---|
| 0 | Input: row-major [rows, dim] float32 |
| 1 | Weight: [dim] float32 |
| 2 | Output: [rows, dim] float32 |
| 3 | Shape: [rows, dim] uint32 |
| 4 | Parameters: [epsilon] float32 |
Each row computes x * weight / sqrt(mean(x*x) + epsilon). Use a positive
epsilon. Input and output must be distinct: each thread reads the entire row.
Split-half rotary embedding
Entry point rope; dispatch rows × dim threads.
| Binding | Buffer |
|---|---|
| 0 | Input: [rows, dim] float32 |
| 1 | Output: [rows, dim] float32; may alias input |
| 2 | Shape: [rows, dim, rotaryDim, startPosition] uint32 |
| 3 | Parameters: [theta, positionScale] float32 |
rotaryDim must be even and no larger than dim. Pair j with
j + rotaryDim/2; use angle
(startPosition + row) * positionScale * theta^(-2*j/rotaryDim).
Unrotated trailing dimensions are copied. Use positive theta. Position
addition must fit uint32. For multiple heads at the same token position,
dispatch each head separately with that position. This is the split-half
convention; model-specific interleaved or multi-axis rotary schemes require
a different kernel.
Single-query attention
Entry point attention; dispatch dim threads.
| Binding | Buffer |
|---|---|
| 0 | Query: [dim] float32 |
| 1 | Keys: row-major [tokens, dim] float32 |
| 2 | Values: row-major [tokens, dim] float32 |
| 3 | Output: [dim] float32 |
| 4 | Shape: [tokens, dim] uint32 |
| 5 | Parameters: [scale] float32, usually 1/sqrt(dim) |
Computes softmax(scale * K*q)^T * V, subtracting the maximum score before
exponentiation. Supply finite activations/scores. Zero tokens produces zero
output. Select the permitted prefix on the host for causal attention; there
is no mask or batching/head dimension. Invoke separately for each head and
select the appropriate shared KV head for grouped-query attention.
DeltaNet recurrent step
Entry point deltaNet; dispatch valueDim threads.
| Binding | Buffer |
|---|---|
| 0 | Query: [keyDim] float32 |
| 1 | Key: [keyDim] float32 |
| 2 | Value: [valueDim] float32 |
| 3 | Mutable state: row-major [keyDim, valueDim] float32 |
| 4 | Output: [valueDim] float32 |
| 5 | Shape: [keyDim, valueDim] uint32 |
| 6 | Parameters: [decay, beta] float32 |
One step computes D = decay*S, residual = beta*(v - k^T*D),
S = D + k outer residual, then output = q^T*S. State updates in place;
all other writable/input buffers must remain distinct. Initialize state to
zero for a fresh sequence and dispatch sequentially for successive tokens.
Normalize/scale q and k and compute decay/beta on the host as required by the
model. This recurrence is a primitive, not the complete Qwen3.5 layer: causal
convolution, projections, gates, head reshaping, and output normalization
remain the caller’s responsibility.
Multihead RoPE
Entry point ropeMultiHead; dispatch tokens × heads × dim threads.
Bindings match rope: 0 input, 1 output, 2 shape, 3 parameters.
- Input/output: contiguous
[tokens, heads, dim]float32; may alias. - Shape:
[tokens, heads, dim, rotaryDim, startPosition]uint32. - Parameters:
[theta, positionScale]float32.
All heads within a token use the same startPosition + token position.
Split-half pairing and trailing-dimension copying follow rope. For one decode
token, set tokens = 1; dispatch all attention or KV heads together. Dimensions
must have a uint32-safe flattened product. Rotary size must be even and no
larger than dim; zero rotary size copies the input.
Multihead grouped-query attention
Entry point attentionMultiHead; dispatch queryHeads × dim threads.
Bindings match attention: 0 query, 1 keys, 2 values, 3 output, 4 shape,
5 parameters.
- Query/output: contiguous
[queryHeads, dim]float32 for one decode token. - Shape:
[tokens, queryHeads, kvHeads, dim, tokenStride, headStride]uint32. - Parameters:
[scale]float32. - Keys/values: element
(token, head, j)is attoken * tokenStride + head * headStride + j.
Strides count float32 elements, not bytes. A zero tokenStride defaults to
kvHeads * dim; a zero headStride defaults to dim, giving token-major
[tokens, kvHeads, dim]. For a head-major cache with capacity token slots,
use tokenStride = dim, headStride = capacity * dim. Both caches use the
same strides. Padded caches are supported; provide enough storage for the
largest referenced offset.
queryHeads must be a positive multiple of positive kvHeads. Query head
h selects KV head h / (queryHeads / kvHeads) (contiguous grouped-query
mapping). Select the allowed causal prefix with tokens; zero tokens writes
zero output. The stable softmax and finite-input requirements of attention
apply. This batches heads, not multiple query tokens; it does not add masking
or FlashAttention-style tiling.
Multihead grouped DeltaNet
Entry point deltaNetMultiHead; dispatch valueHeads × valueDim threads.
Bindings match deltaNet: 0 query, 1 key, 2 value, 3 mutable state, 4 output,
5 shape, 6 parameters.
- Query/key:
[keyHeads, keyDim]float32. - Value/output:
[valueHeads, valueDim]float32. - Shape:
[keyHeads, valueHeads, keyDim, valueDim, stateLayout]uint32. - Parameters:
[valueHeads, 2]float32, interleaveddecay, betaper head. - State layout 0: contiguous
[valueHeads, keyDim, valueDim]. - State layout 1: contiguous
[valueHeads, valueDim, keyDim].
valueHeads must be a positive multiple of positive keyHeads. Value head
h selects query/key head h / (valueHeads / keyHeads). Equal counts give
ordinary independent heads. Each value head has independent gates and state;
state updates in place. The recurrence and normalization responsibilities are
identical to deltaNet. Dispatch once per token for all heads and preserve
state between tokens. Unsupported layouts or invalid head ratios leave outputs
untouched; validate shapes on the host.
Synthetic validation and timing
tests/native/runtime/inference-shaders.m compiles the actual bundled source with Metal
and checks all four cooperative quant formats against the scalar reference
entries using randomized blocks, odd row counts, nonzero offsets, and padded
or implicit strides. It checks multihead RoPE against CPU trigonometry, grouped
attention against CPU softmax in token-major and padded head-major caches,
and repeated DeltaNet steps in both state layouts. No models are loaded.
clang -O2 tests/native/runtime/inference-shaders.m -framework Foundation -framework Metal -o /tmp/inference-shaders
/tmp/inference-shaders compiler/runtime/inference.metalThe same test reports GPU command-buffer execution times for a synthetic 6144-row × 2048-column Q4_K matrix, warmed up and averaged over five runs. On the development Mac on 2026-09-24: scalar 7.401 ms, cooperative 0.117 ms (63.01×). This excludes shader compilation, host submission/wait overhead, weight transfer, and other model operations; it is not token throughput.