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 have to wrap the model with its respective wrapper.
Note
you must update your Python code to guard usage of vllm behind a if name == 'main': block. For example, instead of this:
import vllm
llm = vllm.LLM(...)
if __name__ == '__main__':
import vllm
llm = vllm.LLM(...)
See more troubleshooting
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 but not float32. vLLM does not optimize inference performance for float32.
Note
| Format | Bits | Exponent | Fraction |
|---|---|---|---|
| float32 | 32 | 8 | 23 |
| float16 | 16 | 5 | 10 |
| bfloat16 | 16 | 8 | 7 |
If the model weights are stored in float32:
- VLLM uses float16 for inference by default to inference a float32 model, it will keep numerical precision in most cases, for it have retains relatively more Fraction bits. However, due to the smaller Exponent part (only 5 bits), some models (e.g., the Gemma family) may risk producing NaN. VLLM maintains a list models that may cause NaN values and uses bfloat16 for inference by default.
- Using bfloat16 for inference avoids NaN risks because its Exponent part matches float32 with 8 bits. However, with only 7 Fraction bits, numerical precision decreases noticeably.
- Using float32 for inference incurs no precision loss but is about four times slower than float16/bfloat16.
If model weights are stored in float16 or bfloat16, vLLM defaults to using the original dtype for inference.
Quantization: With the advancement of open-source large models, fine-tuning of larger models for tasks like embedding and reranking is increasing. Exploring quantization methods to accelerate inference and reduce GPU memory usage may become necessary.
Unpadding¶
By default, Sentence Transformers (st) pads all inputs in a batch to the length of the longest one, which is undoubtedly very inefficient. VLLM avoids padding entirely during inference.
Sentence Transformers (st) suffers a noticeable drop in speed when handling requests with varied input lengths, whereas vLLM does not.
Others¶
For models using bidirectional attention, such as BERT, VLLM offers a range of performance optimizations:
- Optimized CUDA kernels, including FlashAttention and FlashInfer integration
- 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, and FP8—for efficient deployment
- Continuous batching of incoming requests to maximize throughput
For causal attention models, such as the Qwen3 reranker, the following optimizations are also applicable:
- 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 optimizations are primarily designed for and most effective with causal language models (generative models). For the full list of features, refer to the vllm documentation.
API Reference¶
mteb.models.vllm_wrapper.VllmWrapperBase
¶
Wrapper for vllm serving engine.
Source code in mteb/models/vllm_wrapper.py
32 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 | |
__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, 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 string. |
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 does not support fp32. Therefore, it defaults to using fp16 for inference on fp32 models. Testing has shown a relatively small drop in accuracy. You can manually opt for fp32, but inference speed will be very slow. |
'auto'
|
head_dtype
|
Literal['model'] | Dtype | None
|
"head" refers to the last Linear layer(s) of an LLMs, such as the score or classifier in a classification model. Uses fp32 for the head by default to gain extra precision. |
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
|
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
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 | |
cleanup()
¶
Clean up the VLLM distributed runtime environment and release GPU resources.
Source code in mteb/models/vllm_wrapper.py
137 138 139 140 141 142 143 144 145 146 147 148 | |
Info
For all vLLM 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
157 158 159 160 161 162 163 164 165 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 | |
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
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 | |
mteb.models.vllm_wrapper.VllmCrossEncoderWrapper
¶
Bases: VllmWrapperBase
vLLM wrapper for CrossEncoder models.
Source code in mteb/models/vllm_wrapper.py
267 268 269 270 271 272 273 274 275 276 277 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 | |
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
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 | |