生成模型¶
vLLM为生成式模型提供一流的支持,涵盖大多数大型语言模型。
在vLLM中,生成式模型实现了VllmModelForTextGeneration接口。这些模型基于输入的最终隐藏状态,输出待生成token的对数概率,然后通过[Sampler][vllm.model_executor.layers.Sampler]处理以获得最终文本。
配置¶
模型运行器 (--runner)¶
通过选项--runner generate以生成模式运行模型。
提示
在绝大多数情况下无需设置此选项,因为vLLM可以通过--runner auto自动检测要使用的模型运行器。
离线推理¶
LLM 类提供了多种离线推理的方法。初始化模型时的选项列表请参阅configuration。
LLM.generate¶
vLLM中所有生成式模型都提供了generate方法。该方法与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}")
重要
默认情况下,如果未指定SamplingParams,vLLM会通过应用HuggingFace模型仓库中的generation_config.json文件(如果存在)来使用模型创建者推荐的采样参数。在大多数情况下,这将为您提供最佳的默认结果。
但如果倾向于使用vLLM的默认采样参数,请在创建LLM实例时传入generation_config="vllm"。
代码示例可在此处找到: examples/offline_inference/basic/basic.py
LLM.beam_search¶
beam_search 方法在 generate 基础上实现了 beam search。例如,要使用5个beam进行搜索并最多输出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的输入,并自动应用模型的chat template来格式化提示词。
重要
一般来说,只有经过指令调优的模型才具备聊天模板。基础模型可能表现不佳,因为它们未经训练以响应聊天对话。
Code
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,能够接受文本和多模态输入,适用于带有聊天模板的模型。