Author: torontoai
NLP Data Scientist – Chisel AI – Toronto, ON
From Chisel AI – Thu, 28 Mar 2019 12:10:23 GMT – View all Toronto, ON jobs
Sr. Data Scientist – Thomson Reuters – Toronto, ON
From Thomson Reuters – Thu, 28 Mar 2019 10:27:18 GMT – View all Toronto, ON jobs
Announcing the first winner of the AWS DeepRacer League Summit circuit!
Today, at the AWS Summit in Santa Clara, California, we kicked off the 2019 season of the world’s first global autonomous racing league. The AWS DeepRacer League allows developers of all skill levels to get hands on with machine learning through a series of live racing events at AWS Global Summits around the world. The AWS DeepRacer League includes virtual events and tournaments throughout the year.
It was an exciting day as developers put their machine learning skills to the test! After 9 hours, 400 autonomously driven laps, and over 5 miles of racing, the Santa Clara winner was declared. Chris Miller, founder of Cloud Brigade, based in Santa Cruz California, topped the leaderboard and will be the first victor to advance on an expenses-paid trip to the AWS DeepRacer Championship Cup at re:Invent 2019 in Las Vegas, Nevada. With a winning time of 10.43 seconds, Chris and his team came to the Santa Clara Summit with the intent to learn more about AI and ML “I’m excited about machine learning and the technology that is being made available for modern applications”. Chris trained his winning model in one of the AWS DeepRacer workshops at the summit. Next on the agenda for Chris – he is now preparing for re:Invent by learning more about machine learning and how he can customize his model further.
The top three developers on the leaderboard: Chris Miller (Center) Santa Clara Summit Champion, Rahul Shah (left) First Runner Up, Adrian Sarno (Right) Second Runner Up
Machine Learning available for all
The league is only just beginning and you don’t have to be at an AWS Summit to start learning about machine learning with AWS DeepRacer. Today we are launching a new online digital training course called AWS DeepRacer: Driven by Reinforcement Learning. The course is available at no cost as part of AWS Training and Certification, within the AWS Machine Learning Developer Learning Path. The course has 6 self-guided chapters and in 90 minutes will help you prepare to compete in the AWS DeepRacer League. You will learn how to build a reinforcement learning model and find tips and tricks about how to tune those models to climb the leaderboard.
Up next!
The journey to crown the 2019 AWS DeepRacer Champion continues on April 2nd at the AWS Summit in Paris. Follow the live results on the AWS DeepRacer League webpage. While you’re there, plan your next race. And don’t forget, this competition is open to all. If you don’t have an AWS DeepRacer car or your own model, our Summit pit crew is there to help you select a pre-trained model and race it straight-away. Also, if you can’t make it to any of the in-person events, our virtual circuit is coming soon and will allow anyone, anywhere to compete.
See you on the tracks!
About the Author
Alexandra Bush is a Senior Product Marketing Manager for AWS AI. She is passionate about how technology impacts the world around us and enjoys being able to help make it accessible to all. Out of the office she loves to run, travel and stay active in the outdoors with family and friends.
Train Deep Learning Models on GPUs using Amazon EC2 Spot Instances
You’ve collected your datasets, designed your deep neural network architecture, and coded your training routines. You are now ready to run training on a large dataset for multiple epochs on a powerful GPU instance. You learn that the Amazon EC2 P3 instances with NVIDIA Tesla V100 GPUs are ideal for compute-intensive deep learning training jobs, but you have a tight budget and want to lower your cost-to-train.
Spot-instance pricing makes high-performance GPUs much more affordable for deep learning researchers and developers who run training jobs that span several hours or days. Spot instances allow you to access spare Amazon EC2 compute capacity at a steep discount compared to on-demand rates. For an up-to-date list of prices by instance and Region, visit the Spot Instance Advisor. To learn more about the key differences between spot instances and on-demand instances, I recommend going through this Amazon EC2 user-guide.
Spot instances are great for deep learning workflows, but there are a few challenges associated using spot instances versus on-demand instances. First, spot instances can be preempted and can be terminated with just 2 minutes notice. This means you can’t count on your instance to run a training job to completion. Therefore, it’s not recommended for time-sensitive workloads. Second, instance termination can cause data loss if the training progress is not saved properly. Third, if you decide your application should not be interrupted after launching the spot instance, your only option is to stop the spot instance and re-launch as an on-demand or reserved instance.
To address these challenges, here is a step-by-step tutorial on how to set up spot instances for deep learning training workflows while minimizing training progress loss if a spot interruption occurs. My goal is to implement a setup with the following characteristics:
- Decouple compute, storage and code artifacts, and keep the compute instance stateless. This enables easy recovery and training state restore when an instance is terminated and replaced
- Use a dedicated volume for datasets, training progress (checkpoints) and logs. This volume should be persistent and not be affected by instance termination
- Use a version control system (e.g. Git) for training code. This repo should be cloned to commence/resume training. this enables traceability and prevents loss of code changes when instance is terminated
- Minimize code changes to the training script. This ensures that the training script can be developed independently and backup and snapshot operations are performed outside of the training code
- Automate, automate, automate. Automate replacement instance creation after termination, attaching of dataset and checkpoints EBS volume at launch, moving volumes across Availability Zones, performing instance state restore, resuming training, and terminating instance once training is finished
Deep learning with Spot Instances using TensorFlow and the AWS Deep Learning AMI
In this example, I use spot instances and the AWS Deep Learning AMI to train a ResNet50 model on the CIFAR10 dataset. I use TensorFlow 1.12 configured with CUDA 9 available on the AWS Deep Learning AMI version 21. AWS Deep Learning AMIs are updated frequently, check the AWS Marketplace first to make sure you’re using the latest version compatible with your training code. For TensorFlow 1.13 and CUDA 10 use this AWS Deep Learning AMI instead.
I show you how to set up a spot fleet request for deep learning training jobs, which and you use as a starting point for your specific dataset and models.
To follow along, I assume you’ve met the following pre-requisites:
- You have an AWS account, and AWS CLI tool installed on your host
- You are familiar with Python and at least one deep learning framework
As you go through the implementation details, you learn everything else required. All the code, configuration files and AWS CLI commands are available on GitHub.
I use the following AWS and open-source services and concepts. Figure 1 shows how all of these fit together in our example.
- AWS CLI: I use the CLI to interact with AWS services. Everything you can do with the CLI can also be done through the AWS console. The CLI will let you automate, which is one of my goals for this example.
- Amazon EC2 spot instance and spot instance requests: Spot requests ensure that the specified number of spot instances are running. Spot fleet places spot requests to meet the target capacity and automatically replenish any interrupted instances.
- AWS Deep Learning AMI: An Amazon machine image with pre-installed deep learning frameworks. In this example, I use the GPU-accelerated TensorFlow framework for training
- Amazon Elastic Block Storage (EBS): A persistent volume to store datasets, checkpoints and logs, that can be attached to a currently running instance
- Amazon EBS snapshots: Snapshots let you back up data on your Amazon EBS volumes to Amazon S3. A snapshot contains all of the information needed to restore your data to a new EBS volume and can be used to migrate volumes to a new Availability Zone.
- Amazon EC2 user data and instance metadata: At instance launch, user data shell script can be executed to perform actions such as attaching volumes, initiating training and clean up. Instance metadata allows an instance to query information about itself such as instance-id for use with use data shell scripts
- Amazon IAM role and policy: Grants EC2 instance permissions to use AWS services on your behalf. Essential to automate everything.
Figure 1: Reference architecture for using spot instances in deep learning workflows
Step 1: Set up a dedicated EBS volume for datasets and checkpoints using a general-purpose instance
The first step is to set up our dedicated EBS volume for storing datasets, checkpoints and other information that needs to persist such as logs and other metadata. This step is only done once so I start by launching an on-demand m4.xlarge instance. If your dataset is small and you’re not going to be performing any pre-processing steps during preparation, then you could launch an instance with lesser memory and processing power that may cost less. If you’re going to be transcoding images or running other multi-threaded pre-processing routines then pick a GPU-backed or compute-optimized CPU instance.
Run the following command on your terminal using the AWS CLI. All the commands listed here were tested on a MacOS.
image-id refers to the Deep Learning AMI Ubuntu instance. Be sure to update the security group, key ID and subnet ID to allow SSH connections into the instance. See this documentation page for more details.
Important: Create a subnet in a specific Availability Zone and remember your choice. EBS volumes can only be attached to instances in the same subnet. See Figure 1 for illustration. In this example I use us-west-2b as my Availability Zone for setup. In step 3 I show you how to automate migration of EBS volumes between Availability Zones using EBS snapshots.
Throughout this example, everything in italics needs to be replaced with values specific to your setup, the rest can just be copied.
Next, create an EBS volume for your datasets and checkpoints. Here I request 100 GiB. You should choose a value that suits your dataset needs. The EBS volume should be in the same Availability Zone as your instance. After you create the volume, attach it to your instance. Specify the ID details from the output of the run-instances and create-volume commands.
Follow the steps in the documentation to connect by using SSH into your instance and then format and mount the attached volume. In this example, I use a mount point directory at root named /dltraining
Do this step only once. Later in step 3 you can see how each new spot instance will automatically self-mount the volume at launch so the datasets and checkpoints are available for training.
In this example I use the following paths:
- Datasets:
/dltraining/datasets - Training progress checkpoints:
/dltraining/checkpoints
To follow along with this example, you can create and then leave these directories empty. The training script ec2_spot_keras_training.py will download the CIFAR10 dataset using Keras, the first-time training is initiated.
You can terminate this instance using the command below. Volume setup is now complete and will persist in the Availability Zone it was created in.
Step 2: Create IAM role and policy to grant instance permissions
If you’re new to the cloud, AWS Identity and Access Management (IAM) concepts may be new to you. IAM roles and policies are used to grant instances specific permissions that allow access other AWS services on your behalf.
During training, I want the spot instance to have access to my datasets and checkpoints in the EBS volume I created in step 1. However, only volumes in the same Availability Zone as the instances can be attached to it. If the volume and the instance are in different Availability Zones, a new volume needs to be created using a snapshot of the volume stored in Amazon S3.
All these steps can be performed at instance launch using the AWS CLI and user data bash script, and you can see how in step 3. Here are all the AWS CLI commands you need to run at instance launch:
- Query for volumes with the name tag: DL-datasets-checkpoints (there should be only one)
- Create a snapshot of this volume with tag: DL-datasets-checkpoints-snapshot
- If the instance and volume are in the same Availability Zone, attach volume to the instance
- If the instance and volume are in different Availability Zones, create a new volume from the snapshot in the instance’s Availability Zone with name: DL-datasets-checkpoints, and attach it to the instance. Delete the volume in the different Availability Zone to ensure there is only one copy.
- Once training is complete, cancel the spot fleet request and terminate all training instances
In order for the instance to be able to perform these actions, I will need to grant the instance the permissions to do so on my behalf. This way I don’t grant the instance all the same permissions that I as a user have and risk potential abuse.
I start by first creating a role for my Amazon EC2 instance, called the IAM role. After that I grant specific permissions to this role by creating what is called a policy. Execute the following command to create a new IAM role. I’ve named my role DL-Training feel free to choose another name.
Next, I will create and attach a policy that grants the instance the following permissions:
- Describe, create, attach and delete volumes
- Create snapshots from volumes
- Describe spot instances
- Cancel spot fleet requests and terminate instances
You can grant permissions to access other AWS services if you’re going to be using them in your application. In general, the more specific you are about the actions the instance takes the better. The permissions are in a file called ec2-permissions-dl-training.json on the example GitHub repository.
And run the following to create a policy and attach it to our IAM role:
Be sure to substitute <account_id> with your AWS account ID in the attach-role-policy command.
Step 3: Create EC2 user data bash script
Next, I create a launch specification file with details about the instance you want to run your training on. In this example I’m going to be using a p3.2xlarge. If you’re running a multi-GPU training job then you can request for an instance with more GPUs. Note, by multi-GPU jobs, I’m referring to multiple GPUs on the same instance. Currently, the maximum number of GPUs you can get on a single instance are 8 GPUs with a p3.16xlarge or p3dn.24xlarge. I cover distributed/multi-node training use-cases in a future blog post.
As discussed in step 2, Amazon EC2 allows you to pass user data shell scripts to an instance that gets executed at launch. Let’s take a look at our user data shell script. The full script (user_data_script.sh) is available on GitHub.
There are 4 key sections in the file:
Get instance ID and query volume
In this section the script queries the instance metadata API to access to the ID instance on which this script is running. It then uses this information to search for the datasets and checkpoints volume with the tag: DL-datasets-checkpoints
Check if the volume and instance are in the same availability zone
In this section the script checks with the volume and the instance are in the same Availability Zone. If they are in different Availability Zones, it first creates a point-in-time snapshot of the volume in Amazon S3. Once the snapshot is created, it deletes the volume and creates a new volume from the snapshot in the instance’s Availability Zone. Figure 2 illustrates the two patterns.
The aws ec2 wait command ensures that snapshot and volume creation are complete before proceeding to the next command.
Figure 2: On spot instance termination, if a new spot instance is launched in a different availability zone (a), EBS volume snapshots are saved to S3 and a new volume is created from the snapshot in the instance’s availability zone. If the new spot instance is launched in the same availability zone as the volume (b), the same EBS volume is attached to the new instance
Attach and mount volume: In this section the script first attaches the volume that is in the same Availability Zone as the instance. It then mounts the attached volume to the mount point directory at /dltraining. And then updates the ownership to the Ubuntu user since the user data script is run as root.
Get training scripts: In this section, the script clones the training code git repository
Initiate/resume training: The script activates the tensorflow_p36 Conda environment and runs the training script as the Ubuntu user. The training script takes care of loading the dataset from the Amazon EBS volume and resuming training from checkpoints. Step 4 will go into the modification needed for your training script.
Clean up: Once training is complete, the script cleans up by canceling spot fleet requests associated with the current instance. cancel-spot-fleet-requests can also terminate instances managed by the fleet.
Step 4: Create a spot fleet request configuration file
Next, I will create a spot fleet configuration file that includes target capacity (1 instance in our example), launch specifications for the instance, and the maximum price that you are willing to pay. Spot fleet places requests to meet the target capacity and automatically replenish any interrupted instances.
Under LaunchSpecifications section, I have two different specifications.
- A p3.2xlarge instance type that may be placed in any Availability Zone within the us-west-2 Region
- A p2.xlarge instance type that may be placed in any Availability Zone within the us-west-2 Region
The spot fleet configuration is in a file called spot_fleet_config.json in the example GitHub repository. Spot fleet configuration file gives you the flexibility to mix and match instance types and Availability Zones. If your training script takes advantage of NVIDIA Tesla V100’s mixed-precision Tensor Cores, you may want to restrict instance types to only p3.2xlarge. The p2.xlarge with NVIDIA Tesla K80 only supports single (FP32) and double precision (FP64), and are cheaper but slower than V100 for deep learning training. Choose a combination that suits your needs.
Be sure to use a security group that allows you to SSH into the instance for debugging and checking progress manually and use your Key pair name for authentication. Under IAM instance profile, update the IAM role you created in step 2, that grants the instance necessary permissions.
To use the spot fleet Request, create an IAM fleet role by running the following commands:
In the configuration snippet above, under user data you have to replace the text base64_encoded_bash_script with base64-encoded user data shell script. To do this you can use the base64 utility available on Mac and linux based OS. The following works on a Mac; for Linux flavors, replace -b with -w to remove line breaks. The sed command replaces all occurrences of the string base64_encoded_bash_script with the base64-encoded bash script.
Step 5: Update deep learning training script
The final step is to update your deep learning training script to ensure datasets are loaded from and checkpoints are saved to the attached Amazon EBS volume. In this example I’m training a ResNet50 model on the CIFAR10 dataset. A typical deep learning training script may have the following steps. In pseudo-code below, are changes you’ll need to make to your training script to use with our setup.
To summarize,
- Load data from the mounted Amazon EBS volume, in our example that would be
/dltraining - Check if a checkpoint exists, then load the checkpoint and update epoch number to resume training. If not, define the model architecture and start training from scratch.
- In the training loop, check if termination notice has been issued. If yes, then pause training to avoid termination during checkpointing to avoid corrupt or incomplete checkpoints.
- If termination notice hasn’t been issued, save the model checkpoints to
/dltraining/checkpoints/
The training script for this example is called ec2_spot_keras_training.py and is available in the example repository. Below is a code snippet from our training script. The function load_checkpoint_model() loads the latest checkpoint to resume training.
Since I’m using Keras with a TensorFlow backend, I didn’t have to explicitly write the training loop. Keras provides convenient callback functions for saving checkpoints and logging progress after each epoch.
Note: if you’re implementing your own training loop with TensorFlow’s low-level API, PyTorch or other framework, you are responsible for checkpointing progress. This can be very tricky if you don’t know what you’re doing. To resume training properly, you’ll need to make sure that you’re saving (1) model architecture to re-define the model (2) completed epoch number and weights of the model at the end of the current epoch (3) training hyper-parameters such as loss function, optimizer, learning rate schedule etc. (4) optimizer state at the end of the epoch
Keras callbacks I’m using to checkpoint progress and check for termination status are below:
Step 6: Initiate spot request to start the training
I’m now ready to submit our spot fleet request using the spot_fleet_config.json configuration file I created in Step 4.
How it all comes together
So far I’ve introduced lot of code, configuration files and AWS CLI commands. Figure 3 shows how all these code and configuration artifacts fit together. Let’s walk through the process so you can get a better sense of how they are all connected.
Figure 3: Data, code and configuration artifacts dependency chart
Let’s start with you, the user.
As a deep learning researcher or developer, first prototype and develop your models locally or on an inexpensive CPU-only Amazon EC2 on-demand instance with the AWS Deep Learning AMI. When you’re ready to run a training job on GPUs, you then push your training scripts to a Git repository.
Next, submit a spot request using the aws ec2 request-spot-fleet command shown in step 6. This sets everything into motion.
The spot request uses the spot fleet configuration file spot_fleet_config.json to launch the desired spot instance type. In this example, you run a training job on a p3.2xlarge instance in any of the us-west-2 Region’s Availability Zones. The training script will run on an instance imaged using the AWS Deep Learning AMI, which includes GPU optimized TensorFlow framework.
The spot fleet configuration file also includes the user_data_script.sh bash script file. The user data bash script is executed on the spot instance at launch. This script is responsible for mounting the dataset and checkpoint volume, cloning the training scripts, and initiating the training as we saw in step 3.
In the event of a spot interruption due to higher spot instance price or lack of capacity, the instance will be terminated and the dataset and checkpoints Amazon EBS volume will be detached. Spot fleet then places another request to automatically replenish the interrupted instance.
When the request is fulfilled again, a new spot instance will be launched and it will execute the user_data_script.sh at launch. The script queries for the dataset and checkpoint volume. If the volume and the instance are in different Availability Zones, it first creates a snapshot of the volume and then creates a new volume based on the snapshot in the current instance’s Availability Zone. The volume in the previous Availability Zone is deleted to ensure there is only one source of truth.
The script then attaches the volume to the instance and resumes training from the most recent checkpoint. Once training is complete the spot fleet request is cancelled and the current running instance is terminated.
If you want to specify a higher maximum spot instance price, or change instance types or Availability Zones, simply cancel the running spot fleet request by issuing aws ec2 cancel-spot-fleet-requests and initiating a new request with an updated spot fleet configuration file spot_fleet_config.json
Summary
That’s your overview about how spot instances can be used to run deep learning training experiments on GPU instances at a much lower cost than on-demand instances.
The setup in this blog post can be extended to cover more advanced deep learning workflows, and here are some ideas:
- Multi-GPU training. Update the training script to enable multi-GPU training
- Sub-epoch granularity checkpointing and resuming. In this example, checkpoints are saved only at the end of each epoch. For large datasets and complex models that take long time to finish an epoch, frequent checkpointing minimizes progress loss during interruption.
- Multiple parallel experiments. Increase spot fleet target capacity to run multiple independent training jobs with different hyperparameters.
I hope you enjoyed reading this post. If you have questions, comments or feedback please use the comments section below. Happy spot training!
About the Author
Shashank Prasanna is an AI & Machine Learning Technical Evangelist at Amazon Web Services (AWS) where he focuses on helping engineers, developers and data scientists solve challenging problems with machine learning. Prior to joining AWS, he worked at NVIDIA, MathWorks (makers of MATLAB & Simulink) and Oracle in product marketing, product management, and software development roles.
Vector Institute’s Chief Scientific Advisor, Dr. Geoffrey Hinton, receives ACM A.M. Turing Award alongside Dr. Yoshua Bengio and Dr. Yann LeCun.

Today, Vector’s very own Chief Scientific Advisor, Dr. Geoffrey Hinton, received computer science’s top distinction, the ACM A.M. Turing Award, for his foundational research in deep learning, neural networks, and artificial intelligence (AI). Dr. Hinton is also VP and Engineering Fellow, Google, and Emeritus Professor, University of Toronto.
Along with Dr. Hinton, this year’s winners include fellow Canadian, Dr. Yoshua Bengio, and New York-based Dr. Yann LeCun, the latter of whom did his postdoctoral research with Dr. Hinton at the University of Toronto. Together, they are considered the founding fathers of deep learning. Like the award’s namesake, each one of them has pushed the boundaries of understanding and possibility in computing. And they have all made research advancements in Canada.
Introduced in 1966, the Turing Award is computing’s highest honour. The award celebrates scientists and engineers for propelling the field forward and making a significant technical impact. It comes with a $1 million, Google-sponsored prize.
As a Canadian-based researcher and Companion of the Order of Canada, Dr. Hinton – and the recognition he has received thus far – has shone an international spotlight on the revolutionary work in machine learning and AI being done right here.
Just two years ago, Canada became the first country to announce a national AI strategy, taking our place at the forefront of the field. More and more leading global companies, public institutions, and tech startups look to us to lead. Dr. Hinton and others continue to make great strides, and their influence extends well beyond the lab.
Since Vector’s inception in 2017, we have been among a series of catalysts for over $1 billion in AI and tech-related investments, which will result in the creation of 25,000 jobs across Canada. Over 240 researchers, encompassing faculty, postdocs, students, and affiliates, have become part of Vector’s community. And now we have a Turing Award winner amongst us.
The future of AI is bright, and Canada will play a major role in unlocking its potential.
“I am honoured to receive the ACM A.M. Turing Award, a high honour and recognition from the computer science community. Deep learning and neural networks have tremendous potential to revolutionize nearly every sector of society – from predicting aftershocks or floods to designing new materials and pharmaceuticals to interpreting medical images and personalized medicine. With the ever-increasing volume of data and computing capacity, industry has woken up to the transformational power of this technology. The Vector Institute is playing a unique role as a convener of academia and industry, enabling Vector’s researchers and industry sponsors to take bold steps and realize the full potential of the technology for which Yann and Yoshua and I are being recognized today. Together, we are ensuring Canadian companies and all Canadians benefit from ongoing research in the field.”
– Dr. Geoffrey Hinton, Chief Scientific Advisor, Vector Institute; VP and Engineering Fellow, Google; Emeritus Professor, University of Toronto
CVPR 2019 Challenges on Domain Adaptation in Autonomous Driving
We all dream of a future in which autonomous cars can drive us to every corner
of the world. Numerous researchers and companies are working day and night to
chase this dream by overcoming scientific and technological barriers. One of the
greatest challenges we still face is developing machine learning models that can
be trained in a local environment and also perform well in new, unseen
situations. For example, self-driving cars may utilize perception models to
recognize drivable areas from images. Companies in Silicon Valley can build and
perfect such a model using large local datasets from the Bay Area for training.
However, if the same model were deployed in a snowy area such as Boston, it
would likely perform miserably, because it has never seen snow before. Boston,
during winter, and Silicon Valley, during any time of the year, can be labeled
as separate domains for perception models, since they present clear differences
in climate and challenges in perception. In other cases, domains may be much
closer in nature, such as a city street and a nearby highway. The process of
transferring knowledge and models between different domains in machine learning
is called domain adaptation.
A large number of papers on domain adaptation of perception models have appeared
in top publishing venues for machine learning and computer vision. However, most
of these works focus on image classification and semantic segmentation. Hardly
any attention has been paid to instance-level tasks, such as object detection
and tracking, even though localization of nearby objects is arguably more
important for autonomous driving. To foster the study of domain adaptation of
perception models, Berkeley
DeepDrive and Didi Chuxing are
co-hosting two competitions in CVPR 2019 Workshop on
Autonomous Driving. The challenges will focus on domain adaptation of object
detection and tracking based on the BDD100K, from Berkeley DeepDrive, and
D2-City, from Didi Chuxing, datasets. The domain of BDD100K covers US
scenes, while D2-City was collected on China’s streets. The
competitions ask participants to transfer object detectors from BDD100K to
D2-City and object trackers from D2-city to BDD100K. More
information about the challenges can be found on our website and D2-City.
Following our introduction of the BDD100K dataset, we have been busy working to
provide more temporal annotations. Above is an example of object tracking
annotation, created by our open-source annotation platform Scalabel. Some of the tracking labels are
used in the domain adaptation challenge for object tracking. More data will be
released this summer. Of course, we also have object tracking at night.
Software Developer, Omnia AI – Toronto – Deloitte – Toronto, ON
From Deloitte – Tue, 26 Mar 2019 22:39:49 GMT – View all Toronto, ON jobs
Reducing deep learning inference cost with MXNet and Amazon Elastic Inference
Amazon Elastic Inference (Amazon EI) is a service that allows you to attach low-cost GPU-powered acceleration to Amazon EC2 and Amazon SageMaker instances. MXNet has supported Amazon EI since its initial release at AWS re:Invent 2018.
In this blog post, we’ll explore the cost and performance benefits of using Amazon EI with MXNet. We’ll walk you through an example that shows you how we improved our initial inference latency of 43ms by 1.69x, and how we improved cost efficiency by 75 percent.
The benefits of Amazon Elastic Inference
Amazon Elastic Inference can reduce the cost of running deep learning inference by up to 75 percent. First let’s take a look at how Elastic Inference compares to other Amazon EC2 options in terms of performance and cost.

The table below lists the specific details for each EC2 option, in terms of resources, capacity and cost. Note that the c5.xlarge plus eia1.xlarge has a similar amount of compute capacity as a p2.xlarge (see the two highlighted rows in the table below).
| Instance Type | vCPUs | CPU Memory (GB) | GPU Memory (GB) | FP32 TFLOPS | $/hour | TFLOPS/$/hr |
| C5.Large | 2 | 4 | – | 0.08 | $0.09 | 0.94 |
| C5.XLarge | 4 | 8 | – | 0.17 | $0.17 | 1.00 |
| C5.2XLarge | 8 | 16 | – | 0.33 | $0.34 | 0.97 |
| C5.4XLarge | 16 | 32 | – | 0.67 | $0.68 | 0.99 |
| C5.9XLarge | 32 | 64 | – | 1.34 | $1.36 | 0.99 |
| P2.XLarge (K80) | 4 | 61 | 12 | 4.30 | $0.90 | 4.78 |
| P3.2XLarge (V100) | 8 | 61 | 16 | 15.70 | $3.06 | 5.13 |
| EIA1.Medium | – | – | 1 | 1.00 | $0.13 | 7.69 |
| EIA1.Large | – | – | 2 | 2.00 | $0.26 | 7.69 |
| EIA1.Xlarge | – | – | 4 | 4.00 | $0.52 | 7.69 |
| C5.XL + EIA.XL | 4 | 8 | 4 | 4.17 | $0.69 | 6.04 |
If we look at the compute capability (Tera-Floating-point-Operations-Per-Second, or TFLOPS) a C5.4XLarge provides 0.67 TFLOPS of performance for $0.68 an hour, whereas an EIA1.Medium with 1.00 TFLOPS costs just $0.13 per hour. If pure performance (ignoring costs) is the goal, clearly leveraging a P3.2XLarge instance will provide the most compute at 15.7 TFLOPS. But in the last column showing TFLOPS per dollar we see that the EI accelerators (EIA) provide the most value. Since EI accelerators (EIA) must be attached to an EC2 instance, the last row shows one possible combination. The C5.XLarge plus the EIA1.XLarge has a similar amount of vCPUs and TFLOPS as a P2.XLarge, but the cost per hour of the C5XLarge plus the EIA1.XLarge is $0.69 per hour compared with $0.90 per hour for the P2.XLarge. That’s a $0.21 per hour discount. This highlights the other benefit of using Amazon EI which is being able to configure the amount of vCPUs, memory, and GPU compute to match your needs.
Using Apache MXNet with Amazon EI
Apache MXNet is an open source deep learning framework used to build, train, and deploy deep neural networks. MXNet abstracts much of the complexity involved in implementing neural networks, is highly performant and scalable, and offers APIs across popular programming languages such as Python, C++, Java, R, Scala, and more. Amazon EI enabled Apache MXNet is available in the AWS Deep Learning AMI. A ‘pip’ package is also available on Amazon S3 so you can build it in to your own Amazon Linux or Ubuntu AMIs, or Docker containers.
Now we’ll analyze the performance (latency) and cost efficiency trade-offs for a ResNet-152 model for various instances. We’ll start with this example code from AWS and modify it for this blog post. The changes required to measure inference performance are in blue below:
You can see we added a loop around the inference call and timed the forward() and get_outputs() functions. MXNet uses lazy evaluation, so to force it to execute the forward call we need to use the outputs (by converting them to a numpy array). The first inference is abnormally slow due to initialization with the remote GPU on the EIA, so we stored the first inference time and summed the remaining inference latencies to compute an average.
Setting up an instance with an EI accelerator
We’ll launch an instance using the AWS Deep Learning AMI (DLAMI), which already provides support for Apache MXNet with Amazon EI. You can review Elastic Inference Prerequisites for the instructions related to Elastic Inference. You can review how to launch a DLAMI with an Elastic Inference Accelerator in the Elastic Inference documentation.
Testing on an instance with an EI accelerator
We launched a C5.4XLarge instance with the largest EI accelerator: EIA1.XLarge. This is probably more compute than we need but it will give us a good starting point from which to work backward from the best performance we can get with EI. Next, we activated the conda environment that was pre-installed for MXNet on EI with the following command:
Running our code on an instance with an EI accelerator produces this output:
Notice that the larger first inference time is 2763.00 ms. After the first inference, the average for the other 99 iterations is 20.34 ms.
Testing on a C5 instance
We can use the same script with just one change to run inference using only the CPU on the same instance. Here MXNet won’t use the EI accelerator when we set the context to CPU:
Running this code now produces this output:
Notice that the average inference is 44.61 ms. Compared to our initial run using the EI accelerator, the CPU takes 2.19x longer for each inference call on average when using a standard C5 instance.
Testing on GPU instances
Next, we launched a separate P2.XLarge instance to compare the performance to. We used the same DLAMI version. After the instance was launched we activated the regular MXNet conda environment:
Now we need to make two more tweaks to our script:
The first context that we change is the one used for binding, and the second context we change is the one that defines where our input data resides. For CPU and EIA instances, data must be allocated on a CPU context. It’s important to point out that typically you create your ndarrays on the same context that you bind the model to (CPU for CPU, and GPU for GPU). But for EIA you bind your model to the EIA context. You create your data with the CPU context. MXNet automatically copies the data over as needed for EIA.
Running this code on the P2.XLarge instance now produces this output:
Before we draw any conclusions, let’s launch a separate P3.2XLarge instance to compare the performance to. We can reuse the same script, DLAMI, and conda environment that we used earlier for the P2.XLarge instance. Running the code now produces this output on the P3.2XLarge instance:
Comparing C5, P2, P3, and EIA instances
Plotting the data we’ve collected thus far we can see that GPU performed better than CPU (as expected) and the V100 GPU in P3 instances is 3.34x faster than the K80 GPU in P2 instances. Where before you had to choose between P2 and P3, now EI gives you another choice in between with a 2.02x increase in speed over P2.

Based purely on instance cost per hour (in us-east-1 for EIA and EC2) we can see that the cost for the C5.4XL + EIA.XL is in between the costs for the P2 and P3 instances (see the following table). However, when factoring the cost to perform 100,000 inferences we can see that the P2 and P3 instances have similar costs, and the C5.4XL and the C5.4XL +EI instances are also within a penny of each other ($0.84 and $0.83). The big picture here is that by using EIA we get better than P2 performance at the cost of a C5 instance. What a deal!
| Instance Type | Cost per hour | Infer latency [ms] | Cost per 100k inferences |
| C5.4XLarge | $0.68 | 44.61 | $0.84 |
| C5.4XL + EIA.XL | $1.20 | 24.89 | $0.83 |
| P2.Xlarge | $0.90 | 41.10 | $1.03 |
| P3.2XLarge | $3.06 | 12.31 | $1.05 |
Exploring all possibilities
Now, let’s do more investigation and try out additional instance combinations for EI. After rerunning the initial script we started with on combinations of C5.Large, C5.XLarge, C5.2XLarge, and C5.4XLarge with EI accelerators EIA1.Medium, EIA1.Large, and EIA1.XLarge we produced the latest table:
| Host instance type | EI Accelerator type | Cost per hour | Infer latency [ms] | Cost per 100k inferences |
| C5.Large | EIA1.Medium | $0.22 | 39.00 | $0.23 |
| EIA1.Large | $0.35 | 25.68 | $0.25 | |
| EIA1.XLarge | $0.61 | 20.29 | $0.34 | |
| C5.XLarge | EIA1.Medium | $0.30 | 38.55 | $0.32 |
| EIA1.Large | $0.43 | 25.99 | $0.31 | |
| EIA1.XLarge | $0.69 | 21.12 | $0.40 | |
| C5.2XLarge | EIA1.Medium | $0.47 | 38.56 | $0.50 |
| EIA1.Large | $0.60 | 26.45 | $0.44 | |
| EIA1.XLarge | $0.86 | 20.76 | $0.50 | |
| C5.4XLarge | EIA1.Medium | $0.81 | 39.18 | $0.88 |
| EIA1.Large | $0.94 | 25.90 | $0.68 | |
| EIA1.XLarge | $1.20 | 20.34 | $0.68 |
In this table, when we look at the host instance types with the EIA1.Medium (yellow highlight) we see similar results. This means that there isn’t a lot of host-side processing, so going to a larger host instance doesn’t improve performance. This indicates to us that we can save on cost by choosing a smaller instance. Similarly, looking at host instances with all using the largest EIA1.XLarge accelerator (blue highlight) there isn’t a noticeable performance difference either. This confirms that EIA performance isn’t limited by the size of the host either. It also means that we can continue to use the C5.Large host instance type, achieve the same performance, and pay less.
Comparing inference latency
Now that we’ve decided on a C5.Large host instance type, we can look at the accelerator types. There is a progression from 39.18ms to 25.90ms and finally to 20.34ms in terms of inference latency. The following chart shows what we get if we add our new data points for the various accelerator sizes to our previous chart:

This chart shows that the EI accelerators provide a set of steps between P2 and P3 in terms of raw performance.
Comparing inference cost efficiency
The last column in the table shows the cost efficiency of the combination. Reviewing this column we see that the C5.Large + EIA1.Medium has the best cost efficiency. In a pure least-cost comparison, the C5.Large + EIA1.Medium combination provides the best cost efficiency when compared to the C5.4XL and the P2/P3 instances. Savings are 71 percent to 77 percent. And the C5.Large + EIA1.XLarge provides a 2.02x increase in speed over a P2 and a 2.19x speedup over the C5.4XL (CPU only). The savings are 66 percent and 59 percent, respectively.
Conclusions
Here’s what we’ve found so far:
- Combining EI accelerators with any host instance type enables users to choose the amount of host compute, memory, etc. with a configurable amount of GPU memory and compute.
- EI accelerators provide a range of memory and compute that is similar to P2 instances, but with a lower cost
- EI accelerators can bridge the gap in terms of raw performance (inference latency) between P2 and P3 instance types.
- EI accelerators can achieve a better cost efficiency than C5 and P2/P3 instances.
In our analysis we found that the ease of use in MXNet is as simple as changing the context for binding a model and ndarray creation. This allowed us to use largely the same test script on CPU, GPU, and EIA contexts in MXNet, and ease our testing and performance analysis.
We started with a Resnet-152 model running on a C5.4XLarge instance with a 44ms inference latency. We reduced it to 20ms by migrating to a C5.Large + EIA.XLarge. This resulted in a 2.19x increase in speed with a $0.07 hourly cost savings to top it off. We also found that we could achieve a 71 percent cost savings ($0.84versus $0.24 per 100k inferences) with a C5.Large + EIA.Medium and still get better performance (44ms versus 39ms).
Call to Action
Try out MXNet on EI and see how much you can save while still improving performance for inference on your model. Here are the steps we went through to analyze the design space for deep learning inference, and you can follow these steps for your model:
- Write a test script to analyze inference performance for CPU context.
- Create copies of the script with tweaks for GPU and EIA contexts.
- Run scripts on C5, P2, and P3 instance types to get a baseline for performance.
- Analyze the performance of EIA.
- Start with largest EI accelerator type and a large host instance type.
- Work backward until you find a combo that is too small.
- Introduce cost efficiency to the analysis by computing the cost to perform 100k inferences.
How much can you save while still improving the performance of inference for your model? How fast can you improve the inference latency of your model without spending a single cent more? Share your results in the comments section.
About the Authors
Sam Skalicky is a Software Engineer with AWS Deep Learning and enjoys building heterogeneous high performance computing systems. He is an avid coffee enthusiast and avoids hiking at all costs.
Hagay Lupesko is an Engineering Manager for AWS Deep Learning. He focuses on building Deep Learning tools that enable developers and scientists to build intelligent applications. In his spare time he enjoys reading, hiking and spending time with his family.