Skip to content
mhpentaPublic

About

Transformer inference in pure Go on CPU or Apple silicon GPU (Metal, no cgo). BERT, T5, Llama, Qwen3, with every layer checked against PyTorch.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

infer

Transformer inference in Go, on the CPU or an Apple silicon GPU: load Hugging Face weights, tokenize, run the model, pool or quantize the result. No cgo, no ONNX, no Python.

Outputs match PyTorch: every model is checked layer by layer against reference outputs dumped from transformers (see Testing).

What it runs today

Every model but Qwen3.5 also runs on the Apple silicon GPU (the default there), and is checked against the same goldens on both devices; see GPU inference.

Model Output Check against PyTorch
all-MiniLM-L6-v2 (BERT, 22M) 384-dim mean-pooled embedding every layer within 5e-6, cosine 1.000000000
mxbai-embed-large-v1 (BERT, 335M, fp16) 512-bit binary embedding (CLS, normalize, Matryoshka 512, sign bits) bit-identical on 20 texts
t5-small (T5, 60M) and T5 fine-tunes greedy generation with a KV cache every encoder and decoder layer within 1.5e-6 of its range; generated tokens identical on 5 inputs up to 512 tokens
MiniCPM5-1B (Llama architecture, 1.1B, bf16) greedy generation with a KV cache, chat template every layer within 5.8e-6 of its range; top-64 logits within 1e-5 at every position; generated tokens identical on 4 prompts up to 2,461 tokens
MiniCPM5-2B (same architecture, 42 layers, bf16) the same, with its own chat template chat template matches transformers on 12 conversations; generated tokens identical on 3 prompts; on the GPU, the CPU's tokens with logits within 6.5e-6 (not in CI: 5 GB, scripts/fetch_models.sh minicpm5-2b)
Qwen3-1.7B (Qwen3ForCausalLM: per-head q/k RMSNorm, tied embeddings, bf16) greedy or sampled generation, chat template, NFC tokenizer every layer within 7.3e-6 of its range; top-64 logits within 1.2e-5 after the first position (3e-5 there, an attention sink); generated tokens identical on 4 prompts up to 2,579 tokens (not in CI: 4.1 GB, scripts/fetch_models.sh qwen3)
Qwen3-4B (same architecture: 36 layers, 32 query heads over 8 key-value heads, bf16) the same, with Qwen3-1.7B's tokenizer and chat template layer inputs and the final output within 5.4e-6 of their range on a chat prompt; top-64 logits within 6.4e-6 at every position; generated tokens identical on 4 prompts up to 2,579 tokens, on the CPU and the GPU (not in CI: 8 GB, scripts/fetch_models.sh qwen3-4b)
OpenJev 0.8B and 4B (Qwen3_5ForSequenceClassification: Qwen3.5's Gated DeltaNet linear attention in 18 of 24 layers, gated attention in the rest, bf16; CPU only) NLI probabilities, and typed decisions (choice, score, yes/no) as OpenJev's openjev_decide.py makes them; Qwen3.5's tokenizer every layer within 7.9e-6 of its range; logits within 2.6e-6 up to 2,575 tokens; options scored from a shared prefix bit-identical to scoring each alone; decision probabilities within 1e-5 (not in CI: 1.7 and 9.1 GB, scripts/fetch_models.sh openjev-0.8b and openjev-4b; see Qwen3.5 and OpenJev)
Inkling 2 Mini (Inkling2LoopForConditionalGeneration's text decoder: 26B mixture of experts, 8 of 128 per token, layers 6–17 looped three times; experts NVFP4 and MXFP8 as shipped, the rest bf16; CPU only) greedy or sampled generation, chat template with reasoning effort and tools, o200k tokenizer on a tiny random checkpoint in the original layout, loaded by transformers' converter: every layer visit within 5.1e-6 of its range, logits within 2.1e-5, greedy tokens identical with the caches; tokenizer and chat template match on 400 random strings and 7 conversations. Not yet checked on the real weights (19.5 GB, scripts/fetch_models.sh inkling2-mini; see Inkling 2)
YOLOS-Tiny (YolosForObjectDetection: ViT-Tiny encoder, 6.5M, f32; CPU and Metal) COCO object detections (class label, score, normalized corner box) every encoder layer within 1.9e-5 of its range on CPU (1.1e-5 on Metal), logits within 1.9e-5 (1.2e-5 on Metal), boxes within 1.4e-5, detections exact across 4 test images (scripts/fetch_models.sh yolos-tiny)

Packages

Package
tensor dense, row-major float32 tensors
ops matrix products and the rest of the kernels: LayerNorm, GELU, softmax, attention, the gated delta rule of Qwen3.5's linear attention, and products over NVFP4 and MXFP8 weights (ops.Microscaled)
safetensors memory-mapped .safetensors reader (F32 zero-copy, F16/BF16 upcast, the raw bytes of any tensor, such as F8_E4M3 and U8 microscaled weights), and a writer for F32 and BF16 tensors, byte for byte what the Python library's save_file writes
tokenizer/wordpiece BERT's tokenizer, matching Hugging Face's fast BertTokenizer
tokenizer/unigram SentencePiece Unigram from tokenizer.json (T5), including the precompiled NFKC character map
tokenizer/bpe byte-level BPE from tokenizer.json (MiniCPM5, Qwen3, Qwen3.5, Inkling 2 and other GPT-2-style tokenizers): NFC normalization, the GPT-4-style split patterns (cl100k's variants and o200k's) as hand-written scanners, ignore_merges, and the pattern tokenizer_config.json records when transformers ignores tokenizer.json's (Qwen3.5)
tokenizer/chat chat templates in Go, recognized by the hash of the model's Jinja template (MiniCPM5-1B and -2B, Qwen3, Inkling 2), with tool calling for Qwen3 and Inkling 2: tool definitions, tool calls and responses, and parsing calls from a reply
model/bert the BERT encoder; on Apple silicon, on the GPU by default (bert.LoadWith(dir, bert.Options{Device: ...}))
model/t5 the T5 encoder-decoder: relative position bias, cross-attention, greedy decoding with a KV cache; on Apple silicon, on the GPU by default (t5.Options)
model/llama Llama-family decoders (LlamaForCausalLM, Qwen3ForCausalLM): grouped-query attention, rotary embeddings, SwiGLU, bf16 or int8 weights (llama.LoadWith(dir, llama.Options{Int8: true})), greedy or sampled decoding with a KV cache, capture of selected layers' activations during it (llama.Capture); on Apple silicon, on the GPU by default, bf16 or int8 (Options.Device, INFER_DEVICE), checked against the same goldens
model/qwen35 Qwen3.5's text decoder on the CPU: Gated DeltaNet linear attention with its convolution and recurrent state, gated attention with partial rotary embeddings, zero-centered RMSNorm; the sequence-classification head (Classify), and scoring several continuations of one prefix with the prefix run once (ClassifyShared); bf16 or int8 weights
model/inkling2 Inkling 2 Mini's text decoder on the CPU: experts read from the checkpoint's NVFP4 and MXFP8 bytes, attention residuals over blocks of layers, the looped core with its message gates, sliding and full attention with learned relative bias, sinks and short convolutions; Generate, GenerateWith, Logits, HiddenStates
model/yolos the YOLOS Vision Transformer object detector (YolosForObjectDetection): patch projection, cached 2D bicubic positional embedding interpolation, Pre-LN ViT encoder, and 3-layer ReLU class/box heads; on Apple silicon, on the GPU by default (yolos.LoadWith(dir, yolos.Options{Device: ...}))
vision/preprocess RGB extraction, antialiased bilinear resizing (YolosImageProcessor), rescaling, normalization, non-overlapping patch extraction, and PyTorch-compatible 2D bicubic interpolation
vision/postprocess DETR/YOLOS softmax decoding, background filtering, confidence thresholding, center-to-corner box conversion, clipping, and IoU
openjev typed decisions with OpenJev's NLI checkpoints: Decide(state, questions) returns each option's probability, and NLI(premise, hypothesis) the three labels'
accel choosing the device a model runs on: the option, then INFER_DEVICE, then auto; opens the GPU once per process and self-checks its kernels against ops
metal GPU compute through Apple's Metal, without cgo (through internal/objc): devices, run-time compiled kernels, shared buffers, command buffers, and the models' kernels (products over bf16, fp16, float32 or int8 weights, RMSNorm and LayerNorm, RoPE, attention over a key/value cache, causal or not, with an optional bias, SwiGLU, GELU and ReLU, embedding lookup, argmax), each checked against ops. Every model in model/ but Qwen3.5 runs on it; see GPU inference
sample choosing the next token: greedy, or temperature, top-k, top-p and repetition penalty with transformers' meaning and order, defaults read from generation_config.json; the distributions match transformers' logits processors
pool mean and CLS pooling, L2 normalization
quant sentence-transformers' binary quantization
cmd/embed a small CLI: go run ./cmd/embed <model_dir> "some text"
cmd/decide typed decisions from the command line: go run ./cmd/decide <model_dir> questions.json < state.txt
cmd/detect object detection from the command line: go run ./cmd/detect <model_dir> photo.jpg
tok, err := wordpiece.LoadDir(dir) // vocab.txt + tokenizer_config.json
model, err := bert.Load(dir)       // config.json + model.safetensors
defer model.Close()

hidden, err := model.Forward(tok.Encode("Revenue grew 12% year over year."))
embedding := pool.Mean(hidden)
tok, err := unigram.LoadDir(dir) // tokenizer.json + tokenizer_config.json
model, err := t5.Load(dir)       // config.json + model.safetensors
defer model.Close()

out, err := model.Generate(tok.Encode("translate English to German: The house is wonderful."), 64)
fmt.Println(tok.Decode(out, true)) // Das Haus ist wunderbar.
tok, err := bpe.LoadDir(dir)    // tokenizer.json + tokenizer_config.json
tmpl, err := chat.Load(dir)     // chat_template.jinja, recognized by its hash
model, err := llama.Load(dir)   // config.json + safetensors shards
defer model.Close()

prompt, err := tmpl.Render([]chat.Message{{Role: "user", Content: "What is 17 * 23? Answer with just the number."}},
	chat.Options{AddGenerationPrompt: true, Thinking: chat.ThinkingOff})
out, err := model.Generate(tok.EncodeRaw(prompt), 64)
fmt.Println(tok.Decode(out, true)) // 17 * 23 = 391

// Or sample, with the model's own settings (MiniCPM5-2B: temperature 1, top-k 50, top-p 0.95).
cfg, err := sample.LoadConfig(dir) // generation_config.json, with transformers' defaults
s, err := sample.New(cfg, seed)
err = model.GenerateWith(tok.EncodeRaw(prompt), 512, s, func(token int, _ []float32) bool {
	out = append(out, token)
	return true
})

// A conversation re-renders its whole history each round. A session keeps
// the keys and values it has computed and runs only what a prompt adds to
// the longest prefix it shares with the last one.
session := model.NewSession()
err = session.GenerateWith(tok.EncodeRaw(prompt), 512, s, fn)

Reading activations

HiddenStates gives what enters each layer. A Capture reads what each layer computes, on the CPU or the GPU, for the layers and points it selects: the attention contribution after o_proj (AttentionOut), the activations between SwiGLU and down_proj (SwiGLUOut), and the feed-forward contribution after down_proj (MLPOut). They match transformers' forward hooks.

// A whole sequence, keeping copies in a Recording.
var rec llama.Recording
err := model.Capture(ids, llama.Capture{Layers: []int{3, 12}, Points: []llama.Point{llama.MLPOut}, Fn: rec.Record})
mlp, ok := rec.Get(12, llama.MLPOut) // mlp.Values is [len(ids), hidden]

// During generation with the KV cache. Fn sees the model's own memory, valid
// until it returns, and copies only what it wants: here, one position's norm.
err = model.GenerateCapture(prompt, 64, nil, llama.Capture{
	Layers: []int{12},
	Points: []llama.Point{llama.SwiGLUOut},
	Fn: func(a llama.Activation) {
		last := a.Values.Row(a.Values.Rows() - 1) // position a.Start + rows - 1
		norms = append(norms, norm(last))
	},
}, fn)

// In a session, where only positions the cache does not reuse run.
err = session.SetCapture(&llama.Capture{Points: []llama.Point{llama.AttentionOut}, Fn: rec.Record})

Prompts on the GPU run in chunks of 512 positions, so a long one reaches Fn in several calls: place rows with Start. Without a Capture a forward pass checks one pointer per layer (see the benchmarks in model/llama/bench_test.go).

Editing weights

safetensors.Write and an index let a checkpoint differ from another in a few tensors, without copying it. model.safetensors.index.json decides where each tensor comes from:

edited/
  config.json, generation_config.json, tokenizer.json, ...   symlinks to the base model
  base-0.safetensors, ...                                    symlinks to its shards
  delta.safetensors                                          the edited tensors
  model.safetensors.index.json                               edited tensors -> delta, the others -> base-N

No file may be called model.safetensors: the loader prefers that file and never reads the index, so the delta would be silently ignored.

Store a bf16 model's edits as BF16 when they can be: nothing else about the model changes. An F32 delta keeps precision bf16 would round away, and runs on either device (accel.Auto stays on the GPU), at the cost of float32 memory and bandwidth for the layers it covers. Both devices stack q_proj, k_proj and v_proj into one layer, and gate_proj and up_proj into another, so an F32 delta covering part of a stack (gate_proj without up_proj, say) makes that whole stack float32.

A delta of unchanged values, BF16 or F32, gives logits bit-identical to the base model's on the same device. Across devices they differ within float32 rounding, so when comparing an edited model with its base, check Model.Device on both.

How the matrix products work

ops follows the design of BLIS and OpenBLAS. Weights are packed once, at load time, into 16-column panels; inputs are packed per product into 6-row strips; an outer-product microkernel keeps a 6×16 block of the output in registers, and loops are blocked for the caches.

CPU Microkernel Notes
x86-64 with AVX2 + FMA 6×16, 12 YMM accumulators
x86-64 with AVX-512 12×32, 24 ZMM accumulators enabled only after a startup self-check against the portable kernel passes (ops.KernelCheck), within a bound on float32 rounding of the sums
arm64 6×16 NEON, 24 accumulators
anything else, or -tags purego portable Go

Weights stored as fp16 (like mxbai's) or bf16 (like most language models) can stay in that format in memory (ops.PackHalf, ops.PackBF16) and be widened to float32 in registers: half the memory and bandwidth, the same float32 values, so outputs are bit-identical. fp16 is widened by the x86 kernels; bf16 by the x86 and NEON kernels. Any weight can instead be quantized to int8 (ops.PackInt8, one scale per output column), which halves bf16's memory again; products are bit-identical to the float32 product on the integers, then scaled. The x86 and NEON kernels widen int8 in registers, but on NEON that costs enough instructions that generation is only 1.13–1.14× faster than bf16 (see docs/int8-weights.md, which also has the quality measurements). Softmax and GELU use AVX2 vector loops on x86. ops.PeakGFLOPS, ops.KernelGFLOPS and ops.MatMulGFLOPS measure the kernels on the machine they run on.

A product with a single row (each decoding step) skips the strip packing and runs a matrix-vector kernel that streams four panels at a time; it sums in the same order as the matrix kernels, so a row gives the same bits either way. Each group of four panels is read start to finish, so the weights stream from memory sequentially, and the work is cut into four chunks per thread, claimed as threads free up, so Apple's slower efficiency cores do not hold back the rest. Decoding is bound by memory bandwidth: on an M2 Max the bf16 kernel streams about 96 GB/s from DRAM, against roughly 115 GB/s for plain reads. ops.KVCache keeps attention keys and values in the packed layout the kernels read, appended once per position, so a decoder step packs nothing but its own new key and value. KVCache.Truncate cuts it back to a prefix, which is how llama.Session reuses a shared prompt prefix. Every operation computes a row the same way whichever rows run with it, and attention's softmax gives a row the same bits however many masked keys pad it to its pass's length (on amd64 the leftover entries past a multiple of 8 run through the vector code too), so a reused prefix gives bit-identical logits to running the whole prompt again.

The amd64 assembly is generated by scripts/gen_amd64_kernels.py.

T5 generation speed

t5-small, greedy, one thread on an M2 Max, against PyTorch 2.1.1 (which uses Apple's Accelerate BLAS, running large products on the AMX matrix unit):

Input / output tokens infer PyTorch
11 / 6 42 ms 50 ms
19 / 31 179 ms 226 ms
45 / 31 197 ms 233 ms
50 / 62 361 ms 457 ms
512 / 41 845 ms 398 ms

Decoding is faster than PyTorch; a long input's encoder pass (570 ms of the last row) is where Accelerate's AMX products pull ahead.

Testing

Weights are not checked in. Fetch the pinned revisions (with hash checks) into testdata/models, then run the tests; tests that need a model skip without it.

scripts/fetch_models.sh
go test ./...

-tags purego runs everything on the portable kernels. On Apple silicon, an amd64 Docker container exercises the AVX2 kernels (Rosetta exposes AVX2, not AVX-512); INFER_REQUIRE_AVX2=1 makes the tests fail rather than skip without it:

docker run --rm --platform linux/amd64 -v "$PWD":/src -w /src -e INFER_REQUIRE_AVX2=1 golang:1.25 go test -short ./...

The reference outputs in testdata/golden come from scripts/dump_golden_bert.py, scripts/dump_golden_mxbai.py, scripts/dump_golden_t5.py, scripts/dump_golden_llama.py, scripts/dump_golden_llama_hooks.py and scripts/dump_golden_sample.py (PyTorch + transformers). scripts/check_safetensors_write.py checks the writer's files against the Python library and PyTorch. benchcmp/ is a separate module comparing the matrix product with gonum and vek.

License

MIT

About

Transformer inference in pure Go on CPU or Apple silicon GPU (Metal, no cgo). BERT, T5, Llama, Qwen3, with every layer checked against PyTorch.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages