Work / 01 / LLM inference · Rust

MiniInfer

A Llama inference runtime in Rust, measured against llama.cpp on the same model file.

Run the Llama forward pass inside the runtime, on Candle's quantized kernels, then check speed claims with order-controlled benchmarks, greedy output against Candle’s reference model, and perplexity against llama.cpp.

  1. 5,848 → 145 ms

    time to first token, 1,040-token prompt with in-session prefix reuse

    Apple M1 CPU, SmolLM2-360M Q8_0, arms interleaved request by request. Reuse only helps when the prefix repeats. source for “time to first token, 1,040-token prompt with in-session prefix reuse” ↗

  2. ≤ 0.105%

    largest perplexity difference from llama.cpp on the same GGUF, SmolLM2-360M (Q8_0 and Q4_K_M)

    Worst case 40.8274 vs 40.8702 (Q4_K_M, CPU), which the log rounds to 0.10%. An agreement check on one 8,918-token corpus (CPU and Metal), not a model-quality claim. source for “largest perplexity difference from llama.cpp on the same GGUF, SmolLM2-360M (Q8_0 and Q4_K_M)” ↗

  3. 1.13–2.91×

    faster Metal prefill after moving attention to Candle's fused SDPA kernel

    Versus MiniInfer's own matmul path, 64–1,984 tokens, paired in-process A/B on one M1. Not a comparison with llama.cpp. source for “faster Metal prefill after moving attention to Candle's fused SDPA kernel” ↗

Status
Research prototype v0.1
Period
Nov 2026 – present
Context
Independent open-source project
Stack
Rust · Candle 0.11.1 · Apple Metal · CUDA · GGUF
On this page
  1. The problem
  2. Design
  3. Measurement
  4. Against llama.cpp
  5. A bug in the kernel
  6. Where it stops
  7. Read the implementation
  8. Evidence

MiniInfer implements the model code, KV cache, session logic, memory pre-flight, CLI, tests and benchmark harnesses. The attention and matrix kernels come from Candle. The project’s contribution is how those pieces are wired together, the guard that keeps one kernel correct, and the measurements. The result is a runtime whose perplexity agrees with llama.cpp to about 0.1% on the same file. It is faster than llama.cpp in some configurations and clearly slower in others, and the numbers below say which.

What is whose

v0.1 research prototype, developed on an 8 GB Apple M1. Newer work (CUDA, Windows, batching, KVCacheX paging, CI) is on the pushed miniinfer/integrate-kvcachex branch; figures from it are labelled.

The problem

Most local-inference projects wrap llama.cpp or Candle’s ready-made model code. I wanted to understand where the time and memory of a Llama forward pass actually go on consumer hardware, which meant owning the pass itself: weights loaded from GGUF, RMSNorm, rotary embeddings, grouped-query attention and the SwiGLU MLP. Then I had to prove it computes the same thing as the reference implementations before believing any of its timings.

The constraint shaped everything: an 8 GB laptop that was already swapping. A run that silently overcommits memory produces benchmark numbers that measure the swap file rather than the engine.

Design

  1. 01

    Load & check

    config.rs · memory.rs · model.rs

    GGUF metadata is validated, then memory::check_budget refuses the run before weights load if weights + KV + activations exceed the budget. LlamaModel::load, then warmup() compiles exactly the kernels that will run.

  2. 02

    Tokenize

    tokenizer.rs

    The HF tokenizer is checked against the GGUF vocabulary; chat prompts use the model’s ChatML template.

  3. 03

    Reuse prefix

    generate.rs

    Session::generate keeps the longest common prefix already in the cache (truncate) and recomputes only the rest — always at least one token.

  4. 04

    Prefill

    model.rs · forward()

    The remaining prompt goes through forward() in prefill_chunk-sized pieces, so activation memory stays bounded.

  5. 05

    Decode

    model.rs · sampling.rs

    One token per forward(); the sampler rejects non-finite logits instead of emitting garbage, and the loop stops at EOS, the token budget or a full context.

Inside forward() — repeated for every layer

  1. RMSNorm
  2. Q · K · V QMatMul, quantized
  3. RoPE interleaved
  4. cache.append write K, V
  5. Attention GQA, no K/V copy
  6. SwiGLU MLP + residuals
Prefill
s = one chunk of the prompt. Metal runs Candle’s fused sdpa_full kernel; its in-kernel causal mask is used only when in_kernel_causal_is_safe() holds, otherwise an explicit mask is passed (see §4). CPU uses grouped matmul with an additive causal mask.
Decode
s = 1. Metal runs Candle’s fused vector sdpa kernel directly on views of the cache; attention reads every cached position, so per-token cost grows with context.

Fig. 1 The request path and one forward pass. Switch phases to see what changes between prefill and decode.

Source docs/architecture.md

A preallocated, contiguous KV cache. Each layer reserves K and V for the full context up front. Appends copy only the new rows and attention reads views without copying, so the KV reservation is known before the first token. The cost is that a short conversation still pays for the whole reservation. For a single user that predictability was worth more than the memory paging would save. Paging is the other project’s job: main can use KVCacheX as an optional backend that attention reads through a dense mirror, and the feature branch adds in-place paged decode.

Trade-off

Measured cost of the alternative: a concat-per-step cache decoded at 32.3 tok/s vs 54.8 for the contiguous cache at 1,984 tokens on Metal (E9).

Grouped-query attention without copying K and V. Candle’s reference model repeats K/V heads to match the query heads. MiniInfer reshapes the queries instead, so each KV head is read once per group. A unit test checks that the grouped path equals the replicated one.

Detail

grouped_attention_equals_replicated in src/model.rs.

Refuse instead of swapping. Before any weights load, memory::check_budget adds up weights, Candle’s CPU repack copy, the full KV reservation, one prefill chunk of activations and the RoPE tables, and refuses with an itemised report if the total exceeds the budget. There is no silent backend fallback either: asking for Metal and getting CPU would invalidate a benchmark.

Detail

The total is an estimate, not a bound: 1,104 MiB predicted against 1,138 MiB peak RSS for a 511-token prefill (E6). Individual terms can err the other way — the repack copy was estimated at 105 MiB where 58 MiB was measured on Q4_K_M.

Measurement

The Metal kernel comparisons below are paired A/B runs inside one process: both arms run on the same loaded model, alternating which goes first, with dozens of pairs per configuration, reported as medians of per-pair ratios with bootstrap confidence intervals. Prefix reuse (Fig. 3) interleaves its two arms request by request. The comparison with llama.cpp runs each engine as its own process, in rotated order, and is described in its own section. On a fanless laptop, order and temperature effects are larger than many of the effects worth measuring.

Time to first token on Apple M1 Metal, matmul attention vs Candle's fused SDPA kernel, by prompt length
Prompt Bars Speed-up
64 tok 54.3 ms with matmul attention 48.1 ms with fused SDPA 1.13× (95% CI 1.12 to 1.13)
512 tok 707.3 ms with matmul attention 362.4 ms with fused SDPA 1.94× (95% CI 1.93 to 1.96)
1,024 tok 1,730.6 ms with matmul attention 742.4 ms with fused SDPA 2.33× (95% CI 2.32 to 2.33)
1,984 tok 4,979 ms with matmul attention 1,729.2 ms with fused SDPA 2.91× (95% CI 2.89 to 2.92)

Fig. 2 Metal prefill: MiniInfer’s matmul attention vs Candle’s fused SDPA kernel. Choose a prompt length.

Apple M1 (8 GB), Metal, SmolLM2-360M Q8_0, f32 KV. Paired in-process A/B, arm order alternated within pairs, 40 pooled pairs per length; median of per-pair ratios with 95% bootstrap CI. First tokens identical in both arms.

Source results/raw/prefill_ab/summary.md

The fused kernel is Candle’s work. MiniInfer’s part was making the cache layout fit it without copies, using native GQA, warming exactly the pipelines it needs and finding the shapes where it is wrong (§4). Decode moved to the fused vector kernel too: 5% faster at 64 tokens of context, rising to 21% faster at 1,984, in the same paired setup.

Scope

Decode, pooled median ratios: 64 → 1.05×, 1024 → 1.11×, 1500 → 1.17×, 1984 → 1.21×. Source.

Time to first token by prompt length, without and with prefix reuse
Condition No reuse (ms)Prefix reused (ms)
272 tokens prompt 1,189.1 ms — No reuse 121.5 ms — Prefix reused
1,040 tokens prompt 5,848 ms — No reuse 144.5 ms — Prefix reused

Fig. 3 Time to first token with and without in-session prefix reuse (CPU).

Apple M1 CPU, SmolLM2-360M Q8_0. Shared prefix + distinct 16-token question; arms interleaved request by request (an earlier non-interleaved run showed an order/thermal bias and was discarded). TTFT p50. Raw: results/raw/prefix_reuse_cpu.json (experiment E10).

Source docs/experiment-log.md

Is it computing the right thing?

Speed means nothing if the logits are wrong. MiniInfer is checked three ways. Real-model tests compare greedy tokens with Candle’s independent quantized_llama and incremental decoding with an uncached full-sequence pass. On the branch, default tests also run a synthetic GGUF model against quantized_llama, with no download needed. And perplexity is compared with llama.cpp’s llama-perplexity on the same file and corpus, after confirming the token ids match llama-tokenize exactly.

Perplexity of MiniInfer and llama.cpp on the same model files and corpus
Model Backend MiniInfer llama.cpp Diff
SmolLM2-360M Q8_0CPU39.715339.6791+0.09%
SmolLM2-360M Q8_0Metal39.587139.5877−0.002%
SmolLM2-360M Q4_K_MCPU40.827440.8702−0.10%
SmolLM2-360M Q4_K_MMetal40.657840.6590−0.003%

Fig. 4 Perplexity vs llama.cpp on the same GGUF files.

Corpus eval/ppl_corpus_v1.txt (8,918 tokens, n_ctx 512, 17 chunks); token ids matched llama-tokenize exactly. Statistical uncertainty ≈ ±5%, so this checks implementation agreement, not model quality.

Source docs/experiment-log.md

Against llama.cpp

An early comparison suggested MiniInfer was faster than llama.cpp on CPU at 512 and 1,024 tokens. A rerun under lighter load did not support it, and the README was changed to call the comparison unsettled. Part of the problem was that the two engines stored the KV cache at different precisions (f32 vs f16). The like-for-like rerun below uses f16 in both. The short-context advantage disappeared. The long-context CPU advantage held, with non-overlapping ranges at 2,048 tokens.

Corrected

History in docs/experiment-log.md (E12 → E18 → E22). The original tables are kept in the log and marked superseded rather than deleted.

Prefill and decode throughput of MiniInfer and llama.cpp on Apple M1
Backend · prompt MiniInfer prefill llama.cpp prefill MiniInfer decode llama.cpp decode
CPU · 128422.9506.089.5102.8
CPU · 512326.2372.977.165.4
CPU · 1024277.9254.066.049.0
CPU · 2048220.1160.848.933.1
Metal · 1281545.22154.993.485.7
Metal · 5121584.22221.689.684.7
Metal · 10241558.12114.881.182.3
Metal · 20481470.61890.375.979.0

Fig. 5 Like-for-like with llama.cpp on the M1: prefill and decode throughput (tokens/s, higher is better).

Apple M1, same GGUF (SmolLM2-360M Q8_0), f16 KV in both, llama.cpp build 11669 via llama-bench, batch 512, 64 generated tokens, 5 runs × 2 rounds with engine order rotated and 15 s cooldown. Machine was not idle (2.8 GB swap in use).

Source results/raw/macos_m1/fair_20261201T064853Z/summary.md · on a pushed feature branch

On Metal, llama.cpp prefills 1.29–1.40× faster at every length, and decode is within about 10% either way. MiniInfer used 27% less memory there (502 vs 685 MiB peak RSS). On a Windows laptop with an RTX 4070, run by a friend from the same scripts, llama.cpp was far ahead: 3.6–4.1× faster decode on CUDA. MiniInfer’s CUDA decode sits flat at about 90 tok/s, which points at per-token overhead (many small kernels and a host sync per token) rather than arithmetic. I haven’t profiled it yet.

Reading it

Windows results: results/raw/windows_cuda/REPORT.md (branch). With f32 weights all five CUDA tests pass; one quantized comparison exceeds its pre-set bound (3.32 vs 3.0), and the bound was not loosened.

A bug in the kernel

Moving prefill to Candle’s fused kernel made a model test fail: 100-token chunks at offset 700 produced a maximum logit difference of 0.53, against 0.0074 for the matmul path. I narrowed it to Candle 0.11.1’s Metal sdpa with in-kernel causal masking, which lets queries see future keys for certain shapes. A standalone reproduction using only Candle APIs, compared against a CPU explicit-mask reference, found 24 of 49 tested shapes wrong.

Maximum absolute error by query and key length
Query length Key length Max |error| Result
2642.8e-2Wrong
31649.2e-1Wrong
32647.2e-7Correct
34641.3e-1Wrong
63642.75Wrong
348006.8e-3Wrong
638001.2e-1Wrong
any100≤ 8e-7Correct

Fig. 6 Selected shapes from the reproduction: maximum absolute error of Metal causal SDPA vs an explicit-mask reference.

examples/sdpa_causal_repro.rs: Candle Metal sdpa(do_causal=true) vs a CPU explicit-mask reference, f32, head_dim 64, 4 heads, on the M1. 24 of 49 tested shapes were wrong; every other shape agreed to ≤ 1.6e-6.

Source docs/upstream-candle.md · on a pushed feature branch

MiniInfer works around it. in_kernel_causal_is_safe() allows the kernel’s own masking only where its block-limit arithmetic is provably in range, and passes an explicit mask otherwise, so the fused kernel stays on by default without the wrong answers. The analysis points at an unclamped block limit and a masking window that is too narrow when the key and query lengths are misaligned. An open upstream PR (huggingface/candle#4062) addresses it.

Status

Not yet reported upstream by me. A draft comment with the reproduction is in docs/upstream-candle.md. Part of the index analysis was done with an AI review agent; the reproduction itself is ordinary code anyone can run.

Where it stops

  • Scope. Dense Llama-family GGUF only. Two models are validated: SmolLM2-360M, and Llama-3.2-1B on the branch. Mixture-of-experts models, sliding-window attention and other architectures are rejected at load time rather than run incorrectly.
  • Not a server. One user. The batch engine on the branch has no preemption and runs each joining request’s prefill alone.
  • Numerics. Exact equivalence with the references is verified only with dequantized f32 weights. Candle’s CPU int8 activation quantization makes results depend on evaluation shape.
  • Memory. Candle’s CPU repack keeps a second copy of the weights (+314 MiB on 367 MiB of SmolLM2 weights). It is documented in the repo, not yet fixed.
  • Hardware. Most numbers come from one swapping 8 GB M1 whose GPU switches between performance states roughly 1.6× apart. CUDA has been run on one Tesla T4 and one RTX 4070 laptop only.

Read the implementation

  1. LlamaModel::forward One forward pass: RMSNorm, RoPE, GQA, SwiGLU
  2. Session::generate Prefix reuse and chunked prefill
  3. memory::check_budget Memory pre-flight
  4. incremental_decode_matches_uncached_full_sequence Incremental decode equals an uncached pass

Evidence

Every number on this page comes from one of these files, pinned to the commit it was read from.

  1. results/raw/prefill_ab/summary.md main @ 5c0d5e4
  2. results/raw/decode_ab/summary.md main @ 5c0d5e4
  3. docs/experiment-log.md main @ 5c0d5e4
  4. results/raw/macos_m1/fair_20261201T064853Z/summary.md feature branch @ a2d329c
  5. docs/upstream-candle.md feature branch @ a2d329c
  6. docs/known-limitations.md main @ 5c0d5e4
  7. results/raw/windows_cuda/REPORT.md feature branch @ a2d329c