Distributed data parallel MaskRCNN training with PyTorch and SageMaker distributed

Amazon SageMaker’s distributed library can be used to train deep learning models faster and cheaper. The data parallel feature in this library (smdistributed.dataparallel) is a distributed data parallel training framework for PyTorch, TensorFlow, and MXNet.

This notebook demonstrates how to use smdistributed.dataparallel with PyTorch(version 1.10.2) on Amazon SageMaker to train a MaskRCNN model on COCO 2017 dataset using Amazon FSx for Lustre file-system as data source.

The outline of steps is as follows:

  1. Stage COCO 2017 dataset on Amazon S3

  2. Create Amazon FSx Lustre file-system and import data into the file-system from S3

  3. Build Docker training image and push it to Amazon ECR

  4. Configure data input channels for SageMaker

  5. Configure hyper-prarameters

  6. Define training metrics

  7. Define training job, set distribution strategy to SMDataParallel and start training

NOTE: With large training dataset, we recommend using Amazon FSx as the input file system for the SageMaker training job. FSx file input to SageMaker significantly cuts down training start up time on SageMaker because it avoids downloading the training data each time you start the training job (as done with S3 input for SageMaker training job) and provides good data read throughput.

NOTE: This example requires SageMaker Python SDK v2.X

Amazon SageMaker Initialization

Initialize the notebook instance. Get the AWS Region and a SageMaker execution role.

SageMaker role

The following code cell defines role which is the IAM role ARN used to create and run SageMaker training and hosting jobs. This is the same IAM role used to create this SageMaker Notebook instance.

role must have permission to create a SageMaker training job and host a model. For granular policies you can use to grant these permissions, see Amazon SageMaker Roles. If you do not require fine-tuned permissions for this demo, you can use the IAM managed policy AmazonSageMakerFullAccess to complete this demo.

As described above, since we will be using FSx, please make sure to attach FSx Access permission to this IAM role.

[ ]:
%%time
! python3 -m pip install --upgrade sagemaker
import sagemaker
from sagemaker import get_execution_role
from sagemaker.estimator import Estimator
import boto3

sagemaker_session = sagemaker.Session()
bucket = sagemaker_session.default_bucket()

role = (
    get_execution_role()
)  # provide a pre-existing role ARN as an alternative to creating a new role
role_name = role.split(["/"][-1])
print(f"SageMaker Execution Role:{role}")
print(f"The name of the Execution role: {role_name[-1]}")

client = boto3.client("sts")
account = client.get_caller_identity()["Account"]
print(f"AWS account:{account}")

session = boto3.session.Session()
region = session.region_name
print(f"AWS region:{region}")

To verify that the role above has required permissions:

  1. Go to the IAM console: https://console.aws.amazon.com/iam/home.

  2. Select Roles.

  3. Enter the role name in the search box to search for that role.

  4. Select the role.

  5. Use the Permissions tab to verify this role has required permissions attached.

Prepare SageMaker Training Images

  1. SageMaker by default use the latest Amazon Deep Learning Container Images (DLC) PyTorch training image. In this step, we use it as a base image and install additional dependencies required for training MaskRCNN model.

  2. In the GitHub repository https://github.com/HerringForks/DeepLearningExamples.git we have made a smdistributed.dataparallel PyTorch MaskRCNN training script available for your use. We will be installing the same on the training image.

Build and Push Docker Image to ECR

Run the below command build the docker image and push it to ECR.

[ ]:
image = "<ADD NAME OF REPO>"  # Example: mask-rcnn-smdataparallel-sagemaker
tag = "<ADD TAG FOR IMAGE>"  # Example: pt1.8
[ ]:
!pygmentize ./Dockerfile
[ ]:
!pygmentize ./build_and_push.sh
[ ]:
dlc_account_id = 763104351884  # By default, set the account ID used for most regions
[ ]:
! aws ecr get-login-password --region {region} | docker login --username AWS --password-stdin {dlc_account_id}.dkr.ecr.{region}.amazonaws.com
! chmod +x build_and_push.sh; bash build_and_push.sh {dlc_account_id} {region} {image} {tag}

Preparing FSx Input for SageMaker

  1. Download and prepare your training dataset on S3.

  2. Follow the steps listed here to create a FSx linked with your S3 bucket with training data - https://docs.aws.amazon.com/fsx/latest/LustreGuide/create-fs-linked-data-repo.html. Make sure to add an endpoint to your VPC allowing S3 access.

  3. Follow the steps listed here to configure your SageMaker training job to use FSx https://aws.amazon.com/blogs/machine-learning/speed-up-training-on-amazon-sagemaker-using-amazon-efs-or-amazon-fsx-for-lustre-file-systems/

Important Caveats

  1. You need to use the same subnet and vpc and security group used with FSx when launching the SageMaker notebook instance. The same configurations will be used by your SageMaker training job.

  2. Make sure you set appropriate inbound/output rules in the security group. Specially, opening up these ports is necessary for SageMaker to access the FSx file system in the training job. https://docs.aws.amazon.com/fsx/latest/LustreGuide/limit-access-security-groups.html

  3. Make sure SageMaker IAM Role used to launch this SageMaker training job has access to AmazonFSx.

SageMaker PyTorch Estimator function options

In the following code block, you can update the estimator function to use a different instance type, instance count, and distribution strategy. You’re also passing in the training script you reviewed in the previous cell.

Instance types

SMDataParallel supports model training on SageMaker with the following instance types only. For best performance, it is recommended you use an instance type that supports Amazon Elastic Fabric Adapter (ml.p3dn.24xlarge and ml.p4d.24xlarge).

  1. ml.p3.16xlarge

  2. ml.p3dn.24xlarge [Recommended]

  3. ml.p4d.24xlarge [Recommended]

Instance count

To get the best performance and the most out of SMDataParallel, you should use at least 2 instances, but you can also use 1 for testing this example.

Distribution strategy

Note that to use DDP mode, you update the distribution strategy, and set it to use smdistributed dataparallel.

[ ]:
import os
from sagemaker.pytorch import PyTorch
[ ]:
instance_type = "ml.p4d.24xlarge"  # Other supported instance type: ml.p3.16xlarge, ml.p4d.24xlarge
instance_count = 2  # You can use 2, 4, 8 etc.
docker_image = f"{account}.dkr.ecr.{region}.amazonaws.com/{image}:{tag}"  # YOUR_ECR_IMAGE_BUILT_WITH_ABOVE_DOCKER_FILE
region = "<REGION>"  # Example: us-west-2
username = "AWS"
subnets = ["<SUBNET_ID>"]  # Should be same as Subnet used for FSx. Example: subnet-0f9XXXX
security_group_ids = [
    "<SECURITY_GROUP_ID>"
]  # Should be same as Security group used for FSx. sg-03ZZZZZZ
job_name = "pytorch-smdataparallel-mrcnn-fsx"  # This job name is used as prefix to the sagemaker training job. Makes it easy for your look for your training job in SageMaker Training job console.
file_system_id = "<FSX_ID>"  # FSx file system ID with your training dataset. Example: 'fs-0bYYYYYY'
config_file = (
    "e2e_mask_rcnn_R_50_FPN_1x_16GPU_4bs.yaml"  # file that specifies the model config options
)

In the hyperparameter’s dictionary, add the following: 1. To use AMP (FP16), add "fp16": "" to set True. In the training script, there’s already an option action="store_true" that automatically sets the empty inputs to True. 2. To properly set the training data path for the SageMaker training environment, add "data-dir": "/opt/ml/input/data/train".

[ ]:
hyperparameters = {
    "config-file": config_file,
    "skip-test": "",
    "seed": 987,
    "fp16": "",
    "max_steps": 1000,
    "data-dir": "/opt/ml/input/data/train",
}
[ ]:
estimator = PyTorch(
    entry_point="train_pytorch_smdataparallel_maskrcnn.py",
    role=role,
    image_uri=docker_image,
    source_dir=".",
    instance_count=instance_count,
    instance_type=instance_type,
    framework_version="1.10.2",
    py_version="py38",
    sagemaker_session=sagemaker_session,
    hyperparameters=hyperparameters,
    subnets=subnets,
    security_group_ids=security_group_ids,
    debugger_hook_config=False,
    # Training using SMDataParallel Distributed Training Framework
    distribution={"smdistributed": {"dataparallel": {"enabled": True}}},
)
[ ]:
# Configure FSx Input for your SageMaker Training job

from sagemaker.inputs import FileSystemInput

file_system_directory_path = "YOUR_MOUNT_PATH_FOR_TRAINING_DATA"  # NOTE: '/fsx/' will be the root mount path. Example: '/fsx/mask_rcnn/PyTorch'
file_system_access_mode = "ro"
file_system_type = "FSxLustre"
train_fs = FileSystemInput(
    file_system_id=file_system_id,
    file_system_type=file_system_type,
    directory_path=file_system_directory_path,
    file_system_access_mode=file_system_access_mode,
)
data_channels = {"train": train_fs}
[ ]:
# Submit SageMaker training job
estimator.fit(inputs=data_channels, job_name=job_name)