Smp Fine Tune Gpt Sharded Data Parallel
Fine-tune GPT-2 with near-linear scaling using Sharded Data Parallelism technique in 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.
In this notebook, you learn how to fine-tune 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
-
To learn more about the SageMaker model parallelism library, see Model Parallel Distributed Training with SageMaker Distributed.
-
To learn more about using the SageMaker Python SDK with PyTorch, see Using PyTorch with the SageMaker Python SDK.
-
To learn more about launching a training job in Amazon SageMaker with your own training image, see Use Your Own Training Algorithms.
-
To learn more about sharded data parallelism, check Sharded Data Parallelism or the blog Near-linear scaling of gigantic-model training on AWS.
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 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.
Also note that we add the fine_tune parameter that activates the code lines for fine-tuning in the script train.py.
Set the model configuration. Specify 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_countinstance_typevolume_sizebase_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).
- For GPT-2 with 30-billion parameters, you need at least 16
ml.p4d.24xlargeinstances. - For GPT-2 xl, use 1
ml.p4d.24xlargeat least. - For GPT-2 small, use 1
ml.p3.16xlargeat 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 fine-tuning 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 set up a persistent endpoint to get predictions from your models, use SageMaker hosting services. For an overview on deploying a single model or multiple models with SageMaker hosting services, see Deploy a Model on SageMaker Hosting Services.
- To get predictions for an entire dataset, use SageMaker batch transform. For an overview on deploying a model with SageMaker Batch Transform, see Get Inferences for an Entire Dataset with Batch Transform.
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.