Skip to content
mattsaundPublic

About

A small, fast LLM inference engine for GGUF models on low-power hardware. A lightweight alternative to llama.cpp, in Rust with zero dependencies.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

SmaLLM

SmaLLM is an inference engine for language models in GGUF format, the format llama.cpp and Ollama use. It targets single-board computers, mini PCs and old laptops, and uses GPUs where there are some. One binary of 1.5 to 2.8 MB, no dependencies, no required configuration. Anonymous memory beyond the mapped model file is a few MB.

Website: https://msaunders.dev/smallm/

Binary size, release builds:
2.34 MB Linux (x86_64), 1.86 MB Linux (arm64)
2.55 MB and 2.07 MB for the same with GPUs
1.85 MB Linux (armv7), 1.51 MB Linux (riscv64)
2.39 MB macOS (Intel), 1.96 MB macOS (Apple silicon)
2.75 MB Windows (x86_64), 2.24 MB Windows (arm64)

Anonymous memory, Llama 3.2 1B, 4,096-token context:
7.6 MB. llama.cpp b12858: 637 MB. Memory has the method and the trade-offs.

Install

Linux, macOS

curl -fsSL https://raw.githubusercontent.com/mattsaund/SmaLLM/main/install.sh | sh

Windows

irm https://raw.githubusercontent.com/mattsaund/SmaLLM/main/install.ps1 | iex

Downloads the newest release for the machine and verifies it against the release's SHA-256 checksums. Installs one binary to ~/.local/bin. Linux binaries are static and run on any distribution. A static program cannot open a GPU driver, so a machine with a graphics card, Vulkan and glibc 2.35 gets a Linux binary that can. SMALLM_GPU=0 or 1 in front of sh decides it by hand. Missing dependencies are installed after a prompt: curl for model downloads, plus Rust and a C compiler when no release exists for the machine and SmaLLM is built from source.

smallm uninstall removes the binary, downloaded models and settings. What changed: CHANGELOG.

Use

smallm pull bartowski/SmolLM2-135M-Instruct-GGUF   # download a model, 105 MB
smallm run SmolLM2-135M                            # chat with it
smallm run SmolLM2-135M "Why is the sky blue?"     # one answer, then exit
smallm serve SmolLM2-135M                          # an OpenAI-compatible API

A model is a .gguf file, or the name of a downloaded model. Part of the name is enough when it singles one out.

Command Does
run <model> [prompt] Answers a prompt, or opens a chat when none is given
serve [model...] Serves OpenAI's API (/v1/chat/completions, /v1/completions, /v1/embeddings, /v1/models), Anthropic's (/v1/messages), Ollama's (/api/chat and others), and /v1/rerank, /tokenize, /detokenize, /apply-template and /slots. Several models, or all that are downloaded, load when a request wants them
embed <model> [text...] Prints the embedding of each text, one JSON array per line
rerank <model> <query> <document>... Scores how well each document answers the query, best first
pull <user/repo> Downloads a model from Hugging Face, all its files. user/repo:q8_0 picks a quantization
list, rm <model> Lists downloaded models, deletes one
info <model> Shows what a model is: size, layers, weight format, chat format
bench <model> Measures speed on this machine. --profile shows where the time goes
devices Lists the GPUs that models can run on
perplexity <model> -f <file> Measures how well a model predicts a text
tokenize <model> <text> Shows how a model reads a text
config Shows the settings and where they are kept. --reset restores the defaults
uninstall Removes the program, its downloaded models and its settings

smallm <command> --help lists the options of a command: threads and the CPUs to run on, context size, what to do when the context is full, temperature and the other sampling settings, stop strings, system message. Sampling settings that the model file recommends are the defaults. In a chat, /clear starts over, /system sets a system message, /save and /load keep the conversation in a file and /exit leaves. --session names such a file on the command line. It holds the model's cache, so a conversation goes on without being read again.

GPUs. A graphics card or Apple's GPU is used when there is one and the model runs on it, and the CPU runs the layers that do not fit. --device cpu stays on the CPU, --device 1,2 uses the GPUs of those numbers in smallm devices, and --gpu-layers limits the layers. It goes through Vulkan and Metal, without CUDA or another toolkit to install.

Reasoning output. For models that emit reasoning before the answer (Qwen3, LFM3, Gemma 4, Inkling 2, DeepSeek R1, gpt-oss), the chat prints it dimmed and keeps it out of the conversation history. Piped output omits it. The server returns it as reasoning_content, the field llama.cpp uses. --think off makes Qwen3, LFM3 and RWKV-7 G1 answer without reasoning, and --think on turns it on for Gemma 4. gpt-oss always reasons and takes --think low, medium or high. Inkling 2 sets its effort from the same choices: off is 0, which shortens its reasoning but does not end it. In the server, chat_template_kwargs.enable_thinking and reasoning_effort choose per request. --reasoning-budget 200 ends the reasoning after 200 tokens, so that the answer begins.

Structured output. --json-schema (-j) keeps an answer to JSON that follows a schema, and --grammar to a grammar in llama.cpp's GBNF notation. The server takes OpenAI's response_format and llama.cpp's grammar and json_schema.

smallm run SmolLM2-135M "Describe a cat." -j '{"type": "object",
  "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
  "required": ["name", "age"]}'

Adapters. --lora adapter.gguf adds a LoRA adapter to a model, and --lora adapter.gguf:0.5 half of it. --control-vector adds a control vector. Both are read in place.

Settings. Every setting has a line in one file, smallm.conf, named like its command-line option. smallm config shows the settings in effect and where the file is, and writes it with the defaults the first time. smallm config --reset puts the defaults back. An option on the command line wins over the file.

What it runs

Models. 181 of the 183 architectures that llama.cpp b12870 names:

  • Transformers: Llama, Mistral 3, Qwen to Qwen3 (the language models of Qwen-VL included), Gemma to Gemma 4 and Gemma 3n, Phi-2 to Phi-4, OLMo to OLMo 3, GLM-4, ERNIE 4.5, Hunyuan, EXAONE, InternLM2, MiniCPM, Command-R, Granite, SmolLM3, Seed-OSS, Apertus, Nemotron, StableLM, StarCoder 1 and 2, Falcon, GPT-NeoX (Pythia), GPT-2, BLOOM, MPT, T5, BitNet and more.
  • Mixtures of experts: gpt-oss, Mixtral, Llama 4, the MoE models of Qwen, GLM-4.5, ERNIE, Hunyuan, Granite, LFM2, OLMo, Phi and Arcee, Ling, dots.llm1, MiniMax M2 and M3, MiniCPM 5, Kimi K3, Grok, DBRX, MiMo V2, Hunyuan V4, DeepSeek from MoE to V4 with latent and sparse attention and hyper-connections, and Inkling 2 and Inkling 2 Mini, whose blocks attend over the outputs of earlier blocks and whose middle layers run three times.
  • Hybrids and models that are not transformers: Qwen3.5 and Qwen3-Next (gated delta nets and attention), LFM2 and LFM3 (short convolutions and attention), Granite 4.0 H, Falcon-H1, Nemotron-H and Jamba (Mamba and attention), Kimi Linear, MiniMax-01, PLaMo 2, Mamba, Mamba 2, RWKV-6 and RWKV-7.
  • Diffusion models (Dream, LLaDA), decision models (Clef), draft models (EAGLE-3, DFlash, Gemma 4's assistant), and the text sides of image and speech models.
  • Embeddings and reranking: BERT, nomic-bert, Jina's, ModernBERT, EuroBERT, NeoBERT, EmbeddingGemma, Qwen3-Embedding and Qwen3-Reranker. Any other decoder makes embeddings with --pooling.

The engine is tested against llama.cpp on 35 models. Tokens match exactly, and greedy output matches up to near ties between two candidates. Every architecture added since 0.4.0 is also compared with llama.cpp b12870 on a small random model (tools/reference). LFM3 is checked against llama.cpp's source.

Tokenizers. SentencePiece, byte-level BPE with the word splitting rules of all 71 families llama.cpp knows, Gemma 4's, RWKV's World tokenizer, and the encoder tokenizers WordPiece (BERT) and Unigram (T5, XLM-RoBERTa). llama.cpp's own tokenizer test texts pass on every vocabulary it ships that uses one of these, and on RWKV's.

Weights. F32, F16, BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2_K, Q3_K, Q4_K, Q5_K, Q6_K, the i-quants IQ1_S, IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_NL and IQ4_XS, the ternary TQ1_0 and TQ2_0, MXFP4, NVFP4, and the 1- and 2-bit Q1_0 and Q2_0. Dequantization is bit-exact with ggml for every format, checked by tests/quant.rs. Weights stay in the file's format and are memory mapped. Loading takes milliseconds and allocates no memory for weights.

Platforms. Linux, macOS and Windows. x86-64 with AVX2 and ARM64 with NEON get hand-written kernels, selected at startup. Everything else, including 32-bit ARM and RISC-V, runs portable code. GPUs run models with plain attention and feed-forward networks, the Llama, Qwen, Gemma 1 to 3 and Phi kind. Experts, hybrids and the rest run on the CPU.

Chat formats. The Jinja template in the model file, run by an interpreter built in. Sixteen formats are written out by hand for files without one that runs: ChatML, Llama 3, Llama 2, Mistral, Gemma, Gemma 4, Granite, Phi-3, Phi-4-mini, Zephyr, DeepSeek, DeepSeek V2, Kimi, OpenAI's Harmony (gpt-oss), RWKV World and Inkling.

Tool calls. The server takes OpenAI's tools and answers with tool_calls. How a model writes calls is learned from its template, and they are held to the tools' schemas. Models whose template has no tools are told about them in words.

Speed

Llama 3.2 1B, Q4_K_M, in tokens per second:

Threads Prompt: SmaLLM llama.cpp Ollama Generation: SmaLLM llama.cpp Ollama
1 182 104 101 26.1 27.0 25.3
2 351 198 201 42.0 39.3 40.3
4 678 386 389 48.9 46.4 48.0
8 1209 706 716 52.4 48.9 50.9
2, ARM board 53.6 29.2 41.7 11.4 10.0 10.7

Intel Core i7-14700K under Linux, and an Allwinner A733's two Cortex-A76 cores. Release builds of llama.cpp b12858 and Ollama 0.40.18 on the CPU, a 256-token prompt (128 on the board) and 64 tokens generated after it, the best of five runs (three), the engines taking turns. With its threads tuned, llama.cpp reaches 744 and 51.4 on 8 threads. docs/PARITY.md has 28 more models and formats.

On GPUs, a 512-token prompt (about 500 for Ollama) and 128 tokens generated:

GPU Prompt: SmaLLM llama.cpp Ollama Generation: SmaLLM llama.cpp Ollama
RTX 5060 Ti 27,362 19,372 18,462 359 345 323
RTX 3060 12,467 11,298 10,691 262 272 254
Apple M4 1,537 1,451 1,361 121 112 113

Vulkan and Metal, against llama.cpp b12870's CUDA build (its Vulkan build is slower) and Metal, and Ollama 0.40.18. The two cards are on PCIe x1 links.

Guessing ahead. Where an answer repeats its context, as in edits of code, summaries and lists, or where a grammar leaves one way to go on, the next tokens are guessed and evaluated together. Guesses are checked, so the answer is the same byte for byte. Llama 3.2 1B, 8 threads, in tokens per second:

Task One at a time Guessing ahead
Rename a variable in 30 lines of code 36 90
A JSON list of five records, with a schema 48 86
A 250-word explanation 46 49

--draft-max 0 turns it off, and --model-draft adds a small model that guesses.

Memory

Weights are never copied out of the model file, and nothing is allocated before it is used. Anonymous memory (RssAnon), Llama 3.2 1B Q4_K_M:

Model loaded Session, 4,096-token context After 256 tokens
SmaLLM 7.5 MB 7.6 MB 26 MB
llama.cpp 508 MB 637 MB 668 MB

As servers, after the same request, SmaLLM holds 32 MB, llama.cpp 695 MB and Ollama 1,038 MB. The difference grows with the weights. On gpt-oss-20b (MXFP4) the servers hold 66 MB, 9,957 MB and 11,817 MB.

How it works

  • Weights are read in place. The GGUF file is memory mapped, and the kernels read its quantized blocks in the file's layout. llama.cpp repacks most weight tensors into an interleaved layout in anonymous memory at load, which is most of its 508 MB. SmaLLM packs a few rows into a cache-sized tile per prompt batch instead, the packing step of BLAS-style matrix multiplication (GotoBLAS, BLIS). Generation reads the file layout directly.
  • The key/value cache is allocated on demand, in 256-position chunks of 16-bit floats. llama.cpp allocates the whole context window when the session starts. Memory scales with the tokens in the context, not with the configured window. Layers that attend over a sliding window (Gemma, gpt-oss, LFM2) also free the chunks that fall behind it. --cache-type q8 keeps 8-bit integers in 56 percent of the memory.
  • Small working set. Scratch buffers are sized for a 64-token batch, or 128 for models with experts. The vocabulary is read from the mapped file. Logits are computed for the last token only.
  • Per-architecture state. DeepSeek's latent attention caches one compressed row per position and layer. Mamba and RWKV keep a fixed-size recurrent state and one saved copy of it. Gemma 4's shared layers have no cache of their own.

Use cases

  • Low-RAM boards. RAM goes to the model's pages and to other processes.
  • Models close to RAM size, especially mixtures of experts. A token reads only its routed experts. The kernel evicts the pages of cold experts and faults them back in when they are needed.
  • Several processes on one model. Mapped file pages are shared through the page cache, so every process uses the same copy of the weights.
  • Millisecond loads. Nothing is copied or repacked at load.

On a graphics card the weights are in its memory. A server with Llama 3.2 1B then holds 83 MB of its own and 848 MiB of the card's, llama.cpp's CUDA build 305 MB and 1,120 MiB. On an Apple GPU the weights stay in the mapped file: 124 MB against 270.

Trade-offs

  • Total memory still includes the model. The figures above leave out file-backed pages, and full speed needs the file resident. The total for a server with Llama 3.2 1B is 0.80 GB for SmaLLM, 1.47 GB for llama.cpp and 1.07 GB for Ollama, which does not map the file.
  • Under memory pressure, speed depends on storage. The kernel evicts file pages and faults them back in on access. That is workable on NVMe or eMMC and slow on an SD card. llama.cpp's repacked copy is anonymous memory and can only go to swap. --mlock keeps the whole file resident instead, which costs reading all of it at load and needs a locked-memory limit (ulimit -l) as large as the file.
  • No up-front check. A context window too large for the machine fails when the conversation reaches it, not when the session starts.
  • Packing on every prompt batch. Tiles are packed per batch, not once at load. On x86 the kernels absorb the cost (see Speed). On an Allwinner A733's Cortex-A76 cores packing takes about 6 percent of a prompt's time, and Q4_0 prompts run 7 percent behind llama.cpp on the two fast cores (docs/PARITY.md). Q4_K_M prompts run 1.5 to 3.5 times as fast there.

Measured with smallm bench, which prints these figures on Linux, against llama.cpp b12858 on an Intel Core i7-14700K with a 4,096-token context.

Size

The program (chat, server, downloader) is 1.51 to 2.75 MB depending on the platform. The engine as a shared library is 1.66 to 2.32 MB. llama.cpp b12858's CPU-only libraries total 8.5 MB on the same machine, and 27 MB with the ones its server and chat need. Ollama's program is 45 MB, next to 65 MB of CPU libraries. Both have features SmaLLM lacks, listed in docs/TODO.md.

Release builds compile the standard library for size (-Z build-std with optimize_for_size), which saves about 20 percent. The program around the engine is always compiled for size. A source build with stable Rust is about 3.3 MB.

Context

The context window has no built-in limit. The key/value cache is allocated in 256-token chunks as the context fills, so a large window allocates nothing up front.

smallm run model.gguf --ctx 262144

Tested end to end at 262,144 tokens. The practical limit is memory, 32 KB per token for Llama 3.2 1B. Output quality degrades past the model's training length. The default window is the model's training length, capped at 4,096 tokens.

When the window is full, --overflow (or the overflow setting) decides:

Choice Does
middle (default) Keeps the start, the system prompt and the first question, and drops the oldest tokens after it
slide Drops the oldest tokens and slides forward
stop Ends the answer

Kept tokens are not evaluated again. Their cached keys are rotated to their new positions, which takes milliseconds.

Use it from your code

SmaLLM is a library first. The program is one user of it.

Rust

use std::sync::Arc;
use smallm::{generate, Model, Session, SessionConfig};

let model = Arc::new(Model::load("model.gguf")?);
let mut session = Session::new(model, SessionConfig::default())?;
let options = generate::Options { max_tokens: 64, ..Default::default() };
generate::run(&mut session, "Once upon a time", &options, |piece| {
    print!("{piece}");
    true
})?;

C, and every language that can call C

#include "smallm.h"

smallm_model *model = smallm_model_load("model.gguf");
smallm_session *session = smallm_session_new(model, NULL);
smallm_generate(session, "Once upon a time", NULL, print, NULL, NULL);

Python

import smallm

model = smallm.Model("model.gguf")
session = model.session()
print(session.chat([{"role": "user", "content": "Hello!"}]))

JSON schemas, tools, reasoning and every sampling setting go through session.request (smallm_request in C), which takes what the server takes.

Anything that speaks HTTP

smallm serve model.gguf
curl http://127.0.0.1:8080/v1/chat/completions \
  -d '{"messages": [{"role": "user", "content": "Hello!"}]}'

Requests that come at the same time run together, four by default (--parallel). Their tokens share one pass over the weights: four answers at once from Llama 3.2 1B come at 132 tokens per second together, where one comes at 41 (i7-14700K, 8 threads). What conversations begin with, such as the same instructions, is read once and is in memory once. smallm serve a.gguf b.gguf serves both models, loaded when a request wants them. Clients made for Anthropic's and Ollama's APIs work too.

Each release has the library for Linux, macOS and Windows, shared and static, with the header and the Python binding. capi/README.md covers the C API, and docs/ARCHITECTURE.md how the engine works.

Status

Version 0.7.0. docs/TODO.md lists what is done and what is left, and docs/PARITY.md compares SmaLLM with llama.cpp and Ollama area by area, with measurements.

Build from source

Rust 1.85 or newer, and nothing else.

git clone https://github.com/mattsaund/SmaLLM
cd SmaLLM
cargo build --release                  # target/release/smallm
cargo build --release -p smallm-capi   # the C library, beside it
cargo test --workspace

The smaller build that the releases use needs a nightly compiler. .github/workflows/release.yml has the exact flags.

Contributing

AI policy. I am open to AI and agentic coding, but the code written needs to follow specific guidelines:

  1. MUST be human readable, acceptable variable/function names.
  2. Easily traceable, following a good program flow.
  3. Contributors MUST look at and document code and code changes. You need to understand the code that is being written.

Tests. cargo test, cargo clippy and cargo fmt. CI runs all three on Linux, macOS and Windows, on x86-64 and ARM, and compares the engine's output with llama.cpp's on real models. docs/CONTRIBUTING.md has the project map and the rules, and docs/DEVELOPMENT.md what to measure on a single-board computer. A version is released by tagging it. See .github/workflows/release.yml.

License and credits

Created by Matthew Saunders, https://msaunders.dev

MIT. See LICENSE. SmaLLM has no dependencies, so nothing else is compiled in. The GGUF format and the layouts of the quantized weights come from llama.cpp (MIT), whose output is the reference this engine is tested against. The character tables in src/tokenizer/unicode_tables.rs are derived from the Unicode Character Database.

About

A small, fast LLM inference engine for GGUF models on low-power hardware. A lightweight alternative to llama.cpp, in Rust with zero dependencies.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages