From 6ac5bb28dcbe29e16d3cb8fe7169cabe1c6f34eb Mon Sep 17 00:00:00 2001 From: Qingwei Li Date: Fri, 9 Sep 2022 14:46:54 -0400 Subject: [PATCH 1/4] Add GPT large inference notebook (#3594) * CLI upgrade * reformat * grammatical changes Co-authored-by: Qingwei Li Co-authored-by: atqy --- ...PT-J-6B-model-parallel-inference-DJL.ipynb | 441 ++++++++++++++++++ 1 file changed, 441 insertions(+) create mode 100644 advanced_functionality/pytorch_deploy_large_GPT_model/GPT-J-6B-model-parallel-inference-DJL.ipynb diff --git a/advanced_functionality/pytorch_deploy_large_GPT_model/GPT-J-6B-model-parallel-inference-DJL.ipynb b/advanced_functionality/pytorch_deploy_large_GPT_model/GPT-J-6B-model-parallel-inference-DJL.ipynb new file mode 100644 index 0000000000..d979d03d7d --- /dev/null +++ b/advanced_functionality/pytorch_deploy_large_GPT_model/GPT-J-6B-model-parallel-inference-DJL.ipynb @@ -0,0 +1,441 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "bc5ab391", + "metadata": {}, + "source": [ + "# Serve large models on SageMaker with model parallel inference and DJLServing" + ] + }, + { + "cell_type": "markdown", + "id": "98b43ca5", + "metadata": {}, + "source": [ + "In this notebook, we explore how to host a large language model on SageMaker using model parallelism from DeepSpeed and DJLServing.\n", + "\n", + "Language models have recently exploded in both size and popularity. In 2018, BERT-large entered the scene and, with its 340M parameters and novel transformer architecture, set the standard on NLP task accuracy. Within just a few years, state-of-the-art NLP model size has grown by more than 500x with models such as OpenAI’s 175 billion parameter GPT-3 and similarly sized open source Bloom 176B raising the bar on NLP accuracy. This increase in the number of parameters is driven by the simple and empirically-demonstrated positive relationship between model size and accuracy: more is better. With easy access from models zoos such as Hugging Face and improved accuracy in NLP tasks such as classification and text generation, practitioners are increasingly reaching for these large models. However, deploying them can be a challenge because of their size.\n", + "\n", + "Model parallelism can help deploy large models that would normally be too large for a single GPU. With model parallelism, we partition and distribute a model across multiple GPUs. Each GPU holds a different part of the model, resolving the memory capacity issue for the largest deep learning models with billions of parameters. This notebook uses tensor parallelism techniques which allow GPUs to work simultaneously on the same layer of a model and achieve low latency inference relative to a pipeline parallel solution.\n", + "\n", + "In this notebook, we deploy a PyTorch GPT-J model from Hugging Face with 6 billion parameters across two GPUs on an Amazon SageMaker ml.g5.48xlarge instance. DeepSpeed is used for tensor parallelism inference while DJLServing handles inference requests and the distributed workers. " + ] + }, + { + "cell_type": "markdown", + "id": "81c2bdf4", + "metadata": {}, + "source": [ + "## Step 1: Creating image for SageMaker endpoint\n", + "We first pull the docker image djl-serving:0.18.0-deepspeed" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2876d11c", + "metadata": {}, + "outputs": [], + "source": [ + "%%sh\n", + "docker pull deepjavalibrary/djl-serving:0.18.0-deepspeed" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "73d0ff93", + "metadata": {}, + "outputs": [], + "source": [ + "!docker images" + ] + }, + { + "cell_type": "markdown", + "id": "e822977b", + "metadata": {}, + "source": [ + "You should see the image `djl-serving` listed from running the code above. Please note the `IMAGE ID`. We will need it for the next step." + ] + }, + { + "cell_type": "markdown", + "id": "6c695144", + "metadata": {}, + "source": [ + "### Push image to ECR\n", + "The following code pushes the `djl-serving` image, downloaded from previous step, to ECR. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "47ab31d1", + "metadata": { + "scrolled": true + }, + "outputs": [], + "source": [ + "%%sh\n", + "\n", + "# The name of our container\n", + "img=djl_deepspeed\n", + "\n", + "\n", + "account=$(aws sts get-caller-identity --query Account --output text)\n", + "\n", + "# Get the region defined in the current configuration\n", + "region=$(aws configure get region)\n", + "\n", + "fullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${img}:latest\"\n", + "\n", + "# If the repository doesn't exist in ECR, create it.\n", + "aws ecr describe-repositories --repository-names \"${img}\" > /dev/null 2>&1\n", + "\n", + "if [ $? -ne 0 ]\n", + "then\n", + " aws ecr create-repository --repository-name \"${img}\" > /dev/null\n", + "fi\n", + "\n", + "# Get the login command from ECR and execute it directly\n", + "aws ecr get-login-password --region ${region}|docker login --username AWS --password-stdin ${fullname}\n", + "\n", + "\n", + "# # Build the docker image locally with the image name and then push it to ECR\n", + "image_id=$(docker images -q | head -n1)\n", + "docker tag $image_id ${fullname}\n", + "\n", + "docker push $fullname" + ] + }, + { + "cell_type": "markdown", + "id": "1ac32e96", + "metadata": {}, + "source": [ + "## Step 2: Create a `model.py` and `serving.properties`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6f4864eb", + "metadata": {}, + "outputs": [], + "source": [ + "%%writefile model.py\n", + "\n", + "from djl_python import Input, Output\n", + "import os\n", + "import deepspeed\n", + "import torch\n", + "from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer\n", + "\n", + "predictor = None\n", + "\n", + "\n", + "def get_model():\n", + " model_name = \"EleutherAI/gpt-j-6B\"\n", + " tensor_parallel = int(os.getenv(\"TENSOR_PARALLEL_DEGREE\", \"2\"))\n", + " local_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\n", + " model = AutoModelForCausalLM.from_pretrained(\n", + " model_name, revision=\"float32\", torch_dtype=torch.float32\n", + " )\n", + " tokenizer = AutoTokenizer.from_pretrained(model_name)\n", + "\n", + " model = deepspeed.init_inference(\n", + " model,\n", + " mp_size=tensor_parallel,\n", + " dtype=model.dtype,\n", + " replace_method=\"auto\",\n", + " replace_with_kernel_inject=True,\n", + " )\n", + " generator = pipeline(\n", + " task=\"text-generation\", model=model, tokenizer=tokenizer, device=local_rank\n", + " )\n", + " return generator\n", + "\n", + "\n", + "def handle(inputs: Input) -> None:\n", + " global predictor\n", + " if not predictor:\n", + " predictor = get_model()\n", + "\n", + " if inputs.is_empty():\n", + " # Model server makes an empty call to warmup the model on startup\n", + " return None\n", + "\n", + " data = inputs.get_as_string()\n", + " result = predictor(data, do_sample=True, min_tokens=200, max_new_tokens=256)\n", + " return Output().add(result)" + ] + }, + { + "cell_type": "markdown", + "id": "f02b6929", + "metadata": {}, + "source": [ + "### Setup serving.properties\n", + "\n", + "User needs to add engine Rubikon as shown below. If you would like to control how many worker groups, you can set\n", + "\n", + "```\n", + "gpu.minWorkers=1\n", + "gpu.maxWorkers=1\n", + "```\n", + "by adding these lines in the below file. By default, we will create as much worker group as possible based on `gpu_numbers/tensor_parallel_degree`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2c5ea96a", + "metadata": {}, + "outputs": [], + "source": [ + "%%writefile serving.properties\n", + "\n", + "engine = Rubikon" + ] + }, + { + "cell_type": "markdown", + "id": "f44488e6", + "metadata": {}, + "source": [ + "The code below creates the SageMaker model file (`model.tar.gz`) and upload it to S3. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5a536439", + "metadata": {}, + "outputs": [], + "source": [ + "import sagemaker, boto3\n", + "\n", + "session = sagemaker.Session()\n", + "account = session.account_id()\n", + "region = session.boto_region_name\n", + "img = \"djl_deepspeed\"\n", + "fullname = account + \".dkr.ecr.\" + region + \"amazonaws.com/\" + img + \":latest\"\n", + "\n", + "bucket = session.default_bucket()\n", + "path = \"s3://\" + bucket + \"/DEMO-djl-big-model/\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9965dd7c", + "metadata": {}, + "outputs": [], + "source": [ + "%%sh\n", + "if [ -d gpt-j ]; then\n", + " rm -d -r gpt-j\n", + "fi #always start fresh\n", + "\n", + "mkdir -p gpt-j\n", + "mv model.py gpt-j\n", + "mv serving.properties gpt-j\n", + "tar -czvf gpt-j.tar.gz gpt-j/\n", + "#aws s3 cp gpt-j.tar.gz {path}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "db47f969", + "metadata": {}, + "outputs": [], + "source": [ + "!aws s3 cp gpt-j.tar.gz {path}" + ] + }, + { + "cell_type": "markdown", + "id": "c507e3ef", + "metadata": {}, + "source": [ + "## Step 3: Create SageMaker endpoint" + ] + }, + { + "cell_type": "markdown", + "id": "f96c494a", + "metadata": {}, + "source": [ + "First let us make sure we have the lastest awscli" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0b665515", + "metadata": {}, + "outputs": [], + "source": [ + "!pip3 install --upgrade --user awscli" + ] + }, + { + "cell_type": "markdown", + "id": "32589338", + "metadata": {}, + "source": [ + "You should see two images from code above. Please note the image name similar to`.dkr.ecr.us-east-1.amazonaws.com/djl_deepspeed`. This is the ECR image URL that we need for later use. \n", + "\n", + "Now we create our [SageMaker model](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html). Make sure you provide an IAM role that SageMaker can assume to access model artifacts and docker image for deployment on ML compute hosting instances. In addition, you also use the IAM role to manage permissions the inference code needs. Please check out our SageMaker Roles [documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) for more details. \n", + "\n", + " You must enter ECR image name, S3 path for the model file, and an execution-role-arn in the code below." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "026d27d2", + "metadata": {}, + "outputs": [], + "source": [ + "!aws sagemaker create-model \\\n", + "--model-name gpt-j \\\n", + "--primary-container \\\n", + "Image=,ModelDataUrl={path},Environment={TENSOR_PARALLEL_DEGREE=2} \\\n", + "--execution-role-arn " + ] + }, + { + "cell_type": "markdown", + "id": "22d2fc2b", + "metadata": {}, + "source": [ + "Note that we configure `ModelDataDownloadTimeoutInSeconds` and `ContainerStartupHealthCheckTimeoutInSeconds` to acommodate the large size of our model. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84e25dd4", + "metadata": {}, + "outputs": [], + "source": [ + "%%sh\n", + "aws sagemaker create-endpoint-config \\\n", + " --region $(aws configure get region) \\\n", + " --endpoint-config-name gpt-j-config \\\n", + " --production-variants '[\n", + " {\n", + " \"ModelName\": \"gpt-j\",\n", + " \"VariantName\": \"AllTraffic\",\n", + " \"InstanceType\": \"ml.g5.48xlarge\",\n", + " \"InitialInstanceCount\": 1,\n", + " \"ModelDataDownloadTimeoutInSeconds\": 1800,\n", + " \"ContainerStartupHealthCheckTimeoutInSeconds\": 3600\n", + " }\n", + " ]'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "962a1aef", + "metadata": {}, + "outputs": [], + "source": [ + "%%sh\n", + "aws sagemaker create-endpoint \\\n", + "--endpoint-name gpt-j \\\n", + "--endpoint-config-name gpt-j-config" + ] + }, + { + "cell_type": "markdown", + "id": "2dc2a85a", + "metadata": {}, + "source": [ + "The creation of the SageMaker endpoint might take a while. After the endpoint is created, you can test it out using the following code. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ed7a325", + "metadata": {}, + "outputs": [], + "source": [ + "import boto3, json\n", + "\n", + "client = boto3.client(\"sagemaker-runtime\")\n", + "\n", + "endpoint_name = \"gpt-j\" # Your endpoint name.\n", + "content_type = \"text/plain\" # The MIME type of the input data in the request body.\n", + "payload = \"Amazon.com is the best\" # Payload for inference.\n", + "response = client.invoke_endpoint(\n", + " EndpointName=endpoint_name, ContentType=content_type, Body=payload\n", + ")\n", + "print(response[\"Body\"].read())" + ] + }, + { + "cell_type": "markdown", + "id": "92e83c91", + "metadata": {}, + "source": [ + "## Step 4: Clean up" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a15980a3", + "metadata": {}, + "outputs": [], + "source": [ + "%%sh\n", + "aws sagemaker delete-endpoint --endpoint-name gpt-j" + ] + }, + { + "cell_type": "markdown", + "id": "2eff050b", + "metadata": {}, + "source": [ + "## Conclusion\n", + "\n", + "In this notebook, you use tensor parallelism to partition a large language model across multiple GPUs for low latency inference. With tensor parallelism, multiple GPUs work on the same model layer at once allowing for faster inference latency when a low batch size is used. Here, we use open source DeepSpeed as the model parallel library to partition the model and open source Deep Java Library Serving as the model serving solution.\n", + "\n", + "As a next step, you can experiment with larger models from Hugging Face such as GPT-NeoX. You can also adjust the tensor parallel degree to see the impact to latency with models of different sizes." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3.8.9 64-bit", + "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.8.9" + }, + "vscode": { + "interpreter": { + "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 81ee21f2acd53b70e4aad0d62cd08ccb33c80a4c Mon Sep 17 00:00:00 2001 From: Loki Date: Mon, 12 Sep 2022 09:54:16 -0700 Subject: [PATCH 2/4] Updating Training Compiler Single Node Multi GPU notebook to use HF-PT 1.11 (#3593) * Adding new CV notebook for distributed training with PT 1.11 * Upgrading notebook to demonstrate PT 1.11 capabilities * Removing stale files * Renaming notebook * Retry tests * Upgrading numpy and pandas installation * Minor correction in wording --- .../gpt-2.ipynb} | 341 +++++----- .../scripts/requirements.txt | 2 + .../scripts/run_clm.py | 0 .../scripts/launch_pt_dt_sm_native.py | 34 - .../scripts/launch_sm_training_compiler.py | 9 - .../scripts/run_mlm.py | 600 ------------------ 6 files changed, 175 insertions(+), 811 deletions(-) rename sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/{language-modeling-multi-gpu-single-node.ipynb => language-modeling/gpt-2.ipynb} (71%) create mode 100644 sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/scripts/requirements.txt rename sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/{ => language-modeling}/scripts/run_clm.py (100%) delete mode 100644 sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/launch_pt_dt_sm_native.py delete mode 100644 sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/launch_sm_training_compiler.py delete mode 100644 sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/run_mlm.py diff --git a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling-multi-gpu-single-node.ipynb b/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/gpt-2.ipynb similarity index 71% rename from sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling-multi-gpu-single-node.ipynb rename to sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/gpt-2.ipynb index 6c4ff1b8aa..c68f7f0089 100644 --- a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling-multi-gpu-single-node.ipynb +++ b/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/gpt-2.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "c5608edd", + "id": "aa619cfc", "metadata": {}, "source": [ "# Compile and Train the GPT2 Model using the Transformers Trainer API with the SST2 Dataset for Single-Node Multi-GPU Training" @@ -10,7 +10,7 @@ }, { "cell_type": "markdown", - "id": "ec894c6c", + "id": "2f479baf", "metadata": {}, "source": [ "1. [Introduction](#Introduction) \n", @@ -25,7 +25,7 @@ }, { "cell_type": "markdown", - "id": "9e9d46c4", + "id": "83e922ff", "metadata": {}, "source": [ "## SageMaker Training Compiler Overview\n", @@ -40,14 +40,14 @@ "\n", "In this demo, you'll use Hugging Face's `transformers` and `datasets` libraries with Amazon SageMaker Training Compiler to train the `gpt-2` model on the `Stanford Sentiment Treebank v2 (SST2)` dataset. To get started, we need to set up the environment with a few prerequisite steps, for permissions, configurations, and so on. \n", "\n", - "**NOTE:** You can run this demo in SageMaker Studio, SageMaker notebook instances, or your local machine with AWS CLI set up. If using SageMaker Studio or SageMaker notebook instances, make sure you choose one of the PyTorch-based kernels, `Python 3 (PyTorch x.y Python 3.x CPU Optimized)` or `conda_pytorch_p36` respectively.\n", + "**NOTE:** You can run this demo in SageMaker Studio, SageMaker notebook instances, or your local machine with AWS CLI set up. If using SageMaker Studio or SageMaker notebook instances, make sure you choose one of the PyTorch-based kernels, `Python 3 (PyTorch x.y Python 3.x CPU Optimized)` or `conda_pytorch_p38` respectively.\n", "\n", - "**NOTE:** This notebook uses two `ml.p3.8xlarge` instances that have multiple GPUs. If you don't have enough quota, see [Request a service quota increase for SageMaker resources](https://docs.aws.amazon.com/sagemaker/latest/dg/regions-quotas.html#service-limit-increase-request-procedure). " + "**NOTE:** This notebook uses 2 `ml.g4dn.12xlarge` instances that have multiple GPUs. If you don't have enough quota, see [Request a service quota increase for SageMaker resources](https://docs.aws.amazon.com/sagemaker/latest/dg/regions-quotas.html#service-limit-increase-request-procedure). " ] }, { "cell_type": "markdown", - "id": "3977fe0f", + "id": "7bb2751c", "metadata": {}, "source": [ "## Development Environment " @@ -55,54 +55,44 @@ }, { "cell_type": "markdown", - "id": "dbc4930a", + "id": "b945c6f4", "metadata": {}, "source": [ "### Installation\n", "\n", - "This example notebook requires the **SageMaker Python SDK v2.70.0** and **transformers v4.11.0**." + "This example notebook requires the **SageMaker Python SDK v2.108.0**." ] }, { "cell_type": "code", "execution_count": null, - "id": "7045eb46", + "id": "37613be5", "metadata": {}, "outputs": [], "source": [ - "!pip install --force-reinstall sagemaker==2.70.0" + "!pip install \"sagemaker>=2.108.0\" botocore boto3 awscli pandas numpy --upgrade" ] }, { "cell_type": "code", "execution_count": null, - "id": "25f110f1", - "metadata": {}, - "outputs": [], - "source": [ - "!pip install transformers==4.11.0" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f7a8ceb9", + "id": "5bed8ad5", "metadata": {}, "outputs": [], "source": [ "import botocore\n", "import boto3\n", "import sagemaker\n", - "import transformers\n", "import pandas as pd\n", "\n", "print(f\"sagemaker: {sagemaker.__version__}\")\n", - "print(f\"transformers: {transformers.__version__}\")" + "print(f\"boto3: {boto3.__version__}\")\n", + "print(f\"botocore: {botocore.__version__}\")" ] }, { "cell_type": "markdown", - "id": "6bcc3a46", + "id": "51a693fa", "metadata": {}, "source": [ "Copy and run the following code if you need to upgrade IPython widgets for `datasets` library and restart kernel. This is only needed when preprocessing is done in the notebook.\n", @@ -118,7 +108,7 @@ }, { "cell_type": "markdown", - "id": "5e5c0cdb", + "id": "5a4f105f", "metadata": {}, "source": [ "### SageMaker environment " @@ -127,7 +117,7 @@ { "cell_type": "code", "execution_count": null, - "id": "655beb77", + "id": "8a56b484", "metadata": {}, "outputs": [], "source": [ @@ -152,129 +142,148 @@ }, { "cell_type": "markdown", - "id": "12032413", + "id": "97e3b0d2", "metadata": {}, "source": [ "## SageMaker Training Job\n", "\n", - "To create a SageMaker training job, we use a `HuggingFace` estimator. Using the estimator, you can define which fine-tuning script should SageMaker use through `entry_point`, which `instance_type` to use for training, which `hyperparameters` to pass, and so on.\n", + "To create a SageMaker training job, we use an estimator. We use a `HuggingFace` estimator for SageMaker Training Compiler. Using the estimator, you can define which training script should SageMaker use through `entry_point`, which `instance_type` to use for training, which `hyperparameters` to pass, and so on.\n", "\n", - "When a SageMaker training job starts, SageMaker takes care of starting and managing all the required machine learning instances, picks up the `HuggingFace` Deep Learning Container, uploads your training script, and downloads the data from `sagemaker_session_bucket` into the container at `/opt/ml/input/data`.\n", + "When a SageMaker training job starts, SageMaker takes care of starting and managing all the required machine learning instances, picks up the appropriate `HuggingFace` Deep Learning Container, uploads your training script, and downloads the data from `sagemaker_session_bucket` into the container at `/opt/ml/input/data`.\n", "\n", - "In the following section, you learn how to set up two versions of the SageMaker `HuggingFace` estimator, a native one without the compiler and an optimized one with the compiler." - ] - }, - { - "cell_type": "markdown", - "id": "5f608b6c", - "metadata": {}, - "source": [ - "### Training Setup" + "First, we define some basic parameters common to all estimators.\n", + "\n", + "**Note**: We recommend you to turn the SageMaker Debugger's profiling and debugging tools off to avoid additional overheads." ] }, { "cell_type": "code", "execution_count": null, - "id": "182822a2", + "id": "f8f50795", "metadata": {}, "outputs": [], "source": [ - "# Here we configure the training job. Please configure the appropriate options below:\n", - "EPOCHS = 100\n", - "\n", - "# Choose between Causal Language Model and Masked Language Model\n", - "LANGUAGE_MODELING_LOSS = \"clm\" # or \"mlm\"\n", - "\n", - "MODEL_NAME = \"gpt2\"\n", - "TOKENIZER_NAME = \"gpt2\"\n", - "MODEL_CONFIG = \"model_type\"\n", - "\n", - "# For more information about the options, please look into the training scripts\n", + "estimator_args = dict(\n", + " source_dir=\"scripts\",\n", + " entry_point=\"run_clm.py\",\n", + " instance_type=\"ml.g4dn.12xlarge\",\n", + " instance_count=1,\n", + " role=role,\n", + " py_version=\"py38\",\n", + " volume_size=100,\n", + " disable_profiler=True, # Disabling SageMaker Profiler to avoid overheads during benchmarking\n", + " debugger_hook_config=False, # Disabling SageMaker Debugger to avoid overheads during benchmarking\n", + " base_job_name=\"trcomp-pt-example\",\n", + " metric_definitions=[\n", + " {\"Name\": \"summary_train_runtime\", \"Regex\": \"'train_runtime': ([0-9.]*)\"},\n", + " {\n", + " \"Name\": \"summary_train_samples_per_second\",\n", + " \"Regex\": \"'train_samples_per_second': ([0-9.]*)\",\n", + " },\n", + " {\"Name\": \"summary_train_steps_per_second\", \"Regex\": \"'train_steps_per_second': ([0-9.]*)\"},\n", + " {\"Name\": \"summary_train_loss\", \"Regex\": \"'train_loss': ([0-9.]*)\"},\n", + " {\"Name\": \"epoch\", \"Regex\": \"'epoch': ([0-9.]*)\"},\n", + " {\"Name\": \"train_loss\", \"Regex\": \"'loss': ([0-9.]*)\"},\n", + " {\"Name\": \"learning_rate\", \"Regex\": \"'learning_rate': ([0-9.]*)\"},\n", + " ],\n", + ")\n", "\n", - "# SageMaker Training Compiler currently only supports training on GPU\n", - "# Select Instance type for training\n", - "INSTANCE_TYPE = \"ml.p3.8xlarge\" # ml.p3.8xlarge is easily available. However, p3.16xlarge provides better performance.\n", + "# Since ml.g4dn.12xlarge instance has 4 GPUs, we set num_gpus_per_instance to 4\n", "num_gpus_per_instance = 4" ] }, { "cell_type": "markdown", - "id": "03b85427", + "id": "6c2b1bb3", "metadata": {}, "source": [ - "### Training with Native PyTorch" - ] - }, - { - "cell_type": "markdown", - "id": "2b6e9683", - "metadata": {}, - "source": [ - "The batch size below is the maximum batch we could fit into the memory of a `ml.p3.8xlarge` instance. If you change the model, instance type, sequence length, and other parameters, you need to do some experiments to find the largest batch size that will fit into GPU memory.\n", - "\n", - "This example uses HuggingFace training script `run_clm.py`, which you can find it inside the `scripts` folder. \n", - "\n", - "To get the most performance out of the multi GPU configuration, we use a wrapper script to launch a single training process per GPU using `pytorch.distributed`. This allows us to get around the Python GIL bottleneck." + "Next, we define some basic arguments to be passed to the training script." ] }, { "cell_type": "code", "execution_count": null, - "id": "2d1efd5b", + "id": "db0f6871", "metadata": {}, "outputs": [], "source": [ - "from sagemaker.huggingface import HuggingFace\n", + "# Hyperparameters are passed to the training script as arguments.\n", "\n", - "# The original LR was set for a batch of 32. Here we scale learning_rate with an adjusted batch size and the number of GPUs per instance.\n", - "batch_size_native = 8\n", - "learning_rate_native = float(\"5e-5\") / 32 * batch_size_native * num_gpus_per_instance\n", - "\n", - "# hyperparameters are passed to the training entrypoint as arguments\n", "hyperparameters = {\n", - " \"training_script\": f\"run_{LANGUAGE_MODELING_LOSS}.py\",\n", - " MODEL_CONFIG: MODEL_NAME,\n", - " \"tokenizer_name\": TOKENIZER_NAME,\n", + " \"model_type\": \"gpt2\",\n", + " \"tokenizer_name\": \"gpt2\",\n", " \"dataset_name\": \"glue\",\n", " \"dataset_config_name\": \"sst2\",\n", " \"do_train\": True,\n", - " \"do_eval\": True,\n", + " \"do_eval\": False,\n", " \"fp16\": True,\n", - " \"per_device_train_batch_size\": batch_size_native,\n", - " \"learning_rate\": learning_rate_native,\n", - " \"per_device_eval_batch_size\": 16,\n", - " \"num_train_epochs\": EPOCHS,\n", + " \"per_device_eval_batch_size\": 8,\n", + " \"num_train_epochs\": 100,\n", " \"block_size\": 512,\n", " \"overwrite_output_dir\": True,\n", " \"save_strategy\": \"no\",\n", + " \"evaluation_strategy\": \"no\",\n", " \"logging_strategy\": \"epoch\",\n", " \"output_dir\": \"/opt/ml/model\",\n", - "}\n", + " \"dataloader_drop_last\": True,\n", + "}" + ] + }, + { + "cell_type": "markdown", + "id": "6b5204bc", + "metadata": {}, + "source": [ + "In the following sections, we will create estimators and start training.\n", "\n", - "# configure the training job\n", - "native_estimator = HuggingFace(\n", - " entry_point=\"launch_pt_dt_sm_native.py\",\n", - " source_dir=\"./scripts\",\n", - " instance_type=INSTANCE_TYPE,\n", - " instance_count=1,\n", - " role=role,\n", - " py_version=\"py38\",\n", - " transformers_version=\"4.11.0\",\n", - " pytorch_version=\"1.9.0\",\n", - " volume_size=100,\n", - " hyperparameters=hyperparameters,\n", - " disable_profiler=True, # Disabling SageMaker Profiler to avoid overheads during benchmarking\n", - " debugger_hook_config=False, # Disabling SageMaker Debugger to avoid overheads during benchmarking\n", + "### Training with Native PyTorch\n", + "\n", + "In the following sections, we will create estimators and start training.\n", + "\n", + "The `per_device_train_batch_size` below is the largest batch we could fit into the memory of a `ml.g4dn.12xlarge` instance. If you change the model, instance type, sequence length, or other parameters that affect memory consumption, you need to find the corresponding largest batch size.\n", + "\n", + "This example uses HuggingFace training script `run_clm.py`, which you can find it inside the `scripts` folder. \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8dbc83ab", + "metadata": {}, + "outputs": [], + "source": [ + "from sagemaker.pytorch import PyTorch\n", + "\n", + "# The original learning rate was set for a batch of 32. Here we scale learning rate linearly with an adjusted batch size\n", + "per_device_train_batch_size = 10\n", + "global_batch_size = (\n", + " per_device_train_batch_size * num_gpus_per_instance * estimator_args[\"instance_count\"]\n", + ")\n", + "learning_rate = float(\"5e-5\") / 32 * global_batch_size\n", + "\n", + "# Configure the training job\n", + "native_estimator = PyTorch(\n", + " framework_version=\"1.11\",\n", + " hyperparameters=dict(\n", + " **hyperparameters,\n", + " **{\n", + " \"per_device_train_batch_size\": per_device_train_batch_size,\n", + " \"learning_rate\": learning_rate,\n", + " },\n", + " ),\n", + " distribution={\"pytorchddp\": {\"enabled\": True}},\n", + " **estimator_args,\n", ")\n", "\n", - "# start the training job\n", + "# Start the training job\n", "native_estimator.fit(wait=False)\n", + "\n", "native_estimator.latest_training_job.name" ] }, { "cell_type": "markdown", - "id": "85e624f7", + "id": "2ef182d4", "metadata": {}, "source": [ "### Training with Optimized PyTorch" @@ -282,68 +291,55 @@ }, { "cell_type": "markdown", - "id": "d63763c1", + "id": "8c2011e0", "metadata": {}, "source": [ - "Compilation through Training Compiler changes the memory footprint of the model. Most commonly, this manifests as a reduction in memory utilization and a consequent increase in the largest batch size that can fit on the GPU. Note that if you want to change the batch size, you must adjust the learning rate appropriately.\n", - "\n", - "**Note:** We recommend you to turn the SageMaker Debugger's profiling and debugging tools off when you use compilation to avoid additional overheads.\n", + "Compilation through Training Compiler changes the memory footprint of the model. Most commonly, this manifests as a reduction in memory utilization and a consequent increase in the largest batch size that can fit on the GPU. Note that when you change the batch size, you must adjust the learning rate appropriately. Below, we have scaled the learning rate linearly with the increase in batch size.\n", "\n", - "Here, instead of using the `distribution` kwarg to launch a multi node training job, we use a wrapper script to set up an inter-node communication using `torch_xla.distributed.sm_dist`, which has been optimized to work with SageMaker Training Compiler." + "**Note:** We are using distribution mechanism `pytorchxla` which is a compiler aware method of distributed training.\n" ] }, { "cell_type": "code", "execution_count": null, - "id": "96d5450c", - "metadata": {}, - "outputs": [], - "source": [ - "!pygmentize ./scripts/launch_sm_training_compiler.py" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a1948135", + "id": "405d7bec", "metadata": {}, "outputs": [], "source": [ "from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig\n", "\n", - "# with SageMaker Training Compiler we are able to fit a larger batch into memory\n", - "hyperparameters[\"per_device_train_batch_size\"] = 22\n", - "\n", - "# The original LR was set for a batch of 32. Here we scale learning_rate with an adjusted batch size and the number of GPUs per instance.\n", - "hyperparameters[\"learning_rate\"] = (\n", - " float(\"5e-5\") / 32 * hyperparameters[\"per_device_train_batch_size\"] * num_gpus_per_instance\n", + "# The original learning rate was set for a batch of 32. Here we scale learning rate linearly with an adjusted batch size\n", + "new_per_device_train_batch_size = 20\n", + "global_batch_size = (\n", + " new_per_device_train_batch_size * num_gpus_per_instance * estimator_args[\"instance_count\"]\n", ")\n", + "learning_rate = float(\"5e-5\") / 32 * global_batch_size\n", "\n", - "# configure the training job\n", + "# Configure the training job\n", "optimized_estimator = HuggingFace(\n", - " entry_point=\"launch_sm_training_compiler.py\", # Wrapper around training script that enables multi GPU training\n", - " compiler_config=TrainingCompilerConfig(), # We are enabling SageMaker Training Compiler here !\n", - " source_dir=\"./scripts\",\n", - " instance_type=\"ml.p3.8xlarge\",\n", - " instance_count=1,\n", - " role=role,\n", - " volume_size=100,\n", - " py_version=\"py38\",\n", - " transformers_version=\"4.11.0\",\n", - " pytorch_version=\"1.9.0\",\n", - " hyperparameters=hyperparameters,\n", - " disable_profiler=True, # Disabling SageMaker Profiler to avoid overheads during benchmarking\n", - " debugger_hook_config=False, # Disabling SageMaker Debugger to avoid overheads during benchmarking\n", + " compiler_config=TrainingCompilerConfig(),\n", + " transformers_version=\"4.21\",\n", + " pytorch_version=\"1.11\",\n", + " hyperparameters=dict(\n", + " **hyperparameters,\n", + " **{\n", + " \"per_device_train_batch_size\": new_per_device_train_batch_size,\n", + " \"learning_rate\": learning_rate,\n", + " },\n", + " ),\n", + " distribution={\"pytorchxla\": {\"enabled\": True}},\n", + " **estimator_args,\n", ")\n", "\n", - "# start the training job\n", + "# Start the training job\n", "optimized_estimator.fit(wait=False)\n", + "\n", "optimized_estimator.latest_training_job.name" ] }, { "cell_type": "markdown", - "id": "56f47e19", + "id": "acc95f44", "metadata": {}, "source": [ "### Wait for training jobs to complete" @@ -352,7 +348,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5676eefc", + "id": "1b8ca2bd", "metadata": {}, "outputs": [], "source": [ @@ -360,15 +356,12 @@ " \"training_job_completed_or_stopped\"\n", ")\n", "waiter.wait(TrainingJobName=native_estimator.latest_training_job.name)\n", - "waiter = optimized_estimator.sagemaker_session.sagemaker_client.get_waiter(\n", - " \"training_job_completed_or_stopped\"\n", - ")\n", "waiter.wait(TrainingJobName=optimized_estimator.latest_training_job.name)" ] }, { "cell_type": "markdown", - "id": "78053474", + "id": "25f266b9", "metadata": {}, "source": [ "## Analysis" @@ -376,19 +369,31 @@ }, { "cell_type": "markdown", - "id": "7591a352", + "id": "85df1b04", "metadata": {}, "source": [ "**Note:** If the estimator object is no longer available due to a kernel break or refresh, you need to directly use the training job name and manually attach the training job to a new HuggingFace estimator. For example:\n", "\n", "```python\n", - "huggingface_estimator = HuggingFace.attach(\"your_huggingface_training_job_name\")\n", + "native_estimator = PyTorch.attach(\"your_huggingface_training_job_name\")\n", + "optimized_estimator = HuggingFace.attach(\"your_huggingface_training_job_name\")\n", "```" ] }, + { + "cell_type": "code", + "execution_count": null, + "id": "7a4195d5", + "metadata": {}, + "outputs": [], + "source": [ + "native_estimator = PyTorch.attach(native_estimator.latest_training_job.name)\n", + "optimized_estimator = HuggingFace.attach(optimized_estimator.latest_training_job.name)" + ] + }, { "cell_type": "markdown", - "id": "b5e54aca", + "id": "20bb89b1", "metadata": {}, "source": [ "### Load logs of the training job *with* SageMaker Training Compiler" @@ -397,7 +402,7 @@ { "cell_type": "code", "execution_count": null, - "id": "64b14de7", + "id": "b14fa522", "metadata": {}, "outputs": [], "source": [ @@ -409,7 +414,7 @@ }, { "cell_type": "markdown", - "id": "a9f687a0", + "id": "14944bde", "metadata": {}, "source": [ "### Load logs of the training job *without* SageMaker Training Compiler" @@ -418,7 +423,7 @@ { "cell_type": "code", "execution_count": null, - "id": "279602f2", + "id": "bb9f1be8", "metadata": {}, "outputs": [], "source": [ @@ -430,7 +435,7 @@ }, { "cell_type": "markdown", - "id": "a1d72507", + "id": "ba586740", "metadata": {}, "source": [ "### Create helper functions for analysis" @@ -439,7 +444,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2a1b029c", + "id": "5376e667", "metadata": {}, "outputs": [], "source": [ @@ -480,7 +485,7 @@ }, { "cell_type": "markdown", - "id": "5800d165", + "id": "853afbef", "metadata": {}, "source": [ "### Plot Optimized vs Native Training Throughput\n", @@ -491,7 +496,7 @@ { "cell_type": "code", "execution_count": null, - "id": "01e672f5", + "id": "bd5f2774", "metadata": {}, "outputs": [], "source": [ @@ -510,7 +515,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3d26ca26", + "id": "7eed5237", "metadata": {}, "outputs": [], "source": [ @@ -528,7 +533,7 @@ }, { "cell_type": "markdown", - "id": "4cdd3e80", + "id": "f17d5bbd", "metadata": {}, "source": [ "### Convergence of Training Loss\n", @@ -539,7 +544,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2ce7fbd4", + "id": "dc92a294", "metadata": {}, "outputs": [], "source": [ @@ -558,7 +563,7 @@ }, { "cell_type": "markdown", - "id": "ee290661", + "id": "85bcad63", "metadata": {}, "source": [ "### Training Stats\n", @@ -569,7 +574,7 @@ { "cell_type": "code", "execution_count": null, - "id": "27462c06", + "id": "f34beb9b", "metadata": {}, "outputs": [], "source": [ @@ -581,7 +586,7 @@ { "cell_type": "code", "execution_count": null, - "id": "055d4fb2", + "id": "214e263f", "metadata": {}, "outputs": [], "source": [ @@ -598,7 +603,7 @@ }, { "cell_type": "markdown", - "id": "6fd0199c", + "id": "468541aa", "metadata": {}, "source": [ "### Total Billable Time\n", @@ -609,7 +614,7 @@ { "cell_type": "code", "execution_count": null, - "id": "612a6491", + "id": "0a9192ac", "metadata": {}, "outputs": [], "source": [ @@ -624,7 +629,7 @@ { "cell_type": "code", "execution_count": null, - "id": "12742c78", + "id": "7b30b9ed", "metadata": {}, "outputs": [], "source": [ @@ -637,7 +642,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bfc2a8b4", + "id": "b696a714", "metadata": {}, "outputs": [], "source": [ @@ -647,7 +652,7 @@ }, { "cell_type": "markdown", - "id": "c580614f", + "id": "a0dfc123", "metadata": {}, "source": [ "## Clean up\n", @@ -658,7 +663,7 @@ { "cell_type": "code", "execution_count": null, - "id": "983acde4", + "id": "34367f18", "metadata": {}, "outputs": [], "source": [ @@ -679,7 +684,7 @@ }, { "cell_type": "markdown", - "id": "33bec82a", + "id": "7524e3ba", "metadata": {}, "source": [ "Also, to find instructions on cleaning up resources, see [Clean Up](https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-cleanup.html) in the *Amazon SageMaker Developer Guide*." @@ -688,9 +693,9 @@ ], "metadata": { "kernelspec": { - "display_name": "conda_pytorch_latest_p36", + "display_name": "conda_pytorch_p38", "language": "python", - "name": "conda_pytorch_latest_p36" + "name": "conda_pytorch_p38" }, "language_info": { "codemirror_mode": { @@ -702,7 +707,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.13" + "version": "3.8.12" } }, "nbformat": 4, diff --git a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/scripts/requirements.txt b/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/scripts/requirements.txt new file mode 100644 index 0000000000..c8f87cceeb --- /dev/null +++ b/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/scripts/requirements.txt @@ -0,0 +1,2 @@ +transformers==4.21.1 +datasets==1.18.4 \ No newline at end of file diff --git a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/run_clm.py b/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/scripts/run_clm.py similarity index 100% rename from sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/run_clm.py rename to sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling/scripts/run_clm.py diff --git a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/launch_pt_dt_sm_native.py b/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/launch_pt_dt_sm_native.py deleted file mode 100644 index 28727d0074..0000000000 --- a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/launch_pt_dt_sm_native.py +++ /dev/null @@ -1,34 +0,0 @@ -import argparse -import os, subprocess -from pdb import run - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - - # hyperparameters sent by the client are passed as command-line arguments to the script. - parser.add_argument("--training_script", type=str, default="run_mlm.py") - parser.add_argument("--n_gpus", type=str, default=os.environ["SM_NUM_GPUS"]) - parser.add_argument("--output_dir", type=str, default=os.environ["SM_OUTPUT_DIR"]) - - args, rem_args = parser.parse_known_args() - print("Parsed Arguments: ", vars(args), rem_args) - os.environ["GPU_NUM_DEVICES"] = str(args.n_gpus) - - # native torch distributed as benchmark - training_command = "python -m torch.distributed.launch " - training_command += f"--nproc_per_node={args.n_gpus} " - training_command += "--nnodes=1 --node_rank=0 --master_addr=127.0.0.1 --master_port=1234 " - - training_command += args.training_script + " " - - # output directory - training_command += f"--output_dir {args.output_dir} " - for i in range(0, len(rem_args), 2): - arg, value = rem_args[i], rem_args[i + 1] - if value == "True": - training_command += f"{arg} " - elif value != "False": - training_command += f"{arg} {value} " - - print("Training Command: ", training_command) - subprocess.check_call(training_command, shell=True) diff --git a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/launch_sm_training_compiler.py b/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/launch_sm_training_compiler.py deleted file mode 100644 index 655af389a2..0000000000 --- a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/launch_sm_training_compiler.py +++ /dev/null @@ -1,9 +0,0 @@ -import subprocess -import sys - -if __name__ == "__main__": - arguments_command = " ".join([arg for arg in sys.argv[1:]]) - """ - The following line will take care of setting up inter node communication as well as managing intra node workers for each GPU. - """ - subprocess.check_call("python -m torch_xla.distributed.sm_dist " + arguments_command, shell=True) diff --git a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/run_mlm.py b/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/run_mlm.py deleted file mode 100644 index 3a1375bf86..0000000000 --- a/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/scripts/run_mlm.py +++ /dev/null @@ -1,600 +0,0 @@ -#!/usr/bin/env python -# coding=utf-8 -# Copyright 2020 The HuggingFace Team All rights reserved. -# Modifications Copyright 2021 Amazon.com, Inc. or its affiliates. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" -Fine-tuning the library models for masked language modeling (BERT, ALBERT, RoBERTa...) on a text file or a dataset. - -Here is the full list of checkpoints on the hub that can be fine-tuned by this script: -https://huggingface.co/models?filter=masked-lm -""" -# You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments. - -import logging -import math -import os -import sys -from dataclasses import dataclass, field -from typing import Optional - -import datasets -from datasets import load_dataset - -import transformers -from transformers import ( - CONFIG_MAPPING, - MODEL_FOR_MASKED_LM_MAPPING, - AutoConfig, - AutoModelForMaskedLM, - AutoTokenizer, - DataCollatorForLanguageModeling, - HfArgumentParser, - Trainer, - TrainingArguments, - set_seed, -) -from transformers.trainer_utils import get_last_checkpoint -from transformers.utils import check_min_version -from transformers.utils.versions import require_version - - -# Will error if the minimal version of Transformers is not installed. Remove at your own risks. -check_min_version("4.10.0") - -require_version( - "datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt" -) - -logger = logging.getLogger(__name__) -MODEL_CONFIG_CLASSES = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) -MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) - - -@dataclass -class ModelArguments: - """ - Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. - """ - - model_name_or_path: Optional[str] = field( - default=None, - metadata={ - "help": "The model checkpoint for weights initialization." - "Don't set if you want to train a model from scratch." - }, - ) - model_type: Optional[str] = field( - default=None, - metadata={ - "help": "If training from scratch, pass a model type from the list: " - + ", ".join(MODEL_TYPES) - }, - ) - config_overrides: Optional[str] = field( - default=None, - metadata={ - "help": "Override some existing default config settings when a model is trained from scratch. Example: " - "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" - }, - ) - config_name: Optional[str] = field( - default=None, - metadata={"help": "Pretrained config name or path if not the same as model_name"}, - ) - tokenizer_name: Optional[str] = field( - default=None, - metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}, - ) - cache_dir: Optional[str] = field( - default=None, - metadata={ - "help": "Where do you want to store the pretrained models downloaded from huggingface.co" - }, - ) - use_fast_tokenizer: bool = field( - default=True, - metadata={ - "help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not." - }, - ) - model_revision: str = field( - default="main", - metadata={ - "help": "The specific model version to use (can be a branch name, tag name or commit id)." - }, - ) - use_auth_token: bool = field( - default=False, - metadata={ - "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script " - "with private models)." - }, - ) - - def __post_init__(self): - if self.config_overrides is not None and ( - self.config_name is not None or self.model_name_or_path is not None - ): - raise ValueError( - "--config_overrides can't be used in combination with --config_name or --model_name_or_path" - ) - - -@dataclass -class DataTrainingArguments: - """ - Arguments pertaining to what data we are going to input our model for training and eval. - """ - - dataset_name: Optional[str] = field( - default=None, - metadata={"help": "The name of the dataset to use (via the datasets library)."}, - ) - dataset_config_name: Optional[str] = field( - default=None, - metadata={ - "help": "The configuration name of the dataset to use (via the datasets library)." - }, - ) - train_file: Optional[str] = field( - default=None, metadata={"help": "The input training data file (a text file)."} - ) - validation_file: Optional[str] = field( - default=None, - metadata={ - "help": "An optional input evaluation data file to evaluate the perplexity on (a text file)." - }, - ) - overwrite_cache: bool = field( - default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} - ) - validation_split_percentage: Optional[int] = field( - default=5, - metadata={ - "help": "The percentage of the train set used as validation set in case there's no validation split" - }, - ) - max_seq_length: Optional[int] = field( - default=None, - metadata={ - "help": "The maximum total input sequence length after tokenization. Sequences longer " - "than this will be truncated." - }, - ) - preprocessing_num_workers: Optional[int] = field( - default=None, - metadata={"help": "The number of processes to use for the preprocessing."}, - ) - mlm_probability: float = field( - default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} - ) - line_by_line: bool = field( - default=False, - metadata={ - "help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences." - }, - ) - pad_to_max_length: bool = field( - default=False, - metadata={ - "help": "Whether to pad all samples to `max_seq_length`. " - "If False, will pad the samples dynamically when batching to the maximum length in the batch." - }, - ) - max_train_samples: Optional[int] = field( - default=None, - metadata={ - "help": "For debugging purposes or quicker training, truncate the number of training examples to this " - "value if set." - }, - ) - max_eval_samples: Optional[int] = field( - default=None, - metadata={ - "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this " - "value if set." - }, - ) - - def __post_init__(self): - if self.dataset_name is None and self.train_file is None and self.validation_file is None: - raise ValueError("Need either a dataset name or a training/validation file.") - else: - if self.train_file is not None: - extension = self.train_file.split(".")[-1] - assert extension in [ - "csv", - "json", - "txt", - ], "`train_file` should be a csv, a json or a txt file." - if self.validation_file is not None: - extension = self.validation_file.split(".")[-1] - assert extension in [ - "csv", - "json", - "txt", - ], "`validation_file` should be a csv, a json or a txt file." - - -def main(): - # See all possible arguments in src/transformers/training_args.py - # or by passing the --help flag to this script. - # We now keep distinct sets of args, for a cleaner separation of concerns. - - parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) - if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): - # If we pass only one argument to the script and it's the path to a json file, - # let's parse it to get our arguments. - model_args, data_args, training_args = parser.parse_json_file( - json_file=os.path.abspath(sys.argv[1]) - ) - else: - model_args, data_args, training_args = parser.parse_args_into_dataclasses() - - # Setup logging - logging.basicConfig( - format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", - datefmt="%m/%d/%Y %H:%M:%S", - handlers=[logging.StreamHandler(sys.stdout)], - ) - - log_level = training_args.get_process_log_level() - logger.setLevel(log_level) - datasets.utils.logging.set_verbosity(log_level) - transformers.utils.logging.set_verbosity(log_level) - transformers.utils.logging.enable_default_handler() - transformers.utils.logging.enable_explicit_format() - - # Log on each process the small summary: - logger.warning( - f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" - + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" - ) - # Set the verbosity to info of the Transformers logger (on main process only): - logger.info(f"Training/evaluation parameters {training_args}") - - # Detecting last checkpoint. - last_checkpoint = None - if ( - os.path.isdir(training_args.output_dir) - and training_args.do_train - and not training_args.overwrite_output_dir - ): - last_checkpoint = get_last_checkpoint(training_args.output_dir) - if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: - raise ValueError( - f"Output directory ({training_args.output_dir}) already exists and is not empty. " - "Use --overwrite_output_dir to overcome." - ) - elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: - logger.info( - f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " - "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." - ) - - # Set seed before initializing model. - set_seed(training_args.seed) - - # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) - # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ - # (the dataset will be downloaded automatically from the datasets Hub - # - # For CSV/JSON files, this script will use the column called 'text' or the first column. You can easily tweak this - # behavior (see below) - # - # In distributed training, the load_dataset function guarantee that only one local process can concurrently - # download the dataset. - if data_args.dataset_name is not None: - # Downloading and loading a dataset from the hub. - raw_datasets = load_dataset( - data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir - ) - if "validation" not in raw_datasets.keys(): - raw_datasets["validation"] = load_dataset( - data_args.dataset_name, - data_args.dataset_config_name, - split=f"train[:{data_args.validation_split_percentage}%]", - cache_dir=model_args.cache_dir, - ) - raw_datasets["train"] = load_dataset( - data_args.dataset_name, - data_args.dataset_config_name, - split=f"train[{data_args.validation_split_percentage}%:]", - cache_dir=model_args.cache_dir, - ) - else: - data_files = {} - if data_args.train_file is not None: - data_files["train"] = data_args.train_file - extension = data_args.train_file.split(".")[-1] - if data_args.validation_file is not None: - data_files["validation"] = data_args.validation_file - extension = data_args.validation_file.split(".")[-1] - if extension == "txt": - extension = "text" - raw_datasets = load_dataset( - extension, data_files=data_files, cache_dir=model_args.cache_dir - ) - - # If no validation data is there, validation_split_percentage will be used to divide the dataset. - if "validation" not in raw_datasets.keys(): - raw_datasets["validation"] = load_dataset( - extension, - data_files=data_files, - split=f"train[:{data_args.validation_split_percentage}%]", - cache_dir=model_args.cache_dir, - ) - raw_datasets["train"] = load_dataset( - extension, - data_files=data_files, - split=f"train[{data_args.validation_split_percentage}%:]", - cache_dir=model_args.cache_dir, - ) - - # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at - # https://huggingface.co/docs/datasets/loading_datasets.html. - - # Load pretrained model and tokenizer - # - # Distributed training: - # The .from_pretrained methods guarantee that only one local process can concurrently - # download model & vocab. - config_kwargs = { - "cache_dir": model_args.cache_dir, - "revision": model_args.model_revision, - "use_auth_token": True if model_args.use_auth_token else None, - } - if model_args.config_name: - config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs) - elif model_args.model_name_or_path: - config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs) - else: - config = CONFIG_MAPPING[model_args.model_type]() - logger.warning("You are instantiating a new config instance from scratch.") - if model_args.config_overrides is not None: - logger.info(f"Overriding config: {model_args.config_overrides}") - config.update_from_string(model_args.config_overrides) - - tokenizer_kwargs = { - "cache_dir": model_args.cache_dir, - "use_fast": model_args.use_fast_tokenizer, - "revision": model_args.model_revision, - "use_auth_token": True if model_args.use_auth_token else None, - } - if model_args.tokenizer_name: - tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs) - elif model_args.model_name_or_path: - tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs) - else: - raise ValueError( - "You are instantiating a new tokenizer from scratch. This is not supported by this script." - "You can do it from another script, save it, and load it from here, using --tokenizer_name." - ) - - if model_args.model_name_or_path: - model = AutoModelForMaskedLM.from_pretrained( - model_args.model_name_or_path, - from_tf=bool(".ckpt" in model_args.model_name_or_path), - config=config, - cache_dir=model_args.cache_dir, - revision=model_args.model_revision, - use_auth_token=True if model_args.use_auth_token else None, - ) - else: - logger.info("Training new model from scratch") - model = AutoModelForMaskedLM.from_config(config) - - model.resize_token_embeddings(len(tokenizer)) - - # Preprocessing the datasets. - # First we tokenize all the texts. - if training_args.do_train: - column_names = raw_datasets["train"].column_names - else: - column_names = raw_datasets["validation"].column_names - text_column_name = "text" if "text" in column_names else column_names[0] - - if data_args.max_seq_length is None: - max_seq_length = tokenizer.model_max_length - if max_seq_length > 1024: - logger.warning( - f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). " - "Picking 1024 instead. You can change that default value by passing --max_seq_length xxx." - ) - max_seq_length = 1024 - else: - if data_args.max_seq_length > tokenizer.model_max_length: - logger.warning( - f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the" - f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." - ) - max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) - - if data_args.line_by_line: - # When using line_by_line, we just tokenize each nonempty line. - padding = "max_length" if data_args.pad_to_max_length else False - - def tokenize_function(examples): - # Remove empty lines - examples[text_column_name] = [ - line for line in examples[text_column_name] if len(line) > 0 and not line.isspace() - ] - return tokenizer( - examples[text_column_name], - padding=padding, - truncation=True, - max_length=max_seq_length, - # We use this option because DataCollatorForLanguageModeling (see below) is more efficient when it - # receives the `special_tokens_mask`. - return_special_tokens_mask=True, - ) - - with training_args.main_process_first(desc="dataset map tokenization"): - tokenized_datasets = raw_datasets.map( - tokenize_function, - batched=True, - num_proc=data_args.preprocessing_num_workers, - remove_columns=[text_column_name], - load_from_cache_file=not data_args.overwrite_cache, - desc="Running tokenizer on dataset line_by_line", - ) - else: - # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts. - # We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more - # efficient when it receives the `special_tokens_mask`. - def tokenize_function(examples): - return tokenizer(examples[text_column_name], return_special_tokens_mask=True) - - with training_args.main_process_first(desc="dataset map tokenization"): - tokenized_datasets = raw_datasets.map( - tokenize_function, - batched=True, - num_proc=data_args.preprocessing_num_workers, - remove_columns=column_names, - load_from_cache_file=not data_args.overwrite_cache, - desc="Running tokenizer on every text in dataset", - ) - - # Main data processing function that will concatenate all texts from our dataset and generate chunks of - # max_seq_length. - def group_texts(examples): - # Concatenate all texts. - concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} - total_length = len(concatenated_examples[list(examples.keys())[0]]) - # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can - # customize this part to your needs. - if total_length >= max_seq_length: - total_length = (total_length // max_seq_length) * max_seq_length - # Split by chunks of max_len. - result = { - k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)] - for k, t in concatenated_examples.items() - } - return result - - # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a - # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value - # might be slower to preprocess. - # - # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: - # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map - - with training_args.main_process_first(desc="grouping texts together"): - tokenized_datasets = tokenized_datasets.map( - group_texts, - batched=True, - num_proc=data_args.preprocessing_num_workers, - load_from_cache_file=not data_args.overwrite_cache, - desc=f"Grouping texts in chunks of {max_seq_length}", - ) - - if training_args.do_train: - if "train" not in tokenized_datasets: - raise ValueError("--do_train requires a train dataset") - train_dataset = tokenized_datasets["train"] - if data_args.max_train_samples is not None: - train_dataset = train_dataset.select(range(data_args.max_train_samples)) - - if training_args.do_eval: - if "validation" not in tokenized_datasets: - raise ValueError("--do_eval requires a validation dataset") - eval_dataset = tokenized_datasets["validation"] - if data_args.max_eval_samples is not None: - eval_dataset = eval_dataset.select(range(data_args.max_eval_samples)) - - # Data collator - # This one will take care of randomly masking the tokens. - pad_to_multiple_of_8 = ( - data_args.line_by_line and training_args.fp16 and not data_args.pad_to_max_length - ) - data_collator = DataCollatorForLanguageModeling( - tokenizer=tokenizer, - mlm_probability=data_args.mlm_probability, - pad_to_multiple_of=8 if pad_to_multiple_of_8 else None, - ) - - # Initialize our Trainer - trainer = Trainer( - model=model, - args=training_args, - train_dataset=train_dataset if training_args.do_train else None, - eval_dataset=eval_dataset if training_args.do_eval else None, - tokenizer=tokenizer, - data_collator=data_collator, - ) - - # Training - if training_args.do_train: - checkpoint = None - if training_args.resume_from_checkpoint is not None: - checkpoint = training_args.resume_from_checkpoint - elif last_checkpoint is not None: - checkpoint = last_checkpoint - train_result = trainer.train(resume_from_checkpoint=checkpoint) - trainer.save_model() # Saves the tokenizer too for easy upload - metrics = train_result.metrics - - max_train_samples = ( - data_args.max_train_samples - if data_args.max_train_samples is not None - else len(train_dataset) - ) - metrics["train_samples"] = min(max_train_samples, len(train_dataset)) - - trainer.log_metrics("train", metrics) - trainer.save_metrics("train", metrics) - trainer.save_state() - - # Evaluation - if training_args.do_eval: - logger.info("*** Evaluate ***") - - metrics = trainer.evaluate() - - max_eval_samples = ( - data_args.max_eval_samples - if data_args.max_eval_samples is not None - else len(eval_dataset) - ) - metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) - try: - perplexity = math.exp(metrics["eval_loss"]) - except OverflowError: - perplexity = float("inf") - metrics["perplexity"] = perplexity - - trainer.log_metrics("eval", metrics) - trainer.save_metrics("eval", metrics) - - if training_args.push_to_hub: - kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "fill-mask"} - if data_args.dataset_name is not None: - kwargs["dataset_tags"] = data_args.dataset_name - if data_args.dataset_config_name is not None: - kwargs["dataset_args"] = data_args.dataset_config_name - kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" - else: - kwargs["dataset"] = data_args.dataset_name - - trainer.push_to_hub(**kwargs) - - -def _mp_fn(index): - # For xla_spawn (TPUs) - main() - - -if __name__ == "__main__": - main() From 261f914b29527c004a16a2ee0908246f6700d521 Mon Sep 17 00:00:00 2001 From: Qingwei Li Date: Mon, 12 Sep 2022 14:21:01 -0400 Subject: [PATCH 3/4] Boto3 version notebook (#3597) * CLI upgrade * reformat * grammatical changes * boto3 version * boto3 version-with minor change * serving.perperties remove empty line * set env variable for tensor_parallel_degree * grammatic fix * black-nb * grammatical change * endpoint_name fix * "By" cap * minor change Co-authored-by: Qingwei Li Co-authored-by: atqy Co-authored-by: atqy <95724753+atqy@users.noreply.github.com> --- ...PT-J-6B-model-parallel-inference-DJL.ipynb | 125 ++++++++++-------- 1 file changed, 69 insertions(+), 56 deletions(-) diff --git a/advanced_functionality/pytorch_deploy_large_GPT_model/GPT-J-6B-model-parallel-inference-DJL.ipynb b/advanced_functionality/pytorch_deploy_large_GPT_model/GPT-J-6B-model-parallel-inference-DJL.ipynb index d979d03d7d..74565437de 100644 --- a/advanced_functionality/pytorch_deploy_large_GPT_model/GPT-J-6B-model-parallel-inference-DJL.ipynb +++ b/advanced_functionality/pytorch_deploy_large_GPT_model/GPT-J-6B-model-parallel-inference-DJL.ipynb @@ -22,6 +22,16 @@ "In this notebook, we deploy a PyTorch GPT-J model from Hugging Face with 6 billion parameters across two GPUs on an Amazon SageMaker ml.g5.48xlarge instance. DeepSpeed is used for tensor parallelism inference while DJLServing handles inference requests and the distributed workers. " ] }, + { + "cell_type": "code", + "execution_count": null, + "id": "d6ed354b", + "metadata": {}, + "outputs": [], + "source": [ + "!pip install boto3==1.24.68" + ] + }, { "cell_type": "markdown", "id": "81c2bdf4", @@ -179,13 +189,13 @@ "source": [ "### Setup serving.properties\n", "\n", - "User needs to add engine Rubikon as shown below. If you would like to control how many worker groups, you can set\n", + "User needs to add engine Rubikon as shown below. If you would like to control how many worker groups, you can set by adding these lines in the below file.\n", "\n", "```\n", "gpu.minWorkers=1\n", "gpu.maxWorkers=1\n", "```\n", - "by adding these lines in the below file. By default, we will create as much worker group as possible based on `gpu_numbers/tensor_parallel_degree`." + "By default, we will create as much worker group as possible based on `gpu_numbers/tensor_parallel_degree`." ] }, { @@ -196,7 +206,6 @@ "outputs": [], "source": [ "%%writefile serving.properties\n", - "\n", "engine = Rubikon" ] }, @@ -221,10 +230,9 @@ "account = session.account_id()\n", "region = session.boto_region_name\n", "img = \"djl_deepspeed\"\n", - "fullname = account + \".dkr.ecr.\" + region + \"amazonaws.com/\" + img + \":latest\"\n", - "\n", + "fullname = account + \".dkr.ecr.\" + region + \".amazonaws.com/\" + img + \":latest\"\n", "bucket = session.default_bucket()\n", - "path = \"s3://\" + bucket + \"/DEMO-djl-big-model/\"" + "path = \"s3://\" + bucket + \"/DEMO-djl-big-model\"" ] }, { @@ -253,7 +261,9 @@ "metadata": {}, "outputs": [], "source": [ - "!aws s3 cp gpt-j.tar.gz {path}" + "model_s3_url = sagemaker.s3.S3Uploader.upload(\n", + " \"gpt-j.tar.gz\", path, kms_key=None, sagemaker_session=session\n", + ")" ] }, { @@ -266,77 +276,82 @@ }, { "cell_type": "markdown", - "id": "f96c494a", + "id": "32589338", "metadata": {}, "source": [ - "First let us make sure we have the lastest awscli" + "Now we create our [SageMaker model](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_model). Make sure your execution role has access to your model artifacts and ECR image. Please check out our SageMaker Roles [documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) for more details. " ] }, { "cell_type": "code", "execution_count": null, - "id": "0b665515", + "id": "026d27d2", "metadata": {}, "outputs": [], "source": [ - "!pip3 install --upgrade --user awscli" + "from datetime import datetime\n", + "\n", + "sm_client = boto3.client(\"sagemaker\")\n", + "\n", + "time_stamp = datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n", + "model_name = \"gpt-j-\" + time_stamp\n", + "\n", + "create_model_response = sm_client.create_model(\n", + " ModelName=model_name,\n", + " ExecutionRoleArn=session.get_caller_identity_arn(),\n", + " PrimaryContainer={\n", + " \"Image\": fullname,\n", + " \"ModelDataUrl\": model_s3_url,\n", + " \"Environment\": {\"TENSOR_PARALLEL_DEGREE\": \"2\"},\n", + " },\n", + ")" ] }, { "cell_type": "markdown", - "id": "32589338", + "id": "22d2fc2b", "metadata": {}, "source": [ - "You should see two images from code above. Please note the image name similar to`.dkr.ecr.us-east-1.amazonaws.com/djl_deepspeed`. This is the ECR image URL that we need for later use. \n", - "\n", - "Now we create our [SageMaker model](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html). Make sure you provide an IAM role that SageMaker can assume to access model artifacts and docker image for deployment on ML compute hosting instances. In addition, you also use the IAM role to manage permissions the inference code needs. Please check out our SageMaker Roles [documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) for more details. \n", - "\n", - " You must enter ECR image name, S3 path for the model file, and an execution-role-arn in the code below." + "Now we create an endpoint configuration that SageMaker hosting services uses to deploy models. Note that we configured `ModelDataDownloadTimeoutInSeconds` and `ContainerStartupHealthCheckTimeoutInSeconds` to accommodate the large size of our model. " ] }, { "cell_type": "code", "execution_count": null, - "id": "026d27d2", + "id": "84e25dd4", "metadata": {}, "outputs": [], "source": [ - "!aws sagemaker create-model \\\n", - "--model-name gpt-j \\\n", - "--primary-container \\\n", - "Image=,ModelDataUrl={path},Environment={TENSOR_PARALLEL_DEGREE=2} \\\n", - "--execution-role-arn " + "initial_instance_count = 1\n", + "instance_type = \"ml.g5.48xlarge\"\n", + "variant_name = \"AllTraffic\"\n", + "endpoint_config_name = \"t-j-config-\" + time_stamp\n", + "\n", + "production_variants = [\n", + " {\n", + " \"VariantName\": variant_name,\n", + " \"ModelName\": model_name,\n", + " \"InitialInstanceCount\": initial_instance_count,\n", + " \"InstanceType\": instance_type,\n", + " \"ModelDataDownloadTimeoutInSeconds\": 1800,\n", + " \"ContainerStartupHealthCheckTimeoutInSeconds\": 3600,\n", + " }\n", + "]\n", + "\n", + "endpoint_config = {\n", + " \"EndpointConfigName\": endpoint_config_name,\n", + " \"ProductionVariants\": production_variants,\n", + "}\n", + "\n", + "ep_conf_res = sm_client.create_endpoint_config(**endpoint_config)" ] }, { "cell_type": "markdown", - "id": "22d2fc2b", + "id": "e4b3bc26", "metadata": {}, "source": [ - "Note that we configure `ModelDataDownloadTimeoutInSeconds` and `ContainerStartupHealthCheckTimeoutInSeconds` to acommodate the large size of our model. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "84e25dd4", - "metadata": {}, - "outputs": [], - "source": [ - "%%sh\n", - "aws sagemaker create-endpoint-config \\\n", - " --region $(aws configure get region) \\\n", - " --endpoint-config-name gpt-j-config \\\n", - " --production-variants '[\n", - " {\n", - " \"ModelName\": \"gpt-j\",\n", - " \"VariantName\": \"AllTraffic\",\n", - " \"InstanceType\": \"ml.g5.48xlarge\",\n", - " \"InitialInstanceCount\": 1,\n", - " \"ModelDataDownloadTimeoutInSeconds\": 1800,\n", - " \"ContainerStartupHealthCheckTimeoutInSeconds\": 3600\n", - " }\n", - " ]'" + "We are ready to create an endpoint using the model and the endpoint configuration created from above steps. " ] }, { @@ -346,10 +361,10 @@ "metadata": {}, "outputs": [], "source": [ - "%%sh\n", - "aws sagemaker create-endpoint \\\n", - "--endpoint-name gpt-j \\\n", - "--endpoint-config-name gpt-j-config" + "endpoint_name = \"gpt-j\" + time_stamp\n", + "ep_res = sm_client.create_endpoint(\n", + " EndpointName=endpoint_name, EndpointConfigName=endpoint_config_name\n", + ")" ] }, { @@ -367,11 +382,10 @@ "metadata": {}, "outputs": [], "source": [ - "import boto3, json\n", + "import json\n", "\n", "client = boto3.client(\"sagemaker-runtime\")\n", "\n", - "endpoint_name = \"gpt-j\" # Your endpoint name.\n", "content_type = \"text/plain\" # The MIME type of the input data in the request body.\n", "payload = \"Amazon.com is the best\" # Payload for inference.\n", "response = client.invoke_endpoint(\n", @@ -395,8 +409,7 @@ "metadata": {}, "outputs": [], "source": [ - "%%sh\n", - "aws sagemaker delete-endpoint --endpoint-name gpt-j" + "sm_client.delete_endpoint(endpoint_name)" ] }, { From 6299535b80b44ef0b61b95c979b1511157965810 Mon Sep 17 00:00:00 2001 From: Marc Karp Date: Tue, 13 Sep 2022 12:07:21 -0700 Subject: [PATCH 4/4] Add TensorFlow Triton example (#3543) * Add CatBoost MME BYOC example * formatted * Resolving comment # 1 and 2 * Resolving comment # 1 and 2 * Resolving comment # 4 * Resolving clean up comment * Added comments about CatBoost and usage for MME * Reformatted the jupyter file * Added the container with the relevant py files * Added formatting using Black. Also fixed the comments from the Jupyter file * Added formatting using Black. Also fixed the comments from the Jupyter file * Added formatting using Black. Also fixed the comments from the Jupyter file * Add TensorFlow Triton example * format TensorFlow Triton example * Action feedback * Fix link(s) to be descriptive * Formatted * Update delete cell Co-authored-by: rsgrewal Co-authored-by: atqy <95724753+atqy@users.noreply.github.com> --- ...TensorFlow-Model-Using-NVIDIA-Triton.ipynb | 461 ++++++++++++++++++ 1 file changed, 461 insertions(+) create mode 100644 sagemaker-triton/TensorFlow/Deploy-TensorFlow-Model-Using-NVIDIA-Triton.ipynb diff --git a/sagemaker-triton/TensorFlow/Deploy-TensorFlow-Model-Using-NVIDIA-Triton.ipynb b/sagemaker-triton/TensorFlow/Deploy-TensorFlow-Model-Using-NVIDIA-Triton.ipynb new file mode 100644 index 0000000000..18d3922922 --- /dev/null +++ b/sagemaker-triton/TensorFlow/Deploy-TensorFlow-Model-Using-NVIDIA-Triton.ipynb @@ -0,0 +1,461 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "6d6ee543", + "metadata": {}, + "source": [ + "# Deploy a TensorFlow Model using NVIDIA Triton on SageMaker" + ] + }, + { + "cell_type": "markdown", + "id": "7634d547", + "metadata": {}, + "source": [ + "Amazon SageMaker is a fully managed service for data science and machine learning workflows. It helps data scientists and developers to prepare, build, train, and deploy high-quality ML models quickly by bringing together a broad set of capabilities purpose-built for ML.\n", + "\n", + "Now, NVIDIA Triton Inference Server can be used to serve models for inference in Amazon SageMaker. Thanks to the new NVIDIA Triton container image, you can easily serve ML models and benefit from the performance optimizations, dynamic batching, and multi-framework support provided by NVIDIA Triton. Triton helps maximize the utilization of GPU and CPU, further lowering the cost of inference.\n", + "\n", + "This example will showcase how to deploy a pre-trained TensorFlow model using NVIDIA Triton on SageMaker.\n", + "\n", + "The model used here was pre-trained on the MNIST dataset. See this [Deploy a Trained TensorFlow V2 Model example](https://github.com/aws/amazon-sagemaker-examples/blob/1c5da8941bc933b176b56a93157073d5645d8cdf/frameworks/tensorflow/get_started_mnist_deploy.ipynb) for the training of the model. \n", + "\n", + "## Contents\n", + "1. [Introduction to NVIDIA Triton Server](#Introduction-to-NVIDIA-Triton-Server)\n", + "1. [Set up the environment](#Set-up-the-environment)\n", + "1. [Transform TensorFlow Model structure](#Transform-TensorFlow-Model-structure)\n", + " 1. [Inspect the model using the saved_model_cli](#Inspect-the-model-using-the-saved_model_cli)\n", + " 1. [Create the config.pbtxt](#Create-the-config.pbtxt)\n", + " 1. [Create the tar ball in the required Triton structure](#Create-the-tar-ball-in-the-required-Triton-structure)\n", + "1. [Deploy model to SageMaker Endpoint](#Deploy-model-to-SageMaker-Endpoint)\n", + "1. [Clean up](#Clean-up)" + ] + }, + { + "cell_type": "markdown", + "id": "51ab88ee", + "metadata": {}, + "source": [ + "## Introduction to NVIDIA Triton Server\n", + "\n", + "[NVIDIA Triton Inference Server](https://github.com/triton-inference-server/server/) was developed specifically to enable scalable, cost-effective, and easy deployment of models in production. NVIDIA Triton Inference Server is open-source inference serving software that simplifies the inference serving process and provides high inference performance.\n", + "\n", + "Some key features of Triton are:\n", + "* **Support for Multiple frameworks**: Triton can be used to deploy models from all major frameworks. Triton supports TensorFlow GraphDef, TensorFlow SavedModel, ONNX, PyTorch TorchScript, TensorRT, RAPIDS FIL for tree based models, and OpenVINO model formats. \n", + "* **Model pipelines**: Triton model ensemble represents a pipeline of one or more models or pre/post processing logic and the connection of input and output tensors between them. A single inference request to an ensemble will trigger the execution of the entire pipeline.\n", + "* **Concurrent model execution**: Multiple models (or multiple instances of the same model) can run simultaneously on the same GPU or on multiple GPUs for different model management needs.\n", + "* **Dynamic batching**: For models that support batching, Triton has multiple built-in scheduling and batching algorithms that combine individual inference requests together to improve inference throughput. These scheduling and batching decisions are transparent to the client requesting inference.\n", + "* **Diverse CPUs and GPUs**: The models can be executed on CPUs or GPUs for maximum flexibility and to support heterogeneous computing requirements.\n", + "\n", + "**Note**: This initial release of NVIDIA Triton on SageMaker will only support a single model. Future releases will have multi-model support. A minimal `config.pbtxt` configuration file is **required** in the model artifacts. This release doesn't support inferring the model config automatically.\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "5cf5f5fc", + "metadata": {}, + "source": [ + "## Set up the environment\n", + "\n", + "Download the pre-trained TensorFlow model from a public S3 bucket.\n", + "Also define the IAM role that will give SageMaker access to the model artifacts and the NVIDIA Triton ECR image.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13469557", + "metadata": {}, + "outputs": [], + "source": [ + "%%time\n", + "import boto3\n", + "\n", + "# use the region-specific saved model object\n", + "region = boto3.Session().region_name\n", + "saved_model = \"s3://sagemaker-sample-files/datasets/image/MNIST/model/tensorflow-training-2020-11-20-23-57-13-077/model.tar.gz\"\n", + "!aws s3 cp $saved_model models/SavedModel/" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "76af8c28", + "metadata": {}, + "outputs": [], + "source": [ + "import sagemaker\n", + "\n", + "sm_session = sagemaker.Session()\n", + "role = sagemaker.get_execution_role()\n", + "bucket_name = sm_session.default_bucket()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "31b31768", + "metadata": {}, + "outputs": [], + "source": [ + "account_id_map = {\n", + " \"us-east-1\": \"785573368785\",\n", + " \"us-east-2\": \"007439368137\",\n", + " \"us-west-1\": \"710691900526\",\n", + " \"us-west-2\": \"301217895009\",\n", + " \"eu-west-1\": \"802834080501\",\n", + " \"eu-west-2\": \"205493899709\",\n", + " \"eu-west-3\": \"254080097072\",\n", + " \"eu-north-1\": \"601324751636\",\n", + " \"eu-south-1\": \"966458181534\",\n", + " \"eu-central-1\": \"746233611703\",\n", + " \"ap-east-1\": \"110948597952\",\n", + " \"ap-south-1\": \"763008648453\",\n", + " \"ap-northeast-1\": \"941853720454\",\n", + " \"ap-northeast-2\": \"151534178276\",\n", + " \"ap-southeast-1\": \"324986816169\",\n", + " \"ap-southeast-2\": \"355873309152\",\n", + " \"cn-northwest-1\": \"474822919863\",\n", + " \"cn-north-1\": \"472730292857\",\n", + " \"sa-east-1\": \"756306329178\",\n", + " \"ca-central-1\": \"464438896020\",\n", + " \"me-south-1\": \"836785723513\",\n", + " \"af-south-1\": \"774647643957\",\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd92a880", + "metadata": {}, + "outputs": [], + "source": [ + "if region not in account_id_map.keys():\n", + " raise (\"UNSUPPORTED REGION\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0cc3ddf8", + "metadata": {}, + "outputs": [], + "source": [ + "base = \"amazonaws.com.cn\" if region.startswith(\"cn-\") else \"amazonaws.com\"\n", + "triton_image_uri = \"{account_id}.dkr.ecr.{region}.{base}/sagemaker-tritonserver:21.08-py3\".format(\n", + " account_id=account_id_map[region], region=region, base=base\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "39414be7", + "metadata": {}, + "outputs": [], + "source": [ + "!tar -xf models/SavedModel/model.tar.gz -C models/SavedModel/" + ] + }, + { + "cell_type": "markdown", + "id": "a1e5faca", + "metadata": {}, + "source": [ + "## Transform TensorFlow Model structure\n", + "\n", + "\n", + "The model that we want to deploy currently has the following structure:\n", + "\n", + "```\n", + "00000000\n", + " ├── saved_model.pb\n", + " ├── assets/\n", + " └── variables/\n", + " ├── variables.data-00000-of-00001\n", + " └── variables.index\n", + "```\n", + "For Triton, the model needs to have the following structure:\n", + "```\n", + "\n", + "├── config.pbtxt\n", + "└── 1/\n", + " └── model.savedmodel\n", + " ├── saved_model.pb\n", + " ├── assets/\n", + " └── variables/\n", + " ├── variables.data-00000-of-00001\n", + " └── variables.index\n", + " \n", + "\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "392b33db", + "metadata": {}, + "outputs": [], + "source": [ + "! mkdir -p models/TritonModel/MNIST/1\n", + "! cp models/SavedModel/00000000 --recursive ./models/TritonModel/MNIST/1/model.savedmodel/" + ] + }, + { + "cell_type": "markdown", + "id": "4c21b8be", + "metadata": {}, + "source": [ + "### Inspect the model using the `saved_model_cli`\n", + "\n", + "In order to create the `config.pbtxt` we need to confirm the model inputs and outputs (Signature).\n", + "We use the `saved_model_cli` to inspect the model and take note of the input and output shape." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "42b58467", + "metadata": {}, + "outputs": [], + "source": [ + "!saved_model_cli show --all --dir {\"models/SavedModel/00000000\"}" + ] + }, + { + "cell_type": "markdown", + "id": "1332701d", + "metadata": {}, + "source": [ + "### Create the config.pbtxt \n", + "\n", + "Triton requires a [Model Configuration file](https://github.com/triton-inference-server/server/blob/main/docs/model_configuration.md) known as a `config.pbtxt`. We create one below in the correct directory.\n", + "\n", + "The `name` in the `config.pbtxt` must match the name of our model directory. In this case we will use `MNIST`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0f843f41", + "metadata": {}, + "outputs": [], + "source": [ + "%%writefile models/TritonModel/MNIST/config.pbtxt\n", + "name: \"MNIST\"\n", + "platform: \"tensorflow_savedmodel\"\n", + "max_batch_size: 0\n", + "\n", + "instance_group {\n", + " count: 1\n", + " kind: KIND_GPU\n", + "}\n", + "\n", + "dynamic_batching {\n", + "\n", + "}\n", + "\n", + "input [\n", + " {\n", + " name: \"input_1\"\n", + " data_type: TYPE_FP32\n", + " dims: [-1, 28, 28, 1]\n", + " }\n", + "]\n", + "output [\n", + " {\n", + " name: \"output_1\"\n", + " data_type: TYPE_FP32\n", + " dims: [-1, 10]\n", + " }\n", + "]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "af89bd5e", + "metadata": {}, + "outputs": [], + "source": [ + "model_location = f\"s3://{bucket_name}/TritonModel/TritonModel.tar.gz\"" + ] + }, + { + "cell_type": "markdown", + "id": "311b6185", + "metadata": {}, + "source": [ + "### Create the tar ball in the required Triton structure" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e69c75c4", + "metadata": {}, + "outputs": [], + "source": [ + "%%sh\n", + "cd models/TritonModel/ \n", + "tar -czvf TritonModel.tar.gz MNIST/" + ] + }, + { + "cell_type": "markdown", + "id": "32dfbd14", + "metadata": {}, + "source": [ + "### Upload the new tar ball containing the Triton model structure to s3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1bec7fb4", + "metadata": {}, + "outputs": [], + "source": [ + "!aws s3 cp models/TritonModel/TritonModel.tar.gz $model_location" + ] + }, + { + "cell_type": "markdown", + "id": "bedf430a", + "metadata": {}, + "source": [ + "## Deploy model to SageMaker Endpoint\n", + "We start off by creating a sagemaker model from the model files we uploaded to s3 in the previous step.\n", + "\n", + "In this step we also provide an additional Environment Variable i.e. `SAGEMAKER_TRITON_DEFAULT_MODEL_NAME` which specifies the name of the model to be loaded by Triton. The value of this key should match the folder name in the model package uploaded to s3. This variable is optional in case of a single model. In case of ensemble models, this key has to be specified for Triton to startup in SageMaker.\n", + "\n", + "Additionally, customers can set `SAGEMAKER_TRITON_BUFFER_MANAGER_THREAD_COUNT` and `SAGEMAKER_TRITON_THREAD_COUNT` for optimizing the thread counts." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9097c998", + "metadata": {}, + "outputs": [], + "source": [ + "from sagemaker.model import Model\n", + "\n", + "tensorflow_model = Model(\n", + " model_data=model_location,\n", + " role=role,\n", + " env={\"SAGEMAKER_TRITON_DEFAULT_MODEL_NAME\": \"MNIST\"},\n", + " image_uri=triton_image_uri,\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ea99bee4", + "metadata": {}, + "outputs": [], + "source": [ + "from datetime import datetime\n", + "\n", + "date = datetime.now().strftime(\"%Y-%m-%d-%H-%m-%S\")\n", + "\n", + "endpoint_name = f\"Triton-MNIST-{date}\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "376ca9af", + "metadata": {}, + "outputs": [], + "source": [ + "predictor = tensorflow_model.deploy(\n", + " initial_instance_count=1,\n", + " instance_type=\"ml.g4dn.xlarge\",\n", + " endpoint_name=endpoint_name,\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a1e48701", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import json\n", + "\n", + "payload = {\n", + " \"inputs\": [\n", + " {\n", + " \"name\": \"input_1\",\n", + " \"shape\": [4, 28, 28, 1],\n", + " \"datatype\": \"FP32\",\n", + " \"data\": np.random.rand(4, 28, 28, 1).tolist(),\n", + " }\n", + " ]\n", + "}\n", + "runtime_sm_client = boto3.client(\"sagemaker-runtime\")\n", + "response = runtime_sm_client.invoke_endpoint(\n", + " EndpointName=endpoint_name,\n", + " ContentType=\"application/octet-stream\",\n", + " Body=json.dumps(payload),\n", + ")\n", + "\n", + "predictions = json.loads(response[\"Body\"].read())[\"outputs\"][0][\"data\"]\n", + "predictions = np.array(predictions, dtype=np.float32)\n", + "predictions = np.argmax(predictions)\n", + "predictions" + ] + }, + { + "cell_type": "markdown", + "id": "f0f2a7d2", + "metadata": {}, + "source": [ + "## Clean up\n", + "We strongly recommend to delete the Real-time endpoint created to stop incurring cost when finished with the example" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8f9e893f", + "metadata": {}, + "outputs": [], + "source": [ + "sm_client = boto3.client(\"sagemaker\")\n", + "# Delete endpoint\n", + "sm_client.delete_endpoint(EndpointName=endpoint_name)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "conda_tensorflow2_p38", + "language": "python", + "name": "conda_tensorflow2_p38" + }, + "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.8.12" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}