In modern AI engineering, training a foundation model represents less than 15% of the total lifecycle cost. The remaining 85% is consumed by inference serving—the operational compute required to execute millions of forward passes across production applications, robotics, smartphones, and edge devices.
Inference is not a simple function execution. It is a systems-level battle against hardware physical boundaries:
The Prefill vs Decode Phase Dilemma: Processing the user prompt is compute-bound; generating subsequent tokens autoregressively is strictly memory-bandwidth bound.
The KV Cache Memory Explosion: Storing past Key and Value activations for 4k-128k context windows rapidly exhausts GPU VRAM, causing memory fragmentation and limiting concurrent batch sizes.
The Edge Constraint Envelope: Deploying vision and sensory models to microcontrollers (TinyML) where SRAM is capped at 256 KB, requiring zero dynamic memory allocation and INT8 quantization.
We engineer our inference systems across this complete continuum: from multi-GPU vLLM clusters down to bare-metal ARM Cortex-M microcontrollers.
Imagine you manage a high-speed express train station.
Prompt Processing (Prefill) is when 500 passengers arrive at once: you open all turnstiles in parallel, check tickets instantly, and fill the train cars to capacity (Compute-Bound).
Token Generation (Decode) is what happens after the train departs: the train must stop at 50 consecutive stations, and at every single station, only one person gets on. The train has to brake, open the doors, let one passenger step inside, and accelerate back to top speed 50 times in a row. It feels horribly inefficient because you are moving an entire 100-ton train for one person (Memory-Bandwidth-Bound).
Inference Engineering is the discipline of fixing this: packing multiple passenger streams together on the fly (Continuous Batching), guessing what stations people want in advance (Speculative Decoding), packing baggage tighter (Quantization), and building ultra-light electric scooters for field medics who have no train tracks (TinyML on Edge Microcontrollers).
1. The Roofline Model: Hardware Operational Regimes
Every piece of compute hardware—from an 80GB NVIDIA H100 GPU down to a $2 ESP32 microcontroller—operates under the mathematical boundaries of the Roofline Model:
The Roofline Model determines whether your AI workload is Memory-Bandwidth-Bound or Compute-Bound. In LLM serving: Prompt Prefill has high arithmetic intensity (Compute-Bound), while Autoregressive Token Generation reads gigabytes of weights to produce 1 token (Memory-Bandwidth-Bound).
Neural Mastery
The Two Operational Regimes
The peak attainable throughput of a model on a given hardware accelerator is bounded by:
Compute-Bound Regime (I>Iknee): The arithmetic intensity is high enough that the execution units (ALUs / Tensor Cores) are saturated. Performance is limited by compute FLOPs.
Memory-Bandwidth-Bound Regime (I<Iknee): The execution units sit idle waiting for weights and activations to arrive across the memory bus. Performance is limited by memory bandwidth.
Predict First
Why does increasing the serving batch size (e.g. from batch size 1 to batch size 64) during autoregressive token decoding dramatically increase token throughput without linearly increasing latency?
2. KV Cache Optimization & PagedAttention
In modern transformer models, recomputing past keys and values at every token generation step scales quadratically: O(L2). To achieve linear generation time, models store past Key and Value projection vectors in a KV Cache.
However, the memory footprint of the KV Cache grows rapidly with sequence length:
KV Cache Size per Request (Bytes)=2×2×nlayers×nheads×dhead×L×Precision Bytes
PagedAttention vs Contiguous Allocation
In naive inference servers, memory for each request was allocated contiguously for the request's max_seq_len. This caused 60% to 80% of VRAM to be wasted due to over-reservation and memory fragmentation.
Explore how PagedAttention (vLLM) resolves memory fragmentation using virtual memory paging:
PagedAttention (vLLM, Kwon et al.) brings virtual memory paging to LLM serving. In traditional contiguous allocation, 60% to 80% of VRAM is wasted on over-reservation and external fragmentation. PagedAttention eliminates external fragmentation completely, enabling 2x to 4x higher serving throughput.
Traditional batching (Static Batching) waits for all sequences in a batch to finish before accepting new requests. Because different sequences generate different lengths, shorter sequences sit idle (creating "inference bubbles") while waiting for the longest sequence.
Continuous Batching (iteration-level scheduling) evaluates scheduling after every single token generation step: finished sequences are evicted immediately and new requests are inserted into the running iteration.
Accelerating Generation: Speculative Decoding
Autoregressive token generation requires sequential execution. Speculative Decoding breaks this sequential dependency by pairing a small, fast Draft Model with a large Target Model:
Speculative Decoding converts memory-bandwidth-bound token generation into compute-bound parallel verification. The draft model proposes K tokens sequentially, and the target model verifies all K tokens in parallel in a single forward pass, yielding 2x to 3x wall-clock speedup without any loss in output distribution.
Neural Mastery
The Speculative Decoding Guarantees
Parallel Verification: The target model evaluates all K draft tokens in a single parallel forward pass (O(1) verification).
Exact Distributional Fidelity: Using modified rejection sampling, tokens are accepted with probability:
αi=min(1,Pdraft(xi)Ptarget(xi))
If a token is rejected, the target model resamples a replacement token from the normalized residual distribution:
Presample(x)=relu(Ptarget(x)−Pdraft(x))
This guarantees that the final output distribution is mathematically identical to sampling directly from the large target model!
4. Quantization: Compressing Precision for Datacenter & Edge
Quantization maps continuous 32-bit or 16-bit floating point numbers into discrete low-bit integer or floating representations (FP8, INT8, INT4):
Fixed-point integer arithmetic: q = round(x / Scale) + ZeroPoint. 4x memory compression; runs on microcontrollers with no FPU.
Discretization Math & Reconstruction
Quantization Formula: q = round(x / Scale)
Scale factor ($S$): 0.04724
Quantized Integer ($q$): 81 (stored in 8 bits)
Reconstructed Float (x̂): 3.827
Reconstruction Error ($\epsilon$): 0.0230
70B Model VRAM Footprint
70 GB
Weights only (excluding KV Cache)
Hardware Infrastructure
1x 80GB H100 (Single GPU!)
Minimum serving cluster requirement
Memory Bandwidth Speedup
4x Throughput
Fewer bytes loaded across memory bus per token
Quantization transforms continuous floating point tensors into compact discrete representations. Converting FP16 to INT8 halves memory bandwidth pressure on GPUs, and running INT4 via AWQ enables 70B parameter models to run on single workstations and edge devices with less than 1% perplexity degradation.
Neural Mastery
Uniform Affine INT8 Quantization
The fundamental quantization mapping from real float x∈[α,β] to an 8-bit integer q∈[−128,127] is:
q=clamp(⌊Sx⌉+Z,−128,127)
Where the Scale factor (S) and Zero-point (Z) are defined as:
S=qmax−qminβ−α=255β−α
Z=round(S−α)+qmin
De-quantization reconstructs the approximate floating-point value:
x^=S×(q−Z)
In Symmetric Quantization (used for zero-centered weights), Z=0 and S=127max(∣x∣), eliminating integer offset additions during matrix multiplications.
5. Inference on the Edge: TinyML & Microcontrollers
Moving inference to embedded microcontrollers (ARM Cortex-M0/M4/M7, ESP32, RISC-V) introduces an entirely different set of physical constraints:
Zero Operating System: Bare-metal C++ execution with no virtual memory or swap space.
Microsecond Memory Budget: Typically 64 KB to 256 KB of SRAM and 512 KB to 1 MB of Flash ROM.
Zero Dynamic Allocation: malloc and free lead to heap fragmentation and embedded Hard Fault crashes.
The Static Tensor Arena
Explore how TensorFlow Lite Micro structures memory execution inside embedded microcontrollers:
Edge AI & Microcontroller Architecture
TinyML Memory Architecture: Flash (ROM) vs SRAM Tensor Arena
Memory Planning Model
Flash Memory (ROM) — Read Only110 KB / 512 KB
Model weights, quantized INT8 constants, and operator kernels execute directly in place (XIP - eXecute In Place). Consumes 0 bytes of SRAM!
TinyML runs on microcontrollers with milliwatt budgets and zero OS. Dynamic malloc/free causes fatal heap fragmentation on embedded systems. TensorFlow Lite Micro uses a static Tensor Arena: model weights execute directly from Flash (ROM), while intermediate layer activations overlap and reuse SRAM offsets with zero dynamic allocation.
Neural Mastery
The Three Invariants of Microcontroller Inference
eXecute In Place (XIP): Quantized INT8 model weights reside permanently in non-volatile Flash memory (ROM) and are read directly, consuming zero bytes of precious SRAM.
The Static Tensor Arena: A single static byte buffer (uint8_t tensor_arena[ARENA_SIZE]) is allocated at startup.
6. Live Interactive Inference Calculation in Python
Test this real, in-browser Python implementation to calculate the exact VRAM footprint, KV cache size, and memory bandwidth throughput for any model architecture:
Inference is a systems-algorithm co-design problem. In the cloud, maximize batch size and arithmetic intensity with PagedAttention and speculative decoding. On the edge, eliminate dynamic allocation with static tensor arenas and compress model weights with symmetric INT8 quantization.