Notebooks
A
Amazon Web Services
Smp Train Gpt Sharded Data Parallel

Smp Train Gpt Sharded Data Parallel

data-scienceinferencearchivedamazon-sagemaker-examplesreinforcement-learningmachine-learningsmp-gpt-sharded-data-parallelawsexamplesdeep-learningsagemakerjupyter-notebooktrainingmlops

Train GPT-2 with near-linear scaling using the sharded data parallelism technique in the SageMaker Model Parallelism library


This notebook's CI test result for us-west-2 is as follows. CI test results in other regions can be found at the end of the notebook.

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable


In this notebook, you learn how to train the Hugging Face Transformers GPT-2 model with the Sharded Data Parallelism technique in SageMaker's Model Parallelism library (SMP) with PyTorch 1.13 and GLUE/SST2 dataset on SageMaker.

The GPT-2 model was proposed by OpenAI in the paper Language Models are Unsupervised Multitask Learners. The original GPT-2 is a large transformer-based language model with 1.5 billion parameters. In this notebook, you can experiment with the model parameters to achieve different model sizes. This notebook uses the Hugging Face Transformers GPT-2 implementation with the SMP integration.

Sharded data parallelism is a distributed training technique that splits the model parameters, gradients, and optimizer states across GPUs in a data parallel group. It is purpose-built for extreme-scale models and leverages Amazon in-house MiCS technology which achieves a near-linear scaling efficiency. For large models that cannot fit into a single GPU, we recommend to use the sharded data parallelism technique with Activation Checkpointing and Activation Offloading in SMP first, before leveraging other techniques such as tensor parallelism or pipeline parallelism.

This notebook is accompanied with the following files:

  • train.py: The entry point script that'll be passed to the SageMaker PyTorch estimator later in this notebook when launching the training job. This script is prepared to run an end-to-end training of the GPT-2 model with SMP, settings for sharded data parallelism applied, and implemented with code lines to save, load, and fine-tune the model. You can follow the comments throughout the script to learn where the SMP APIs and code modifications are implemented.
  • data_pipeline.py: This has data pipeline functions to prepare the training dataset.
  • learining_rate.py: This has functions for learning rate schedule.
  • requirements.txt: This installs the dependencies, including huggingface transformers.
  • memory_tracker.py: This has functions to track memory usage.
  • model_config.py: This has functions to get model configuration information.
  • sdp_utils.py: This has util functions for sharded data parallelism

Additional Resources

Prerequisites

You must create an S3 bucket to store the input data for training. This bucket must be located in the same AWS Region that you choose to launch your training job. To learn how to create a S3 bucket, see Create your first S3 bucket in the Amazon S3 documentation.

Amazon SageMaker Initialization

Run the following cell to import the SageMaker modules and retrieve information of your current SageMaker work environment, such as your AWS account ID, the AWS Region, and the ARN of your Amazon SageMaker execution role. Upgrade SageMaker SDK to the latest version.

NOTE: This step might require a kernel restart.

[ ]
[ ]

Download and prepare GLUE/SST2 data

Here you will download, prepare the GLUE/SST2 dataset and then copy the files to S3.

Install the Hugging Face Transformers and Datasets libraries

[ ]
[ ]
[ ]
[ ]

Load data

This section loads the GLUE/SST2 dataset and splits it to training and validation datasets.

[ ]
[ ]
[ ]

Load tokenizer

Nearly every NLP task begins with a tokenizer. A tokenizer converts your text data into a format (token) that can be processed by the NLP model. The following cell loads a tokenizer for GPT-2 using AutoTokenizer.from_pretrained().

[ ]

Preprocess data

The following two cells set up a function to run the tokenizer and group texts into chunks smaller than the block size.

[ ]
[ ]

Set additional hyperparameters and S3 paths for mapping the train and validation datasets properly depending on the phase (training or validation) of the training job in each epoch.

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

Specify Amazon S3 bucket paths

Here you need to specify the paths for training data to be used by your job. The bucket used must be in the same region as where training will run. In the cells above you downloaded the GLUE/SST2 training and validation split datasets and uploaded the json files in an S3 bucket in your account. This example will train on those json files.

After you successfully run this example tensor parallel training job, you can modify the S3 bucket to where your own dataset is stored.

[ ]
[ ]

The following S3 bucket will store the output artifacts of the training job. You can modify this as needed.

[ ]

Define Data Channels for SageMaker Training Using Amazon S3

In this step, define SageMaker training data channels to the S3 buckets.

[ ]

(Optional) Set Up and Use Amazon FSx for Data Channels and Checkpoints

While the previous option of using Amazon S3 is easier to setup, using an FSx can be beneficial for performance when dealing with large input sizes and large model sizes. If you are using models above 13B, checkpointing should be done using FSx.

Please see the instructions from Distributed Training of Mask-RCNN in Amazon SageMaker Using FSx to create an FSx Lustre file system and import the dataset from the S3 bucket to your FSx file system. Note that the FSx file system must be created in a private subnet with internet gateway to ensure that training job has access to the internet. For general guidance on setting an FSx Lustre file system as data input channel, see Configure Data Input Channel to Use Amazon FSx for Lustre.

[ ]

Set hyperparameters, metric definitions, and MPI options

The following hyperparameters dictionary passes arguments to the training script (train.py) and set the model parallel configuration when creating the training job.

You can also add custom mpi flags. By default, we have --mca btl_vader_single_copy_mechanism none to remove unnecessary logs.

Next, we add a base metric definitions to enable the metric upload in SageMaker. You can add any further metric definitions.

Note that we add the sharded_data_parallel_degree parameter to the hyperparameter dictionary. This will be parsed and used when we configure a SageMaker PyTorch estimator to activate sharded data parallelism.

[ ]

Set the model configuration by choose one from gpt2-30b, gpt2-xl and gpt2-small.

[ ]

Specify essential parameters for a SageMaker Training job

Next, you use the SageMaker Estimator class to define a SageMaker Training Job, passing values through the following parameters for training job name, the number of EC2 instances, the instance type, and the size of the volume attached to the instances.

  • instance_count
  • instance_type
  • volume_size
  • base_job_name

Update the type and the number of EC2 instance to use

The instance type and the number of instances you specify to the instance_type and instance_count parameters, respectively, determine the total number of GPUs (world size).

(world size) = (the number of GPUs on a single instance)×(the number of instances) \text{(world size) = (the number of GPUs on a single instance)}\times\text{(the number of instances)}

  • For GPT-2 with 30-billion parameters, you need at least 16 ml.p4d.24xlarge instances.
  • For GPT-2 xl, use 1 ml.p4d.24xlarge at least.
  • For GPT-2 small, use 1 ml.p3.16xlarge at least.
[ ]

To look up the number of GPUs of different instance types, see Amazon EC2 Instance Types. Use the section Accelerated Computing to see general purpose GPU instances. Note that, for example, a given instance type p4d.24xlarge has a corresponding instance type ml.p4d.24xlarge in SageMaker. For SageMaker supported ml instances and cost information, see Amazon SageMaker Pricing.

Specify a base job name

[ ]
[ ]
[ ]

Create a SageMaker PyTorch estimator

The following cell constructs a PyTorch estimator using the parameters defined above. To see how the SageMaker APIs and functions are applied to the script, see the train.py file.

[ ]

Finally, run the estimator.fit method to launch the SageMaker training job of the GPT-2 model with sharded data parallelism.

[ ]

Accessing the Training Logs

You can access the training logs from Amazon CloudWatch. Make sure to look at the logs of algo-1 because that is the main node whose output stream has the training job logs.

You can use CloudWatch to track SageMaker GPU and memory utilization during training and inference. To view the metrics and logs that SageMaker writes to CloudWatch, see SageMaker Jobs and Endpoint Metrics in the Amazon SageMaker Developer Guide.

If you are a new user of CloudWatch, see Getting Started with Amazon CloudWatch.

For additional information on monitoring and analyzing Amazon SageMaker training jobs, see Monitor and Analyze Training Jobs Using Metrics.

Deploying Trained Model for Inference

In most cases, a trained model can be deployed on a single device for inference because inference only requires a small amount of memory. You can use the SMP API to create a single, unified model after training: the smp.DistributedModel.save_model() method for TensorFlow, and the smp.save() function for PyTorch.

After you build and train your models, you can deploy them to get predictions in one of two ways:

To learn more about deploying models for inference using SageMaker, see Deploy Models for Inference.

Notebook CI Test Results

This notebook was tested in multiple regions. The test results are as follows, except for us-west-2 which is shown at the top of the notebook.

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable

This badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable