C++: reading llama.cpp, one token through the code

A guided reading of a real C/C++ inference engine: build it, run a small model, and follow one token from the prompt to the sampled word through the model file, the ggml graph, the scheduler, the thread pool and the SIMD kernel that really runs, with every excerpt pinned to one commit and every count measured on an Apple M1 Pro. Reading: 37 min, plus 39 in closed details. Data as of October 2026.
The idea in one sentenceOne generated token is a ggml graph: libllama builds it once from the model file, ggml plans its memory once, and a pool of threads walks it node by node, spending its arithmetic in one SIMD kernel that reads weights repacked at load time, a kernel most guides never mention.

One token through the layers

  1. Your program. 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.
  2. libllama. 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.
  3. ggml: graph, memory, scheduler. In 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.
  4. The thread pool. In 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.
  5. Matrix products. In 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.
  6. The kernel that runs. 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.
  7. Back up to the sampler. 49,152 logits are copied out of the graph, and the greedy sampler in 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.

ggml: llama.cpp's tensor library: tensors, the compute graph, the file format and the backends.
Backend: the code that runs operations on one device (CPU, Metal, CUDA, BLAS).
Graph, node: the recorded forward pass; each node is one operation on tensors.
ne, nb: a ggml tensor's sizes and byte strides, innermost dimension first.
Split: a run of consecutive nodes on one backend, with copies between splits.
Repack: copying quantised weights at load into an interleaved layout for a faster CPU kernel.
Chunk: a slice of a matrix product's rows that a thread takes from a shared atomic counter.
Barrier: a point no thread passes until all have arrived; one after every operation.
Q8_0 block: 32 weights as 8-bit integers sharing one 16-bit scale, 34 bytes.
Slot: one request in progress inside 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).

In one screen

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.

Each stop: where it is, the features it uses, the one thing to take away
StopWhereFeatures it usesTake away
The mapggml/, src/, tools/C core, C++ around itTwo libraries: ggml (tensors, kernels, backends) and libllama (models, KV cache, sampling) behind a C API
BuildingCMakeLists.txtCMake options, shared librariesBackends are chosen at build time; one .dylib per backend
The APIexamples/simple/simple.cppC API, opaque pointers, unique_ptr deletersLoad, tokenize, decode, sample, free: the whole program in 240 lines
GGUFggml/src/gguf.cppfixed-width binary I/O, exceptionsA header of key-values and tensor descriptions, then aligned raw bytes; 41 lines of Python read it
Loadingsrc/llama-model-loader.cppRAII mmap, pointer arithmeticWeights are mapped, not read; on this M1 most are then copied into a faster layout
Tensorsggml/include/ggml.hplain C structs, stridesA tensor is sizes, byte strides and a pointer; a view or transpose moves no data
The model graphsrc/models/llama.cpptemplates, if constexpr, structured bindingsModel code builds a graph of nodes; nothing is computed yet
Graph to computesrc/llama-context.cpp, ggml-backend.cppfunction-pointer interfaces, reference countsBuild once, reuse; all intermediates of a token fit in MiB
Threadsggml-cpu/ggml-cpu.cpthreads, atomics, barriersEvery thread walks every node; matrix rows are split into chunks taken from an atomic counter
Quantised kernelsggml-common.h, quants.c, repack.cpppacked structs, static_assert, NEON intrinsics32 weights share one scale; the kernel that runs here is not the one most guides point to
KV cache and samplingllama-kv-cache.cpp, llama-sampler.cppvirtual classes and C vtables side by sideThe cache is one tensor per layer, read through a strided view
Servertools/server/lambdas, std::unique_ptr membersMany requests, one batch per step
The surprise of this tour
Guides (and older notes in this knowledge base) say: to see the hot loop, read 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.

1. The map: what is where

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.
The rest of the tree

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.

From Python
It is the same shape as PyTorch: a Python API (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).

Half the code is C++, and the CPU backend alone is about 95,000 lines of hand-vectorised kernels

Lines per area, counted with git ls-files at the pinned commit (src/cl/code/repo_map.py). Hover or tap a bar.

2. Building it

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:


OptionDefault hereWhat it changes
GGML_METALONApple GPU backend; -ngl 99 at run time then puts all layers on the GPU
GGML_CUDAOFFNVIDIA backend; needs the CUDA toolkit (nvcc); the kernels are Topic: cuda-and-gpu-programming's subject
GGML_NATIVEONCompile for this exact processor (-mcpu=native): fast here, may crash on an older machine
GGML_CPU_REPACKONRearrange quantised weights at load time for faster CPU kernels (section 5)
GGML_LLAMAFILEONExtra matrix-multiply kernels from the llamafile project (tinyBLAS)
CMAKE_BUILD_TYPERelease hereA 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.

The libraries, the option lines and the real build output

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):


From Python
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.

3. The API and the smallest program

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):

The setup code, and the full output

C and C++ in this file
  • A C API with opaque pointers. 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).
  • RAII for C++ callers. 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).
The two lines that turn a C handle into a unique_ptr, and the ordinary C++ around them

Ordinary 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.

From Python
With 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?

4. GGUF: reading the model file

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.

The format as gguf.h writes it down, the 41-line reader and its output


The 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:

The alignment code, and this model's file drawn to scale
The file to scale. The header is bytes, mostly the tokenizer's 49,152 token strings and 48,900 merge rules; then padding to a multiple of 32; then tensors back to back. Tap a block.
C++ in gguf.cpp
A 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?

5. Loading: mmap, then a surprise copy

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.
Two more log lines explained: the weights not repacked, and a 135M model labelled 256M; the log and the source
  • 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?

6. ggml tensors: sizes, strides, a pointer

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 source
From Python
NumPy's a.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.

From Python
This is tracing, as in 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.

Three views, one buffer: only the strides change

7. The model as a graph

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:

C++ features, and why they are here
  • 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).
  • Structured binding: auto [Qcur, Kcur, Vcur] = build_qkv(...) names the three tensors a function returns (Python's q, k, v = build_qkv(...)).
The attention block and the output head in the source

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>:

Four features in one small program you can compile, and what static_assert buys

Four 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.

The real graph of one token

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:

  1. The input row, normalised. 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.
  2. Q, K and V. Three 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.
  3. Into the cache. A 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).
  4. Views cost nothing. Three more 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.
  5. Attention, then the residual. 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.
  6. The feed-forward block. 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.
  7. Built, not yet run. 31 nodes for this layer, 7 of them matrix products, and nothing computed: the graph is data. Thirty such layers plus the input and the output head make the whole graph.
  8. Then the CPU runs it, in order. The backend walks the nodes as listed, skips the 12 views, reshapes and permutes (more than a third of the layer), and computes the other 19, with a barrier after each (section 9): the data flows down the edges.

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.

Every node as llama-eval-callback printed it: the input, layer 0, the last layer and output, the count by operation

Each line of build_attn and build_ffn became a node, and more than a third of them move no data

Predict. 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.)

8. From graph to memory to compute

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 source

Graph 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.

The reference count in ggml-alloc.c
From Python
This is CPython's reference counting, done ahead of time: a tensor is freed when the last operation that uses it has run. PyTorch's caching allocator does it at run time, as tensors go out of scope.

The 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.

One token, the GPU, the first scheduling pass in the source, and the measured splits

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?

With chunks off a counter, one slow thread costs a little; with fixed shares it doubles the time

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).

9. The CPU backend: threads, barriers, chunks

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 in the source, and how an operation splits its work

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?

  1. Each thread starts on chunk 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(&current_chunk, 1) and get 4, 5 and 6.
  2. Whoever is free takes the next number. At t = 2 thread 3 finishes chunk 3 as the others finish 4 to 6, and all four take a number: 7, 8, 9 and 10.
  3. The slow thread simply takes fewer. At t = 3 the fast threads take 11, 12 and 13; thread 3 is still half-way through chunk 10.
  4. The last two chunks. At t = 4 everyone is free and only 14 and 15 are left: threads 0 and 1 take them, threads 2 and 3 go to the barrier.
  5. Done at t = 5. The slow thread did 2 chunks, the others 5, 5 and 4: one slow thread cost one time unit, against 4 units with four fast threads.
The chunking code: the generic version and the repacked kernel's

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).

A real mismatch on this machine
The thread pool aligns its counters to 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.
The thread pool struct, the alignment macro and the printed offsets

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.


Threads and speed

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.

Generation peaks at a few threads, and 8 threads collapse on a busy laptop

Median of 5 runs of llama-bench; dots are the individual runs. Measured while the laptop was busy (load average to on 10 cores).

10. Quantised blocks and the kernels that read them

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):

  1. One Q8_0 block, to scale. The first block of layer 0's query weights (row 0, weights 0 to 31) as the file stores it: a 2-byte scale d, then 32 one-byte integers q. 34 bytes for 32 weights, 8.5 bits each.
  2. The integers, as signed bars. 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.
  3. The same 32 weights as Q4_0. 16 levels instead of 255: weight = (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 .
  4. Repacked at load. The CPU backend weaves four rows' blocks into one 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.
  5. One SDOT, four rows. The token's activations are quantised to Q8_0 too. One 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.
  6. Eight cover the block. Eight such instructions use the 32 activation bytes once for all four rows; one fused multiply-add applies both scales, and four outputs come out together. The activation is loaded once per 4 rows instead of once per row.

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.

Open one real block: its 34 bytes, and the same 32 weights through the Q8_0 and Q4_0 quantisers, step by step

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.

  1. The input. The 32 weights of the block as real numbers (blue bars); the largest magnitude is weight , .
  2. Find the largest magnitude. amax = max |x| = (the outlined bar).
  3. Choose the scale. d = amax / 127 = , stored as a 16-bit float. The largest weight maps to ±127, the end of the int8 range.
  4. Round each weight. q = roundf(x / d): 32 integers from −127 to 127, the labels under the bars.
  5. Dequantise and compare. d × q (orange dots) lands exactly on every bar, maximum error , because these weights were Q8_0 already: our Python reproduces ggml's rounding.
  6. Store the block. 2 bytes of d + 32 bytes of q = 34 bytes, identical to the bytes in the file above.
Tap a bar for its numbers.

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.

The dot product, as most guides show it

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.

The portable reference version and the NEON version, read line by line

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:

What actually runs on this M1

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:

The function most guides point to ran zero times; a repacked kernel did every product

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 repacked block type, and where the kernel picks gemm or gemv

The arithmetic checks out exactly: one decoded token is products × 16 chunks = gemv calls.

The prompt's count, and what runs with --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.

Correction to the old notes and the root page's milestone
"Trace one call of 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?

11. KV cache, batches and sampling

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.

  1. Allocated once, for every layer. At context creation the cache gets one K and one V tensor per layer, 30 of each, every one 192 numbers (3 KV heads of 64) for each of 256 cells, in F16. Nothing is written yet.
  2. The prompt fills 5 cells. The 5 prompt tokens are computed together; in every layer two SET_ROWS nodes write their K and V into 5 cells.
  3. Each new token, one more cell. The decoded token's K and V go into one more cell of each of the 60 tensors; nothing already in the cache moves.
  4. Attention reads through a view. For layer 0, 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.
  5. Sized for 256 cells. 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.
The class declaration and the SET_ROWS write, in the source

Size, 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.

The batch helper in simple.cpp

Sampling (the rules: Sampling and decoding). Samplers are C style, each filling in a struct of function pointers. Greedy takes the highest logit:

The sampler interface and greedy's table of function pointers

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).

12. The server

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:

The slot struct, and one real request with the server's log

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.

From Python
This is the role vLLM or Text Generation Inference play in Python land: a scheduler that batches requests around one model. llama-server is the C++ version for a single machine, often a laptop.

The next token skips building, scheduling and planning: only its inputs change

Files the token has passed are shaded, the current ones outlined; files faded are skipped in this mode.

13. One token, end to end, timed

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.

  1. Into the library. 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.
  2. Build the graph. No graph exists for 5 tokens yet, so 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.
  3. Schedule, then plan memory. 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.
  4. Inputs and KV slots. 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.
  5. Compute: 4 threads walk every node. 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.
  6. Chunks, then the kernel. In 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.
  7. Attention reads the cache through a view. FLASH_ATTN_EXT reads K and V through a 4-dimensional view {64, 3, cells} of each layer's cache: no copy.
  8. Logits out, a token picked, printed. Only the last token asked for logits, so the last layer kept one row (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.
The code at the current step

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):

PhaseMeasuredWhat it is
Load msFrom 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 tokenOne 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.

Habits for reading or running llama.cpp, collected
  • Check what runs before reading a kernel: call counters, or the log's repack, splits and offloaded lines (sections 5, 8, 10).
  • Read shapes innermost first: ne[0] is contiguous; ggml_mul_mat(a, b) multiplies rows of a by rows of b (section 6).
  • A ggml call only adds a node: inspect values with llama-eval-callback, after the graph runs (section 7).
  • Pass -ngl 0 to study the CPU path; the default offloads every layer (section 3).
  • Benchmark with repetitions and fewer threads than free cores, and record the load average (section 9).
  • Build Release for timing; keep a Debug build only for stepping through code in a debugger (section 2).
  • Grep surprising log lines: model type = 256M for a 135M model (section 5).
  • Instrument a copy, never the clone you are reading, so every excerpt and line number stays true to the commit (section 10).

How this was run

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.

Provenance: commit, model, machine, what was not done

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.

Every command and raw output: reproduce, one prompt three ways, kernel counts, every benchmark sample, versions

Reproduce


One prompt, three ways


Generated text, as printed: CPU ; Metal ; Q4_0 on the CPU .

Which kernels ran

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):


Speed, every sample


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.

Versions