Zero Labs
Industry News / AI

Inference Infrastructure Engineering for Everyone

Source · Towards AI By Sahariarhasan

From the publisher’s feed, collected in the ZeroLabs newsroom.

Every chatbot reply, code suggestion and AI search answer is produced by inference infrastructure: the hardware and software that turns a trained model into fast, affordable answers. This is a 12-stage tour of that field, written so a curious beginner can follow it and a working engineer can use it as a map.Speak the language firstA handful of terms come up in every stage. Learn them once and the rest reads easily.Time to first token (TTFT): how long you wait before the first word of the answer appears.Tokens per second: how fast the answer streams once it starts.Inter-token latency (ITL): the gap between one token and the next.Latency vs throughput: latency is one user’s wait; throughput is total work done for everyone. Improving one often costs the other.Latency percentiles (P50, P95, P99): the wait that 50%, 95% or 99% of requests beat. Tail latency is what users complain about.End-to-end metrics: total time from request to complete answer, including queueing and network.Real-time factor: for audio, processing time divided by audio length. Below 1 means faster than real time.Prefill and decode: reading the prompt vs writing the answer (Stage 3).Online vs offline inference: online serves live users with strict latency; offline processes big batches where only cost matters.Asynchronous inference: submit a job, get the result later. Ideal for long or non-urgent work.Know your workload. The right design depends on context: AI-native apps vs bolt-on features, consumer traffic vs business-to-business contracts, and reasoning models that generate many hidden thinking tokens before answering, which multiplies decode cost.Stage 1: Systems FoundationsInference is a systems problem before it is an AI problem. Every slow model eventually traces back to memory, scheduling or a badly used processor, so the first stage is learning to see those layers.What to learnA systems language. Python orchestrates; C++ or Rust does the work where speed and memory control matter. Learn pointers, stack vs heap, ownership (Rust) or RAII (C++), and why cache locality matters.Python profiling. cProfile, py-spy and perf show where time actually goes. Most "slow model" complaints are slow tokenizers, copies or serialization.Linux internals. Processes, threads, virtual memory, page faults, sockets. Production inference runs on Linux, and htop, vmstat and strace are your stethoscope.The memory hierarchy. Registers, L1/L2/L3 cache, RAM, SSD: each level is bigger and slower than the last.CPU vs GPU vs NPU. A CPU is a few brilliant workers, a GPU is thousands of simple ones, and an NPU is a specialist built for fixed neural-network math, common in phones and laptops.Mental model: a kitchen. Ingredients (data) live in a warehouse (RAM), a fridge (cache) and your hands (registers). A fast chef who waits for ingredients is not fast.Try this: write the same matrix multiply in pure Python, NumPy and C++, then profile all three and explain the gaps.Stage 2: GPU Architecture and Modern SiliconA GPU is a throughput machine: it hides slowness by running enormous numbers of threads at once. Knowing how it is built tells you why some code flies and some crawls.What to learnCUDA basics. Kernels, grids, blocks, threads and warps (groups of 32 threads that move together).Tensor cores. Dedicated units for matrix math, which dominates transformers. Each hardware generation adds lower-precision formats (FP16, FP8, FP4) that run faster.HBM bandwidth. High-bandwidth memory is stacked next to the GPU die. Recent data-center parts reach several terabytes per second, and for LLM decoding that number often matters more than raw compute.SM occupancy. Streaming multiprocessors (SMs) are the GPU’s work units. Occupancy measures how many warps they keep busy while waiting on memory.Hopper and Blackwell. Know what each generation changed: memory capacity and speed, supported precisions, interconnect, and the chiplet-style multi-die packaging on newer parts.Telemetry. nvidia-smi for a quick look, DCGM for fleet-wide metrics such as utilization, memory, power and errors.Mental model: a stadium of cooks sharing one narrow delivery door. The door (memory bandwidth) often limits the meal, not the number of cooks.Try this: run nvidia-smi dmon during a model load and a generation run, and note when memory, not compute, is the busy part.Stage 3: Transformer and MoE Inference AnatomyBefore optimizing a workload, understand its shape. LLM inference has two very different phases, and almost every trick in this guide targets one of them.Prefill reads your whole prompt at once. Thousands of tokens are processed in parallel, so the GPU is busy with math. This phase is compute-bound and sets time to first token (TTFT).Decode generates one token at a time. Each step reads all the model weights plus the cache of past tokens, to produce a single token. This phase is memory-bound and sets inter-token latency (ITL).KV cache math. To avoid recomputing attention over past tokens, the model stores each layer’s keys and values. Its size grows with every token and every concurrent user:KV cache bytes = 2 × layers × KV heads × head dimension × tokens × bytes per valueMultiply by the number of concurrent sequences and you see why long contexts, not model weights, often decide how many users fit on one GPU.Arithmetic intensity is FLOPs performed per byte moved from memory. Prefill has high intensity (compute-bound); decode has very low intensity (memory-bound). The roofline model, introduced in Stage 8, turns this into a picture.Mixture-of-Experts (MoE). Instead of one big feed-forward block, an MoE layer has many “experts” and a router that sends each token to a few of them. You get a big model’s capacity at a smaller per-token compute cost, but all experts must still live in memory, and uneven routing creates hot spots.Long-context scaling. Attention cost and KV cache both grow with context length, which is why 128K-token prompts stress memory and scheduling far more than short chats.Try this: write a 20-line calculator that takes a model’s layers, KV heads and head dimension and prints KV cache per token and per 32K-token session.Stage 4: Serving Engines and Constrained DecodingRunning a model once is easy. Serving it to thousands of people at once, efficiently, is what serving engines are for.vLLM: PagedAttention and continuous batching; the common open-source starting point.SGLang: prefix reuse (RadixAttention), fast structured generation and complex prompting programs.TGI (Hugging Face): production-ready serving tightly integrated with the Hugging Face ecosystem.TensorRT-LLM: NVIDIA’s heavily optimized engine for squeezing the most out of NVIDIA GPUs.Continuous batching. Older systems waited for a full batch to finish together. Continuous batching lets new requests join and finished ones leave at every token step, so the GPU stays full. Think of a bus that picks up passengers at every stop instead of waiting for the whole route.PagedAttention. KV caches used to be allocated as one big contiguous block per request, wasting memory. PagedAttention stores them in small pages, like an operating system’s virtual memory, so far more requests fit.Constrained decoding. When your app needs valid JSON or text matching a grammar, the engine masks out tokens that would break the rules at each step. This is how structured output and grammar-guided generation guarantee well-formed results instead of hoping the model behaves.Try this: serve a small model with vLLM, then load-test it with 1, 8 and 64 concurrent requests and record throughput and TTFT at each level.Stage 5: KV Cache and Memory HierarchiesIf Stage 3 showed that the KV cache is the biggest memory consumer, Stage 5 is about managing it like the valuable resource it is.Prefix caching. Many requests start with the same system prompt or document. Compute its KV cache once and reuse it, cutting TTFT and cost.Chunked prefill. Split a long prompt into slices and interleave them with other requests’ decode steps, so one huge prompt does not stall everyone else.KV quantization. Store the cache in FP8 or INT8 instead of 16-bit values to fit roughly twice as many tokens, at some cost in accuracy you must measure.Hierarchical offloading. Keep hot caches in GPU memory, warm ones in CPU RAM and cold ones on SSD, moving them back when a session returns. Each tier is larger and slower, so the win depends on how fast you can bring data back.Multi-turn session reuse. In a chat or agent loop, the previous turns are already cached. Route the next message to the same replica and keep the cache alive between turns.Eviction policies. When memory fills, something must go. LRU (least recently used) is the baseline; smarter policies weigh prefix popularity, recompute cost and session priority.Mental model: a desk, a filing cabinet and a warehouse. The art is deciding what stays on the desk.Try this: replay a chat transcript against your server with prefix caching on and off, and compare TTFT on turns 2 to 10.Stage 6: Quantization and Compression at ScaleQuantization stores numbers with fewer bits. Smaller weights mean less memory to read, and since decode is memory-bound, they often mean faster tokens too.FP16 / BF16: the 16-bit baseline for inference.FP8: near-baseline quality with big speed and memory gains on supported GPUs.INT8: widely supported 8-bit weights and activations.FP4 / INT4: aggressive compression; needs careful calibration and hardware support.Methods. GPTQ and AWQ compress weights after training, using a small calibration set to protect the weights that matter most. Mixed-precision serving keeps sensitive layers at higher precision. Sparsity skips zeros, though real speedups need hardware and kernel support.Measure, do not assume. Every format trades quality against speed differently per model family. For each candidate record perplexity or a task benchmark, latency, throughput and memory, then plot quality drop against gain. A 20% speedup that costs three points on your real task may not be a win.Try this: quantize one open model to FP8 and INT4, then compare perplexity, tokens per second and peak memory against the 16-bit baseline in a single table.Stage 7: Speculative Decoding and Advanced ParallelismSpeculative decoding attacks the one-token-at-a-time bottleneck. A small, fast draft model guesses several tokens ahead; the large target model checks all of them in a single pass and keeps the correct prefix. Because verification is parallel, you get several tokens for roughly the price of one step, and the output matches what the big model would have produced.Draft-target pipelines use a separate small model. The better it predicts the target, the bigger the speedup.Medusa and EAGLE attach lightweight prediction heads to the target model itself, removing the need for a second model.Watch the acceptance rate. If drafts are rejected often, the extra work wastes capacity. Gains are largest at low batch sizes and shrink when the GPU is already saturated.Parallelism is how one model spans many GPUs:Tensor parallelism: splits each layer’s matrices across GPUs. Best for fitting big models and lowering latency within a node.Pipeline parallelism: splits groups of layers across GPUs. Best for spanning nodes with less communication.Expert parallelism: splits MoE experts across GPUs. Best for large MoE models.Sequence parallelism: splits the token dimension across GPUs. Best for very long contexts.Try this: enable speculative decoding in vLLM or SGLang and plot speedup against batch size to find where it stops paying off.Stage 8: Kernel-Level OptimizationA kernel is the small GPU program that does one operation. Stage 8 is where you stop using fast operations and start writing them.Triton. A Python-based language for writing GPU kernels without managing every thread by hand. The friendliest on-ramp to custom kernels.FlashAttention-3. Attention rewritten to work in small tiles that stay in fast on-chip memory, avoiding the huge intermediate matrices that would otherwise be written to slow memory. It exploits newer Hopper-class hardware features.Operator fusion. Combine several small operations into one kernel so data is read and written once instead of repeatedly.CUDA graphs. Record a sequence of GPU launches and replay it at once, removing launch overhead that hurts small, fast decode steps.Custom attention kernels. Needed when the standard ones do not fit your model, cache layout or hardware.Nsight Compute. The profiler that shows whether a kernel is limited by memory, compute or latency.The roofline model plots achievable speed against arithmetic intensity. Low-intensity kernels hit the memory-bandwidth slope; high-intensity ones hit the compute ceiling. Place your kernel on that chart and you know what to fix.Try this: write a fused softmax in Triton, profile it against the unfused PyTorch version, and explain the gap using bytes moved.Stage 9: Distributed and Disaggregated InferenceWhen one machine is not enough, the network becomes part of the computer.Interconnects. NVLink links GPUs inside a node at very high bandwidth. InfiniBand and RDMA move data between nodes with minimal CPU involvement. Cross-node links are much slower than in-node ones, which shapes every parallelism choice.Multi-node serving. Splitting a model across nodes adds communication on every layer or stage; keep latency-sensitive splits inside the fastest links.Disaggregated prefill and decode. Since prefill is compute-heavy and decode is memory-heavy, run them on separate GPU pools, each tuned for its job, and transfer the KV cache between them. This removes interference where a long prefill delays everyone’s decoding.MoE expert parallelism. Experts are spread across GPUs, and tokens are shuffled to the right ones with all-to-all communication. Load imbalance and network speed decide your efficiency.Prefill-decode ratio tuning. How many GPUs to give each pool depends on your prompt lengths, output lengths and latency targets. Revisit it when traffic changes.Mental model: a restaurant with separate prep and grill stations. Specializing helps only if the hand-off between them is fast.Try this: model KV transfer time for a 32K-token session over different link speeds and decide when disaggregation beats running both phases together.Stage 10: Autoscaling, FinOps and EconomicsGPUs are expensive, so an idle one is burning money and an overloaded one is losing customers.Queue-based scaling. CPU load is a poor signal for GPU services. Scale on queue depth or in-flight requests, for example with KEDA on Kubernetes.Cold start mitigation. Loading tens of gigabytes of weights takes minutes. Cache weights on local disk, use fast model loaders, and keep a small warm pool.Spot GPU orchestration. Spare-capacity GPUs are far cheaper but can be reclaimed. Use them for tolerant workloads and keep on-demand capacity as a safety net.Cost per token. Divide total GPU spend by tokens produced, separating input and output tokens. This number is the real unit of comparison.MFU (model FLOPs utilization). The share of the hardware’s peak compute your workload actually uses. Low MFU on decode is normal; very low MFU everywhere means wasted money.Per-tenant budgeting. Meter tokens by customer or team, set quotas, and show cost back to the people causing it.Cost per 1M tokens = (GPU cost per hour ÷ tokens per hour) × 1,000,000Try this: take your Stage 4 load test, plug in a real GPU hourly price, and report cost per million output tokens at three concurrency levels.Stage 11: AI Gateway, Routing and ReliabilityThe gateway is the front door of your inference platform. It decides which model answers, protects the GPUs behind it, and keeps users happy when something breaks.Smart model routing. Send easy requests to a small, cheap model and hard ones to a large model, based on task type, length or a lightweight classifier.Fallback chains. If a model times out or a region fails, retry on the next option automatically, with timeouts and circuit breakers so one failure does not cascade.Semantic caching. Return a stored answer for questions that mean the same thing as a previous one. Powerful but risky: tune similarity thresholds and never cache personalized or sensitive answers.Rate limits. Limit by tokens as well as requests, per tenant, so one heavy user cannot starve the rest.SLOs. Set explicit targets for TTFT and ITL (for example, a P95 TTFT) and alert on them, not on averages.Agent-aware session routing. Agents make many chained calls with growing context, so keep a session on the replica that holds its KV cache.Observability and chaos testing. Track TTFT, ITL, queue depth, cache hit rate and error rate, and deliberately kill replicas in testing to prove the fallbacks work.Try this: put a small gateway in front of two models with a per-tenant token limit and a fallback, then break one model on purpose and watch the metrics.Stage 12: Edge Inference and PortfolioNot all inference happens in a data center. Running models on laptops, phones and browsers removes network latency and keeps data local, and it is also the cheapest place to practice.MLX is Apple’s array framework, designed around Apple Silicon’s unified memory where CPU and GPU share one pool.llama.cpp runs quantized GGUF models efficiently on CPUs and many kinds of GPUs, from servers to single-board computers.WebGPU brings GPU compute into the browser, enabling models that run with no server at all.Build proof of skill. Hiring teams trust evidence over certificates. Publish:Latency, throughput and cost benchmarks with the exact hardware, model, settings and scripts, so others can reproduce them.A kernel optimization write-up: baseline, profile, bottleneck, fix, measured result.A self-hosted cluster teardown: what you deployed, what broke, what it cost, and what you would change.Five polished, reproducible projects beat twenty half-finished ones.Beyond the stages: model strategyBefore tuning infrastructure, decide what to run.Open vs closed models. Closed models are rented through an API and need no infrastructure. Open-weight models you host yourself give control over cost, privacy and customization, at the price of operating them.Inference vs training. Training builds the model once at great expense; inference runs it millions of times. Inference usually dominates lifetime cost and has different goals: low latency and cost per token rather than raw learning speed.Shared vs dedicated inference. Shared endpoints are cheap and flexible but have noisy neighbors; dedicated GPUs give predictable performance and cost more when idle.Model selection and evaluation. Pick the smallest model that meets your quality bar, and test it on your own tasks, not just public leaderboards.Fine-tuning. Adapt a model to your domain, often cheaply with adapters such as LoRA.Distillation. Train a small model to imitate a large one, trading a little quality for large savings in cost and latency.Beyond the stages: models that are not text LLMsThe same ideas (memory bandwidth, batching, caching, quantization) carry over, but each model family has its own bottlenecks.Image and video generation. Diffusion models build a picture by refining noise over many steps, so cost scales with the step count. Few-step and distilled models cut that sharply. Video adds a time dimension and is far heavier on compute and memory.Vision-language and omni-modal models. These read images, video or audio alongside text. Preprocessing and the extra input tokens can dominate latency.Embedding models. Turn text into vectors for search and retrieval. They are mostly prefill-only, so large batches and high throughput matter more than streaming speed. Both BERT-style and LLM-based embedders exist.Speech. Voice activity detection, automatic speech recognition, text-to-speech and streaming TTS have strict real-time requirements. Speech-to-speech systems chain these and must keep total delay low enough to feel like conversation.Bottleneck analysis ties it together. The ops-to-byte ratio (arithmetic intensity) and the roofline model show whether each model type is limited by compute or memory, and which optimization will actually help.Attention variants such as multi-query and grouped-query attention share keys and values across heads, shrinking the KV cache with little quality loss. They are a main reason newer models serve more users per GPU.Beyond the stages: tooling, formats and benchmarkingFrameworks and libraries. PyTorch is the base; Hugging Face Transformers and Diffusers supply ready-made models.Model formats. safetensors is a safe, fast way to store weights. TensorRT builds NVIDIA-optimized engines, and ONNX Runtime runs models portably across hardware.Benchmarking tools. AIPerf, Locust and SGLang’s genai-bench generate realistic traffic against your server and report TTFT, ITL and throughput. Always benchmark with your real prompt and output lengths.Profiling. Profile first, then optimize: the same discipline from Stage 8 applies at the system level.NVIDIA Dynamo. An inference framework for distributed, disaggregated serving across many GPUs, covering routing, KV cache transfer and scaling.Custom kernels and fusion. Choose between library kernels and writing your own, and fuse small operations when launch overhead and memory traffic dominate.Local and edge inference. Desktop and mobile runtimes (Stage 12) need small, quantized models and careful memory budgets.Beyond the stages: production extrasContainerization. Package models and dependencies in Docker images so every environment behaves the same. Pin versions, since drivers, CUDA and libraries must match. NVIDIA’s NIM containers offer pre-built, optimized model services.Kubernetes autoscaling. Scale on queue depth, handle cold starts, and consider scale-to-zero for rarely used models and independent scaling of components such as prefill and decode pools.Routing and load balancing. Beyond round-robin: send requests where the cache is warm, and route to replicas that already hold the right LoRA adapter.Request queueing. Absorb bursts instead of dropping them, with priorities and timeouts.GPU procurement and capacity. Decide between buying, renting or reserving GPUs, size instances for memory first, and plan capacity ahead of demand.Multi-cloud and geo-aware routing. Spread across providers to find capacity and send users to the nearest region.Security and compliance. Protect model weights and user data, isolate tenants, and meet your industry’s regulatory requirements.Zero-downtime deployment and cost estimation. Roll out new model versions gradually with the ability to roll back, and forecast spend before traffic arrives.Where to start this weekYou do not need to finish one stage before touching the next, and you do not need a data-center GPU to begin.Run a small model locally with llama.cpp or MLX and note its tokens per second.Profile one Python script with py-spy and read where the time goes.Write the KV cache calculator from Stage 3 and check it against a real model’s memory use.Serve the same model with vLLM and load-test it at three concurrency levels.Write down what you measured, and publish it.The skill that separates an inference engineer from someone who calls an API is the ability to answer one question with evidence: why is this slow, and what would make it faster or cheaper? Every stage above exists to make that answer sharper.Inference Infrastructure Engineering for Everyone was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.