notebooks/sagemaker/deploy-mixtral-8x7b.ipynb (425 lines of code) (raw):
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Deploy Mixtral 8x7B on AWS Inferentia2\n",
"\n",
"Mixtral 8x7B is an open-source LLM from Mistral AI. It is a Sparse Mixture of Experts and has a similar architecture to Mistral 7B, but comes with a twist: it’s actually 8 “expert” models in one. If you want to learn more about MoEs check out [Mixture of Experts Explained](https://huggingface.co/blog/moe).\n",
"\n",
"In this tutorial you will learn how to deploy [mistralai/Mixtral-8x7B-Instruct-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) model on AWS Inferentia2 with Hugging Face Optimum Neuron on Amazon SageMaker. We are going to use the Hugging Face TGI Neuron Container, a purpose-built Inference Container to easily deploy LLMs on AWS Inferentia2 powered by [Text Generation Inference](https://huggingface.co/docs/text-generation-inference/index) and [Optimum Neuron](https://huggingface.co/docs/optimum-neuron/index).\n",
"\n",
"\n",
"We will cover how to:\n",
"1. [Setup a development environment](#1-setup-development-environment)\n",
"2. [Retrieve the latest Hugging Face TGI Neuron DLC](#2-retrieve-the-latest-hugging-face-tgi-neuron-dlc)\n",
"3. [Deploy Mixtral 8x7B to Inferentia2](#3-deploy-Mixtral-8x7B-to-inferentia2)\n",
"4. [Clean up](#4-clean-up)\n",
"\n",
"Lets get started! 🚀\n",
"\n",
"[AWS inferentia (Inf2)](https://aws.amazon.com/ec2/instance-types/inf2/) are purpose-built EC2 for deep learning (DL) inference workloads. Here are the different instances of the Inferentia2 family.\n",
"\n",
"| instance size | accelerators | Neuron Cores | accelerator memory | vCPU | CPU Memory | on-demand price ($/h) |\n",
"| ------------- | ------------ | ------------ | ------------------ | ---- | ---------- | --------------------- |\n",
"| inf2.xlarge | 1 | 2 | 32 | 4 | 16 | 0.76 |\n",
"| inf2.8xlarge | 1 | 2 | 32 | 32 | 128 | 1.97 |\n",
"| inf2.24xlarge | 6 | 12 | 192 | 96 | 384 | 6.49 |\n",
"| inf2.48xlarge | 12 | 24 | 384 | 192 | 768 | 12.98 |\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Setup development environment\n",
"\n",
"For this tutorial, we are going to use a Notebook Instance in Amazon SageMaker with the Python 3 (ipykernel) and the `sagemaker` python SDK to deploy Mixtral 8x7B to a SageMaker inference endpoint.\n",
"\n",
"Make sur you have the latest version of the SageMaker SDK installed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install sagemaker --upgrade --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then, instantiate the sagemaker role and session."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"metadata": {}
},
"outputs": [],
"source": [
"import sagemaker\n",
"import boto3\n",
"sess = sagemaker.Session()\n",
"# sagemaker session bucket -> used for uploading data, models and logs\n",
"# sagemaker will automatically create this bucket if it not exists\n",
"sagemaker_session_bucket=None\n",
"if sagemaker_session_bucket is None and sess is not None:\n",
" # set to default bucket if a bucket name is not given\n",
" sagemaker_session_bucket = sess.default_bucket()\n",
"\n",
"try:\n",
" role = sagemaker.get_execution_role()\n",
"except ValueError:\n",
" iam = boto3.client('iam')\n",
" role = iam.get_role(RoleName='sagemaker_execution_role')['Role']['Arn']\n",
"\n",
"sess = sagemaker.Session(default_bucket=sagemaker_session_bucket)\n",
"\n",
"print(f\"sagemaker role arn: {role}\")\n",
"print(f\"sagemaker session region: {sess.boto_region_name}\")\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Retrieve the latest Hugging Face TGI Neuron DLC\n",
"\n",
"The latest Hugging Face TGI Neuron DLCs can be used to run inference on AWS Inferentia2. You can use the `get_huggingface_llm_image_uri` method of the `sagemaker` SDK to retrieve the appropriate Hugging Face TGI Neuron DLC URI based on your desired `backend`, `session`, `region`, and `version`. You can find the latest version of the container [here](https://huggingface.co/docs/optimum-neuron/containers), if not yet added to the SageMaker SDK."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"metadata": {}
},
"outputs": [],
"source": [
"from sagemaker.huggingface import get_huggingface_llm_image_uri\n",
" \n",
"# retrieve the llm image uri\n",
"llm_image = get_huggingface_llm_image_uri(\n",
" \"huggingface-neuronx\",\n",
")\n",
" \n",
"# print ecr image uri\n",
"print(f\"llm image uri: {llm_image}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Deploy Mixtral 8x7B to Inferentia2\n",
"\n",
"At the time of writing, [AWS Inferentia2 does not support dynamic shapes for inference](https://awsdocs-neuron.readthedocs-hosted.com/en/v2.6.0/general/arch/neuron-features/dynamic-shapes.html#neuron-dynamic-shapes), which means that we need to specify our sequence length and batch size ahead of time.\n",
"To make it easier for customers to utilize the full power of Inferentia2, we created a [neuron model cache](https://huggingface.co/docs/optimum-neuron/guides/cache_system), which contains pre-compiled configurations for the most popular LLMs, including Mixtral 8x7B. \n",
"\n",
"This means we don't need to compile the model ourselves, but we can use the pre-compiled model from the cache. You can find compiled/cached configurations on the\n",
" [Hugging Face Hub](https://huggingface.co/aws-neuron/optimum-neuron-cache/tree/main/inference-cache-config). If your desired configuration is not yet cached, you can compile it yourself using the [Optimum CLI](https://huggingface.co/docs/optimum-neuron/guides/export_model) or open a request at the [Cache repository](https://huggingface.co/aws-neuron/optimum-neuron-cache/discussions).\n",
"\n",
" Let's check the different configurations that are in the cache. For that you first need to log in the Hugging Face Hub, using a [User Access Token](https://huggingface.co/docs/hub/en/security-tokens) with read access.\n",
"\n",
"Make sure you have the necessary permissions to access the model. You can request access to the model [here](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from huggingface_hub import notebook_login\n",
"\n",
"notebook_login()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then, we need to install the latest version of Optimum Neuron."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install optimum-neuron --upgrade --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, we can query the cache and retrieve the existing set of configurations for which we maintained a compiled version of the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"HF_MODEL_ID = \"mistralai/Mixtral-8x7B-Instruct-v0.1\"\n",
"\n",
"!optimum-cli neuron cache lookup $HF_MODEL_ID"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You should retrieve two entries in the cache:\n",
"```code\n",
"*** 2 entrie(s) found in cache for mistralai/Mixtral-8x7B-Instruct-v0.1 for inference.***\n",
"\n",
"auto_cast_type: bf16\n",
"batch_size: 1\n",
"checkpoint_id: mistralai/Mixtral-8x7B-Instruct-v0.1\n",
"checkpoint_revision: 41bd4c9e7e4fb318ca40e721131d4933966c2cc1\n",
"compiler_type: neuronx-cc\n",
"compiler_version: 2.16.372.0+4a9b2326\n",
"num_cores: 24\n",
"sequence_length: 4096\n",
"task: text-generation\n",
"\n",
"auto_cast_type: bf16\n",
"batch_size: 4\n",
"checkpoint_id: mistralai/Mixtral-8x7B-Instruct-v0.1\n",
"checkpoint_revision: 41bd4c9e7e4fb318ca40e721131d4933966c2cc1\n",
"compiler_type: neuronx-cc\n",
"compiler_version: 2.16.372.0+4a9b2326\n",
"num_cores: 24\n",
"sequence_length: 4096\n",
"task: text-generation\n",
"```"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"**Deploying Mixtral 8x7B to a SageMaker Endpoint** \n",
"\n",
"Before deploying the model to Amazon SageMaker, we must define the TGI Neuron endpoint configuration. We need to make sure the following additional parameters are defined: \n",
"\n",
"- `HF_NUM_CORES`: Number of Neuron Cores used for the compilation.\n",
"- `HF_BATCH_SIZE`: The batch size that was used to compile the model.\n",
"- `HF_SEQUENCE_LENGTH`: The sequence length that was used to compile the model.\n",
"- `HF_AUTO_CAST_TYPE`: The auto cast type that was used to compile the model.\n",
"\n",
"We still need to define traditional TGI parameters with:\n",
"\n",
"- `HF_MODEL_ID`: The Hugging Face model ID.\n",
"- `HF_TOKEN`: The Hugging Face API token to access gated models.\n",
"- `MAX_BATCH_SIZE`: The maximum batch size that the model can handle, equal to the batch size used for compilation.\n",
"- `MAX_INPUT_TOKEN`: The maximum input length that the model can handle. \n",
"- `MAX_TOTAL_TOKENS`: The maximum total tokens the model can generate, equal to the sequence length used for compilation.\n",
"\n",
"Optionnaly, you can configure the endpoint to support chat templates:\n",
"- `MESSAGES_API_ENABLED`: Enable Messages API \n",
"\n",
"**Select the right instance type**\n",
"\n",
"Mixtral 8x7B is a large model and requires a lot of memory. We are going to use the `inf2.48xlarge` instance type, which has 192 vCPUs and 384 GB of accelerator memory. The `inf2.48xlarge` instance comes with 12 Inferentia2 accelerators that include 24 Neuron Cores. In our case we will use a batch size of 4 and a sequence length of 4096. \n",
"\n",
"After that we can create our endpoint configuration and deploy the model to Amazon SageMaker. We will deploy the endpoint with the Messages API enabled, so that it is fully compatible with the OpenAI Chat Completion API."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"metadata": {}
},
"outputs": [],
"source": [
"from sagemaker.huggingface import HuggingFaceModel\n",
"\n",
"# sagemaker config\n",
"instance_type = \"ml.inf2.48xlarge\"\n",
"health_check_timeout = 2400 # additional time to load the model\n",
"volume_size = 512 # size in GB of the EBS volume\n",
"\n",
"# Define Model and Endpoint configuration parameter\n",
"config = {\n",
" \"HF_MODEL_ID\": \"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n",
" \"HF_NUM_CORES\": \"24\", # number of neuron cores\n",
" \"HF_AUTO_CAST_TYPE\": \"bf16\", # dtype of the model\n",
" \"MAX_BATCH_SIZE\": \"4\", # max batch size for the model\n",
" \"MAX_INPUT_TOKENS\": \"4000\", # max length of input text\n",
" \"MAX_TOTAL_TOKENS\": \"4096\", # max length of generated text\n",
" \"MESSAGES_API_ENABLED\": \"true\", # Enable the messages API\n",
" \"HF_TOKEN\": \"<REPLACE WITH YOUR TOKEN>\",\n",
"}\n",
"\n",
"assert (\n",
" config[\"HF_TOKEN\"] != \"<REPLACE WITH YOUR TOKEN>\"\n",
"), \"Please replace '<REPLACE WITH YOUR TOKEN>' with your Hugging Face Hub API token\"\n",
"\n",
"\n",
"# create HuggingFaceModel with the image uri\n",
"llm_model = HuggingFaceModel(role=role, image_uri=llm_image, env=config)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"After we have created the `HuggingFaceModel` we can deploy it to Amazon SageMaker using the `deploy` method. We will deploy the model with the `ml.inf2.48xlarge` instance type. TGI will automatically distribute and shard the model across all Inferentia devices."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"metadata": {}
},
"outputs": [],
"source": [
"# Deploy model to an endpoint\n",
"# https://sagemaker.readthedocs.io/en/stable/api/inference/model.html#sagemaker.model.Model.deploy\n",
"llm_model._is_compiled_model = True\n",
" \n",
"llm = llm_model.deploy(\n",
" initial_instance_count=1,\n",
" instance_type=instance_type,\n",
" container_startup_health_check_timeout=health_check_timeout,\n",
" volume_size=volume_size\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"SageMaker will now create our endpoint and deploy the model to it. It takes around 15 minutes for deployment."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"After our endpoint is deployed we can run inference on it. We will use the `predict` method from the `predictor` to run inference on our endpoint. \n",
"\n",
"The endpoint supports the Messages API, which is fully compatible with the OpenAI Chat Completion API. The Messages API allows us to interact with the model in a conversational way. We can define the role of the message and the content. The role can be either `system`,`assistant` or `user`. The `system` role is used to provide context to the model and the `user` role is used to ask questions or provide input to the model.\n",
"\n",
"Parameters can be defined as in the `parameters` attribute of the payload. Check out the chat completion [documentation](https://platform.openai.com/docs/api-reference/chat/create) to find supported parameters.\n",
"\n",
"```json\n",
"{\n",
" \"messages\": [\n",
" { \"role\": \"system\", \"content\": \"You are a helpful assistant.\" },\n",
" { \"role\": \"user\", \"content\": \"What is deep learning?\" }\n",
" ]\n",
"}\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"metadata": {}
},
"outputs": [],
"source": [
"# Prompt to generate\n",
"messages = [\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
" {\"role\": \"user\", \"content\": \"What is deep learning in one sentence?\"},\n",
"]\n",
"\n",
"# Generation arguments https://platform.openai.com/docs/api-reference/chat/create\n",
"parameters = {\n",
" \"max_tokens\": 100,\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay lets test it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"metadata": {}
},
"outputs": [],
"source": [
"chat = llm.predict({\"messages\": messages, **parameters, \"steam\": True})\n",
"\n",
"print(chat[\"choices\"][0][\"message\"][\"content\"].strip())"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Clean up\n",
"\n",
"To clean up, we can delete the model and endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"llm.delete_model()\n",
"llm.delete_endpoint()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "hf",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "5fcf248a74081676ead7e77f54b2c239ba2921b952f7cbcdbbe5427323165924"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}