零基础入门AI:两步快速本地部署ChatGPT的平替 - 小羊驼 Vicuna

1,248 阅读4分钟

前言

ChatGPT 引发了大家对大语言模型的热情,但是其封闭的生态也带来了诸多限制。所幸Meta是越来越开放,自LLaMA发布以来,围绕它微调和开发的模型越来越多,逐渐形成了羊驼系列大模型,2023年9月Meta又发布了LLaMA 2,最高支持16K上下文输入,同时修改了授权协议,允许商用,进一步大大降低了这类开源大模型的研究、应用门槛。

羊驼系列大模型中,尤其以UC伯克利大学的研究人员联合其它几家研究机构共同推出的小羊驼(Vicuna)最为出色,仅用少量的数据微调(费用约为300美元),就达到了ChatGPT 90%的性能,实在是企业或者个人研究的必备良心平替。本文将梳理在本地部署和使用 Vicuna 的详细教程。

Step 1: 安装 Vicuna 框架 - FastChat

  • 使用pip安装
pip3 install "fschat[model_worker,webui]"
  • 从源码安装
git clone https://github.com/lm-sys/FastChat.git
cd FastChat
pip3 install --upgrade pip  # enable PEP 660 support
pip3 install -e ".[model_worker,webui]"

如果后续有基于Vicuna做进一步定制开发的需求,建议从源码安装。

Step 2: 下载 Vicuna 模型

目前 Vicuna 的最新版是基于LLaMA 2微调的 v1.5,可以使用如下命令运行,如果模型未下载将自动下载。也可从Hugging Face下载模型,然后在命令中再指定模型路径。

SizeChat CommandHugging Face Repo
7Bpython3 -m fastchat.serve.cli --model-path lmsys/vicuna-7b-v1.5lmsys/vicuna-7b-v1.5
7B-16kpython3 -m fastchat.serve.cli --model-path lmsys/vicuna-7b-v1.5-16klmsys/vicuna-7b-v1.5-16k
13Bpython3 -m fastchat.serve.cli --model-path lmsys/vicuna-13b-v1.5lmsys/vicuna-13b-v1.5
13B-16kpython3 -m fastchat.serve.cli --model-path lmsys/vicuna-13b-v1.5-16klmsys/vicuna-13b-v1.5-16k
33Bpython3 -m fastchat.serve.cli --model-path lmsys/vicuna-33b-v1.3lmsys/vicuna-33b-v1.3

应用场景

微调

UC伯克利大学的研究人员使用4 x A100 (40GB),在70K的数据上微调,共计花费$300。

我用4块A100-SXM4-80GB,在10条数据上也微调成功了,共计花费不到¥300。

torchrun --nproc_per_node=4 --master_port=20001 fastchat/train/train_mem.py \
    --model_name_or_path meta-llama/Llama-2-7b-hf \
    --data_path data/dummy_conversation.json \
    --bf16 True \
    --output_dir output_vicuna \
    --num_train_epochs 3 \
    --per_device_train_batch_size 2 \
    --per_device_eval_batch_size 2 \
    --gradient_accumulation_steps 16 \
    --evaluation_strategy "no" \
    --save_strategy "steps" \
    --save_steps 1200 \
    --save_total_limit 10 \
    --learning_rate 2e-5 \
    --weight_decay 0. \
    --warmup_ratio 0.03 \
    --lr_scheduler_type "cosine" \
    --logging_steps 1 \
    --fsdp "full_shard auto_wrap" \
    --fsdp_transformer_layer_cls_to_wrap 'LlamaDecoderLayer' \
    --tf32 True \
    --model_max_length 2048 \
    --gradient_checkpointing True \
    --lazy_preprocess True

命令行聊天

如果已经下载完成,如下命令将从指定路径加载后运行命令行聊天,是最方便的体验方式。

$ CUDA_VISIBLE_DEVICES=1 python -m fastchat.serve.cli --model-path models/vicuna-7b-v1.5/
Loading checkpoint shards: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:08<00:00,  4.40s/it]
USER: Who are you?
ASSISTANT: I am Vicuna, a language model trained by researchers from Large Model Systems Organization (LMSYS).

网页版聊天

要使用网页版聊天,需要运行三个模块:

  • Controller:python -m fastchat.serve.controller
  • Worker:python -m fastchat.serve.model_worker --model-path models/vicuna-13b
  • WEB服务器:python -m fastchat.serve.gradio_web_server

最后的运行效果如下: 1.png

RESTful API Server

要运行 RESTful API server,需要运行三个模块:

  • Controller:python -m fastchat.serve.controller
  • Worker:python -m fastchat.serve.model_worker --model-path models/vicuna-13b
  • WEB服务器:python -m fastchat.serve.openai_api_server --host 0.0.0.0 --port 8000

要调用API有两种方式:

OpenAI SDK

这种调用方式需要先安装openai库:pip install --upgrade openai

import openai

openai.api_key = "EMPTY"
openai.base_url = "http://localhost:8000/v1/"

model = "vicuna-7b-v1.5"
prompt = "Once upon a time"

# create a completion
completion = openai.completions.create(model=model, prompt=prompt, max_tokens=64)
# print the completion
print(prompt + completion.choices[0].text)

# create a chat completion
completion = openai.chat.completions.create(
  model=model,
  messages=[{"role": "user", "content": "Hello! What is your name?"}]
)
# print the completion
print(completion.choices[0].message.content)

HTTP

这种调用方式可以用requests库,以下仅用curl演示:

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "vicuna-7b-v1.5",
    "messages": [{"role": "user", "content": "Hello! What is your name?"}]
  }'

词嵌入

获取词嵌入的API接口:

curl http://localhost:8000/v1/embeddings \
  -H "Content-Type: application/json" \
  -d '{
    "model": "vicuna-7b-v1.5",
    "input": "Hello world!"
  }'

关于使用词嵌入的使用场景,官方提供了一些基础案例如下:

Vicuna + LangChain 实现本地知识库问答系统

官方举例:

from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import TextLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.indexes import VectorstoreIndexCreator

embedding = OpenAIEmbeddings(model="text-embedding-ada-002")
loader = TextLoader("state_of_the_union.txt")
index = VectorstoreIndexCreator(embedding=embedding).from_loaders([loader])
llm = ChatOpenAI(model="gpt-3.5-turbo")

questions = [
    "Who is the speaker",
    "What did the president say about Ketanji Brown Jackson",
    "What are the threats to America",
    "Who are mentioned in the speech",
    "Who is the vice president",
    "How many projects were announced",
]

for query in questions:
    print("Query:", query)
    print("Answer:", index.query(query, llm=llm))

LangChain支持加载多种格式(HTML、CSV、JSON、MARKDOWN、PDF)的本地知识库,所以可以根据实际场景,调整以上示例中的loader,即可实现一个简单的本地知识库问答系统。

第三方框架

Ollama + Vicuna

Ollama 是一个可以在本地部署和管理开源大语言模型的框架,由于它极大的简化了开源大语言模型的安装和配置细节,一经推出就广受好评,目前已在github上获得了46k star。

如果小伙伴们觉得 Vicuna 官方提供的框架使用不便,也可以用第三方框架Ollama来调用Vicuna模型,如下命令即可一键下载并运行Vicuna模型:ollama run vicuna

关于Ollama的更多介绍和安装方法请参见 零基础入门AI:一键本地运行各种开源大语言模型 - Ollama

text-generation-webui + Vicuna

如果小伙伴们觉得 Vicuna 自带的 WEB GUI 太简陋,也可以使用第三方的WEB GUI框架 text-generation-webui,然后加载 Vicuna 模型即可。