vLLM 如何用 LLM 类离线 API 完成生成、chat 与 pooling 模型推理
【免费下载链接】vllmA high-throughput and memory-efficient inference and serving engine for LLMs项目地址: https://gitcode.com/GitHub_Trending/vl/vllm
如果你需要在自己的 Python 代码中批量调用 vLLM 模型,而不是启动一个在线服务,vLLM 的LLM类就是离线推理的入口:不经过单独的推理服务器,直接在进程内完成文本生成(LLM.generate、LLM.chat)以及分类、嵌入、打分等 pooling 任务(LLM.classify、LLM.embed、LLM.score)。
本文覆盖三类离线推理场景:用生成类模型做 prompt 补全、用 chat 模型做多轮对话推理、用 pooling 模型做分类/嵌入/打分。适用前提是 Linux 系统、Python 3.10–3.13(来源:快速开始文档)。API 总览见 离线推理文档,可运行的脚本都在 examples/basic/offline_inference/。
准备条件:安装 vLLM 并确认环境
在 NVIDIA GPU 环境下,文档推荐使用uv创建环境并安装 vLLM:
uv venv --python 3.12 --seed source .venv/bin/activate uv pip install vllm --torch-backend=auto--torch-backend=auto让uv根据本机 CUDA 驱动版本自动选择合适的 PyTorch 索引;也可以显式指定,例如--torch-backend=cu126。AMD ROCm、Intel GPU、TPU 等其他平台有各自的安装方式,见 安装文档。
两个影响运行行为的前提:
vLLM 默认从 Hugging Face 下载模型。如果要改用 ModelScope 上的模型,在初始化引擎前设置环境变量
VLLM_USE_MODELSCOPE:export VLLM_USE_MODELSCOPE=True默认情况下,如果 Hugging Face 模型仓库里存在
generation_config.json,vLLM 会应用模型作者推荐的采样参数。想改用 vLLM 自身默认值,创建LLM实例时传generation_config="vllm"。
生成类模型:用 LLM.generate 批量补全 prompt
最简单的用法可以直接运行仓库中的脚本:
python examples/basic/offline_inference/basic.py脚本内容(basic.py)展示了最小调用路径:
from vllm import LLM, SamplingParams # Sample prompts. prompts = [ "Hello, my name is", "The president of the United States is", "The capital of France is", "The future of AI is", ] # Create a sampling params object. sampling_params = SamplingParams(temperature=0.8, top_p=0.95) llm = LLM(model="facebook/opt-125m") # The output is a list of RequestOutput objects # that contain the prompt, generated text, and other information. outputs = llm.generate(prompts, sampling_params) for output in outputs: prompt = output.prompt generated_text = output.outputs[0].text print(f"Prompt: {prompt!r}") print(f"Output: {generated_text!r}")运行后,输出应为每条 prompt 各打印一行Prompt: ...和Output: ...。llm.generate返回一个RequestOutput对象列表,每个对象包含 prompt、生成文本等信息;output.outputs[0].text是本次要读取的生成结果。
两点使用边界:
llm.generate不会自动套用模型的 chat 模板。如果用的是 Instruct/Chat 模型,要么手动用 tokenizer 的apply_chat_template处理输入,要么直接用下面的llm.chat方法。- 想批量传入引擎参数(如
--tensor-parallel-size等),可以用带参数解析的 generate.py,它通过EngineArgs.add_cli_args暴露了与LLM兼容的全部引擎参数,用python examples/basic/offline_inference/generate.py --help可以查看全部可选项。默认模型为meta-llama/Llama-3.2-1B-Instruct。
chat 模型:用 LLM.chat 做多轮对话推理
chat 场景的脚本是 chat.py,运行方式同样是python examples/basic/offline_inference/chat.py。核心调用:
from vllm import LLM llm = LLM(model="meta-llama/Llama-3.2-1B-Instruct") sampling_params = llm.get_default_sampling_params() conversation = [ {"role": "system", "content": "You are a helpful assistant"}, {"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hello! How can I assist you today?"}, {"role": "user", "content": "Write an essay about the importance of higher education."}, ] outputs = llm.chat(conversation, sampling_params, use_tqdm=False) generated_text = outputs[0].outputs[0].text消息列表的格式与 OpenAIclient.chat.completions的 messages 一致。llm.chat同样支持批量推理:传入conversations列表即可,use_tqdm=True会显示进度条。
可选分支:默认使用模型自带的 chat 模板;也可以从文件读取模板覆盖,脚本通过--chat-template-path参数指定模板文件路径,读取后传给llm.chat(..., chat_template=chat_template)。
pooling 模型:classify、embed 与 score
pooling 模型不生成内容,主要用于分类与检索任务,例如 bge-m3、Qwen3 Reranker。与生成模型的关键区别是构造LLM实例时要传runner="pooling";三个官方示例脚本(classify.py、embed.py、score.py)都同时设置了enforce_eager=True。
分类:LLM.classify
from vllm import LLM llm = LLM(model="jason9693/Qwen2.5-1.5B-apeach", runner="pooling", enforce_eager=True) outputs = llm.classify(prompts) for prompt, output in zip(prompts, outputs): probs = output.outputs.probs print(f"Prompt: {prompt!r}") print(f"Class Probabilities: {probs} (size={len(probs)})")输出是每个 prompt 对应的类别概率向量。脚本可直接运行:python examples/basic/offline_inference/classify.py。
嵌入:LLM.embed
from vllm import LLM from vllm.utils.print_utils import print_embeddings llm = LLM(model="intfloat/e5-small", runner="pooling", enforce_eager=True) outputs = llm.embed(prompts) for prompt, output in zip(prompts, outputs): embeds = output.outputs.embedding print_embeddings(embeds)输出是每个 prompt 的嵌入向量(脚本直接运行:python examples/basic/offline_inference/embed.py)。
打分:LLM.score
打分模型用于计算句子对之间的相似度,示例默认模型为 cross-encoder 类的BAAI/bge-reranker-v2-m3:
from vllm import LLM llm = LLM(model="BAAI/bge-reranker-v2-m3", runner="pooling", enforce_eager=True) outputs = llm.score(query, documents) for document, output in zip(documents, outputs): score = output.outputs.score print(f"Pair: {[query, document]!r} \nScore: {score}")注意限制:只有分类模型的输出num_labels等于 1 时才能作为打分模型使用并启用LLM.score(来源:Pooling 模型文档)。
通用入口:LLM.encode
LLM.encode适用于所有 pooling 模型,需要显式指定任务:
from vllm import LLM llm = LLM(model="intfloat/e5-small", runner="pooling") (output,) = llm.encode("Hello, my name is", pooling_task="embed") print(f"Data: {output.outputs.data!r}")如果默认 pooling 任务不是你想要的(例如需要 token 级的token_classify、token_embed),离线时用PoolerConfig(task=<task>)指定,在线服务对应--pooler-config.task <task>。另外score任务已在 v0.21 中移除,请使用classify。
可选:调整采样参数与生成配置
examples/basic/offline_inference/下的 chat/generate/classify/embed/score 脚本都内置了命令行参数解析:
- chat 与 generate 脚本接受采样参数:
--max-tokens、--temperature、--top-p、--top-k; --generation-config指定LLM.get_default_sampling_params()的生成配置来源:设为auto时从模型路径加载,设为文件夹路径时从该目录加载,不提供则使用 vLLM 默认值。若 generation config 中指定了max_new_tokens,它会成为所有请求的输出 token 上限;- 引擎参数(通过
EngineArgs暴露)任意一个都可用--help查看,例如文档中给出的 GGUF 量化用法--model unsloth/Qwen3-0.6B-GGUF:Q4_K_M --tokenizer Qwen/Qwen3-0.6B,以及用--cpu-offload-gb 10把一部分权重放到 CPU 内存来“虚拟”扩大显存(需要较快的 CPU-GPU 互联)。
结果核对与边界
- 生成/chat 任务:核对方式是每条输入 prompt 都能从
outputs[i].outputs[0].text取到非空的生成文本,且outputs列表长度与输入数量一致(chat.py 中对批量结果断言len(outputs) == len(prompts))。 - pooling 任务:
classify返回概率向量、embed返回嵌入向量、score返回句子对分数,脚本运行后按 prompt 逐条打印即可核对。 - 文档同时说明:pooling 模型目前在 vLLM 中主要出于便利性支持,并不保证比直接使用 Hugging Face Transformers 或 Sentence Transformers 有性能提升。
- 如果你还需要异步排队、profiling、sleep mode 等能力,
LLM类还提供enqueue/enqueue_chat、start_profile/stop_profile、sleep/wake_up等 API,完整清单见 离线推理文档;需要在线服务时,可参考 在线服务文档 改用vllm serve。
【免费下载链接】vllmA high-throughput and memory-efficient inference and serving engine for LLMs项目地址: https://gitcode.com/GitHub_Trending/vl/vllm
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考