Leanpub Header

Skip to main content

Bare-Metal LLM Inference in C++

Building Quantized GEMM Kernels and Paged KV-Cache Systems for Continuous Batching

Bare-Metal LLM Inference in C++

A 12,000-token prompt arrives and every other stream freezes. A 4-bit model ships and structured output starts failing a few percent of the time. A dual-socket box runs slower on twice the threads. None of these crash. Bare-Metal LLM Inference in C++ builds the engine that catches them: quantized kernels, a paged KV cache, continuous batching, speculative decoding, and a validation ladder that refuses to let a speedup through until the logits match.

Free With Membership

With Membership

Free!

$39.00

You pay

Author earns

$

Also available for 2 book credits with a Reader Membership

PDF
About

About

About the Book

Your quantized model passed perplexity. It’s still failing a few percent of your customers’ JSON, and nothing on your dashboard will tell you that.

Most inference engines are built for benchmarks. They post strong numbers on 128-token prompts with one polite client. In production, three things break them:

  • Bursty traffic. Real load comes in spikes, not one request at a time.
  • Long prompts. A single 12,000-token prefill can freeze every user who is mid-stream.
  • KV-cache waste. Servers run out of KV-cache memory while more than 80% of it holds no tokens at all.

None of these failures crash anything. Health checks stay green while the output quietly goes wrong.

Bare-Metal LLM Inference in C++ is the engineering manual for the layer underneath LLM serving, the part that turns weights and a prompt into tokens. You build a complete production inference engine in modern C++, from a validated model loader to a streaming server with admission control. Each decision is derived from the hardware, measured against a roofline, and checked against a reference implementation before it is allowed to be fast.

What you’ll build
  • A cost model that predicts performance before you write a kernel. It covers bytes per token, arithmetic intensity, and ridge points. You’ll learn why decode at batch size one is waiting on memory bandwidth, and why no amount of FLOPs fixes that.
  • Vectorized and quantized kernels for AVX2, AVX-512, AMX, NEON and SDOT. They include packed GEMM, bandwidth-saturating GEMV, tiled attention, and fused norms and activations. Every SIMD kernel ships with the scalar reference it is tested against.
  • INT8 and 4-bit quantization measured the honest way. That means logit divergence, tail KL on structural tokens, and paired task evaluation, not a single perplexity number. The book handles activation outliers, supports GPTQ and AWQ checkpoints, and imports GGUF formats exactly.
  • A paged, reference-counted KV cache with radix-tree prefix sharing, scan-resistant eviction, INT8 cache quantization, sliding windows, attention sinks, and copy-on-write for beam search.
  • A continuous-batching scheduler with chunked prefill, preemption, fair multi-tenant queueing, and a step-time model the scheduler fits online from its own measurements.
  • Speculative decoding with exact verification. Output matches the target model’s distribution exactly, and an adaptive controller switches speculation off before it costs you throughput.
  • NUMA-aware parallelism on multi-socket CPUs, plus tensor-parallel, pipeline-parallel, and hybrid CPU/GPU execution plans.
  • A production server with lock-free token streaming, cancellation that frees memory within one step, admission control, and an optional deterministic mode that returns bitwise-identical outputs regardless of batch composition.
  • The machinery that keeps it honest: open-loop load testing, a five-rung validation ladder, regression suites, capacity planning, and a release checklist that blocks silent failures.
What makes this book different

Every claim is checkable. Performance figures are given as ranges derived from first principles, never as numbers from benchmarks nobody ran. Every accuracy claim names how it was measured, and every optimization comes with its trade-off stated in the same breath.

The code is real. It is C++20/23 that compiles and handles the failures a live engine actually hits: misaligned buffers, NaNs in activations, integer accumulator overflow, KV-cache exhaustion mid-generation, cancelled requests, and malformed model files. It contains no pseudocode and no “error handling omitted.”

It is written by someone who has debugged these failures. That includes a server that ran out of memory at a fraction of its capacity, a 4-bit model that broke structured output while passing every check, and a dual-socket box that ran slower on twice the threads. Each chapter opens with a failure like these and builds what prevents it. Each chapter closes with the Tokens and Accuracy Ledger, which records what the chapter’s work bought in throughput, latency and memory, and what it cost in accuracy.

Who this book is for

This book is for engineers who will run inference in production:

  • systems and performance engineers,
  • infrastructure and platform teams,
  • anyone responsible for making a model fast, correct and affordable on real hardware.

You should be comfortable with modern C++ and SIMD basics. You don’t need a machine-learning background, because the transformer is introduced only where the engine needs it, and only from the serving side.

If you have ever shipped a speedup and wondered what it broke, this book gives you a way to know.

About the Author

Weston Ashgrove is a systems engineer with more than a decade of experience building high-performance C++ infrastructure. He started in low-latency systems and numerical computing, then moved into performance engineering for compute-heavy workloads. Today he works on the layer underneath large language model serving: inference runtimes, quantized compute kernels, KV-cache memory management, and the schedulers that decide which tokens get computed when. He writes for engineers who have to make systems run correctly in production, not just in a benchmark.

Author

About the Author

Weston Ashgrove

Weston Ashgrove is a C++ systems engineer who builds software where being wrong or slow has a cost. He came up through quantitative trading, building order books, matching logic and the low-latency infrastructure underneath them and now brings the same discipline to performance engineering, concurrency, storage, networking, GPUs, and AI inference.

His rule for performance-critical code is simple: nothing is true until it has been profiled, fuzzed, and replayed. Every technique in his books comes with the measurement that proves it, the trade-off it costs, and the failure it prevents. He writes for working engineers who ship and debug production C++, and he leaves out anything that only works on a slide.

Get the free Community Edition

You can get the free Community Edition in PDF or EPUB just by sharing your name and email address with the author.

 

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub