This article explains concepts and selected implementation pieces involved in designing inference software in C++. The code below is only a small memory-arena example; it does not implement model loading, a tokenizer, all Transformer layers, sampling, or complete CUDA/Metal backends. It is not an LLM engine or a performance comparison.
Why C++, and its trade-offs
C++ is useful when you need control over memory layout, CPU instructions, or device APIs, but changing languages does not automatically make a workload faster. Frameworks such as PyTorch delegate much of the computation to optimized C++ and GPU kernels, so Python calls are not necessarily the bottleneck. Deployment also does not always mean one self-contained binary; GPU runtimes and shared libraries may remain dependencies.
Inference-engine components
graph TD
A["Model and input"] --> B["Tokenizer and model loader"]
B --> C["Tensor operations and graph"]
C --> D["Memory planning and scheduler"]
D --> E["CPU backend"]
D --> FGPU["Optional GPU backend"]
E --> G["Sampling and output"]
FGPU --> G
Matrix operations and memory estimates
Transformers use many matrix multiplications, but their share of runtime varies with the model, batch, sequence length, and hardware. Storing 7,000,000,000 FP32 weights takes 28,000,000,000 bytes (28 GB decimal, about 26.1 GiB) for weights alone. The theoretical raw weight payload for FP16/INT8/INT4 is about one-half, one-quarter, and one-eighth of FP32; quantization metadata, the KV cache, and workspaces add memory, and quantization can affect quality.
A C++17 arena example
The example below reuses an aligned byte region in C++17. reset only rewinds the cursor; it does not call destructors for objects placed in the region. Manage object lifetimes separately and verify that allocations fit.
| |
CPU and GPU backends
CPU SIMD and GPU paths must be designed and measured together with instruction-set support, drivers, runtimes, data layout, and transfers. CUDA offers matrix operations through cuBLAS, and Apple provides matrix APIs through Metal Performance Shaders, but neither becomes a complete backend by copying one short snippet. Shared memory on Apple silicon also does not remove synchronization or resource-management requirements.
Study real implementations
For working inference implementations, study GGML and the source and build instructions of llama.cpp, which uses it. Start with small tensor operations and tests; document the model format, supported operations, numerical precision, memory use, and target hardware. Any performance result should state the model, input, build settings, device, and measurement method.
