Sub topic 6
Running Offline Inference with the `LLM` Class
Assume you know basic Python, can run commands in a terminal, and understand prompts and completions. You should also have an NVIDIA GPU with enough memory for the model. Offline inference means your Python process loads the model and generates responses directly. It does not start an HTTP server.
The offline execution model
The LLM class is vLLM's main offline inference interface. When you create an instance, vLLM loads the model weights and prepares its GPU memory. You then submit one prompt or a batch of prompts to generate or chat.
A batch is useful because vLLM can schedule several requests together. The requests do not need to have the same prompt length. vLLM handles the scheduling and returns one output object for each input.
The main arguments determine how much work vLLM can accept:
| Argument | Purpose |
|---|---|
| `model` | Hugging Face model identifier or local model path |
| `max_model_len` | Maximum number of input and generated tokens in one request |
| `gpu_memory_utilization` | Fraction of GPU memory vLLM may reserve |
Load a chat model and process a batch
Instruction-tuned models expect messages with roles such as user and assistant. The chat method applies the model's chat template before generation. A chat template is the model-specific format that converts messages into tokens.
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
gpu_memory_utilization=0.85,
)
sampling = SamplingParams(
temperature=0.7,
top_p=0.95,
max_tokens=128,
)
conversations = [
[{"role": "user", "content": "Explain the KV cache in two sentences."}],
[{"role": "user", "content": "What is continuous batching?"}],
]
outputs = llm.chat(conversations, sampling)
for conversation, output in zip(conversations, outputs):
prompt = conversation[-1]["content"]
answer = output.outputs[0].text
print(f"Prompt: {prompt}\nAnswer: {answer}\n")The first call downloads model files if they are not already in the local Hugging Face cache. Later runs can reuse those files. Each RequestOutput contains one or more candidate completions in output.outputs. With the default setting, outputs[0] is the selected completion.
max_tokens limits only newly generated tokens. max_model_len covers the whole request context, including the prompt and generated text. Keep these limits realistic: larger contexts reserve more memory and may reduce the number of requests that fit concurrently.
Exercise
Exercise
Which setting limits the number of tokens generated after the input prompt?
Show answer
SamplingParams(max_tokens=...) limits newly generated tokens. max_model_len limits the total context length.