14. Inference engines
Why this layer exists
Chapter 3 counted the arithmetic of one token through a model: every weight in the matrices the token is multiplied by takes part in exactly one multiply-add, FLOPs for such weights, which leaves out the embedding table, since a lookup copies one row and multiplies nothing. It also noted that every one of those weights has to be read. Take a model with such weights stored at bytes each, larger than any cache, on a processor that can move bytes per second from memory and do FLOPs per second. Generating one token for one sequence moves bytes and does FLOPs, so it takes at least
seconds. The memory term is the larger one exactly when , that is when
is a property of the hardware, the FLOPs it can do per byte it reads; is a property of decoding, the FLOPs a weight gets per byte it costs: 1 FLOP per byte at f16 (), 0.5 at f32. When the inequality holds, the arithmetic units wait for memory and the bound on single-sequence decoding speed is
set by the bytes of the weights and nothing else. The KV cache (chapter 12) adds its own bytes to each step, for a cache of bytes, which matters at long contexts; the weights are the fixed part. Compare with from your own machines’ spec sheets; what follows applies whenever the inequality holds.
here is the weights one token is multiplied by, not the parameter count in a model’s name. For a dense model the two are nearly the same. For a mixture-of-experts model (chapter 11) they are not: straylight’s ornith-1.5-35b-a3b stores about 35 billion parameters and multiplies each token by about 3 billion of them, so its is about 3 billion and its decoding bound about twelve times what the name’s first number predicts, while memory must still hold all 35 billion. The section on mixture of experts below works out what that changes.
The bound has three factors that an engine can change, and each is a llama.cpp feature you configure. (llama.cpp’s options, log lines and internals are described here as of commit da89bb3, 2026-09-29.)
- Fewer bytes per weight, a smaller . This is what a GGUF file’s quantization type chooses:
llama-quantize model-f16.gguf model-Q4_0.gguf Q4_0rewrites the weight matrices in ggml’s Q4_0 format at 4.5 bits per weight instead of 16, andQ8_0,Q4_K_Mand the other types trade size against accuracy differently. - More sequences per weight read. One pass over the weights can serve several sequences at once: the bytes are read once and each weight does a multiply-add for every sequence in the batch. llama-server’s parallel slots (
-np) and its continuous batching exist for this. - Fewer sequential steps of the large model. A small draft model guesses several tokens and the large model checks them all in one pass, which for a dense model costs about one step’s weight traffic. llama-server does this with
--spec-draft-model(-md) naming the draft GGUF and--spec-type draft-simpleselecting a standalone draft model;--spec-draft-n-maxsets how many tokens it drafts per step (default 3).
Chapter 19 builds continuous batching. This chapter builds the other two, as the module tinygpt.engine: symmetric int8 quantization and ggml’s Q4_0 with the bytes of ggml’s reference C; a speculative decoder whose output distribution is provably the large model’s; and measurements of what each costs on the Persuasion model of chapter 11. It then works out what a mixture of experts changes in each of the three, and how to read the name of a model file.
Mechanism
Symmetric int8, one scale per output column
A weight matrix of shape (in, out) computes for each output (chapter 3’s contract, of shape (in,)). Give column its own scale,
with of shape (out,) stored as float32 and of shape (in, out) as int8. Write . By the choice of , , so lies in and fits a signed byte without clipping; the code is never used, which keeps the range symmetric. Rounding to the nearest integer moves by at most , , and multiplying by ,
The bound is attained whenever is exactly halfway between two integers (exercise (b)). An all-zero column would give and a division by zero; the reference gives it , and its codes are all 0.
Why a scale per output column: the scale then factors out of the sum each output computes,
so a kernel can form the dot product with the integer codes and multiply by once per output. A second reason is outliers. A single large weight sets the step for every weight that shares its scale. In a (256, 64) matrix of normal weights with standard deviation 0.02 and one entry set to 1.0, a single scale for the whole tensor has step : 2,466 of the other 16,383 weights round to zero, and the RMS error of the weights outside the outlier’s column is , a ninth of the weights’ own size. With a scale per column the same weights have RMS error ; only the outlier’s column pays. Storage is 1 byte per weight plus 4 bytes per column, bits per weight.
Q4_0: blocks of 32 as ggml stores them
ggml’s Q4_0 goes further in both directions: 4 bits per code, and a scale per block of 32 consecutive weights. The format is block_q4_0 in ggml/src/ggml-common.h,
#define QK4_0 32
typedef struct {
ggml_half d; // delta
uint8_t qs[QK4_0 / 2]; // nibbles / quants
} block_q4_0;
an f16 scale and 16 bytes of packed 4-bit codes: 18 bytes per 32 weights, bits per weight. The rule is quantize_row_q4_0_ref in ggml/src/ggml-quants.c (checked against llama.cpp at commit da89bb3, 2026-09-29). For a block :
- Find , the entry of largest magnitude with its sign kept (the first one, if several tie).
- Set , stored as
f16; set , computed from the float32 before it is rounded (and 0 if ). - Code each entry as , an integer in .
- Pack two codes per byte:
qs[j] = q[j] | q[j + 16] << 4for . The first half of the block goes in the low nibbles, the second half in the high nibbles; neighbours are not paired.
Dequantization is , with f16 widened to float32 (dequantize_row_q4_0).
The code runs over the 16 integers : eight negative values and seven positive. The sign in spends the extra negative value on the largest entry, whatever its sign: , so gets code 0 and is reconstructed as , exactly up to the rounding of . When is positive, is negative and the code order is reversed; nothing else changes.
The error bound. Let . Every entry has , so . Since , the stored value is , rounded to the nearest integer (halves up), as long as the clamp at 15 is inactive. Then and
The clamp is active when , that is : entries of the sign opposite to with magnitude at least . They get , and since ,
one full step. In the Persuasion model’s matrices this happens to 890 of 167,936 weights. Rounding to f16 (10 fraction bits, relative error at most while is a normal f16 number, , so ; a block of smaller weights gets a subnormal with fewer significant bits and a larger relative error) adds at most to either bound. test_q4_round_trip_error_bound checks both on random blocks, and test_q4_clamps_the_opposite_extreme builds the tie : comes first and becomes , , and lands on , code , reconstructed as .
Taking from the float32 rather than the rounded one, and doing the arithmetic in float32, matter only at the edges: in 512 random blocks, computing from the f16 value changed 4 to 15 of the 8,192 bytes over seeds 0 to 15, and float64 arithmetic changed one byte in 32,768 blocks. The reference follows ggml’s order, and test_q4_bytes_match_a_transcription_of_ggml compares it byte for byte against a line-by-line transcription of the C loop.
That match is with the C as written, which rounds twice per entry: once after x*id, once after + 8.5f. A compiler allowed to contract the two into one fused multiply-add rounds once, and an entry whose lies within float32 rounding of an integer can then land on the other side of it. GCC contracts by default in its GNU C modes (-ffp-contract=fast), and ggml is built in one: its CMake sets CMAKE_C_STANDARD 11 and leaves CMake’s C extensions on, so GCC compiles it with -std=gnu11. It contracts whenever the target has an FMA instruction: every AArch64 target, or x86 with -march=native on a CPU that has one. Clang’s default contracts only within one expression, and ggml computes x*id and adds 8.5f in separate statements. ggml’s CMake sets no -ffp-contract and puts its -march flags on the CPU backend, not on ggml-quants.c, so which bytes a given llama-quantize writes at such an entry depends on the compiler and target it was built for. Compiled from ggml’s source on talos (x86-64, with FMA) and run on 2,000,000 random blocks and the boundary block of test_q4_rounds_in_float32_like_ggml, the reference agreed with quantize_q4_0 on every block under gcc -O2 and under clang -O2 -march=native; gcc -O2 -march=native differed on 7 of the random blocks and on the boundary block.
Per-block scales and outliers. The outlier matrix above, quantized to Q4_0 in blocks down each column: the outlier’s block has and a step of 0.125, so all 31 of its neighbours, of size about 0.02, round to 0 and their RMS error is , the size of the weights themselves. Every other block keeps its own small scale: the RMS error everywhere else is , identical to that of the same entries in the matrix without the outlier. An outlier costs its own block.
Which axis. A block shares one scale among 32 weights, so the blocks must run along the axis the kernel sums over for the scale to factor out: with blocks along ,
one multiply by per block per output. ggml stores each weight matrix as rows of the reduction dimension (in ggml_mul_mat, both operands have columns, and each row of the weight holds the weights one output uses), and quantizes row by row, so its blocks run along that axis. quantize_model does the same: a Linear weight (in, out) is quantized along in. An embedding table (rows, width) is quantized along its width, the row a lookup copies, so dequantizing one token’s vector touches only that row’s blocks. The axis is mainly about the arithmetic; accuracy moves little: quantizing the Persuasion model’s Linear weights along the output axis instead gives a perplexity of 21.691 against 21.613.
What a real file does beyond this. llama-quantize leaves one-dimensional tensors (biases, norm weights) unquantized, as quantize_model does. It does not store every matrix in the file’s nominal type: without --pure, a Q4_0 file’s output projection is stored as Q6_K, or Q8_0 when its rows are not a multiple of 256 long (llama_tensor_get_type_impl and tensor_type_fallback in src/llama-quant.cpp), and the GGUF metadata key general.file_type describes “the type of the majority of the tensors”. The k-quants (Q4_K, Q6_K and the rest) group smaller blocks into 256-weight super-blocks and quantize the blocks’ scales themselves (block_q4_K stores 8 scales and 8 minimums in 6 bits each under two f16 super-block scales). And with an importance matrix, --imatrix, made by llama-imatrix from the squared activations of each input dimension accumulated over calibration text, quantize_q4_0 stops using the reference rule: quantize_row_q4_0_impl searches for the scale that minimises a squared reconstruction error weighted, per weight, by that input’s importance times , with the row’s mean square. The block layout stays the same; only the choice of and the codes changes.
What quantization costs
quantize_model returns a copy of the model whose matrices are replaced by their quantize-dequantize round trip, so the unmodified forward pass measures the accuracy of the quantized weights. On the chapter 11 Persuasion model (169,344 parameters, of which 167,936 are in matrices), scored on the same 20,000 held-out tokens train_gpt reported:
| scheme | bytes | held-out nats | perplexity |
|---|---|---|---|
| f32 | 677,376 | 3.0117 | 20.321 |
| int8 per column | 182,528 | 3.0116 | 20.320 |
| Q4_0 | 100,096 | 3.0733 | 21.613 |
int8 costs nothing measurable: its loss is 0.00007 nats lower than f32’s, which is noise in both directions; the relative RMS error of the weights is 0.61%. Q4_0 costs 0.062 nats per token, perplexity up by 6.4%, at 8.5% relative weight error, for a file 15% the size of f32’s (the vectors stay at 4 bytes per entry in all three rows; weight_bytes counts them).
The comparison is sound because it holds everything but the weights fixed. Chapter 4 warned that per-token perplexities compare only between models that share a tokenizer and a test set; the quantized copy shares both with the original, so the difference in nats is the extra surprise per token that the rounding caused, on the same predictions.
Batching
With sequences decoded together, one step still reads each weight once, bytes, but uses it times: by chapter 3’s count, a (B, in) input through an (in, out) weight is multiply-adds, so the step does FLOPs. Its time is at least
and it produces tokens, so
Throughput grows linearly in while the first term is the smaller, and stops growing at the crossover ,
where the step becomes compute-bound. Prompt processing is this regime already: the positions of a prompt go through the model together, sharing every weight read, and that is the difference between the two speeds chapter 12’s timings report.
What does not amortise is per-sequence state. Each sequence attends over its own keys and values, so a step reads bytes for cache sizes , and the cache term grows with . Each slot also holds its cache in memory for the life of the request; chapter 12’s is per sequence. That is the price of -np: slots share the weights but not the cache. (A hybrid model keeps a cache in only some of its layers and a fixed-size state in the others, chapter 15, so its per-slot memory is that state plus a smaller cache; the mixture-of-experts section below works it out for ornith.) For a mixture-of-experts model, the weights a step reads also grow with , since the tokens are routed to different experts; the section on mixture of experts below counts them.
Speculative decoding
A causal model’s forward pass over a sequence gives the next-token distribution at every position (chapter 12’s induction: position ’s state depends only on tokens ). So if someone hands the target model a guessed continuation , one pass over the prefix and the guesses returns distributions: for the slot fills, computed at the last prefix position; for the next slot, computed at ’s position as if were right; and so on to , the distribution after all guesses. In the memory-bound regime that pass costs about one decoding step for a dense model: it reads the weights once for positions. (For a mixture-of-experts model it reads the experts all positions are routed to, which can be several times one step’s; see below.)
The guesses come from a draft model, smaller and cheaper, sharing the target’s tokenizer since both must index the same vocabulary (llama.cpp checks this and refuses otherwise: “draft model vocab type must match target model to use speculation”). For target and draft distributions and at the same slot, both of shape (V,), define the residual, where the target wants more mass than the draft offered,
One step of speculative decoding with drafts:
- Draft: for , compute the draft’s distribution given the prefix and , and draw . These are sequential draft calls.
- Verify: one target call over the prefix and gives .
- Accept left to right: accept with probability . At the first rejection, emit instead a token drawn from , and discard , which were drafted after a token that is not in the output.
- If all are accepted, emit a bonus token drawn from , which the same target call already computed.
The output is distributed exactly as the target. Consider one slot with target distribution and draft distribution , both of shape (V,): the draft draws , and an independent uniform decides acceptance. The emitted token is either because the draft proposed and it was accepted, or because some proposal was rejected and the residual draw gave :
The first term is (multiply into the minimum; where the draft never proposes and the term is 0, which is also ). Summing it over gives the probability of accepting whatever was proposed, so
For the residual’s denominator, use (if both sides are ; otherwise both are 0) and :
So when rejection is possible the second term is , and
When , , every ratio is 1, rejection never happens and the residual is never formed. The accept test samples from using a proposal from ; this is rejection sampling in a modified form that, unlike the textbook version, never throws a draw away without emitting something.
For a whole sequence, argue slot by slot. While have been accepted, the emitted prefix equals the drafted one, so and are the target’s and the draft’s distributions given what has actually been emitted, and the slot lemma says slot ’s token is distributed as . After a rejection the remaining drafts are conditioned on a token that was not emitted, and they are discarded, not examined. The bonus token is drawn from , the target’s distribution given the prefix and all accepted tokens, which is exactly what was emitted. So every emitted token, given everything emitted before it, has the target’s conditional distribution, and by the chain rule (chapter 12) the whole sequence has the target’s joint distribution. Two requirements hide in this argument: each acceptance uniform must be independent of the draft’s draw it judges (a bug that reuses one random number for both fails test_speculative_sequences_follow_the_target), and the draft must be conditioned on its own earlier drafts, or it proposes tokens for the wrong prefix; the distribution is still right in that case, but a perfect draft stops being accepted.
Greedy decoding is the special case of one-hot distributions. probs_fn(model, 0) returns rows with 1 on the argmax. The draft proposes its argmax with ; the ratio is 1 if the target’s argmax is also and 0 otherwise, so a draft token is accepted exactly when the two argmaxes agree, and on rejection the residual is , the target’s one-hot: its argmax. The output is the target’s greedy sequence, token for token (test_greedy_speculative_equals_greedy_target).
What llama.cpp verifies. llama-server’s draft-simple drafts deterministically: the draft’s sampler is a top-k of 10 and it proposes the first candidate, the draft’s most probable token, stopping early if that token’s probability is below --spec-draft-p-min. Verification, common_sampler_sample_and_accept_n in common/sampling.cpp, samples the target’s own token at each drafted position with the request’s full sampler chain, and accepts while the sample equals the draft. With the target’s distribution after that sampler chain, that is the scheme above with a one-hot at : acceptance probability , the chance the target’s sample is ; and on rejection the residual normalised is with removed, for , which is the target’s sample conditioned on not being . The two procedures emit the same distribution; llama.cpp’s needs no draft probabilities at all.
Expected tokens per target call. At one slot the acceptance probability is
the overlap of the two distributions. Assume, as a model, that every slot has the same independently. The number of accepted drafts in a step is at least exactly when the first are all accepted, for . Every step emits tokens: the accepted drafts plus one more, the replacement if some draft was rejected or the bonus if none was. To take the mean of , write it as a sum of indicators,
where is 1 if and 0 otherwise: when , the indicators for are 1 and the rest are 0, so the sum is . The expectation of an indicator is the probability of its event, and expectation is linear, so and
Call the sum . Then , and subtracting, :
which rises with toward and never exceeds . llama-server logs the measured version at the end of each request: draft acceptance = … (… accepted / … generated), mean len = …, where mean len is 1 plus accepted drafts per verification step, this same quantity.
Cost. Each step costs draft calls and one target call. Let be the ratio of a draft call’s time to a target call’s. Measured in units of target calls, a step costs and yields tokens, so the speed relative to plain decoding is
Leviathan, Kalman and Matias’s Theorem 3.8. At it is , above 1 exactly when ; the -th draft adds expected tokens for more time, so once it yields fewer tokens than plain decoding would in the same time (the extra target work of a longer verification pass is ignored here).
Measured on Persuasion with the lab’s draft, a one-layer model of width 32 with 47,488 parameters (28% of the target’s), trained on talos for 600 steps to a held-out loss of 3.7150 nats against the target’s 3.0117 (chapter 11’s model, also talos’s). Over 20 prompts of 8 held-out tokens, 48 new tokens each:
| measured | tokens/call, | |||
|---|---|---|---|---|
| greedy, predicted | 0.290 | 1.290 | 1.373 | 1.405 |
| greedy, measured | 1.255 | 1.341 | 1.397 | |
| temperature 1, predicted | 0.520 | 1.520 | 1.791 | 2.005 |
| temperature 1, measured | 1.500 | 1.708 | 1.955 |
Here is averaged over the positions of the target’s own output: for greedy decoding, how often the argmaxes agree; at temperature 1, the overlap of the full distributions. The geometric model predicts the measured rates to within 0.09. Sampling at temperature 1 accepts more than greedy decoding does, because a greedy draft token needs the argmaxes to agree exactly, while at temperature 1 partial overlap of two broad distributions counts.
The cost ratio is the problem. A draft forward pass takes 0.47, 0.77 and 1.13 ms at 12, 36 and 60 positions against the target’s 1.07, 1.93 and 3.09 ms, between 0.37 and 0.44: per-call overheads dominate a model this small (chapter 12’s exercise (e) found the same), so a draft with 28% of the parameters costs 40% of the time. With the formula predicts that only temperature 1 at gains (); every greedy setting and every longer draft loses. Timed over the same 20 prompts on talos, plain sampling from the target takes 1.73 s greedy and 1.84 s at temperature 1, and speculative decoding runs at 0.83, 0.70 and 0.43 times that speed greedy for , and 0.92, 0.86 and 0.73 at temperature 1. Even the one predicted gain is a loss (0.92 against 1.07): the model charges nothing for the verification pass’s extra positions or for the work between calls. A weak draft makes each target call yield few extra tokens, and each draft call is not cheap enough to pay for the ones that are rejected. The paper’s own drafts had below 0.05, being a couple of orders of magnitude smaller than their targets; that, together with an well above , is the condition under which -md helps.
What mixture of experts changes
Chapter 11’s mixture-of-experts block replaces each feed-forward sublayer with experts, of which each token uses a few. This section writes for that number, chapter 11’s top-, since here counts drafts. Split a model’s weights into , the shared weights every token is multiplied by (attention, norms, the router, any shared expert, the head), and the experts: MoE layers, each with experts of weights. Then
and the three levers of this chapter’s opening change as follows.
Decoding reads the active weights. One token passes through the shared weights and, in each layer, through its chosen experts; an engine reads nothing else. With every weight stored at bytes, a decoding step moves bytes and does FLOPs, and the argument of the opening gives
in the memory-bound regime. Published active counts, ornith’s included, usually count the embedding table, of which a token reads one row (chapter 3); using them in the bound overstates the bytes by at most one table, 0.5 billion weights for ornith. The model must still be resident in full, since the next token may route to any expert:
with the KV cache. Capacity is set by the total parameters, bandwidth by the active ones. For ornith, from chapter 11’s count of its configuration, the routed experts are weights, of which a token uses , 1.0 billion; with the model card’s “~3B” active, is about 2 billion. At Q4_0’s 4.5 bits per weight, the 35.95 billion stored parameters are 20.2 GB, 18.8 GiB, and a token reads about GB. Straylight has 125 GiB of unified memory, of which about 104 GiB is the GPU’s ceiling (SYSTEM.md), so the whole model fits several times over; and for every 100 GB/s of bandwidth , the bound is about 59 tokens/s where a dense model of 35.95 billion parameters at the same precision would be held to 4.9, a factor of about . A dense model of 3 billion parameters has the same bound and needs a twelfth of the memory; what the MoE buys with its memory is the quality of a larger model, not speed.
Ornith’s is also smaller than chapter 12’s formula would make it, because ornith is a hybrid (chapter 15): its config.json makes 30 of its 40 layers linear-attention recurrences (Gated DeltaNet), each keeping a fixed-size state per sequence, and only every fourth layer full attention, with 2 key-value heads of width 256 (num_key_value_heads, head_dim). In an f16 cache, llama-server’s default type, a position then costs bytes, against for chapter 12’s model of the same depth and width, and 640 MiB at 32,768 positions. The recurrent layers add about 63 MiB of f32 state per sequence whatever its length (chapter 15 derives the figure from llama.cpp’s sizes at da89bb3). So at 32,768 positions a decoding step reads about 1.69 GB of Q4_0 weights, 0.67 GB of cache and 0.07 GB of state, 2.42 GB in all, 1.44 times its weight bytes; had all 40 layers been full attention with the same heads, the cache alone would be 2.68 GB and the step 2.59 times. The long-context term that dominates a transformer’s step grows here a quarter as fast, and a slot’s memory is mostly fixed in advance.
A batch reads the union of its experts. tokens decoded together share one read of , as in the batching section, but each is routed on its own, so a step reads every expert that any of them chose. Count the distinct experts one layer reads. Suppose each token’s experts are a uniformly random -subset of the , independently across tokens. For one expert , one token avoids it with probability (the subsets without over all subsets), and all tokens avoid it with probability by independence. The number of distinct experts is , and linearity of expectation over the indicators gives
For this is . For small it is close to : expanding, , so , and overlaps are rare while . As grows it approaches : every expert is read. For ornith, and :
| tokens per step | distinct experts per layer, | as a share of |
|---|---|---|
| 1 | 8.00 | 1.000 |
| 2 | 15.75 | 0.984 |
| 4 | 30.53 | 0.954 |
| 8 | 57.42 | 0.897 |
| 16 | 101.96 | 0.797 |
| 64 | 222.44 | 0.434 |
| 256 | 255.92 | 0.125 |
A step of 16 tokens reads 12.75 times the expert weights of a single token’s step, 80% of 16 separate steps’ worth; the shared weights are read once. A step’s weight bytes are , so with ornith’s numbers (, per expert-slot) a step of 16 moves about 4.94 times the bytes of a step of one, where a dense model’s would move the same. Batching still pays, since 16 tokens for about 4.94 steps’ bytes is about 3.2 times the throughput, but far less than the 16 times of the dense bound, and the batch size at which the step turns compute-bound moves up accordingly.
Routing is not uniform in practice, and for tokens that route independently the formula is the worst case. Let expert be chosen by one token with probability , with . The same argument gives . The function is concave on , its second derivative being , so by Jensen’s inequality , and , with equality for uniform . Skewed routing reads fewer distinct experts. The argument assumes that tokens route independently, and dependence can go either way: tokens that tend to share experts read fewer, and tokens that tend to avoid each other’s read more, up to when every token’s experts are disjoint from the others’. Sharing is what has been observed for the consecutive positions of one sequence: the Mixtral paper’s routing analysis (Section 5) reports that “consecutive tokens are often assigned the same experts”, at rates well above those of random assignment in its higher layers. A batch of requests on one topic may share experts too, though that is not measured here. The load-balancing loss of chapter 11 pushes toward the uniform case, the most expensive one for a batch of independently routed tokens.
Speculative verification reads the union too. Verifying drafts is a forward pass over positions, and each routes on its own. With llama-server’s default of 3 drafts, the pass reads the experts of 4 positions: per layer for ornith under uniform routing, and times the bytes of one decoding step. The cost model of the speculative section charged the verification pass as one target step; for this model it is about two, and a draft has to be correspondingly more accurate to pay. Where the positions of one sequence share experts more often than independent choices would, as the Mixtral analysis reports, the pass reads less than this; 1.95 is what independent, uniform routing costs.
Reading a model name
A model file’s name is a compressed configuration, and ggml’s GGUF specification (docs/gguf.md in the ggml repository, as of commit 6af560d, 2026-07-09) gives the convention it follows:
[<Sidecar>-]<BaseName>-<SizeLabel>-<FineTune>-<Version>
-<Encoding>-<Type>-<Shard>.gguf
with every component after the base name optional except the size label and version, which the specification requires for a name to count as following the convention. Read left to right:
- Sidecar:
mmprojfor a multimodal projector, the vision or audio encoder and its projection into the language model (chapter 16), ormtpfor multi-token-prediction heads used as a draft. A sidecar is not a model on its own; it is loaded beside the base model it names. - BaseName: the family and generation, from the file’s
general.basename, such asQwen3orQwen2-VL(VL for vision-language). - SizeLabel:
<expertCount>x<count><scale-prefix>, withK,M,B,TandQfor thousands to quadrillions, fromgeneral.size_label. The older mixture-of-experts form counts experts times expert size,8x7B. The specification allows further-<attribute><count><scale-prefix>pieces, and that is where an active count goes:30B-A3Bis 30 billion parameters of which about 3 billion are active, the and above. The metadata keys[arch].expert_countand[arch].expert_used_counthold and . - FineTune: what the base was tuned for, from
general.finetune:InstructorChatfor chapter 13’s supervised and preference tuning;Thinkingfor a reasoning model, as in Qwen’sQwen3-30B-A3B-Thinking-2507; a name with no fine-tune is usually a base model, pretrained only (chapter 11’strain_gptmakes one). Descriptions of provenance appear here too:Distillmarks a student trained on a larger model’s generated text (chapter 13’s sequence-level distillation), as inDeepSeek-R1-Distill-Qwen-7B, andabliterateda model whose weights were edited to remove the direction in its residual stream that Arditi and colleagues found mediates refusal.uncensoredis a claim about behaviour and names no method. - Version:
v<Major>.<Minor>,v1.0if absent. - Encoding: the quantization, this chapter’s subject.
F16andBF16are 16-bit floats;Q8_0andQ4_0are the block formats derived above, 8.5 and 4.5 bits per weight;Q4_K_Mis a mixture, not one format: llama-quantize stores most matrices asQ4_Kand, in a subset of layers,attn_vandffn_downasQ6_K(llama_tensor_get_type_implinsrc/llama-quant.cpp, as of da89bb3).general.file_typenames the majority type. - Type and Shard:
LoRAfor an adapter (chapter 50) orvocabfor a tokenizer-only file; and00003-of-00009for one file of a model split into several.
The specification says the convention “is not intended to be perfectly parsable in the field”, and it is not a standard names must follow. The names in the reader’s fleet (~/Work/inference/inference/SYSTEM.md) are router aliases, chosen in a preset file, and do not follow it:
ornith-1.5-35b-a3b: family Ornith, version 1.5 (not invform), 35 billion parameters stored, about 3 billion active per token: a mixture-of-experts model whose decoding bound is set by the 3 and whose memory by the 35. No fine-tune is named; the model card describes a model for coding and agentic work, and its template opens a<think>block (chapter 13): a reasoning model. No encoding is named either: the quantization is in the file behind the alias.qwen3-vl-8b-abliterated, served asQ4_K_Mwith an explicitmmproj-url: Qwen3, vision-language, 8 billion parameters (dense: no active count), edited to remove refusals, stored in the Q4_K_M mixture. The vision encoder is a separatemmprojfile, and SYSTEM.md records that the router’s--hf-repodid not attach it, and the preset names it explicitly; chapter 16 traces when-hffinds a projector, and why that record may reflect an older build or the repository’s layout.ggml-large-v3-turbo: not a GGUF name at all. whisper.cpp stores its models in its ownggmlformat asggml-<model>.bin(itsmodels/README.mdlistslarge-v3-turbo, 1.5 GiB);large-v3-turbois OpenAI’s Whisper name, large-v3 with its decoder cut from 32 layers to 4 (OpenAI’s release note, openai/whisper discussion #2363, and the two models’config.jsonfiles), which chapter 16 reads.
Walkthrough
The reference package is py/tinygpt/engine/, two modules re-exported by its __init__.py.
def quantize_int8(w):
"""Symmetric int8 per output column: w (in, out) -> q int8 (in, out), scale float32 (out,)."""
w = np.asarray(w, dtype=np.float64)
amax = np.abs(w).max(axis=0) # (out,)
scale = np.where(amax > 0, amax / 127.0, 1.0).astype(np.float32)
q = np.clip(np.round(w / scale), -127, 127).astype(np.int8)
return q, scale
def dequantize_int8(q, scale):
return q.astype(np.float64) * scale.astype(np.float64)
quantize_int8 takes the maximum absolute value down each column, (out,), and divides by 127, substituting 1 where the column is all zero so the division below is always defined. The scale is rounded to float32, the type it is stored as, before it is used, so the codes are computed with the scale that dequantization will multiply by. np.round rounds halves to even; the bound holds for either convention. The clip is a guard: with the scale defined this way no quotient rounds past 127 in magnitude. When float32 rounds the scale down, the largest quotient is a little above 127 (in 477 of 1,000 columns of normal weights). Rounding to float32 changes the scale by a relative error of at most , so the excess is at most about , and the quotient still rounds to 127. dequantize_int8 broadcasts the (out,) scale over the rows of the (in, out) codes.
def quantize_q4_0(x):
"""Q4_0 along the last axis, blocks of 32: x (..., n) -> d float16 (..., n/32), qs uint8 (..., n/32, 16).
Per block, d = m / -8 where m is the entry of largest magnitude (sign kept), and each entry
stores q = min(15, floor(x/d + 8.5)), so x is approximately (q - 8) d. Two 4-bit q share a
byte: qs[j] = q[j] | q[j + 16] << 4. That is 18 bytes per 32 weights, 4.5 bits per weight.
Arithmetic is float32 and 1/d is taken before d is rounded to float16, as in ggml's
quantize_row_q4_0_ref, so the bytes match that C as written, with x*id and + 8.5f rounded
separately. A build that contracts the two into one fused multiply-add (GCC's default
-ffp-contract=fast in GNU C modes such as ggml's -std=gnu11, on a target with FMA) rounds once and can differ on a rare boundary block.
"""
x = np.asarray(x, dtype=np.float32)
if x.shape[-1] % BLOCK:
raise ValueError(f"last axis {x.shape[-1]} is not a multiple of {BLOCK}")
blocks = x.reshape(*x.shape[:-1], -1, BLOCK) # (..., nb, 32)
idx = np.abs(blocks).argmax(axis=-1)[..., None] # first entry of largest |x|
m = np.take_along_axis(blocks, idx, axis=-1)[..., 0] # (..., nb) signed
d = m / np.float32(-8.0)
inv = np.divide(np.float32(1.0), d, out=np.zeros_like(d), where=d != 0)
q = np.minimum(15, np.floor(blocks * inv[..., None] + np.float32(8.5))).astype(np.uint8)
qs = q[..., :BLOCK // 2] | (q[..., BLOCK // 2:] << 4) # (..., nb, 16)
return d.astype(np.float16), qs
def dequantize_q4_0(d, qs):
q = np.concatenate([qs & 0x0F, qs >> 4], axis=-1).astype(np.float64) # (..., nb, 32)
x = (q - 8.0) * d.astype(np.float64)[..., None]
return x.reshape(*x.shape[:-2], -1) # (..., n)
quantize_q4_0 works on the last axis of an array of any shape. It converts to float32, as ggml quantizes float32 rows, and refuses a last axis that is not a multiple of 32. The reshape splits that axis into (n/32, 32) blocks. argmax of the absolute values returns the first maximum, matching ggml’s strict amax < fabsf(v) scan, and take_along_axis fetches the signed entry. and its inverse stay float32 until the end, and np.divide(..., where=d != 0) leaves the inverse 0 for an all-zero block, whose codes are then all 8 and dequantize to 0. The + 8.5 and floor are ggml’s (int8_t)(x0 + 8.5f): the argument is at least 0.5, and truncation toward zero of a positive number is the floor. The packing slices the block in halves, low nibbles from the first 16 codes and high nibbles from the last 16. dequantize_q4_0 reverses it: qs & 0x0F recovers codes 0 to 15, qs >> 4 codes 16 to 31, concatenated in that order, then and a reshape back to (..., n).
def _roundtrip(w, scheme, axis):
"""Quantize and dequantize w, with int8 scales or Q4 blocks running along axis."""
if scheme == "int8":
wt = np.moveaxis(w, axis, 0) # int8 scales are per column of axis 0
return np.moveaxis(dequantize_int8(*quantize_int8(wt)), 0, axis)
if scheme == "q4_0":
wt = np.moveaxis(w, axis, -1) # Q4 blocks run along the last axis
return np.moveaxis(dequantize_q4_0(*quantize_q4_0(wt)), -1, axis)
raise ValueError(f"unknown scheme {scheme!r}")
def _matrices(model):
"""(parameter, axis) for every matrix: Linear weights (in, out) are quantized along in, the axis
each output sums over; embedding tables (rows, d) along d, the row a lookup returns. An MoE
block's stacked experts (E, in, out) are quantized along axis 1, each expert as its own Linear;
its router stays full precision, as llama-quantize leaves ffn_gate_inp."""
out = [(model.tok, 1)] + ([(model.pos, 1)] if model.pos is not None else [])
for b in model.blocks:
out += [(lin.weight, 0) for lin in (b.attn.query, b.attn.key, b.attn.value, b.attn.proj)]
if b.moe is None:
out += [(b.up.weight, 0), (b.down.weight, 0)]
else:
out += [(b.moe.up, 1), (b.moe.down, 1)]
return out + [(model.head.weight, 0)]
def quantize_model(model, scheme):
"""A copy of model whose matrices are replaced by their quantize-dequantize round trip.
Biases and norm parameters stay as they are."""
new = copy.deepcopy(model) # the same kind of model: a GPT, or an Encoder
for p, axis in _matrices(new):
p.data = _roundtrip(p.data, scheme, axis)
return new
def weight_bytes(model, scheme):
"""Bytes to store the parameters: matrices under scheme ("f32", "int8" or "q4_0"), vectors as f32."""
total = 4 * sum(p.data.size for p in model.parameters())
if scheme == "f32":
return total
if scheme not in ("int8", "q4_0"):
raise ValueError(f"unknown scheme {scheme!r}")
for p, axis in _matrices(model):
n = p.data.size
total -= 4 * n
total += n + 4 * (n // p.data.shape[axis]) if scheme == "int8" else 18 * (n // BLOCK)
return total
_roundtrip moves the quantization axis into place: int8’s scales are per column, so the reduction axis must be axis 0; Q4’s blocks run along the last axis. _matrices lists every matrix it quantizes, with its axis: the token and position tables along axis 1, and along axis 0 the Linear weights of the attention projections, the feed-forward pair and the output head. In a mixture-of-experts block (chapter 11) the feed-forward pair is replaced by the stacked experts up (E, d, 4d) and down (E, 4d, d), along axis 1, so each expert’s matrices are quantized exactly as a Linear’s would be. The router, a (d, E) matrix, is not in the list and stays in full precision, as llama-quantize leaves it: it skips ffn_gate_inp (src/llama-quant.cpp at commit da89bb3, “do not quantize expert gating tensors”), since the router is small and an error in it changes which experts run, not just how precisely they compute. weight_bytes therefore counts every expert, the total parameters and not the active ones, which is what a file stores and memory must hold (the MoE section below), and the router at 4 bytes per entry. test_quantize_model_and_weight_bytes_cover_every_expert checks both, expert by expert. quantize_model deep-copies the model, so the copy is the same kind of model (a GPT, or chapter 15’s Encoder, which has the same tables, blocks and head), then replaces the matrices; the input is never touched, which test_quantized_perplexity_deltas checks by scoring it again afterwards. weight_bytes starts from 4 bytes per parameter and replaces each matrix’s share: for int8, 1 byte per weight and 4 per scale, where the number of scales is the matrix’s size divided by the length of its quantization axis; for Q4_0, 18 bytes per 32 weights.
def probs_fn(model, temperature=1.0):
"""A callable ids -> (len(ids), V): the model's next-token distribution at every position.
temperature 0 gives one-hot rows on the argmax, so greedy decoding is the same algorithm.
ids must fit the model's context; unlike nn.generate, nothing is cropped.
"""
def f(ids):
logits = model(np.array([ids]))
z = logits.data[0]
free_graph(logits)
free_aux(model)
if temperature == 0:
return np.eye(z.shape[-1])[z.argmax(axis=-1)]
return softmax(z / temperature)
return f
probs_fn adapts a model to the interface the decoder needs: a function from a list of token ids to the (len(ids), V) matrix of next-token distributions at every position. It runs chapter 11’s GPT without a cache and frees the graph, as chapter 12’s uncached path did, and an MoE model’s balance-loss graph with chapter 8’s free_aux. At temperature 0 it returns one-hot rows, so greedy decoding needs no separate code path. Any function with the same signature works; the tests pass lookup tables of a bigram-style toy.
def residual(p, q):
"""max(0, p - q), normalized: where the target wants more mass than the draft gave."""
r = np.maximum(p - q, 0.0)
return r / r.sum() if r.sum() > 0 else p # p == q up to rounding: nothing to correct
def speculative_accept(p, q, token, rng):
"""Verify one drafted token (drawn from q) against the target p.
Accept with probability min(1, p[token] / q[token]); otherwise draw from residual(p, q).
Either way the returned token is distributed exactly as p. Returns (token, accepted).
"""
if rng.random() < min(1.0, p[token] / q[token]):
return token, True
return int(rng.choice(len(p), p=residual(p, q))), False
residual is the formula for . A rejection needs , so in exact arithmetic some other token has and the sum is positive; with two floating-point rows that differ only by rounding it can come out 0, and residual then returns itself rather than dividing by zero. speculative_accept draws one uniform and compares it with the ratio; since rng.random() is in , a ratio of at least 1 always accepts. It returns the token and whether it was the draft’s, which the caller needs for its statistics and to know whether to stop.
def speculative_generate(target, draft, prompt, n_new, k, rng):
"""n_new tokens from target's distribution, drafting k at a time with the cheaper draft.
target and draft are probs_fn-style callables, called on at most len(prompt) + n_new ids, which
must therefore fit the models' context. Returns (tokens, stats); stats counts target calls and
drafted / accepted tokens.
"""
ids, out = list(prompt), []
if not ids:
raise ValueError("speculative_generate needs a non-empty prompt")
stats = {"target_calls": 0, "drafted": 0, "accepted": 0}
while len(out) < n_new:
proposal, qs = [], []
for _ in range(min(k, n_new - len(out))): # draft: k cheap sequential steps
q = draft(ids + proposal)[-1]
proposal.append(int(rng.choice(len(q), p=q)))
qs.append(q)
rows = target(ids + proposal) # verify: one call scores them all
ps = rows[len(ids) - 1:] # (len(proposal) + 1, V)
stats["target_calls"] += 1
stats["drafted"] += len(proposal)
for i, t in enumerate(proposal):
tok, ok = speculative_accept(ps[i], qs[i], t, rng)
ids.append(tok)
out.append(tok)
stats["accepted"] += ok
if not ok:
break # later drafts assumed t; discard them
else:
if len(out) < n_new: # all accepted: the target's next row is free
tok = int(rng.choice(ps.shape[-1], p=ps[-1]))
ids.append(tok)
out.append(tok)
return out, stats
Each iteration of the while loop is one step. The draft loop proposes at most tokens, fewer near the end so the output never exceeds n_new; each proposal calls the draft on the prefix plus the proposals so far and keeps the last row, . The target is called once on the prefix plus all proposals. Its rows are indexed by position: row is the distribution for position , so the distribution for the slot right after the prefix is row len(ids) - 1, and ps holds the len(proposal) + 1 rows from there, to . The for loop verifies left to right, appending each emitted token to both ids, the growing prefix, and out; it stops at the first rejection. Python’s for … else runs the else branch only when the loop finished without break, which is exactly the all-accepted case; the bonus draw from ps[-1] happens there if the output still has room.
The decoder recomputes both models over the whole prefix at every call. An engine keeps a KV cache for each (chapter 12): the draft’s cache grows by one position per draft call, the target’s by per verification, and after a rejection at slot both caches must be truncated to the emitted prefix, dropping the keys and values of the discarded drafts. That is what KVCache.truncate is for.
Exercises
(a) Compute the bits per weight of Q4_0 and of Q8_0, and the size of a model with weights stored as f16, Q8_0 and Q4_0, counting every weight in the file’s type.
Answer
Q4_0 is 18 bytes per block of 32: bits per weight, 16 bits of scale spread over 32 weights plus 4 bits of code. block_q8_0 in ggml-common.h is an f16 scale and 32 int8_t codes, 34 bytes per block, bits per weight; its reference quantizer, quantize_row_q8_0_ref, is the symmetric rule of this chapter’s int8 with a scale per block of 32 instead of per column, and codes .
For weights: f16 is bytes, 13.04 GiB; Q8_0 is bytes, 6.93 GiB; Q4_0 is bytes, 3.67 GiB. By the bound at the start of the chapter, the single-sequence decoding limit improves by the same factors, and . A real Q4_0 file is slightly larger, since its output projection is stored at higher precision and its norm vectors in f32.
(b) Prove the int8 bound and find inputs that attain it.
Answer
With , satisfies , so rounding to the nearest integer never needs the clip and ; multiply by . Equality needs exactly halfway between integers. The scale must also be exact, since the reference stores it as float32; a column whose largest magnitude is 127 has exactly:
import numpy as np
from tinygpt.engine import dequantize_int8, quantize_int8
w = np.array([[127.0], [0.5], [2.5], [-1.5], [0.25]])
q, s = quantize_int8(w)
err = np.abs(dequantize_int8(q, s) - w)[:, 0]
print("scale", float(s[0]), "q", q[:, 0].tolist(), "err", err.tolist(), "s/2", float(s[0]) / 2)
scale 1.0 q [127, 0, 2, -2, 0] err [0.0, 0.5, 0.5, 0.5, 0.25] s/2 0.5
0.5, 2.5 and are halfway cases and reach the bound; np.round sends halves to the even neighbour (0, 2, ), but either choice is half a step away. 0.25 is not a halfway case and does not.
(c) Quantize the block , , to Q4_0: find , the codes, and the 16 bytes, and check two of the bytes by hand.
Answer
import numpy as np
from tinygpt.engine import dequantize_q4_0, quantize_q4_0
x = (np.arange(32) - 11) / 16 # -0.6875 ... 1.25; the largest magnitude is +1.25
d, qs = quantize_q4_0(x)
q = np.concatenate([qs[0] & 0x0F, qs[0] >> 4])
print("d =", float(d[0]))
print("q =", q.tolist())
print("bytes:", " ".join(f"{b:02x}" for b in qs[0]))
print("max error", float(np.abs(dequantize_q4_0(d, qs) - x).max()))
d = -0.15625
q = [12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 7, 6, 6, 6, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 1, 1, 0, 0]
bytes: 6c 6c 5c 5b 4b 4a 4a 3a 39 29 28 28 18 17 07 06
max error 0.0625
The largest magnitude is , positive, so , exact in f16, and the codes decrease as increases. . For : , code 12. For : , code 6. Byte 0 is = 0x6c. For : , code 6; for : , code 0, the largest entry at the end of the range; byte 15 is 0x06. The largest error, 0.0625, is below : no entry is near , so the clamp is never reached.
(d) Tabulate the expected tokens per target call for and , and say what the table implies for choosing .
Answer
From :
| 0.3 | 1.390 | 1.425 | 1.429 | 1.429 |
| 0.6 | 1.960 | 2.306 | 2.475 | 2.500 |
| 0.9 | 2.710 | 4.095 | 6.126 | 10.000 |
The -th draft contributes expected tokens and always costs a draft call. At the third draft adds 0.027 tokens and anything beyond buys almost no output for a real cost; at even the eighth adds 0.43. The right is where falls below the draft’s cost ratio , so it grows with and shrinks with . llama-server’s --spec-draft-n-max defaults to 3, and --spec-draft-p-min stops the draft early when its own top token’s probability is below a threshold, which uses the draft’s uncertainty as a stand-in for a low at that position.
(e) Show that a draft equal to the target accepts every token and that a draft whose support is disjoint from the target’s accepts none, and that the output distribution is the target’s in both cases.
Answer
If , the ratio for every proposable , so every draft is accepted and every step emits tokens: and the geometric sum is . The tokens are draws from and the bonus from , so the output is the target’s. test_perfect_draft_needs_few_target_calls sees 12 tokens in 3 calls (5 + 5 + 2) and test_bonus_token_when_every_draft_is_accepted 10 in 2.
If for every , a proposed has positive and therefore : the ratio is 0 and every draft is rejected, , one token per call. The residual is , which equals wherever is positive (there ) and 0 elsewhere, with sum 1: the replacement is a draw from itself. Each step is then one plain target step, wasting draft calls. test_disjoint_draft_accepts_nothing checks the counts (5 calls for 5 tokens, 0 accepted) and that the first two tokens have the target’s joint distribution.
(f) On straylight, run llama-server on the same prompt with and without a draft model, and read the acceptance statistics it reports.
Answer
You need a draft GGUF whose vocabulary matches the target’s (the same tokenizer family, usually a small model of the same series); the server refuses an incompatible one at startup. Straylight’s llama-server already runs as a router near its GPU ceiling (models-max 3, with large models resident), so do not start two more copies of a large target beside it. Run the two configurations one after the other, on one spare port, with the router’s models unloaded or on a machine with room for one target and its draft, differing only in the draft flags:
llama-server -m target.gguf --port 8081 # first run; stop it before the second
llama-server -m target.gguf --port 8081 -md draft.gguf --spec-type draft-simple --spec-draft-n-max 4
Send each the same request with temperature 0 and a fixed n_predict, then again at temperature 1, and keep the responses. Three places report what happened. In the response, timings gains draft_n and draft_n_accepted when drafting ran, beside predicted_per_second. At the end of each request the server log prints a line draft acceptance = A (n accepted / m generated), mean len = L, where A is accepted over drafted and L is 1 plus accepted drafts per verification step, this chapter’s tokens per target call. With --metrics, /metrics exposes the running totals llamacpp:spec_decode_num_draft_tokens_total, …_num_accepted_tokens_total and …_num_drafts_total. Look for three things: whether the greedy outputs of the two runs agree; that mean len and the ratio of the two predicted_per_second values move together as you change the prompt; and whether the speed ratio exceeds 1 at all, which is the question with straylight’s own .
The greedy outputs agree token for token in exact arithmetic, by the argument above, but llama-server’s arithmetic is not exact. The verification pass scores positions in one batch where plain decoding scores one, and the server README warns, under cache_prompt, that “the logits are not guaranteed to be bit-for-bit identical for different batch sizes (prompt processing vs. token generation)”, depending on the backend. Where two tokens’ logits nearly tie, that difference can flip the argmax, and the outputs part from there. At the first differing position, look at the target’s top two logits before suspecting the verification: a near tie there is consistent with this effect.
(g) Simulate ornith’s routing, and , for batches of tokens: count the distinct experts one layer reads when each token picks its uniformly, and when the router prefers expert in proportion to . Compare both with .
Answer
import numpy as np
E, m, trials = 256, 8, 2000
rng = np.random.default_rng(0)
zipf = 1.0 / np.arange(1, E + 1) # a skewed router: expert i preferred as 1/i
def distinct(B, weights=None):
"""Mean number of distinct experts B tokens use, each drawing m distinct experts."""
p = None if weights is None else weights / weights.sum()
return np.mean([len(set(np.concatenate([rng.choice(E, m, replace=False, p=p) for _ in range(B)])))
for _ in range(trials)])
for B in [1, 4, 16, 64]:
formula = E * (1 - (1 - m / E) ** B)
print(f"B={B:2d}: formula {formula:6.2f} uniform {distinct(B):6.2f} skewed {distinct(B, zipf):6.2f}")
B= 1: formula 8.00 uniform 8.00 skewed 8.00
B= 4: formula 30.53 uniform 30.51 skewed 24.99
B=16: formula 101.96 uniform 102.05 skewed 68.52
B=64: formula 222.44 uniform 222.52 skewed 152.34
Run from py/. Uniform routing matches the formula to within the simulation’s noise, and the skewed router reads fewer experts at every : 68.5 instead of 102.0 at , as the concavity argument in the text requires. For a batch, skew is cheaper; the same skew means some experts are rarely trained, the collapse chapter 11’s balance loss exists to prevent. At every router reads exactly . rng.choice with p and replace=False draws the experts one after another, renormalising over those left, so the skewed router’s per-expert probabilities are not exactly proportional to ; the inequality holds for any with .
(h) Parse Mixtral-8x7B-v0.1-KQ2.gguf, Qwen3-30B-A3B-Instruct-v1.0-Q8_0.gguf, mmproj-Qwen2-VL-7B-v1.0-F16.gguf, Qwen3-VL-8B-Instruct-abliterated-v1.0-Q4_K_M.gguf, Grok-100B-v1.0-Q4_0-00003-of-00009.gguf and Ornith-1.5-35B-A3B-Q4_K_M.gguf with the GGUF specification’s validation expression. What does each component tell you, and why does the last fail?
Answer
import re
# The validation expression of ggml's docs/gguf.md, with JavaScript's (?<name> as Python's (?P<name>
GGUF_NAME = re.compile(
r"^(?:(?P<Sidecar>mmproj|mtp)-)?"
r"(?P<BaseName>[A-Za-z0-9\s]*(?:(?:-(?:(?:[A-Za-z\s][A-Za-z0-9\s]*)|(?:[0-9\s]*)))*))-"
r"(?:(?P<SizeLabel>(?:\d+x)?(?:\d+\.)?\d+[A-Za-z](?:-[A-Za-z]+(\d+\.)?\d+[A-Za-z]+)?)"
r"(?:-(?P<FineTune>[A-Za-z0-9\s-]+))?)?-"
r"(?:(?P<Version>v\d+(?:\.\d+)*))(?:-(?P<Encoding>(?!LoRA|vocab)[\w_]+))?"
r"(?:-(?P<Type>LoRA|vocab))?(?:-(?P<Shard>\d{5}-of-\d{5}))?\.gguf$")
names = [
"Mixtral-8x7B-v0.1-KQ2.gguf",
"Qwen3-30B-A3B-Instruct-v1.0-Q8_0.gguf",
"mmproj-Qwen2-VL-7B-v1.0-F16.gguf",
"Qwen3-VL-8B-Instruct-abliterated-v1.0-Q4_K_M.gguf",
"Grok-100B-v1.0-Q4_0-00003-of-00009.gguf",
"Ornith-1.5-35B-A3B-Q4_K_M.gguf",
]
for name in names:
m = GGUF_NAME.match(name)
print(name)
print(" ", {k: v for k, v in m.groupdict().items() if v} if m else "no match")
Mixtral-8x7B-v0.1-KQ2.gguf
{'BaseName': 'Mixtral', 'SizeLabel': '8x7B', 'Version': 'v0.1', 'Encoding': 'KQ2'}
Qwen3-30B-A3B-Instruct-v1.0-Q8_0.gguf
{'BaseName': 'Qwen3', 'SizeLabel': '30B-A3B', 'FineTune': 'Instruct', 'Version': 'v1.0', 'Encoding': 'Q8_0'}
mmproj-Qwen2-VL-7B-v1.0-F16.gguf
{'Sidecar': 'mmproj', 'BaseName': 'Qwen2-VL', 'SizeLabel': '7B', 'Version': 'v1.0', 'Encoding': 'F16'}
Qwen3-VL-8B-Instruct-abliterated-v1.0-Q4_K_M.gguf
{'BaseName': 'Qwen3-VL', 'SizeLabel': '8B', 'FineTune': 'Instruct-abliterated', 'Version': 'v1.0', 'Encoding': 'Q4_K_M'}
Grok-100B-v1.0-Q4_0-00003-of-00009.gguf
{'BaseName': 'Grok', 'SizeLabel': '100B', 'Version': 'v1.0', 'Encoding': 'Q4_0', 'Shard': '00003-of-00009'}
Ornith-1.5-35B-A3B-Q4_K_M.gguf
no match
The first five are two mixture-of-experts models in the two size notations (8 experts of 7B each; 30B total, 3B active), a vision projector that is useless without a Qwen2-VL-7B base, an abliterated vision-language model in the Q4_K_M mixture, and the third of nine files of one model. The expression gives the fine-tune as everything between the size label and the version, Instruct-abliterated: the convention has one fine-tune field, and the provenance words share it. The Ornith name fails because it has no version in v form: 1.5 after the base name is read as part of the base name, and the required -v… never comes, so the expression finds no split. The specification says as much: the convention is for humans at a glance, not a format tools can rely on, and a program that needs the expert counts or the file type reads them from the GGUF metadata ([arch].expert_count, [arch].expert_used_count, general.file_type), as llama.cpp does, not from the file name.
Lab
Implement py/labs/ch14/starter.py: quantize_int8, dequantize_int8, quantize_q4_0, dequantize_q4_0, quantize_model, weight_bytes, residual, speculative_accept and speculative_generate. probs_fn is provided. Run
make lab CH=14 IMPL=mine
until it passes. Read py/labs/ch14/test_lab.py first. The quantization tests pin the int8 bound and per-column scales, Q4_0’s layout and size, ggml’s rule on hand-built blocks (a negative maximum, a positive one, a tie with the clamp), the bytes against a transcription of ggml’s C loop, the axis of every matrix in quantize_model, an MoE model’s every expert included and its router left in full precision, and exact byte counts. The acceptance tests are the two the chapter is about: test_quantized_perplexity_deltas, which requires int8 to move the held-out loss by less than 0.005 nats and Q4_0 by less than 0.1, and more than int8; and test_speculative_sequences_follow_the_target with test_greedy_speculative_equals_greedy_target, which require the speculative output to have the target’s distribution (total variation below 0.03 over all 64 three-token sequences of a toy) and, greedily, to be the target’s own sequence.
Then quantize the Persuasion model and draft for it. Save as /tmp/engine_lab.py:
import math
import pathlib
import sys
import numpy as np
from tinygpt.bpe import BPE
from tinygpt.engine import probs_fn, quantize_model, speculative_generate, weight_bytes
from tinygpt.mlp import Adam
from tinygpt.nn import evaluate, train
from tinygpt.sample import generate
from tinygpt.transformer import GPT, GPTConfig, load
run = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "/tmp/tinygpt-persuasion")
tok, model = BPE.load(run / "tokenizer.json"), load(run / "model.npz")
ids = np.array(tok.encode(pathlib.Path("data/persuasion.txt").read_text()))
cut = int(0.9 * len(ids))
held_out = ids[cut:cut + 20_000] # the same held-out tokens train_gpt scored
for scheme in ["f32", "int8", "q4_0"]:
m = model if scheme == "f32" else quantize_model(model, scheme)
loss = evaluate(m, held_out, model.cfg.context)
print(f"{scheme:5s} {weight_bytes(model, scheme):7d} bytes held-out {loss:.4f} nats perplexity {math.exp(loss):.3f}")
rng = np.random.default_rng(0)
draft = GPT(GPTConfig(tok.vocab_size, model.cfg.context, d_model=32, n_heads=4, n_layers=1), rng)
train(draft, Adam(draft.parameters(), 3e-3), ids[:cut], 600, 64, 16, rng)
print(f"draft held-out {evaluate(draft, held_out, model.cfg.context):.4f} nats")
prompt = tok.encode("Anne was")
for temperature in [0, 1.0]:
for k in [2, 4]:
out, stats = speculative_generate(probs_fn(model, temperature), probs_fn(draft, temperature),
prompt, 48, k, np.random.default_rng(1))
print(f"temperature {temperature} k={k}: {stats}, acceptance {stats['accepted'] / stats['drafted']:.2f}")
plain = generate(model, prompt, 48, np.random.default_rng(0), temperature=0)
spec, _ = speculative_generate(probs_fn(model, 0), probs_fn(draft, 0), prompt, 48, 4, np.random.default_rng(1))
print("greedy speculative == greedy plain:", spec == plain)
and run it from py/:
OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/engine_lab.py /tmp/tinygpt-persuasion
It printed, in about a minute on talos:
f32 677376 bytes held-out 3.0117 nats perplexity 20.321
int8 182528 bytes held-out 3.0116 nats perplexity 20.320
q4_0 100096 bytes held-out 3.0733 nats perplexity 21.613
draft held-out 3.7150 nats
temperature 0 k=2: {'target_calls': 40, 'drafted': 79, 'accepted': 8}, acceptance 0.10
temperature 0 k=4: {'target_calls': 38, 'drafted': 147, 'accepted': 10}, acceptance 0.07
temperature 1.0 k=2: {'target_calls': 30, 'drafted': 59, 'accepted': 19}, acceptance 0.32
temperature 1.0 k=4: {'target_calls': 21, 'drafted': 78, 'accepted': 28}, acceptance 0.36
greedy speculative == greedy plain: True
- The quantization rows are the table in the Mechanism section: int8 is free at 27% of the bytes, Q4_0 costs 0.062 nats at 15%.
- The acceptance column is accepted over drafted, and it understates . A draft after a rejection is counted as drafted but never examined. Greedy with drafted 147 tokens in 38 steps and accepted 10, so most steps rejected their first draft and threw the other three away unexamined. llama-server’s
draft acceptanceis the same ratio,n_draft_accepted / n_draft_total. Tokens per call is the more useful figure: and greedy, and at temperature 1. - This prompt is harder for the draft than average. Along the target’s greedy continuation of “Anne was” the two argmaxes agree at 10 of 48 positions, , against 0.29 over the 20 prompts above, where greedy decoding made 1.34 and 1.40 tokens per call for and 4. With the geometric model predicts 1.25 and 1.26; one prompt of 48 tokens is a small sample.
- Greedy speculation reproduces greedy decoding exactly, with a draft that agrees with the target at a minority of positions. Correctness never depended on the draft; speed does.
Further reading
- Yaniv Leviathan, Matan Kalman and Yossi Matias, “Fast Inference from Transformers via Speculative Decoding”, ICML (2023). Speculative sampling (Section 2.3) with the proof that the output is distributed as (Appendix A.1), the acceptance rate , the expected tokens per run under an i.i.d. assumption, and the walltime improvement factor with the cost coefficient (Theorem 3.8, Corollary 3.9).
- Charlie Chen, Sebastian Borgeaud, Geoffrey Irving, Jean-Baptiste Lespiau, Laurent Sifre and John Jumper, “Accelerating Large Language Model Decoding with Speculative Sampling” (2023). Draft-and-verify with a modified rejection sampling scheme that preserves the target’s distribution, benchmarked on Chinchilla, a 70-billion-parameter model.
- Tim Dettmers, Mike Lewis, Younes Belkada and Luke Zettlemoyer, “LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale”, NeurIPS (2022). Vector-wise int8 quantization with a separate scale for each inner product, and a mixed-precision decomposition that keeps the few outlier feature dimensions in 16 bits.
- Elias Frantar, Saleh Ashkboos, Torsten Hoefler and Dan Alistarh, “GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers”, ICLR (2023). One-shot weight quantization to 3 and 4 bits based on approximate second-order information, which chooses codes to preserve each layer’s output rather than rounding each weight independently.
- Benoit Jacob, Skirmantas Kligys, Bo Chen, Menglong Zhu, Matthew Tang, Andrew Howard, Hartwig Adam and Dmitry Kalenichenko, “Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference”, CVPR (2018). Affine quantization with a scale and zero point, inference in integer arithmetic only, and training that simulates the quantization so accuracy survives it.
- Reiner Pope, Sholto Douglas, Aakanksha Chowdhery, Jacob Devlin, James Bradbury, Anselm Levskaya, Jonathan Heek, Kefan Xiao, Shivani Agrawal and Jeff Dean, “Efficiently Scaling Transformer Inference”, MLSys (2023). Section 2’s cost model: a memory time to load the weights and KV cache once per forward pass, dominated by the weights at small batch sizes and by the KV cache at large batches and long contexts, against a compute time of FLOPs per token; and the separate analysis of prefill and decode.
- ggml:
ggml/src/ggml-common.hforblock_q4_0andblock_q8_0, andggml/src/ggml-quants.cforquantize_row_q4_0_ref,dequantize_row_q4_0and the importance-weightedquantize_row_q4_0_impl;docs/gguf.mdin the ggml repository for the GGUF file format, its tensor types,general.file_type, the expert-count keys and the file-naming convention. llama.cpp:tools/server/README.mdanddocs/speculative.mdfor the--spec-*options and the statistics,common/sampling.cppforcommon_sampler_sample_and_accept_n, andsrc/llama-quant.cppfor howllama-quantizechooses each tensor’s type. - Andy Arditi, Oscar Obeso, Aaquib Syed, Daniel Paleka, Nina Panickssery, Wes Gurnee and Neel Nanda, “Refusal in Language Models Is Mediated by a Single Direction” (2024). A single direction in the residual stream whose removal, by projecting it out of the weights that write to the stream, stops a chat model refusing: the edit behind “abliterated” models.
- whisper.cpp,
models/README.md: theggmlmodel files, their names and sizes. - Albert Q. Jiang, Alexandre Sablayrolles, Antoine Roux, Arthur Mensch and others, “Mixtral of Experts” (2024). Section 5, the routing analysis: consecutive tokens are assigned the same experts more often than uniform assignment would give, significantly so in the higher layers.