Ailoot Engineering
AI inference uses a trained model to generate output from new input. Learn how prefill, decode, the KV cache, performance metrics, serving tools, and deployment choices affect speed and cost.
Inference is where AI models do their work. Every time you send a prompt to ChatGPT, call an LLM API, or run a model locally, you’re running inference. It determines how quickly you get a response, what it costs, and how many users you can serve at once.
Training vs. Inference
Training adjusts a model’s parameters (weights) to learn patterns from data. It’s expensive and slow, and happens once or occasionally for fine-tuning. A frontier model might take months and tens of millions of dollars to train. Once training is done, the weights are fixed.
Inference uses those fixed weights to generate output from new input. No learning happens; the model applies what it already knows. Every API call, chat message, and code suggestion is inference. The economics of AI are shifting toward inference. By some estimates, organizations spend 15–20 times more on inference over a frontier model’s production lifetime than on training it.
If training is writing the textbook, inference is taking the exam. The preparation is over; now you perform.
The Two Phases of LLM Inference
For transformer-based language models, inference breaks into two distinct phases.
Prefill processes the entire input prompt in parallel. All input tokens pass through the transformer layers simultaneously. The model builds a KV cache (key-value cache), storing intermediate attention results so they don’t need to be recomputed later. This phase is compute-bound: it does substantial GPU computation on all tokens at once. Prefill is a major contributor to time to first token (TTFT), alongside factors such as time spent waiting in a queue.
Decode generates output tokens one at a time. Each new token depends on all previous tokens: the original prompt and every token generated so far. The model reads from the KV cache to avoid reprocessing the full sequence, produces one token, appends it, and repeats. This phase is memory-bound: the bottleneck is reading the growing KV cache from GPU memory, rather than raw computation. Decode determines tokens per second (TPS), or how quickly the response streams to you.
The distinction matters for optimization. Speeding up prefill and speeding up decode require different strategies because they encounter different hardware limits.
The KV Cache
The KV cache is a key data structure in LLM inference. During the attention mechanism, each token produces a key and a value vector. These vectors are needed whenever a new token is generated, because each token attends to all previous tokens. Without caching, the model would recompute attention for the entire sequence at every step. For a 1,000-token response, that means reprocessing all previous tokens 1,000 times.
The KV cache stores these vectors so they’re computed once and reused. The tradeoff is memory. For a large model with a long context, the KV cache can consume gigabytes of GPU memory. A 70B-parameter model processing a 32K-token sequence might need 10–20GB just for the KV cache, in addition to memory for the model weights.
This is why context-window length affects performance. Longer contexts mean larger KV caches, which use more memory and can slow decode steps as the model reads more cached data.
Key Performance Metrics
Time to first token (TTFT): How long after sending a prompt before the first token appears. Time to first token includes any time spent waiting in a queue plus processing the prompt and generating the first token. Users notice this as the initial delay before a response starts streaming. For interactive applications, 200–500 ms is good; over 2 seconds feels slow.
Tokens per second (TPS): How quickly tokens generate during the decode phase. This determines how quickly a response completes. Typical ranges: 5–15 TPS on CPU, 30–80 TPS on a single consumer GPU, and 100+ TPS on datacenter GPUs.
Throughput: Total tokens generated per second across concurrent requests. This is the metric that matters for serving many users. A system generating 50 TPS for one user might generate 500 TPS total when batching 20 concurrent requests.
Latency: End-to-end time from request to complete response. It depends on TTFT plus the total number of tokens divided by TPS.
Optimization Techniques
Continuous Batching
Naive batching groups requests together and processes them as a unit, but all requests in the batch must wait for the longest one to finish. Continuous batching dynamically adds and removes requests during inference. When a short response finishes, its slot immediately goes to a new request. This eliminates idle GPU cycles and can increase throughput 2–4 times compared with static batching.
PagedAttention
Traditional KV cache allocation pre-reserves contiguous GPU memory for the maximum possible sequence length, even if much of that memory goes unused. PagedAttention, introduced by vLLM, borrows the concept of virtual memory from operating systems: it divides the KV cache into fixed-size blocks that can be stored in non-contiguous memory and mapped via block tables. This reduces memory waste from 60–80% to under 5%, allowing more concurrent requests on the same hardware.
Speculative Decoding
A small, fast “draft” model generates several tokens quickly. The larger target model then verifies those tokens in parallel. Verification is cheaper than generation because it can process all draft tokens at once, like prefill. If the draft tokens are correct, you’ve generated multiple tokens in the time it would take to generate one. If some are wrong, the target model corrects from the first mismatch. The speedup depends on how well the draft model predicts what the target model would say; well-matched pairs typically see 2–3 times the speed.
Quantization
Reducing the precision of model weights from 16-bit to 8-bit or 4-bit makes inference faster and uses less memory. A 7B model at 16-bit needs about 14GB; at 4-bit, about 4GB. Quantization can reduce output quality; the effect depends on the model, task and method, so measure it on your workload. Quantization is a major option for running models on consumer hardware.
Inference Serving Tools
Ollama is a simple path for local inference. It manages model downloads, handles quantization, and exposes a local API. One command gets you a running model. It is suited to development, experimentation, and single-user use.
vLLM is a production inference engine with continuous batching and PagedAttention built in. For serving a model to multiple users, vLLM is one option.
TensorRT-LLM is NVIDIA’s optimized inference library. It applies GPU-specific optimizations, including kernel fusion and quantization-aware compilation, for performance on NVIDIA hardware. It offers a high performance ceiling but is tied to that hardware ecosystem.
llama.cpp runs models on CPUs and Apple Silicon with minimal dependencies. It powers Ollama and is a common option for running models on machines without NVIDIA GPUs.
Cost Drivers
Inference cost comes down to three factors: hardware utilization, model size, and request volume.
Hardware utilization is why batching and memory optimization matter. A GPU sitting idle between requests costs the same as one at full utilization. Better batching means more tokens per dollar.
Model size directly affects cost. A 70B model needs roughly 10 times the compute of a 7B model per token. If a 7B model handles your task adequately, running the 70B version may waste money. Choosing the right model size for the task is an important cost decision.
Request volume determines whether self-hosting pays off. At low volume, API pricing can be cheaper because you don’t pay for idle hardware. At high volume, the per-token cost of self-hosted inference can drop below API pricing because your hardware runs at high utilization.
Self-Hosted vs. API Inference
API inference from OpenAI, Anthropic, or Google gives you access to frontier models without managing infrastructure. You pay per token, and scaling is handled for you. Trade-offs include sending data to a third party, depending on its uptime, and costs that scale with usage.
Self-hosted inference gives you control over your infrastructure and data. Per-token cost can decrease as utilization increases. Trade-offs include managing hardware and scaling; the quality ceiling may also be lower than frontier APIs when running open-weight models.
A practical split for many teams is to use APIs for tasks requiring maximum quality, such as complex reasoning or nuanced writing, and self-hosted models for high-volume, privacy-sensitive, or latency-critical tasks where a smaller model performs adequately.
Why Inference Matters for AI Engineers
Understanding inference mechanics changes how you build AI systems. When you know that decode is memory-bound, you understand why shorter prompts can produce faster responses: there’s less to process and the KV cache is smaller. When you know that batching exists, you understand why API latency can spike during peak hours. When you know that quantization trades precision for speed, you can make informed decisions about which tradeoff fits your application.
The model is only half the system. The other half is how efficiently you run it. Two teams using the same model can have very different costs and latencies depending on their inference setup.
Keep Reading
What Are Parameters in AI Models?
Parameters are the numbers that make AI models work. Here's what they are, why models have billions of them, and what the count tells you about capability.
What Is Quantization in AI?
Quantization shrinks AI models by reducing numerical precision. Here's how it works, what formats exist, and how to choose a tradeoff between size, speed, and quality.
Continued Pretraining vs RAG: Two Ways to Add Knowledge
Continued pretraining bakes knowledge into model weights. RAG injects it at query time. When to use each, where each breaks down, and why you often need both.
GPT vs Claude vs Gemini: Which AI Model Should You Use?
A practical comparison of GPT, Claude, and Gemini, including their strengths, pricing, context windows, and which model fits which task in 2026.
Originally published on Ailoot. What Is AI Inference and How Does It Work?
Explore Ailoot’s LLM API. Ailoot issues one API key for 1,284 models and variants across 15 categories, making it one of the world’s largest AI routers by model count. Choose Claude or Qwen for code, FLUX for images, Kling for video, Scribe for transcription, Lyria for music and Tripo3D for 3D assets. BGE embeddings support semantic search.
Give your product access to leading text, code and media models through the Ailoot API. Put reasoning with Claude, image generation with FLUX and video with Kling into one workflow.
Ailoot lets new users enter a draw in their account for starter credit. Find a promo code in your account or request one from the Ailoot team for eligible savings.
One subscription covers the full Ailoot catalogue, with day-one access to new flagship models through the same key. Subscriptions and promo codes offer savings of up to 50% compared with official provider API prices. Get your key at https://ailoot.ai/ and check your account for a promo code.
Top comments (0)