examples/simple/simple.cpp puts the token in a batch at the next position (5, after a 5-token prompt) and calls llama_process: ms per token, everything below included.src/llama-context.cpp finds a KV cell; the graph has the same shapes as last time, so only its inputs are written. Its nodes were built for the prompt and the first token, then reused times.ggml-alloc.c and ggml-backend.cpp, one planned buffer of MiB holds every intermediate, and the whole graph is one split on the CPU backend.ggml-cpu/ggml-cpu.c, 4 threads walk every node and meet at a barrier after each of the real operations; the rest are free views.ggml-cpu/repack.cpp, each product quantises its input row to Q8_0 and cuts the weight rows into 16 chunks, taken from an atomic counter: products × 16 chunks = kernel calls.ggml_gemv_q8_0_4x4_q8_0 in arch/arm/repack.cpp: SDOT instructions over four interleaved rows of weights repacked at load. Every weight is read once, about 143 MB per token.src/llama-sampler.cpp takes the largest: the first one sampled here was " Paris".SmolLM2-135M in Q8_0, 4 threads, Apple M1 Pro; every number on the figure and in the steps measured (the objects on each layer are schematic). The sections below open each layer; section 13 walks the same path file by file.
You need: the build and libraries (C++: the essentials); unique_ptr and RAII (C++: ownership, moves and object lifetimes); templates, virtual functions, lambdas (C++: classes, templates and the standard library); cache lines, SIMD, atomics (C++: the machine underneath). What the code computes (attention, the KV cache, batching, quantisation error) is taught by Topic: inference-and-serving, Local and on-device inference and Quantization and precision; this page reads how it is built.
ne, nb: a ggml tensor's sizes and byte strides, innermost dimension first.llama-server.Source pinned at commit , every excerpt linked to its lines; model SmolLM2-135M-Instruct in Q8_0; every log, count and timing real, from a busy Apple M1 Pro (How this was run).
The hero is the path; the sections below follow it from the repository map to the server, one file at a time, each naming the C++ features the file leans on.
| Stop | Where | Features it uses | Take away |
|---|---|---|---|
| The map | ggml/, src/, tools/ | C core, C++ around it | Two libraries: ggml (tensors, kernels, backends) and libllama (models, KV cache, sampling) behind a C API |
| Building | CMakeLists.txt | CMake options, shared libraries | Backends are chosen at build time; one .dylib per backend |
| The API | examples/simple/simple.cpp | C API, opaque pointers, unique_ptr deleters | Load, tokenize, decode, sample, free: the whole program in 240 lines |
| GGUF | ggml/src/gguf.cpp | fixed-width binary I/O, exceptions | A header of key-values and tensor descriptions, then aligned raw bytes; 41 lines of Python read it |
| Loading | src/llama-model-loader.cpp | RAII mmap, pointer arithmetic | Weights are mapped, not read; on this M1 most are then copied into a faster layout |
| Tensors | ggml/include/ggml.h | plain C structs, strides | A tensor is sizes, byte strides and a pointer; a view or transpose moves no data |
| The model graph | src/models/llama.cpp | templates, if constexpr, structured bindings | Model code builds a graph of nodes; nothing is computed yet |
| Graph to compute | src/llama-context.cpp, ggml-backend.cpp | function-pointer interfaces, reference counts | Build once, reuse; all intermediates of a token fit in MiB |
| Threads | ggml-cpu/ggml-cpu.c | pthreads, atomics, barriers | Every thread walks every node; matrix rows are split into chunks taken from an atomic counter |
| Quantised kernels | ggml-common.h, quants.c, repack.cpp | packed structs, static_assert, NEON intrinsics | 32 weights share one scale; the kernel that runs here is not the one most guides point to |
| KV cache and sampling | llama-kv-cache.cpp, llama-sampler.cpp | virtual classes and C vtables side by side | The cache is one tensor per layer, read through a strided view |
| Server | tools/server/ | lambdas, std::unique_ptr members | Many requests, one batch per step |
ggml_vec_dot_q4_0_q8_0 or ggml_vec_dot_q8_0_q8_0. On this M1 with the default build, call counters show those functions run zero times: the weights are rearranged at load time and a different kernel, ggml_gemv_q8_0_4x4_q8_0, does all matrix products of each new token, in calls (section 10). Reading code is not enough; check what runs.A codebase of a million lines is read like a city: first the districts, then one street. llama.cpp has two libraries and a ring of programs around them.
ggml/, the tensor library: tensors, the compute graph, the file format, and one backend per kind of hardware (CPU, Metal, CUDA, Vulkan and others). Its core is C; most backends are C++ (Metal adds Objective-C and Metal shading language, CUDA adds .cu files).src/, libllama: everything that knows what an LLM is: loading a model file, one graph builder per architecture in src/models/, the KV cache, batches, the tokenizer, samplers. All C++.include/llama.h, the public C API (1,774 lines): every program, and every binding from Python, Go or Swift, goes through it.common/ (argument parsing, chat templates, helpers shared by the tools), tools/ (llama-cli, llama-server, llama-bench, llama-quantize), examples/ (small programs; simple/simple.cpp is the one to read first), gguf-py/ (the Python package that writes model files), tests/ and vendor/ (third-party code such as the HTTP library).
Of lines, are C++ and C, plus headers shared by both; of the CPU backend's lines, mostly hand-vectorised kernels for each processor family, you will read about 200.
torch/) over a C++ tensor library (ATen) with one backend per device. Here the "Python API" is the C header llama.h, and the tensor library is ggml. The Python package llama-cpp-python wraps exactly that header with ctypes.How to read it: start from the smallest program that works (examples/simple/simple.cpp), follow each call one level down with grep -rn "name(" src ggml, skip every backend you are not running, and read declarations in headers before definitions. When a log line puzzles you, grep for its text: the code that printed it is the explanation (section 5).
git ls-files at the pinned commit (src/cl/code/repo_map.py). Hover or tap a bar.llama.cpp builds with CMake (the build itself is taught on C++: the essentials): CMake asks questions about the machine (which compiler, is the Accelerate framework there, is Metal there) and writes a plan for Ninja, which runs the compiler in parallel. Each backend is one option() line, chosen at build time:
| Option | Default here | What it changes |
|---|---|---|
GGML_METAL | ON | Apple GPU backend; -ngl 99 at run time then puts all layers on the GPU |
GGML_CUDA | OFF | NVIDIA backend; needs the CUDA toolkit (nvcc); the kernels are Topic: cuda-and-gpu-programming's subject |
GGML_NATIVE | ON | Compile for this exact processor (-mcpu=native): fast here, may crash on an older machine |
GGML_CPU_REPACK | ON | Rearrange quantised weights at load time for faster CPU kernels (section 5) |
GGML_LLAMAFILE | ON | Extra matrix-multiply kernels from the llamafile project (tinyBLAS) |
CMAKE_BUILD_TYPE | Release here | A Debug build is compiled at -O0, without optimisation, many times slower: never time one (C++: the machine underneath, section 5, shows what -O2 does to a loop) |
What the build found: OpenMP not found (Apple's clang ships without it), so ggml uses its own thread pool (section 9); Accelerate, Apple's BLAS library, became a backend of its own, which only takes matrix products where every side is at least 32 long (a long prompt, not one token). Each backend became its own shared library, libllama.dylib on top.
Accelerate converts the weights to float first. The libraries are libggml-cpu.dylib, libggml-metal.dylib and libggml-blas.dylib, linked together by libggml.dylib, which keeps the list of available backends. Building steps took s with 4 parallel jobs on the busy laptop.
What the configure step found, and what the build produced (real output, filtered to the interesting lines):
pip install llama-cpp-python runs this same CMake build for you (through scikit-build); its CMAKE_ARGS="-DGGML_CUDA=on" environment variable is how you pass these options from pip.Start where a user starts: examples/simple/simple.cpp, 238 lines. The setup loads the weights, tokenizes the prompt, and creates a context (the KV cache and compute buffers for one conversation) and a sampler (the rule that picks the next token). The loop runs the model on the batch, samples one token, prints it, and feeds it back as the next batch of one:
What it printed on this laptop, with the model on the CPU (-ngl 0; see the predict box below):
llama_model *, llama_context * and llama_sampler * point to types whose fields you never see; you create each with one function and free it with another (llama_model_free, llama_free, lines 232 to 235). C is what lets Python, Go or Swift call the library: a C function has one agreed calling convention, while C++ names and layouts differ between compilers (the ABI, C++: the machine underneath, section 11).include/llama-cpp.h wraps each handle in a std::unique_ptr with a custom deleter, so the free call cannot be forgotten (C++: ownership, moves and object lifetimes, section 4).unique_ptr, and the ordinary C++ around themOrdinary modern C++ around it: std::string and std::vector<llama_token>, a range-for loop over the tokens, auto, and try/catch (...) around std::stoi. The size query on line 109 is a C idiom: call llama_tokenize once with no buffer, and it returns minus the number of tokens it needs.
transformers this is model = AutoModelForCausalLM.from_pretrained(...), tok(prompt), then model.generate(...), and the garbage collector frees everything. Here every object you create, you destroy, and the generation loop that generate hides is 35 lines you can read.Predict. simple.cpp sets int ngl = 99; (line 33) and passes it as model_params.n_gpu_layers. On this Mac, where do the layers run if you do not pass -ngl?
-ngl 99 logged offloaded 31/31 layers to GPU (30 blocks plus the output layer) and printed a different continuation: . The GPU adds the same numbers in a different order, rounding differs in the last bits, and greedy sampling (always the top score) flips where two scores were nearly tied: floating-point addition is not associative (C++: the machine underneath, SIMD section). This page passes -ngl 0 to stay on the CPU, the code we read; when studying the CPU path, check the log says no layers were offloaded.GGUF is llama.cpp's one-file model format: weights plus architecture, tokenizer and chat template. What it holds and how it compares with safetensors belong to Local and on-device inference (section 3); here we read it as code. Every integer has a fixed width and is little-endian, and a string is a 64-bit length then the bytes, so any language reads it: a complete reader is 41 lines of Python, standard library only.
gguf.h writes it down, the 41-line reader and its outputThe project's own Python package, gguf-py (used by the converters that turn Hugging Face checkpoints into GGUF), reads the same thing and adds names for the types:
Three details matter in the C++ that consumes it. Shapes are stored innermost first: token_embd.weight has ne=[576, 49152] where PyTorch says (49152, 576). Offsets are relative to the start of the data section, which begins at byte , the end of the header rounded up to the alignment of 32 (so every tensor can be loaded with aligned SIMD reads). Sizes follow from the type: Q8_0 stores 32 weights in 34 bytes, so the embedding table is 576 × 49,152 / 32 × 34 = bytes. The C++ reader computes the byte strides from the same numbers:
gguf_reader struct with overloaded read() functions per type, std::vector and std::string for the values, behind a C API. Reads whose length comes from the file sit in try/catch (std::bad_alloc &) and every count is checked against SIZE_MAX before allocating, because a corrupt or malicious file can claim a string of 263 bytes: untrusted binary input is where C and C++ code gets exploited (undefined behaviour, C++: the essentials).Predict. The model has 134.5 million parameters stored mostly as Q8_0. Before looking: is the file bigger or smaller than 134.5 million bytes, and by roughly how much?
8.51 BPW (bits per weight).llama_model_load_from_file reads the header, creates one ggml tensor per weight, and does not read the 143 MB of weights: it maps the file, so nothing is read until a page is touched and a second process mapping the same model shares the pages (mmap: Virtual memory; mapped against read, measured: Local and on-device inference, section 3). Each tensor then points straight into the mapping:
(uint8_t *) mapping->addr() + weight->offs is pointer arithmetic: the base address of the mapped file plus the tensor's offset, cast to bytes so that adding offs moves offs bytes. No copy, no allocation. The std::async lambda is an optional parallel check of the bytes.
Now grep the log, and the code explains each surprising line. The first one:
CPU_REPACK model buffer size = 136.27 MiB. A second copy of almost all the weights: at load the CPU backend copies every Q8_0 matrix into an interleaved layout, four rows woven together, because its fastest kernel reads four rows in one stream (section 10). The layout is picked at run time from the processor's features: the M1 has dotprod (the SDOT instruction) but not i8mm (sysctl hw.optional.arm: FEAT_DotProd: 1, FEAT_I8MM: 0), so 4x4.token_embd.weight (q8_0) (and 61 others) cannot be used with ... CPU_REPACK. The 61 others are the 32-bit norm vectors. The embedding table stays in the mapping because row lookups (GET_ROWS: fetch row number token id) need the plain layout; the output projection tied to it is created a second time (TENSOR_DUPLICATED) and that copy, used for a matrix product, is repacked.model type = 256M for a 135M model. The label is a guess from the number of layers: 30 layers is SmolDocling's size, so every 30-layer Llama-style model is labelled 256M. A cosmetic bug, but a good habit: when a log line surprises you, find the code that printed it.Predict. With repacking, how much memory do the weights take in total, and what happens to the mapped copy of the repacked tensors?
--repack 0 (in llama-bench; use_extra_bufts = false in the API) trades that copy for a slower kernel.Everything in ggml is a struct ggml_tensor, a plain C struct (no methods, no constructor):
ne holds up to four sizes, innermost first (ne[0] is the dimension whose elements are adjacent in memory); nb the matching strides in bytes; data the first byte; op and src say how this tensor is computed from others (section 7); view_src and view_offs mark a tensor that borrows another's memory. Element (i0, i1, i2, i3) lives at data + i0*nb[0] + i1*nb[1] + i2*nb[2] + i3*nb[3], which is why views are free: a transpose swaps two sizes and their strides and touches no data.
A real tensor from our run: layer 0's K cache, cache_k_l0, F16, 192 numbers per position for 256 positions, which attention reads as 3 heads of 64 through a view of the same bytes (section 11). Predict the byte offset where head 1 starts, then switch the view on the right.
ggml_transpose in the sourcea.strides (bytes) and PyTorch's a.stride() (elements) are the same idea, and a.T is the same free view. Two differences: sizes innermost first (a weight PyTorch calls (out, in) is {in, out}), and a quantised type has no per-element stride: nb[0] is the size of a 32-weight block, so only whole blocks are addressable.Nothing is computed when you call an operation. ggml_mul_mat does not multiply: it creates a result tensor, records op = GGML_OP_MUL_MAT and its two sources, and returns.
The result is {a->ne[1], b->ne[1], ...}: each row of a (the weight, one output feature per row) times each row of b (one token per row), so both operands are read along their contiguous dimension. Calling operations builds a graph; running it is section 8, and values exist only after it runs.
torch.compile, torch.fx or jax.jit: calls record a graph of operations; a later step plans memory and runs it. PyTorch's default eager mode is the opposite: each call computes immediately.Each architecture has a file in src/models/ (157 .cpp files at this commit). Our model is a Llama, so its forward pass is written in src/models/llama.cpp. The class is a template:
template <bool embed>: one source, two compiled classes, graph<false> for text and graph<true> for embeddings. The last two lines force both to be compiled (explicit instantiation) so the code can stay in this .cpp instead of a header (templates: C++: classes, templates and the standard library).std::conditional_t<embed, A, B> picks a type at compile time, and if constexpr (embed) picks a branch at compile time: the branch not taken is not compiled into that version at all.std::unique_ptr / std::make_unique (line 95): the graph object is owned and freed automatically. Inheritance: graph<embed> derives from llm_graph_context, which holds the shared building blocks (build_norm, build_attn, build_ffn).auto [Qcur, Kcur, Vcur] = build_qkv(...) names the three tensors a function returns (Python's q, k, v = build_qkv(...)).The attention block of each layer: project to Q, K and V, rotate Q and K by position (RoPE), attend.
Then the residual add, the feed-forward block, and after the last layer the output projection, compiled only into graph<false>:
static_assert buysFour features as llama.cpp uses them (src/cl/code/features.cpp): a block size checked by static_assert, an interface written two ways (a C struct of function pointers, as in the sampler and the backends, and a C++ class with virtual functions, as in the KV cache), if constexpr with std::conditional_t, and a structured binding.
The second compile shows what static_assert buys: someone adds a field to a block, the compiler computes 40 == 34 (the float also brings 2 bytes of padding) and refuses to build. A file written with the old layout would otherwise be read as garbage, silently.
llama-eval-callback (in examples/) prints every node as it is computed. Our token was "Paris" (id ), decoded on the CPU: nodes, per layer. The figure builds layer 0 from that printout, node by node, in the order build_attn and build_ffn wrote them, then runs it:
embd holds this token's 576 numbers, fetched from the embedding table by GET_ROWS. RMS_NORM then MUL by attn_norm.weight is build_norm: two nodes.MUL_MAT nodes are Q, K and V, one per weight matrix (the glass plates: attn_q {576, 576}, attn_k and attn_v {576, 192}). RESHAPE reads Q as 9 heads of 64 and K and V as 3; two ROPE nodes rotate Q and K by position.VIEW flattens K and V back to 192 numbers, and SET_ROWS writes this token's K and V into the cache tensors cache_k_l0 and cache_v_l0 (section 11).VIEW and three PERMUTE nodes give Q and the whole cache the shape attention wants, {64, 3, 256} per head for the cache: sizes and strides only (section 6), no data moved. They are dashed in the figure.FLASH_ATTN_EXT is the whole attention in one fused operation; a RESHAPE back to 576, the output projection (MUL_MAT by attn_output), and the residual ADD of the layer's input.build_ffn: RMS_NORM and MUL again, MUL_MAT gate and up (1,536 rows each), SWIGLU, MUL_MAT down back to 576, and the second residual ADD.Of the nodes, are matrix products: 7 per layer × 30 layers + 1 output projection. They hold nearly all the arithmetic, which is why sections 9 and 10 are about them.
llama-eval-callback printed it: the input, layer 0, the last layer and output, the count by operationbuild_attn and build_ffn became a node, and more than a third of them move no dataPredict. For a single token, how many rows of weights does one forward pass read? (Rows: q 576, k 192, v 192, o 576, gate 1536, up 1536, down 576 per layer; output 49,152.)
llama_process, the C entry point, forwards to llama_context::decode, which splits the batch into micro-batches, finds KV cache room for them, and calls process_ubatch for each: build the graph (or reuse the last one), allocate it, copy the inputs in, compute.
llama_process and process_ubatch in the sourceGraph reuse. For the next token the graph is the same except for its inputs, so can_reuse checks that the shapes match and, if they do, only set_inputs runs. Our run logged graphs reused = : the prompt's graph was built, the first one-token graph was built, and the other 6 decoding steps reused it.
Memory planning. The allocator (ggml-alloc.c) gives every intermediate an address in one buffer: walking the nodes in order, it counts how many later nodes still read each tensor, and when the count reaches zero the memory goes to the next node. From the log: CPU compute buffer size = MiB for every intermediate of a forward pass, against 143 MB of weights. The plan is made once (sched_reserve, at context creation, for the worst case) and reused.
ggml-alloc.cThe scheduler and backends. A backend is an object that can run operations on one device. In C, "an object with methods" is a struct of function pointers, one per method, filled in differently by each backend:
The scheduler (ggml_backend_sched) sends each node to the backend that already holds its data, so operations on weights go where the weights are, and cuts the graph into splits, runs of consecutive nodes on one backend with copies between them. With repacking off and a 64-token prompt, the graph is cut into pieces: each large matrix product goes to the BLAS backend (Accelerate), the rest stays on the CPU. With repacking on, the weights live in a buffer only the CPU backend understands: 1 split.
For one token (tg bs=1) it is 1 split even with repacking off, because BLAS only takes products of at least 32 rows each way (section 2). On the GPU (-ngl 99) the log showed splits = : the embedding lookup runs on the CPU, where the embedding table stayed ( MiB), and the rest on Metal.
Predict. The 302-split graph runs at 1 thread. Is it faster or slower than the 1-split repacked graph, for a 64-token prompt?
Illustrative durations: thread 3 made slow on purpose; time unit, one chunk on a fast thread; the scheme and the 16 chunks are the real ones (counted).
The CPU backend runs the graph with a pool of threads (4 by default, GGML_DEFAULT_N_THREADS), simply and strictly: every thread walks every node, does its share, then waits at a barrier before the next node. The loop each thread runs:
Views, reshapes and permutes are skipped (ggml_op_is_empty), so of the nodes, are real operations: up to barriers per token, and the slowest thread sets the pace at each.
The barrier is a few atomic operations (a few fewer barriers run when fused operations run as one); a waiting thread spins instead of sleeping, which is fast when every thread has a core and wasteful when it does not. Inside a node, each operation splits its work with two numbers in params: ith, this thread's index, and nth, the number of threads (the root page's Design space tab quotes the two lines from ops.cpp).
For matrix products a static split is fragile: if one thread is slow (an efficiency core, or another program takes its core), everyone waits. So the rows are cut into more chunks than threads, and a thread that finishes takes the next chunk from a shared atomic counter; the repacked kernel aims at 4 chunks per thread. Measured with call counters (section 10): every decoded token makes kernel calls = matrix products × chunks (4 threads × 4). Predict: with one thread at half speed, how much later than the others does a fixed four-way split finish?
ith. One time unit in, threads 0 to 2 have finished chunks 0 to 2 and the slow thread 3 is half-way through chunk 3. The fast three call atomic_fetch_add(¤t_chunk, 1) and get 4, 5 and 6.The atomics are memory_order_relaxed: a thread only needs a unique chunk number, not to see other threads' writes in order (memory orders: C++: the machine underneath, section 8).
GGML_CACHE_LINE, which is 64 on every platform, but the M1 Pro has 128-byte lines (measured in C++: the machine underneath, section 8). So n_barrier_passed and current_chunk share one 128-byte line, as do n_graph and n_barrier: the false sharing the alignment was meant to prevent. The cost per token was not measured here; it is a reading, not a benchmark.Compiling the struct's own definition and printing the offsets (src/cl/code/threadpool_offsets.sh; the pool is allocated with vm_allocate, so its start is page-aligned): with 128-byte lines, n_graph (byte ) and n_barrier () share the line from byte 128, and n_barrier_passed () and current_chunk () share the line from byte 256.
Generation peaks at a few threads: a token reads 143 MB once, so once memory bandwidth is the limit, more threads add barrier waiting, not speed. And 8 threads collapse ( tokens/s against at 4) on a laptop where other programs already used most cores: one thread that loses its core stalls the other seven at each of hundreds of barriers per token. On a quiet machine 8 threads would do much better; on a shared server, use fewer threads than free cores, and benchmark with repetitions (llama-bench -r 5), every sample and the load average.
llama-bench; dots are the individual runs. Measured while the laptop was busy (load average to on 10 cores).A quantised type stores weights in blocks: 32 weights share one scale d, and each weight is a small integer q, with weight ≈ d × q. Why quantise, the block types and what they cost in accuracy belong to Quantization and precision and Local and on-device inference (section 4, which also draws the k-quant block); here we read the code. The blocks are plain C structs:
The figure follows one real block from the file to the kernel that reads it on this M1 (the code for each step is below it):
d, then 32 one-byte integers q. 34 bytes for 32 weights, 8.5 bits each.q is a signed byte, and the weight is d × q with d = . The largest magnitude, weight , is stored as 127, the end of the int8 range: that is how the quantiser chose d.q − 8) × d with d = , two weights per byte, 2 + 16 = 18 bytes. The red marks are each weight's error; over the whole matrix the relative RMS error is .block_q8_0x4: their 4 scales first, then their 128 weight bytes interleaved 4 at a time, 136 bytes (section 5's CPU_REPACK copy). Only row 0's block was read from the file, so rows 1 to 3 are drawn without values.vdotq_laneq_s32 multiplies 4 activation bytes (one lane) against 4 bytes of each of the 4 rows: 16 multiply-adds into four 32-bit sums.ggml_half is a 16-bit float stored as a uint16_t (C has no portable half type). The static_assert pins the size: 34 bytes for Q8_0 (8.5 bits per weight), 18 for Q4_0 (4.5 bits: two 4-bit values per byte). The reference quantiser for Q8_0 is ten lines: find the largest magnitude, divide by 127, round each weight.
The bytes below are the first 34 bytes of blk.0.attn_q.weight in the GGUF file (layer 0's query projection, row 0, weights 0 to 31), read by src/cl/code/quant_demo.py; the arithmetic follows quantize_row_q8_0_ref and quantize_row_q4_0_ref in ggml-quants.c, line for line.
The first 2 bytes (highlighted) are the scale d as a 16-bit float, little-endian: . Each of the next 32 bytes is one weight as a signed 8-bit integer q; the weight is d × q. Tap a byte.
The file's weights are already Q8_0, so requantising them as Q8_0 must give back the stored bytes exactly: that is our check that the Python matches ggml (it does). Q4_0 then shows what 4 bits cost on the same input.
amax = max |x| = (the outlined bar).d = amax / 127 = , stored as a 16-bit float. The largest weight maps to ±127, the end of the int8 range.q = roundf(x / d): 32 integers from −127 to 127, the labels under the bars.d × q (orange dots) lands exactly on every bar, maximum error , because these weights were Q8_0 already: our Python reproduces ggml's rounding.d + 32 bytes of q = 34 bytes, identical to the bytes in the file above.max = the weight with the largest magnitude, sign kept: (weight ).d = max / −8 = . Dividing by −8 maps the extreme to −8, stored as q = 0 with no error beyond the rounding of d to 16 bits; the other end of the range reaches only +7.q = min(15, (int8_t)(x / d + 8.5)): integers 0 to 15, the labels. Adding 8.5 then truncating rounds to the nearest of 16 levels and shifts them to be non-negative.(q − 8) × d (orange dots) misses most bars; red lines are the error. Maximum , RMS , against weights of typical size .qs[j] = q[j] | q[j + 16] << 4: byte j holds weight j in its low 4 bits and weight j + 16 in its high 4 bits. 2 + 16 = 18 bytes.Over the whole matrix (576 × 576 weights, 10,368 blocks), Q4_0 has a relative root-mean-square error of against the Q8_0 weights it was made from: about a tenth of the signal.
A matrix-vector product is one dot product per weight row. ggml quantises the activations to Q8_0 too, so the inner loop multiplies 8-bit integers and applies the two scales once per block. In the NEON version of ggml_vec_dot_q8_0_q8_0, ggml_vdotq_s32 is the SDOT instruction: 16 byte pairs multiplied and summed in groups of four into four 32-bit lanes, 16 multiply-adds in one instruction.
vld1q_s8 loads 16 signed bytes into one 128-bit register. Two blocks per iteration, two accumulators (sumv0, sumv1), so two chains of additions run in parallel: the same tricks as the NEON dot product in C++: the machine underneath (section 6), which uses float lanes where this uses bytes. GGML_RESTRICT is C's restrict: a promise that x and y do not overlap, so the compiler need not reload after each store.
The middle of the NEON function; the full function also has SVE and i8mm paths behind #if:
To check, we built a copy of llama.cpp with a counter at the top of each candidate kernel (src/cl/code/instrument.py; the pinned clone stays untouched) and ran the same prompt:
ggml_vec_dot_q8_0_q8_0 runs 0 times. The weights were repacked at load (section 5), so every product goes to ggml_gemv_q8_0_4x4_q8_0 ("matrix times vector", four interleaved rows per step) for single rows and ggml_gemm_q8_0_4x4_q8_0 for groups of four token rows. The loop that really did the work for every token on this page:
The repacked block is a template with two integer parameters (block<8, 4>, a distinct type computed at compile time, which C cannot express): 4 rows' scales and their 32 weights each, interleaved 4 bytes at a time (136 bytes). Each iteration loads 128 weight bytes and the activation block once, and vdotq_laneq_s32 multiplies 4 activation bytes (one "lane" of a register) against 4 bytes of each of the 4 rows: 16 multiply-adds, 4 rows advanced together; eight cover the block, one fused multiply-add applies the scales. Against vec_dot, the activation is loaded once per 4 rows instead of once per row, and the weights stream from one contiguous buffer: fewer loads per multiply, which is what the repack copy buys.
The arithmetic checks out exactly: one decoded token is products × 16 chunks = gemv calls.
--repack 0 (tinyBLAS for the prompt, vec_dot for single rows)The 5-token prompt: 4 rows go through gemm and the fifth through gemv, except in the last layer, where only the last token's row is kept (the GET_ROWS in section 7), so its three feed-forward products and the output projection have one row: (211 − 4) × 16 = gemm calls.
With --repack 0 the generic path runs: ggml_compute_forward_mul_mat ( calls = 211 products × 4 threads × 2 runs, a warm-up and the measured one) offers each product to llamafile's tinyBLAS, which takes the prompt's products but declines single rows (if (n < 2) return false;), and ggml_vec_dot_q8_0_q8_0 computes those one output at a time: (49,152 + 1,536 + 1,536 + 576) rows × 2 runs = calls.
ggml_vec_dot_q4_0_q8_0 from the scalar version to the NEON one" is a good reading exercise, but on an Apple Silicon Mac with the default build that function does not run for Q4_0 weights either (counters: gemv_q4_0_4x4 and gemm_q4_0_4x4 do the work; vec_dot_q4_0_q8_0 runs only with --repack 0, for single-row products). Read the vec_dot functions to learn the idea; read arch/arm/repack.cpp to see the hot loop on this machine. Repacking, tinyBLAS, BLAS or a GPU backend may each take the product.Predict. We converted the model to Q4_0 (llama-quantize --allow-requantize ... Q4_0). The file shrinks from 145 MB to about what, and does the greedy continuation of "The capital of France is" stay the same?
llama-quantize keeps that tensor at higher precision, wanted Q6_K, and logged ncols 576 not divisible by 256 (required for type q6_K) -> falling back to q8_0). The text changed: instead of "... Paris. Paris is a city known for". Requantising an already quantised model, without an importance matrix, on a model this small, costs visible quality: the block opened above measures a relative error on one weight matrix. Decoding was faster: against tokens/s at 4 threads (medians, busy laptop), since fewer bytes are read per token.What the KV cache is and why it exists is taught by Batching, KV cache and scheduling (and how it grows with context by Long context); here is how llama.cpp writes it. It is a C++ class with virtual functions behind an abstract interface, llama_memory_i (a plain cache, a sliding-window one, one for recurrent models), storing one K and one V tensor per layer. Writing this token's K is a SET_ROWS node into the cells chosen for this batch; reading K for attention is a 4-dimensional view of the same tensor (section 6), {64, 3, 256} in our trace: 64 numbers per head, 3 KV heads, 256 cells.
SET_ROWS nodes write their K and V into 5 cells.get_k returns a 4-dimensional view {64, 3, 256} of the same bytes: 3 heads of 64 numbers per cell. FLASH_ATTN_EXT reads K and V through such views, with no copy.simple.cpp asked for 12; the context rounds up to 256, so the cache is 2 × 30 × 256 × 192 × 2 bytes whatever the run uses: mostly empty here.SET_ROWS write, in the sourceSize, from the log: KV buffer size = MiB = 2 (K and V) × 30 layers × cells × 192 numbers × 2 bytes (F16) = bytes. simple.cpp asked for a context of 12 tokens (prompt + 8 − 1); the context rounds it up to cells (cparams.n_ctx = GGML_PAD(cparams.n_ctx, 256); in llama-context.cpp).
Batches. A batch is a list of tokens, each with a position, a sequence id (which conversation) and a flag saying whether its logits are wanted; simple.cpp wants only the last token's, which lets the graph drop the other rows before the output projection.
simple.cppSampling (the rules: Sampling and decoding). Samplers are C style, each filling in a struct of function pointers. Greedy takes the highest logit:
So one codebase writes interfaces two ways: the KV cache as a C++ class with virtual functions, samplers and backends as C structs of function pointers, because they are part of the C API other languages call (section 7's small program does both side by side).
llama-server (in tools/server/, 20,000 lines of C++) serves the model over HTTP with an OpenAI-compatible API (its options, slots and modes, measured: Local and on-device inference, section 6). Several requests share one context, each in a slot (a C++ struct with owning smart pointers), and every step puts the next token of every active slot into one batch (continuous batching: Batching, KV cache and scheduling). The step calls the same llama_process as simple.cpp, inside a lambda capturing by reference ([&]), handed to the task queue so metrics requests are answered while the model runs:
A real request to the server started with 2 slots (-np 2) on the CPU:
The same 8 tokens as simple.cpp, about ms each instead of : the server adds HTTP, JSON, a task queue and per-token work for streaming and stop strings, and ran on the same busy laptop. A Python service calling it only sees the JSON.
Files the token has passed are shaded, the current ones outlined; files faded are skipped in this mode.
Put together, the path of one generated token on the CPU, file by file. Switch between the prompt (the first call, which builds everything) and the next token (which reuses the graph): the same path, with four stops skipped. Before it plays, predict which stops the next token can skip.
simple.cpp: the prompt is tokenized into 5 ids, and batch_set_tokens puts them at positions 0 to 4 and asks for logits only for the last one. llama_process, the C entry point, calls the C++ method llama_context::decode, which splits the batch into micro-batches (one here) and reserves KV cells for its 5 tokens.can_reuse is false. graph<false>'s constructor (models/llama.cpp) loops over 30 layers calling build_norm, build_qkv, ggml_rope_ext, build_attn and build_ffn; in ggml.c each call only records a node: nodes, of them matrix products.ggml-backend.cpp sends every node to the backend that holds its weights; all weights are in CPU buffers (mapped and repacked), so the graph is 1 split. ggml-alloc.c walks the nodes in order and releases a tensor's memory when its last reader has run: every intermediate fits in MiB.set_inputs copies token ids, positions and KV cell indices into the graph's input tensors; in the graph, cpy_k (llama-kv-cache.cpp) is a SET_ROWS node that will write each token's K into its cell.graph_compute calls the CPU backend through the ggml_backend_i table of function pointers; in ggml-cpu.c each of the 4 threads loops over all nodes, skipping views, with a barrier after each of the real operations.repack.cpp each product quantises its input rows to Q8_0, cuts the weight rows into 16 chunks taken from an atomic counter, and per chunk calls gemm (ggml_gemm_q8_0_4x4_q8_0) for 4 token rows and gemv for the 5th: gemm and gemv calls measured for the prompt, 8 vdotq_laneq_s32 per 32-weight block.FLASH_ATTN_EXT reads K and V through a 4-dimensional view {64, 3, cells} of each layer's cache: no copy.GET_ROWS), and llama-context.cpp copies 49,152 floats out of the graph. The greedy sampler scans them for the largest: the first generated token is " Paris". llama_token_to_piece turns the id into text. Prompt time measured: ms for 5 tokens.can_reuse is true: building, scheduling and planning are skipped. Measured: graphs reused = over the run.gemv. One token row: gemv calls per token = products × 16 chunks. This loop does every multiply of the token, every weight of the model once.SET_ROWS; attention reads them with the 5 before through the same kind of view.Counts and timings come from the runs on this page (CPU, 4 threads, SmolLM2-135M Q8_0, prompt "The capital of France is").
And the clock, from the run of simple.cpp (llama_perf_context_print):
| Phase | Measured | What it is |
|---|---|---|
| Load | ms | From the start of model loading to the end of the first evaluation (that is how llama-context.cpp measures it, line 796): read the header, map the file, repack 136 MiB of weights, create the context, plan the graph's memory, and run the prompt |
| Prompt (5 tokens) | ms, ms per token | One forward pass over all 5 tokens; reading the weights once serves all five rows |
| Each next token | ms ( runs) | One forward pass for one row: every weight read for a single dot product |
Per token, the prompt is cheaper than generation because the weights read from memory are reused across five rows: more arithmetic per byte (the roofline: Performance math). The GPU shows the same split more sharply: on Metal a 64-token prompt ran at tokens/s, against on one CPU thread, while generation ran at tokens/s, slower than the CPU's : for a model this small, launching hundreds of tiny GPU kernels per token costs more than the arithmetic. Bigger models change that; measure your own.
repack, splits and offloaded lines (sections 5, 8, 10).ne[0] is contiguous; ggml_mul_mat(a, b) multiplies rows of a by rows of b (section 6).llama-eval-callback, after the graph runs (section 7).-ngl 0 to study the CPU path; the default offloads every layer (section 3).model type = 256M for a 135M model (section 5).One shallow clone at a pinned commit, one 145 MB model, one laptop under load; the scripts in src/cl/ reproduce every output on this page.
Source pinned at commit (); every excerpt links to its exact lines on GitHub at that commit. The model is SmolLM2-135M-Instruct in Q8_0 (145 MB, sha256 checked). Every log line, count and timing is real, recorded on this Apple M1 Pro (8 performance and 2 efficiency cores, macOS 27) on 2026-10-05 while the laptop was busy (load average to ), so timings carry noise; the scripts that reproduce everything are in src/cl/ in the repository.
Model: , sha256 , bytes; repository revision of the model files 2024-10-31. Built with Apple clang 17 (Command Line Tools, macOS 26 SDK), CMake 4.4.4, Ninja; Python 3.13 for the GGUF scripts. Kernel counts come from an instrumented copy built without Metal and BLAS (the CPU path is the same as -ngl 0 for these prompt sizes, where BLAS is not used). Not done: profiling with Instruments or perf (Instruments did not start on this machine), and a quiet-machine benchmark. Versions and every command: src/cl/versions.txt and src/cl/run_all.sh; src/cl/gen_data.py turns the outputs into this page's data, and the page shows nothing else.
Generated text, as printed: CPU ; Metal ; Q4_0 on the CPU .
Call counters from the instrumented copy (src/cl/code/instrument.py inserts one atomic increment at the top of each listed function and prints the totals when the program exits; built without Metal and BLAS):
Load averages before and after each llama-bench group (1, 5 and 15 minute averages; 10 cores). The laptop ran other work throughout, so treat single samples with suspicion and compare medians only where they differ by much more than their spread.
The build, undefined behaviour and sanitizers, libraries and the C API boundary: what this page assumes.
RAII and unique_ptr with custom deleters, the pattern llama-cpp.h wraps every handle in.
Virtual functions, templates, lambdas and the standard containers that sections 7, 11 and 12 read.
Cache lines, SIMD, memory order and false sharing, measured on the same M1 Pro: the effects that decide sections 5, 9 and 10.
GGUF and the other formats, mapping against reading, the GGUF quantisation types measured, llama-server, Ollama and MLX.
Number formats and quantisation methods: why Q8_0 and Q4_0 lose what they lose.
The ideas behind sections 11 and 12: the KV cache, continuous batching, samplers, cache growth with context.
Why decode is bound by memory bandwidth and prefill by arithmetic: section 13's clock explained.
What ggml-cuda does on NVIDIA GPUs: kernels, memory, tiling.
The root: the languages compared; its Design space tab quotes llama.cpp excerpts from the same commit. 10 min
Start with examples/simple/simple.cpp, then src/llama-context.cpp (process_ubatch), then ggml/src/ggml-cpu/. 2 to 4 hours for a first pass
Every type and metadata key (ggml repository). 20 min
Every backend's options. 15 min
Hugging Face blog, Xuan Son Nguyen: contexts, graphs and backends with a small program. 25 min