Starts Nov 23Live Cohort 3 of Vibe Coding & AI Agents (Nov 23, 18:30 MSK): 3 weeks, 9 live hands-on sessionsCohort 3 (Nov 23) →
InfrastructureInsight · On RadarMachine Learning Mastery→ original

A vLLM Request with n=4 Uses Roughly Four Times the KV Cache for Its Outputs

When you ask vLLM for four response variants (n=4), the server keeps four live sequences, and each one has its own KV cache: the region of GPU memory that holds the intermediate data for tokens already processed. The shared prompt portion is reused, but each variant generates its own tokens, so the cache for the generated output grows roughly fourfold. The top-k and top-p filters barely reduce compute. Budget memory based on the number of variants and response length, not on sampler tuning.

AI-processed from Machine Learning Mastery; edited by Hamidun News
A vLLM Request with n=4 Uses Roughly Four Times the KV Cache for Its Outputs
Source: Machine Learning Mastery. Collage: Hamidun News.
Listen to article
Article Fact Sheet & Key Figures
ParameterDetails
Primary sourceMachine Learning Mastery ↗
Editor-in-Chief
Key metric #1Top-k and top-p run after logits have been computed for the model's entire vocabulary
Key metric #2Beam search with width 4 keeps up to four hypotheses and ranks them at every step
Max_tokens is a ceiling, not a reservationa response can end earlier on EOS

Imagine you add a "show four answer options" button to a chat service. For the user it's a single checkbox, but for a server running vLLM (a popular engine for serving language models) it means four responses that are alive at the same time. Each one holds its own KV cache, the region of GPU memory where intermediate data for already processed tokens is stored, so the model doesn't have to recompute them. A Machine Learning Mastery breakdown shows that n=4 yields roughly four times as much cache for the generated portion, even though the model weights and the prompt stay the same. Only the token selection policy changes, but it has a cost in milliseconds and gigabytes.

The sampler: cheaper than the model, but not free

In vLLM, running the model is separated from choosing a token. The SamplingParams object handles the choice. In its examples, the author uses the small SmolLM2-1.7B-Instruct and compares greedy decoding, temperature, top-k, top-p, and a repetition penalty.

An important detail: none of these filters reduce the model's own work. It still computes a score for every word in the vocabulary. Top-k and top-p act afterward, on top of those finished scores (logits). Greedy decoding simply takes the maximum. Temperature sampling additionally converts the scores into probabilities and draws a token. Top-p has to sort the candidates to find the smallest set with the required cumulative probability. The repetition penalty has to look through the history of tokens already emitted.

All of this happens at every generation step. It is usually much smaller than the cost of running the model itself, but its share grows when the model is small, the vocabulary or batch is large, or several processors are active. The author stresses separately that the largest difference in cost often comes from response length. More tokens mean more model calls and a longer KV cache.

Multiple outputs and beam search: you pay in memory

The n parameter asks for several independent response variants to the same prompt. For n=4, the engine runs four live sequences. The prompt and its cache can be shared among them, but once the tokens diverge, each sequence's new portion of the cache becomes private. If each sequence produces G tokens, the generated cache is roughly four times larger than for a single response. Even so, this can still be cheaper than four separate requests, because the shared computation can be reused and the active sequences can be batched together.

Beam search works differently. Here the hypotheses compete on their accumulated score: at each step the engine expands them, ranks the candidates together, and keeps the best ones. Beyond compute and cache, it has to update scores, select the survivors, and make sure references to tokens and cache blocks don't get out of sync. As a result, at the same width and length it costs more than four independent samples. Wide beams also take cache space away from other users' requests. In vLLM, beam search is provided through a separate API with BeamSearchParams.

Stop conditions determine how long a request holds memory

While a request is unfinished, its KV cache blocks stay allocated. That makes the cost highly dependent on when generation stops. max_tokens is an upper bound, not a reservation: a response can finish earlier on the end-of-text token (EOS). A smaller limit caps the worst case for latency and memory, but it won't speed up a request if both configurations would have stopped on the same token anyway.

min_tokens prevents a response from ending too early, so it can only leave the amount of work unchanged or increase it. Stop strings, such as a double newline, require incremental detokenization and checks on the text to detect the end. This adds overhead, but it pays off when responses would otherwise end well before the limit. The engine removes finished sequences from subsequent iterations and fills their slots with other work.

What to do in practice

First, don't choose top-k for speed: it gives no noticeable gain. Second, treat n and beam width as memory multipliers and factor them into your cluster capacity. Third, set a sensible max_tokens and appropriate stop conditions, especially for services with long responses. For measurement, the author recommends the PyTorch profiler and the kv_cache_usage_perc metric, and suggests measuring time to first token and generation throughput through a streaming server or vllm bench serve. A profiled request is unsuitable for a performance report, because profiling itself changes performance.

Limitations: the material contains no ready-made benchmarks. The author deliberately omits machine results, since they depend on hardware, batch size, and the vLLM version. The section on structured output (JSON schemas, regular expressions, grammars) breaks off in the available text at a code example. It is only known that such constraints narrow the allowed tokens at each step and add separate per-request state. Check the cost on your own workload.

Story

Key Questions Answered

What are the key details on The sampler: cheaper than the model, but not free?

In vLLM, running the model is separated from choosing a token. The SamplingParams object handles the choice. In its examples, the author uses the small SmolLM2-1.7B-Instruct and compares greedy decoding, temperature, top-k, top-p, and a repetition penalty. An important detail: none of these filters reduce the model's own work. It still computes a score for every word in the vocabulary. Top-k and top-p act afterward, on top of those finished scores (logits). Greedy decoding simply takes the maximum.

What are the key details on Multiple outputs and beam search: you pay in memory?

The n parameter asks for several independent response variants to the same prompt. For n=4, the engine runs four live sequences. The prompt and its cache can be shared among them, but once the tokens diverge, each sequence's new portion of the cache becomes private. If each sequence produces G tokens, the generated cache is roughly four times larger than for a single response.

What are the key details on Stop conditions determine how long a request holds memory?

While a request is unfinished, its KV cache blocks stay allocated. That makes the cost highly dependent on when generation stops. max_tokens is an upper bound, not a reservation: a response can finish earlier on the end-of-text token (EOS). A smaller limit caps the worst case for latency and memory, but it won't speed up a request if both configurations would have stopped on the same token anyway.

ZK
Zhemal Khamidun — CPO at Alpina Digital, product manager of AlpinaGPT. Building AI products since 2019. Hamidun News is a pet project that grew into a production aggregator with 6,000+ readers.
✦ Unified AI Workspace · Nomad

Test Frontier LLMs & Autonomous Agents in One Workspace

Run Claude Opus 5.5, GPT-6, Gemini 3.1, and DeepSeek side-by-side in Nomad AI (nomadnet.ai) — unified model routing, deep research, and multimodal workflows under one subscription.

Try Nomad AI →Launch Nomad Agent
What do you think?
Loading comments…