gemma4.c README

The project's README from github.com/qmog-ai/gemma4.c. As one markdown file: README.md.

gemma4.c

Gemma 4 E2B CPU inference in 700 lines of pure C.

An educational project made to understand how LLM inference works. The full inference path is implemented in one file without external libraries.

For a detailed walkthrough of the implementation, see the blog post.

Quick start

gemma4.c runs on Linux and Windows. You need a CPU with AVX2, an OpenMP-capable C compiler, and make. The model takes about 5.0 GB of disk space, and 8 GB of RAM is recommended.

Clone the repository and download the ready-to-run model:

git clone https://github.com/qmog-ai/gemma4.c
cd gemma4.c
python3 -m pip install -U huggingface_hub
hf download QmogAI/gemma4-e2b-int8 gemma4-E2B-int8.bin --local-dir .

On Linux:

make
./run -t 0 -n 256 "Why is the sky blue?"

On Windows, use a MinGW-w64 environment that provides gcc, OpenMP, and make:

make win64 WINCC=gcc
.\run.exe -t 0 -n 256 "Why is the sky blue?"

Options

Model

gemma4.c runs google/gemma-4-E2B-it-qat-q4_0-unquantized, the unquantized QAT checkpoint Google released for Gemma 4 E2B. The C runtime cannot read that checkpoint directly. exporter.py takes its tokenizer and language-model weights and writes them in the exact layout used by gemma4.c.

Matrix weights are stored as int8 with FP16 scales. Inputs to linear layers are dynamically quantized to int8 while the rest of the activations remain float32. The resulting file is about 5.0 GB (4.7 GiB).

To create it yourself instead:

python3 -m pip install -r requirements.txt
python3 exporter.py /path/to/gemma-4-E2B-it-qat-q4_0-unquantized -o ./gemma4-E2B-int8.bin

Python is only needed to export the model or run numerical validation. Once the .bin file exists, inference runs entirely through the C program.

Benchmark

Measured on an AMD Ryzen 7 7700 using the default native build.

Prefill (tok/s)

Prompt tokens gemma4.c (int8) llama.cpp (Q8_0)
512 630.73 272.69
2,048 494.14 258.56
8,192 254.02 223.99
16,384 106.36 188.60

Decode (tok/s)

Starting context gemma4.c (int8) llama.cpp (Q8_0)
512 25.16 22.67
2,048 24.04 21.28
8,192 20.35 17.82
16,384 16.80 14.26

Prefill measures the time to process the stated number of prompt tokens. Decode first fills the KV cache to the stated depth, then measures 128 single-token steps. Both include the logits needed to produce the next token, but exclude sampling and terminal output. Results are the mean of three timed runs after one discarded warmup. Both implementations use FP32 KV caches, 512-token batches, eight CPU threads, and native builds.

The benchmark command takes the prefill length followed by the number of decode steps:

./run -m ./gemma4-E2B-int8.bin --bench 512 128

Numerical validation

The implementation is validated against the Hugging Face Transformers reference implementation running Google's unquantized Gemma 4 E2B QAT checkpoint in BF16. Both implementations process the complete Éva Gauthier article from the WikiText-103 validation split under teacher forcing, comparing logits at all 2,388 token positions.

Metric Result
Top-1 agreement 2,305 / 2,388 (96.5%)
Mean KL divergence 0.005207

An exact match is not expected because gemma4.c uses int8 matrix weights and linear inputs while the reference runs the unquantized checkpoint in BF16. The output distributions nevertheless remain closely aligned.

Build the C runtime first (make or make win64). The complete validation peaks at about 10 GiB of RAM:

python3 validation.py

Pass a smaller token count for a quicker check:

python3 validation.py 64

validation.py uses the runtime's --dump-logits flag to collect float32 logits after each prompt position. The flag can also be used directly when comparing gemma4.c with another implementation:

./run -m ./gemma4-E2B-int8.bin --dump-logits "Why is the sky blue?" > logits.bin

Repository contents

gemma4.c (qmog-ai/gemma4.c)

Searching Database…

Что это?gemma4.c — это рантайм инференса на CPU для модели Google Gemma 4 E2B, написанный примерно на 700 строках чистого C и созданный, чтобы показать, как инференс LLM на самом деле устроен под капотом.
Это библиотека для линковки с моим кодом или отдельная программа?Это отдельная консольная программа: вы собираете исполняемый файл с помощью make и запускаете его напрямую с путём к модели и опциями промпта.
Как его запустить?Склонируйте репозиторий, выполните make (или make win64 на Windows), скачайте готовый экспортированный файл модели (около 5,0 ГБ) и запустите получившийся бинарник, указав эту модель через -m.
Что должно быть установлено для сборки и запуска?Нужны процессор с поддержкой AVX2, C-компилятор с OpenMP и make; Python требуется, только если хотите сами экспортировать модель или запустить числовую валидацию.
Работает ли он на любом процессоре и сколько нужно диска/ОЗУ?Требуется AVX2, работает только на Linux и Windows (про macOS/ARM не упоминается); модель занимает около 5,0 ГБ на диске, рекомендуется 8 ГБ ОЗУ, а валидация достигает пика около 10 ГиБ.
Какие операционные системы он поддерживает?Linux и Windows (второй — через тулчейн MinGW-w64 с небольшим слоем совместимости для маппинга памяти).
Насколько он быстрый по сравнению с llama.cpp?На AMD Ryzen 7 7700 int8-сборка gemma4.c обгоняет сборку llama.cpp Q8_0 по большинству длин prefill и скоростям декодирования, например 25,16 против 22,67 tok/s декодирования при контексте 512 токенов.
Насколько точен int8-инференс по сравнению с настоящей моделью?Против Hugging Face Transformers с неквантованным чекпойнтом BF16 на пассаже WikiText-103 gemma4.c совпадает по top-1 токену в 96,5% случаев со средней KL-дивергенцией 0,005207.
Как перевести веса модели в формат, который нужен этому рантайму?exporter.py конвертирует выпущенный Google неквантованный QAT-чекпойнт (google/gemma-4-E2B-it-qat-q40-unquantized) в бинарный формат int8 со масштабами FP16, который C-рантайм читает напрямую.
Что есть в репозитории помимо кода инференса?gemma4.c содержит токенизатор, модель, кернелы и цикл генерации; exporter.py конвертирует чекпойнты; validation.py и validation.txt проверяют числовую точность против Transformers; win.c/win.h добавляют поддержку маппинга памяти в Windows; Makefile собирает обе платформы.
Creator
qmog-ai
Size
<0.1 MB
Stars
182
Updated
CommitSep 10
Age
2mo
Commits · 90 Days