Deploying a Image Recognition Service to AWS Lambda
The source code is available in my repository.
Start a New Project
First, create an new virtual environment:
I used venv for creating the environment, and I named it lambda
and placed it in the ~/pyvenvs
directory.
You may use any other environment manager and name as you wish.
I will name the project resnet-image-recognition
:
The Python packages we are going to use are
awslambdaric
AWS need this package, the runtime interface client, to manage the interaction betweeen Lambda and our source code. See more details here. It will be used as the entry point of the container, as we will see later.pydantic
Mygo-toonly choice for defining data models.fastapi[standard]
Framework for building APIs. Usestandard
feature here to install thefastapi
CLI.mangum
An adapter for running ASGI applications in AWS Lambda. It is used to wrap our FastAPI app:Mangum(app)
.torch
We use PyTorch to define the Resnet50 model.torchvision
We need utilities for transforming images before feeding them into the model.
Project structure:
Define the Restnet50 Architecture
When I was learning the Resnet, I found the original implementation is not that easy to understand. So, I implemented the Resnet model using PyTorch from scratch and add a lot of comments. Hope it will help you.
I put my source code for the Resnet in the sub-package resnet_image_recognition/resnet
.
Check it here.
In this project, we will be using Resnet50.
To use the model for inference,
we also need the pretrained weights (.pt
or .pth
files).
You can download the one provided by PyTorch from here.
Save it under the model
directory.
Implement the ImageRecognizer
using the Resnet50 Model
We are now going to create a simple ImageRecognizer
class powered by the Resnet50 model.
It has a recognize
method, which takes a PIL image as input and returns the class of that image.
The constant IMAGENET_CLASSES
is a tuple consiting of 1000 classes from the ImageNet dataset.
You may check its value here in my repository.
Build a FastAPI App — Deliver the Deep Learning Model as an HTTP Service
The core functionality of the service is done.
To let other users to use our ImageRecognizer
, we need create an API that handles users’ requests and invokes the ImageRecognizer
as a backend service.
Every FastAPI app reqires a global app
instance to be defined.
As a standard procedure, we expose the app
instance in the __init__.py
:
However, we are not going to use this app
(directly) in this project.
But for a general FastAPI project, this is what we need.
For this project, as you will see,
we will wrap the app
further with a Mangum
adapter in a later section.
Health Check
To get started, first create a health_check
API, which simply returns a short message indicating that the server is up and running.
(health_check
is the Hello, World API in the backend development.)
Function like health_check
defined above are oftern referred to as handlers since they handle the incoming requests.
Next, register a route for the health_check
:
app.get
specifies that the request method is GET.
For POST methods, use app.post
.
Recognize Image
Register a route for the recognize_image
:
Final Touch — Mangum Adapter
Wrap the app instance into the Mangum adapter:
Expose the variable handler
in __init__.py
, which will be used as the entrypoint of the container.
The service will be started via app.handler
.
Write a Dockerfile for Building the Image
You can build and tag the image now if you are familiar with Docker. Or, you can check the next section for how to build and push the image to AWS ECR.
Build and Push the Docker Image to AWS ECR
ECR (Elastic Container Registry) is an AWS service that you can store, share and deploy container images.
When deploying an AWS Lambda function using Docker images, you are prompted to choose an image from the ECR.
Enter the ECR console, you will see the following UI. Click Create repository and following the instructions.
After that, click the link to the repository you have created and then click the View push commands button to see the help messages like the following for building and pushing Docker images to ECR.
Create a Lambda Function using the Docker Container
Enter the AWS Lambda console and click Create function:
Choose Container image and click Browse image to select the previously uploaded image from ECR.
Recall that we set the linux/amd64 platform for the container image. So, here choose the x86_64 architecture.
Then click Create function and wait for it.
Create a Funciton URL
Now, your funciton can only be invoked for authenticated AWS users or you other AWS services.
To make it accessible for all users via HTTP requests, you need to generate a function URL.
Set General Configuration
When you invoke the function now, you will possibly encounter the errors of timeout or out of memeory. This is because of the limited resources assigned to the cloud function.
You may assign more resources like time limit and memeory usage by setting the following configuration:
Comments 💬