生成模型
vLLM 为生成模型提供一流支持,这涵盖了大多数大型语言模型(LLM)。
在 vLLM 中,生成模型实现了 VllmModelForTextGeneration 接口。这些模型基于输入的最终隐藏状态输出要生成的 token 的对数概率,然后这些概率通过 [Sampler][vllm.model_executor.layers.Sampler] 进行处理,以获得最终文本。
对于生成模型,唯一支持的 --task
选项是 "generate"
。通常,这会自动推断出来,因此您无需指定它。
离线推理¶
LLM 类提供了多种离线推理方法。初始化模型时的选项列表请参见配置。
LLM.generate
¶
generate 方法适用于 vLLM 中的所有生成模型。它类似于HF Transformers 中对应的方法,不同之处在于分词和逆分词也会自动执行。
from vllm import LLM
llm = LLM(model="facebook/opt-125m")
outputs = llm.generate("Hello, my name is")
for output in outputs:
prompt = output.prompt
generated_text = output.outputs[0].text
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
您可以通过传入SamplingParams 来可选地控制语言生成。例如,通过设置 temperature=0
可以使用贪婪采样。
from vllm import LLM, SamplingParams
llm = LLM(model="facebook/opt-125m")
params = SamplingParams(temperature=0)
outputs = llm.generate("Hello, my name is", params)
for output in outputs:
prompt = output.prompt
generated_text = output.outputs[0].text
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
警告
默认情况下,如果存在,vLLM 将应用 huggingface 模型仓库中的 generation_config.json
来使用模型创建者推荐的采样参数。在大多数情况下,如果您未指定SamplingParams,这将默认提供最佳结果。
但是,如果偏好使用 vLLM 的默认采样参数,请在创建LLM 实例时传递 generation_config="vllm"
。
代码示例可以在这里找到: examples/offline_inference/basic/basic.py
LLM.beam_search
¶
beam_search 方法在 generate 的基础上实现了束搜索。例如,使用 5 个束进行搜索并最多输出 50 个 token
from vllm import LLM
from vllm.sampling_params import BeamSearchParams
llm = LLM(model="facebook/opt-125m")
params = BeamSearchParams(beam_width=5, max_tokens=50)
outputs = llm.beam_search([{"prompt": "Hello, my name is "}], params)
for output in outputs:
generated_text = output.sequences[0].text
print(f"Generated text: {generated_text!r}")
LLM.chat
¶
chat 方法在 generate 的基础上实现了聊天功能。特别是,它接受类似于OpenAI Chat Completions API 的输入,并自动应用模型的聊天模板来格式化 prompt。
警告
通常,只有指令调优模型才具有聊天模板。基础模型由于未经过聊天对话训练,可能表现不佳。
from vllm import LLM
llm = LLM(model="meta-llama/Meta-Llama-3-8B-Instruct")
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)
for output in outputs:
prompt = output.prompt
generated_text = output.outputs[0].text
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
代码示例可以在这里找到: examples/offline_inference/basic/chat.py
如果模型没有聊天模板或您想指定其他模板,可以显式传递一个聊天模板。
from vllm.entrypoints.chat_utils import load_chat_template
# You can find a list of existing chat templates under `examples/`
custom_template = load_chat_template(chat_template="<path_to_template>")
print("Loaded chat template:", custom_template)
outputs = llm.chat(conversation, chat_template=custom_template)
在线服务¶
我们的OpenAI 兼容服务器提供了与离线 API 相对应的端点。
- Completions API 类似于
LLM.generate
,但只接受文本。 - Chat API 类似于
LLM.chat
,对于具有聊天模板的模型,它同时接受文本和多模态输入。