Sub topic 6
Running offline inference with the LLM class
This chapter assumes you can write basic Python and use a command line. It also assumes you know what a prompt and a completion are, and that a GPU has a fixed amount of memory. Earlier chapters covered prefill, decode, the KV cache, PagedAttention and continuous batching. Here you put them to work through vLLM's Python API.
What offline inference means
Offline inference means you run vLLM inside your own Python process, with no HTTP server. You hand it a list of prompts, it generates all the completions, and your script continues. This fits jobs where nobody waits on a single answer:
- Labelling or summarising a dataset.
- Generating synthetic training data.
- Running an evaluation suite.
- Quick experiments in a notebook.
The entry point is the LLM class. When you construct it, vLLM does the slow, one-time work: it downloads the weights from the Hugging Face Hub (or reads a local path), loads them onto the GPU, measures how much memory is left, and reserves that memory for the KV cache. Every later call reuses this setup, so create the LLM object once and call it many times.
Your first run
The example below loads a small instruction-tuned model, applies its chat template through llm.chat, and generates a bounded, sampled reply.
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.7, top_p=0.95, max_tokens=128)
messages = [{"role": "user", "content": "Explain the KV cache in two sentences."}]
outputs = llm.chat(messages, params)
print(outputs[0].outputs[0].text)Three constructor arguments appear here, and each controls memory:
modelis a Hugging Face model ID or a local directory containing the weights, config and tokenizer.max_model_lencaps the total tokens (prompt plus output) of any one request. A smaller value means vLLM must plan for shorter sequences, which frees memory for more concurrent requests. If you leave it out, vLLM uses the model's own maximum, which can be very large.gpu_memory_utilizationis the fraction of GPU memory vLLM may use in total. Weights, activations and the KV cache must all fit inside it.0.85leaves 15% as headroom.
The first run is slow because of the download and because vLLM prepares its execution kernels. Later runs read from the local Hugging Face cache.
Two ways to call the model: generate and chat
LLM has two main generation methods. Choosing the wrong one is a common source of poor output.
| Method | Input | Chat template applied? | Use it for |
|---|---|---|---|
| `llm.generate(prompts, params)` | Raw strings | No | Base models, completion tasks, prompts you format yourself |
| `llm.chat(messages, params)` | List of role/content messages | Yes, automatically | Instruction-tuned and chat models |
With generate, the string goes to the model exactly as written. If you pass "Explain the KV cache" to an instruction-tuned model this way, it may continue the sentence instead of answering, because it never saw the special tokens that mark a user turn. chat reads the template stored with the tokenizer and wraps your messages correctly. A later chapter covers templates in detail.
A raw-text version looks like this:
from vllm import LLM, SamplingParams
llm = LLM(model="Qwen/Qwen2.5-1.5B-Instruct", max_model_len=4096)
params = SamplingParams(temperature=0.0, max_tokens=40)
prompts = [
"The capital of France is",
"Two plus two equals",
"The chemical symbol for gold is",
]
for output in llm.generate(prompts, params):
print(repr(output.prompt), "->", repr(output.outputs[0].text))Batching: pass many prompts in one call
The main reason to use offline mode is throughput. Passing a list lets the scheduler run continuous batching across all the prompts. It keeps the GPU full by admitting a new sequence as soon as another finishes.
from vllm import LLM, SamplingParams
llm = LLM(model="Qwen/Qwen2.5-1.5B-Instruct", max_model_len=4096)
params = SamplingParams(temperature=0.0, max_tokens=64)
conversations = [
[{"role": "user", "content": f"Give one fact about the number {n}."}]
for n in range(1, 101)
]
outputs = llm.chat(conversations, params)
for out in outputs[:3]:
print(out.outputs[0].text.strip())
print("---")Do not write a Python loop that calls llm.chat once per prompt. Each call then holds only one request, the batch never forms, and throughput drops sharply. Give vLLM the whole list and let it decide the order.
vLLM returns results in the same order as your inputs, even though it may finish them in a different order internally. You can match outputs to inputs by position.
Reading the result
Each element of the returned list is a RequestOutput. The fields you use most are:
prompt: the input text.prompt_token_ids: the tokens the prompt became.outputs: a list ofCompletionOutputobjects, one per requested sample (ninSamplingParams).outputs[i].text: the generated text.outputs[i].token_ids: the generated tokens.outputs[i].finish_reason:"stop"if the model ended naturally or hit a stop string,"length"if it hitmax_tokens.
Always check finish_reason. A value of "length" means the answer was cut off, which is easy to miss in a large batch.
from vllm import LLM, SamplingParams
llm = LLM(model="Qwen/Qwen2.5-1.5B-Instruct", max_model_len=4096)
params = SamplingParams(temperature=0.0, max_tokens=20)
messages = [{"role": "user", "content": "Write a long essay about GPUs."}]
result = llm.chat(messages, params)[0]
completion = result.outputs[0]
print("prompt tokens:", len(result.prompt_token_ids))
print("generated tokens:", len(completion.token_ids))
print("finish reason:", completion.finish_reason)Here the finish reason is "length", because 20 tokens is far too few for an essay.
Common errors
Out of memory at startup. The message mentions CUDA out of memory, or says there is not enough room for the KV cache. Lower max_model_len, lower gpu_memory_utilization if other processes share the GPU, or choose a smaller or quantized model.
Context length error. If the model's default maximum context is larger than the KV cache can hold, vLLM refuses to start and tells you the largest length that fits. Set max_model_len to that value or lower.
Using generate on a chat model. Output rambles or repeats the prompt. Switch to llm.chat.
GPU already in use. A second LLM object in the same notebook, or a leftover process, still holds memory. Restart the kernel, or check with nvidia-smi.
Creating LLM inside a loop. Each construction reloads the weights. Build it once.
Scripts that run twice on some platforms. vLLM may start worker processes. Put your code under if __name__ == "__main__": in scripts, especially with multiple GPUs.
Checking the work
Time a batch to see the benefit of batching for yourself. This measures output tokens per second for the whole call:
import time
from vllm import LLM, SamplingParams
llm = LLM(model="Qwen/Qwen2.5-1.5B-Instruct", max_model_len=4096)
params = SamplingParams(temperature=0.0, max_tokens=64)
batch = [[{"role": "user", "content": f"Name a fruit starting with letter {c}."}]
for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"] * 8
start = time.perf_counter()
outputs = llm.chat(batch, params)
elapsed = time.perf_counter() - start
generated = sum(len(o.outputs[0].token_ids) for o in outputs)
print(f"{len(batch)} requests, {generated} tokens, {generated / elapsed:.0f} tokens/s")Run it with a batch of 1 and then 208 requests. The tokens-per-second figure rises by a large factor, because decode steps for many sequences share one pass over the model weights.
Exercise
You wrote a loop that calls llm.chat([msg], params) for each of 1,000 prompts, and it runs slowly while GPU utilization stays low. What is wrong, and how do you fix it?
Show answer
Each call contains a single request, so continuous batching never has multiple sequences to run together, and the GPU is idle during much of each step. Build a list of 1,000 message lists and make one call, llm.chat(all_messages, params). vLLM then schedules the requests together and returns the outputs in input order.
Exercise
An output ends mid-sentence, and finish_reason is "length". Name two possible causes and one fix.
Show answer
Either max_tokens in SamplingParams is too small for the answer, or the prompt plus output reached max_model_len. Raise max_tokens, and if the total is the limit, raise max_model_len as far as KV cache memory allows.