vLLM Wrapper
vLLM¶
Note
vLLM currently supports only a limited number of models, and many implementations have subtle differences compared to the default implementations in mteb. For the full list of supported models, refer to the vllm documentation.
Installation¶
If you're using cuda you can run
pip install "mteb[vllm]"
uv pip install "mteb[vllm]"
For other architectures, please refer to the vLLM installation guide.
Usage¶
To use vLLM with MTEB, you need to wrap the model with its corresponding wrapper class.
Python Multiprocessing Note
You must guard vLLM usage inside an if __name__ == '__main__': block to avoid Python multiprocessing issues. For example, instead of:
import vllm
llm = vllm.LLM(...)
do:
if __name__ == "__main__":
import vllm
llm = vllm.LLM(...)
See the vLLM troubleshooting guide for more details.
import mteb
from mteb.models.vllm_wrapper import VllmEncoderWrapper
def run_vllm_encoder():
"""Evaluate a model on specified MTEB tasks using vLLM for inference."""
encoder = VllmEncoderWrapper(model="intfloat/e5-small")
return mteb.evaluate(
encoder,
mteb.get_task("STS12"),
)
if __name__ == "__main__":
results = run_vllm_encoder()
print(results)
import mteb
from mteb.models.vllm_wrapper import VllmCrossEncoderWrapper
def run_vllm_crossencoder():
"""Evaluate a model on specified MTEB tasks using vLLM for inference."""
cross_encoder = VllmCrossEncoderWrapper(
model="cross-encoder/ms-marco-MiniLM-L-6-v2"
)
return mteb.evaluate(
cross_encoder,
mteb.get_task("AskUbuntuDupQuestions"),
)
if __name__ == "__main__":
results = run_vllm_crossencoder()
print(results)
Why is vLLM Fast?¶
Half-Precision Inference¶
By default, vLLM uses Flash Attention, which only supports float16 and bfloat16, not float32.
We provide a standalone benchmark script scripts/bench_vllm/dtype.py to quantify inference performance across different precisions.
ST: Sentence Transformers backend; vLLM: vLLM backend.
X-axis: Throughput (requests/s); Y-axis: Latency (ms per step, log scale).
The lower‑right curve (↘) is better.
Floating‑Point Formats
| Format | Bits | Exponent | Fraction |
|---|---|---|---|
| float32 | 32 | 8 | 23 |
| float16 | 16 | 5 | 10 |
| bfloat16 | 16 | 8 | 7 |
- When model weights are stored in
float32, vLLM defaults tofloat16for inference. This generally preserves numerical precision well becausefloat16keeps relatively more fraction bits, but due to its smaller exponent (5 bits), some models (e.g., the Gemma family) may produce NaNs. vLLM maintains a list of such models and usesbfloat16for them by default. - Using
bfloat16avoids NaN risks because its exponent matchesfloat32(8 bits), but with only 7 fraction bits, numerical precision degrades noticeably. - Using
float32incurs no precision loss but is roughly 4× slower than half‑precision (float16/bfloat16).
If model weights are natively in float16 or bfloat16, vLLM defaults to the original dtype for inference.
Quantization: With the rise of open‑source large models, fine‑tuned models for embedding and reranking are becoming larger. Exploring quantization methods (GPTQ, AWQ, etc.) to accelerate inference and reduce GPU memory usage may become necessary.
Unpadding¶
By default, Sentence Transformers (ST) pad all inputs in a batch to the length of the longest one, which is highly inefficient. vLLM avoids padding entirely during inference.
We provide a standalone benchmark script scripts/bench_vllm/unpadding.py to quantify inference performance using unpadding.
ST: Sentence Transformers; vLLM: vLLM.
Y-axis: Latency (ms per step, log scale).
The lower‑right curve (↘) is better.
ST suffers a noticeable drop in speed when handling requests with varied input lengths, whereas vLLM does not.
Overlap preprocessing and computation¶
(Available since vLLM 0.26.0)
For these small models, preprocessing bottlenecks are often encountered.
- Use multithreading to accelerate preprocessing. You can specify the number of threads using renderer_num_workers. The total time scales down almost linearly as the number of renderer workers increases, if you encounter preprocessing bottlenecks.
- Tiling to overlap preprocessing and computation for pooling models offline inference. When preprocessing takes less time than computation, the preprocessing overhead can be almost entirely overlapped.
We provide a standalone benchmark script scripts/bench_vllm/renderer_num_workers.py to quantify inference performance using renderer_num_workers.
Y‑axis: Time for 100 embeddings (seconds, log₁₀ scale).
Each curve corresponds to a different number of renderer workers (1, 2, 4, 8).
Lower curves is better.
Other Optimizations¶
For models using bidirectional attention (e.g., BERT), vLLM offers a range of performance optimisations:
- Optimised CUDA kernels (integrating FlashAttention and FlashInfer)
- CUDA Graphs and
torch.compilesupport to reduce overhead and accelerate execution - Support for tensor, pipeline, data, and expert parallelism for distributed inference
- Multiple quantization schemes (GPTQ, AWQ, AutoRound, INT4, INT8, FP8) for efficient deployment
- Continuous batching of incoming requests to maximise throughput
For causal attention models (e.g., Qwen3 reranker), the following additional optimisations apply:
- Efficient KV cache memory management via PagedAttention
- Chunked prefill for improved memory handling during long‑context processing
- Prefix caching to accelerate repeated prompt processing
vLLM’s optimisations are primarily designed for and most effective with causal language models (generative models). For the full list of features, refer to the vLLM features documentation.
vLLM Pooling Models¶
What are pooling models?¶
vLLM models can be categorized into two types:
-
Generative Models - Models that produce text completions or chat responses (e.g., LLaMA, Qwen, DeepSeek). Use
LLM.generate()andLLM.chat()for these models. -
Pooling Models - These models do not generate content. They are primarily used for classification and retrieval tasks, such as bge-m3 and Qwen3 Reranker.
Sequence-wise Task and Token-wise Task¶
The key distinction between sequence-wise task and token-wise task lies in their output granularity: sequence-wise task produces a single result for an entire input sequence, whereas token-wise task yields a result for each individual token within the sequence.
Pooling Usages¶
| Pooling Usages | Description |
|---|---|
| Classification Usages | Predicting which predefined category, class, or label best corresponds to a given input. |
| Embedding Usages | Converts unstructured data (text, images, audio, etc.) into structured numerical vectors (embeddings). |
| Token Classification Usages | Token-wise classification |
| Token Embedding Usages | Token-wise embedding |
| Reward Usages | Evaluates the quality of outputs generated by a language model, acting as a proxy for human preferences. |
| Scoring Usages | Computes similarity scores between two inputs. It supports three model types (aka score_type): cross-encoder, late-interaction, and bi-encoder. |
| Plugins Usages | Allow users to customize input and output processors. For more information, please refer to IO Processor Plugins. |
API Reference¶
mteb.models.vllm_wrapper.VllmWrapperBase
¶
Base wrapper for vLLM serving engine.
Source code in mteb/models/vllm_wrapper.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
__init__(model, revision=None, *, trust_remote_code=True, dtype='auto', head_dtype=None, max_model_len=None, max_num_batched_tokens=None, max_num_seqs=128, renderer_num_workers=1, tensor_parallel_size=1, enable_prefix_caching=None, gpu_memory_utilization=0.9, hf_overrides=None, pooler_config=None, enforce_eager=False, **kwargs)
¶
Wrapper for vLLM serving engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | ModelMeta
|
Model name or ModelMeta instance. |
required |
revision
|
str | None
|
The revision of the model to use. |
None
|
trust_remote_code
|
bool
|
Whether to trust remote code execution when loading the model. Should be True for models with custom code. |
True
|
dtype
|
Dtype
|
Data type for model weights. "auto" will automatically select appropriate dtype based on hardware and model capabilities. vLLM uses flash attention by default, which requires fp16/bf16; using fp32 may cause fallback or slow speed. |
'auto'
|
head_dtype
|
Literal['model'] | Dtype | None
|
If provided, overrides the data type of the head layers. If None (default), the model's original head dtype is kept. |
None
|
max_model_len
|
int | None
|
Maximum sequence length (context window) supported by the model. If None, uses the model's default maximum length. |
None
|
max_num_batched_tokens
|
int | None
|
Maximum number of tokens to process in a single batch. If None, automatically determined. |
None
|
max_num_seqs
|
int
|
Maximum number of sequences to process concurrently. |
128
|
renderer_num_workers
|
int
|
Number of threads for multithreading to accelerate preprocessing. Defaults to 1. Only effective for vLLM versions >= 0.26.0. |
1
|
tensor_parallel_size
|
int
|
Number of GPUs for tensor parallelism. |
1
|
enable_prefix_caching
|
bool | None
|
Whether to enable KV cache sharing for common prompt prefixes. If None, uses the model's default setting. |
None
|
gpu_memory_utilization
|
float
|
Target GPU memory utilization ratio (0.0 to 1.0). |
0.9
|
hf_overrides
|
dict[str, Any] | None
|
Dictionary mapping Hugging Face configuration keys to override values. |
None
|
pooler_config
|
PoolerConfig | None
|
Controls the behavior of output pooling in pooling models. |
None
|
enforce_eager
|
bool
|
Whether to disable CUDA graph optimization and use eager execution. |
False
|
**kwargs
|
Any
|
Additional arguments to pass to the vLLM serving engine model. |
{}
|
Source code in mteb/models/vllm_wrapper.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
cleanup()
¶
Clean up the VLLM distributed runtime environment and release GPU resources.
Source code in mteb/models/vllm_wrapper.py
145 146 147 148 149 150 151 152 153 154 155 156 157 | |
vLLM Engine Arguments
For all vLLM engine parameters, please refer to: https://docs.vllm.ai/en/latest/configuration/engine_args/.
mteb.models.vllm_wrapper.VllmEncoderWrapper
¶
Bases: AbsEncoder, VllmWrapperBase
vLLM wrapper for Encoder models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | ModelMeta
|
model name string or ModelMeta. |
required |
revision
|
str | None
|
The revision of the model to use. |
None
|
prompt_dict
|
dict[str, str] | None
|
A dictionary mapping task names to prompt strings. |
None
|
use_instructions
|
bool
|
Whether to use instructions from the prompt_dict. When False, values from prompt_dict are used as static prompts (prefixes). When True, values from prompt_dict are used as instructions to be formatted using the instruction_template. |
False
|
instruction_template
|
str | Callable[[str, PromptType | None], str] | None
|
A template or callable to format instructions. Can be a string with '{instruction}' placeholder or a callable that takes the instruction and prompt type and returns a formatted string. |
None
|
apply_instruction_to_documents
|
bool
|
Whether to apply instructions to documents prompts. |
True
|
**kwargs
|
Any
|
Additional arguments to pass to the vLLM serving engine model. |
{}
|
Source code in mteb/models/vllm_wrapper.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | |
encode(inputs, *, task_metadata, hf_split, hf_subset, prompt_type=None, **kwargs)
¶
Encodes the given sentences using the encoder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
DataLoader[BatchedInput]
|
The sentences to encode. |
required |
task_metadata
|
TaskMetadata
|
The metadata of the task. Sentence-transformers uses this to determine which prompt to use from a specified dictionary. |
required |
prompt_type
|
PromptType | None
|
The name type of prompt. (query or passage) |
None
|
hf_split
|
str
|
Split of current task |
required |
hf_subset
|
str
|
Subset of current task |
required |
**kwargs
|
Any
|
Additional arguments to pass to the encoder. |
{}
|
Returns:
| Type | Description |
|---|---|
Array
|
The encoded sentences. |
Source code in mteb/models/vllm_wrapper.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | |
mteb.models.vllm_wrapper.VllmCrossEncoderWrapper
¶
Bases: VllmWrapperBase
vLLM wrapper for CrossEncoder models.
Source code in mteb/models/vllm_wrapper.py
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |
predict(inputs1, inputs2, *, task_metadata, hf_split, hf_subset, prompt_type=None, **kwargs)
¶
Predicts relevance scores for pairs of inputs. Note that, unlike the encoder, the cross-encoder can compare across inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs1
|
DataLoader[BatchedInput]
|
First Dataloader of inputs to encode. For reranking tasks, these are queries (for text only tasks |
required |
inputs2
|
DataLoader[BatchedInput]
|
Second Dataloader of inputs to encode. For reranking, these are documents (for text only tasks |
required |
task_metadata
|
TaskMetadata
|
Metadata of the current task. |
required |
hf_split
|
str
|
Split of current task, allows to know some additional information about current split. E.g. Current language |
required |
hf_subset
|
str
|
Subset of current task. Similar to |
required |
prompt_type
|
PromptType | None
|
The name type of prompt. (query or passage) |
None
|
**kwargs
|
Any
|
Additional arguments to pass to the cross-encoder. |
{}
|
Returns:
| Type | Description |
|---|---|
Array
|
The predicted relevance scores for each inputs pair. |
Source code in mteb/models/vllm_wrapper.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |