• <span id="n97xl"><optgroup id="n97xl"></optgroup></span>
          1. <li id="n97xl"></li>
            <label id="n97xl"><meter id="n97xl"></meter></label>

              Mixtral 8X7B MoE模型基于阿里云人工智能平臺(tái)PAI實(shí)踐合集

                 2024-01-12 7240
              核心提示:作者:熊兮、賀弘、臨在Mixtral8x7B大模型是MixtralAI推出的基于decoder-only架構(gòu)的稀疏專家混合網(wǎng)絡(luò)(Mixture-Of-Experts,MOE

              作者:熊兮、賀弘、臨在

              Mixtral 8x7B大模型是Mixtral AI推出的基于decoder-only架構(gòu)的稀疏專家混合網(wǎng)絡(luò)(Mixture-Of-Experts,MOE)開源大語言模型。這一模型具有46.7B的總參數(shù)量,對(duì)于每個(gè)token,路由器網(wǎng)絡(luò)選擇八組專家網(wǎng)絡(luò)中的兩組進(jìn)行處理,并且將其輸出累加組合,在增加模型參數(shù)總量的同時(shí),優(yōu)化了模型推理的成本。在大多數(shù)基準(zhǔn)測(cè)試中,Mixtral 8x7B模型與Llama2 70B和GPT-3.5表現(xiàn)相當(dāng),因此具有很高的使用性價(jià)比。

              阿里云人工智能平臺(tái)PAI是面向開發(fā)者和企業(yè)的機(jī)器學(xué)習(xí)/深度學(xué)習(xí)平臺(tái),提供包含數(shù)據(jù)標(biāo)注、模型構(gòu)建、模型訓(xùn)練、模型部署、推理優(yōu)化在內(nèi)的AI開發(fā)全鏈路服務(wù)。

              本文介紹如何在PAI平臺(tái)針對(duì)Mixtral 8x7B大模型的微調(diào)和推理服務(wù)的最佳實(shí)踐,助力AI開發(fā)者快速開箱。以下我們將分別展示具體使用步驟。

              使用PAI-DSW輕量化微調(diào)Mixtral 8x7B MOE大模型

              PAI-DSW是云端機(jī)器學(xué)習(xí)開發(fā)IDE,為用戶提供交互式編程環(huán)境,同時(shí)提供了豐富的計(jì)算資源。我們?cè)谥谴a實(shí)驗(yàn)室(https://gallery.pai-ml.com/)Notebook Gallery中上線了兩個(gè)微調(diào)Mixtral 8x7B MOE大模型的示例,參見下圖:

               

               

              上述Notebook可以使用阿里云PAI-DSW的實(shí)例打開,并且需要選擇對(duì)應(yīng)的計(jì)算資源和鏡像。

              使用Swift輕量化微調(diào)Mixtral 8x7B MOE大模型

              Swift是魔搭ModelScope開源社區(qū)推出的輕量級(jí)訓(xùn)練推理工具開源庫,使用Swift進(jìn)行這一大模型LoRA輕量化微調(diào)需要使用2張GU108(80G)及以上資源。在安裝完對(duì)應(yīng)依賴后,我們首先下載模型至本地:

               

              !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 qugawmc

               

              mixtral_url = 'http://pai-vision-data-inner-wulanchabu.oss-cn-wulanchabu-internal.aliyuncs.com/mixtral/Mixtral-8x7B-Instruct-v0.1.tar'

              aria2(mixtral_urlmixtral_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'

               

              當(dāng)模型下載完畢后,我們使用Swift一鍵拉起訓(xùn)練任務(wù):

               

              !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

               

              模型訓(xùn)練完成后,我們將學(xué)習(xí)到的LoRA權(quán)重合并到模型Checkpoint中:

               

              !swift merge-lora --ckpt_dir '/root/output/mistral-7b-moe-instruct/v3-20231215-111107/checkpoint-12'

               

              其中,ckpt_dir參數(shù)的值需要替換成模型LoRA權(quán)重保存路徑。為了測(cè)試模型訓(xùn)練的正確性,我們可以使用transformers庫進(jìn)行離線推理測(cè)試:

               

              其中,ckpt_dir參數(shù)的值需要替換成模型LoRA權(quán)重保存路徑。為了測(cè)試模型訓(xùn)練的正確性,我們可以使用transformers庫進(jìn)行離線推理測(cè)試:

               

              from transformers import AutoModelForCausalLMAutoTokenizer

               

              model_id = '/root/output/mistral-7b-moe-instruct/v3-20231215-111107/checkpoint-12-merged'

              tokenizer = AutoTokenizer.from_pretrained(model_iddevice_map='auto')

               

              model = AutoModelForCausalLM.from_pretrained(model_iddevice_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>>

               

              寫一首歌的過程從開始到結(jié)束。 [/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對(duì)Mixtral 8x7B MOE大模型進(jìn)行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 gkoquss

               

              mixtral_url = 'http://pai-vision-data-inner-wulanchabu.oss-cn-wulanchabu-internal.aliyuncs.com/mixtral/Mixtral-8x7B-Instruct-v0.1.tar'

              aria2(mixtral_urlmixtral_url.split('/')[-1], '/root/')

              !cd /root && tar -xf Mixtral-8x7B-Instruct-v0.1.tar

               

              第二步,我們下載一個(gè)示例古詩生成數(shù)據(jù)集,用戶可以根據(jù)下述數(shù)據(jù)格式準(zhǔn)備自己的數(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ù),并且拉起訓(xùn)練任務(wù)。

               

              !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

               

              當(dāng)訓(xùn)練結(jié)束后,我們拷貝額外配置文件至輸出文件夾:

               

              !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庫進(jìn)行離線推理測(cè)試:

               

              import os

              from transformers import AutoModelForCausalLMAutoTokenizer

              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服務(wù),需要將格式轉(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平臺(tái)推出的彈性推理服務(wù),可以將各種大模型部署為在線服務(wù)。當(dāng)Mixtral 8x7B MOE大模型微調(diào)完畢后,我們可以將其部署為PAI-EAS服務(wù)。這里,我們介紹使用PAI-SDK將上述模型進(jìn)行部署。首先,我們?cè)赑AI-DSW環(huán)境安裝PAI-SDK:

               

              !python -m pip install alipai --upgrade


              在安裝完成后,在在命令行終端上執(zhí)行以下命令,按照引導(dǎo)完成配置AccessKey、PAI工作空間以及 OSS Bucket:

               

              python -m pai.toolkit.config


              我們將訓(xùn)練好的模型上傳至OSS Bucket。在下述命令中,source_path為模型Checkpoint保存的本地路徑,oss_path為上傳至OSS的目標(biāo)路徑:

               

              import pai

              from pai.session import get_default_session

              from pai.common.oss_utils import upload

               

              print(pai.__version__)

              sess = get_default_session()

               

              # 上傳模型到默認(rèn)的Bucket

              model_uri = upload(

                 source_path='/root/output',

                 oss_path='mixtral-7b-moe-instruct-sft-ds'

              )

               

              print(model_uri)

               

              PAI 提供了Mixtral 8X7B MOE 模型部署鏡像和部署代碼,用戶可以通過相應(yīng)的部署配置,將微調(diào)后的模型部署到PAI-EAS。

               

              from pai.model import RegisteredModel

              from pai.predictor import Predictor

               

              # 獲取PAI提供的Mixtral模型服務(wù)配置(目前僅支持烏蘭察布)

              inference_spec = RegisteredModel(

                 'Mixtral-8x7B-Instruct-v0.1',

                 model_provider='pai',

              ).inference_spec

               

              # 修改部署配置,使用微調(diào)后的模型

              infer_spec.mount(model_urimodel_path='/ml/model')

               

               

              # 部署推理服務(wù)服務(wù)

              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

                 }

              )

               

              # 查看服務(wù)的Endpoint和Token

              endpoint = predictor.internet_endpoint

              token = predictor.access_token

               

              以上配置項(xiàng)中,metadata.quota_id是用戶購買的靈駿資源配額ID,在購買了靈駿資源之后,用戶可以從PAI控制臺(tái)頁面的資源配額入口獲取相應(yīng)的信息。

              部署的推理服務(wù)支持 OpenAI 的 API 風(fēng)格進(jìn)行調(diào)用,通過推理服務(wù)的詳情頁,用戶可以獲得服務(wù)訪問地址(Endpoint)和訪問憑證(Token)。使用 cURL 調(diào)用推理服務(wù)的示例如下:

               

              # 請(qǐng)注意替換為使用服務(wù)的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微調(diào)和部署Mixtral 8x7B MOE大模型

              快速開始(PAI-QuickStart)集成了國內(nèi)外AI開源社區(qū)中優(yōu)質(zhì)的預(yù)訓(xùn)練模型,支持零代碼或是SDK的方式實(shí)現(xiàn)微調(diào)和部署Mixtral 8x7B MOE大模型,用戶只需要格式準(zhǔn)備訓(xùn)練集和驗(yàn)證集,填寫訓(xùn)練時(shí)候使用的超參數(shù)就可以一鍵拉起訓(xùn)練任務(wù)。Mixtral的模型卡片如下圖所示:

               

               

              我們可以根據(jù)實(shí)際需求上傳訓(xùn)練集和驗(yàn)證集,調(diào)整超參數(shù),例如learning_rate、sequence_length、train_iters等,如下所示:

               

               

              點(diǎn)擊“訓(xùn)練”按鈕,PAI-QuickStart開始進(jìn)行訓(xùn)練,用戶可以查看訓(xùn)練任務(wù)狀態(tài)和訓(xùn)練日志,如下所示:

               

               

              如果需要將模型部署至PAI-EAS,可以在同一頁面的模型部署卡面選擇資源組,并且點(diǎn)擊“部署”按鈕實(shí)現(xiàn)一鍵部署。模型調(diào)用方式和上文PAI-EAS調(diào)用方式相同。

               

               

              相關(guān)資料

              阿里云人工智能平臺(tái)PAI:

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

              交互式建模PAI-DSW:

              https://www.aliyun.com/activity/bigdata/pai/dsw

              模型在線服務(wù)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靈駿智算服務(wù):

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

               

               
              分享到: 0
              收藏 0
               
              更多>同類資訊
              免責(zé)申明
              推薦資訊
              點(diǎn)擊排行
              最新資訊更多>
              最新供應(yīng)更多>
              網(wǎng)站首頁  |  聯(lián)系方式  |  關(guān)于我們  |  問題解析  |  版權(quán)隱私  |  使用協(xié)議  |  網(wǎng)站地圖  |  排名推廣  |  廣告服務(wù)  |  積分換禮  |  網(wǎng)站留言  |  RSS訂閱  |  違規(guī)舉報(bào)  |  粵ICP備1207862號(hào)

              中國智能化網(wǎng)(zgznh®)--引領(lǐng)工業(yè)智能化產(chǎn)業(yè)發(fā)展 共享智能化+優(yōu)質(zhì)平臺(tái)

              版權(quán)所有:深圳市智控網(wǎng)絡(luò)有限公司 學(xué)術(shù)指導(dǎo):深圳市智能化學(xué)會(huì)

              粵ICP備12078626號(hào)

              深公網(wǎng)安備案證字第 4403101901094 號(hào) | 粵公網(wǎng)安備 44030702001206號(hào)

               
              主站蜘蛛池模板: 亚洲综合精品香蕉久久网97| 中文字幕亚洲综合久久菠萝蜜| 伊人色综合九久久天天蜜桃| 国产91色综合久久免费分享| 五月丁香六月综合欧美在线 | 国产成人亚洲综合| 亚洲综合色区在线观看| 亚洲精品欧美综合| 中文字幕亚洲综合久久2| 色综合久久久久综合99| 人人狠狠综合久久亚洲88| 亚洲图片综合区| 色综合久久久久| 色拍自拍亚洲综合图区| 亚洲综合伊人久久大杳蕉| 久久精品桃花综合| 中文自拍日本综合| 天天综合天天做天天综合| 狠狠做深爱婷婷综合一区| 久久综合久久综合九色| 伊人色综合一区二区三区| 久久综合综合久久97色| 99久久国产综合精品麻豆| 天天干天天射综合网| 婷婷激情综合网| 精品亚洲综合久久中文字幕| 少妇熟女久久综合网色欲| 丁香五月综合久久激情| 久久99亚洲综合精品首页| 亚洲欧美日韩国产综合| 狠狠色综合网站久久久久久久 | 精品久久久久久综合日本| 亚洲精品第一国产综合境外资源| 中文字幕亚洲综合精品一区| 97久久久精品综合88久久 | 97久久久精品综合88久久| 丁香五月网久久综合| 色婷婷久久综合中文久久蜜桃av| 久久综合久久伊人| 丁香五月综合久久激情| 久久婷婷午色综合夜啪|