You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+23-23Lines changed: 23 additions & 23 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -36,7 +36,7 @@
36
36
37
37
A Twin Neural Network (commonly known as a Siamese Neural Network) makes predictions leveraging information from multiple sources. A common use case is taking multiple input data, such as two images, and predicting whether they belong to the same class, though its application aren't necessarily limited to computer vision or classification problems. In practise, however, artificial neural network training takes extensive and sophisticated effort. Fortunately, there are a variety of deep learning frameworks available to tackle training. One which stands out, [Fast.ai](https://www.fast.ai/), has become one of the most cutting-edge, open source, deep learning frameworks based on [PyTorch](https://pytorch.org/). It provides a concise user interface and well designed, documented APIs, which empowers developers and machine learning practitioners to train models with productivity and flexibility.
38
38
39
-
For deployment, [Amazon Web Services (Amazon AWS)](https://aws.amazon.com/) developed [TorchServe](https://pytorch.org/serve/) in partnership with Meta (previously, Facebook), which is a flexible and easy-to-use open source tool for serving PyTorch models. It removes the heavy lifting of deploying and serving PyTorch models with Kubernetes. With TorchServe, many features are out-of-the-box and they provide full flexibility of deploying trained PyTorch models at scale. In addition, [Amazon SageMaker](https://aws.amazon.com/sagemaker/) endpoint is a fully managed service that allows users to make real-time inferences via a REST API, which saves developers from managing their own server instances, load balancing, fault-tolerance, auto-scaling and model monitoring, etc. Amazon SageMaker endpoint supports industry level machine learning inference and graphics-intensive applications while being [cost-effective](https://aws.amazon.com/sagemaker/pricing/).
39
+
For deployment, [Amazon Web Services (AWS)](https://aws.amazon.com/) developed [TorchServe](https://pytorch.org/serve/) in partnership with Meta (previously, Facebook), which is a flexible and easy-to-use open source tool for serving PyTorch models. It removes the heavy lifting of deploying and serving PyTorch models with Kubernetes. With TorchServe, many features are out-of-the-box and they provide full flexibility of deploying trained PyTorch models at scale. In addition, [Amazon SageMaker](https://aws.amazon.com/sagemaker/) endpoint is a fully managed service that allows users to make real-time inferences via a REST API, which saves developers from managing their own server instances, load balancing, fault-tolerance, auto-scaling and model monitoring, etc. Amazon SageMaker endpoint supports industry level machine learning inference and graphics-intensive applications while being [cost-effective](https://aws.amazon.com/sagemaker/pricing/).
40
40
41
41
In this repository we demonstrate how to train a Twin Neural Network based on PyTorch and Fast.ai, and deploy it with TorchServe on Amazon SageMaker Inference endpoint. For demonstration purposes, we build an interactive web application for users to upload images and make inferences from the trained and deployed model, based on [Streamlit](https://streamlit.io/), which is an open source framework for data scientists to efficiently create interactive web-based data applications in pure Python.
42
42
@@ -61,7 +61,7 @@ For other installation options, please refer to the fast.ai documentation. The f
61
61
62
62
### Model Architecture
63
63
64
-
For Twin Neural Networks, multiple input data are passed through an _encoding_ neural network to generate their hyper-dimensional embedding vectors, which are concatenated before fed into a _fully connected network_ (FCN) for output, as shown in _Fig. 1_.
64
+
For Twin Neural Networks, multiple input data sources are passed through an _encoding_ neural network to generate their hyper-dimensional embedding vectors, which are concatenated before fed into a _fully connected network_ (FCN) for output, as shown in _Fig. 1_.
65
65
66
66
|  |
67
67
|:--:|
@@ -71,7 +71,7 @@ Now that Fast.ai is installed, we can define this model architecture in pure PyT
71
71
72
72
#### Encoding Network
73
73
74
-
For the encoding network, `ResNet50`is used,as an example,with its pre-trained weights, and the last fully connected layer is removed to be replaced by our own FCNin the following step.
74
+
For the encoding network, `ResNet50`is used as an example with its pre-trained weights, and the last fully connected layer is removed to be replaced by our own FCNin the following step.
75
75
76
76
```python
77
77
import torchvision.models as models
@@ -155,7 +155,7 @@ path = untar_data(URLs.PETS)
155
155
files = get_image_files(path/"images")
156
156
```
157
157
158
-
Next, define the image transformations in PyTorch, including resizing, converting to `FloatTensor` data type, re-order dimension, and image normalisation with statistics from [ImageNet](http://www.image-net.org/) for transfer learning:
158
+
Next, we define the image transformations in PyTorch, including resizing, converting to `FloatTensor` data type, re-order dimension, and image normalisation with statistics from [ImageNet](http://www.image-net.org/) for transfer learning:
Per Fast.ai's unique semantic requirements, define the basic image-pair and label data entity for visualisation.
176
+
Per Fast.ai's unique semantic requirements, we define the basic image-pair and label data entity for visualisation.
177
177
178
178
```python
179
179
classTwinImage(fastuple):
@@ -199,7 +199,7 @@ class TwinImage(fastuple):
199
199
)
200
200
```
201
201
202
-
Then define the helper function parsing image breads from its file path. It takes all the images from the dataset, randomly draw pairs of them, and determines if they are the same breed or not.
202
+
Then we define the helper function parsing image breeds from its file path. It takes all the images from the dataset, randomly draws pairs of them, and determines if they are the same breed or not.
203
203
204
204
```python
205
205
deflabel_func(fname):
@@ -230,11 +230,11 @@ class TwinTransform(Transform):
230
230
return random.choice(self.lbl2files[cls]), same
231
231
```
232
232
233
-
Note the raw image transformation pipeline defined above is applied, together with an extra data augmentation during training. This randomly swaps the two images from the pair without changing the label.
233
+
Note that the raw image transformation pipeline defined above is applied together with an extra data augmentation during training. This randomly swaps the two images from the pair without changing the label.
234
234
235
235
### Split and Dataloader
236
236
237
-
Randomly split the dataset into train/validation partitions, and construct `dataloaders` for each of them with specified batch size.
237
+
Here we randomly split the dataset into train/validation partitions, and construct `dataloaders` for each of them with specified batch size.
238
238
239
239
```python
240
240
splits = RandomSplitter()(files)
@@ -248,7 +248,7 @@ dls = tls.dataloaders(
248
248
249
249
### Training and Saving
250
250
251
-
Now setup loss function and parameter groups, which then triggers the Fast.ai training process.
251
+
Now we setup loss function and parameter groups, which then triggers the Fast.ai training process.
252
252
253
253
```python
254
254
defloss_func(out, targ):
@@ -291,7 +291,7 @@ For more details about the modeling process, refer to `notebook/01_fastai_twin.i
291
291
292
292
### Convolutional Neural Network Interpretation
293
293
294
-
The activations out of each convolutional layer can be interpreted as an extracted feature map of the input image, and the number of activations are determined by the number of convolutional filters specified in that layer. When all these activations are summed up with weights corresponding to a certain prediction, we get the _class activation map_ (CAM) which can be used as a heatmap illustrating the importance of different areas of the input image, or how much attention the model paid to different zones of the image in order to make that prediction. These can be achieved by using PyTorch hook.
294
+
The activations out of each convolutional layer can be interpreted as an extracted feature map of the input image, and the number of activations are determined by the number of convolutional filters specified in that layer. When all these activations are summed up with weights corresponding to a certain prediction, we get the _class activation map_ (CAM) which can be used as a heatmap illustrating the importance of different areas of the input image, or how much attention the model paid to different zones of the image in order to make that prediction. These can be achieved by using a PyTorch hook.
295
295
296
296
```python
297
297
classHookCAM:
@@ -324,7 +324,7 @@ class HookCAMBwd:
324
324
self.hook.remove()
325
325
```
326
326
327
-
With weights being the average of gradients on each convolutional filter, multiplied by the corresponding activations before summing up, we get the CAM for the prediction, as illutrated in _Fig. 2_.
327
+
With weights being the average of gradients on each convolutional filter, when we multiply by the corresponding activations before summing up, we get the CAM for the prediction, as illutrated in _Fig. 2_.
328
328
329
329
```python
330
330
fromPILimport Image
@@ -370,7 +370,7 @@ For more details please refer to `notebook/02_pytorch_inference.ipynb` [[link](n
370
370
371
371
## Deployment to TorchServe
372
372
373
-
Now that we have our trained model for the images of cats, we can easily use TorchServe to serve the model. TorchServe comes with a convenient command line interface (CLI) to deploy locally. It also comes with default handlers for common problems such as image classification, object detection, image segmentation, and text classification. But we can always tailor it for our own specifications because TorchServe is open source, which means it’s fully extensible to fit any deployment needs.
373
+
Now that we have our trained model for the images of cats, we can easily use TorchServe to serve the model. TorchServe comes with a convenient command line interface (CLI) to deploy locally. It also comes with default handlers for common problems such as image classification, object detection, image segmentation, and text classification. We can always tailor it for our own specifications because TorchServe is open source, which means it is fully extensible to fit any deployment needs.
374
374
375
375
In this section we deploy the PyTorch model to TorchServe. For installation, please refer to the TorchServe [Github](https://github.com/pytorch/serve) Repository. Overall, there are 3 main steps to use TorchServe:
376
376
@@ -432,7 +432,7 @@ Initialize works out if GPU resources are available, then identifies the seriali
432
432
433
433
#### `preprocess`
434
434
435
-
This reads the image and applies the transformation pipeline to the inference data.
435
+
Preprocess reads the image and applies the transformation pipeline to the inference data.
436
436
437
437
```python
438
438
defpreprocess(self, data):
@@ -455,7 +455,7 @@ This reads the image and applies the transformation pipeline to the inference da
455
455
456
456
#### `inference`
457
457
458
-
Now it loads the data to the GPU if available, and passes it through the model consisting of both encoder and fully connected network. If CAM is required, it calculates and returns the heatmap.
458
+
Inference loads the data to the GPU if available, and passes it through the model consisting of both encoder and fully connected network. If CAM is required, it calculates and returns the heatmap.
459
459
460
460
```python
461
461
definference(self, left_image, right_image):
@@ -506,7 +506,7 @@ Now it loads the data to the GPU if available, and passes it through the model c
506
506
507
507
#### `postprocess`
508
508
509
-
The inference raw output is unloaded from the GPU if available, and it is combined with CAM to be returned back to the API trigger.
509
+
Postprocess takes the inference raw output which was unloaded from the GPU (if available), and it is then combined with CAM to be returned back to the API trigger.
510
510
511
511
```python
512
512
defpostprocess(self, inference_output):
@@ -527,7 +527,7 @@ The inference raw output is unloaded from the GPU if available, and it is combin
527
527
]
528
528
```
529
529
530
-
Now it's ready to setup and launch TorchServe.
530
+
Now we are ready to setup and launch TorchServe.
531
531
532
532
### TorchServe in Action
533
533
@@ -567,24 +567,24 @@ user 0m0.334s
567
567
sys 0m0.036s
568
568
```
569
569
570
-
The first call would have longer latency due to model weights loading defined in `initialize`, but this will be mitigated from the second call onward. For more details about `TorchServe` setup and usage, please refer to `notebook/02_pytorch_inference.ipynb`[[link](notebook/02_pytorch_inference.ipynb)].
570
+
The first call has longer latency due to model weights loading defined in `initialize`, but this will be mitigated from the second call onward. For more details about `TorchServe` setup and usage, please refer to `notebook/02_pytorch_inference.ipynb`[[link](notebook/02_pytorch_inference.ipynb)].
571
571
572
572
## Deployment to Amazon SageMaker Inference Endpoint
573
573
574
574
For customised machine learning model deployment and hosting, Amazon SageMaker is fully modular, which means we can always bring in customised algorithms and containers and use only the services that are required. In our case it is the Amazon SageMaker Model and Endpoint. Specifically, we are building a TorchServe container and hosting it using Amazon SageMaker for a fully managed model hosting and elastic-scaling experience, with simply a few lines of code. On the client side, we get predictions with simple API calls to its secure endpoint backed by TorchServe.
575
575
576
576
There are 4 steps to setup a SageMaker Endpoint with TorchServe:
577
577
578
-
1. Build a customized Docker Image and push to Amazon Elastic Container Registry (ECR). The dockerfile is provided in root of this code repository, which helps setup CUDA and TorchServe dependencies.
579
-
2. Compress `*.mar` into `*.tar.gz` and upload to Amazon Simple Storage Service (S3).
578
+
1. Build a customized Docker Image and push to Amazon Elastic Container Registry (Amazon ECR). The dockerfile is provided in root of this code repository, which helps setup CUDA and TorchServe dependencies.
579
+
2. Compress `*.mar` into `*.tar.gz` and upload to Amazon Simple Storage Service (Amazon S3).
580
580
3. Create SageMaker model using the docker image from step 1 and the compressed model weights from step 2.
581
581
4. Create the SageMaker endpoint using the model from step 3.
582
582
583
583
The details of these steps are described in `notebook/03_SageMaker.ipynb`[[link](notebook/03_SageMaker.ipynb)]. Once ready, we can invoke the SageMaker endpoint with images in real-time.
584
584
585
585
### Real-time Inference with Python SDK
586
586
587
-
Read sample images.
587
+
Read the sample images.
588
588
589
589
```python
590
590
cam =False
@@ -643,12 +643,12 @@ Make sure that you delete the following resources to prevent any additional char
5. Amazon Simple Storage Service (Amazon S3) Buckets.
648
648
649
649
## Conclusion
650
650
651
-
This repository presented an end-to-end workflow for training a Twin Neural Network with PyTorch and Fast.ai, followed by its deployment with TorchServe eager mode on Amazon SageMaker Endpoint. You can use this repository as a template to develop and deploy your own deep learning solutions. We then used an application built with the open source Streamlit framework that demonstrates how end users can use the new model to compare two images and visualise the results. This approach eliminates the self-maintainance effort to build and manage a customised inference server, which helps to speed up the process from training a cutting-edge deep learning model to its online application in the real world, at scale.
651
+
This repository presents an end-to-end workflow for training a Twin Neural Network with PyTorch and Fast.ai, followed by its deployment with TorchServe eager mode on Amazon SageMaker Endpoint. You can use this repository as a template to develop and deploy your own deep learning solutions. We then used an application built with the open source Streamlit framework that demonstrates how end users can use the new model to compare two images and visualise the results. This approach eliminates the self-maintainance effort to build and manage a customised inference server, which helps to speed up the process from training a cutting-edge deep learning model to its online application in the real world, at scale.
0 commit comments