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, 2N2N FLOPs for NN 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 NN such weights stored at bb bytes each, larger than any cache, on a processor that can move RR bytes per second from memory and do FF FLOPs per second. Generating one token for one sequence moves NbNb bytes and does 2N2N FLOPs, so it takes at least

t≥max(NbR,2NF) t \ge \max\!\left(\frac{Nb}{R}, \frac{2N}{F}\right)

seconds. The memory term is the larger one exactly when Nb/R>2N/FNb/R > 2N/F, that is when

FR>2b. \frac{F}{R} > \frac{2}{b} .

F/RF/R is a property of the hardware, the FLOPs it can do per byte it reads; 2/b2/b is a property of decoding, the FLOPs a weight gets per byte it costs: 1 FLOP per byte at f16 (b=2b = 2), 0.5 at f32. When the inequality holds, the arithmetic units wait for memory and the bound on single-sequence decoding speed is

tokens/s≤RNb, \text{tokens/s} \le \frac{R}{Nb} ,

set by the bytes of the weights and nothing else. The KV cache (chapter 12) adds its own bytes to each step, t≥(Nb+M)/Rt \ge (Nb + M)/R for a cache of MM bytes, which matters at long contexts; the weights are the fixed part. Compare 2/b2/b with F/RF/R from your own machines’ spec sheets; what follows applies whenever the inequality holds.

NN 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 NN 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 bb. This is what a GGUF file’s quantization type chooses: llama-quantize model-f16.gguf model-Q4_0.gguf Q4_0 rewrites the weight matrices in ggml’s Q4_0 format at 4.5 bits per weight instead of 16, and Q8_0, Q4_K_M and 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 NbNb 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-simple selecting a standalone draft model; --spec-draft-n-max sets 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 WW of shape (in, out) computes yj=∑ixiWijy_j = \sum_i x_i W_{ij} for each output jj (chapter 3’s contract, x\mathbf{x} of shape (in,)). Give column jj its own scale,

sj=maxi∣Wij∣127,qij=round(Wijsj),W^ij=sjqij, s_j = \frac{\max_i |W_{ij}|}{127} , \qquad q_{ij} = \mathrm{round}\!\left(\frac{W_{ij}}{s_j}\right) , \qquad \hat{W}_{ij} = s_j\, q_{ij} ,

with s\mathbf{s} of shape (out,) stored as float32 and QQ of shape (in, out) as int8. Write u=Wij/sju = W_{ij}/s_j. By the choice of sjs_j, ∣u∣≤127|u| \le 127, so qijq_{ij} lies in [−127,127][-127, 127] and fits a signed byte without clipping; the code −128-128 is never used, which keeps the range symmetric. Rounding to the nearest integer moves uu by at most 12\frac{1}{2}, ∣u−qij∣≤12|u - q_{ij}| \le \frac{1}{2}, and multiplying by sjs_j,

∣Wij−W^ij∣=sj∣u−qij∣≤sj2. |W_{ij} - \hat{W}_{ij}| = s_j\,|u - q_{ij}| \le \frac{s_j}{2} .

The bound is attained whenever uu is exactly halfway between two integers (exercise (b)). An all-zero column would give sj=0s_j = 0 and a division by zero; the reference gives it sj=1s_j = 1, and its codes are all 0.

Why a scale per output column: the scale then factors out of the sum each output computes,

yj=∑ixisjqij=sj∑ixiqij, y_j = \sum_i x_i\, s_j q_{ij} = s_j \sum_i x_i q_{ij} ,

so a kernel can form the dot product with the integer codes and multiply by sjs_j 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 1/127=0.00791/127 = 0.0079: 2,466 of the other 16,383 weights round to zero, and the RMS error of the weights outside the outlier’s column is 2.29×10−32.29 \times 10^{-3}, a ninth of the weights’ own size. With a scale per column the same weights have RMS error 1.39×10−41.39 \times 10^{-4}; only the outlier’s column pays. Storage is 1 byte per weight plus 4 bytes per column, 8+32/in8 + 32/\mathit{in} 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, 18×8/32=4.518 \times 8/32 = 4.5 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 x0,…,x31x_0, \ldots, x_{31}:

  1. Find mm, the entry of largest magnitude with its sign kept (the first one, if several tie).
  2. Set d=m/(−8)d = m/(-8), stored as f16; set id=1/d\mathit{id} = 1/d, computed from the float32 dd before it is rounded (and 0 if d=0d = 0).
  3. Code each entry as qj=min(15,⌊xj⋅id+8.5⌋)q_j = \min\!\big(15, \lfloor x_j \cdot \mathit{id} + 8.5 \rfloor\big), an integer in [0,15][0, 15].
  4. Pack two codes per byte: qs[j] = q[j] | q[j + 16] << 4 for j=0,…,15j = 0, \ldots, 15. The first half of the block goes in the low nibbles, the second half in the high nibbles; neighbours are not paired.

Dequantization is x^j=(qj−8)d\hat{x}_j = (q_j - 8)\,d, with f16 dd widened to float32 (dequantize_row_q4_0).

The code q−8q - 8 runs over the 16 integers −8,…,7-8, \ldots, 7: eight negative values and seven positive. The sign in d=m/(−8)d = m/(-8) spends the extra negative value on the largest entry, whatever its sign: m⋅id=−8m \cdot \mathit{id} = -8, so mm gets code 0 and is reconstructed as −8d=m-8d = m, exactly up to the rounding of dd. When mm is positive, dd is negative and the code order is reversed; nothing else changes.

The error bound. Let u=xj/du = x_j/d. Every entry has ∣xj∣≤∣m∣=8∣d∣|x_j| \le |m| = 8|d|, so u∈[−8,8]u \in [-8, 8]. Since ⌊u+8.5⌋=⌊u+0.5⌋+8\lfloor u + 8.5 \rfloor = \lfloor u + 0.5 \rfloor + 8, the stored value qj−8q_j - 8 is ⌊u+0.5⌋\lfloor u + 0.5\rfloor, uu rounded to the nearest integer (halves up), as long as the clamp at 15 is inactive. Then ∣u−(qj−8)∣≤12|u - (q_j - 8)| \le \frac{1}{2} and

∣xj−x^j∣=∣d∣∣u−(qj−8)∣≤∣d∣2. |x_j - \hat{x}_j| = |d|\,\big|u - (q_j - 8)\big| \le \frac{|d|}{2} .

The clamp is active when ⌊u+8.5⌋≥16\lfloor u + 8.5 \rfloor \ge 16, that is u≥7.5u \ge 7.5: entries of the sign opposite to mm with magnitude at least 1516∣m∣\frac{15}{16}|m|. They get qj−8=7q_j - 8 = 7, and since u≤8u \le 8,

∣xj−x^j∣=∣d∣(u−7)≤∣d∣, |x_j - \hat{x}_j| = |d|\,(u - 7) \le |d| ,

one full step. In the Persuasion model’s matrices this happens to 890 of 167,936 weights. Rounding dd to f16 (10 fraction bits, relative error at most 2−112^{-11} while dd is a normal f16 number, ∣d∣≥2−14|d| \ge 2^{-14}, so ∣m∣≥2−11≈4.9×10−4|m| \ge 2^{-11} \approx 4.9 \times 10^{-4}; a block of smaller weights gets a subnormal dd with fewer significant bits and a larger relative error) adds at most ∣qj−8∣∣d∣2−11≤8∣d∣2−11=∣d∣/256|q_j - 8|\,|d|\,2^{-11} \le 8|d|\,2^{-11} = |d|/256 to either bound. test_q4_round_trip_error_bound checks both on random blocks, and test_q4_clamps_the_opposite_extreme builds the tie (−1,…,1,…)(-1, \ldots, 1, \ldots): −1-1 comes first and becomes mm, d=0.125d = 0.125, and +1+1 lands on u=8u = 8, code min(15,16)=15\min(15, 16) = 15, reconstructed as 7×0.125=0.8757 \times 0.125 = 0.875.

Taking id\mathit{id} from the float32 dd rather than the rounded one, and doing the arithmetic in float32, matter only at the edges: in 512 random blocks, computing id\mathit{id} 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 x⋅id+8.5x \cdot \mathit{id} + 8.5 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 d=1/(−8)d = 1/(-8) 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 1.99×10−21.99 \times 10^{-2}, the size of the weights themselves. Every other block keeps its own small scale: the RMS error everywhere else is 1.72×10−31.72 \times 10^{-3}, 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 ii,

yj=∑blocks βdβj∑i∈β(qij−8)xi, y_j = \sum_{\text{blocks } \beta} d_{\beta j} \sum_{i \in \beta} (q_{ij} - 8)\, x_i ,

one multiply by dd per block per output. ggml stores each weight matrix as rows of the reduction dimension (in ggml_mul_mat, both operands have kk columns, and each row of the weight holds the kk 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 σ2+x2\sqrt{\sigma^2 + x^2}, with σ2\sigma^2 the row’s mean square. The block layout stays the same; only the choice of dd 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 BB sequences decoded together, one step still reads each weight once, NbNb bytes, but uses it BB times: by chapter 3’s count, a (B, in) input through an (in, out) weight is B⋅in⋅outB \cdot \mathit{in} \cdot \mathit{out} multiply-adds, so the step does 2NB2NB FLOPs. Its time is at least

t(B)≥max(NbR,2NBF), t(B) \ge \max\!\left(\frac{Nb}{R}, \frac{2NB}{F}\right) ,

and it produces BB tokens, so

tokens/s≤Bt(B)=min(BRNb,F2N). \text{tokens/s} \le \frac{B}{t(B)} = \min\!\left(\frac{BR}{Nb}, \frac{F}{2N}\right) .

Throughput grows linearly in BB while the first term is the smaller, and stops growing at the crossover BR/(Nb)=F/(2N)BR/(Nb) = F/(2N),

B∗=FR⋅b2, B^* = \frac{F}{R} \cdot \frac{b}{2} ,

where the step becomes compute-bound. Prompt processing is this regime already: the PP 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 Nb+∑sMsNb + \sum_s M_s bytes for cache sizes MsM_s, and the cache term grows with BB. Each slot also holds its cache in memory for the life of the request; chapter 12’s M=2LSdbM = 2LSdb 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 BB, since the BB 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 jj’s state depends only on tokens 0,…,j0, \ldots, j). So if someone hands the target model a guessed continuation t1,…,tkt_1, \ldots, t_k, one pass over the prefix and the guesses returns k+1k + 1 distributions: p1p_1 for the slot t1t_1 fills, computed at the last prefix position; p2p_2 for the next slot, computed at t1t_1’s position as if t1t_1 were right; and so on to pk+1p_{k+1}, the distribution after all kk guesses. In the memory-bound regime that pass costs about one decoding step for a dense model: it reads the weights once for k+1k + 1 positions. (For a mixture-of-experts model it reads the experts all k+1k + 1 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 pip_i and qiq_i at the same slot, both of shape (V,), define the residual, where the target wants more mass than the draft offered,

ri(x)=max(0,pi(x)−qi(x))∑ymax(0,pi(y)−qi(y)). r_i(x) = \frac{\max\big(0,\, p_i(x) - q_i(x)\big)}{\sum_y \max\big(0,\, p_i(y) - q_i(y)\big)} .

One step of speculative decoding with kk drafts:

  1. Draft: for i=1,…,ki = 1, \ldots, k, compute the draft’s distribution qiq_i given the prefix and t1,…,ti−1t_1, \ldots, t_{i-1}, and draw ti∼qit_i \sim q_i. These are kk sequential draft calls.
  2. Verify: one target call over the prefix and t1,…,tkt_1, \ldots, t_k gives p1,…,pk+1p_1, \ldots, p_{k+1}.
  3. Accept left to right: accept tit_i with probability min(1,pi(ti)/qi(ti))\min\!\big(1, p_i(t_i)/q_i(t_i)\big). At the first rejection, emit instead a token drawn from rir_i, and discard ti+1,…,tkt_{i+1}, \ldots, t_k, which were drafted after a token that is not in the output.
  4. If all kk are accepted, emit a bonus token drawn from pk+1p_{k+1}, which the same target call already computed.

One speculative decoding step with k = 4: draft four tokens, verify them with one target call Five output slots run left to right. Top row, the draft: tokens t1 to t4 fill slots 1 to 4, each drawn from the draft distribution q1 to q4 by its own draft call, each call depending on the token before it. Second row, the target: one forward pass over the prefix and t1 to t4. Third row: that pass returns five distributions, p1 to p5, one per slot; p_i is computed at the position before slot i. Fourth row, verification: t1 and t2 are accepted (ticks), t3 is rejected (a cross), and t4 is discarded unexamined because it was drafted after t3. Bottom row, the emitted tokens: t1, t2, and in slot 3 a replacement t3 prime drawn from r3, the normalised residual max(0, p3 minus q3). A dashed path in slot 5 shows the other outcome: had all four drafts been accepted, a bonus token t5 would be drawn from p5, which the same target call already computed. Draft four calls Target one call Verify left to right Emit three tokens t1 ~ q1 t2 ~ q2 t3 ~ q3 t4 ~ q4 one forward pass over the prefix and t1 … t4 p1 p2 p3 p4 p5 accept t1 accept t2 reject t3 discard t4 t1 t2 t3′ ~ r3 t5 ~ p5 r3 = norm(max(0, p3 − q3)): the mass the target wants beyond what the draft offered dashed in slot 5: the bonus token, drawn only when all four drafts are accepted

The output is distributed exactly as the target. Consider one slot with target distribution pp and draft distribution qq, both of shape (V,): the draft draws t∼qt \sim q, and an independent uniform decides acceptance. The emitted token is xx either because the draft proposed xx and it was accepted, or because some proposal was rejected and the residual draw gave xx:

P(x)=q(x)min(1,p(x)q(x))+P(reject)r(x). P(x) = q(x)\min\!\left(1, \frac{p(x)}{q(x)}\right) + P(\text{reject})\; r(x) .

The first term is min(q(x),p(x))\min\big(q(x), p(x)\big) (multiply q(x)q(x) into the minimum; where q(x)=0q(x) = 0 the draft never proposes xx and the term is 0, which is also min(q,p)\min(q, p)). Summing it over xx gives the probability of accepting whatever was proposed, so

P(reject)=1−∑ymin(p(y),q(y)). P(\text{reject}) = 1 - \sum_y \min\big(p(y), q(y)\big) .

For the residual’s denominator, use max(0,p−q)=p−min(p,q)\max(0, p - q) = p - \min(p, q) (if p≥qp \ge q both sides are p−qp - q; otherwise both are 0) and ∑yp(y)=1\sum_y p(y) = 1:

∑ymax(0,p(y)−q(y))=1−∑ymin(p(y),q(y))=P(reject). \sum_y \max\big(0, p(y) - q(y)\big) = 1 - \sum_y \min\big(p(y), q(y)\big) = P(\text{reject}) .

So when rejection is possible the second term is P(reject)⋅max(0,p(x)−q(x))/P(reject)=max(0,p(x)−q(x))P(\text{reject}) \cdot \max(0, p(x) - q(x)) / P(\text{reject}) = \max\big(0, p(x) - q(x)\big), and

P(x)=min(p(x),q(x))+max(0,p(x)−q(x))=p(x). P(x) = \min\big(p(x), q(x)\big) + \max\big(0, p(x) - q(x)\big) = p(x) .

When ∑ymin(p,q)=1\sum_y \min(p, q) = 1, p=qp = q, every ratio is 1, rejection never happens and the residual is never formed. The accept test samples from pp using a proposal from qq; 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 t1,…,ti−1t_1, \ldots, t_{i-1} have been accepted, the emitted prefix equals the drafted one, so pip_i and qiq_i are the target’s and the draft’s distributions given what has actually been emitted, and the slot lemma says slot ii’s token is distributed as pip_i. 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 pk+1p_{k+1}, the target’s distribution given the prefix and all kk 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 tt with q(t)=1q(t) = 1; the ratio p(t)/q(t)p(t)/q(t) is 1 if the target’s argmax is also tt and 0 otherwise, so a draft token is accepted exactly when the two argmaxes agree, and on rejection the residual is max(0,p−q)\max(0, p - q), 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 pp the target’s distribution after that sampler chain, that is the scheme above with a one-hot qq at tt: acceptance probability min(1,p(t)/1)=p(t)\min(1, p(t)/1) = p(t), the chance the target’s sample is tt; and on rejection the residual max(0,p−et)\max(0, p - \mathbf{e}_t) normalised is pp with tt removed, p(x)/(1−p(t))p(x)/(1 - p(t)) for x≠tx \ne t, which is the target’s sample conditioned on not being tt. 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

α=∑xq(x)min(1,p(x)q(x))=∑xmin(p(x),q(x)), \alpha = \sum_x q(x) \min\!\left(1, \frac{p(x)}{q(x)}\right) = \sum_x \min\big(p(x), q(x)\big) ,

the overlap of the two distributions. Assume, as a model, that every slot has the same α\alpha independently. The number AA of accepted drafts in a step is at least ii exactly when the first ii are all accepted, P(A≥i)=αiP(A \ge i) = \alpha^i for i≤ki \le k. Every step emits A+1A + 1 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 AA, write it as a sum of indicators,

A=∑i=1k1[A≥i], A = \sum_{i=1}^{k} \mathbf{1}[A \ge i] ,

where 1[A≥i]\mathbf{1}[A \ge i] is 1 if A≥iA \ge i and 0 otherwise: when A=aA = a, the indicators for i=1,…,ai = 1, \ldots, a are 1 and the rest are 0, so the sum is aa. The expectation of an indicator is the probability of its event, and expectation is linear, so E[A]=∑i=1kP(A≥i)=∑i=1kαi\mathbb{E}[A] = \sum_{i=1}^{k} P(A \ge i) = \sum_{i=1}^{k} \alpha^i and

E[tokens per call]=1+∑i=1kαi=∑i=0kαi. \mathbb{E}[\text{tokens per call}] = 1 + \sum_{i=1}^{k} \alpha^i = \sum_{i=0}^{k} \alpha^i .

Call the sum SS. Then αS=∑i=1k+1αi\alpha S = \sum_{i=1}^{k+1} \alpha^i, and subtracting, S−αS=1−αk+1S - \alpha S = 1 - \alpha^{k+1}:

E[tokens per call]=1−αk+11−α, \mathbb{E}[\text{tokens per call}] = \frac{1 - \alpha^{k+1}}{1 - \alpha} ,

which rises with kk toward 1/(1−α)1/(1 - \alpha) and never exceeds k+1k + 1. 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 kk draft calls and one target call. Let cc be the ratio of a draft call’s time to a target call’s. Measured in units of target calls, a step costs 1+kc1 + kc and yields (1−αk+1)/(1−α)(1 - \alpha^{k+1})/(1 - \alpha) tokens, so the speed relative to plain decoding is

1−αk+1(1−α)(1+kc), \frac{1 - \alpha^{k+1}}{(1 - \alpha)(1 + kc)} ,

Leviathan, Kalman and Matias’s Theorem 3.8. At k=1k = 1 it is (1+α)/(1+c)(1 + \alpha)/(1 + c), above 1 exactly when α>c\alpha > c; the ii-th draft adds αi\alpha^{i} expected tokens for cc more time, so once αi<c\alpha^{i} < c 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:

α\alpha measured tokens/call, k=1k = 1 k=2k = 2 k=4k = 4
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 α\alpha is ∑xmin(p,q)\sum_x \min(p, q) 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, cc 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 c=0.4c = 0.4 the formula predicts that only temperature 1 at k=1k = 1 gains (1.50/1.40=1.071.50/1.40 = 1.07); 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 k=1,2,4k = 1, 2, 4, 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 cc below 0.05, being a couple of orders of magnitude smaller than their targets; that, together with an α\alpha well above cc, 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 EE experts, of which each token uses a few. This section writes mm for that number, chapter 11’s top-kk, since kk here counts drafts. Split a model’s weights into NsN_s, the shared weights every token is multiplied by (attention, norms, the router, any shared expert, the head), and the experts: LL MoE layers, each with EE experts of nen_e weights. Then

Ntotal=Ns+LEne,Nactive=Ns+Lmne, N_{\text{total}} = N_s + L E n_e , \qquad N_{\text{active}} = N_s + L m n_e ,

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 mm chosen experts; an engine reads nothing else. With every weight stored at bb bytes, a decoding step moves NactivebN_{\text{active}}\, b bytes and does 2Nactive2N_{\text{active}} FLOPs, and the argument of the opening gives

tokens/s≤RNactiveb \text{tokens/s} \le \frac{R}{N_{\text{active}}\, b}

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:

memory≥Ntotalb+M, \text{memory} \ge N_{\text{total}}\, b + M ,

with MM 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 LEne=40×256×3,145,728=32.2×109L E n_e = 40 \times 256 \times 3{,}145{,}728 = 32.2 \times 10^9 weights, of which a token uses 8/2568/256, 1.0 billion; with the model card’s “~3B” active, NsN_s 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 3×109×4.5/8=1.693 \times 10^9 \times 4.5/8 = 1.69 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 RR, 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 35.95/3=12.035.95/3 = 12.0. 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 MM 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 10×2×2×256×2=20,48010 \times 2 \times 2 \times 256 \times 2 = 20{,}480 bytes, against 2Ldb=2×40×2048×2=327,6802Ldb = 2 \times 40 \times 2048 \times 2 = 327{,}680 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. BB tokens decoded together share one read of NsN_s, 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 mm experts are a uniformly random mm-subset of the EE, independently across tokens. For one expert ee, one token avoids it with probability (E−1m)/(Em)=(E−m)/E=1−m/E\binom{E-1}{m} / \binom{E}{m} = (E - m)/E = 1 - m/E (the subsets without ee over all subsets), and all BB tokens avoid it with probability (1−m/E)B(1 - m/E)^B by independence. The number of distinct experts is D=∑e1[e chosen by some token]D = \sum_{e} \mathbf{1}[e \text{ chosen by some token}], and linearity of expectation over the EE indicators gives

E[D]=E(1−(1−mE)B). \mathbb{E}[D] = E\Big(1 - \big(1 - \tfrac{m}{E}\big)^B\Big) .

For B=1B = 1 this is mm. For small BB it is close to BmBm: expanding, (1−m/E)B=1−Bm/E+(B2)(m/E)2−⋯(1 - m/E)^B = 1 - Bm/E + \binom{B}{2}(m/E)^2 - \cdots, so E[D]=Bm−(B2)m2/E+⋯\mathbb{E}[D] = Bm - \binom{B}{2}\, m^2/E + \cdots, and overlaps are rare while Bm≪EBm \ll E. As BB grows it approaches EE: every expert is read. For ornith, E=256E = 256 and m=8m = 8:

tokens per step distinct experts per layer, E[D]\mathbb{E}[D] as a share of BmBm
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 b(Ns+LE[D]ne)b\big(N_s + L\,\mathbb{E}[D]\, n_e\big), so with ornith’s numbers (Ns≈2×109N_s \approx 2 \times 10^9, Lne=1.26×108L\, n_e = 1.26 \times 10^8 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 ee be chosen by one token with probability πe\pi_e, with ∑eπe=m\sum_e \pi_e = m. The same argument gives E[D]=∑e(1−(1−πe)B)\mathbb{E}[D] = \sum_e \big(1 - (1 - \pi_e)^B\big). The function ϕ(π)=1−(1−π)B\phi(\pi) = 1 - (1 - \pi)^B is concave on [0,1][0, 1], its second derivative being −B(B−1)(1−π)B−2≤0-B(B-1)(1 - \pi)^{B-2} \le 0, so by Jensen’s inequality 1E∑eϕ(πe)≤ϕ(1E∑eπe)=ϕ(m/E)\frac{1}{E}\sum_e \phi(\pi_e) \le \phi\big(\frac{1}{E}\sum_e \pi_e\big) = \phi(m/E), and E[D]≤E(1−(1−m/E)B)\mathbb{E}[D] \le E(1 - (1 - m/E)^B), with equality for uniform π\pi. 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 BmBm 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 kk drafts is a forward pass over k+1k + 1 positions, and each routes on its own. With llama-server’s default of 3 drafts, the pass reads the experts of 4 positions: E[D]=30.53\mathbb{E}[D] = 30.53 per layer for ornith under uniform routing, and (Ns+L⋅30.53ne)/(Ns+L⋅8ne)≈1.95\big(N_s + L \cdot 30.53\, n_e\big) / \big(N_s + L \cdot 8\, n_e\big) \approx 1.95 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: mmproj for a multimodal projector, the vision or audio encoder and its projection into the language model (chapter 16), or mtp for 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 as Qwen3 or Qwen2-VL (VL for vision-language).
  • SizeLabel: <expertCount>x<count><scale-prefix>, with K, M, B, T and Q for thousands to quadrillions, from general.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-A3B is 30 billion parameters of which about 3 billion are active, the NtotalN_{\text{total}} and NactiveN_{\text{active}} above. The metadata keys [arch].expert_count and [arch].expert_used_count hold EE and mm.
  • FineTune: what the base was tuned for, from general.finetune: Instruct or Chat for chapter 13’s supervised and preference tuning; Thinking for a reasoning model, as in Qwen’s Qwen3-30B-A3B-Thinking-2507; a name with no fine-tune is usually a base model, pretrained only (chapter 11’s train_gpt makes one). Descriptions of provenance appear here too: Distill marks a student trained on a larger model’s generated text (chapter 13’s sequence-level distillation), as in DeepSeek-R1-Distill-Qwen-7B, and abliterated a model whose weights were edited to remove the direction in its residual stream that Arditi and colleagues found mediates refusal. uncensored is a claim about behaviour and names no method.
  • Version: v<Major>.<Minor>, v1.0 if absent.
  • Encoding: the quantization, this chapter’s subject. F16 and BF16 are 16-bit floats; Q8_0 and Q4_0 are the block formats derived above, 8.5 and 4.5 bits per weight; Q4_K_M is a mixture, not one format: llama-quantize stores most matrices as Q4_K and, in a subset of layers, attn_v and ffn_down as Q6_K (llama_tensor_get_type_impl in src/llama-quant.cpp, as of da89bb3). general.file_type names the majority type.
  • Type and Shard: LoRA for an adapter (chapter 50) or vocab for a tokenizer-only file; and 00003-of-00009 for 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 in v form), 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 as Q4_K_M with an explicit mmproj-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 separate mmproj file, and SYSTEM.md records that the router’s --hf-repo did not attach it, and the preset names it explicitly; chapter 16 traces when -hf finds 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 own ggml format as ggml-<model>.bin (its models/README.md lists large-v3-turbo, 1.5 GiB); large-v3-turbo is 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.json files), 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 s/2s/2 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 2−242^{-24}, so the excess is at most about 127⋅2−24≈7.6×10−6127 \cdot 2^{-24} \approx 7.6 \times 10^{-6}, 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. dd 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 (q−8)d(q - 8)d 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 rr. A rejection needs p(t)<q(t)p(t) < q(t), so in exact arithmetic some other token has p>qp > q and the sum is positive; with two floating-point rows that differ only by rounding it can come out 0, and residual then returns pp itself rather than dividing by zero. speculative_accept draws one uniform and compares it with the ratio; since rng.random() is in [0,1)[0, 1), 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 kk 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, qiq_i. The target is called once on the prefix plus all proposals. Its rows are indexed by position: row jj is the distribution for position j+1j + 1, 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, p1p_1 to pk+1p_{k+1}. 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 k+1k + 1 per verification, and after a rejection at slot ii 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 7×1097 \times 10^9 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: 18×8/32=4.518 \times 8 / 32 = 4.5 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, 34×8/32=8.534 \times 8/32 = 8.5 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, d=amax/127d = \mathrm{amax}/127 and codes round(x/d)\mathrm{round}(x/d).

For 7×1097 \times 10^9 weights: f16 is 1.4×10101.4 \times 10^{10} bytes, 13.04 GiB; Q8_0 is 7×109×34/32=7.4375×1097 \times 10^9 \times 34/32 = 7.4375 \times 10^9 bytes, 6.93 GiB; Q4_0 is 7×109×18/32=3.9375×1097 \times 10^9 \times 18/32 = 3.9375 \times 10^9 bytes, 3.67 GiB. By the bound at the start of the chapter, the single-sequence decoding limit R/(Nb)R/(Nb) improves by the same factors, 16/8.5=1.8816/8.5 = 1.88 and 16/4.5=3.5616/4.5 = 3.56. 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 ∣w−w^∣≤s/2|w - \hat{w}| \le s/2 and find inputs that attain it.

Answer

With s=max∣w∣/127s = \max|w|/127, u=w/su = w/s satisfies ∣u∣≤127|u| \le 127, so rounding to the nearest integer never needs the clip and ∣u−round(u)∣≤1/2|u - \mathrm{round}(u)| \le 1/2; multiply by ss. Equality needs uu 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 s=1s = 1 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 −1.5-1.5 are halfway cases and reach the bound; np.round sends halves to the even neighbour (0, 2, −2-2), but either choice is half a step away. 0.25 is not a halfway case and does not.

(c) Quantize the block xj=(j−11)/16x_j = (j - 11)/16, j=0,…,31j = 0, \ldots, 31, to Q4_0: find dd, 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 x31=20/16=1.25x_{31} = 20/16 = 1.25, positive, so d=1.25/(−8)=−0.15625=−5/32d = 1.25/(-8) = -0.15625 = -5/32, exact in f16, and the codes decrease as xx increases. xj/d=−(j−11)/16×32/5=−0.4(j−11)x_j/d = -(j - 11)/16 \times 32/5 = -0.4(j - 11). For j=0j = 0: 4.4+8.5=12.94.4 + 8.5 = 12.9, code 12. For j=16j = 16: −2+8.5=6.5-2 + 8.5 = 6.5, code 6. Byte 0 is q0∣q16≪4=12+6×16=108q_0 \mid q_{16} \ll 4 = 12 + 6 \times 16 = 108 = 0x6c. For j=15j = 15: −1.6+8.5=6.9-1.6 + 8.5 = 6.9, code 6; for j=31j = 31: −8+8.5=0.5-8 + 8.5 = 0.5, code 0, the largest entry at the end of the range; byte 15 is 6+0=6 + 0 = 0x06. The largest error, 0.0625, is below ∣d∣/2=0.078|d|/2 = 0.078: no entry is near −1.25-1.25, so the clamp is never reached.

(d) Tabulate the expected tokens per target call for α=0.3,0.6,0.9\alpha = 0.3, 0.6, 0.9 and k=2,4,8k = 2, 4, 8, and say what the table implies for choosing kk.

Answer

From (1−αk+1)/(1−α)(1 - \alpha^{k+1})/(1 - \alpha):

α\alphak=2k = 2k=4k = 4k=8k = 8k→∞k \to \infty
0.31.3901.4251.4291.429
0.61.9602.3062.4752.500
0.92.7104.0956.12610.000

The ii-th draft contributes αi\alpha^i expected tokens and always costs a draft call. At α=0.3\alpha = 0.3 the third draft adds 0.027 tokens and anything beyond k=2k = 2 buys almost no output for a real cost; at α=0.9\alpha = 0.9 even the eighth adds 0.43. The right kk is where αk\alpha^k falls below the draft’s cost ratio cc, so it grows with α\alpha and shrinks with cc. 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 α\alpha 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 q=pq = p, the ratio p(t)/q(t)=1p(t)/q(t) = 1 for every proposable tt, so every draft is accepted and every step emits k+1k + 1 tokens: α=∑min(p,p)=1\alpha = \sum \min(p, p) = 1 and the geometric sum is k+1k + 1. The tokens are draws from q=pq = p and the bonus from pk+1p_{k+1}, 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 p(x)q(x)=0p(x)\,q(x) = 0 for every xx, a proposed tt has positive q(t)q(t) and therefore p(t)=0p(t) = 0: the ratio is 0 and every draft is rejected, α=∑min(p,q)=0\alpha = \sum \min(p, q) = 0, one token per call. The residual is max(0,p−q)\max(0, p - q), which equals pp wherever pp is positive (there q=0q = 0) and 0 elsewhere, with sum 1: the replacement is a draw from pp itself. Each step is then one plain target step, wasting kk 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 α>c\alpha > c question with straylight’s own cc.

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 k+1k + 1 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, E=256E = 256 and m=8m = 8, for batches of B=1,4,16,64B = 1, 4, 16, 64 tokens: count the distinct experts one layer reads when each token picks its mm uniformly, and when the router prefers expert ii in proportion to 1/i1/i. Compare both with E(1−(1−m/E)B)E(1 - (1 - m/E)^B).

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 B>1B > 1: 68.5 instead of 102.0 at B=16B = 16, 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 B=1B = 1 every router reads exactly mm. rng.choice with p and replace=False draws the mm experts one after another, renormalising over those left, so the skewed router’s per-expert probabilities πe\pi_e are not exactly proportional to 1/i1/i; the inequality holds for any π\pi with ∑eπe=m\sum_e \pi_e = m.

(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 α\alpha. A draft after a rejection is counted as drafted but never examined. Greedy with k=4k = 4 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 acceptance is the same ratio, n_draft_accepted / n_draft_total. Tokens per call is the more useful figure: 48/40=1.2048/40 = 1.20 and 48/38=1.2648/38 = 1.26 greedy, 48/30=1.6048/30 = 1.60 and 48/21=2.2948/21 = 2.29 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, α=0.21\alpha = 0.21, against 0.29 over the 20 prompts above, where greedy decoding made 1.34 and 1.40 tokens per call for k=2k = 2 and 4. With α=0.21\alpha = 0.21 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 pp (Appendix A.1), the acceptance rate α=E[∑xmin(p,q)]\alpha = \mathbb{E}[\sum_x \min(p, q)], the expected tokens per run (1−αγ+1)/(1−α)(1 - \alpha^{\gamma+1})/(1 - \alpha) under an i.i.d. assumption, and the walltime improvement factor with the cost coefficient cc (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 2N2N FLOPs per token; and the separate analysis of prefill and decode.
  • ggml: ggml/src/ggml-common.h for block_q4_0 and block_q8_0, and ggml/src/ggml-quants.c for quantize_row_q4_0_ref, dequantize_row_q4_0 and the importance-weighted quantize_row_q4_0_impl; docs/gguf.md in 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.md and docs/speculative.md for the --spec-* options and the statistics, common/sampling.cpp for common_sampler_sample_and_accept_n, and src/llama-quant.cpp for how llama-quantize chooses 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: the ggml model 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.

results matching ""

    No results matching ""