examples/gpt-2 directory provides a CPU-based C++ implementation of GPT-2 inference using ggml. It also supports Cerebras-GPT models.
Supported models
Performance (MacBook M1 Pro)
Build
Build ggml with examples enabled from the repo root:build/bin/gpt-2 and build/bin/gpt-2-quantize.
Getting a model
There are three ways to obtain a GPT-2 model in ggml format:- Download pre-converted
- Convert from OpenAI checkpoint
- Convert Cerebras-GPT
The fastest option — download a pre-converted ggml binary directly:
Pre-converted models are hosted by the project maintainer and may be removed in the future. Use the conversion scripts as a fallback.
Run inference
Generate text from a prompt:CLI options
Sample output
Quantization
You can quantize a converted model to reduce memory usage. Quantization is most useful for large models — applying it to small models (117M, 345M) will significantly reduce quality.Batched generation
Thegpt-2-batched binary generates multiple independent sequences from the same prompt in a single forward pass:
Inference workflow
1
Load the model
The model is loaded from a binary file. The loader reads the vocabulary (50257 tokens for GPT-2), hyperparameters (
n_ctx, n_embd, n_head, n_layer), and weight tensors into a ggml context.2
Tokenize the prompt
The input string is split into BPE tokens using the embedded GPT-2 vocabulary. The number of tokens is printed at startup (
number of tokens in prompt).3
Run the forward pass
Tokens are processed in batches (
-b). For each new token, the model runs a full transformer forward pass: token embedding → N transformer blocks (self-attention + FFN) → output projection → softmax.4
Sample the next token
The output logits are filtered with top-k and top-p sampling, then scaled by temperature before sampling. The sampled token is appended to the sequence and fed back for the next step.
5
Repeat until done
Steps 3–4 repeat until
--n_predict tokens have been generated or an end-of-text token is produced.