Skip to content
moonbitstackPublic

About

Tensors and computation graphs for MoonBit, on CPU and WebGPU.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

moonggml

Tensors, the graph you build from them, and the schedule that runs it.

A tensor is a type, up to four dimensions, the strides that walk them, and a handle on where the numbers are. A graph is a list of steps that each read values and write a new one, so a value is written once, where it is created. A schedule decides where each value lives and which backend runs which step. The backend in this package needs nothing but the language, and computes every operation a transformer needs: matrix products over weights in blocks, gathers, normalisation, rotation, attention, gated feed-forward, and the shape changes in between.

Install

moon add moonbitstack/moonggml
import {
  "moonbitstack/moonggml/tensor",
  "moonbitstack/moonggml/graph",
  "moonbitstack/moonggml/backend",
  "moonbitstack/moonggml/cpu",
  "moonbitstack/moonggml/sched",
}

Packages

Package What it holds
tensor Types, shapes, strides, the storage handle, half precision
quant The block formats: unpacking all of them, writing Q8_0 and Q4_0
graph A context that builds the graph, the steps, the rotation settings
plan Where each intermediate lives and for how long; the Planner seam
backend The Backend contract, and the range of steps one backend is handed
cpu The backend that needs nothing: every kernel, twice
sched The schedule: reserving memory, splitting the graph, running it

A first graph

let ctx = @graph.Ctx::new()

// Two weights of three inputs each, and a batch of two three-long vectors.
let w = @tensor.Tensor::from_f32(ne = [3, 2], data = [1.0, 0.0, 0.0, 0.0, 1.0, 1.0])
let x = @tensor.Tensor::from_f32(ne = [3, 2], data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0])

let weight = ctx.input(w)
let input = ctx.input(x)
let projected = ctx.mul_mat(weight, input)
let normalised = ctx.rms_norm(projected)
let out = ctx.silu(normalised)
let _ = ctx.output(out)

The graph is the list of steps; nothing has run yet. A schedule runs it:

let backend : &@backend.Backend = @cpu.cpu
let sched = @sched.Sched::fresh(backends = [backend])
let plan = sched.reserve(graph = ctx.graph())
sched.compute(graph = ctx.graph())

assert_eq(out.shape_text(), "2x2")
assert_eq(Show::to_string(plan), "3 buffers, 32 bytes at peak")

reserve asks the planner for a plan and gives every intermediate its memory; compute cuts the graph into slices and hands each to its backend. With one backend there is one slice, and the split is the whole graph.

Operations

Every operation reads the values it names and writes a new one. A shape that does not line up is refused where the graph is built, not when it runs.

Operation Reads Writes
mul_mat(a, b) a[k, m], b[k, n] [m, n]
get_rows(table, ids) table[n, rows], row numbers [n, len(ids)]
add, mul two values of one shape that shape
scale(a, scale) a value that shape
rms_norm(a, eps), norm(a, eps) rows of the first dimension that shape
rope(a, pos, rope) [features, heads, tokens] and one position per token that shape
soft_max(a, mask?, scale) rows of the first dimension that shape
silu(a), gelu(a) a value that shape
swiglu(a, gate) two values of one shape that shape
cpy(a), cont(a) a value the same numbers
permute(a, axes), transpose(a) a value the axes reordered
view(a, ne), reshape(a, ne) a value the same numbers, another shape
argmax(a) a matrix one position per row, as I32

mul_mat, get_rows and the shape operations also take weights that are not single precision: a half-precision table, or one of the block formats below.

Types

The codes are the ones the file format assigns, so a type read from a file needs no translation.

Type Code Elements per block Bytes per block
F32 0 1 4
F16 1 1 2
Q4_0 2 32 18
Q4_1 3 32 20
Q5_0 6 32 22
Q5_1 7 32 24
Q8_0 8 32 34
Q2_K 10 256 84
Q3_K 11 256 110
Q4_K 12 256 144
Q5_K 13 256 176
Q6_K 14 256 210
I32 26 1 4
BF16 30 1 2

A quantised row is a whole number of blocks; a shape whose first dimension does not fill one is refused, because padding would travel with the tensor into every kernel.

Weights in blocks

Every block format can be read:

// Two blocks of Q4_0: a half-precision scale and sixteen bytes of nibbles each.
let image = FixedArray::make(36, b'\x00')
@tensor.write_u16_le(image, 0, 0x3C00)
@tensor.write_u16_le(image, 18, 0x3C00)
let values = @quant.dequantize_row(dtype = @tensor.Q4_0, image = image, n = 64)
assert_eq(values.length(), 64)

Two formats can also be written, which is what building a quantised tensor from float numbers needs:

let source : Array[Float] = Array::make(64, 0.5)
let blocks = FixedArray::make(@tensor.Q8_0.row_bytes(64), b'\x00')
@quant.quantize_into(dtype = @tensor.Q8_0, values = source[:], image = blocks)
let back = @quant.dequantize_row(dtype = @tensor.Q8_0, image = blocks, n = 64)
assert_eq((back[0] - 0.5F).abs() <= 0.00004F, true)

Q8_0 divides the largest magnitude of a block by 127 and stores the result in half precision, so a value comes back within one step of that scale: a row of one repeated value is that step, not a rounding of the value itself.

Rotation

A rotation turns pairs of features by an angle that depends on the position. n_dims of zero turns the whole first dimension, which is the usual case; the two orders pair features differently.

let ctx2 = @graph.Ctx::new()
let x2 = @tensor.Tensor::from_f32(ne = [4, 1, 2], data = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])
let pos = @tensor.Tensor::from_i32(ne = [2], data = [0, 1])
let turned = ctx2.rope(ctx2.input(x2), ctx2.input(pos))
assert_eq(turned.ne(), [4, 1, 2, 1])

Rope carries the frequencies: freq_base, freq_scale, and the extrapolation settings ext_factor, attn_factor, beta_fast, beta_slow, n_ctx_orig. @graph.rope is the unscaled configuration of a model trained on 4096 tokens.

Two paths through every kernel

The kernels that add, multiply, scale, dot and sum are written twice: once over 128-bit vectors and once element by element. On WebAssembly the first is a real instruction; on the targets without one the same code is lowered to the same scalar work. @cpu.Cpu::new(vector = false) picks the second, and the tests hold both to the same expected values.

Extending it

Three contracts are open, and a caller implements them without changing a line here.

  • @backend.Backend is what a second device plugs into: a name, which operations it takes, allocating, moving bytes in and out, and running a range of steps.
  • @plan.Planner decides where each intermediate lives. @plan.fresh gives each one its own buffer; a planner that reuses buffers is another value of the same contract.
  • @plan.Pass rewrites a graph. @plan.Passes runs them in order; it holds none yet, so adding the first fusion does not move a caller.

Consistency

Every operation is compared against an outside implementation, on several shapes and with fixed inputs. The vectors come from a program built against llama.cpp at a pinned version, which computes each operation and prints the inputs and the results as bit patterns; scripts/reference/ holds that program and the script that turns its output into the corpus the tests replay.

There are 70 cases, and every one runs twice, once per arithmetic path. Exact where the arithmetic is exact; the rest is compared as |got - want| <= abs + rel * |want|:

Operation rel abs Why not exact
add, mul, scale, cpy, cont, permute, transpose, view, reshape — — the same arithmetic in the same order
get_rows, argmax — — a copy and a comparison
block unpacking, block writing — — compared as bytes, bit for bit
mul_mat 1e-4 1e-6 the sum is taken in a different order
rms_norm, norm 1e-5 1e-6 one-pass against two-pass sums
soft_max 1e-5 1e-7 the exponential is another library's
rope 1e-5 1e-6 the same
silu, swiglu 1e-5 1e-7 the same
gelu 5e-3 1e-5 the reference rounds its input to 16 bits first

One difference is deliberate and worth stating: the reference's own product of a quantised weight with a float vector rounds that vector to eight bits first, which trades accuracy for speed. This library unpacks the weights and multiplies in single precision, so the comparison is against the reference computing the same product over the unpacked weights. The unpacking itself is compared bit for bit, so nothing about the block formats is left loose.

Licence

Apache-2.0. See LICENSE.

About

Tensors and computation graphs for MoonBit, on CPU and WebGPU.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

Generated from moonbitstack/moonkit