生成模型#

vLLM 为生成模型提供一流的支持,涵盖了大多数 LLM。

在 vLLM 中,生成模型实现了 VllmModelForTextGeneration 接口。基于输入的最终隐藏状态,这些模型输出要生成的 token 的对数概率,然后通过 Sampler 传递以获得最终文本。

对于生成模型,唯一支持的 --task 选项是 "generate"。通常,这是自动推断的,因此您不必指定它。

离线推理#

LLM 类为离线推理提供了各种方法。有关初始化模型时的选项列表,请参阅 引擎参数

LLM.generate#

generate 方法适用于 vLLM 中的所有生成模型。它类似于 HF Transformers 中的对应方法,不同之处在于 tokenization 和 detokenization 也是自动执行的。

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 来使用贪婪采样

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}")

代码示例可以在这里找到: examples/offline_inference/basic/basic.py

LLM.chat#

chat 方法在 generate 之上实现了聊天功能。特别是,它接受类似于 OpenAI Chat Completions API 的输入,并自动应用模型的 聊天模板 来格式化提示。

重要提示

通常,只有指令调优的模型才有聊天模板。基础模型可能表现不佳,因为它们没有经过训练来响应聊天对话。

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 对应的端点