すべてのプロダクト
Search
ドキュメントセンター

Platform For AI:Mixtral-8x7B MoEモデルのデプロイと微調整

最終更新日:Feb 07, 2025

Mixtral-8x7Bは、Mistral AIによってリリースされた最新の大規模言語モデル (LLM) であり、さまざまなベンチマークテストでGPT-3.5モデルを上回り、最先端のオープンソースLLMの1つです。Platform for AI (PAI) は、Mixtral-8x7Bモデルを完全にサポートします。 PAIを使用すると、開発者やエンタープライズユーザーは、モデルギャラリーに基づいてMixtral-8x7Bモデルを効率的に微調整およびデプロイできます。

モデル紹介

Mixtral-8x7Bは、エンコーダ (デコーダのみ) アーキテクチャに基づくSparse Mixture of Experts (SMoE) オープンソースLLMであり、Apache 2.0プロトコルを使用してリリースされています。 Mixtral-8x7Bは、各トークンを処理するために8つのエキスパートグループから2つを選択し、それらの出力を蓄積して組み合わせるルーターネットワークのおかげで際立っています。 その結果、Mixtral-8x7Bが合計470億のパラメータを持っているにもかかわらず、トークンごとに130億しかアクティブに使用されません。 これにより、推論速度が向上し、130億個のパラメータを持つモデルに匹敵します。

Mixtral-8x7Bは、フランス語、ドイツ語、スペイン語、イタリア語、英語などの複数の言語と、32,000トークンのコンテキスト長をサポートしています。 Mixtral-8x7Bは、評価されたすべてのベンチマークテストで、LLaMA2-70BおよびGPT-3.5モデルのパフォーマンスと一致またはそれを超えます。 Mixtral-8x7Bは、特に数学、コード生成、および多言語ベンチマークテストでLLaMA2-70Bモデルを大幅に上回ります。

image.png

出典: https://arxiv.org/abs/2401.04088

Mistral AIは、Mixtral-8x7Bの命令調整バージョンであるMixtral-8x7B-Instruct-v0.1もリリースしました。 このバージョンは、教師付き微調整と直接優先最適化 (DPO) を使用して最適化されています。 これにより、Mixtral-8x7B-Instruct-v0.1は人間の指示によく従い、他のオープンソースの命令調整モデルよりも会話機能が向上します。

image.png

ソース: https:// huggingface.co/spaces/lmsys/chatbot-arena-leaderboard

前提条件

Lingjunリソースが購入されます。 詳細については、「リソースグループの作成とLingjunリソースの購入」をご参照ください。

環境要件

  • Mixtral-8x7Bは、サイズが大きいため、中国 (Ulanqab) リージョンとLingjunクラスターでのみ実行できます。

  • GU108 (80 GB) GPUの使用を推奨します。 推論には少なくとも2つのGPUが必要であり、低ランク適応 (LoRA) 微調整には少なくとも4つのGPUが必要です。

PAIコンソールでのモデルの使用

モデルサービスのデプロイと呼び出し

  1. モデルギャラリーページに移動します。

    1. PAI コンソールにログインします。

    2. 中国 (Ulanqab) リージョンを選択します。

    3. 左側のナビゲーションペインで、[ワークスペース] をクリックします。 [ワークスペース] ページで、管理するワークスペースの名前をクリックします。

    4. 左側のナビゲーションウィンドウで、[クイックスタート] > [モデルギャラリー] を選択します。

  2. モデルギャラリーページのモデルリストで、Mixtral-8x7B-Instruct-v0.1カードをクリックします。

  3. モデルの詳細ページで、右上隅の [デプロイ] をクリックします。 [デプロイ] パネルで、Lingjunコンピューティングリソースを設定し、[デプロイ] をクリックします。

    モデルでは、デプロイにLingjunリソースが必要です。 少なくとも2つのGU108 GPUを持つリソースクォータを選択してください。

    image.png

  4. モデルサービスを呼び出します。

    HTTP APIの使用

    OpenAI APIを使用してモデルサービスを呼び出すことができます。 モデルサービスのエンドポイントとトークンは、モデルサービスの詳細ページで取得できます。 次のサンプルコードは、curlコマンドを実行してモデルサービスを呼び出す方法の例を示しています。

    # Replace <ENDPOINT> and <TOKEN> with the endpoint and token of your model service.
    export API_ENDPOINT="<ENDPOINT>"
    export API_TOKEN="<TOKEN>"
    
    # View the model list.
    curl $API_ENDPOINT/v1/models \
    	-H "Content-Type: application/json" \
    	-H "Authorization: Bearer $API_TOKEN"
    
    # Call a general-purpose text generation 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": "Introduce the history of Shanghai"}
            ]
          }'
    

    SDKの使用

    OpenAI SDKを使用してモデルサービスを呼び出す前に、SDKをインストールする必要があります。

    # Install the SDK.
    python -m pip install openai

    次のサンプルコードは、SDKを使用してモデルサービスを呼び出す方法の例を示しています。

    import openai
    
    # Replace <ENDPOINT> and <TOKEN> with the endpoint and token of your model service that you obtained on the model service details page. 
    openai.api_key = "<TOKEN>"
    openai.base_url = "<ENDPOINT>" + "/v1"
    
    
    # Call a chat API.
    completion = openai.chat.completions.create(
        model="Mixtral-8x7B-Instruct-v0.1",
        temperature=0.0,
        top_p=0.8,
        frequency_penalty=0.0,
        messages=[{"role": "user", "content": "Introduce yourself."}],
        # stream=True,
    )
    # Print the output content.
    print(completion.choices[0].message.content)
    

モデルのトレーニング

モデルギャラリーは、Mixtral-8x7B-Instruct-v0.1モデルのための標準的な微調整アルゴリズムを提供します。

微調整アルゴリズムは、JSON形式の入力をサポートします。 各データレコードは、命令フィールドによって指定されるクエリと、出力フィールドによって指定される応答とからなる。 例:

[
    {
        "instruction": "Write a poem on a topic 'On a Political Prisoner': \n",
        "output": "She that but little patience knew,\r\nFrom childhood on, had now so much\r\nA grey gull lost its fear and flew\r\nDown to her cell and there alit,\r\nAnd there endured her fingers' touch\r\nAnd from her fingers ate its bit.\r\nDid she in touching that lone wing."
    },
    {
        "instruction": "Write a poem on a topic 'To His Love': ",
        "output": "He's gone, and all our plans\r\n   Are useless indeed.\r\nWe'll walk no more on Cotswold\r\n   Where the sheep feed\r\n   Quietly and take no heed.\r\n His body that was so quick\r\n   Is not as you\r\nKnew it, on Severn river\r\n   Under the blue\r\n   Driving our small boat through."
    }
]
  1. モデルの詳細ページで、右上隅の [電車] をクリックします。 Trainパネルで、次の主要なパラメータを設定します。

    • データセット設定: 準備したデータセットを含むObject Storage Service (OSS) パスを指定するか、file Storage NAS (NAS) またはCloud Parallel File Storage (CPFS) に保存されているデータセットファイルを選択できます。 既定のパスを選択して、PAIが提供するパブリックデータセットを使用することもできます。

    • コンピューティングリソース: 微調整アルゴリズムには、80 GBのメモリを備えた4つのGU108 GPUが必要です。 使用するリソースクォータに十分なコンピューティングリソースがあることを確認してください。

    • ハイパーパラメータ: 次の表に、微調整アルゴリズムのハイパーパラメータを示します。 ビジネス要件に基づいてハイパーパラメータを設定します。

      ハイパーパラメータ

      タイプ

      デフォルト値

      必須 / 任意

      説明

      learning_rate

      float

      5e-5

      対象

      モデルが調整される範囲を制御する学習率。

      num_train_epochs

      int

      1

      対象

      エポックの数。 エポックは、トレーニングデータセット内の各サンプルをアルゴリズムに公開する完全なサイクルです。

      per_device_train_batch_size

      int

      1

      対象

      各GPUが1回のトレーニングイテレーションで処理するサンプルの数。 値が高いほど、トレーニング効率とメモリ使用量が高くなります。

      seq_length

      int

      128

      対象

      シーケンスの長さ。 モデルが一度に処理する入力データの長さ。

      lora_dim

      int

      16

      非対象

      低ランク適応 (LoRA) またはQLoRAトレーニングで使用される低ランク行列の内次元。 このパラメーターを0より大きい値に設定します。

      lora_alpha

      int

      32

      非対象

      LoRAまたはQLoRAの重み。 このパラメーターは、lora_dimパラメーターを0より大きい値に設定した場合にのみ有効になります。

      load_in_4bit

      bool

      true

      非対象

      モデルを4ビット量子化で読み込むかどうかを指定します。

      load_in_8bit

      bool

      false

      非対象

      モデルを8ビット量子化で読み込むかどうかを指定します。

      gradient_accumulation_steps

      int

      8

      非対象

      勾配累積ステップの数。

      apply_chat_template

      bool

      true

      非対象

      アルゴリズムがトレーニングデータを既定のチャットテンプレートと組み合わせるかどうかを指定します。 設定例:

      • 質問: <| begin_of_text |><| start_header_id |>user<| end_header_id |>\ n\n + instruction + <| eot_id |>

      • 回答: <| start_header_id |> アシスタント <| end_header_id |>\ n\n + output + <| eot_id |>

  2. [トレイン] をクリックします。 トレーニングジョブの詳細ページで、トレーニングジョブのステータスとログを表示できます。

    詳細ドロップダウンリストをクリックし、右上隅のTensorboardを選択して、モデルの収束ステータスを表示します。image.png

    トレーニング済みモデルは、AIアセット管理モジュールのモデルに自動的に登録されます。 モデルを表示またはデプロイできます。 詳細については、「モデルの登録と管理」をご参照ください。

PAI SDK for Pythonでのモデルの使用

PAI SDK for Pythonを使用して、モデルギャラリーで事前トレーニング済みモデルを呼び出すことができます。 モデルを呼び出す前に、Python用PAI SDKをインストールして設定する必要があります。 サンプルコード:

# Install PAI SDK for Python.
python -m pip install alipai --upgrade

# Interactively configure the required information, such as your AccessKey pair and PAI workspace.
python -m pai.toolkit.config

AccessKeyペアやPAIワークスペースなど、必要な情報を取得する方法については、「Python用PAI SDKのインストールと設定」をご参照ください。

モデルサービスのデプロイと呼び出し

推論サービス設定は、モデルギャラリーのモデルで事前設定されています。 MixtralモデルをElastic Algorithm service (EAS) に効率的にデプロイするには、リソース情報とサービス名のみを指定する必要があります。

from pai.session import get_default_session
from pai.model import RegisteredModel
from pai.common.utils import random_str
from pai.predictor import Predictor

session = get_default_session()

# Obtain the model from Model Gallery.
m = RegisteredModel(
    model_name="Mixtral-8x7B-Instruct-v0.1",
    model_provider="pai",
)

# View the default deployment configurations of the model.
print(m.inference_spec)

# Deploy a model as an inference service.
# Provide a resource quota that is created on Lingjun resources, which has at least two GU108 GPUs with 80 GB of memory.
predictor = m.deploy(
    service_name="mixtral_8_7b_{}".format(random_str(6)),
    options={
        # The ID of the resource quota.
        "metadata.quota_id": "<LingJunResourceQuotaId>",
        "metadata.quota_type": "Lingjun",
        "metadata.workspace_id": session.workspace_id,
    }
)

# Obtain the endpoint and token of the model service.
endpoint = predictor.internet_endpoint
token = predictor.access_token

モデルサービスの呼び出し方法については、「モデルサービスのデプロイと呼び出し」をご参照ください。 Python用PAI SDKを使用してモデルサービスを呼び出すこともできます。

from pai.predictor import Predictor

p = Predictor("<MixtralServiceName>")

res = p.raw_predict(
    path="/v1/chat/completions",
    method="POST",
    data={
        "model": "Mixtral-8x7B-Instruct-v0.1",
        "messages": [
            {"role": "user", "content": "Introduce the history of Shanghai"}
        ]
    }
)

print(res.json())

モデルサービスを呼び出した後、PAIコンソールで、またはPAI SDK for Pythonを使用して、モデルサービスを削除してリソースをリリースする必要があります。

# Delete a model service.
predictor.delete_service()

モデルのトレーニング

PAI SDK for Pythonを使用してモデルギャラリーから事前トレーニング済みモデルを取得すると、アルゴリズムでサポートされているハイパーパラメーター設定やアルゴリズムの入出力データなど、モデルの微調整アルゴリズムを表示できます。

from pai.model import RegisteredModel

# Obtain the Mixtral-8x7B-Instruct-v0.1 model from Model Gallery.
m = RegisteredModel(
    model_name="Mixtral-8x7B-Instruct-v0.1",
    model_provider="pai",
)

# Obtain the fine-tuning algorithm for the model.
est = m.get_estimator()

# View the hyperparameters supported by the algorithm and the input and output information of the algorithm.
print(est.hyperparameter_definitions)
print(est.input_channel_definitions)

Mixtral-8x7B-Instruct-v0.1モデルによって提供される微調整アルゴリズムは、Lingjunリソースのみをサポートします。 現在のリソースクォータのIDを取得し、PAIコンソールでトレーニングジョブに必要なリソース情報を設定する必要があります。 トレーニングジョブを送信する前に、トレーニングジョブに適切なハイパーパラメーターを設定できます。

# Configure the ID of the Lingjun resource quota used by the training job.
est.resource_id = "<LingjunResourceQuotaId>"

# Configure hyperparameters for the training job.
hps = {
    "learning_rate": 1e-5,
    "per_device_train_batch_size": 2,
}

est.set_hyperparameters(**hps)

微調整アルゴリズムは、次の入力をサポートします。

  • model: 事前にトレーニングされたMixtral-8x7B-Instruct-v0.1モデル。

  • train: モデルトレーニングに使用されるトレーニングデータセット。

  • validation: モデルトレーニングに使用される検証データセット。

データセットの形式については、「モデルのトレーニング」をご参照ください。 PAIコンソールまたはOSSUtilsを使用して、オブジェクトをOSSバケットにアップロードできます。 SDKを使用して、オブジェクトをOSSバケットにアップロードすることもできます。

from pai.common.oss_utils import upload
# View the input information of the fine-tuning algorithm.

# Obtain the input data of the fine-tuning algorithm, including the model and the public-read dataset for model training.
training_inputs = m.get_estimator_inputs()
print(training_inputs)
# {
#     "model": "oss://pai-quickstart-cn-wulanchabu.oss-cn-wulanchabu-internal.aliyuncs.com/huggingface/models/Mixtral-8x7B-Instruct-v0.1/main/",
#     "train": "oss://pai-quickstart-cn-wulanchabu.oss-cn-wulanchabu-internal.aliyuncs.com/huggingface/datasets/llm_instruct/en_poetry_train_mixtral.json",
#     "validation": "oss://pai-quickstart-cn-wulanchabu.oss-cn-wulanchabu-internal.aliyuncs.com/huggingface/datasets/llm_instruct/en_poetry_test_mixtral.json",
# }

# Upload user data. Use the actual on-premises file path and OSS bucket path.
train_data_uri = upload("/path/to/local/train.json", "path/of/train/data")
validation_data_uri = upload("/path/to/local/validation.json", "path/of/validation/data")


# Use the developer training data.
# training_inputs["train"] = train_data_uri
# training_inputs["validation"] = validation_data_uri

上記のトレーニングデータ形式を参照して、データを準備できます。 トレーニング検証をトレーニングと検証のデータセットに置き換えて、トレーニングジョブを送信します。 PAI SDK for Pythonが提供するトレーニングジョブのURLを使用して、PAIコンソールでトレーニングジョブのステータスとログを表示できます。 TensorBoardを使用して、トレーニングジョブの進行状況とモデルコンバージェンスを表示することもできます。

from pai.common.oss_utils import download


# Submit the training job and print the URL of the training job.
est.fit(
    inputs=training_inputs,
    wait=False,
)

# Open TensorBoard to view the training progress.
est.tensorboard()

# Wait for the training job to complete.
est.wait()

# View the model path saved in the OSS bucket.
print(est.model_data())

# You can download the model to your on-premises machine by using OSSUtils or a convenient method provided by PAI SDK for Python.
download(est.model_data())

Python用PAI SDKを使用してモデルギャラリーで事前トレーニング済みモデルを使用する方法の詳細については、「Python用PAI SDKで事前トレーニング済みモデルを使用する」をご参照ください。

関連ドキュメント