作者:熊兮、賀弘镀赌、臨在
Mixtral 8x7B大模型是Mixtral AI推出的基于decoder-only架構的稀疏專家混合網(wǎng)絡(Mixture-Of-Experts爵赵,MOE)開源大語言模型叁鉴。這一模型具有46.7B的總參數(shù)量瘫析,對于每個token,路由器網(wǎng)絡選擇八組專家網(wǎng)絡中的兩組進行處理救巷,并且將其輸出累加組合壶熏,在增加模型參數(shù)總量的同時,優(yōu)化了模型推理的成本浦译。在大多數(shù)基準測試中棒假,Mixtral 8x7B模型與Llama2 70B和GPT-3.5表現(xiàn)相當,因此具有很高的使用性價比精盅。
阿里云人工智能平臺PAI是面向開發(fā)者和企業(yè)的機器學習/深度學習平臺帽哑,提供包含數(shù)據(jù)標注、模型構建叹俏、模型訓練妻枕、模型部署、推理優(yōu)化在內(nèi)的AI開發(fā)全鏈路服務粘驰。
本文介紹如何在PAI平臺針對Mixtral 8x7B大模型的微調(diào)和推理服務的最佳實踐屡谐,助力AI開發(fā)者快速開箱。以下我們將分別展示具體使用步驟蝌数。
使用PAI-DSW輕量化微調(diào)Mixtral 8x7B MOE大模型
PAI-DSW是云端機器學習開發(fā)IDE愕掏,為用戶提供交互式編程環(huán)境,同時提供了豐富的計算資源顶伞。我們在智碼實驗室(https://gallery.pai-ml.com/)Notebook Gallery中上線了兩個微調(diào)Mixtral 8x7B MOE大模型的示例饵撑,參見下圖:
上述Notebook可以使用阿里云PAI-DSW的實例打開,并且需要選擇對應的計算資源和鏡像枝哄。
使用Swift輕量化微調(diào)Mixtral 8x7B MOE大模型
Swift是魔搭ModelScope開源社區(qū)推出的輕量級訓練推理工具開源庫肄梨,使用Swift進行這一大模型LoRA輕量化微調(diào)需要使用2張GU108(80G)及以上資源阻荒。在安裝完對應依賴后挠锥,我們首先下載模型至本地:
!apt-get update
!echo y | apt-get install aria2
def aria2(url, filename, d):
!aria2c --console-log-level=error -c -x 16 -s 16 {url} -o {filename} -d ay8y6yq
mixtral_url = "http://pai-vision-data-inner-wulanchabu.oss-cn-wulanchabu-internal.aliyuncs.com/mixtral/Mixtral-8x7B-Instruct-v0.1.tar"
aria2(mixtral_url, mixtral_url.split("/")[-1], "/root/")
!cd /root && mkdir -p AI-ModelScope
!cd /root && tar -xf Mixtral-8x7B-Instruct-v0.1.tar -C /root/AI-ModelScope
import os
os.environ['MODELSCOPE_CACHE']='/root'
當模型下載完畢后,我們使用Swift一鍵拉起訓練任務:
!cd swift/examples/pytorch/llm && PYTHONPATH=../../.. \
CUDA_VISIBLE_DEVICES=0,1 \
python llm_sft.py \
--model_id_or_path AI-ModelScope/Mixtral-8x7B-Instruct-v0.1 \
--model_revision master \
--sft_type lora \
--tuner_backend swift \
--dtype AUTO \
--output_dir /root/output \
--ddp_backend nccl \
--dataset alpaca-zh \
--train_dataset_sample 100 \
--num_train_epochs 2 \
--max_length 2048 \
--check_dataset_strategy warning \
--lora_rank 8 \
--lora_alpha 32 \
--lora_dropout_p 0.05 \
--lora_target_modules ALL \
--batch_size 1 \
--weight_decay 0.01 \
--learning_rate 1e-4 \
--gradient_accumulation_steps 16 \
--max_grad_norm 0.5 \
--warmup_ratio 0.03 \
--eval_steps 300 \
--save_steps 300 \
--save_total_limit 2 \
--logging_steps 10 \
--only_save_model true \
--gradient_checkpointing false
模型訓練完成后侨赡,我們將學習到的LoRA權重合并到模型Checkpoint中:
!swift merge-lora --ckpt_dir '/root/output/mistral-7b-moe-instruct/v3-20231215-111107/checkpoint-12'
其中蓖租,ckpt_dir參數(shù)的值需要替換成模型LoRA權重保存路徑粱侣。為了測試模型訓練的正確性,我們可以使用transformers庫進行離線推理測試:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "/root/output/mistral-7b-moe-instruct/v3-20231215-111107/checkpoint-12-merged"
tokenizer = AutoTokenizer.from_pretrained(model_id, device_map='auto')
model = AutoModelForCausalLM.from_pretrained(model_id, device_map='auto')
text = """[INST] <<SYS>>
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.
<</SYS>>
寫一首歌的過程從開始到結束蓖宦。 [/INST]"""
inputs = tokenizer(text, return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=512)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
使用Deepspeed輕量化微調(diào)Mixtral 8x7B MOE大模型
我們也可以使用Deepspeed對Mixtral 8x7B MOE大模型進行LoRA輕量化微調(diào)齐婴。同樣的,我們需要使用2張GU108(80G)及以上資源稠茂。我們首先下載模型至本地:
!apt-get update
!echo y | apt-get install aria2
def aria2(url, filename, d):
!aria2c --console-log-level=error -c -x 16 -s 16 {url} -o {filename} -d ywom8a6
mixtral_url = "http://pai-vision-data-inner-wulanchabu.oss-cn-wulanchabu-internal.aliyuncs.com/mixtral/Mixtral-8x7B-Instruct-v0.1.tar"
aria2(mixtral_url, mixtral_url.split("/")[-1], "/root/")
!cd /root && tar -xf Mixtral-8x7B-Instruct-v0.1.tar
第二步柠偶,我們下載一個示例古詩生成數(shù)據(jù)集,用戶可以根據(jù)下述數(shù)據(jù)格式準備自己的數(shù)據(jù)集睬关。
!wget -c https://pai-quickstart-predeploy-hangzhou.oss-cn-hangzhou.aliyuncs.com/huggingface/datasets/llm_instruct/en_poetry_train_mixtral.json
!wget -c https://pai-quickstart-predeploy-hangzhou.oss-cn-hangzhou.aliyuncs.com/huggingface/datasets/llm_instruct/en_poetry_test_mixtral.json
第三步诱担,我們可以修改示例命令的超參數(shù),并且拉起訓練任務电爹。
!mkdir -p /root/output
!deepspeed /ml/code/train_sft.py \
--model_name_or_path /root/Mixtral-8x7B-Instruct-v0.1/ \
--train_path en_poetry_train_mixtral.json \
--valid_path en_poetry_test_mixtral.json \
--learning_rate 1e-5 \
--lora_dim 32 \
--max_seq_len 256 \
--model mixtral \
--num_train_epochs 1 \
--per_device_train_batch_size 8 \
--zero_stage 3 \
--gradient_checkpointing \
--print_loss \
--deepspeed \
--output_dir /root/output/ \
--offload
當訓練結束后蔫仙,我們拷貝額外配置文件至輸出文件夾:
!cp /root/Mixtral-8x7B-Instruct-v0.1/generation_config.json /root/output
!cp /root/Mixtral-8x7B-Instruct-v0.1/special_tokens_map.json /root/output
!cp /root/Mixtral-8x7B-Instruct-v0.1/tokenizer.json /root/output
!cp /root/Mixtral-8x7B-Instruct-v0.1/tokenizer.model /root/output
!cp /root/Mixtral-8x7B-Instruct-v0.1/tokenizer_config.json /root/output
我們同樣可以使用transformers庫進行離線推理測試:
import os
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
model_id = "/root/output/"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id,device_map='auto',torch_dtype=torch.float16)
text = """[INST] Write a poem on a topic 'Care for Thy Soul as Thing of Greatest Price': [/INST]"""
inputs = tokenizer(text, return_tensors="pt").to('cuda')
outputs = model.generate(**inputs, max_new_tokens=20)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
如果用戶需要將上述模型部署為EAS服務,需要將格式轉(zhuǎn)換成safetensors格式:
state_dict = model.state_dict()
model.save_pretrained(
model_id,
state_dict=state_dict,
safe_serialization=True)
使用PAI-EAS在線部署Mixtral 8x7B MOE大模型
PAI-EAS是PAI平臺推出的彈性推理服務丐箩,可以將各種大模型部署為在線服務摇邦。當Mixtral 8x7B MOE大模型微調(diào)完畢后,我們可以將其部署為PAI-EAS服務屎勘。這里施籍,我們介紹使用PAI-SDK將上述模型進行部署。首先挑秉,我們在PAI-DSW環(huán)境安裝PAI-SDK:
!python -m pip install alipai --upgrade
在安裝完成后法梯,在在命令行終端上執(zhí)行以下命令,按照引導完成配置AccessKey犀概、PAI工作空間以及 OSS Bucket:
python -m pai.toolkit.config
我們將訓練好的模型上傳至OSS Bucket立哑。在下述命令中,source_path為模型Checkpoint保存的本地路徑姻灶,oss_path為上傳至OSS的目標路徑:
import pai
from pai.session import get_default_session
from pai.common.oss_utils import upload
print(pai.__version__)
sess = get_default_session()
# 上傳模型到默認的Bucket
model_uri = upload(
source_path="/root/output",
oss_path="mixtral-7b-moe-instruct-sft-ds"
)
print(model_uri)
PAI 提供了Mixtral 8X7B MOE 模型部署鏡像和部署代碼铛绰,用戶可以通過相應的部署配置,將微調(diào)后的模型部署到PAI-EAS产喉。
from pai.model import RegisteredModel
from pai.predictor import Predictor
# 獲取PAI提供的Mixtral模型服務配置(目前僅支持烏蘭察布)
inference_spec = RegisteredModel(
"Mixtral-8x7B-Instruct-v0.1",
model_provider="pai",
).inference_spec
# 修改部署配置捂掰,使用微調(diào)后的模型
infer_spec.mount(model_uri, model_path="/ml/model")
# 部署推理服務服務
m = Model(inference_spec=infer_spec)
predictor: Predictor = m.deploy(
service_name = 'mixtral_sdk_example_ds',
options={
"metadata.quota_id": "<ResourceGroupQuotaId>",
"metadata.quota_type": "Lingjun",
"metadata.workspace_id": session.workspace_id
}
)
# 查看服務的Endpoint和Token
endpoint = predictor.internet_endpoint
token = predictor.access_token
以上配置項中,metadata.quota_id
是用戶購買的靈駿資源配額ID曾沈,在購買了靈駿資源之后这嚣,用戶可以從PAI控制臺頁面的資源配額入口獲取相應的信息。
部署的推理服務支持 OpenAI 的 API 風格進行調(diào)用塞俱,通過推理服務的詳情頁姐帚,用戶可以獲得服務訪問地址(Endpoint)和訪問憑證(Token)。使用 cURL 調(diào)用推理服務的示例如下:
# 請注意替換為使用服務的Endpoint和Token
export API_ENDPOINT="<ENDPOINT>"
export API_TOKEN="<TOKEN>"
# 查看模型list
curl $API_ENDPOINT/v1/models \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $API_TOKEN"
# 調(diào)用通用的文本生成API
curl $API_ENDPOINT/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $API_TOKEN" \
-d '{
"model": "Mixtral-8x7B-Instruct-v0.1",
"prompt": "San Francisco is a",
"max_tokens": 256,
"temperature": 0
}'
curl $API_ENDPOINT/v1/chat/completions \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "Mixtral-8x7B-Instruct-v0.1",
"messages": [
{"role": "user", "content": "介紹一下上海的歷史"}
]
}'
使用PAI-QuickStart微調(diào)和部署Mixtral 8x7B MOE大模型
快速開始(PAI-QuickStart)集成了國內(nèi)外AI開源社區(qū)中優(yōu)質(zhì)的預訓練模型障涯,支持零代碼或是SDK的方式實現(xiàn)微調(diào)和部署Mixtral 8x7B MOE大模型罐旗,用戶只需要格式準備訓練集和驗證集膳汪,填寫訓練時候使用的超參數(shù)就可以一鍵拉起訓練任務。Mixtral的模型卡片如下圖所示:
我們可以根據(jù)實際需求上傳訓練集和驗證集九秀,調(diào)整超參數(shù)遗嗽,例如learning_rate、sequence_length鼓蜒、train_iters等痹换,如下所示:
[圖片上傳失敗...(image-87ab30-1705042641432)]
點擊“訓練”按鈕,PAI-QuickStart開始進行訓練都弹,用戶可以查看訓練任務狀態(tài)和訓練日志晴音,如下所示:
[圖片上傳失敗...(image-5edd4d-1705042641432)]
如果需要將模型部署至PAI-EAS,可以在同一頁面的模型部署卡面選擇資源組缔杉,并且點擊“部署”按鈕實現(xiàn)一鍵部署锤躁。模型調(diào)用方式和上文PAI-EAS調(diào)用方式相同。
相關資料
阿里云人工智能平臺PAI:
https://www.aliyun.com/product/bigdata/learn
交互式建模PAI-DSW:
https://www.aliyun.com/activity/bigdata/pai/dsw
模型在線服務PAI-EAS:
https://www.aliyun.com/product/bigdata/learn/eas
PAI 快速開始:
https://help.aliyun.com/zh/pai/user-guide/quick-start-overview
PAI Python SDK:
https://github.com/aliyun/pai-python-sdk
阿里云PAI靈駿智算服務: