Deploying a computer vision model on AWS SageMaker involves several steps, from preparing your trained model and packaging your inference code to creating and deploying an endpoint that can serve predictions. Below is an overview of the process along with sample code snippets and best practices.
Step 1. Prepare Your Computer Vision Model
-
Train or Obtain Your Model Artifacts:
- You might have trained your model using frameworks like TensorFlow, PyTorch, or MXNet.
- Ensure your model is serialized (e.g., a
.pt, .h5, or other artifact) and saved to an Amazon S3 bucket.
-
Develop a Custom Inference Script (Optional):
- Write an
inference.py script that handles model loading in memory and defines methods such as input_fn, predict_fn, and output_fn.
- These functions let you process incoming requests and format outgoing responses.
Example snippet for a PyTorch model:
import io
import torch
from torchvision import models, transforms
from PIL import Image
def model_fn(model_dir):
# Load the saved model artifact from model_dir
model = torch.load(f'{model_dir}/model.pth', map_location=torch.device('cpu'))
model.eval()
return model
def input_fn(request_body, content_type='application/x-image'):
if content_type == 'application/x-image':
return Image.open(io.BytesIO(request_body))
raise Exception(f'Unsupported content type: {content_type}')
def predict_fn(input_object, model):
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
input_tensor = preprocess(input_object).unsqueeze(0) # add batch dimension
with torch.no_grad():
prediction = model(input_tensor)
return prediction
def output_fn(prediction, accept='application/json'):
# Convert prediction to a CPU tensor and then to list for JSON serialization
prediction = prediction.cpu().numpy().tolist()
return prediction
Step 2. Package Your Code
There are two main approaches to deploy the model:
A. Using SageMaker Pre-Built Containers
If your model is built using a supported framework (e.g., PyTorch, TensorFlow), SageMaker provides pre-built containers. You only need to supply the model artifacts and your inference script.
B. Creating a Custom Docker Container (Optional)
For more control (or if you’re using custom libraries), create your own container:
-
Dockerfile Example:
FROM pytorch/pytorch:1.8.1-cuda10.2-cudnn7-runtime
# Install additional packages
RUN pip install --upgrade pip && \
pip install torchvision
# Copy your code
COPY inference.py /opt/program/inference.py
COPY model.pth /opt/ml/model/model.pth
ENV SAGEMAKER_PROGRAM inference.py
ENV PYTHONUNBUFFERED TRUE
WORKDIR /opt/program
ENTRYPOINT ["python", "inference.py"]
-
Push the Image to Amazon ECR:
Step 3. Create a SageMaker Model and Deploy an Endpoint
You can use the SageMaker Python SDK to streamline deployment.
Example using SageMaker’s Pre-Built PyTorch Container:
-
Upload Your Model Artifact to S3:
import boto3
s3 = boto3.client('s3')
bucket_name = 'your-bucket-name'
model_artifact = 's3://your-bucket-name/path/to/model.pth'
-
Deploy Using SageMaker PyTorchModel Class:
import sagemaker
from sagemaker.pytorch import PyTorchModel
# Specify the IAM role with SageMaker permissions.
role = 'arn:aws:iam::your-account-id:role/your-sagemaker-execution-role'
# Create a PyTorchModel object, pointing to your inference script and model artifact.
pytorch_model = PyTorchModel(
model_data=model_artifact,
role=role,
entry_point='inference.py', # the inference script in your working directory
framework_version='1.8.1',
py_version='py3'
)
# Deploy the endpoint
predictor = pytorch_model.deploy(
initial_instance_count=1,
instance_type='ml.m5.xlarge'
)
For a custom container hosted on ECR, you would use the InferenceModel or specify the image_uri parameter.
-
Invoke the Deployed Endpoint:
# Assuming you have an image in binary format (e.g., read using open('image.jpg', 'rb'))
with open('image.jpg', 'rb') as f:
image_bytes = f.read()
result = predictor.predict(image_bytes)
print(result)
Step 4. Clean Up Resources
After testing, delete the endpoint to avoid incurring ongoing charges:
predictor.delete_endpoint()
Additional Considerations
-
Monitoring & Logging:
Use CloudWatch for logs and metrics to monitor your endpoint.
-
Scaling & Performance:
Adjust instance types, auto-scaling settings, or use multi-model endpoints if you expect high traffic.
-
Security & IAM:
Ensure that your SageMaker execution role has the correct permissions for S3, ECR, CloudWatch, etc.
-
Testing Locally:
Consider using SageMaker Local Mode for initial testing before deploying in production.
By following these steps and adapting the code snippets to your specific model and requirements, you can successfully deploy a computer vision model on AWS SageMaker and create a scalable, production-ready endpoint. Enjoy building your solution!