philschmid blog

Distributed training on multilingual BERT with Hugging Face Transformers & Amazon SageMaker

#HuggingFace #AWS #BERT #PyTorch
, January 25, 2022 · 8 min read

Photo by Ryan Ancill on Unsplash

Welcome to this end-to-end multilingual Text-Classification example using PyTorch. In this demo, we will use the Hugging Faces transformers and datasets library together with Pytorch to fine-tune a multilingual transformer for text-classification. This example is a derived version of the text-classificiaton.ipynb notebook and uses Amazon SageMaker for distributed training. In the text-classificiaton.ipynb we showed how to fine-tune distilbert-base-multilingual-cased on the amazon_reviews_multi dataset for sentiment-analysis. This dataset has over 1.2 million data points, which is huge. Running training would take on 1x NVIDIA V100 takes around 6,5h for batch_size 16, which is quite long.

To scale and accelerate our training we will use Amazon SageMaker, which provides two strategies for distributed training, data parallelism and model parallelism. Data parallelism splits a training set across several GPUs, while model parallelism splits a model across several GPUs. We are going to use SageMaker Data Parallelism, which has been built into the Trainer API. To be able use data-parallelism we only have to define the distribution parameter in our HuggingFace estimator.

I moved the “training” part of the text-classificiaton.ipynb notebook into a separate training script train.py, which accepts the same hyperparameter and can be run on Amazon SageMaker using the HuggingFace estimator.

Our goal is to decrease the training duration by scaling our global/effective batch size from 16 up to 128, which is 8x bigger than before. For monitoring our training we will use the new Training Metrics support by the Hugging Face Hub

Installation

1 #!pip install sagemaker
2 !pip install transformers datasets tensorboard datasets[s3] --upgrade

This example will use the Hugging Face Hub as remote model versioning service. To be able to push our model to the Hub, you need to register on the Hugging Face. If you already have an account you can skip this step. After you have an account, we will use the notebook_login util from the huggingface_hub package to log into our account and store our token (access key) on the disk.

1 from huggingface_hub import notebook_login
2
3 notebook_login()

Setup & Configuration

In this step we will define global configurations and parameters, which are used across the whole end-to-end fine-tuning proccess, e.g. tokenizer and model we will use.

1 import sagemaker
2
3 sess = sagemaker.Session()
4 # sagemaker session bucket -> used for uploading data, models and logs
5 # sagemaker will automatically create this bucket if it not exists
6 sagemaker_session_bucket=None
7 if sagemaker_session_bucket is None and sess is not None:
8 # set to default bucket if a bucket name is not given
9 sagemaker_session_bucket = sess.default_bucket()
10
11 role = sagemaker.get_execution_role()
12 sess = sagemaker.Session(default_bucket=sagemaker_session_bucket)
13
14 print(f"sagemaker role arn: {role}")
15 print(f"sagemaker bucket: {sess.default_bucket()}")
16 print(f"sagemaker session region: {sess.boto_region_name}")

Note: The execution role is only available when running a notebook within SageMaker (SageMaker Notebook Instances or Studio). If you run get_execution_role in a notebook not on SageMaker, expect a region error.

You can comment in the cell below and provide a an IAM Role name with SageMaker permissions to setup your environment out side of SageMaker.

1 # import sagemaker
2 # import boto3
3 # import os
4
5 # os.environ["AWS_DEFAULT_REGION"]="your-region"
6
7 # # This ROLE needs to exists with your associated AWS Credentials and needs permission for SageMaker
8 # ROLE_NAME='role-name-of-your-iam-role-with-right-permissions'
9
10 # iam_client = boto3.client('iam')
11 # role = iam_client.get_role(RoleName=ROLE_NAME)['Role']['Arn']
12 # sess = sagemaker.Session()
13
14 # print(f"sagemaker role arn: {role}")
15 # print(f"sagemaker bucket: {sess.default_bucket()}")
16 # print(f"sagemaker session region: {sess.boto_region_name}")

In this example are we going to fine-tune the distilbert-base-multilingual-cased a multilingual DistilBERT model.

1 model_id = "distilbert-base-multilingual-cased"
2
3 # name for our repository on the hub
4 model_name = model_id.split("/")[-1] if "/" in model_id else model_id
5 repo_name = f"{model_name}-sentiment"

Dataset & Pre-processing

As Dataset we will use the amazon_reviews_multi a multilingual text-classification. The dataset contains reviews in English, Japanese, German, French, Chinese and Spanish, collected between November 1, 2015 and November 1, 2019. Each record in the dataset contains the review text, the review title, the star rating, an anonymized reviewer ID, an anonymized product ID and the coarse-grained product category (e.g. ‘books’, ‘appliances’, etc.) The corpus is balanced across stars, so each star rating constitutes 20% of the reviews in each language.

1 dataset_id="amazon_reviews_multi"
2 dataset_config="all_languages"
3
4 seed=33

To load the amazon_reviews_multi dataset, we use the load_dataset() method from the 🤗 Datasets library.

1 from datasets import load_dataset
2
3 dataset = load_dataset(dataset_id,dataset_config)

Pre-processing & Tokenization

The amazon_reviews_multi has 5 classes (stars) to match those into a sentiment-analysis task we will map those star ratings to the following classes labels:

  • [1-2]: Negative
  • [3]: Neutral
  • [4-5]: Positive

Those labels can be later used to create a user friendly output after we fine-tuned our model.

1 from datasets import ClassLabel
2
3 def map_start_to_label(review):
4 if review["stars"] < 3:
5 review["stars"] = 0
6 elif review["stars"] == 3:
7 review["stars"] = 1
8 else:
9 review["stars"] = 2
10 return review
11
12 # convert 1-5 star reviews to 0,1,2
13 dataset = dataset.map(map_start_to_label)
14
15 # convert feature from Value to ClassLabel
16 class_feature = ClassLabel(names=['negative','neutral', 'positive'])
17 dataset = dataset.cast_column("stars", class_feature)
18
19 # rename our target column to labels
20 dataset = dataset.rename_column("stars","labels")
21
22 # drop columns that are not needed
23 dataset = dataset.remove_columns(['review_id', 'product_id', 'reviewer_id', 'review_title', 'language', 'product_category'])

Before we prepare the dataset for training. Lets take a quick look at the class distribution of the dataset.

1 import pandas as pd
2
3 df = dataset["train"].to_pandas()
4
5 df.hist()

distribution

The Distribution is not perfect, but lets give it a try and improve on this later.

To train our model we need to convert our “Natural Language” to token IDs. This is done by a 🤗 Transformers Tokenizer which will tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary). If you are not sure what this means check out chapter 6 of the Hugging Face Course.

1 from transformers import AutoTokenizer
2
3 tokenizer = AutoTokenizer.from_pretrained(model_id)

Additionally we add the truncation=True and max_length=512 to align the length and truncate texts that are bigger than the maximum size allowed by the model.

1 def process(examples):
2 tokenized_inputs = tokenizer(
3 examples["review_body"], truncation=True, max_length=512
4 )
5 return tokenized_inputs
6
7 tokenized_datasets = dataset.map(process, batched=True)
8 tokenized_datasets["train"].features

Before we can start our distributed Training, we need to upload our already pre-processed dataset to Amazon S3. Therefore we will use the built-in utils of datasets

1 import botocore
2 from datasets.filesystems import S3FileSystem
3
4 s3 = S3FileSystem()
5
6 # save train_dataset to s3
7 training_input_path = f's3://{sess.default_bucket()}/{dataset_id}/train'
8 tokenized_datasets["train"].save_to_disk(training_input_path, fs=s3)
9
10 # save validation_dataset to s3
11 eval_input_path = f's3://{sess.default_bucket()}/{dataset_id}/test'
12 tokenized_datasets["validation"].save_to_disk(eval_input_path, fs=s3)

Creating an Estimator and start a training job

Last step before we can start our managed training is to define our Hyperparameters, create our sagemaker HuggingFace estimator and configure distributed training.

1 from sagemaker.huggingface import HuggingFace
2 from huggingface_hub import HfFolder
3
4 # hyperparameters, which are passed into the training job
5 hyperparameters={
6 'model_id':'distilbert-base-multilingual-cased',
7 'epochs': 3,
8 'per_device_train_batch_size': 16,
9 'per_device_eval_batch_size': 16,
10 'learning_rate': 3e-5*8,
11 'fp16': True,
12 # logging & evaluation strategie
13 'strategy':'steps',
14 'steps':5_000,
15 'save_total_limit':2,
16 'load_best_model_at_end':True,
17 'metric_for_best_model':"f1",
18 # push to hub config
19 'push_to_hub': True,
20 'hub_model_id': 'distilbert-base-multilingual-cased-sentiment-2',
21 'hub_token': HfFolder.get_token()
22 }
23
24 # configuration for running training on smdistributed Data Parallel
25 distribution = {'smdistributed':{'dataparallel':{ 'enabled': True }}}
26
27 # create the Estimator
28 huggingface_estimator = HuggingFace(
29 entry_point = 'train.py',
30 source_dir = './scripts',
31 instance_type = 'ml.p3.16xlarge',
32 instance_count = 1,
33 role = role,
34 transformers_version = '4.12',
35 pytorch_version = '1.9',
36 py_version = 'py38',
37 hyperparameters = hyperparameters,
38 distribution = distribution
39 )

Since, we are using SageMaker Data Parallelism our total_batch_size will be per_device_train_batch_size * n_gpus.

1 # define a data input dictonary with our uploaded s3 uris
2 data = {
3 'train': training_input_path,
4 'eval': eval_input_path
5 }
6
7 # starting the train job with our uploaded datasets as input
8 # setting wait to False to not expose the HF Token
9 huggingface_estimator.fit(data,wait=False)

Since we are using the Hugging Face Hub intergration with Tensorboard we can inspect our progress directly on the hub, as well as testing checkpoints during the training.

1 from huggingface_hub import HfApi
2
3 whoami = HfApi().whoami()
4 username = whoami['name']
5
6 print(f"https://huggingface.co/{username}/{hyperparameters['hub_model_id']}")

tensorboard

Conclusion

We managed to scale our training from 1x GPU to 8x GPU without any issues or code changes required. We used the Python SageMaker SDK to create our managed training job and only needed to provide some information about the environment our training should run, our training script and our hyperparameters.

With this we were able to reduce the training time from 6,5 hours to ~1,5 hours, which is huge! With this we can evaluate and test ~5x more models than before.


You can find the code here and feel free to open a thread on the forum.

Thanks for reading. If you have any questions, feel free to contact me, through Github, or on the forum. You can also connect with me on Twitter or LinkedIn.