models
BERT #
Bert.open(dir, backend) loads model.safetensors and config.json from a folder. Bert.run(m, encodings) takes encodings from the tokenizer, pads them to the longest, and gives Output(hidden, pooled): the last hidden state [batch, seq, hidden_size] and the pooler output [batch, hidden_size] (none when the checkpoint has no pooler). Bert.embed(m, encodings) gives one vector per sentence, the mean of its token vectors without the padding. Bert.load(c, config, backend) builds the model from an open Hub.Checkpoint and a Config (the fields of config.json). Bert.forward(m, ids, type_ids, mask) runs it on tensors: ids and type_ids are I32 and mask is F32 (1.0 for a token, 0.0 for padding), all [batch, seq]. run builds these from the encodings. Close it with Bert.close(out).
import Bert from "pkg/transformers/bert"
import Tensor from "pkg/tensor/tensor"
import WordPiece from "pkg/transformers/tokenizer/wordpiece"
def main() -> Void
backend = Tensor.Backend.Ggml(Tensor.Device.Cpu)
tok = WordPiece.open("bert-base-uncased/tokenizer.json").unwrap!
m = Bert.open("bert-base-uncased", backend).unwrap!
sentences = ["Hello, world!", "The quick brown fox jumps over the lazy dog."]
encodings = sentences.map { |s| WordPiece.encode(tok, s).unwrap! }
out = Bert.run(m, encodings).unwrap!
puts(Tensor.shape(out.hidden))
puts(Tensor.shape(Bert.embed(m, encodings).unwrap!))
end[2, 12, 768]
[2, 768]- A run's outputs, and the model itself, hold ggml memory that
Bert.close(out)andBert.close_model(m)free at once;embedfrees what it made. Nothing may use a closed model: a call that does is an error. - The padding is masked as Hugging Face does, so a sentence in a padded batch gets what it gets alone.
- The model matches
BertModelinfloat32on ggml CPU and Vulkan: the largest gap is 5e-5 onbert-base-uncased, over six sentences and a padded batch. - Checkpoints with the
bert.prefix andgamma/betalayer norms (bert-base-uncased) and those without (save_pretrainedtoday) both load; thecls.*head is ignored. Amodel_typeother thanbert, a position embedding other thanabsoluteand an activation other thangelu,gelu_new,gelu_pytorch_tanhandreluare errors. - On ggml the forward is one graph with the weights as constants; the other backends run it eagerly. The weights are
F32in memory (about 0.4 GB forbert-base-uncased). - The sequence length may not pass
max_position_embeddings(512), and every encoding needs a token. Bert.weights(m)gives the weights by their names in the checkpoint (encoder.layer.0.attention.self.query.weight; underbert.when the file has that prefix, the layer norms asweightandbiaseven when the file saysgammaandbeta, the pooler when there is one), andBert.with_weights(m, weights)gives the model with those tensors in their place, asDistilBertdoes.Bert.pooled(m, ids, type_ids, mask, normalize)is the mean embedding as plain tensor calls, for a loss withParamsandTrain.fit: the pooler is not in it, so it has no gradient there. Freeze it, or train a head overBert.forward, to use it.tools/minilm_finetune.agcis a check thatsentence-transformers/all-MiniLM-L6-v2(6 layers, width 384) loads and trains:sh tools/fetch_minilm.shdownloads the pinned revision and checks its sha256, andagentica tools/minilm_finetune.agc MODEL_DIR [cpu|vulkan|xla|torch]fine-tunes it for a few steps on eight scored pairs on ggml (CPU or Vulkan), XLA or libtorch. On libtorch every weight trains too: a step of 16 sentences of 16 tokens peaks at 1.4 GiB of resident memory. Its embeddings match Hugging Face's within 1e-4, measured 2.5e-6 (tools/bert_check.agc).- Reference, ggml and libtorch are tested (libtorch for the gradient and
Train.fit).Bert.openreadsmodel.safetensorsonly, not a sharded checkpoint.
DistilBERT #
DistilBert.open(dir, backend) loads model.safetensors and config.json of a DistilBERT (sentence-transformers/msmarco-distilbert-cos-v5, distilbert-base-uncased): BERT's blocks with word and position embeddings only, no token types and no pooler. DistilBert.run(m, encodings) pads the encodings to the longest and gives the last hidden state [batch, seq, dim]. DistilBert.embed(m, encodings, normalize) gives one vector per sentence, [batch, dim]: the mean of its token vectors, and with normalize: true that mean over its length, which is what a sentence-transformers model with Pooling and Normalize modules answers. msmarco-distilbert-cos-v5 lists Normalize in its modules.json, so its embeddings need normalize: true.
import DistilBert from "pkg/transformers/distilbert"
import Tensor from "pkg/tensor/tensor"
import WordPiece from "pkg/transformers/tokenizer/wordpiece"
def main() -> Void
backend = Tensor.Backend.Ggml(Tensor.Device.Cpu)
dir = "msmarco-distilbert-cos-v5"
tok = WordPiece.open("#{dir}/tokenizer.json").unwrap!
m = DistilBert.open(dir, backend).unwrap!
sentences = ["How big is London?", "London has 9 million people."]
encodings = sentences.map { |s| WordPiece.encode(tok, s).unwrap! }
puts(Tensor.shape(DistilBert.embed(m, encodings, true).unwrap!))
end[2, 768]DistilBert.forward(m, ids, mask)isrunon tensors:I32ids and anF32mask (1.0 for a token, 0.0 for padding), both[batch, seq].DistilBert.weights(m)gives the weights by their names in the checkpoint (transformer.layer.0.attention.q_lin.weight; underdistilbert.when the file has that prefix), andDistilBert.with_weights(m, weights)gives the model with those tensors in their place: the names ofweights(m), no more and no fewer, with the same shapes. The result shares those tensors, with no copy, soclose_modelof it closes them. WithParamsof the train package they train the model or part of it.DistilBert.pooled(m, ids, mask, normalize)is the mean embedding as plain tensor calls, for a loss: with the traced weights ofwith_weightsit is part of the trace, soTrain.fittakes its gradient.Sentence.cosine_similarity_lossof two of them is the loss of a model trained on scored pairs. Outside a trace it runs eagerly, which is an error on ggml ("does not run eagerly on the ggml backend"):embedis the call for inference. The gradient runs on the reference, ggml and libtorch.- A LoRA adapter (
Loraof the train page) goes on these names (targets: ["q_lin", "v_lin"]), and a PEFT adapter of aDistilBertModelloads as it is; for a checkpoint with thedistilbert.prefix the names carry it.DistilBert.embeddings(m)names the two embedding tables, forLora.save. - The results belong to the caller (
Lift.close), andDistilBert.close_model(m)frees the weights. Nothing may use a closed model. - A checkpoint with the
distilbert.prefix (DistilBertFor...) loads too, and its head is ignored. The layer-normepsis 1e-12, as in Hugging Face's code. Amodel_typeother thandistilbert, an activation other thangeluand sinusoidal positions are errors. - Only
model.safetensorsis read, neverpytorch_model.bin. Reference, ggml and libtorch are tested (libtorch for the gradient andTrain.fit).
Sentence (pkg/transformers/sentence) holds the pieces a sentence-embedding model adds to an encoder, each usable inside a trace:
Sentence.mean_pooled(hidden, mask)averages[batch, seq, width]over the tokens the[batch, seq]mask keeps. A row with no token gives zeros.Sentence.normalized(x)gives each row of[batch, width]over its length. A row of zeros stays zeros.Sentence.cosine_similarity_loss(a, b, scores)is the mean of(cosine - score)^2over pairs of rows (Nn.cosine_similarity) with[batch]scores: sentence-transformers'CosineSimilarityLoss.
ResNet #
ResNet.open(dir, backend) loads model.safetensors and config.json of a ResNetForImageClassification (microsoft/resnet-50, microsoft/resnet-18). ResNet.run(m, images) takes the images as F32 [batch, 3, height, width], already normalized as the checkpoint's image processor does, and gives the logits [batch, classes]. ResNet.top(m, logits, k) gives the k best classes of each image as Classify.Prediction(id, label, logit), best first, with the names of config.json. The vision package makes the input: Hugging Face's image processor (resample 3, bicubic; size 224; crop_pct 0.875) of these checkpoints resizes the shorter side to 256 (224 over crop_pct 0.875), cuts the center 224 by 224, scales to 0..1 and normalizes with the ImageNet mean and std. Vision.Step.Resize(256, Vision.Kernel.Cubic), CenterCrop(224, 224) and normalize do the same up to two differences: the pixels are at most one 8-bit level (0.0175 normalized) from Pillow's, 95% of them exactly, and a crop with an odd gap between the sizes (half a pixel) rounds the offset to the even pixel, as torchvision does, where Hugging Face floors it, so the crop can sit one pixel apart. To classify an image:
import ResNet from "pkg/transformers/resnet"
import Tensor from "pkg/tensor/tensor"
import Vision from "pkg/vision/vision"
backend = Tensor.Backend.Ggml(Tensor.Device.Cpu)
m = ResNet.open("resnet-50", backend).unwrap!
photo = Vision.Folder(classes: ["photo"], paths: ["cat.jpg"], labels: [0])
steps = [Vision.Step.Resize(256, Vision.Kernel.Cubic), Vision.Step.CenterCrop(224, 224)]
batch = Vision.samples(photo, [0], steps, 0, backend).unwrap!
pixels = Vision.normalize(batch.inputs, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]).unwrap!
logits = ResNet.run(m, pixels).unwrap!
for p in ResNet.top(m, logits, 5).unwrap![0]
puts("#{p.label}: #{p.logit}")
end- The batch norm after each convolution is folded into the convolution when the model loads, so the model is for inference and the weights it holds are not the checkpoint's. On ggml
runis one graph; close its logits withResNet.close(logits)and the weights withResNet.close_model(m). - The ids and names are those of ImageNet-1k in the checkpoint's
config.json. Amodel_typeother thanresnet, an activation other thanreluand alayer_typeother thanbottleneckandbasicare errors, and so is an input that is not[batch, 3, height, width]. Any height and width that the strides leave a pixel of are valid; the checkpoints were trained at 224. - Against Hugging Face's
ResNetForImageClassificationinfloat32, on four images through the whole pipeline, the best 5 classes are the same and in the same order for both models on CPU and Vulkan. On Hugging Face's own pixels the largest gap of a logit is 1.6e-5 (ResNet-50) and 1.1e-5 (ResNet-18); withvision's own resize (Cubic, the kernel ofresample3) it is 0.092 and 0.048, from the pixels, which are one level (0.0175) from Pillow's at the most after normalizing (0.16 and 0.065 with libvips' default Lanczos 3). - Speed on the machine of
benchmarks/(ResNet-50, 224 by 224): 7.6 images per second at batch 1 and 8.1 at batch 32 on the CPU, 17.8 and 27.8 on Vulkan; the forward and backward of the folded model takes 1.5 s at batch 1 and 35 s at batch 32 on the CPU. - Reference and ggml are tested; libtorch is not.
ResNet.forward(m, images)is the same model as plain tensor calls, for a loss.
ViT #
ViT.open(dir, backend) loads model.safetensors and config.json of a ViTForImageClassification (google/vit-base-patch16-224). ViT.run(m, images) takes the images as F32 [batch, 3, 224, 224], already normalized as the checkpoint's image processor does, and gives the logits [batch, classes]. ViT.top(m, logits, k) gives the k best classes of each image as Classify.Prediction(id, label, logit), best first, with the names of config.json. The vision package makes the input: Hugging Face's image processor of this checkpoint stretches the whole image to 224 by 224 (no crop, no aspect ratio kept; resample bilinear), scales to 0..1 and normalizes with mean and std 0.5. Vision.Step.ResizeTo(224, 224, Vision.Kernel.Linear) and normalize do the same: the pixels are one level (0.0078 normalized) from Pillow's at the most, 92% of them exactly (0.0235 with libvips' default Lanczos 3). To classify an image:
import Tensor from "pkg/tensor/tensor"
import Vision from "pkg/vision/vision"
import ViT from "pkg/transformers/vit"
backend = Tensor.Backend.Ggml(Tensor.Device.Cpu)
m = ViT.open("vit-base-patch16-224", backend).unwrap!
photo = Vision.Folder(classes: ["photo"], paths: ["cat.jpg"], labels: [0])
batch = Vision.samples(photo, [0], [Vision.Step.ResizeTo(224, 224, Vision.Kernel.Linear)], 0, backend).unwrap!
pixels = Vision.normalize(batch.inputs, [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]).unwrap!
logits = ViT.run(m, pixels).unwrap!
for p in ViT.top(m, logits, 5).unwrap![0]
puts("#{p.label}: #{p.logit}")
end- The model is a convolution of stride 16 (the patches), a class token, learned positions, twelve pre-norm blocks of
Nn.EncoderBlockwith the exact GELU, a final layer norm and a linear head on the class token. On ggmlrunis one graph; close its logits withViT.close(logits)and the weights withViT.close_model(m). - The ids and names are those of ImageNet-1k in the checkpoint's
config.json. Amodel_typeother thanvitand an activation other thangeluare errors, and so is an input that is not[batch, 3, image_size, image_size]: the position table is for one size, and nothing interpolates it. The names and shapes of the checkpoint's tensors are checked before any is loaded. - Against Hugging Face's
ViTForImageClassificationinfloat32, on four images: with Hugging Face's own 8-bit pixels the top 5 classes are the same and in the same order, and the largest gap of a logit is 1.2e-5 on CPU and 9.6e-6 on Vulkan. Throughvision's own resize (Linear) the largest gap is 0.103 (0.156 with Lanczos 3), from the pixels, and the top 5 is Hugging Face's in the same order, on CPU and Vulkan (with Lanczos 3 the best five of these drawn images, whose logits lie within 0.03 to 0.3 of each other, were reordered). - Speed on the machine of
benchmarks/: ViT-B/16 forward at 224 by 224 runs at 2.6 images per second at batch 1 and 3.4 at batch 32 on the CPU, 5.3 and 7.4 on Vulkan (exactfloat32). - Reference and ggml are tested; libtorch is not.
ViT.forward(m, images)is the same model as plain tensor calls, for a loss.
Qwen3 #
Qwen3.open(dir, backend, weights) loads config.json and model.safetensors from a folder (or one .gguf file, whose key-values give the config) (Qwen/Qwen3-0.6B, whose weights are bfloat16 on disk and F32 in memory). The same loader reads Qwen2.5 (Qwen/Qwen2.5-0.5B-Instruct): its config.json says model_type qwen2, which has no query and key norms and has a bias on the query, key and value projections, and head_dim is hidden_size / num_attention_heads when the config has none. It reads Llama too (model_type llama, the architecture of SmolLM2, the text model of SmolVLM): the same block with neither the norms nor the biases (attention_bias and mlp_bias must be false), tested against Hugging Face's LlamaForCausalLM on a tiny model. Qwen3.open_idefics3(dir, backend, weights) reads the Llama text model of a SmolVLM folder (SmolVLM-256M-Instruct: model_type idefics3, the model in text_config, its tensors under model.text_model. and an untied lm_head.weight; the tower and the connector in the file are not read), and its logits on a prompt of token ids match Hugging Face's on the real 256M checkpoint. A prompt with image features goes through Generate like Qwen3.5's: Generate.start(some(KvDecoder.plain_sight(features, Qwen3.image_token(dir).unwrap!, ids))) splices the rows of SmolVlmVision.encode into the embeddings at the image tokens, and its logits on a tile match Hugging Face's on the real checkpoint (generate takes the same sight). Qwen3.run(m, rows) takes rows of token ids of one length and gives the logits [batch, seq, vocab_size]: each position reads itself and the ones before it. With last: true it gives only the last position's, [batch, 1, vocab_size], the row that picks the next token. With weights: Dtype.F16 the big matrices (the projections, the token table and the output head) are kept as half weights on ggml: half the memory and a decode 1.6 times faster on Vulkan, with a load close to F32's (the CPU gain is not claimed: see the hub page). With weights: Dtype.Q8_0 and a .gguf file that stores its matrices as Q8_0, or weights: Dtype.Q4_K and one that stores them as Q4_K and Q6_K, they stay as quantized blocks on ggml (see the hub page). F32 is the default and the exact path, and Vulkan multiplies in fp16 by default (Tensor.vulkan_fp16), which breaks the Hugging Face goldens with F32 weights too: Tensor.vulkan_fp16(false) before the first ggml call makes it exact, as the checks of this package do.
import Bpe from "pkg/transformers/tokenizer/bpe"
import Qwen3 from "pkg/transformers/qwen3"
import Tensor from "pkg/tensor/tensor"
def main() -> Void
backend = Tensor.Backend.Ggml(Tensor.Device.Vulkan(0))
tok = Bpe.open("Qwen3-0.6B/tokenizer.json").unwrap!
m = Qwen3.open("Qwen3-0.6B", backend).unwrap!
ids = Bpe.encode(tok, "The capital of France is").unwrap!
puts(ids)
puts(Tensor.shape(Qwen3.run(m, [ids], true).unwrap!))
end[785, 6722, 315, 9625, 374]
[1, 1, 151936]- The model matches
Qwen3ForCausalLMinfloat32on ggml CPU and Vulkan: over five prompts of 5 to 50 tokens the largest gap of a logit is 4.9e-5 on the CPU and 8.6e-5 on Vulkan, and the five largest logits name the same ids at every position. - Qwen2.5-0.5B-Instruct matches
Qwen2ForCausalLMinfloat32too: the largest gap of a logit is 4.3e-5 on the CPU and 1.3e-4 on Vulkan over the same five prompts, the 24 greedy ids of each prompt are Hugging Face's on Vulkan (on the CPU for prompts 0 to 2), and its tokenizer agrees withtokenizerson 1827 cases. Hugging Face's owngeneratefor Qwen2.5-Instruct applies therepetition_penalty1.1 of itsgeneration_config.jsoneven when greedy, so its ids differ from ours (the goldens set 1.0). - A Q8_0 GGUF of Qwen3-0.6B (made by llama.cpp's
llama-quantizefrom the F16 file) runs withweights: Dtype.Q8_0in 2.0 GB at the peak ofqwen_checkagainst 4.1 GB withF32weights (the same GGUF read asF32), and its prompts take 15% to 25% less time on the CPU (one run). Against the logits of llama.cpp for the same file (tools/llama_golden.c;QUANTIZED=1 qwen_check) the largest gap of a logit is 0.32 to 0.59 over the five prompts, on logits of up to 30. Both round every activation of a product to Q8_0 blocks, and that rounding is chaotic: llama.cpp against itself with anF32KV cache instead of anF16one moves by up to 0.65. WithF32weights from the same file dequantized the model matches llama.cpp's ownF32run of it to 0.018. - A Q4_K_M GGUF of Qwen3-0.6B (made by
llama-quantize; Q4_K and Q6_K matrices) runs withweights: Dtype.Q4_Kin 1.6 GB at the peak ofqwen_checkagainst 3.2 GB withF32weights. Against the logits of llama.cpp for the same file the largest gap of a logit is 1.66 over the five prompts, on logits of up to 30, which is the noise of rounding the activations to blocks: llama.cpp against its ownF32run of the dequantized file differs by 0.65 to 1.97. WithF32weights from the same file the gap against llama.cpp'sF32run of it is 0.021. Against llama.cpp on the same file at equal threads (4), a prompt of 128 tokens runs about 1.1 times as fast as llama.cpp's on the CPU and 0.84 times on Vulkan, and 64 tokens after it 0.89 times and 0.84 times; the CPU memory is the same (0.74 GB) and, on Vulkan, the GPU memory a little lower (565 against 627 MB) and the host RSS 0.29 GB higher (benchmarks/README.md, ml#291). - The layers are grouped-query attention (Qwen3 normalizes the query and key per head; Qwen2.5 has no such norms and has a bias on the query, key and value projections), rotary positions with
rope_theta, a SwiGLU MLP, RMS norms, and an output head tied to the embedding table when the config says so (the file'slm_head.weightis then ignored). Qwen3.logits(m, ids, last)isrunon a tensor ofI32ids[batch, seq]onm.device(the backend the model was opened on; withlayers_on_deviceits table may be on the CPU); the caller keepsids.Qwen3.read_config(dir)gives theConfigofconfig.json,Qwen3.checkpoint(dir)the weights, andQwen3.load(c, config, backend, weights)builds the model from both, asopendoes.Qwen3.weights(m)gives the weights by their Hugging Face names (model.layers.0.self_attn.q_proj.weight; a tied head is the table and has no name of its own), andQwen3.with_weights(m, weights)gives the model with those tensors in place of its own; the names must be the model's, no more and no fewer, each with the model's shape. WithParamsof the train page they train part of a model: inside a loss the tensors are traced andQwen3.logitsof the rebuilt model is part of the trace. A half or quantized weight has no gradient, so train a model loaded asF32.- A LoRA adapter (
Loraof the train page) goes on these names:targets: ["q_proj", "v_proj"]takes those projections of every layer, and a PEFT adapter of aQwen3ForCausalLMloads as it is.Qwen3.with_weights(m, try Lora.merged(Qwen3.weights(m), adapter))is the model with the adapter merged in.Qwen3.embeddings(m)names the embedding table, forLora.save(dir, adapter, Qwen3.embeddings(m)), which then refuses an adapter PEFT would misread. Qwen3.runis the forward over a whole sequence, with no cache: on ggml every call traces and plans a graph (0.6 to 1.7 seconds on the CPU, 0.2 to 0.6 second on Vulkan for these prompts). To generate, useGenerate.Qwen3.open(dir, backend, weights, layers_on_device)withlayers_on_device: non a Vulkan device loads the weights of the blocks from thenth on on the CPU, so a model that does not fit in the memory of the card still runs, as with-nglin llama.cpp. A step runs those blocks on the CPU, with their KV cache in host memory, and the firstnblocks on the device; withnbelow the number of blocks the embedding table is on the CPU, and the head and the final norm are on the device (a tied head is a second copy of the table there, which costs the size of the table in card memory, about 128 MB for Qwen3-0.6B Q6_K, and the time to read it again at load), as with-nglin llama.cpp, which puts its output layer on the GPU for any-nglof 1 or more; withnof 0 they are on the CPU too. The activations cross the bus once at each boundary. The default,none, keeps everything on the device, exactly as before, and on a CPU backend, or with annof the number of blocks or more,nchanges nothing. The logits of a step are those of the model with every block on the device (nof 0, 1 or the number of blocks, in the tests), up to the rounding that the two backends differ by. The tools oftools/read theAGENTICA_ML_LAYERS_ON_DEVICEenvironment variable, andAGENTICA_ML_KV=hostfor the cache in host memory. On Qwen3-0.6B Q4_K_M the card holds 579 MB with every block, 453 MB with 26, 290 MB with 13 and 2 MB with none; against llama.cpp with the same blocks on the card (-ngl 27,-ngl 14,-ngl 0) the prompt runs at about 0.65 (26 blocks), 0.96 (13) and 1.44 (none) times its speed and a token at 0.48, 0.68 and 0.78 times. The knob is for a model that does not fit in the memory of the card, not for speed: the card's clock drops when it is idle part of each step, so a step with a few blocks on the CPU takes much longer than one with all of them on the card (benchmarks/README.md). See the tensor page for how the graph is split.Placement.fit(footprint, budget)(import Placement from "pkg/transformers/placement") picks thelayers_on_devicefor a budget in bytes: the largestnwhose layout (the one above: the firstnblocks and a copy of the head on the card, or all of them with the table and the head once each) needs at mostbudget, and 0 when not even one block fits.footprintis aPlacement.Footprint(blocks, table, head, tied)with the bytes of each block (add its KV cache to count it), of the embedding table and of the head with the final norm, andtiedfor a head that is the table.Placement.footprint(c, layers, blocks, table, head, norm, weights, kv)counts it from an open checkpoint without reading a value (blockiis the tensors named{layers}{i}.pluskvbytes for its cache; the head is the table whenheadis not in the checkpoint).Placement.budget(free, reserve, cap)isfreelessreserve(for the compute buffers), not abovecapwhen it issome, and never below 0. Both are pure: they read no device. For example, five blocks of 100 MB, a table of 40 MB and an untied head of 30 MB with 330 MB to spare:
footprint = Placement.Footprint(blocks: [100000000, 100000000, 100000000, 100000000, 100000000], table: 40000000, head: 30000000, tied: false)
n = Placement.fit(footprint, Placement.budget(400000000, 70000000, none)) # 3: 30 + 3 * 100 MB
m = try Qwen3.open(dir, backend, weights, some(n))Qwen3.layers_that_fit(dir, backend, weights, max_device_bytes, context, reserve) does it for a Qwen3 folder (or GGUF) on a Vulkan device: it reads the free memory of the device (Tensor.device_memory), takes reserve bytes off it (256 MB by default, for the compute buffers) and max_device_bytes as a cap when it is some, counts the KV cache of context tokens (2048 by default, F32) for each block, and answers some(n), the layers_on_device that fills the card; none on any other backend. Qwen3.layers_within(c, config, weights, budget, context) is the same for a budget you give. With weights: BF16 on ggml the matrices are F16 (see the hub page), so the budget is the one of F16. The tied embedding and head share their stored weight when both are on the device. Both take kv: Placement.Kv.Host as a last argument when the cache is kept in host memory, and then count none of it on the card (the step of the prompt still makes its cache there first, so keep room for it in reserve). The count is a reading of the moment, not a reservation. The tools take the cap from AGENTICA_ML_MAX_DEVICE_BYTES (bench_qwen.agc, with AGENTICA_ML_LAYERS_ON_DEVICE as the other way to choose).
n = Qwen3.layers_that_fit(dir, backend, weights, some(4000000000)).unwrap!
m = Qwen3.open(dir, backend, weights, n).unwrap!Qwen3.close_model(m)frees the weights; the logits belong to the caller (Lift.close).qwen_checkpeaks at 3.7 GB on ggml CPU and 1.5 GB on Vulkan, where the weights live in device memory.- A
model_typeother thanqwen3,qwen2orllama, an activation other thansilu,attention_bias: true,mlp_bias: true,rope_scaling,use_sliding_window: true(asliding_windowsize with itfalseis ignored, as Hugging Face does), a head count that the key heads do not divide, and a tensor of another shape are errors. Reference and ggml are tested; libtorch is not, and a sharded checkpoint is not tested. On the reference backend attention needsq * kof at most 1,048,576, about 1024 tokens with the causal mask; ggml has no such limit.
Qwen3.5 #
Its tokenizer is Bpe and its chat template Chat.apply("qwen3_5", ...), below. Qwen3_5.open(dir, backend, weights) loads the text model of Qwen/Qwen3.5-0.8B from the folder of its official repository (config.json, and model.safetensors or its index; the weights are bfloat16 on disk and F32 in memory). Qwen3_5.open(dir, backend, weights, layers_on_device) takes the layers_on_device of Qwen3: on a Vulkan device the layers from the nth on, with their keys and recurrent states, run on the CPU and the logits are those of the model with every layer on the device (n of 0, 1, 2 and the number of layers, in the tests); AGENTICA_ML_LAYERS_ON_DEVICE sets it for generate_qwen35_check. Qwen3_5.run(m, rows, last) is the forward over whole sequences, as Qwen3.run, with no cache; Generate of pkg/transformers/generate_qwen35 generates with a cache that holds the keys and values of the full-attention layers and the states of the linear ones.
import Qwen3_5 from "pkg/transformers/qwen3_5"
import Tensor from "pkg/tensor/tensor"
def main() -> Void
m = Qwen3_5.open("Qwen3.5-0.8B", Tensor.Backend.Ggml(Tensor.Device.Cpu)).unwrap!
puts(Tensor.shape(Qwen3_5.run(m, [[760, 6511, 314, 9338, 369]], true).unwrap!))
Qwen3_5.close_model(m)
end- The model is hybrid: by
layer_types, a layer is linear attention (a Gated DeltaNet,Delta.gated_delta_netof nn) or full attention (grouped-query, with an output gate and rotary positions on part of each head, a quarter in 0.8B), followed by a gated MLP. The head is the embedding table.Qwen3_5.openignores the vision tower and the multi-token-prediction head of the checkpoint;Qwen3_5Visionreads the tower (see Images below). - Qwen3.8-27B (
Qwen/Qwen3.8-27B) is aqwen3_5checkpoint at another size, andQwen3_5.openreads it the same way. Its config adds fields that Hugging Face'sQwen3_5code does not read, and neither does this loader:output_gate_type(swish; the attention gate stays the sigmoid), the multi-token-prediction fields,full_attention_intervalbesidelayer_types, andmamba_ssm_dtype. The other Qwen3.8 models are notqwen3_5: Qwen3.8-Flash-Next isqwen4_exp(ml#436). - The norms of Qwen3.5 scale by
1 + weight; the loader adds the 1. OnlyF32weights are loaded, a batch is unrolled row by row in the graph, and the model cannot be fine-tuned withtrain/. - Against Hugging Face's
Qwen3_5ForCausalLMinfloat32on ggml CPU, over five prompts of 5 to 50 tokens, the largest gap of a logit is 2.0e-5 (5.5e-5 on Vulkan withvulkan_fp16off) and the five largest logits of every position are the same ids. A tiny random model is tested on the reference and ggml. - Generation:
Generate.open(m)ofpkg/transformers/generate_qwen35is the generator of a Qwen3.5 model, withgenerate,step,step_logits,step_top,finishandcloseas in Generation. The cache of a full-attention layer is the padded KV cache described there; a linear-attention layer keeps its two states (the last rows of the convolution's input and the recurrent state), which do not grow. Generate.open(m, usable)is the one of Qwen3 above. The embedding of Qwen3.5 has more rows than its tokenizer has tokens (248,320 and 248,070 in 0.8B), and the ids in between have no text, so a caller with a tokenizer passes its token count (Generate.open(m, tok.pieces.size)) and the sampler never gives an id thatBpe.decoderejects. The default 0 is Hugging Face's, no mask.- Against Hugging Face's greedy
generateforQwen/Qwen3.5-0.8Binfloat32, the 24 new ids of each of six prompts (5 to 375 tokens) are equal on ggml CPU and on Vulkan (withvulkan_fp16off), at 8 to 9 tokens per second after the prompt (7.8 on CPU, 8.7 on Vulkan,benchmarks/README.md). - A
model_typeother thanqwen3_5, an activation other thansilu,attention_bias: true, arope_typeother thandefaultand a layer type other thanlinear_attentionandfull_attentionare errors.
Images with Qwen3.5 #
Qwen3_5Vision.open(dir, backend) loads the vision tower of the same folder, and Qwen3_5Vision.encode(v, patches, height, width) turns the patches of one image (Vision.patches, height and width in patches) into its features, one row for each merge by merge square of patches (Qwen3_5Vision.merge(v), 2 in the checkpoint). Chat.IMAGE in the content of a user or assistant message is where the image goes: the template writes <|vision_start|><|image_pad|><|vision_end|>, and any content that holds that text has an image, whoever wrote it (a system message cannot hold one: it is an error). The qwen2 and qwen3 templates have no images, and write the same text as the tags it is. The tokenizer makes one <|image_pad|> of it, which Mrope.expand(ids, pad, grids, merge) repeats once for each token of its grid (height / merge * width / merge), and Generate.generate(g, ids, n, stop, none, some(sight)) splices the features in at those ids, with the M-RoPE positions of Hugging Face's get_rope_index (Mrope.layout). A prompt with several images takes one Mrope.Grid for each, in the order of the pads, and the rows of all their features in one tensor (features of the Sight).
backend = Tensor.Backend.Ggml(Tensor.Device.Cpu)
dir = "Qwen3.5-0.8B"
tok = Bpe.open("#{dir}/tokenizer.json").unwrap!
image_token = Qwen3_5.image_token(dir).unwrap!
vision = Qwen3_5Vision.open(dir, backend).unwrap!
merge = Qwen3_5Vision.merge(vision)
steps = [Vision.Step.SmartResize(32, 65536, 16777216, Vision.Kernel.Cubic)]
srgb = Image.colourspace(Image.load("photo.jpg").unwrap!, Image.Space.Srgb).unwrap!
x = Vision.normalize(Vision.to_tensor(Vision.apply(srgb, steps).unwrap!, backend).unwrap!, [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]).unwrap!
patches = Vision.patches(x, 16, merge).unwrap!
grid = Mrope.Grid(height: Tensor.shape(x)[1] / 16, width: Tensor.shape(x)[2] / 16)
features = Qwen3_5Vision.encode(vision, patches, grid.height, grid.width).unwrap!
Lift.close([patches])
Qwen3_5Vision.close_model(vision)
m = Qwen3_5.open(dir, backend).unwrap!
g = Generate.open(m, tok.pieces.size).unwrap!
text = Chat.apply("qwen3_5", [Chat.Message(role: "user", content: Chat.IMAGE + "What is in this picture?")]).unwrap!
ids = Mrope.expand(Bpe.encode(tok, text).unwrap!, image_token, [grid], merge).unwrap!
layout = Mrope.layout(ids, image_token, [grid], merge).unwrap!
sight = KvDecoder.Sight(features: features, image_token: image_token, layout: layout)
made = Generate.generate(g, ids, 64, [248046, 248044], none, some(sight)).unwrap!
puts(Bpe.decode(tok, made).unwrap!)
Generate.close(g)
Qwen3_5.close_model(m)
Lift.close([features])- Close the tower before opening the text model (
Qwen3_5.open) and the two never share the memory: the 0.8B model fits in 5 GB this way on CPU and on Vulkan.Qwen3_5.image_token(dir)reads the id fromconfig.json; the runnable path of this fragment, with its imports, ischeckofvision/test/qwen35_image_hf_test.agc. smart_resizebounds the number of image tokens (max_pixels / 1024, 16,384 at the checkpoint's own bounds): pass smallermin_pixelsandmax_pixelstoSmartResizefor a short prompt. A picture with an alpha band is an error inVision.patches: flatten it first.- Against Hugging Face's
Qwen3_5ForConditionalGenerationinfloat32on the realQwen/Qwen3.5-0.8B, for three pictures (two shrunk, one enlarged) given as the 8-bit crops that Hugging Face's image processor made, the prompt ids (75 to 90 tokens) are the ones of its processor and chat template, and the 24 greedy ids are equal on ggml CPU and on Vulkan. The five largest logits of every step are within 0.005 of Hugging Face's on both (the largest gap measured is 0.0023 on CPU and 0.0021 on Vulkan). Through our own resize (SmartResize) the pixels are up to one 8-bit level from the processor's and the logits up to 0.3 from its own, with the same ids: that gap comes from the pixels, not from the model. - Video and the numbered images of the chat template's
add_vision_idare not supported.
SmolVLM #
SmolVlmVision.open(dir, backend) loads the vision tower and the connector of SmolVLM (Idefics3ForConditionalGeneration, such as HuggingFaceTB/SmolVLM-256M-Instruct) from the folder of its official repository (config.json and model.safetensors; the weights are bfloat16 on disk and F32 in memory). SmolVlmVision.encode(v, tiles) turns tiles of 512 by 512 pixels, as the image processor normalizes them (Vision.to_tensor, then Vision.normalize with the mean and std 0.5), into the rows that the text model reads at the image tokens: [tiles, 64, 576] in the 256M model, 64 rows for each tile. The caller passes whole tiles only: no padded tile and none of the all-zero tiles that Hugging Face's processor pads a batch with (its model drops them, this one would compute them); padded tiles and the patch mask come with the processor. Only the 256M and 500M models (tiles of 512 pixels, a side of 32 patches, a pixel shuffle by 4) are checked against Hugging Face.
backend = Tensor.Backend.Ggml(Tensor.Device.Cpu)
v = SmolVlmVision.open("SmolVLM-256M-Instruct", backend).unwrap!
image = Image.colourspace(Image.load("tile.png").unwrap!, Image.Space.Srgb).unwrap!
tile = Vision.normalize(Vision.to_tensor(image, backend).unwrap!, [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]).unwrap!
rows = SmolVlmVision.encode(v, tile).unwrap!
# rows is [1, 64, 576]
Lift.close([tile, rows])
SmolVlmVision.close_model(v)To describe an image, cut it into tiles, put the tiles through the tower one at a time (so one tile of the tower is in memory), close the tower, and generate with the features spliced in at the <image> ids. The 256M model fits in 5 GB this way. This is the path of vision/test/smolvlm_chat_hf_test.agc, whose greedy ids are Hugging Face's generate ones (24 and 12 new ids, two images, on Vulkan):
backend = Tensor.Backend.Ggml(Tensor.Device.Cpu)
dir = "SmolVLM-256M-Instruct"
tok = Bpe.open("#{dir}/tokenizer.json").unwrap!
made = Native.arena do
image = Image.colourspace(Image.load("photo.jpg").unwrap!, Image.Space.Srgb).unwrap!
Vision.idefics3_tiles(image, backend)
end
tiles = made.unwrap!
v = SmolVlmVision.open(dir, backend).unwrap!
values: List[Tensor.Values] = []
width = 0
for t in tiles.tiles
x = Vision.normalize(t, [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]).unwrap!
rows = SmolVlmVision.encode(v, x).unwrap!
width = Tensor.shape(rows)[2]
values = values + Tensor.to_list(rows).unwrap!
Lift.close([x, rows])
end
SmolVlmVision.close_model(v)
features = Tensor.from_list(values, [values.size / width, width], Tensor.Dtype.F32, backend).unwrap!
question = Chat.SMOLVLM_IMAGE + "What is in this picture?"
text = Chat.apply("idefics3", [Chat.Message(role: "user", content: question)]).unwrap!
grids = [SmolVlmPrompt.Grid(rows: tiles.rows, cols: tiles.cols)]
ids = SmolVlmPrompt.expand(Bpe.encode(tok, text).unwrap!, SmolVlmPrompt.open(dir).unwrap!, grids).unwrap!
sight = KvDecoder.plain_sight(features, Qwen3.image_token(dir).unwrap!, ids)
m = Qwen3.open_idefics3(dir, backend).unwrap!
g = Generate.open(m).unwrap!
made = Generate.generate(g, ids, 64, [2], none, some(sight)).unwrap!
puts(Bpe.decode(tok, made).unwrap!)
Generate.close(g)
Qwen3.close_model(m)
Lift.close([features])- The stop id 2 is
<|im_end|>, which the checkpoint'sgeneratestops at (the model writes<end_of_utterance>before it). A photo that makes 3 by 4 tiles is 13 frames and some 880 ids of prompt; the CPU takes a while for that, Vulkan some 15 seconds. - The tower is SigLIP: a patch convolution, learned positions, 12 pre-norm blocks of full attention with an MLP of
gelu_pytorch_tanh, and a final layer norm; the connector joins each 4 by 4 square of patches (scale_factor) into one vector with a pixel shuffle and takes it to the text width with one linear layer. Every tile is a whole square ofimage_sizebyimage_sizepixels: a tile of another size is an error. - Against Hugging Face's
Idefics3ForConditionalGeneration.get_image_featuresinfloat32on the realSmolVLM-256M-Instruct, for two tiles, the rows (the mean, the mean of the absolute values and 505 values of each tile) are within 5.3e-5 on ggml CPU and 1.1e-4 on Vulkan, and a tiny random model is within 2e-5 on the reference and 1e-4 on ggml (transformers/DESIGN.md). SmolVlmPrompt.expand(ids, prompt, grids)writes the prompt as Hugging Face'sIdefics3Processordoes: each<image>id ofids(the template writes one for each image) becomes the ids of its tiles, row by row (<fake_token_around_image>,<row_r_col_c>and 64<image>ids, a newline after each row), then its global image (<fake_token_around_image>,<global-img>, 64<image>ids and<fake_token_around_image>);gridsis therowsandcolsof each image (Vision.idefics3_tiles; 1 to 6 each, anddo_image_splitting: falseis not supported).SmolVlmPrompt.open(dir)reads the ids fromtokenizer.json(the added tokens and the entries of the two newlines) andprocessor_config.jsonof the folder. The expanded ids are the processor's on prompts with one and two images.Bpe.open("SmolVLM-256M-Instruct/tokenizer.json")is the tokenizer of the text around them (the pre-tokenizer of SmolLM2: each digit is a piece, then the GPT-2 split), and gives<image>as one id; its ids and text are those oftokenizerson a tiny tokenizer and on the real one.Chat.apply("idefics3", messages)is its chat template:User: ...<end_of_utterance>andAssistant:at the end, withChat.SMOLVLM_IMAGE(<image>) in thecontentwhere an image goes (at the start, the text follows the colon with no space, as Hugging Face's list of parts writes it). The features for the splice are those ofSmolVlmVision.encodeon each tile, in the order of the ids.Nn.Activation.GeluTanhis the tanh GELU as ops that ggml compiles, for a checkpoint withgelu_pytorch_tanhthat runs on ggml (Nn.Activation.Geluis the same function, not lowered to ggml yet).
Qwen4-Exp #
Qwen4Exp.open(dir, backend) (pkg/transformers/qwen4_exp) loads the text model of a Qwen4-Exp checkpoint (model_type: "qwen4_exp", the architecture of Qwen/Qwen3.8-Flash-Next) from the folder of its official repository (config.json, and model.safetensors or its index; F32 in memory). Qwen4Exp.run(m, rows, last) is the forward over whole sequences, as Qwen3_5.run is, with no cache, and Qwen4Exp.close_model(m) frees the weights; Generate of pkg/transformers/generate_qwen4_exp generates with a cache.
import Qwen4Exp from "pkg/transformers/qwen4_exp"
import Tensor from "pkg/tensor/tensor"
def main() -> Void
m = Qwen4Exp.open("tiny-qwen4-exp", Tensor.Backend.Ggml(Tensor.Device.Cpu)).unwrap!
puts(Tensor.shape(Qwen4Exp.run(m, [[3, 1, 4, 1, 5]], true).unwrap!))
Qwen4Exp.close_model(m)
end- The residual stream is
hc_countcopies of the hidden state (Hyperof nn). Each layer mixes the copies into the input of its mixer and injects the answer back, then does the same around a mixture of experts (Moe, with a sigmoid-gated shared expert). A last mix gives the hidden state of the head. - The mixer is a Gated DeltaNet (
linear_attention; its gated norm gates bysigmoidwithoutput_gate_type: "sigmoid") or a gated attention whose keys QSA picks (Qsa;full_attentionin a checkpoint reads asindexed_attention, as in Hugging Face). The layers ofple_layer_idsfirst add the per-layer embedding of the hashed n-grams of the tokens (NGram,Ple). - The loader stacks the experts (one tensor per expert in the file) and joins the
split_ngram_partsshards of each n-gram table. The n-gram table of Qwen3.8-Flash-Next is about 90 GiB, so this release checks the model only on tiny random checkpoints. - Against Hugging Face's
Qwen4ExpForCausalLM(transformers 5.22.2,float32) on a tiny random model (4 layers, PLE on 2, QSA dropping keys, 2 streams, 4 experts), the logits of every position of two prompts with EOS inside match on ggml CPU, XLA and libtorch (1e-3), and those of the first prompt on the reference (1e-4). - Generation:
Generate.open(m)ofpkg/transformers/generate_qwen4_expis the generator of a Qwen4-Exp model, withgenerate,step,step_logits,step_top,finishandcloseas in Generation. The cache of an indexed layer is the padded KV cache described there plus the raw keys of its QSA indexer (F32); a linear layer keeps the two states of its delta net, and a PLE layer the last rows of the input of its dilated convolution, which do not grow. The host hashes the n-grams of each step from the ids fed before. The 14 greedy ids and the logits of each step of Hugging Face'sgenerateon the tiny model match on ggml CPU (1e-3); the reference is not run, as the model in Agentica is too slow for a test of 14 steps. - The rules of Hugging Face's
validate_architectureare errors (QSA fields, PLE only on linear layers,hc_countof 2 or more, the experts), and so are amodel_typeother thanqwen4_exp, an activation other thansiluand arope_typeother thandefault. A config reads with Hugging Face's defaults:layer_typesfromfull_attention_interval, expert sizes of 512, noindexer_*fields when no layer is indexed, and n-gram shards of any sizes. The vision tower and the multi-token-prediction layers are not read, and the model cannot be fine-tuned withtrain/.
Granite MoE #
GraniteMoe.open(dir, backend, weights, layers_on_device) loads IBM Granite MoE (granitemoe, the 1B-A400M model ibm-granite/granite-3.1-1b-a400m-instruct) from the folder of its official repository (config.json, and model.safetensors or its index; the weights are bfloat16 on disk and F32 in memory, 5.3 GB for the 1B-A400M model). GraniteMoe.run(m, rows, last) is the forward over whole sequences, as Qwen3.run, with no cache; Generate of pkg/transformers/generate_granite_moe generates with a KV cache, as in Generation. There is no tokenizer or chat template for it yet, so a caller passes token ids. layers_on_device is that of Qwen3: on a Vulkan device the layers from the nth on, with their experts and keys, run on the CPU, and the logits are those of the model with every layer on the device (n of 0, 1 and the number of layers, in the tests); AGENTICA_ML_LAYERS_ON_DEVICE sets it for generate_granite_moe_check.
import GraniteMoe from "pkg/transformers/granite_moe"
import Tensor from "pkg/tensor/tensor"
def main() -> Void
m = GraniteMoe.open("granite-3.1-1b-a400m-instruct", Tensor.Backend.Ggml(Tensor.Device.Cpu)).unwrap!
puts(Tensor.shape(GraniteMoe.run(m, [[1318, 203, 35]], true).unwrap!))
GraniteMoe.close_model(m)
end- Each block is attention (grouped-query, rotary positions with
rope_theta, the scores scaled byattention_multiplier) and a mixture of experts (Moe.moeof nn): the router picksnum_experts_per_tokofnum_local_expertsexperts for each token, and their gated MLPs are added with the softmax of the picked scores as gates. The embeddings are multiplied byembedding_multiplier, each of the two branches of a block byresidual_multiplierbefore it is added, and the logits are divided bylogits_scaling. The head is the embedding table whentie_word_embeddingsis true, elselm_head.weight. - Only
F32weights are loaded, and the model cannot be fine-tuned withtrain/. The experts of a layer are two stacked tensors, so the model needs about 6 GB of memory on the CPU. - Against Hugging Face's
GraniteMoeForCausalLMinfloat32on the real checkpoint, over five prompts of 5 to 217 tokens, the largest gap of a logit is 3.7e-5 on ggml CPU and 9.3e-5 on Vulkan withvulkan_fp16off, and the five largest logits of every position are the same ids. Withvulkan_fp16on (the default on Vulkan) the largest gap is 0.34, and the fifth largest id of two positions differs. CallTensor.vulkan_fp16(false)before the first ggml call for exact logits. A tiny random model is tested on the reference and ggml. - Against Hugging Face's greedy
generatefor the same checkpoint infloat32, the 24 new ids of each of five prompts (5 to 217 tokens) are equal on ggml CPU, at about 17 tokens per second after the prompt and 5.6 GB at the peak. The KV cache isF32; a step's logits are 8.2e-5 from Hugging Face's. - A
model_typeother thangranitemoe, an activation other thansilu,attention_bias: trueandrope_scalingare errors.
LFM3 #
Lfm3.open(dir, backend, weights, layers_on_device) loads Liquid AI's LFM3 (lfm3, LiquidAI/LFM3-1.7B) from the folder of its official repository (config.json, and model.safetensors or its index; the weights are bfloat16 on disk, 3.4 GB, and F32 in memory, or F16 with weights: Dtype.F16 on ggml). Lfm3.run(m, rows, last) is the forward over whole sequences, as Qwen3.run is, so its cost grows with the square of the length; Generate of pkg/transformers/generate_lfm3 generates with a cache, below. Its tokenizer is Bpe and its chat template Chat.apply("lfm3", ...), both below: the tokenizer has no normalizer, cuts digits in groups of up to three and takes a piece that is a token as it is (ignore_merges), and gives the ids of Hugging Face tokenizers on tokenizer.json (<|startoftext|> is 124894, <|im_end|> 124900). The weights are Liquid AI's, under the LFM Open License v1.0. Nothing of LFM3 is redistributed here: the tests use random weights, and the scripts that make their goldens import Liquid AI's code from a local download, whose license the person running them accepts. layers_on_device is that of Qwen3: on a Vulkan device the layers from the nth on, with their convolution states and keys, run on the CPU, and the logits are those of the model with every layer on the device (n of 0, 1, 2 and the number of layers, in the tests); AGENTICA_ML_LAYERS_ON_DEVICE sets it for generate_lfm3_check.
import Lfm3 from "pkg/transformers/lfm3"
import Tensor from "pkg/tensor/tensor"
def main() -> Void
m = Lfm3.open("LFM3-1.7B", Tensor.Backend.Ggml(Tensor.Device.Cpu), Tensor.Dtype.F16).unwrap!
puts(Tensor.shape(Lfm3.run(m, [[1, 2, 3]], true).unwrap!))
Lfm3.close_model(m)
end- A layer is a gated short convolution (
ShortConvof nn: 7 taps, with no bias), a sliding-window attention (the last 256 tokens, rotated by theta 1e4) or a global one (theta 1e6, half of each head rotated), bylayer_types, then a SwiGLU MLP. Each of the two branches is normed before and after, and the attention has a gate of one number per head. - Against the official code (
trust_remote_code, infloat32layer by layer from thebfloat16file) on the real checkpoint, over five prompts of 5 to 375 tokens (the last is past the window), the largest gap of a logit withF16weights is 4.7e-5 on ggml CPU and 1.7e-4 on Vulkan withvulkan_fp16off, and the five largest logits of every position are the same ids. The CPU run holds 3.9 GB at the peak.F16rounds each weight once at load: abfloat16value from 6.1e-5 to 65504 is exact, a larger one is an error that names the tensor, a smaller one keeps fewer digits and one under 3e-8 becomes 0 (in the checkpoint, 4.6 million of the 1.73 billion weights of theF16matrices are not 0 and under 6.1e-5, and 125,000 of them are under 3e-8). - Generation:
Generate.open(m, usable)ofpkg/transformers/generate_lfm3is the generator of an LFM3 model, withgenerate,step,step_logits,step_top,finishandcloseas in Generation. The cache holds the keys and values of the 11 attention layers (padded to a capacity of 8, 16, 32 and so on,F16on ggml; a sliding layer keeps every row and hides the ones past its window with its mask) and the last 6 rows of the input of each of the 13 convolution layers, which do not grow. The embedding has 128,000 rows and the tokenizer 125,033 tokens, so a caller with a tokenizer passes its token count (Generate.open(m, tok.pieces.size)). - Against the official
generate(float32layer by layer from thebfloat16file) withF16weights, the 24 new ids of each of six prompts (5 to 601 tokens, two past the window) are equal on ggml CPU and on Vulkan withvulkan_fp16off. The logits at the five largest ids are within 3.6e-3 with theF16cache and 2.9e-5 with anF32one, so the cache is the gap. A tiny random model with a window of 4 is tested on the reference and ggml. The cost of a prompt grows with the square of its length (its masks and scores are dense), so the practical context is a few thousand tokens and not the 256K of the config; nothing past 601 tokens was measured. Speed is inbenchmarks/. - A
model_typeother thanlfm3,conv_bias: true,use_sandwich_norm: false, arope_typeother thandefaultand a layer type other thanconv,full_attentionandsliding_attentionare errors, and so areweightsother thanF32andF16. The model cannot be fine-tuned withtrain/.
Llama #
Llama.open(dir, backend, weights, layers_on_device) (pkg/transformers/llama) loads LlamaForCausalLM (model_type: "llama", Llama 3.x and compatible checkpoints) from a Hugging Face folder (config.json, model.safetensors or its index), and LlamaGguf.open(path, backend, weights, layers_on_device) (pkg/transformers/llama_gguf) loads the same Llama.Llama from a GGUF file (general.architecture: "llama"). Llama.run(m, rows, last) runs the forward pass over sequences, and GenerateLlama (pkg/transformers/generate_llama) generates with a KV cache over KvDecoder.
import GenerateLlama from "pkg/transformers/generate_llama"
import Llama from "pkg/transformers/llama"
import LlamaGguf from "pkg/transformers/llama_gguf"
import Tensor from "pkg/tensor/tensor"
backend = Tensor.Backend.Ggml(Tensor.Device.Cpu)
m = LlamaGguf.open("llama-3.2-1b-instruct.gguf", backend).unwrap!
g = GenerateLlama.open(m).unwrap!
ids = GenerateLlama.generate(g, [128000, 128006, 882, 128007], 16).unwrap!
puts(ids)
GenerateLlama.close(g)
Llama.close_model(m)- Both loaders share
Llama.Llama,Llama.run,Llama.rope_of(standard andllama3scaled RoPE), andGenerateLlama(start,step,step_logits,step_top,step_picks,rollback,finish,generate,generate_speculative,close).LlamaGgufparsesllama.*GGUF metadata (block_count,embedding_length,feed_forward_length,attention.head_count, optionalattention.head_count_kvandattention.key_length,context_length,attention.layer_norm_rms_epsilonandrope.freq_base) and loadstoken_embd.weight,output_norm.weight, optionaloutput.weight(tied when absent), andblk.{i}.*weights (with optional biases, no query/key norms). It reads the layout of llama.cpp's converter: the rows of each query and key head are reordered, so the rope turns the columns2iand2i + 1together, and allama3model carriesrope_freqs.weight(the divisor of each frequency) in place of therope_scalingkeys. Allama.rope.scaling.typeother thannoneordefaultis an error (linearandyarnare not supported), and so is allama.rope.dimension_countother than the head size. Chat.apply("llama", messages, add_generation_prompt)formats Llama 3.x conversations (<|begin_of_text|>,<|start_header_id|>role<|end_header_id|>\n\ncontent<|eot_id|>, and trailing<|start_header_id|>assistant<|end_header_id|>\n\nwhenadd_generation_promptis true).Bpe(pkg/transformers/tokenizer/bpe) reads Llama 3 tiktoken-styletokenizer.jsonfiles (\p{N}{1,3}digit grouping, no normalizer,ignore_merges, and added special tokens).- Synthetic tiny models (unscaled,
llama3-scaled tied, and biased) and GGUF files in llama.cpp's layout are tested against a Python peer on Reference, ggml CPU, and XLA CPU. - Tested checkpoint: Llama 3.2 1B Instruct, from the ungated copies
unsloth/Llama-3.2-1B-Instruct(safetensors, revision5a8abab) andunsloth/Llama-3.2-1B-Instruct-GGUF(Llama-3.2-1B-Instruct-BF16.gguf, revisionb69aef1, sha256f5d05e90d179fa27c01a049be1574a0201bdc09ba0b345eb85e1dbf3b87610f3).tools/generate_llama_check.agccompares 24 greedy ids on five prompts (one of 602 tokens) with Hugging Face'sLlamaForCausalLMinfloat32(test/fixtures/llama32_1b_check_golden.json, made bytest/generate_llama_check_golden.py). Withweights: F16, the ids are equal on ggml CPU and Vulkan, from the safetensors and from the GGUF file, and the logits at Hugging Face's five largest ids differ by at most 0.011. Thellama3scaling moves 17 of the 32 rotary frequencies, as in Hugging Face; with the scaling off, the ids stay the same but the logits move by 0.07 to 1.3, so the check fails. The run is manual: the checkpoint is not in CI.weights: BF16gives the same ids and gaps (ggml holds its matrices asF16), with a peak of 3.1 GB on the CPU.