AI Model Deployment
Deploy Custom AI Models to Production Platforms
Table of Contents
-
Introduction
What this is about and why it is relevant
-
Why Build a Custom Model?
The benefits of building a custom model
-
How to Build a Custom Model
3 different ways to build a custom model
-
Building a Model from Scratch
Using PyTorch to build a model architecture
-
Exporting the Model
Convert the Model to ONNX
End-to-End Deployment of AI Models
The pace at which Artificial Intelligence is developing is breathtaking. The scientific community generates an endless stream of ever-improving models and research which pushes the performance and accuracy of AI models to new heights. Frameworks like PyTorch and TensorFlow provide powerful facilities for building and training modern deep-layered networks.
At Quilliance we employ state-of-the-art AI models to solve complex computational problems. However, the majority of AI scientific literature and online resources focuses on architecting and training AI models. In this article, we explain the process on how to move a trained AI model to different production environments.
We explain how you can get your model from the Python training domain and integrate it with your apps, software and enterprise architecture. It shows how a model training using PyTorch is converted and used in TensorRT for Cuda-based servers and embedded devices.
Building a Custom Model
Why Build a Custom Model?
There is a myriad of powerful of AI models which are available ready-for-use. However, there are multiple reasons why building and training your own model:
-
Your Own Data
The structure of your data assets are different from the data for which existing models are trained. For example, most visual classification and detection models are trained for common classes such as cats, dogs, cars, etc. But you need a visual model to detect products from your own portfolio.
-
Optimized Architectures
You can adapt the architecture of existing high-performance models to better match your use case. For example, most visual detection model use special architectural patterns to detect objects at different scales inside an image (a big cat in the foreground versus a small cat in the background). However, in your use case target objects are always presented at the same scale. You can optimize your model to focus on your pre-defined detection scale.
-
Licensing
Pre-trained models may be constraint by licenses which limit their use for non-scientific or commercial use. Building your own architecture frees you from any license restrictions and attribution obligations.
-
Compliance
Pre-trained AI models may introduce biases which are a violation to your organization's regulatory regime and requirements. You can prevent compliance breaches by changing AI model architectures to mitigate these biases. For example, you are planning to label shopping behaviour based on your customers' data point. However, you want to demonstrate due care by assuring that none of your customers are disadvantaged by their age or background.
Ways to Build a Custom Model
Unique problems often require unique solutions: Available AI models may not fulfill the exclusive requirements of your data or use case. The good news is that you do not have to re-invent the wheel: You can base your custom model on existing model architectures. There are four ways to build a custom model:
|
|
|
|
|
-
Build a Model from the Ground Up
Your model architecture is a composition of existing layer components. The components are choose and assembled based on your very specific use case.
This approach is often used for solving problems of minor complexity (i.e. less than 2 million parameters). The AI development is characterized by frequent and fundamental changes to the model architecture.
For example, you are building a model to predict server capacity based on recent user creation and authentications.
|
|
|
|
|
-
Derive from Existing Architecture
You build a model whose architecture is based on an existing model (e.g. Yolo). You use the scientific description of the model to implement its layer network in PyTorch. You train the model from you own data.
This approach has the advantage of using proven and powerful architectures for custom use cases. Your custom model is free of any license constraints and royalties. You can adapt the architecture to your specific needs. Or, you can incorporate marginal upgrades to your model's performance.
For example, you are developing an object classification model for detecting your company's products in pictures. You base your implementation on the latest incarnation of ResNet. You scale the model and train to the number of different products of your company.
|
|
|
|
|
-
Transfer Learning of Pre-Trained Models
You can tune pre-trained models to fit your specific data assets. This will free you from the costs of building and training the model from the ground up while still optimizing it to your use case.
This is a good way to use employ the advantages and performance of deep learning models for your specific application. It is a very cost-efficient way to achieve your objective if your use case is close to the original target objective of the pre-trained model.
Building a Model from Scratch - Example
For this example we will build a custom model for Image Classification. We use the dataset Fine-Grained Visual Classification of Aircraft (FGVC-Aircraft) [1] created as a benchmark for detailed image classification.
We implement the ResNet34 [2]model. Our implementation of the ResNet model is on par with the reference performance of the FGVC performance reference [1].
The focus of this blog is the deployment process. We chose ResNet because its architecture is a precursor for most of the high-performing deep learning models for the visual classification task [3].
We implement and train our RestNet34 model in PyTorch.
We implement and train our RestNet34 model in PyTorch.
- ResNet
- Residual Block
- Input Convolution
class ResNet(nn.Module):
"""Generic network for ResNet"""
def __init__(self, number_of_classes=10):
super(ResNet, self).__init__()
self.in_channels = 64
# the input layers
self.input_conv = InputConvolution(self.in_channels)
self.input_max_pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# residual layers
self.layer_64 = self.stack_residual_layers(64, 3, stride=1)
self.layer_128 = self.stack_residual_layers(128, 4, stride=2)
self.layer_256 = self.stack_residual_layers(256, 6, stride=2)
self.layer_512 = self.stack_residual_layers(512, 3, stride=2)
# output layers
self.avg_pool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512, number_of_classes)
def stack_residual_layers(self, out_channels, blocks, stride=1):
"""Creates repeated sequence of residual block type"""
down_sample = None
if stride != 1 or self.in_channels != out_channels:
down_sample = nn.Sequential(
nn.Conv2d(self.in_channels, out_channels, kernel_size=1, stride=stride),
nn.BatchNorm2d(out_channels),
)
layers = [ResidualBlock(self.in_channels, out_channels, stride, down_sample)]
self.in_channels = out_channels
for i in range(1, blocks):
layers.append(ResidualBlock(self.in_channels, out_channels))
# create the sequence of layers
return nn.Sequential(*layers)
def forward(self, x):
# input
x = self.input_conv(x)
x = self.input_max_pool(x)
# residual layers
x = self.layer_64(x)
x = self.layer_128(x)
x = self.layer_256(x)
x = self.layer_512(x)
# output
x = self.avg_pool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
class ResidualBlock(nn.Module):
"""two-layer building block used in Resnet"""
def __init__(self, in_channels, out_channels, stride=1, down_sample=None):
super(ResidualBlock, self).__init__()
self.first_convolution = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU()
)
self.second_convolution = nn.Sequential(
nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(out_channels))
self.down_sample = down_sample
self.relu = nn.ReLU()
self.out_channels = out_channels
def forward(self, x):
# copy the input for the residual
residual = x
out = self.first_convolution(x)
out = self.second_convolution(out)
if self.down_sample:
residual = self.down_sample(x)
# add the residual
out += residual
out = self.relu(out)
return out
class InputConvolution(nn.Module):
"""The input convolution layer"""
def __init__(self, out_channels):
super(InputConvolution, self).__init__()
self.conv = nn.Conv2d(3, out_channels, kernel_size=7, stride=2, padding=3)
self.bn = nn.BatchNorm2d(out_channels)
self.activation = nn.ReLU()
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activation(x)
return x
Exporting the Model
Converting the model to ONNX
We trained our model in PyTorch. But in order to deploy it into production, we convert it the ONNX format.
What is ONNX?
The Open Neural Network Exchange (ONNX) describes an open format for AI models. The format describes the model architecture and parameters as a graph of mathematical primitives. This set of primitives is called opset. The opset includes basic arithmetic operators like Add and Mult, but also more complex operation like Conv and MaxPool.
PyTorch/TensorFlow in Production
We often find that AI models are deployed using the frameworks they were trained in - for instance, PyTorch or Keras.
This is not wrong per se. But deploying the model to an ONNX target will provide you with the execution optimization, flexibility to move to the cloud and security.
You can think of the ONNX format as assembly language for AI models: It is a lower-level computing abstraction for serialized execution.
Executing ONNX
Most AI production execution platforms accept the ONNX format as the model definition. This includes Nvidia's TensorRT and AWS SageMaker. The only exception is Apple's CoreML.
Most execution platforms will inspect the AI model in ONNX format and partition the model code for execution optimized for the underlying computing hardware.
Exporting PyTorch to ONNX
import torch
from models import ResNet
import onnxruntime as rt
# the number of different aircraft families
number_of_classes = 70
# instantiate the model
model = ResNet(number_of_classes=number_of_classes)
# load the trained weights
model_state_dict = torch.load("output/fgvc_resnet.pth")
model.load_state_dict(model_state_dict)
# no gradient and training features
model.eval()
with torch.no_grad():
# create a dummy input
# we need this to trace the model execution for export
dummy_input_image = torch.randn(1, 3, 224, 224)
# export the model for named static input/output
torch.onnx.export(
model,
dummy_input_image,
"output/fgvc_resnet.onnx",
# export weights
export_params=True,
opset_version=10,
do_constant_folding=True,
# names of ONNX inputs/outputs
input_names=["image"],
output_names=["aircraft_family"]
)
### use the exported onnx model
# create ONNX execution session on CPU for testing
onnx_execution_session = rt.InferenceSession(
"output/fgvc_resnet.onnx",
providers=['CPUExecutionProvider']
)
# execute the inference
dummy_output = onnx_execution_session.run(
["aircraft_family"],
{
"image": dummy_input_image
}
)
Conclusion
In this blog page, we created a custom AI model in PyTorch for the task of image classification. We explored different approaches to creating a custom AI model.
In the last step, we export the PyTorch model to ONNX.
The next step in is to load the ONNX to the target platform: TensorRT.