On-device AI: MLX, llama.cpp, GGUF¶
On-device AI runs the model on hardware you hold: a laptop, a desktop, a phone. There is exactly one user, so batch size is 1 and every generated token must read the whole model from memory. Decode speed is memory bandwidth divided by model bytes. Everything in the local stack (unified memory, 4-bit block formats, memory-mapped GGUF files, MLX's lazy arrays) exists to make that division come out well.
10,000 ft
For most of the deep-learning era, running a large model meant renting a data-centre GPU. Three things changed that between 2023 and 2026. Open-weight models became good. Quantisation to about 4 bits became nearly free in quality (quantisation). And Apple Silicon put tens to hundreds of gigabytes of fast memory, shared between CPU and GPU, into ordinary computers. A 2026 laptop runs an 8 B model faster than you can read and a 70 B model usably. Phones run 3 B-class models: Apple Intelligence's on-device model has about 3 B parameters at 2 bits per weight. The reasons to go local are privacy (data never leaves the device), latency (no network), cost (no per-token bill), offline use and control. The physics is the same as in compute maths and serving, with one difference: you cannot batch across users, so bytes per token is everything.
2,000 ft
Running a model locally is four decisions and one formula:
- Model: parameter count sets quality and size. For MoE models, memory needs the total parameters and speed depends on the active ones.
- Format: a single-file GGUF with llama.cpp's block quantisations (Q4_K_M is the usual default), or an MLX checkpoint (4-bit affine, groups of 64).
- Fit: weights + KV cache for your context + working buffers must fit in the memory the GPU is allowed to use.
- Runtime: llama.cpp (and Ollama and LM Studio, built on it) for portability; MLX on Apple Silicon; Core ML, ExecuTorch or a vendor SDK inside a shipped app.
- Expectation: decode tokens/s ≈ 0.5–0.8 × bandwidth ÷ bytes read per token. Prompt processing is compute-bound and is where small devices are slowest.
Ground level¶
Batch 1 changes the economics¶
A data-centre server amortises each read of the weights over dozens or hundreds of users (serving). Your laptop serves one. So the decode identity applies in its purest form:
Halve the bytes and you double the speed. That is why local inference uses 4-bit formats by default, while data centres often stop at 8-bit or FP8: at batch 1, bytes are the only lever.
Measured numbers bear this out. The llama.cpp community keeps a benchmark of Llama 2 7B on every Apple chip (discussion #4167):
Two lessons from the figure. Speed tracks bandwidth almost linearly across five years of chips, so if you want faster local generation, buy bandwidth, not GPU cores. And the 4-bit format reaches a lower fraction of its bound (45–60% for the large chips) than F16 does (70–78%), because unpacking 4-bit blocks costs instructions. The step from 16 to 4 bits buys 2.3–2.9× rather than the 3.5× that file sizes promise.
Unified memory: why a Mac runs models a gaming GPU cannot¶
A discrete GPU has its own memory (VRAM) on the card, connected to the CPU's RAM over PCIe. An RTX 4090 has 24 GB of VRAM at about 1 TB/s: fast, but a 70 B model at 4 bits (42.5 GB) does not fit, and spilling layers to CPU RAM over PCIe is an order of magnitude slower.
Apple Silicon puts CPU, GPU and Neural Engine on one chip that shares a single pool of LPDDR memory: unified memory. There is no copy between "host" and "device", and the GPU can address most of the machine's memory.
Apple's published figures (from its press releases):
| Chip | Max memory | Bandwidth | Llama 3.1 8B Q4_K_M (4.92 GB): bound | Llama 3.1 70B Q4_K_M (42.5 GB) |
|---|---|---|---|---|
| M4 | 32 GB | 120 GB/s | 24 tok/s | does not fit |
| M5 | (varies by device) | 153 GB/s | 31 tok/s | does not fit |
| M4 Pro | 64 GB | 273 GB/s | 55 tok/s | 6.4 tok/s, needs the 64 GB model |
| M4 Max | 128 GB | 546 GB/s | 111 tok/s | 12.8 tok/s |
| M3 Ultra | 512 GB | over 800 GB/s (819) | 166 tok/s | 19 tok/s |
| H100 SXM, for comparison | 80 GB | 3,350 GB/s | 681 tok/s | 79 tok/s |
The bounds are bandwidth ÷ file size. Expect 50–80% of them in practice, less at long context, where the KV cache adds bytes. The trade-off is the other column of the hardware sheet: an M4 Max GPU has a small fraction of an H100's FLOP/s. Apple's own M5 announcement makes the point: its new per-core GPU "Neural Accelerators" give over 4× the M4's peak AI compute, but bandwidth rose only 28% (120 to 153 GB/s). Apple's MLX team measured what that means: time to first token improved 3.3–4.1×, generation speed only 19–27% (Apple ML Research, Nov 2025). Prefill follows FLOPs; decode follows bandwidth.
Not all of unified memory is GPU memory
By default macOS lets the GPU wire only part of unified memory. Community measurements put it
at roughly two-thirds to three-quarters, depending on RAM size and OS version. llama.cpp
prints the limit at start-up as recommendedMaxWorkingSetSize. It can be raised with the
iogpu.wired_limit_mb sysctl. Apple does not document that setting, and you must leave
room for the OS. A 64 GB Mac therefore does not comfortably run a 42.5 GB model with a long
context.
The memory budget¶
To check whether a model fits, add three things:
- Weights: the file size. Llama 3.1 8B is 16 GB in BF16, 8.5 GB in Q8_0 and 4.9 GB in Q4_K_M. The 70B is 42.5 GB in Q4_K_M and 26.4 GB in Q2_K (real files on Hugging Face).
- KV cache: \(2 \cdot L \cdot n_{kv} \cdot d_h \cdot\) bytes per token (see
compute maths). For Llama
3.1 8B in F16 that is 128 KiB per token: 1 GB at 8k context, 16 GB at its full 128k. Local
runtimes allocate the cache for the context you request (
-c/--ctx-size), so asking for 128k "just in case" can cost more memory than the weights. Both llama.cpp and MLX can store the cache in 8-bit or 4-bit. - Buffers: compute scratch space, typically a few hundred MB to a few GB, growing with the prompt-processing batch size.
For a mixture-of-experts model the rule splits in two. Memory must hold all the experts; speed depends on the experts each token uses. OpenAI's gpt-oss-20b has 20.9 B parameters but only 3.6 B active per token, and ships as a 12.8 GiB checkpoint with its experts in MXFP4 (model card). It needs a 16 GB-class machine but generates at the speed of a ~4 B dense model. That combination of large memory and modest bandwidth suits unified-memory machines unusually well.
GGUF: one file, memory-mapped¶
GGUF is the file format of llama.cpp and its ecosystem (Ollama, LM Studio, and many others). It replaced the earlier GGML, GGMF and GGJT formats in August 2023. Its design goals: one file holds everything needed to run the model; it is fast to load; and it can be extended without breaking old readers (spec).
Three properties matter in practice:
- Self-contained. The tokenizer, chat template and architecture hyperparameters live in the
metadata, so one
.gguffile is a runnable model. (Most "wrong output" bugs in local models are a wrong chat template, and GGUF carries the right one with the weights.) - Memory-mapped. Tensor data is aligned so the runtime can
mmapthe file and use the bytes in place. Loading is nearly instant; the OS page cache keeps the model warm between runs; several processes share one copy. The Build it section writes and maps a GGUF file. - Typed per tensor. Each tensor declares its own quantisation type. That is what makes mixtures like Q4_K_M possible: most tensors in Q4_K, sensitive ones in Q6_K.
llama.cpp's quantisation formats¶
llama.cpp started in March 2023 as Georgi Gerganov's plain C/C++ port of LLaMA inference for a MacBook. It grew into the most widely used local inference engine, on top of the ggml tensor library, with CPU SIMD, Metal, CUDA, Vulkan and other back-ends. Its formats are block quantisations designed to be unpacked inside SIMD registers:
| Type | Layout | Bits/weight |
|---|---|---|
| Q8_0 | blocks of 32: one FP16 scale + 32 int8 | 8.5 |
| Q4_0 | blocks of 32: one FP16 scale + 32 × 4-bit, value = \(d\,(q - 8)\) | 4.5 |
| Q2_K | super-block of 256 = 16 blocks of 16, 4-bit scales and mins | 2.56 (stated) |
| Q3_K | 16 blocks of 16, 6-bit scales | 3.44 |
| Q4_K | super-block of 256 = 8 blocks of 32, 6-bit scales and mins, FP16 super-scale | 4.5 |
| Q5_K | as Q4_K with 5-bit values | 5.5 |
| Q6_K | 16 blocks of 16, 8-bit scales | 6.56 |
The k-quants (PR #1684, June 2023) use two levels of scale. Each small block gets its own scale (and minimum), stored in 6 bits relative to one FP16 scale per 256-weight super-block. That gives fine granularity, which, as quantisation explains, is the main lever on error, at a fraction of a bit of overhead. The named mixes assign types per tensor: Q4_K_M puts half of the attention-value and FFN-down matrices in Q6_K and the rest in Q4_K, averaging about 4.8–4.9 bits per weight on Llama 3.1 (4.92 GB for 8.03 B parameters). The PR's measurements on the original LLaMA 7B (WikiText perplexity):
| Format | Perplexity | Size |
|---|---|---|
| F16 | 5.9066 | 13.0 GB |
| Q6_K | 5.9110 | 5.15 GB |
| Q5_K_S | 5.9419 | 4.33 GB |
| Q4_K_M | 5.9601 | 3.80 GB |
| Q4_K_S | 6.0215 | 3.56 GB |
| Q3_K_M | 6.1503 | 3.06 GB |
| Q2_K | 6.7764 | 2.67 GB |
Q6_K is within 0.1% of F16. Q4_K_M costs about 0.9% perplexity for a 3.4× smaller file, which is why it is the default recommendation. Below 4 bits the curve bends sharply.
Two later additions borrow ideas from the GPU quantisation literature:
- Importance matrix (imatrix): run calibration text through the model, record how strongly each weight column is activated, and weight the rounding error by it when choosing scales. It is the same insight as AWQ: errors on weights that meet large activations matter more. It helps most at 2–3 bits.
- i-quants (IQ2_XXS, IQ3_S, IQ4_XS and others) use lattice codebooks and non-uniform grids, in the spirit of QuIP#, to reach usable quality near 2 bits per weight.
MLX: an array framework built for unified memory¶
MLX is Apple's open-source array framework, released by
Apple machine-learning research in December 2023. It feels like NumPy with PyTorch-style
nn and optimisers, and three design choices make it different:
- Unified memory is the programming model. Arrays live in shared memory. You choose the
device per operation (
stream=mx.gpuormx.cpu), not per array, and nothing is ever copied between them. - Lazy evaluation. Operations build a graph and run only when a result is needed
(
mx.eval, printing, converting to NumPy). The framework can then fuse and schedule work;mx.compilegoes further and compiles a function's graph into fused Metal kernels. - Composable transforms.
mx.grad,mx.value_and_gradandmx.vmapwork like JAX's. Training and fine-tuning (including LoRA) are first-class, not an afterthought.
mlx-lm is the LLM package on top: generation, chat, an
OpenAI-compatible server, conversion with quantisation, and LoRA fine-tuning. MLX's default
quantisation is affine, 4-bit, groups of 64: each group stores a scale and a bias (the group
minimum) in the input's 16-bit type, so 4 + 32/64 = 4.5 bits per weight. As of 2026 it also
supports the block-float MXFP4, MXFP8 and NVFP4 modes
(mx.quantize docs).
The mlx-community organisation on Hugging Face hosts
pre-converted models.
pip install mlx-lm
mlx_lm.generate --model mistralai/Mistral-7B-Instruct-v0.3 --prompt "hello" # converts on the fly
mlx_lm.convert --model mistralai/Mistral-7B-Instruct-v0.3 -q # save a 4-bit copy
mlx_lm.chat # interactive chat
The llama.cpp equivalents, from its README (current builds use one llama binary; older builds
name the tools llama-cli, llama-server, llama-quantize):
llama cli -hf ggml-org/Qwen3.5-0.8B-GGUF # download a GGUF from Hugging Face and chat
llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF # OpenAI-compatible server with a web UI
# your own model: convert to GGUF, then quantise (optionally with an importance matrix)
python convert_hf_to_gguf.py --outfile model-bf16.gguf --outtype bf16 <hf-model-dir>
./build/bin/llama-quantize --imatrix imatrix.gguf model-bf16.gguf model-Q4_K_M.gguf Q4_K_M
Which to use? On a Mac, both are excellent and close in speed; benchmark your own model. MLX is the natural choice if you also want to train or fine-tune locally, and it is a Python library you can hack. llama.cpp runs everywhere (Mac, Linux, Windows, phones, Raspberry Pi), has the largest model catalogue in GGUF, and is what Ollama and LM Studio wrap. LM Studio can run both back-ends.
Inside apps and on phones¶
Shipping a model inside an application is a different problem from running one on your own machine. The model must be small (phones have 8–16 GB shared with everything else and far less bandwidth than a laptop), and it must not drain the battery.
- Apple Foundation Models framework: from 2025, apps can call the ~3 B on-device model behind Apple Intelligence through a Swift API (docs), with guided generation (structured output) and tool calling.
- Core ML converts and runs models on Apple devices, using the CPU, GPU and Neural Engine.
- ExecuTorch (PyTorch) exports PyTorch models to run on iOS, Android and embedded devices, with back-ends for mobile NPUs.
- MLC LLM (mlc.ai) compiles models with TVM for phones, browsers (WebGPU) and desktops.
Apple's 2025 technical report is a compact case study in on-device design (Apple Intelligence Foundation Language Models: Tech Report 2025). Every trick in it attacks bytes:
- 2 bits per weight via quantisation-aware training, with the embedding table at 4 bits and the KV cache at 8 bits. LoRA adapters trained afterwards recover lost quality.
- KV-cache sharing: the model is split into two blocks. Block 1 holds 62.5% of the layers. Block 2 (37.5%) has no key and value projections and reuses Block 1's KV cache. That cuts KV-cache memory by 37.5% and time to first token by about 37.5%.
- For the larger server model, weights are compressed to about 3.56 bits per weight with ASTC, a texture-compression format that Apple GPUs decompress in fixed-function hardware. The graphics hardware is repurposed as a free dequantiser.
Making local inference faster¶
Beyond choosing the format, the levers are the serving levers applied to one user:
- Keep the context you need, not the maximum. KV-cache size and per-token KV reads grow with
context. A quantised KV cache (
--cache-type-k q8_0in llama.cpp, or MLX's KV quantisation) halves it. - Prompt caching. Local agents re-send the same long system prompt and tool definitions. llama.cpp's server reuses the KV of a matching prefix; mlx-lm can save a prompt cache to disk and reload it.
- Speculative decoding. At batch 1 the target model's verification pass is nearly free, so a small draft model with the same tokenizer can speed up predictable text (code, edits, structured output) substantially. Both llama.cpp and mlx-lm support draft models; measure the gain on your own prompts.
- Offload carefully. If a model barely does not fit on a discrete GPU, llama.cpp can keep some
layers on the CPU (
-nglsets how many go to the GPU). Every CPU layer runs at CPU-RAM bandwidth, so speed falls steeply. On MoE models, keeping attention on the GPU and the experts in CPU RAM is the better split.
First principles¶
Why bandwidth, not compute, sets local speed. A dense model does \(2N\) FLOPs per token and reads about \(N \cdot \text{bpw}/8\) bytes, an arithmetic intensity of about \(16/\text{bpw}\) FLOPs per byte: 4 for a 4-bit model. Every modern chip's ridge point is far above that (an H100's is about 295 FLOPs per byte, and laptop GPUs sit in the tens). So at batch 1 the processor is always waiting for memory, and only bandwidth and bytes matter. Prefill is the exception: it processes the whole prompt at once, its intensity is about the prompt length, and it is bound by compute. That is why a laptop answers a short question instantly but takes noticeable seconds to "read" a long document.
Why unified memory changes what is possible, not how fast it is. Bandwidth per dollar on a Mac is not remarkable next to a gaming GPU. What is unusual is capacity at reasonable bandwidth: 128–512 GB that the GPU can read at 0.5–0.8 TB/s. Data-centre GPUs have more bandwidth but less capacity per device; consumer GPUs have bandwidth but little capacity. For batch-1 inference of large or MoE models, capacity decides whether you can run the model at all, and bandwidth then decides how fast.
Why memory-mapping is the right loading strategy. A model file is immutable and larger than
any one function needs at once. mmap lets the OS load pages lazily, keep them in the page cache
across runs, share them between processes and evict them under memory pressure, with no
deserialisation step. That requires the file's tensors to be stored already in the in-memory
layout and aligned, which is exactly what GGUF guarantees and what pickled PyTorch checkpoints
did not. (Safetensors, the Hugging Face format, makes the same choice for the same reason.)
Why small blocks with cheap scales. A CPU or GPU unpacks 4-bit weights in registers just before multiplying them. The unit of work is a SIMD register (128 bits on NEON is 32 four-bit weights), so blocks of 32 align with the hardware. Small blocks also track local magnitude well. Two-level scales (k-quants, NVFP4) keep the per-block scale small while preserving range.
The maths¶
Decode time per token on a device with bandwidth \(\beta\), for a model with \(N\) parameters at \(b\) bits per weight, \(L\) layers, \(n_{kv}\) KV heads of size \(d_h\), a cache stored at \(c\) bytes per element, and context \(s\):
where \(\eta \in [0.45, 0.8]\) is the achieved fraction of peak bandwidth (measured above). For an MoE model replace \(N\) by \(N_{\text{active}}\) in the first term, but not in the memory budget.
Fit condition: with \(M\) the memory, \(f\) the share the GPU may use and \(B\) the buffers,
Bits per weight of a block format: elements of \(b\) bits in blocks of \(g\), each block with scale bits \(b_s\) (and min bits \(b_m\)), plus super-block overhead \(S\) bits per \(G\) weights:
Q4_0: \(4 + 16/32 = 4.5\). Q4_K: \(4 + (6 + 6)/32 + 32/256 = 4.5\). MLX 4-bit, \(g = 64\): \(4 + 32/64 = 4.5\). Q6_K: \(6 + 8/16 + 16/256 = 6.5625\).
Derivation: why Q4_0 maps the signed maximum to −8
A 4-bit code \(q \in \{0,\dots,15\}\) dequantised as \(d\,(q - 8)\) covers \(\{-8d, \dots, 7d\}\): one more level on the negative side. ggml chooses \(d = m/(-8)\), where \(m\) is the block's element of largest magnitude with its sign. If \(m > 0\) then \(d < 0\), and \(m\) maps to \(q = 0\), i.e. \(-8d = m\). If \(m < 0\) then \(d > 0\) and \(m = -8d\) again. Either way the largest element is represented exactly, and the 16 levels run from \(m\) to \(-\tfrac{7}{8}m\). Compared with symmetric absmax (\(d = |m|/7\), 15 levels), the step is \(7/8\) as large, which reduces the rounding-noise variance \(d^2/12\) by about 23% at no cost.
Build it¶
Three NumPy programs. The first reimplements llama.cpp's Q8_0 and Q4_0 exactly as in ggml's
reference code (quantize_row_q4_0_ref), plus MLX's default affine format, and measures bits per
weight and error on a weight matrix with heavy-ish tails.
import numpy as np
rng = np.random.default_rng(0)
f16 = lambda x: x.astype(np.float16).astype(np.float32) # scales are stored as FP16
def q4_0(x): # ggml quantize_row_q4_0_ref: blocks of 32, one FP16 scale
b = x.reshape(-1, 32)
i = np.abs(b).argmax(1)
d = f16(b[np.arange(len(b)), i] / -8) # signed max maps exactly to -8
q = np.minimum(15, np.floor(b / np.where(d == 0, 1, d)[:, None] + 8.5)).astype(np.uint8)
packed = q[:, :16] | (q[:, 16:] << 4) # two 4-bit values per byte
nbytes = d.size * 2 + packed.size
return ((q.astype(np.float32) - 8) * d[:, None]).reshape(x.shape), nbytes
def q8_0(x): # ggml quantize_row_q8_0_ref: blocks of 32, int8, FP16 scale
b = x.reshape(-1, 32)
d = f16(np.abs(b).max(1) / 127)
q = np.round(b / np.where(d == 0, 1, d)[:, None]).astype(np.int8)
return (q * d[:, None]).reshape(x.shape), d.size * 2 + q.size
def mlx_affine(x, bits=4, g=64): # mlx.core.quantize default: groups of 64, scale + bias
b = x.reshape(-1, g)
lo, hi = b.min(1, keepdims=True), b.max(1, keepdims=True)
s = f16((hi - lo) / (2**bits - 1)); lo = f16(lo)
q = np.round((b - lo) / s)
return (q * s + lo).reshape(x.shape), (b.size * bits) // 8 + 4 * len(b)
W = rng.standard_t(df=5, size=(4096, 4096)).astype(np.float32) * 0.02 # heavy-ish tails
for name, fn in [("Q8_0", q8_0), ("Q4_0", q4_0), ("MLX 4-bit g64", mlx_affine),
("MLX 3-bit g64", lambda x: mlx_affine(x, 3))]:
Wq, nbytes = fn(W)
rel = np.linalg.norm(Wq - W) / np.linalg.norm(W)
print(f"{name:14s} {8 * nbytes / W.size:5.3f} bits/weight relative error {100 * rel:5.2f}% "
f"{nbytes / 2**20:6.2f} MiB for a 4096x4096 matrix (F16: {W.size * 2 / 2**20:.0f} MiB)")
Q8_0 8.500 bits/weight relative error 0.68% 17.00 MiB for a 4096x4096 matrix (F16: 32 MiB)
Q4_0 4.500 bits/weight relative error 10.77% 9.00 MiB for a 4096x4096 matrix (F16: 32 MiB)
MLX 4-bit g64 4.500 bits/weight relative error 11.02% 9.00 MiB for a 4096x4096 matrix (F16: 32 MiB)
MLX 3-bit g64 3.500 bits/weight relative error 23.63% 7.00 MiB for a 4096x4096 matrix (F16: 32 MiB)
Two different 4.5-bit designs (symmetric blocks of 32 versus affine groups of 64) land within a few per cent of each other. Granularity and bit count matter far more than the exact recipe.
The second is a "will it run, and how fast?" calculator using real file sizes and Apple's published bandwidths, at an 8k context, assuming 60% of peak bandwidth (the measured Q4_0 figure for an M4 Max).
import numpy as np
# Chips: (memory GB, bandwidth GB/s, share of memory the GPU may use). Apple figures from
# Apple's newsroom; the ~75% GPU share on Macs is the usual default, adjustable via sysctl.
CHIPS = {"M4 16GB": (16, 120, .75), "M4 Pro 48GB": (48, 273, .75), "M4 Max 128GB": (128, 546, .75),
"M3 Ultra 512GB": (512, 819, .75), "RTX 4090 24GB": (24, 1008, .95)}
# Models: (file GB, GB read per token, KV bytes per token, fixed KV bytes)
GiB = 2**30
MODELS = {
"Llama-3.1-8B Q4_K_M": (4.92, 4.92, 2 * 32 * 8 * 128 * 2, 0), # real file sizes (bartowski)
"Llama-3.1-8B Q8_0": (8.54, 8.54, 2 * 32 * 8 * 128 * 2, 0),
"Llama-3.1-70B Q4_K_M": (42.52, 42.52, 2 * 80 * 8 * 128 * 2, 0),
# MoE: all 20.9B weights must be resident, but a token reads only the 3.6B active ones
"gpt-oss-20b MXFP4": (12.8 * GiB / 1e9, 3.61 / 20.91 * 12.8 * GiB / 1e9,
2 * 12 * 8 * 64 * 2, 2 * 12 * 8 * 64 * 2 * 128), # 12 dense + 12 windowed layers
}
CTX, EFF = 8192, 0.6 # context length; fraction of peak bandwidth llama.cpp typically reaches
print(f"{'':22s}" + "".join(f"{c:>16s}" for c in CHIPS))
for m, (file_gb, read_gb, kv_tok, kv_fixed) in MODELS.items():
kv_gb = (CTX * kv_tok + kv_fixed) / 1e9
row = f"{m:22s}"
for c, (mem, bw, share) in CHIPS.items():
need = file_gb + kv_gb + 1.0 # + ~1 GB compute buffers
if need > mem * share:
row += f"{'no (' + format(need, '.0f') + ' GB)':>16s}"
else:
tok_s = EFF * bw / (read_gb + CTX * kv_tok / 1e9) # every token reads weights + KV
row += f"{format(tok_s, '.0f') + ' tok/s':>16s}"
print(row)
M4 16GB M4 Pro 48GB M4 Max 128GB M3 Ultra 512GB RTX 4090 24GB
Llama-3.1-8B Q4_K_M 12 tok/s 27 tok/s 55 tok/s 82 tok/s 101 tok/s
Llama-3.1-8B Q8_0 7 tok/s 17 tok/s 34 tok/s 51 tok/s 63 tok/s
Llama-3.1-70B Q4_K_M no (46 GB) no (46 GB) 7 tok/s 11 tok/s no (46 GB)
gpt-oss-20b MXFP4 no (15 GB) 64 tok/s 127 tok/s 191 tok/s 235 tok/s
Check it against reality: the same model gives about 86 tok/s for Llama 2 7B Q4_0 (3.8 GB) on a 546 GB/s M4 Max at short context, and the benchmark above measured 83. Notice the MoE row: gpt-oss-20b is more than twice the size of the 8B Q4_K_M file but generates faster, because each token reads only its active experts. (The gpt-oss estimate assumes the bytes read scale with active parameters, an approximation: attention and embedding weights are stored differently from the MXFP4 experts.)
The third writes a tiny GGUF file by hand, following the spec, and reads it back with a parser
that also works on real .gguf files. It then memory-maps the tensor without copying it.
import struct, mmap, numpy as np, os, tempfile
def gguf_str(s): b = s.encode(); return struct.pack("<Q", len(b)) + b
def write_tiny_gguf(path, arr): # one metadata pair, one F32 tensor
hdr = b"GGUF" + struct.pack("<IQQ", 3, 1, 1) # magic, version 3, 1 tensor, 1 kv
kv = gguf_str("general.architecture") + struct.pack("<I", 8) + gguf_str("llama") # 8 = STRING
info = gguf_str("token_embd.weight") + struct.pack("<I", arr.ndim)
info += struct.pack(f"<{arr.ndim}Q", *arr.shape[::-1]) # GGUF lists dims fastest-varying first
info += struct.pack("<IQ", 0, 0) # type 0 = F32, offset 0 in data section
head = hdr + kv + info
with open(path, "wb") as f:
f.write(head + b"\0" * (-len(head) % 32) + arr.astype("<f4").tobytes()) # align to 32
SCALARS = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
def read_gguf(path):
with open(path, "rb") as f: # map, don't read: real files are GBs
buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
pos = 0
def take(fmt):
nonlocal pos; v = struct.unpack_from("<" + fmt, buf, pos); pos += struct.calcsize("<" + fmt)
return v if len(v) > 1 else v[0]
def string(): n = take("Q"); s = buf[pos:pos + n].decode(); skip(n); return s
def skip(n): nonlocal pos; pos += n
def value(t):
if t == 8: return string()
if t == 9: et, n = take("IQ"); return [value(et) for _ in range(n)] # ARRAY
return take(SCALARS[t])
assert buf[:4] == b"GGUF"; skip(4)
version, n_tensors, n_kv = take("IQQ")
meta = {}
for _ in range(n_kv):
k = string(); meta[k] = value(take("I"))
tensors = []
for _ in range(n_tensors):
name = string(); nd = take("I"); dims = [take("Q") for _ in range(nd)]
ttype, off = take("IQ"); tensors.append((name, dims, ttype, off))
align = meta.get("general.alignment", 32)
data_start = pos + (-pos % align)
return version, meta, tensors, data_start
path = os.path.join(tempfile.mkdtemp(), "tiny.gguf")
write_tiny_gguf(path, np.arange(12, dtype=np.float32).reshape(3, 4))
version, meta, tensors, start = read_gguf(path)
print("version", version, "| metadata", meta, "| tensors", tensors, "| data at byte", start)
name, dims, ttype, off = tensors[0]
w = np.memmap(path, dtype="<f4", mode="r", offset=start + off, shape=tuple(dims[::-1]))
print(name, "memory-mapped, no copy:\n", w)
version 3 | metadata {'general.architecture': 'llama'} | tensors [('token_embd.weight', [4, 3], 0, 0)] | data at byte 128
token_embd.weight memory-mapped, no copy:
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]]
Things to try
- Point
read_ggufat a real model file and printmeta["tokenizer.chat_template"],meta["general.architecture"]and a histogram of tensor types. (Skip the longtokenizer.ggml.tokensarray when printing.) How many tensors are Q6_K in a Q4_K_M file? - Implement Q4_1 (blocks of 32 with a scale and a minimum, 5 bpw) and compare its error
with Q4_0 on post-ReLU-like data (
np.abs(W)). - Extend the calculator with a
--ctxsweep from 2k to 128k for Llama 3.1 8B on an M4 Pro: at what context does the KV cache cost more bandwidth than the weights? - If you have a Mac: run the same model with
mlx_lm.generateand with llama.cpp at the same bit width, and compute each one's achieved bandwidth (tokens/s × bytes read per token). - Add speculative decoding to the calculator: a 1 B draft at acceptance 0.7, γ = 4 (formula in serving). Which chips gain most?
In practice¶
- Start with Q4_K_M (GGUF) or 4-bit MLX for any model of 7 B and above. Go to Q5_K_M or Q6_K if you have memory to spare and care about maths or code. Use 8-bit for small models (≤ 3 B), which suffer more from quantisation. Below 4 bits, prefer a larger model at Q3 over a smaller one at Q8 only after testing on your task.
- Prefer an imatrix-calibrated GGUF for anything at 3 bits or lower. Well-known uploaders publish these routinely.
- Set the context deliberately. Default context sizes in local runtimes vary; long contexts silently consume memory and slow every token.
- Use the model's chat template. GGUF files and MLX conversions carry it; custom prompt formats are the most common cause of "the local model is dumb".
- Measure tokens/s for prompt and generation separately.
llama-benchreports both (ppandtg). If generation is far below bandwidth ÷ size, check that all layers are on the GPU. - Mind licences and provenance. Community GGUF and MLX conversions are convenient. Check the original model's licence, and prefer conversions from the model's publisher or well-known maintainers.
Common misconceptions¶
\"More GPU cores means faster chat.\"
Generation speed tracks memory bandwidth. Extra cores speed up prompt processing (and training), not token generation at batch 1. Compare chips by GB/s.
\"A 30 B MoE model runs like a 30 B dense model.\"
It needs the memory of its total parameters but runs at the speed of its active parameters. On unified-memory machines MoE models are often the best quality per token/s.
\"If it fits in RAM, it fits.\"
The GPU may use only part of unified memory by default, the KV cache grows with the configured context, and the OS needs room. Budget weights + KV + buffers against the GPU's limit, not total RAM.
\"Quantisation formats are interchangeable.\"
Q4_0 and Q4_K_M, or MLX 4-bit with group 64 and 32, are different files with different quality. Model names on download sites encode the format; read them.
Check yourself¶
An M4 Pro has 273 GB/s. Roughly how fast can it generate with a 14 B model in Q4_K_M (~4.85 bits/weight), and what limits it?
File ≈ 14e9 × 4.85 / 8 ≈ 8.5 GB. Bound ≈ 273 / 8.5 ≈ 32 tokens/s; at 60% efficiency about 19 tokens/s, less at long context as the KV cache adds bytes. The limit is memory bandwidth: the GPU's compute would allow far more.
Why does Apple's M5 improve time to first token about 4× over M4, but generation only about 20–27%?
Prompt processing is compute-bound (intensity ≈ prompt length), and the M5 GPU adds Neural Accelerators with over 4× the peak AI compute. Generation is bandwidth-bound, and bandwidth rose only 28% (120 → 153 GB/s).
What does Q4_K_M mean, and why is it larger than 4.5 bits per weight?
K-quant, 4-bit base, "medium" mix: most tensors in Q4_K (4.5 bpw: 4-bit values, 6-bit block scales and mins, an FP16 super-block scale), with half of the attention-value and FFN-down tensors in Q6_K (6.56 bpw) and the output layer at 6 bits. The mix averages about 4.8–4.9 bpw.
Why can a GGUF model start in under a second even when it is 40 GB?
The runtime memory-maps the file instead of reading it. Tensor data is already in its in-memory layout and aligned, so pages are loaded lazily by the OS as the model touches them, and stay in the page cache for the next run. (The first token may still wait while pages stream in from disk the first time.)
Apple's on-device model shares the KV cache of its first 62.5% of layers with the remaining 37.5%. Why does that cut time to first token as well as memory?
Prefill exists to build the KV cache for the prompt, plus the output at the last position. Block 2 contributes nothing to the cache: its layers reuse Block 1's keys and values. So its computation for the prompt positions is not needed by anything, and the report says prefill can bypass all of Block 2's computation. That removes 37.5% of the layers' prefill work, and TTFT falls by about 37.5%.
Hard: when is a 70 B model at Q3_K_M better than a 32 B model at Q8_0 on the same 64 GB machine?
Sizes: 70 B × ~3.9 bpw ≈ 34 GB versus 32 B × 8.5 bpw ≈ 34 GB, the same bytes and so about the same speed. The k-bit scaling-law result says that for fixed bits, more parameters at lower precision usually win down to about 4 bits, while at 3 bits the quantisation loss grows quickly. So it depends on the model family and task. Measure both on your evaluation set, and prefer an imatrix-calibrated Q3 file if you try it.
Go deeper¶
Papers and reports
- Apple Intelligence Foundation Language Models: Tech Report 2025 — Apple, 2025. KV-cache sharing, 2-bit QAT and ASTC weight compression: on-device design end to end.
- gpt-oss-120b & gpt-oss-20b Model Card — OpenAI, 2025. An open MoE model designed to fit on 16 GB devices with MXFP4 experts.
- The case for 4-bit precision: k-bit Inference Scaling Laws — Dettmers and Zettlemoyer, 2022. Why 4 bits is the default local trade-off.
- AWQ — Lin et al., 2023. Activation-aware quantisation and on-device kernels (TinyChat); the idea behind imatrix.
Official documentation and specs
- GGUF specification — ggml. The file format, field by field.
- k-quants, llama.cpp PR #1684 — ikawrakow, 2023. Design and measurements of the Q2_K–Q6_K family.
- llama.cpp quantize README — Every quantisation type and how to produce it.
- MLX documentation — Apple. Lazy evaluation, unified memory, function transforms, quantisation modes.
Videos and lectures
- Get started with MLX for Apple silicon — Apple, WWDC25. The framework's design from its authors.
- Explore large language models on Apple silicon with MLX — Apple, WWDC25. mlx-lm: generation, quantisation and fine-tuning.
Articles and benchmarks
- Exploring LLMs with MLX and the Neural Accelerators in the M5 GPU — Apple ML Research, 2025. Prefill follows compute, decode follows bandwidth, measured.
- Performance of llama.cpp on Apple Silicon M-series — llama.cpp community. The benchmark table behind this page's figure.
- GGUF on the Hugging Face Hub — Hugging Face. Browsing, inspecting and using GGUF files.
Code
- ggml-org/llama.cpp — The engine;
ggml/src/ggml-quants.cholds every quantiser. - ml-explore/mlx and ml-explore/mlx-lm — The framework and its LLM package.
- pytorch/executorch — PyTorch's runtime for phones and embedded devices.
Where this leads¶
- Quantisation: the theory behind every format on this page.
- Serving LLMs: what changes when there are thousands of users instead of one.
- Your workbench: setting up Python, PyTorch and MLX on your own machine.
- Fine-tune a model with LoRA: a project you can run locally with mlx-lm.
- Case study: how Jarvis is built: where a hosted model and local tools meet in a real product.