ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

vLLM 如何用 LLM 类离线 API 完成生成、chat 与 pooling 模型推理

vLLM 如何用 LLM 类离线 API 完成生成、chat 与 pooling 模型推理 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创建环境并安装 vLLMuv venv --python 3.12 --seed source .venv/bin/activate uv pip install vllm --torch-backendauto--torch-backendauto让uv根据本机 CUDA 驱动版本自动选择合适的 PyTorch 索引也可以显式指定例如--torch-backendcu126。AMD ROCm、Intel GPU、TPU 等其他平台有各自的安装方式见 安装文档。两个影响运行行为的前提vLLM 默认从 Hugging Face 下载模型。如果要改用 ModelScope 上的模型在初始化引擎前设置环境变量VLLM_USE_MODELSCOPEexport VLLM_USE_MODELSCOPETrue默认情况下如果 Hugging Face 模型仓库里存在generation_config.jsonvLLM 会应用模型作者推荐的采样参数。想改用 vLLM 自身默认值创建LLM实例时传generation_configvllm。生成类模型用 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(temperature0.8, top_p0.95) llm LLM(modelfacebook/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(fPrompt: {prompt!r}) print(fOutput: {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(modelmeta-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_tqdmFalse) generated_text outputs[0].outputs[0].text消息列表的格式与 OpenAIclient.chat.completions的 messages 一致。llm.chat同样支持批量推理传入conversations列表即可use_tqdmTrue会显示进度条。可选分支默认使用模型自带的 chat 模板也可以从文件读取模板覆盖脚本通过--chat-template-path参数指定模板文件路径读取后传给llm.chat(..., chat_templatechat_template)。pooling 模型classify、embed 与 scorepooling 模型不生成内容主要用于分类与检索任务例如 bge-m3、Qwen3 Reranker。与生成模型的关键区别是构造LLM实例时要传runnerpooling三个官方示例脚本classify.py、embed.py、score.py都同时设置了enforce_eagerTrue。分类LLM.classifyfrom vllm import LLM llm LLM(modeljason9693/Qwen2.5-1.5B-apeach, runnerpooling, enforce_eagerTrue) outputs llm.classify(prompts) for prompt, output in zip(prompts, outputs): probs output.outputs.probs print(fPrompt: {prompt!r}) print(fClass Probabilities: {probs} (size{len(probs)}))输出是每个 prompt 对应的类别概率向量。脚本可直接运行python examples/basic/offline_inference/classify.py。嵌入LLM.embedfrom vllm import LLM from vllm.utils.print_utils import print_embeddings llm LLM(modelintfloat/e5-small, runnerpooling, enforce_eagerTrue) 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-m3from vllm import LLM llm LLM(modelBAAI/bge-reranker-v2-m3, runnerpooling, enforce_eagerTrue) outputs llm.score(query, documents) for document, output in zip(documents, outputs): score output.outputs.score print(fPair: {[query, document]!r} \nScore: {score})注意限制只有分类模型的输出num_labels等于 1 时才能作为打分模型使用并启用LLM.score来源Pooling 模型文档。通用入口LLM.encodeLLM.encode适用于所有 pooling 模型需要显式指定任务from vllm import LLM llm LLM(modelintfloat/e5-small, runnerpooling) (output,) llm.encode(Hello, my name is, pooling_taskembed) print(fData: {output.outputs.data!r})如果默认 pooling 任务不是你想要的例如需要 token 级的token_classify、token_embed离线时用PoolerConfig(tasktask)指定在线服务对应--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),仅供参考
返回列表