OpenAI 兼容服务器#
vLLM 提供了一个 HTTP 服务器,实现了 OpenAI 的 Completions API、Chat API 以及更多功能!
您可以通过 vllm serve
命令或通过 Docker 启动服务器
vllm serve NousResearch/Meta-Llama-3-8B-Instruct --dtype auto --api-key token-abc123
要调用服务器,您可以使用 官方 OpenAI Python 客户端,或任何其他 HTTP 客户端。
from openai import OpenAI
client = OpenAI(
base_url="https://127.0.0.1:8000/v1",
api_key="token-abc123",
)
completion = client.chat.completions.create(
model="NousResearch/Meta-Llama-3-8B-Instruct",
messages=[
{"role": "user", "content": "Hello!"}
]
)
print(completion.choices[0].message)
提示
vLLM 支持一些 OpenAI 不支持的参数,例如 top_k
。您可以使用 OpenAI 客户端在请求的 extra_body
参数中将这些参数传递给 vLLM,例如 extra_body={"top_k": 50}
代表 top_k
。
重要提示
默认情况下,如果 Hugging Face 模型仓库中存在 generation_config.json
,服务器将应用它。这意味着某些采样参数的默认值可能会被模型创建者推荐的值覆盖。
要禁用此行为,请在启动服务器时传递 --generation-config vllm
。
支持的 API#
我们目前支持以下 OpenAI API
Completions API (
/v1/completions
)仅适用于 文本生成模型 (
--task generate
)。注意:不支持
suffix
参数。
Chat Completions API (
/v1/chat/completions
)Embeddings API (
/v1/embeddings
)仅适用于 嵌入模型 (
--task embed
)。
Transcriptions API (
/v1/audio/transcriptions
)仅适用于自动语音识别 (ASR) 模型 (OpenAI Whisper) (
--task generate
)。
此外,我们还提供以下自定义 API
Tokenizer API (
/tokenize
,/detokenize
)适用于任何带有分词器的模型。
Pooling API (
/pooling
)适用于所有 池化模型。
Score API (
/score
)适用于嵌入模型和 交叉编码器模型 (
--task score
)。
Re-rank API (
/rerank
,/v1/rerank
,/v2/rerank
)Jina 和 Cohere 的 API 非常相似;Jina 的 API 在重新排序端点的响应中包含额外信息。
仅适用于 交叉编码器模型 (
--task score
)。
聊天模板#
为了使语言模型支持聊天协议,vLLM 要求模型在其分词器配置中包含聊天模板。聊天模板是一个 Jinja2 模板,用于指定角色、消息和其他聊天特定 token 如何在输入中编码。
有关 NousResearch/Meta-Llama-3-8B-Instruct
的聊天模板示例,请参见 此处
某些模型即使经过指令/聊天微调,也不提供聊天模板。对于这些模型,您可以使用 --chat-template
参数手动指定其聊天模板,参数值为聊天模板的文件路径或字符串形式的模板。如果没有聊天模板,服务器将无法处理聊天,所有聊天请求都会出错。
vllm serve <model> --chat-template ./path-to-chat-template.jinja
vLLM 社区为流行的模型提供了一组聊天模板。您可以在 examples 目录下找到它们。
随着多模态聊天 API 的加入,OpenAI 规范现在接受一种新的聊天消息格式,该格式同时指定了 type
和 text
字段。下面提供了一个示例
completion = client.chat.completions.create(
model="NousResearch/Meta-Llama-3-8B-Instruct",
messages=[
{"role": "user", "content": [{"type": "text", "text": "Classify this sentiment: vLLM is wonderful!"}]}
]
)
大多数 LLM 的聊天模板都期望 content
字段为字符串,但也有一些较新的模型(如 meta-llama/Llama-Guard-3-1B
)期望内容根据请求中的 OpenAI 模式进行格式化。vLLM 尽最大努力自动检测这一点,检测结果将记录为类似 *“Detected the chat template content format to be…”* 的字符串,并在内部转换传入的请求以匹配检测到的格式,格式可以是以下之一
"string"
:一个字符串。示例:
"Hello world"
"openai"
:字典列表,类似于 OpenAI 模式。示例:
[{"type": "text", "text": "Hello world!"}]
如果结果与您期望的不符,您可以设置 --chat-template-content-format
CLI 参数来覆盖要使用的格式。
额外参数#
vLLM 支持一组不属于 OpenAI API 的参数。为了使用它们,您可以将它们作为额外参数在 OpenAI 客户端中传递。或者,如果您直接使用 HTTP 调用,则可以直接将它们合并到 JSON 有效负载中。
completion = client.chat.completions.create(
model="NousResearch/Meta-Llama-3-8B-Instruct",
messages=[
{"role": "user", "content": "Classify this sentiment: vLLM is wonderful!"}
],
extra_body={
"guided_choice": ["positive", "negative"]
}
)
额外 HTTP 标头#
目前仅支持 X-Request-Id
HTTP 请求标头。可以使用 --enable-request-id-headers
启用它。
请注意,在高 QPS 速率下启用标头可能会显着影响性能。因此,我们建议在路由器级别(例如,通过 Istio)而不是在 vLLM 层内实现 HTTP 标头。有关更多详细信息,请参阅 此 PR。
completion = client.chat.completions.create(
model="NousResearch/Meta-Llama-3-8B-Instruct",
messages=[
{"role": "user", "content": "Classify this sentiment: vLLM is wonderful!"}
],
extra_headers={
"x-request-id": "sentiment-classification-00001",
}
)
print(completion._request_id)
completion = client.completions.create(
model="NousResearch/Meta-Llama-3-8B-Instruct",
prompt="A robot may not injure a human being",
extra_headers={
"x-request-id": "completion-test",
}
)
print(completion._request_id)
CLI 参考#
vllm serve
#
vllm serve
命令用于启动 OpenAI 兼容服务器。
usage: vllm serve [-h] [--host HOST] [--port PORT]
[--uvicorn-log-level {debug,info,warning,error,critical,trace}]
[--disable-uvicorn-access-log] [--allow-credentials]
[--allowed-origins ALLOWED_ORIGINS]
[--allowed-methods ALLOWED_METHODS]
[--allowed-headers ALLOWED_HEADERS] [--api-key API_KEY]
[--lora-modules LORA_MODULES [LORA_MODULES ...]]
[--prompt-adapters PROMPT_ADAPTERS [PROMPT_ADAPTERS ...]]
[--chat-template CHAT_TEMPLATE]
[--chat-template-content-format {auto,string,openai}]
[--response-role RESPONSE_ROLE] [--ssl-keyfile SSL_KEYFILE]
[--ssl-certfile SSL_CERTFILE] [--ssl-ca-certs SSL_CA_CERTS]
[--enable-ssl-refresh] [--ssl-cert-reqs SSL_CERT_REQS]
[--root-path ROOT_PATH] [--middleware MIDDLEWARE]
[--return-tokens-as-token-ids]
[--disable-frontend-multiprocessing]
[--enable-request-id-headers] [--enable-auto-tool-choice]
[--tool-call-parser {granite-20b-fc,granite,hermes,internlm,jamba,llama3_json,mistral,phi4_mini_json,pythonic} or name registered in --tool-parser-plugin]
[--tool-parser-plugin TOOL_PARSER_PLUGIN] [--model MODEL]
[--task {auto,generate,embedding,embed,classify,score,reward,transcription}]
[--tokenizer TOKENIZER] [--hf-config-path HF_CONFIG_PATH]
[--skip-tokenizer-init] [--revision REVISION]
[--code-revision CODE_REVISION]
[--tokenizer-revision TOKENIZER_REVISION]
[--tokenizer-mode {auto,slow,mistral,custom}]
[--trust-remote-code]
[--allowed-local-media-path ALLOWED_LOCAL_MEDIA_PATH]
[--download-dir DOWNLOAD_DIR]
[--load-format {auto,pt,safetensors,npcache,dummy,tensorizer,sharded_state,gguf,bitsandbytes,mistral,runai_streamer,fastsafetensors}]
[--config-format {auto,hf,mistral}]
[--dtype {auto,half,float16,bfloat16,float,float32}]
[--kv-cache-dtype {auto,fp8,fp8_e5m2,fp8_e4m3}]
[--max-model-len MAX_MODEL_LEN]
[--guided-decoding-backend GUIDED_DECODING_BACKEND]
[--logits-processor-pattern LOGITS_PROCESSOR_PATTERN]
[--model-impl {auto,vllm,transformers}]
[--distributed-executor-backend {ray,mp,uni,external_launcher}]
[--pipeline-parallel-size PIPELINE_PARALLEL_SIZE]
[--tensor-parallel-size TENSOR_PARALLEL_SIZE]
[--data-parallel-size DATA_PARALLEL_SIZE]
[--enable-expert-parallel]
[--max-parallel-loading-workers MAX_PARALLEL_LOADING_WORKERS]
[--ray-workers-use-nsight] [--block-size {8,16,32,64,128}]
[--enable-prefix-caching | --no-enable-prefix-caching]
[--prefix-caching-hash-algo {builtin,sha256}]
[--disable-sliding-window] [--use-v2-block-manager]
[--num-lookahead-slots NUM_LOOKAHEAD_SLOTS] [--seed SEED]
[--swap-space SWAP_SPACE] [--cpu-offload-gb CPU_OFFLOAD_GB]
[--gpu-memory-utilization GPU_MEMORY_UTILIZATION]
[--num-gpu-blocks-override NUM_GPU_BLOCKS_OVERRIDE]
[--max-num-batched-tokens MAX_NUM_BATCHED_TOKENS]
[--max-num-partial-prefills MAX_NUM_PARTIAL_PREFILLS]
[--max-long-partial-prefills MAX_LONG_PARTIAL_PREFILLS]
[--long-prefill-token-threshold LONG_PREFILL_TOKEN_THRESHOLD]
[--max-num-seqs MAX_NUM_SEQS] [--max-logprobs MAX_LOGPROBS]
[--disable-log-stats]
[--quantization {aqlm,awq,deepspeedfp,tpu_int8,fp8,ptpc_fp8,fbgemm_fp8,modelopt,nvfp4,marlin,gguf,gptq_marlin_24,gptq_marlin,awq_marlin,gptq,compressed-tensors,bitsandbytes,qqq,hqq,experts_int8,neuron_quant,ipex,quark,moe_wna16,torchao,None}]
[--rope-scaling ROPE_SCALING] [--rope-theta ROPE_THETA]
[--hf-token [HF_TOKEN]] [--hf-overrides HF_OVERRIDES]
[--enforce-eager]
[--max-seq-len-to-capture MAX_SEQ_LEN_TO_CAPTURE]
[--disable-custom-all-reduce]
[--tokenizer-pool-size TOKENIZER_POOL_SIZE]
[--tokenizer-pool-type TOKENIZER_POOL_TYPE]
[--tokenizer-pool-extra-config TOKENIZER_POOL_EXTRA_CONFIG]
[--limit-mm-per-prompt LIMIT_MM_PER_PROMPT]
[--mm-processor-kwargs MM_PROCESSOR_KWARGS]
[--disable-mm-preprocessor-cache] [--enable-lora]
[--enable-lora-bias] [--max-loras MAX_LORAS]
[--max-lora-rank MAX_LORA_RANK]
[--lora-extra-vocab-size LORA_EXTRA_VOCAB_SIZE]
[--lora-dtype {auto,float16,bfloat16}]
[--long-lora-scaling-factors LONG_LORA_SCALING_FACTORS]
[--max-cpu-loras MAX_CPU_LORAS] [--fully-sharded-loras]
[--enable-prompt-adapter]
[--max-prompt-adapters MAX_PROMPT_ADAPTERS]
[--max-prompt-adapter-token MAX_PROMPT_ADAPTER_TOKEN]
[--device {auto,cuda,neuron,cpu,tpu,xpu,hpu}]
[--num-scheduler-steps NUM_SCHEDULER_STEPS]
[--use-tqdm-on-load | --no-use-tqdm-on-load]
[--multi-step-stream-outputs [MULTI_STEP_STREAM_OUTPUTS]]
[--scheduler-delay-factor SCHEDULER_DELAY_FACTOR]
[--enable-chunked-prefill [ENABLE_CHUNKED_PREFILL]]
[--speculative-config SPECULATIVE_CONFIG]
[--model-loader-extra-config MODEL_LOADER_EXTRA_CONFIG]
[--ignore-patterns IGNORE_PATTERNS]
[--preemption-mode PREEMPTION_MODE]
[--served-model-name SERVED_MODEL_NAME [SERVED_MODEL_NAME ...]]
[--qlora-adapter-name-or-path QLORA_ADAPTER_NAME_OR_PATH]
[--show-hidden-metrics-for-version SHOW_HIDDEN_METRICS_FOR_VERSION]
[--otlp-traces-endpoint OTLP_TRACES_ENDPOINT]
[--collect-detailed-traces COLLECT_DETAILED_TRACES]
[--disable-async-output-proc]
[--scheduling-policy {fcfs,priority}]
[--scheduler-cls SCHEDULER_CLS]
[--override-neuron-config OVERRIDE_NEURON_CONFIG]
[--override-pooler-config OVERRIDE_POOLER_CONFIG]
[--compilation-config COMPILATION_CONFIG]
[--kv-transfer-config KV_TRANSFER_CONFIG]
[--worker-cls WORKER_CLS]
[--worker-extension-cls WORKER_EXTENSION_CLS]
[--generation-config GENERATION_CONFIG]
[--override-generation-config OVERRIDE_GENERATION_CONFIG]
[--enable-sleep-mode] [--calculate-kv-scales]
[--additional-config ADDITIONAL_CONFIG] [--enable-reasoning]
[--reasoning-parser {deepseek_r1,granite}]
[--disable-cascade-attn]
[--disable-chunked-mm-input [DISABLE_CHUNKED_MM_INPUT]]
[--disable-log-requests] [--max-log-len MAX_LOG_LEN]
[--disable-fastapi-docs] [--enable-prompt-tokens-details]
[--enable-server-load-tracking]
命名参数#
- --host
主机名。
- --port
端口号。
默认值:8000
- --uvicorn-log-level
可能选项:debug, info, warning, error, critical, trace
uvicorn 的日志级别。
默认值:“info”
- --disable-uvicorn-access-log
禁用 uvicorn 访问日志。
默认值:False
- --allow-credentials
允许凭据。
默认值:False
- --allowed-origins
允许的来源。
默认值:[‘*’]
- --allowed-methods
允许的方法。
默认值:[‘*’]
- --allowed-headers
允许的标头。
默认值:[‘*’]
- --api-key
如果提供,服务器将要求在标头中提供此密钥。
- --lora-modules
LoRA 模块配置,格式为 ‘name=path’ 或 JSON 格式。示例(旧格式):
'name=path'
示例(新格式):{"name": "name", "path": "lora_path", "base_model_name": "id"}
- --prompt-adapters
提示适配器配置,格式为 name=path。可以指定多个适配器。
- --chat-template
指定模型的聊天模板文件路径或单行形式的模板。
- --chat-template-content-format
可能选项:auto, string, openai
在聊天模板中渲染消息内容的格式。
“string” 将内容渲染为字符串。示例:
"Hello World"
“openai” 将内容渲染为字典列表,类似于 OpenAI 模式。示例:
[{"type": "text", "text": "Hello world!"}]
默认值:“auto”
- --response-role
如果
request.add_generation_prompt=true
,则返回的角色名称。默认值:assistant
- --ssl-keyfile
SSL 密钥文件的文件路径。
- --ssl-certfile
SSL 证书文件的文件路径。
- --ssl-ca-certs
CA 证书文件。
- --enable-ssl-refresh
当 SSL 证书文件更改时刷新 SSL 上下文
默认值:False
- --ssl-cert-reqs
是否需要客户端证书(请参阅 stdlib ssl 模块)。
默认值:0
- --root-path
当应用程序位于基于路径的路由代理之后时,FastAPI root_path。
- --middleware
要应用于应用程序的其他 ASGI 中间件。我们接受多个 --middleware 参数。该值应为导入路径。如果提供了函数,vLLM 将使用
@app.middleware('http')
将其添加到服务器。如果提供了类,vLLM 将使用app.add_middleware()
将其添加到服务器。默认值:[]
- --return-tokens-as-token-ids
当指定
--max-logprobs
时,将单个 token 表示为 ‘token_id:{token_id}’ 形式的字符串,以便可以识别不可 JSON 编码的 token。默认值:False
- --disable-frontend-multiprocessing
如果指定,将在与模型服务引擎相同的进程中运行 OpenAI 前端服务器。
默认值:False
- --enable-request-id-headers
如果指定,API 服务器将在响应中添加 X-Request-Id 标头。注意:在高 QPS 下,这会降低性能。
默认值:False
- --enable-auto-tool-choice
为支持的模型启用自动工具选择。使用
--tool-call-parser
指定要使用的解析器。默认值:False
- --tool-call-parser
根据您使用的模型选择工具调用解析器。这用于将模型生成的工具调用解析为 OpenAI API 格式。
--enable-auto-tool-choice
需要此参数。- --tool-parser-plugin
指定工具解析器插件,用于将模型生成的工具解析为 OpenAI API 格式,在此插件中注册的名称可在
--tool-call-parser
中使用。默认值:“”
- --model
要使用的 huggingface 模型的名称或路径。
默认值:“facebook/opt-125m”
- --task
可能选项:auto, generate, embedding, embed, classify, score, reward, transcription
模型要执行的任务。即使同一个模型可以用于多个任务,每个 vLLM 实例也仅支持一个任务。当模型仅支持一个任务时,可以使用
"auto"
选择它;否则,您必须明确指定要使用的任务。默认值:“auto”
- --tokenizer
要使用的 huggingface 分词器的名称或路径。如果未指定,将使用模型名称或路径。
- --hf-config-path
要使用的 huggingface 配置的名称或路径。如果未指定,将使用模型名称或路径。
- --skip-tokenizer-init
跳过分词器和反分词器的初始化。期望输入中提供有效的 prompt_token_ids,并且 prompt 为 None。生成的输出将包含 token ID。
默认值:False
- --revision
要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID。如果未指定,将使用默认版本。
- --code-revision
用于 Hugging Face Hub 上模型代码的特定修订版本。它可以是分支名称、标签名称或提交 ID。如果未指定,将使用默认版本。
- --tokenizer-revision
要使用的 huggingface 分词器的修订版本。它可以是分支名称、标签名称或提交 ID。如果未指定,将使用默认版本。
- --tokenizer-mode
可能选项:auto, slow, mistral, custom
分词器模式。
“auto” 将在可用时使用快速分词器。
“slow” 将始终使用慢速分词器。
“mistral” 将始终使用 mistral_common 分词器。
“custom” 将使用 –tokenizer 选择预注册的分词器。
默认值:“auto”
- --trust-remote-code
信任来自 huggingface 的远程代码。
默认值:False
- --allowed-local-media-path
允许 API 请求从服务器文件系统指定的目录读取本地图像或视频。这是一个安全风险。仅应在受信任的环境中启用。
- --download-dir
下载和加载权重的目录。
- --load-format
可能选项:auto, pt, safetensors, npcache, dummy, tensorizer, sharded_state, gguf, bitsandbytes, mistral, runai_streamer, fastsafetensors
要加载的模型权重的格式。
“auto” 将尝试加载 safetensors 格式的权重,如果 safetensors 格式不可用,则回退到 pytorch bin 格式。
“pt” 将加载 pytorch bin 格式的权重。
“safetensors” 将加载 safetensors 格式的权重。
“npcache” 将加载 pytorch 格式的权重,并存储 numpy 缓存以加速加载。
“dummy” 将使用随机值初始化权重,主要用于性能分析。
“tensorizer” 将使用 CoreWeave 的 tensorizer 加载权重。有关更多信息,请参阅“示例”部分中的“张量化 vLLM 模型”脚本。
“runai_streamer” 将使用 Run:ai Model Streamer 加载 Safetensors 权重。
“bitsandbytes” 将使用 bitsandbytes 量化加载权重。
“sharded_state” 将从预分片检查点文件加载权重,支持高效加载张量并行模型
“gguf” 将从 GGUF 格式文件加载权重(详细信息请参阅 ggml-org/ggml)。
“mistral” 将从 Mistral 模型使用的合并 safetensors 文件加载权重。
默认值:“auto”
- --config-format
可能选项:auto, hf, mistral
要加载的模型配置的格式。
“auto” 将尝试加载 hf 格式的配置,如果不可用,则尝试加载 mistral 格式
默认值:“ConfigFormat.AUTO”
- --dtype
可能选项:auto, half, float16, bfloat16, float, float32
模型权重和激活的数据类型。
“auto” 将对 FP32 和 FP16 模型使用 FP16 精度,对 BF16 模型使用 BF16 精度。
“half” 表示 FP16。推荐用于 AWQ 量化。
“float16” 与 “half” 相同。
“bfloat16” 在精度和范围之间取得平衡。
“float” 是 FP32 精度的简写。
“float32” 表示 FP32 精度。
默认值:“auto”
- --kv-cache-dtype
可能选项:auto, fp8, fp8_e5m2, fp8_e4m3
kv 缓存存储的数据类型。如果为 “auto”,将使用模型数据类型。CUDA 11.8+ 支持 fp8 (=fp8_e4m3) 和 fp8_e5m2。ROCm (AMD GPU) 支持 fp8 (=fp8_e4m3)
默认值:“auto”
- --max-model-len
模型上下文长度。如果未指定,将自动从模型配置中派生。支持 k/m/g/K/M/G 人类可读格式。示例:- 1k → 1000 - 1K → 1024
- --guided-decoding-backend
默认情况下,哪个引擎将用于引导解码(JSON 模式/正则表达式等)。当前支持 mlc-ai/xgrammar 和 guidance-ai/llguidance.Valid。有效的后端值包括 “xgrammar”、“guidance” 和 “auto”。使用 “auto” 时,我们将根据请求内容和后端库当前支持的内容做出有主见的决定,因此行为可能会在每个版本中更改。
默认值:“xgrammar”
- --logits-processor-pattern
可选的正则表达式模式,用于指定可以使用 logits_processors 额外完成参数传递的有效 logits 处理器限定名称。默认为 None,表示不允许任何处理器。
- --model-impl
可能选项:auto, vllm, transformers
要使用的模型实现。
“auto” 将尝试使用 vLLM 实现(如果存在),如果 vLLM 实现不可用,则回退到 Transformers 实现。
“vllm” 将使用 vLLM 模型实现。
“transformers” 将使用 Transformers 模型实现。
默认值:“auto”
- --distributed-executor-backend
可能选项:ray, mp, uni, external_launcher
用于分布式模型工作程序的后端,可以是 “ray” 或 “mp”(多进程)。如果 pipeline_parallel_size 和 tensor_parallel_size 的乘积小于或等于可用 GPU 的数量,“mp” 将用于保持在单个主机上处理。否则,如果安装了 Ray,则默认为 “ray”,否则将失败。请注意,tpu 仅支持 Ray 进行分布式推理。
- --pipeline-parallel-size, -pp
流水线并行阶段数。
默认值:1
- --tensor-parallel-size, -tp
张量并行副本数。
默认值:1
- --data-parallel-size, -dp
数据并行副本数。MoE 层将根据 tensor-parallel-size 和 data-parallel-size 的乘积进行分片。
默认值:1
- --enable-expert-parallel
对 MoE 层使用专家并行而不是张量并行。
默认值:False
- --max-parallel-loading-workers
在多个批次中顺序加载模型,以避免在使用张量并行和大型模型时出现 RAM OOM。
- --ray-workers-use-nsight
如果指定,则使用 nsight 分析 Ray 工作程序。
默认值:False
- --block-size
可能选项:8, 16, 32, 64, 128
token 块大小,用于 token 的连续块。在 neuron 设备上将被忽略,并设置为
--max-model-len
。在 CUDA 设备上,仅支持最大为 32 的块大小。在 HPU 设备上,块大小默认为 128。- --enable-prefix-caching, --no-enable-prefix-caching
启用自动前缀缓存。使用
--no-enable-prefix-caching
显式禁用。- --prefix-caching-hash-algo
可能选项:builtin, sha256
设置前缀缓存的哈希算法。选项包括 ‘builtin’(Python 的内置哈希)或 ‘sha256’(抗冲突但具有一定开销)。
默认值:“builtin”
- --disable-sliding-window
禁用滑动窗口,限制为滑动窗口大小。
默认值:False
- --use-v2-block-manager
[已弃用] 块管理器 v1 已被删除,SelfAttnBlockSpaceManager(即块管理器 v2)现在是默认设置。将此标志设置为 True 或 False 对 vLLM 行为没有影响。
默认值:True
- --num-lookahead-slots
推测解码所需的实验性调度配置。这将在未来被推测配置取代;它目前的存在是为了启用正确性测试。
默认值:0
- --seed
操作的随机种子。
- --swap-space
每个 GPU 的 CPU 交换空间大小 (GiB)。
默认值:4
- --cpu-offload-gb
每个 GPU 要卸载到 CPU 的空间,以 GiB 为单位。默认值为 0,表示不卸载。直观地看,此参数可以看作是增加 GPU 内存大小的虚拟方法。例如,如果您有一个 24 GB GPU 并将其设置为 10,则实际上可以将其视为 34 GB GPU。然后,您可以加载一个 13B 模型和 BF16 权重,这至少需要 26GB GPU 内存。请注意,这需要快速的 CPU-GPU 互连,因为模型的一部分在每次模型前向传递中都会从 CPU 内存动态加载到 GPU 内存。
默认值:0
- --gpu-memory-utilization
用于模型执行器的 GPU 内存的比例,范围为 0 到 1。例如,值为 0.5 表示 50% 的 GPU 内存利用率。如果未指定,将使用默认值 0.9。这是一个按实例限制,仅适用于当前的 vLLM 实例。如果您在同一 GPU 上运行另一个 vLLM 实例,则无关紧要。例如,如果您在同一 GPU 上运行两个 vLLM 实例,则可以将每个实例的 GPU 内存利用率设置为 0.5。
默认值:0.9
- --num-gpu-blocks-override
如果指定,则忽略 GPU 性能分析结果,并使用此 GPU 块数。用于测试抢占。
- --max-num-batched-tokens
每次迭代的最大批处理 token 数。
- --max-num-partial-prefills
对于分块预填充,最大并发部分预填充数。
默认值:1
- --max-long-partial-prefills
对于分块预填充,将并发预填充的最大提示数(提示长度超过 –long-prefill-token-threshold)。将此值设置得小于 –max-num-partial-prefills 将允许较短的提示在某些情况下跳过较长提示的队列,从而提高延迟。
默认值:1
- --long-prefill-token-threshold
对于分块预填充,如果提示长度超过此 token 数,则该请求被认为是长的。
默认值:0
- --max-num-seqs
每次迭代的最大序列数。
- --max-logprobs
要返回的最大对数概率数,logprobs 在 SamplingParams 中指定。
默认值:20
- --disable-log-stats
禁用日志统计信息。
默认值:False
- --quantization, -q
可选选项:aqlm, awq, deepspeedfp, tpu_int8, fp8, ptpc_fp8, fbgemm_fp8, modelopt, nvfp4, marlin, gguf, gptq_marlin_24, gptq_marlin, awq_marlin, gptq, compressed-tensors, bitsandbytes, qqq, hqq, experts_int8, neuron_quant, ipex, quark, moe_wna16, torchao, None
用于量化权重的技术。如果为 None,我们首先检查模型配置文件中的 quantization_config 属性。如果该属性也为 None,我们则假定模型权重未被量化,并使用 dtype 来确定权重的data type(数据类型)。
- --rope-scaling
RoPE scaling(RoPE 缩放)配置,JSON 格式。例如:
{"rope_type":"dynamic","factor":2.0}
- --rope-theta
RoPE theta。与 rope_scaling 配合使用。在某些情况下,更改 RoPE theta 可以提高缩放模型的性能。
- --hf-token
用作远程文件 HTTP bearer authorization(持有者授权)的token(令牌)。如果为 True,将使用运行 huggingface-cli login 时生成的token(存储在 ~/.huggingface 中)。
- --hf-overrides
HuggingFace 配置的额外参数。这应该是一个 JSON 字符串,将被解析为一个字典。
- --enforce-eager
始终使用 eager-mode(eager 模式) PyTorch。如果为 False,将结合使用 eager mode 和 CUDA graph(CUDA 图)以获得最大的性能和灵活性。
默认值:False
- --max-seq-len-to-capture
CUDA graphs(CUDA 图)覆盖的最大序列长度。当序列的上下文长度大于此值时,我们将回退到 eager mode(eager 模式)。此外,对于 encoder-decoder(编码器-解码器)模型,如果 encoder input(编码器输入)的序列长度大于此值,我们也将回退到 eager mode(eager 模式)。
默认值:8192
- --disable-custom-all-reduce
请参阅 ParallelConfig。
默认值:False
- --tokenizer-pool-size
用于异步 tokenization(分词)的 tokenizer pool(分词器池)的大小。如果为 0,将使用同步 tokenization(分词)。
默认值:0
- --tokenizer-pool-type
用于异步 tokenization(分词)的 tokenizer pool(分词器池)的类型。如果 tokenizer_pool_size 为 0,则忽略此项。
默认值:“ray”
- --tokenizer-pool-extra-config
tokenizer pool(分词器池)的额外配置。这应该是一个 JSON 字符串,将被解析为一个字典。如果 tokenizer_pool_size 为 0,则忽略此项。
- --limit-mm-per-prompt
对于每个 multimodal plugin(多模态插件),限制每个 prompt(提示)允许的输入实例数量。期望一个逗号分隔的项目列表,例如:image=16,video=2 允许每个 prompt(提示)最多 16 张图像和 2 个视频。默认为每种模态 1。
- --mm-processor-kwargs
多模态输入映射/处理的覆盖设置,例如,图像处理器。例如:
{"num_crops": 4}
。- --disable-mm-preprocessor-cache
如果为 true,则禁用 multi-modal preprocessor/mapper(多模态预处理器/映射器)的缓存。(不推荐)
默认值:False
- --enable-lora
如果为 True,启用 LoRA adapters(LoRA 适配器)的处理。
默认值:False
- --enable-lora-bias
如果为 True,为 LoRA adapters(LoRA 适配器)启用 bias(偏置)。
默认值:False
- --max-loras
单个 batch(批次)中 LoRA 的最大数量。
默认值:1
- --max-lora-rank
LoRA rank(LoRA 秩)的最大值。
默认值:16
- --lora-extra-vocab-size
LoRA adapter(LoRA 适配器)中可能存在的额外 vocabulary(词汇表)的最大大小(添加到基础模型 vocabulary(词汇表))。
默认值:256
- --lora-dtype
可选选项:auto, float16, bfloat16
LoRA 的data type(数据类型)。如果为 auto,将默认为基础模型 dtype。
默认值:“auto”
- --long-lora-scaling-factors
指定多个 scaling factors(缩放因子)(可以与基础模型 scaling factor 不同 - 请参阅例如 Long LoRA),以允许同时使用使用这些 scaling factors 训练的多个 LoRA adapters(LoRA 适配器)。如果未指定,则仅允许使用使用基础模型 scaling factor 训练的 adapters(适配器)。
- --max-cpu-loras
存储在 CPU 内存中的 LoRA 的最大数量。必须 >= max_loras。
- --fully-sharded-loras
默认情况下,只有一半的 LoRA 计算通过 tensor parallelism(张量并行)进行分片。启用此选项将使用 fully sharded layers(完全分片层)。在高序列长度、最大 rank(秩)或 tensor parallel size(张量并行大小)下,这可能更快。
默认值:False
- --enable-prompt-adapter
如果为 True,启用 PromptAdapters(Prompt 适配器)的处理。
默认值:False
- --max-prompt-adapters
一个 batch(批次)中 PromptAdapters(Prompt 适配器)的最大数量。
默认值:1
- --max-prompt-adapter-token
PromptAdapters tokens(Prompt 适配器令牌)的最大数量
默认值:0
- --device
可选选项:auto, cuda, neuron, cpu, tpu, xpu, hpu
vLLM 执行的 device type(设备类型)。
默认值:“auto”
- --num-scheduler-steps
每个 scheduler call(调度器调用)的最大 forward steps(前向步骤)数。
默认值:1
- --use-tqdm-on-load, --no-use-tqdm-on-load
加载模型权重时是否启用/禁用进度条。
默认值:True
- --multi-step-stream-outputs
如果为 False,则 multi-step(多步)将在所有步骤结束时 stream outputs(流式输出)
默认值:True
- --scheduler-delay-factor
在调度下一个 prompt(提示)之前,应用延迟(延迟因子乘以先前的 prompt latency(提示延迟))。
默认值:0.0
- --enable-chunked-prefill
如果设置,prefill requests(预填充请求)可以基于 max_num_batched_tokens 进行分块。
- --speculative-config
speculative decoding(推测解码)的配置。应为 JSON 字符串。
- --model-loader-extra-config
model loader(模型加载器)的额外配置。这将传递给与所选 load_format(加载格式)对应的 model loader(模型加载器)。这应该是一个 JSON 字符串,将被解析为一个字典。
- --ignore-patterns
加载模型时要忽略的 pattern(模式)。默认值为 original/**/*,以避免重复加载 llama 的 checkpoints(检查点)。
默认值:[]
- --preemption-mode
如果为 ‘recompute’,引擎通过重新计算执行 preemption(抢占);如果为 ‘swap’,引擎通过 block swapping(块交换)执行 preemption(抢占)。
- --served-model-name
API 中使用的 model name(s)(模型名称)。如果提供了多个名称,服务器将响应任何提供的名称。响应的 model 字段中的模型名称将是列表中的第一个名称。如果未指定,模型名称将与
--model
参数相同。请注意,如果提供多个名称,此名称也将用于 prometheus metrics(普罗米修斯指标)的 model_name tag content(标签内容)中,metrics tag(指标标签)将采用第一个名称。- --qlora-adapter-name-or-path
QLoRA adapter(QLoRA 适配器)的名称或路径。
- --show-hidden-metrics-for-version
启用自指定版本以来已隐藏的 deprecated(已弃用) Prometheus metrics(普罗米修斯指标)。例如,如果先前已弃用的 metric(指标)自 v0.7.0 版本以来已被隐藏,您可以使用 –show-hidden-metrics-for-version=0.7 作为临时应急方案,同时迁移到新 metrics(指标)。该 metric(指标)很可能在即将发布的版本中被完全删除。
- --otlp-traces-endpoint
OpenTelemetry traces(OpenTelemetry 追踪)将被发送到的目标 URL。
- --collect-detailed-traces
有效选项为 model, worker, all。仅当设置了
--otlp-traces-endpoint
时,设置此项才有意义。如果设置,它将为指定的模块收集 detailed traces(详细追踪)。这涉及使用可能代价高昂和/或阻塞的操作,因此可能会对性能产生影响。- --disable-async-output-proc
禁用 async output processing(异步输出处理)。这可能会导致性能降低。
默认值:False
- --scheduling-policy
可选选项:fcfs, priority
要使用的 scheduling policy(调度策略)。“fcfs”(先到先服务,即按照到达顺序处理请求;默认)或 “priority”(基于给定的 priority(优先级)处理请求(值越低表示越早处理),并以到达时间决定任何并列情况)。
默认值:“fcfs”
- --scheduler-cls
要使用的 scheduler class(调度器类)。“vllm.core.scheduler.Scheduler” 是默认的 scheduler(调度器)。可以是直接的类,也可以是 “mod.custom_class” 形式的类路径。
默认值:“vllm.core.scheduler.Scheduler”
- --override-neuron-config
覆盖或设置 neuron device configuration(neuron 设备配置)。例如:
{"cast_logits_dtype": "bloat16"}
。- --override-pooler-config
覆盖或设置 pooling models(池化模型)的 pooling method(池化方法)。例如:
{"pooling_type": "mean", "normalize": false}
。- --compilation-config, -O
模型的 torch.compile 配置。当它是一个数字(0, 1, 2, 3)时,它将被解释为 optimization level(优化级别)。注意:级别 0 是默认级别,没有任何优化。级别 1 和 2 仅用于内部测试。级别 3 是推荐用于生产的级别。要指定完整的 compilation config(编译配置),请使用 JSON 字符串。按照传统编译器的惯例,也支持不带空格地使用 -O。-O3 等同于 -O 3。
- --kv-transfer-config
distributed KV cache transfer(分布式 KV 缓存传输)的配置。应为 JSON 字符串。
- --worker-cls
用于 distributed execution(分布式执行)的 worker class(工作进程类)。
默认值:“auto”
- --worker-extension-cls
worker cls(工作进程类)之上的 worker extension class(工作进程扩展类),如果您只想向 worker class(工作进程类)添加新功能而不更改现有功能,这将非常有用。
默认值:“”
- --generation-config
generation config(生成配置)的文件夹路径。默认为 ‘auto’,generation config(生成配置)将从模型路径加载。如果设置为 ‘vllm’,则不加载 generation config(生成配置),将使用 vLLM 默认值。如果设置为文件夹路径,generation config(生成配置)将从指定的文件夹路径加载。如果在 generation config(生成配置)中指定了 max_new_tokens,则它将为所有请求设置服务器范围内的输出 tokens(令牌)数量限制。
默认值:auto
- --override-generation-config
以 JSON 格式覆盖或设置 generation config(生成配置)。例如:
{"temperature": 0.5}
。如果与 –generation-config=auto 一起使用,override parameters(覆盖参数)将与模型的默认配置合并。如果 generation-config 为 None,则仅使用 override parameters(覆盖参数)。- --enable-sleep-mode
为引擎启用 sleep mode(睡眠模式)。(仅支持 cuda 平台)
默认值:False
- --calculate-kv-scales
当 kv-cache-dtype 为 fp8 时,启用 k_scale 和 v_scale 的动态计算。如果 calculate-kv-scales 为 false,则 scales(缩放)将从模型 checkpoint(检查点)加载(如果可用)。否则,scales(缩放)将默认为 1.0。
默认值:False
- --additional-config
JSON 格式的指定平台的 additional config(附加配置)。不同的平台可能支持不同的配置。确保配置对于您正在使用的平台有效。输入格式类似于 ‘{“config_key”:”config_value”}’
- --enable-reasoning
是否为模型启用 reasoning_content(推理内容)。如果启用,模型将能够生成 reasoning content(推理内容)。
默认值:False
- --reasoning-parser
可选选项:deepseek_r1, granite
根据您正在使用的模型选择 reasoning parser(推理解析器)。这用于将 reasoning content(推理内容)解析为 OpenAI API 格式。
--enable-reasoning
需要此项。- --disable-cascade-attn
为 V1 禁用 cascade attention(级联注意力)。虽然 cascade attention(级联注意力)不会改变数学上的正确性,但禁用它可以用于防止潜在的数值问题。请注意,即使将其设置为 False,cascade attention(级联注意力)也仅在 heuristic(启发式)表明它有利时才使用。
默认值:False
- --disable-chunked-mm-input
为 V1 禁用 multimodal input chunking attention(多模态输入分块注意力)。如果设置为 true 并且启用了 chunked prefill(分块预填充),我们不希望部分调度 multimodal item(多模态项目)。这确保了如果一个请求具有混合 prompt(提示)(例如文本 tokens TTTT 后跟图像 tokens IIIIIIIIII),其中只能调度一些图像 tokens(例如 TTTTIIIII,留下 IIIII),它将分步调度为 TTTT 和 IIIIIIIIII。
默认值:False
- --disable-log-requests
禁用 logging requests(请求日志记录)。
默认值:False
- --max-log-len
日志中打印的最大 prompt characters(提示字符)或 prompt ID numbers(提示 ID 号)数量。默认值 None 表示无限制。
- --disable-fastapi-docs
禁用 FastAPI 的 OpenAPI schema(OpenAPI 模式)、Swagger UI 和 ReDoc endpoint(ReDoc 端点)。
默认值:False
- --enable-prompt-tokens-details
如果设置为 True,则在 usage(用量)中启用 prompt_tokens_details。
默认值:False
- --enable-server-load-tracking
如果设置为 True,则在 app state(应用状态)中启用 tracking server_load_metrics(跟踪服务器负载指标)。
默认值:False
配置文件#
您可以通过 YAML 配置文件加载 CLI 参数。参数名称必须是 上面 列出的长格式。
例如
# config.yaml
model: meta-llama/Llama-3.1-8B-Instruct
host: "127.0.0.1"
port: 6379
uvicorn-log-level: "info"
使用上述配置文件
vllm serve --config config.yaml
注意
如果同时使用命令行和配置文件提供参数,则以命令行中的值为准。优先级顺序为 命令行 > 配置文件值 > 默认值
。例如,vllm serve SOME_MODEL --config config.yaml
,SOME_MODEL 优先于配置文件中的 model
。
API 参考#
Completions API(补全 API)#
我们的 Completions API(补全 API)与 OpenAI 的 Completions API(补全 API) 兼容;您可以使用 官方 OpenAI Python 客户端 与之交互。
代码示例:examples/online_serving/openai_completion_client.py
额外参数#
支持以下 sampling parameters(采样参数) 。
use_beam_search: bool = False
top_k: Optional[int] = None
min_p: Optional[float] = None
repetition_penalty: Optional[float] = None
length_penalty: float = 1.0
stop_token_ids: Optional[list[int]] = Field(default_factory=list)
include_stop_str_in_output: bool = False
ignore_eos: bool = False
min_tokens: int = 0
skip_special_tokens: bool = True
spaces_between_special_tokens: bool = True
truncate_prompt_tokens: Optional[Annotated[int, Field(ge=1)]] = None
allowed_token_ids: Optional[list[int]] = None
prompt_logprobs: Optional[int] = None
支持以下额外参数
add_special_tokens: bool = Field(
default=True,
description=(
"If true (the default), special tokens (e.g. BOS) will be added to "
"the prompt."),
)
response_format: Optional[ResponseFormat] = Field(
default=None,
description=
("Similar to chat completion, this parameter specifies the format of "
"output. Only {'type': 'json_object'}, {'type': 'json_schema'} or "
"{'type': 'text' } is supported."),
)
guided_json: Optional[Union[str, dict, BaseModel]] = Field(
default=None,
description="If specified, the output will follow the JSON schema.",
)
guided_regex: Optional[str] = Field(
default=None,
description=(
"If specified, the output will follow the regex pattern."),
)
guided_choice: Optional[list[str]] = Field(
default=None,
description=(
"If specified, the output will be exactly one of the choices."),
)
guided_grammar: Optional[str] = Field(
default=None,
description=(
"If specified, the output will follow the context free grammar."),
)
guided_decoding_backend: Optional[str] = Field(
default=None,
description=(
"If specified, will override the default guided decoding backend "
"of the server for this specific request. If set, must be one of "
"'outlines' / 'lm-format-enforcer'"),
)
guided_whitespace_pattern: Optional[str] = Field(
default=None,
description=(
"If specified, will override the default whitespace pattern "
"for guided json decoding."),
)
priority: int = Field(
default=0,
description=(
"The priority of the request (lower means earlier handling; "
"default: 0). Any priority other than 0 will raise an error "
"if the served model does not use priority scheduling."),
)
logits_processors: Optional[LogitsProcessors] = Field(
default=None,
description=(
"A list of either qualified names of logits processors, or "
"constructor objects, to apply when sampling. A constructor is "
"a JSON object with a required 'qualname' field specifying the "
"qualified name of the processor class/factory, and optional "
"'args' and 'kwargs' fields containing positional and keyword "
"arguments. For example: {'qualname': "
"'my_module.MyLogitsProcessor', 'args': [1, 2], 'kwargs': "
"{'param': 'value'}}."))
return_tokens_as_token_ids: Optional[bool] = Field(
default=None,
description=(
"If specified with 'logprobs', tokens are represented "
" as strings of the form 'token_id:{token_id}' so that tokens "
"that are not JSON-encodable can be identified."))
Chat API(聊天 API)#
我们的 Chat API(聊天 API)与 OpenAI 的 Chat Completions API(聊天补全 API) 兼容;您可以使用 官方 OpenAI Python 客户端 与之交互。
我们支持 Vision(视觉) 和 Audio(音频) 相关参数;有关更多信息,请参阅我们的 Multimodal Inputs(多模态输入) 指南。
注意:不支持
image_url.detail
参数。
代码示例:examples/online_serving/openai_chat_completion_client.py
额外参数#
支持以下 sampling parameters(采样参数) 。
best_of: Optional[int] = None
use_beam_search: bool = False
top_k: Optional[int] = None
min_p: Optional[float] = None
repetition_penalty: Optional[float] = None
length_penalty: float = 1.0
stop_token_ids: Optional[list[int]] = Field(default_factory=list)
include_stop_str_in_output: bool = False
ignore_eos: bool = False
min_tokens: int = 0
skip_special_tokens: bool = True
spaces_between_special_tokens: bool = True
truncate_prompt_tokens: Optional[Annotated[int, Field(ge=1)]] = None
prompt_logprobs: Optional[int] = None
支持以下额外参数
echo: bool = Field(
default=False,
description=(
"If true, the new message will be prepended with the last message "
"if they belong to the same role."),
)
add_generation_prompt: bool = Field(
default=True,
description=
("If true, the generation prompt will be added to the chat template. "
"This is a parameter used by chat template in tokenizer config of the "
"model."),
)
continue_final_message: bool = Field(
default=False,
description=
("If this is set, the chat will be formatted so that the final "
"message in the chat is open-ended, without any EOS tokens. The "
"model will continue this message rather than starting a new one. "
"This allows you to \"prefill\" part of the model's response for it. "
"Cannot be used at the same time as `add_generation_prompt`."),
)
add_special_tokens: bool = Field(
default=False,
description=(
"If true, special tokens (e.g. BOS) will be added to the prompt "
"on top of what is added by the chat template. "
"For most models, the chat template takes care of adding the "
"special tokens so this should be set to false (as is the "
"default)."),
)
documents: Optional[list[dict[str, str]]] = Field(
default=None,
description=
("A list of dicts representing documents that will be accessible to "
"the model if it is performing RAG (retrieval-augmented generation)."
" If the template does not support RAG, this argument will have no "
"effect. We recommend that each document should be a dict containing "
"\"title\" and \"text\" keys."),
)
chat_template: Optional[str] = Field(
default=None,
description=(
"A Jinja template to use for this conversion. "
"As of transformers v4.44, default chat template is no longer "
"allowed, so you must provide a chat template if the tokenizer "
"does not define one."),
)
chat_template_kwargs: Optional[dict[str, Any]] = Field(
default=None,
description=("Additional kwargs to pass to the template renderer. "
"Will be accessible by the chat template."),
)
mm_processor_kwargs: Optional[dict[str, Any]] = Field(
default=None,
description=("Additional kwargs to pass to the HF processor."),
)
guided_json: Optional[Union[str, dict, BaseModel]] = Field(
default=None,
description=("If specified, the output will follow the JSON schema."),
)
guided_regex: Optional[str] = Field(
default=None,
description=(
"If specified, the output will follow the regex pattern."),
)
guided_choice: Optional[list[str]] = Field(
default=None,
description=(
"If specified, the output will be exactly one of the choices."),
)
guided_grammar: Optional[str] = Field(
default=None,
description=(
"If specified, the output will follow the context free grammar."),
)
guided_decoding_backend: Optional[str] = Field(
default=None,
description=(
"If specified, will override the default guided decoding backend "
"of the server for this specific request. If set, must be either "
"'outlines' / 'lm-format-enforcer'"),
)
guided_whitespace_pattern: Optional[str] = Field(
default=None,
description=(
"If specified, will override the default whitespace pattern "
"for guided json decoding."),
)
priority: int = Field(
default=0,
description=(
"The priority of the request (lower means earlier handling; "
"default: 0). Any priority other than 0 will raise an error "
"if the served model does not use priority scheduling."),
)
request_id: str = Field(
default_factory=lambda: f"{random_uuid()}",
description=(
"The request_id related to this request. If the caller does "
"not set it, a random_uuid will be generated. This id is used "
"through out the inference process and return in response."),
)
logits_processors: Optional[LogitsProcessors] = Field(
default=None,
description=(
"A list of either qualified names of logits processors, or "
"constructor objects, to apply when sampling. A constructor is "
"a JSON object with a required 'qualname' field specifying the "
"qualified name of the processor class/factory, and optional "
"'args' and 'kwargs' fields containing positional and keyword "
"arguments. For example: {'qualname': "
"'my_module.MyLogitsProcessor', 'args': [1, 2], 'kwargs': "
"{'param': 'value'}}."))
return_tokens_as_token_ids: Optional[bool] = Field(
default=None,
description=(
"If specified with 'logprobs', tokens are represented "
" as strings of the form 'token_id:{token_id}' so that tokens "
"that are not JSON-encodable can be identified."))
Embeddings API(嵌入 API)#
我们的 Embeddings API(嵌入 API)与 OpenAI 的 Embeddings API(嵌入 API) 兼容;您可以使用 官方 OpenAI Python 客户端 与之交互。
如果模型具有 chat template(聊天模板) ,您可以使用 messages
列表替换 inputs
(与 Chat API(聊天 API) 相同的 schema(模式)),这将作为模型的单个 prompt(提示)处理。
代码示例:examples/online_serving/openai_embedding_client.py
Multi-modal inputs(多模态输入)#
您可以通过为服务器定义自定义 chat template(聊天模板)并在请求中传递 messages
列表,将 multi-modal inputs(多模态输入)传递给 embedding models(嵌入模型)。请参阅以下示例以进行说明。
要服务该模型
vllm serve TIGER-Lab/VLM2Vec-Full --task embed \
--trust-remote-code --max-model-len 4096 --chat-template examples/template_vlm2vec.jinja
重要提示
由于 VLM2Vec 具有与 Phi-3.5-Vision 相同的模型架构,因此我们必须显式传递 --task embed
以在 embedding mode(嵌入模式)而不是 text generation mode(文本生成模式)下运行此模型。
自定义 chat template(聊天模板)与此模型的原始模板完全不同,可以在这里找到:examples/template_vlm2vec.jinja
由于请求 schema(模式)不是由 OpenAI 客户端定义的,我们使用较低级别的 requests
库向服务器发布请求
import requests
image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
response = requests.post(
"https://127.0.0.1:8000/v1/embeddings",
json={
"model": "TIGER-Lab/VLM2Vec-Full",
"messages": [{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": image_url}},
{"type": "text", "text": "Represent the given image."},
],
}],
"encoding_format": "float",
},
)
response.raise_for_status()
response_json = response.json()
print("Embedding output:", response_json["data"][0]["embedding"])
要服务该模型
vllm serve MrLight/dse-qwen2-2b-mrl-v1 --task embed \
--trust-remote-code --max-model-len 8192 --chat-template examples/template_dse_qwen2_vl.jinja
重要提示
与 VLM2Vec 类似,我们必须显式传递 --task embed
。
此外,MrLight/dse-qwen2-2b-mrl-v1
需要一个 EOS token(EOS 令牌)用于 embeddings(嵌入),这由自定义 chat template(聊天模板)处理:examples/template_dse_qwen2_vl.jinja
重要提示
MrLight/dse-qwen2-2b-mrl-v1
需要一个 placeholder image(占位符图像),其大小为 text query embeddings(文本查询嵌入)的最小图像大小。有关详细信息,请参阅下面的完整代码示例。
完整示例:examples/online_serving/openai_chat_embedding_client_for_multimodal.py
额外参数#
支持以下 pooling parameters(池化参数) 。
additional_data: Optional[Any] = None
默认情况下支持以下额外参数
add_special_tokens: bool = Field(
default=True,
description=(
"If true (the default), special tokens (e.g. BOS) will be added to "
"the prompt."),
)
priority: int = Field(
default=0,
description=(
"The priority of the request (lower means earlier handling; "
"default: 0). Any priority other than 0 will raise an error "
"if the served model does not use priority scheduling."),
)
对于类似聊天的输入(即,如果传递了 messages
),则支持以下额外参数
add_special_tokens: bool = Field(
default=False,
description=(
"If true, special tokens (e.g. BOS) will be added to the prompt "
"on top of what is added by the chat template. "
"For most models, the chat template takes care of adding the "
"special tokens so this should be set to false (as is the "
"default)."),
)
chat_template: Optional[str] = Field(
default=None,
description=(
"A Jinja template to use for this conversion. "
"As of transformers v4.44, default chat template is no longer "
"allowed, so you must provide a chat template if the tokenizer "
"does not define one."),
)
chat_template_kwargs: Optional[dict[str, Any]] = Field(
default=None,
description=("Additional kwargs to pass to the template renderer. "
"Will be accessible by the chat template."),
)
mm_processor_kwargs: Optional[dict[str, Any]] = Field(
default=None,
description=("Additional kwargs to pass to the HF processor."),
)
priority: int = Field(
default=0,
description=(
"The priority of the request (lower means earlier handling; "
"default: 0). Any priority other than 0 will raise an error "
"if the served model does not use priority scheduling."),
)
Transcriptions API(转录 API)#
我们的 Transcriptions API(转录 API)与 OpenAI 的 Transcriptions API(转录 API) 兼容;您可以使用 官方 OpenAI Python 客户端 与之交互。
注意
要使用 Transcriptions API(转录 API),请使用额外的音频依赖项进行安装,方法是使用 pip install vllm[audio]
。
Tokenizer API(分词器 API)#
我们的 Tokenizer API(分词器 API)是 HuggingFace-style tokenizers(HuggingFace 风格的分词器) 的简单包装器。它由两个 endpoint(端点)组成
/tokenize
对应于调用tokenizer.encode()
。/detokenize
对应于调用tokenizer.decode()
。
Pooling API(池化 API)#
我们的 Pooling API(池化 API)使用 pooling model(池化模型) 对输入 prompts(提示)进行编码,并返回相应的 hidden states(隐藏状态)。
输入格式与 Embeddings API(嵌入 API) 相同,但输出数据可以包含任意嵌套列表,而不仅仅是 1-D floats(浮点数)列表。
Score API(评分 API)#
我们的 Score API(评分 API)可以应用 cross-encoder model(交叉编码器模型)或 embedding model(嵌入模型)来预测句子对的 scores(分数)。当使用 embedding model(嵌入模型)时,score(分数)对应于每个 embedding pair(嵌入对)之间的 cosine similarity(余弦相似度)。通常,句子对的 score(分数)指的是两个句子之间的相似度,范围为 0 到 1。
您可以在 sbert.net 找到 cross encoder models(交叉编码器模型)的文档。
代码示例:examples/online_serving/openai_cross_encoder_score.py
Single inference(单句推理)#
您可以将字符串传递给 text_1
和 text_2
,形成单个句子对。
请求
curl -X 'POST' \
'http://127.0.0.1:8000/score' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"model": "BAAI/bge-reranker-v2-m3",
"encoding_format": "float",
"text_1": "What is the capital of France?",
"text_2": "The capital of France is Paris."
}'
响应
{
"id": "score-request-id",
"object": "list",
"created": 693447,
"model": "BAAI/bge-reranker-v2-m3",
"data": [
{
"index": 0,
"object": "score",
"score": 1
}
],
"usage": {}
}
Batch inference(批量推理)#
您可以将字符串传递给 text_1
,将列表传递给 text_2
,形成多个句子对,其中每个句子对由 text_1
和 text_2
中的字符串构建。句子对的总数为 len(text_2)
。
请求
curl -X 'POST' \
'http://127.0.0.1:8000/score' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"model": "BAAI/bge-reranker-v2-m3",
"text_1": "What is the capital of France?",
"text_2": [
"The capital of Brazil is Brasilia.",
"The capital of France is Paris."
]
}'
响应
{
"id": "score-request-id",
"object": "list",
"created": 693570,
"model": "BAAI/bge-reranker-v2-m3",
"data": [
{
"index": 0,
"object": "score",
"score": 0.001094818115234375
},
{
"index": 1,
"object": "score",
"score": 1
}
],
"usage": {}
}
您可以将列表传递给 text_1
和 text_2
,形成多个句子对,其中每个句子对由 text_1
中的字符串和 text_2
中的对应字符串构建(类似于 zip()
)。句子对的总数为 len(text_2)
。
请求
curl -X 'POST' \
'http://127.0.0.1:8000/score' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"model": "BAAI/bge-reranker-v2-m3",
"encoding_format": "float",
"text_1": [
"What is the capital of Brazil?",
"What is the capital of France?"
],
"text_2": [
"The capital of Brazil is Brasilia.",
"The capital of France is Paris."
]
}'
响应
{
"id": "score-request-id",
"object": "list",
"created": 693447,
"model": "BAAI/bge-reranker-v2-m3",
"data": [
{
"index": 0,
"object": "score",
"score": 1
},
{
"index": 1,
"object": "score",
"score": 1
}
],
"usage": {}
}
额外参数#
支持以下 pooling parameters(池化参数) 。
additional_data: Optional[Any] = None
支持以下额外参数
priority: int = Field(
default=0,
description=(
"The priority of the request (lower means earlier handling; "
"default: 0). Any priority other than 0 will raise an error "
"if the served model does not use priority scheduling."),
)
Re-rank API(重排序 API)#
我们的 Re-rank API(重排序 API)可以应用 embedding model(嵌入模型)或 cross-encoder model(交叉编码器模型)来预测单个 query(查询)与文档列表中的每个文档之间的相关 scores(分数)。通常,句子对的 score(分数)指的是两个句子之间的相似度,范围为 0 到 1。
您可以在 sbert.net 找到 cross encoder models(交叉编码器模型)的文档。
rerank endpoint(重排序端点)支持流行的 re-rank models(重排序模型),例如 BAAI/bge-reranker-base
以及其他支持 score
任务的模型。此外, /rerank
、 /v1/rerank
和 /v2/rerank
endpoint(端点)与 Jina AI 的 re-rank API interface(重排序 API 接口) 和 Cohere 的 re-rank API interface(重排序 API 接口) 兼容,以确保与流行的开源工具的兼容性。
代码示例:examples/online_serving/jinaai_rerank_client.py
示例请求#
请注意, top_n
请求参数是可选的,默认值为 documents
字段的长度。结果文档将按相关性排序,并且可以使用 index
属性来确定原始顺序。
请求
curl -X 'POST' \
'http://127.0.0.1:8000/v1/rerank' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"model": "BAAI/bge-reranker-base",
"query": "What is the capital of France?",
"documents": [
"The capital of Brazil is Brasilia.",
"The capital of France is Paris.",
"Horses and cows are both animals"
]
}'
响应
{
"id": "rerank-fae51b2b664d4ed38f5969b612edff77",
"model": "BAAI/bge-reranker-base",
"usage": {
"total_tokens": 56
},
"results": [
{
"index": 1,
"document": {
"text": "The capital of France is Paris."
},
"relevance_score": 0.99853515625
},
{
"index": 0,
"document": {
"text": "The capital of Brazil is Brasilia."
},
"relevance_score": 0.0005860328674316406
}
]
}
额外参数#
支持以下 pooling parameters(池化参数) 。
additional_data: Optional[Any] = None
支持以下额外参数
priority: int = Field(
default=0,
description=(
"The priority of the request (lower means earlier handling; "
"default: 0). Any priority other than 0 will raise an error "
"if the served model does not use priority scheduling."),
)