Mixtral 8X7B MoE模型基于阿里云人工智能平臺PAI實踐合集

作者:熊兮、賀弘镀赌、臨在

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大模型的示例饵撑,參見下圖:

image.png

上述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的模型卡片如下圖所示:

image.png

我們可以根據(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)用方式相同。

image.png

相關資料

阿里云人工智能平臺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靈駿智算服務:

https://www.aliyun.com/product/bigdata/learn/pailingjun

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末或详,一起剝皮案震驚了整個濱河市系羞,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌霸琴,老刑警劉巖椒振,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異梧乘,居然都是意外死亡澎迎,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門选调,熙熙樓的掌柜王于貴愁眉苦臉地迎上來夹供,“玉大人,你說我怎么就攤上這事仁堪∠ⅲ” “怎么了?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵弦聂,是天一觀的道長鸟辅。 經(jīng)常有香客問我,道長莺葫,這世上最難降的妖魔是什么匪凉? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮捺檬,結果婚禮上再层,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好树绩,可當我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著隐轩,像睡著了一般饺饭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上职车,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天瘫俊,我揣著相機與錄音,去河邊找鬼悴灵。 笑死扛芽,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的积瞒。 我是一名探鬼主播川尖,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼茫孔!你這毒婦竟也來了叮喳?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤缰贝,失蹤者是張志新(化名)和其女友劉穎馍悟,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體剩晴,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡锣咒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了赞弥。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片毅整。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖绽左,靈堂內(nèi)的尸體忽然破棺而出毛嫉,到底是詐尸還是另有隱情,我是刑警寧澤妇菱,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布承粤,位于F島的核電站,受9級特大地震影響闯团,放射性物質(zhì)發(fā)生泄漏辛臊。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一房交、第九天 我趴在偏房一處隱蔽的房頂上張望彻舰。 院中可真熱鬧,春花似錦、人聲如沸刃唤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至解总,卻和暖如春蟆融,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背唯卖。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留躬柬,地道東北人拜轨。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像允青,于是被迫代替她去往敵國和親橄碾。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容