安装
# (Recommended) Create a new conda environment.
conda create -n myenv python=3.9 -y
conda activate myenv
# Install vLLM with CUDA 12.1.
pip install vllm -i https://pypi.tuna.tsinghua.edu.cn/simple/
离线推理
from vllm import LLM, SamplingParams
llm = LLM(model="meta-llama/Meta-Llama-3-8B-Instruct") # 你的模型路径
sampling_params = SamplingParams(temperature=0.5) # 生成文本的控制参数,temperature越大,生成的内容越随机
# 处理输出
def print_outputs(outputs):
for output in outputs:
prompt = output.prompt
generated_text = output.outputs[0].text
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
print("-" * 80)
print("=" * 80)
# 模型的输入对话
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.",
},
]
# 将输入对话,采样参数传给模型
# use_tqdm=False是不启用进度条
outputs = llm.chat(conversation,
sampling_params=sampling_params,
use_tqdm=False)
print_outputs(outputs)
# A chat template can be optionally supplied.
# If not, the model will use its default chat template.
# with open('template_falcon_180b.jinja', "r") as f:
# chat_template = f.read()
# outputs = llm.chat(
# conversations,
# sampling_params=sampling_params,
# use_tqdm=False,
# chat_template=chat_template,
# )
适配openAI-API的API服务
使用vllm将大模型推理做成api服务非常方便,你可以通过 - -host和 - -port参数来自定义地址,而且无需担心chat模板,因为它默认会使用由tokenizer提供的chat模板
使用python命令行部署
关于下面的参数设置,建议去官网查看,解释比较清晰全面
官网:https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html
conda activate vllm \ # 激活环境
CUDA_VISIBLE_DEVICES=6 \ # 设置gpu device
nohup python -m vllm.entrypoints.openai.api_server \
--model /LLM/Qwen_1_5_4B_chat/ \ # 指定你的模型路径
--max_model_len=2048 \ # 设置模型生成长度
--served-model-name sevice_name \ # 设置你起的模型服务名
--trust-remote-code \
--api-key 123456 \ # 设置你api key
--port 1234 \ # 设置你的端口
--dtype=half \ # 设置你的数据精度
> /vllm.log 2>&1 & # 设置你的输出log
使用docker部署
docker run --runtime nvidia --gpus all \
-v /path:/path \ # 本地模型的路径/path,挂载到容器下面的路径/path
--rm --name docker_name \ # 你容器的名字
-p 8000:8000 \ # 端口映射,本地端口8000映射到容器端口8000,可修改
--ipc=host \
e********a \ # 镜像id
--model model_path \ # 你的模型路径
--api-key=123456 \ # 设置你的api key
--served-model-name=sevice_name # 设置你起的模型服务名
调用启动成功的API
from openai import OpenAI
openai_api_key = "123456" # 这里是你上述设置的api-key
openai_api_base = "http://ip:8000/v1" # 这里的ip是运行你上述部署脚本所在的主机ip,8000是你脚本里面设置的端口
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
response = client.chat.completions.create(
model="sevice_name", # 这里的sevice_name是你上述脚本中定义的服务名
messages=[
{"role": "system", "content": ""},
{"role": "user", "content": "讲一个笑话"},
],
temperature=0.7,
stream=True # 设置流式返回
)
# 这里是流式返回
for chunk in response:
# print(chunk.choices[0])
if chunk.choices[0].delta:
print(chunk.choices[0].delta.content)