Sub topic 7
Controlling Generation with SamplingParams
This chapter assumes you know basic Python, can run a vLLM model, and understand prompts and completions. SamplingParams is a vLLM object that controls how the model chooses each output token. A token is a small piece of text, such as a word, punctuation mark, or word fragment.
A working example
Start with a loaded model and create one set of sampling parameters:
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
gpu_memory_utilization=0.85,
)
params = SamplingParams(
temperature=0.2,
top_p=0.9,
max_tokens=80,
)
prompts = [
"Give one sentence explaining why tests matter.",
"Give one sentence explaining why logs matter.",
]
outputs = llm.generate(prompts, params)
for output in outputs:
text = output.outputs[0].text.strip()
print(text)max_tokens limits the number of generated tokens. It does not limit the input prompt. A small value protects latency and cost, but an answer can stop abruptly if the limit is too low.
temperature controls randomness. Values near zero make token selection more predictable. Higher values produce more variation. A value of 0.2 fits short, factual answers. Creative writing may benefit from values around 0.7 or higher.
top_p limits sampling to the smallest group of likely next tokens whose combined probability reaches the given value. Lower values reduce variation. Usually, tune temperature and top_p one at a time instead of making both highly restrictive.
Useful controls
| Parameter | Effect | Typical use |
|---|---|---|
| `temperature` | Changes randomness | Lower it for repeatable answers |
| `top_p` | Limits the probability mass considered | Reduce unlikely choices |
| `top_k` | Limits choices to the K most likely tokens | Apply a hard candidate limit |
| `max_tokens` | Caps output length | Bound latency and response size |
| `stop` | Stops at specified strings | End structured sections |
| `n` | Requests multiple completions | Compare several candidate answers |
The model can still produce different text with a low temperature. Sampling, prompt details, and backend behavior affect the result. If you need reproducible experiments, set a seed when your vLLM version supports it and keep the model, parameters, and prompts unchanged.
How choices affect output
A common error is expecting max_tokens to force a complete answer. It only sets an upper bound. Another error is using high randomness for classification or extraction, where unexpected wording can break downstream code.
Exercise
You are generating a short product category for a database field. Which settings are a sensible starting point: temperature 0.2 or 1.2, and max_tokens 20 or 200? Explain why.
Show answer
Start with temperature 0.2 and max_tokens 20. The lower temperature favors consistent choices, and the small limit prevents an unexpectedly long field.