tiny-llm runs a 1-billion-parameter language model on a MacBook Air’s CPU. It has no GPU, no ML framework, and its tensors are written by hand. It also has a terminal UI that shows, token by token, where the model is looking. The first full run took about four minutes for one answer. Seven weeks of work later, it generates around six tokens a second.

This post covers what I built, which optimizations paid off, which didn’t, and where I’m going next.

tiny-llm generating text in the terminal, with attention heatmaps, candidate logits and latency stats updating live

Why I built it

I wanted to understand large language models properly, beyond calling an API. The best way I know to understand something is to write it down in code, so every idea in tiny-llm lives in the source, with comments explaining it.

There was also a practical reason. I was planning AI features for my note app, OpenNote, and wanted to know what running a model locally really takes. OpenNote has since been sunset. In that post I called tiny-llm “the counterexample I built by accident”: a small project with a clear scope, which ended up getting more attention than the big one.

What tiny-llm is

A minimal inference engine for MiniCPM5-1B, written in Rust:

  • CPU-only. You don’t need a GPU.
  • Hand-written tensors. TinyTensor and its operations are my own code. I learned a lot from reading candle.
  • A KV cache, so each new token doesn’t recompute the whole history.
  • A TUI that shows how the model “thinks” while it generates.

These are the parts of the model I implemented:

Component What it does
Embedding Looks up a vector for each token ID
RoPE Encodes each token’s position by rotating its query and key vectors
Attention Multi-head attention with GQA (grouped query attention)
MLP Feed-forward block with the SwiGLU activation
Normalization RMSNorm before attention and the MLP
Residual connections Skip connections after attention and the MLP

The TUI

The TUI is what makes tiny-llm more than another engine. While the model generates, you can see:

  • Attention heatmaps for each layer and head (such as L23 H4). Rows are query tokens, columns are context tokens, and brighter cells mean more attention.
  • Candidate logits: the tokens the model is weighing and their raw scores. The top one is picked (greedy decoding).
  • Latency and throughput: time to first token, average and P95 latency per token, and tokens per second.
  • Tensor shapes per layer, such as [1, 1, 1536] for one new token with 1,536 hidden features, and [1, 1, 130560] at the LM head, which gives one score for every word in the vocabulary.

Watching the heatmap change from many rows (processing the prompt) to a single row (generating one token with the KV cache) taught me more about attention than any diagram had.

How it went

When Milestone
Jun 24 First commit, under the name “tiny-llama”: RMSNorm, then a linear layer and vector math
Jun 29 RoPE
Jul 10 A complete MiniCPM5-1B engine built on candle, plus the TUI
Aug 4 Replaced candle with my own TinyTensor
Aug 11 SIMD for element-wise and broadcast operations
Aug 13 Turned on Apple AMX for matrix multiplication
Aug 14 KV cache, and the TUI updated to work with it

I kept each stage on its own branch, such as candle-based-implementation and without-kv-cache. If you want to learn from the code, start with the simplest version and add one idea at a time.

Making it fast

Every optimization started from a profile, not a guess. I used Instruments on an M3 MacBook Air, found the biggest hotspot, and worked on that. I wrote down every result in OPTIMIZATIONS.md, including the experiments that failed.

Step 1: My own tensor

Moving from candle to TinyTensor didn’t make anything faster, and that wasn’t the goal. The goal was to own every operation, so I could understand and change it. My version ended up on par with candle’s CPU backend, which was good enough.

Step 2: SIMD — the big win

Most tensor operations in a transformer are element-wise: add these two tensors, multiply by this scale. My first version did them one number at a time. I switched the contiguous cases to rten-simd, which processes several numbers per instruction using the best instruction set available on the CPU at runtime. Broadcasting and strided layouts still fall back to the general path, so the results stay the same.

End-to-end inference time, one prompt (shorter is better)

Before SIMD  ########################################  4m 3s
After SIMD   ###########                               1m 5s   (~3.7x faster)

One prompt went from 4 minutes 3 seconds to 1 minute 5 seconds, about 3.7× faster. The linear-layer function’s share of the profile fell from 26% to 5.8%. This came from one profiling comparison, not a controlled benchmark, but the size of the jump left no doubt.

Step 3: SwiGLU — the experiment that failed

After SIMD, the new hotspot was compute_swiglu, at about 48.6% of inference time. SwiGLU computes two projections of the same input, “gate” and “up”, then combines them. I tried two ideas:

  1. Fuse the two weight matrices into one, so that one big matrix multiplication replaces two. Performance didn’t change, whether I fused the weights on the fly or once at load time.
  2. Run the two projections in parallel. This made things worse.
Per-token latency, ms (shorter is better)     # sequential   = parallel

Average  #######################                  430.71
         ========================                 449.27
Median   #####################                    404.49
         ======================                   415.88
P95      #####################################    695.82
         =======================================  737.05

Throughput: 2.32 -> 2.23 tokens/s (single runs, 96 vs 101 tokens emitted)

The reason became clear once I looked inside the matrix multiplication: each one was already using every CPU core through Rayon. Running two at the same time didn’t add any parallelism. They just competed for the same cores, cache and memory bandwidth.

Parallelism doesn’t stack when the inner operation already fills the machine. I didn’t commit either change and moved on.

Step 4: Matrix multiplication — read before you rewrite

At this point matrix multiplication was about 41% of the profile, so the obvious next step was to write a faster one. Before doing that, I read the dependency I was using, gemm. It already has hand-tuned SIMD kernels for each architecture: NEON on Apple Silicon, AVX on x86, and AVX-512 if you opt in. It picks the best one at runtime. Writing my own would have duplicated work that was already done well.

What I found instead was an opt-in feature: experimental-apple-amx. It lets gemm use the matrix coprocessor on M1–M3 chips. Turning it on was a one-line change.

Share of profile samples                      = before   # after

compute_linear_layer  =======================              26%
                      #####                                5.8%  (after SIMD)
matrix_multiply       ==================================== ~41%
                      #################################    ~37%  (after AMX)

It was a modest gain, from about 41% to 37%. It also told me something useful: matrix multiplication was close to its limit, and any further big gains would have to come from doing less work, not from doing the same work faster.

Step 5: KV cache — doing less work

A transformer generates text one token at a time. Without a cache, every new token means feeding the whole text back through every layer and recomputing everything for every earlier token, again. The work grows with every token.

But look at what attention actually needs. For each layer it needs:

  • a query (Q) for the new token only, and
  • keys (K) and values (V) for every token so far.

The K and V of earlier tokens never change. So the engine can store them, compute K and V for the new token only, and append them to the cache. Q is thrown away after each step. That’s the whole idea of the KV cache.

Decoding throughput, tokens/s (longer is better)

Without KV cache  #########                              ~1-2 tok/s
With KV cache     #####################################  ~6 tok/s   (~3x)

Generation went from 1–2 tokens per second to about 6, roughly 3× faster. Of everything I did, it gave the most gain for the least code.

What I learned

1. Shapes are where the bugs are

Almost every bug I hit while building the KV cache was a shape mismatch. Syntax errors hardly mattered next to them. A tensor shaped [batch, heads, seq, dim] and one shaped [batch, seq, heads, dim] hold the same number of values, so nothing crashes. The output is simply wrong. Writing tensor code means getting into the habit of asking, at every line, what shape you’re holding.

2. Profile, then decide

Every successful step started with a profile, and so did the failed one. That matters just as much: the profile showed that SwiGLU was the hotspot, and the measurements showed that my ideas for it didn’t help. Without numbers, I would have kept the “parallel” version, because it sounds faster.

3. Write down the negative results

OPTIMIZATIONS.md lists the experiments that were never committed, with their numbers. Six months from now, that’s what stops me (or a reader) from trying the same idea again.

4. Hand-write what you want to understand, reuse the rest

I wrote attention, RoPE, RMSNorm, SwiGLU and the tensor type myself, because those were what I wanted to learn. I didn’t write a GEMM kernel, a SIMD layer or a tokenizer, because excellent ones already exist. This is the same “reuse first” lesson that OpenNote taught me, applied with clearer judgment about what to reuse.

5. A small scope gets finished

tiny-llm took about seven weeks and 40 commits. It has 43 stars, and the MiniCPM team at OpenBMB featured it on X, with a graphic they made:

OpenBMB's graphic featuring tiny-llm as a MiniCPM5-1B inference engine in Rust

The project had a single clear goal: run one model, correctly, and show how it works. Because of that, every commit moved it forward.

What tiny-llm can’t do

To be honest about its limits:

  • FP32 only. No quantization, so even a 1B model uses several gigabytes of memory.
  • One model architecture. It runs MiniCPM5-1B and nothing else.
  • Greedy decoding only. No temperature, top-p or chat template.
  • CPU only. No Metal, CUDA or Vulkan backend.
  • Single prompt. No conversation loop and no server.
  • About 6 tokens per second on a 1B model. Fine for learning, too slow for real work.

That’s fine for what tiny-llm is: an engine to learn from. It’s not an engine to use every day.

What’s next

My next goal is to build an inference engine that runs real, productive local models on consumer-grade hardware. I mean models you’d actually rely on for writing, coding and research, running at a usable speed on the laptop or desktop you already own. Not a 1B demo.

tiny-llm showed me where the hard parts are. Memory bandwidth matters more than raw compute, cutting work matters more than speeding it up, and you should measure everything. I’ll share more once there’s something to show.

If you want to learn how an LLM works from the inside, tiny-llm is on GitHub under the MIT license. Start with the candle-based-implementation branch, then work forward.

Thanks

To OpenBMB for MiniCPM and for the shout-out. To candle, whose codebase taught me how tensors are built. To gemm and rten-simd, which did the heavy lifting I chose not to rewrite. And to everyone who starred the repo.