Sub topic 7
Controlling generation with SamplingParams
This chapter assumes you can run LLM(...) and llm.chat(...) from the offline inference chapter. It also assumes you know that a model produces a probability distribution over the next token at each decode step. Here you will learn which SamplingParams fields control that step, which defaults catch people out, and how to set the same options through the server.
What SamplingParams does
SamplingParams is a plain object that you pass to llm.generate or llm.chat. It tells vLLM how to turn the model's output scores (logits) into a token, and when to stop. Each request carries its own SamplingParams. Because of continuous batching, requests with different settings can share one batch.
The sampling step happens once per decode iteration, after the forward pass. The fields below act on the logits in roughly this order.
Randomness: temperature, top_p, top_k, min_p
temperature rescales the logits before they become probabilities. Values below 1 sharpen the distribution, and values above 1 flatten it. A temperature of 0 means greedy decoding: always pick the most likely token. Greedy output is repeatable on the same hardware and software, but it can loop or repeat itself on long outputs.
The other three fields remove unlikely tokens before sampling:
| Field | Meaning | Disabled value |
|---|---|---|
| `top_p` | Keep the smallest set of tokens whose probabilities add up to at least `p` | `1.0` |
| `top_k` | Keep only the `k` most likely tokens | `-1` (or `0` in newer versions) |
| `min_p` | Drop tokens whose probability is below `min_p` times the top token's probability | `0.0` |
A common starting point for chat is temperature=0.7 and top_p=0.95. For extraction, classification, or code, use temperature=0 or a value near 0.2. Tune one knob at a time. Setting temperature, top_p, and top_k aggressively together makes it hard to tell which one changed the output.
Length and stopping
Generation ends when one of these happens:
- The model emits its end-of-sequence token.
- The output reaches
max_tokens. - The output contains a string in
stop, or a token ID instop_token_ids. - The total length reaches
max_model_len.
The finish reason tells you which condition ended the output. A finish_reason of "length" means the reply was truncated. A value of "stop" means the model ended, or a stop string or stop token matched.
Two related fields are min_tokens, which blocks the end-of-sequence token until a minimum length is reached, and ignore_eos, which keeps generating past end-of-sequence. ignore_eos=True is mainly useful in benchmarks, where you want every request to produce exactly max_tokens tokens.
By default, a matched stop string is removed from the text. Set include_stop_str_in_output=True to keep it.
A runnable example
This script sends the same prompt with three configurations in one generate call. It prints the finish reason for each, so you can see truncation.
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
gpu_memory_utilization=0.85,
)
prompt = "List three uses of a KV cache:\n1."
configs = {
"greedy": SamplingParams(temperature=0, max_tokens=60),
"creative": SamplingParams(temperature=1.0, top_p=0.9, max_tokens=60, seed=7),
"short": SamplingParams(temperature=0, max_tokens=8),
}
outputs = llm.generate([prompt] * len(configs), list(configs.values()))
for name, out in zip(configs, outputs):
completion = out.outputs[0]
print(f"--- {name} (finish_reason={completion.finish_reason}) ---")
print(completion.text)llm.generate accepts either one SamplingParams for all prompts or a list with one entry per prompt. The short request ends with finish_reason="length", because 8 tokens is not enough for the list.
Reproducibility and the model's own defaults
seed makes a request's random sampling repeatable. It fixes the random draw, not the numerical results. Different batch compositions, GPU types, or vLLM versions can still produce slightly different logits, so a seeded run is not a guarantee of identical text across deployments.
There is a second gotcha. By default, vLLM reads generation_config.json from the model repository and uses its values (for example top_k or repetition_penalty) as defaults for requests that do not set them. Your request is therefore not always using the library defaults. You can inspect the effective defaults like this:
from vllm import LLM
llm = LLM(model="Qwen/Qwen2.5-1.5B-Instruct", max_model_len=4096)
defaults = llm.get_default_sampling_params()
print(defaults)To ignore the model's file, pass generation_config="vllm" when you create the LLM, or use --generation-config vllm with vllm serve.
Penalties and multiple outputs
Three fields discourage repetition:
repetition_penaltyis multiplicative and applies to tokens that appeared in the prompt or the output. A value of1.0has no effect, and values slightly above1, such as1.1, reduce repetition.presence_penaltysubtracts a fixed amount from any token that has already appeared. The range is -2.0 to 2.0, and0disables it.frequency_penaltysubtracts an amount that grows with how often a token has appeared. The range is the same as forpresence_penalty.
Penalties distort the distribution, so small values usually work best. Raise them only when you see actual looping.
n asks for several completions per prompt, returned in outputs[0].outputs as a list. With temperature=0, all n completions are identical, so use n > 1 only with sampling. Setting logprobs=k returns the top k log probabilities for each generated token. This is useful for confidence scores and for debugging why a token was chosen, but it adds work and response size.
The same options through the server
The OpenAI-compatible server accepts the standard fields temperature, top_p, max_tokens, stop, seed, n, presence_penalty, and frequency_penalty. Fields that the OpenAI API lacks, such as top_k, min_p, and repetition_penalty, go in extra_body, which the OpenAI client merges into the JSON request.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
response = client.chat.completions.create(
model="Qwen/Qwen2.5-1.5B-Instruct",
messages=[{"role": "user", "content": "Name two uses of prefix caching."}],
temperature=0.7,
top_p=0.95,
max_tokens=120,
stop=["\n\n"],
extra_body={"top_k": 40, "repetition_penalty": 1.05},
)
choice = response.choices[0]
print(choice.message.content)
print("finish_reason:", choice.finish_reason)In the server's responses, finish_reason is "length" when max_tokens was reached and "stop" otherwise. A client that never checks it will silently treat truncated text as a complete answer.
Common errors
- Truncated output. The cause is usually the default
max_tokens=16or a low explicit value. Checkfinish_reason. - Different results from run to run. Sampling is on. Set
temperature=0or aseed, and remember that neither is a cross-hardware guarantee. - Request rejected for length. The prompt tokens plus
max_tokenscan exceedmax_model_len. Shorten the prompt or lowermax_tokens. - Settings that seem ignored.
temperature=0makestop_pandtop_kirrelevant, because only one token can be chosen. - Unexpected behavior with no code change. The model's
generation_config.jsonsupplied a default. Printget_default_sampling_params().
Exercise
A teammate's script calls llm.generate(prompts, SamplingParams(temperature=0.8)) and every answer stops mid-sentence. What is the likely cause, what field in the output confirms it, and what is the fix?
Show answer
SamplingParams defaults maxtokens to 16, so each reply is cut after 16 tokens. The finishreason of each completion (outputs[0].finishreason) will be "length", which confirms truncation. The fix is to set maxtokens explicitly, for example SamplingParams(temperature=0.8, maxtokens=256), keeping the prompt length plus maxtokens within maxmodellen.
Exercise
You need a classifier that returns the same label every time for a given input, and you call it through vllm serve with the OpenAI client. Which request fields would you set, and why is a seed alone a weaker choice?
Show answer
Set temperature=0 for greedy decoding and a small max_tokens such as 5 to 10, since a label is short. A seed only fixes the random draw, so it still samples from a distribution, and output can still differ across batch compositions or hardware. Greedy decoding removes the random choice entirely.