0%
LLM Inference and Serving: GPUs, Batching, and Cost
Hardware and Memory
Making Inference Fast
Serving Systems
What Happens During Inference
A language model never sees text. It sees a sequence of integers, each one the index of a token in a fixed vocabulary, and it produces a probability for every possible next integer. Everything that serving systems do, from batching to caching to billing, is measured in these tokens. This section explains what a token is, how text becomes tokens and back, and why the token count of a request matters more to an inference engineer than its character count or its word count.
What a token is
A token is a chunk of text that the model treats as one unit. In modern models a token is usually a common word, a piece of a word or a run of punctuation or whitespace. The word the with its leading space is typically one token. A rarer word such as unbelievably may be split into two or three pieces. Numbers are often split into groups of one to three digits, and code is split along identifiers, operators and indentation. The model has a fixed vocabulary of these pieces, and each piece has an integer identifier from zero up to the vocabulary size.
Vocabulary sizes have grown over time. GPT 2 used about 50,000 tokens. Llama 2 used 32,000. Llama 3 moved to a vocabulary of about 128,000 tokens, and recent OpenAI models use a vocabulary of about 200,000. A larger vocabulary means each token covers more text on average, so the same document needs fewer tokens, which shortens sequences and lowers cost. The trade off is a larger embedding table and a larger output layer, since the model must score every vocabulary entry at every step.
Byte pair encoding
Most current tokenizers are built with byte pair encoding or a close relative. The algorithm starts with individual bytes as the vocabulary and repeatedly merges the most frequent adjacent pair in a large training corpus into a new token, until the vocabulary reaches the target size. Frequent words end up as single tokens and rare words are spelled out from smaller pieces. Because the base vocabulary includes all 256 byte values, any input can be encoded, including emoji, binary junk and languages the tokenizer was barely trained on. Nothing is ever out of vocabulary; it is just split into more pieces.
SentencePiece, used by many open models, applies the same idea directly to raw text with whitespace treated as an ordinary symbol, which makes the tokenizer independent of language specific word splitting. The details differ between libraries, but the effect for a serving engineer is the same: the tokenizer is a deterministic function from text to a list of integers and back, and it must exactly match the one the model was trained with. Using the wrong tokenizer does not crash anything. It silently produces garbage.
Tokens per word
A useful rule of thumb for English prose with modern tokenizers is about four characters per token, or roughly three quarters of a word per token. A thousand words of English is about 1,300 tokens. The ratio is much worse for some other languages: scripts and languages that were underrepresented in the tokenizer training data can need two to four times as many tokens for the same meaning, which makes the same request slower and more expensive. Code varies widely with the language and the formatting, and long runs of whitespace or repeated punctuation can be surprisingly expensive with older tokenizers.
These ratios matter for capacity planning. A product team that says users will paste five page documents is really saying something about tokens, and an engineer has to translate it. Five pages of dense English is about 2,500 words, which is about 3,300 tokens, which is a different serving problem from 3,300 words. Measure with the real tokenizer on real inputs rather than estimating from characters, because every estimate in this course, from memory to cost, starts from a token count.
Special tokens and chat templates
Vocabularies include special tokens that never appear in ordinary text: a beginning of sequence token, an end of sequence token and, for chat models, tokens that mark the start and end of each turn and the role that wrote it. A chat request with a system prompt, a user message and the start of an assistant turn is rendered by a chat template into a single flat token sequence with these markers in the right places. The model was fine tuned on that exact format, so a template that is off by one marker can noticeably degrade quality.
Inference servers apply the template on the server side when a client sends a list of messages, which is one reason the model and its template are packaged together. Engineers running their own models should treat the template as part of the model version: changing the template changes behavior as surely as changing the weights. Tool calling and structured output formats add further conventions on top of the template, again expressed as tokens the model learned to produce.
Detokenization and streaming
On the way out, the model produces token ids and the server turns them back into text. This is not always one token to one printable chunk. A single character such as an emoji or a character from a non Latin script may be spread across several byte level tokens, and printing each token as soon as it arrives would emit broken characters. Streaming servers therefore buffer bytes until they form complete characters before sending them, and they handle tokens that only make sense together with the next one, such as a leading space.
Streaming also interacts with stop sequences. If a client asks the server to stop when it produces the text END, the server must hold back output that could be the beginning of that sequence until it knows whether the sequence completes. These details are small, but they explain why a well built streaming client receives text in uneven chunks rather than one token at a time, and why streaming correctness is part of an inference server rather than something every client must reinvent.
Context windows are token limits
Every model has a maximum context length, the largest number of tokens it can attend over in one sequence: prompt and generated output together. Early chat models had context windows of 2,048 or 4,096 tokens. Current models commonly support 128,000 tokens, and some support a million or more. The context limit is partly a property of how the model was trained and partly a property of the serving hardware, because, as later lessons show, the memory needed for each sequence grows linearly with its length.
A long context window is a ceiling, not a target. A request that uses 100,000 tokens of context costs far more to serve than one that uses 2,000, both in compute for the prompt and in memory for every generated token. Product decisions about how much history, retrieved text or tool output to include are therefore serving decisions as well. Retrieval systems, conversation summarization and prompt caching all exist partly to keep the token count of each request under control.
Why serving engineers count tokens
Almost every quantity in LLM serving is expressed per token. Latency is measured as time to the first token and time per output token. Throughput is measured in tokens per second, per GPU or per fleet. Memory for in flight requests is measured in bytes per token of context. Cost is quoted in dollars per million input tokens and per million output tokens, usually at different prices. A request is not a fixed unit of work: a 50 token question with a 20 token answer and a 30,000 token document summary are both one request, and they differ in cost by three orders of magnitude.
The practical habit this lesson builds is to describe every workload in tokens: the distribution of input lengths, the distribution of output lengths and the arrival rate. With those three numbers, the rest of this course lets you estimate memory, latency, throughput and cost for a given model and GPU before you deploy anything.
Latency, throughput, memory and price are all measured per token, and the same request can be fifty tokens or fifty thousand. Describe every workload by its input length distribution, output length distribution and arrival rate, measured with the real tokenizer.
A language model answers one question: given this sequence of tokens, what is the probability of each possible next token. Generating a whole response means asking that question again and again, each time appending the chosen token to the sequence. This loop is called autoregressive decoding, and nearly every performance property of LLM serving follows from its shape. This section walks through one iteration of the loop and then the loop as a whole.
One step of the loop
A single step takes the current token sequence and runs it through the model. Each token id is looked up in an embedding table to get a vector, typically a few thousand numbers long. The vectors pass through a stack of transformer layers; Llama 3 8B has 32 layers and Llama 3 70B has 80. At the end, the vector at the last position is multiplied by an output matrix with one row per vocabulary entry, producing one score, called a logit, for every possible next token. A softmax turns the logits into probabilities.
The server then picks one token from that distribution, according to the sampling settings, appends it to the sequence and repeats. Only the last position matters for choosing the next token, but the computation at that position depends on every earlier token through the attention mechanism, which is how the model takes the context into account.
Why the loop is sequential
Each generated token depends on the one before it, because the chosen token becomes part of the input. The model cannot compute token 50 of a response until it has chosen token 49. This is the fundamental serial dependency of autoregressive generation, and no amount of hardware removes it for a single sequence. A response of 500 tokens needs 500 sequential model steps. If each step takes 20 milliseconds, the response takes ten seconds to finish, however many GPUs are available.
Engineers work around this dependency in three ways, all covered later in the course. They make each step faster, mostly by reducing the memory that must be read per step. They run many sequences through each step at once, so the serial cost is shared across many users. And they guess several future tokens cheaply and verify them in one step, which is speculative decoding. None of these changes the fact that the per user experience is a sequence of steps.
Recomputing everything would be wasteful
A naive loop would run the full sequence through the model at every step. At step 500, it would recompute the internal state for all 499 earlier tokens, which were identical at step 499. That is quadratic work, and for long responses it would be prohibitively slow. Real inference stores the intermediate values that later steps need, the keys and values from every attention layer, in what is called the KV cache. With the cache, each step processes only the newest token and reads the cached state of the earlier ones.
The KV cache is the reason generation is feasible, and it is also the main consumer of GPU memory in a serving system, the main reason long contexts are expensive and the object that batching, paging, prefix caching and disaggregation all manage. Lesson three is devoted to it. For now, the key point is that a step in the loop does a small amount of new computation for one token while reading a large amount of stored state.
When the loop stops
The loop ends when one of several conditions is met. The model can produce an end of sequence token, which is how it signals that its answer is complete. The response can reach a maximum token limit set by the client or the server. The output can match a stop sequence the client provided. Or the sequence can hit the context window limit of the model. Servers report which condition ended generation, usually as a finish reason, and clients should check it: a response that ended because of the length limit is truncated, not complete.
Choosing a maximum output length is also a capacity decision. A server that reserves memory for the worst case output length of every request can hold fewer requests at once. Many serving systems therefore allocate memory as tokens are produced rather than up front, and they need a policy for what to do when memory runs out mid generation, such as pausing or preempting a request. Later lessons cover these policies.
The loop in a server
In a server, the loop is not run separately for each request. An engine runs a single loop over a batch of active sequences. At each step it gathers the next position of every active sequence, runs one batched model pass, samples one token for each sequence, appends them, removes sequences that finished and admits waiting requests into the freed slots. This design, called continuous or iteration level batching, means requests of very different lengths can share the GPU efficiently, because the batch is rebuilt at every step.
From the point of view of one user, nothing changes: their sequence advances by one token per engine step. From the point of view of the GPU, each step now does useful work for dozens or hundreds of users at once. The difference between those two views, per user latency versus aggregate throughput, is the central tension of LLM serving and the subject of much of this course.
Measuring the loop
Because generation is a loop, its timing has two parts: how long until the first token appears and how long each subsequent token takes. The first token waits for the whole prompt to be processed; later tokens each wait for one step of the loop. These are measured as time to first token and time per output token, defined carefully in lesson four. A simple model of a response is then the first token latency plus the number of output tokens times the per token latency. Almost every optimization in this course targets one of those two terms, and some improve one at the expense of the other.
Streaming the loop to users
Because tokens arrive one step at a time, most interactive products stream them to the client as they are produced, usually over server sent events or a WebSocket. Streaming does not make generation faster, but it changes what the user perceives: the first words appear after the prefill and the first step, and reading can begin while the rest is generated. A ten second answer that starts after half a second feels far faster than one that appears all at once after ten seconds. For non interactive uses, such as a batch job that extracts fields from documents, streaming adds overhead without benefit, and clients should request the full response in one piece.
Streaming has operational consequences. Connections stay open for the whole generation, so load balancers and proxies must allow long lived responses and must not buffer them. A client that disconnects halfway should cause the server to cancel the request and free its memory, otherwise abandoned generations keep consuming GPU time. Servers that do not propagate cancellation waste a surprising fraction of their capacity on answers nobody reads, especially in products where users frequently stop generation or navigate away.
The loop as a cost model
The loop also explains a basic fact of pricing. Prompt tokens are processed together in a few large steps, while each output token needs its own step that occupies a slot in the batch and reads the weights and cache. Output tokens therefore consume more GPU time each than input tokens, and pricing reflects it. A request that asks for a long answer is more expensive to serve than one with the same total tokens split the other way, and products that can ask for shorter outputs, such as a label instead of an explanation, save more than products that trim their prompts by the same number of tokens.
A response of N output tokens costs N sequential model steps for that user, whatever the hardware. Faster steps, more users per step and verifying several guessed tokens per step are the only levers, and the rest of the course is about pulling them.
A request goes through two very different phases. First the model processes the entire prompt; then it generates the response one token at a time. These phases are called prefill and decode. They use the same weights and the same code paths, yet they stress the hardware in opposite ways, and separating them in your head is the single most useful mental model in LLM serving.
Prefill processes the prompt in parallel
During prefill, the server runs all prompt tokens through the model in one forward pass. Unlike decoding, there is no serial dependency between prompt tokens: they are all known in advance, so the model can compute every position at once, with attention masked so each position only looks at earlier ones. A 2,000 token prompt becomes large matrix multiplications with 2,000 rows, which is exactly the work GPUs are built for. Prefill fills the KV cache with keys and values for every prompt position and produces the distribution for the first output token.
Because so many tokens are processed together, prefill is compute bound. The weights are read from memory once and used for thousands of multiply accumulate operations each, so the arithmetic units, not memory bandwidth, set the speed. A rough estimate of prefill work is two floating point operations per parameter per token. For an 8 billion parameter model and a 2,000 token prompt, that is about 32 trillion operations, which an H100 can do in a few tens of milliseconds at realistic utilization.
Decode generates one token per step
During decode, each step processes a single new token per sequence. The model still has to read all of its weights from GPU memory to do that, but it performs only about two operations per parameter for that one token. The ratio of arithmetic to bytes read is tiny, so the arithmetic units wait for memory most of the time. Decode is therefore memory bandwidth bound: the time per step is roughly the bytes that must be read divided by the memory bandwidth.
A quick calculation makes this concrete. An 8 billion parameter model in 16 bit precision has 16 gigabytes of weights. An H100 SXM has about 3.35 terabytes per second of memory bandwidth. Reading 16 gigabytes takes about 4.8 milliseconds, so a single sequence cannot decode faster than about 200 tokens per second on that GPU, even though the arithmetic for one token would take a small fraction of that time. Every decode step also reads the KV cache of the sequence, which adds to the bytes as the context grows.
Batching helps decode, not prefill
Since decode is limited by reading the weights, running several sequences through the same step costs little more than running one: the weights are read once and used for every sequence in the batch. Doubling the batch from 1 to 2 nearly doubles decode throughput at almost no latency cost. This continues until either the arithmetic units become the bottleneck or the memory for all those KV caches runs out, and in practice memory usually runs out first. That is why serving systems care so much about KV cache memory.
Prefill is already compute bound, so batching prefills together does not create free throughput the way it does for decode. A GPU running a large prefill is busy, and anything else scheduled in the same step waits for it. This asymmetry explains a lot of serving behavior: why a single long prompt can stall token streaming for everyone else on the same GPU, why engines split long prompts into chunks and why some systems run prefill and decode on separate machines.
The cost of a request has two parts
The prefill cost of a request grows with its input length, and the decode cost grows with its output length times the context it attends over. A request with a 10,000 token prompt and a 50 token answer is dominated by prefill. A request with a 100 token prompt and a 2,000 token answer is dominated by decode. The two use the GPU in such different ways that providers price them separately: output tokens usually cost several times more than input tokens per token, because a decode token occupies GPU time and memory much less efficiently than a prefill token.
Workloads therefore have a shape. Retrieval augmented question answering and summarization are prefill heavy. Chat assistants are mixed. Code generation, long form writing and reasoning models that produce long chains of thought are decode heavy. The right hardware, batch sizes, parallelism and even pricing depend on that shape, and the first question in any serving design review should be what the input and output length distributions look like.
Attention changes the picture for long contexts
The estimates above treat the weights as the main cost, which is right for short contexts. As context grows, attention adds work that scales with the sequence length. In prefill, attention over a prompt of length n costs work proportional to n squared, which becomes significant for prompts of tens of thousands of tokens. In decode, each step must read the keys and values of every earlier token, so the bytes read per step grow with the context. For long contexts and large batches, reading the KV cache can rival or exceed reading the weights.
This is why long context serving is expensive in a way that a simple per token price can hide. A 100,000 token conversation makes every decode step read a large cache, reduces how many sequences fit in memory and therefore reduces the batch size and throughput of the whole GPU. Later lessons quantify this exactly with the KV cache size formula and show how techniques such as grouped query attention, cache quantization and paging reduce it.
Interference between phases
On a shared GPU, prefill and decode compete. When the engine admits a new request, it runs that request prefill, and during that time decode steps for other requests are delayed or slowed. Users who are watching a stream see a pause. The scheduler has to balance admitting new requests quickly, which lowers their time to first token, against keeping existing streams smooth, which keeps time per output token low. Chunked prefill, which splits long prompts into pieces interleaved with decode steps, and disaggregated serving, which puts the two phases on different GPUs, are the two main answers, covered in lesson thirteen.
Measuring the two phases
Most inference engines report prefill and decode separately, and dashboards should too. Prefill throughput is measured in prompt tokens processed per second, and it is high, often tens of thousands of tokens per second per GPU for a mid sized model. Decode throughput is measured in output tokens generated per second across the batch, and it is much lower per GPU even at large batch sizes. Mixing the two into one tokens per second figure hides almost everything useful, because a workload shift toward longer prompts can make the mixed figure rise while users see worse latency. Track prompt tokens, output tokens, prefill time and decode step time as four separate series.
Where the phases meet
The first output token sits at the boundary of the two phases. Its distribution comes out of the last position of the prefill pass, so a request has its first token as soon as prefill finishes and one sampling step runs. Every later token comes from a decode step. This is why time to first token tracks prompt length and queueing, while time per output token tracks batch size and context length, and why an optimization such as prefix caching, which skips part of the prefill, mainly improves the first number, while quantization of weights, which reduces bytes per step, mainly improves the second.
A large prefill is compute bound and occupies the GPU. Without chunked prefill or separate prefill capacity, every stream on that GPU pauses while it runs, which shows up as spikes in time per output token for unrelated users.
The model gives a probability for every token in the vocabulary. Turning that distribution into one chosen token is called sampling, and the sampling settings of a request change its output, its determinism and sometimes its cost. Sampling is cheap compared with the forward pass, but it is where many confusing production behaviors come from, such as answers that change between identical requests or a model that repeats itself.
Logits and probabilities
The final layer produces a logit for every vocabulary entry, a real number where larger means more likely. A softmax converts logits to probabilities that sum to one. For a well determined next token, such as the word after The capital of France is, the distribution is very peaked: one token may have probability 0.9 and the rest share the remainder. For an open ended continuation, the probability is spread across many plausible tokens. Sampling decides how to choose given that shape.
Greedy decoding
The simplest strategy, greedy decoding, always picks the token with the highest probability. It is deterministic in principle and works well for short factual answers, classification and extraction, where the most likely answer is the one you want. For long open ended text, greedy decoding tends to produce bland and repetitive output, because the single most likely token at each step does not add up to the most natural sequence. Greedy is equivalent to sampling with temperature zero, which is how most APIs expose it.
Temperature
Temperature rescales the logits before the softmax by dividing them by a constant. A temperature below one sharpens the distribution, making the top token even more likely, and a temperature of zero becomes greedy. A temperature above one flattens it, giving less likely tokens more chance. Moderate temperatures such as 0.7 are common for chat; creative writing may use higher values, and tool calls and extraction typically use zero. Temperature does not change the ranking of tokens, only how strongly the top ranks are preferred.
Top k, top p and min p
Pure sampling at any temperature can occasionally choose a token from the long tail of very unlikely options, and one bad token can derail the rest of a response. Truncation methods remove the tail before sampling. Top k keeps only the k most likely tokens. Top p, also called nucleus sampling, keeps the smallest set of tokens whose probabilities sum to at least p, such as 0.9, so the set is small when the model is confident and larger when it is not. Min p keeps tokens whose probability is at least some fraction of the top token probability. Servers apply these filters, renormalize and then sample.
Penalties and constraints
Repetition penalties lower the logits of tokens that already appeared, reducing loops in long generations. Frequency and presence penalties are variants that scale with how often a token appeared or whether it appeared at all. Logit bias lets a client raise or lower specific tokens directly. Structured output goes further: the server constrains sampling so only tokens consistent with a grammar or JSON schema can be chosen, by masking all other logits at each step. This guarantees well formed output and is now built into most inference engines, at the cost of some extra work per step to compute the allowed set.
Determinism is harder than it looks
Setting temperature to zero or fixing a random seed does not guarantee identical outputs across requests in a production server. Floating point arithmetic is not associative, and GPU kernels may sum numbers in different orders depending on the batch size, the other requests in the batch and the kernel chosen. Two logits that are nearly tied can swap order, the chosen token changes and the rest of the response diverges. Batch invariant kernels can make outputs reproducible at some cost in speed, but by default, engineers should expect small nondeterminism and design evaluations and caches accordingly.
Sampling and performance
Sampling itself is cheap relative to the forward pass, but a few settings affect performance. Very large vocabularies make the final softmax and sorting for top p measurably expensive at large batch sizes, so engines implement sampling with fused GPU kernels. Generating several candidate responses for one prompt, a parameter often called n, shares the prompt prefill and its KV cache across candidates and is much cheaper than sending n separate requests. Beam search, which keeps multiple partial sequences and expands the best ones, is rarely used for chat models and is less well optimized in modern engines. Structured output constraints add per step overhead that good implementations keep to a small fraction of the step time.
Choosing settings in production
A sensible default is temperature zero for extraction, classification, tool calls and anything that is evaluated against a fixed answer, and a moderate temperature with top p for conversational text. Settings should be part of the prompt version and tested in evaluations, because changing temperature can change quality metrics as much as changing the prompt. Reasoning models often come with recommended sampling settings from their authors, and departing from them can degrade accuracy. Logging the sampling settings with every request is essential for reproducing a user complaint later.
Sampling across a batch
In a batched engine, every sequence in a step may have different sampling settings: one request uses greedy decoding, another uses temperature 0.8 with top p 0.95, a third has a grammar constraint and a fourth has a logit bias. The engine applies the settings per row of the batch, usually in a fused kernel that handles temperature, truncation and the random draw for all rows at once, with a separate random generator state per request so that seeds remain meaningful. Grammar constraints are applied by computing an allowed token mask per row, often on the CPU in parallel with the GPU forward pass, so that the mask is ready when the logits are.
This is also where some quality bugs hide. An engine that ignores an unsupported parameter instead of rejecting it, or applies a penalty with a slightly different formula than another engine, produces outputs that differ in subtle ways from those seen during development. When moving a workload from one serving stack to another, compare outputs under identical sampling settings on a fixed evaluation set before switching traffic, and check that every parameter the client sends is actually honored.
Reasoning models and sampling
Reasoning models generate a long internal chain of thought before the final answer, sometimes thousands of tokens. Sampling settings matter more for them, because a long chain gives more opportunities for a poor token to send the reasoning in a bad direction, and authors typically publish the settings their evaluations used. From a serving point of view, reasoning models are extremely decode heavy: a short question can produce a ten thousand token trace. That changes capacity planning, cost per request and latency expectations, and it is one of the main reasons decode efficiency has become the focus of inference work.
Logprobs as a signal
Many servers can return the log probability of each chosen token and of the top alternatives. These values are useful beyond debugging. A classifier built on a language model can read the probability of each label token directly instead of parsing text, which gives a calibrated confidence score for free. Low probability tokens in a factual answer can flag spans worth checking. Evaluations can compare models by the likelihood they assign to reference answers. Returning logprobs adds a little work per step, so it is usually opt in per request.
Temperature, top p, penalties and output constraints change quality as much as wording does. Version them together with the prompt, use temperature zero for anything graded against a fixed answer and log the settings with each request.
With tokens, the generation loop, the two phases and sampling in place, it becomes possible to say where the time and cost of inference actually go. This section builds a simple model that later lessons refine. It is deliberately approximate: the goal is to know which numbers dominate and to be able to estimate them in a few minutes.
The GPU holds three things
A serving GPU holds three main things in its memory. First, the model weights, which are fixed: an 8 billion parameter model in 16 bit precision needs about 16 gigabytes, and a 70 billion parameter model needs about 140 gigabytes, which is why it must be split across several GPUs or quantized. Second, the KV cache for all in flight sequences, which grows with the number of sequences and their lengths. Third, activations and workspace for the current step, which is comparatively small. Whatever memory is left after the weights is what determines how many sequences can be served at once.
Time per request
The time a user waits is roughly the queueing delay plus prefill time plus the number of output tokens times the per step decode time. Prefill time grows with input length and is set by compute. Decode time per step is set mostly by memory bandwidth: the bytes of weights plus the bytes of KV cache read per step, divided by bandwidth. Queueing delay depends on load and on how the scheduler admits work. For most interactive products, decode dominates the total because output lengths of hundreds of tokens multiply a per step time of tens of milliseconds.
Throughput per GPU
Throughput is the number of tokens a GPU produces per second across all users. Because a decode step reads the weights once for the whole batch, throughput grows almost linearly with batch size at first: a batch of 64 produces close to 64 times as many tokens per step as a batch of 1, while each step gets only somewhat slower. The limit is usually memory for KV caches, sometimes compute at very large batches. Typical well tuned deployments of mid sized models produce thousands of output tokens per second per GPU, while a single user stream on the same GPU might see only tens or a hundred tokens per second.
Cost per token
The cost of serving is mostly the cost of GPU time. If a GPU costs a few dollars per hour and produces a known number of tokens per second at a target latency, the cost per million tokens follows directly: hourly price divided by tokens per hour, times a million. Higher throughput per GPU means lower cost per token, which is why batching, memory efficiency and quantization are cost levers as much as speed levers. Lesson nineteen develops this into a full model including utilization, idle capacity and the different costs of input and output tokens.
The latency throughput trade off
Larger batches raise throughput and lower cost, but each step gets slower, so each user sees more time per output token, and new requests may wait longer to be admitted. Smaller batches give each user faster tokens at a higher cost per token. Every serving deployment picks a point on this curve, usually by setting a latency target such as a maximum time per output token at the 95th or 99th percentile, then running the largest batch that meets it. Products with different latency needs, such as an interactive assistant and an overnight batch job, belong at very different points on the curve, often on separate deployments.
Utilization is the hidden variable
Real fleets do not run at full batch all the time. Traffic varies by hour and by day, and capacity must cover the peak with headroom. A GPU that is busy for ten hours of a 24 hour day costs the same as one that is busy all day but produces less than half the tokens. Average utilization is therefore one of the biggest factors in real cost per token, often larger than the difference between engines or kernels. Autoscaling, batch workloads that fill off peak hours, and sharing GPUs across models all exist to raise utilization.
A first estimate in practice
Suppose a team wants to serve an 8 billion parameter model on one H100 with 80 gigabytes of memory. Weights take 16 gigabytes, leaving roughly 55 gigabytes for KV cache after workspace. With the cache size formula from lesson three, about 128 kilobytes per token for that model, the GPU can hold around 430,000 tokens of context, for example 200 sequences of 2,000 tokens each. Decode steps read 16 gigabytes of weights plus the active caches, so a full batch step takes perhaps 15 to 25 milliseconds, giving each user roughly 40 to 60 tokens per second and the GPU several thousand tokens per second in total. These numbers are rough, but they are the right order of magnitude, and each later lesson sharpens one of them.
What the rest of the course does
The remaining lessons follow the structure of this estimate. The next three explain the forward pass, the KV cache and latency metrics in detail. The hardware section explains GPU memory, bandwidth and parallelism. The optimization section covers each technique that raises tokens per step or lowers bytes per token. The serving systems section covers the engines, routers and autoscalers that run models at fleet scale, and the final section turns all of it into cost, caching, evaluation and reliability practice.
Input and output have different costs
The asymmetry between prefill and decode shows up directly in cost per request. Prefill processes prompt tokens in large, efficient batches, so the GPU time per prompt token is small. Decode spends one step per output token per sequence, and each step is limited by memory reads that are only partly shared across the batch. Per token, output is therefore several times more expensive to produce than input, and commercial price lists reflect this with output prices commonly three to five times the input price. Prompt caching makes repeated input even cheaper, so long shared prefixes such as system prompts and documents become cheaper still, while output stays the dominant cost for verbose responses.
This asymmetry suggests practical levers. Asking for concise answers, structured outputs instead of prose and short reasoning when long reasoning is not needed all cut the expensive side. Moving stable instructions to a shared, cached prefix cuts the cheap side further. Engineers who model the cost of a feature should estimate input and output tokens separately and multiply each by its own price, rather than using a blended figure that hides where the money goes.
Overheads outside the GPU
Not all time is GPU time. Tokenization, chat template rendering, request validation, routing, network transfer and streaming all add latency, typically small compared with generation but noticeable for short requests. Python overhead in the engine scheduler can matter at very small step times, which is why engines use CUDA graphs and move scheduling logic out of the hot path. Retrieval, tool calls and guardrail models in front of or behind the LLM often add more latency than the model itself for short answers. A latency budget should list every stage, not just the model step, before deciding which optimization to pursue.
A junior engineer knows models generate one token at a time and that prompts and outputs are billed in tokens. A mid level engineer explains prefill versus decode, why decode is memory bound and how batching raises throughput. A senior engineer estimates memory, latency, throughput and cost for a model and workload from first principles and knows which optimization moves which number.