Path: blob/master/examples/vision/ipynb/near_dup_search.ipynb
3236 views
Near-duplicate image search
Author: Sayak Paul
Date created: 2021/09/10
Last modified: 2023/08/30
Description: Building a near-duplicate image search utility using deep learning and locality-sensitive hashing.
Introduction
Fetching similar images in (near) real time is an important use case of information retrieval systems. Some popular products utilizing it include Pinterest, Google Image Search, etc. In this example, we will build a similar image search utility using Locality Sensitive Hashing (LSH) and random projection on top of the image representations computed by a pretrained image classifier. This kind of search engine is also known as a near-duplicate (or near-dup) image detector. We will also look into optimizing the inference performance of our search utility on GPU using TensorRT.
There are other examples under keras.io/examples/vision that are worth checking out in this regard:
Finally, this example uses the following resource as a reference and as such reuses some of its code: Locality Sensitive Hashing for Similar Item Search.
Note that in order to optimize the performance of our parser, you should have a GPU runtime available.
Setup
Imports
Load the dataset and create a training set of 1,000 images
To keep the run time of the example short, we will be using a subset of 1,000 images from the tf_flowers
dataset (available through TensorFlow Datasets) to build our vocabulary.
Load a pre-trained model
In this section, we load an image classification model that was trained on the tf_flowers
dataset. 85% of the total images were used to build the training set. For more details on the training, refer to this notebook.
The underlying model is a BiT-ResNet (proposed in Big Transfer (BiT): General Visual Representation Learning). The BiT-ResNet family of models is known to provide excellent transfer performance across a wide variety of different downstream tasks.
Create an embedding model
To retrieve similar images given a query image, we need to first generate vector representations of all the images involved. We do this via an embedding model that extracts output features from our pretrained classifier and normalizes the resulting feature vectors.
Take note of the normalization layer inside the model. It is used to project the representation vectors to the space of unit-spheres.
Hashing utilities
The shape of the vectors coming out of embedding_model
is (2048,)
, and considering practical aspects (storage, retrieval performance, etc.) it is quite large. So, there arises a need to reduce the dimensionality of the embedding vectors without reducing their information content. This is where random projection comes into the picture. It is based on the principle that if the distance between a group of points on a given plane is approximately preserved, the dimensionality of that plane can further be reduced.
Inside hash_func()
, we first reduce the dimensionality of the embedding vectors. Then we compute the bitwise hash values of the images to determine their hash buckets. Images having same hash values are likely to go into the same hash bucket. From a deployment perspective, bitwise hash values are cheaper to store and operate on.
Query utilities
The Table
class is responsible for building a single hash table. Each entry in the hash table is a mapping between the reduced embedding of an image from our dataset and a unique identifier. Because our dimensionality reduction technique involves randomness, it can so happen that similar images are not mapped to the same hash bucket everytime the process run. To reduce this effect, we will take results from multiple tables into consideration -- the number of tables and the reduction dimensionality are the key hyperparameters here.
Crucially, you wouldn't reimplement locality-sensitive hashing yourself when working with real world applications. Instead, you'd likely use one of the following popular libraries:
In the following LSH
class we will pack the utilities to have multiple hash tables.
Now we can encapsulate the logic for building and operating with the master LSH table (a collection of many tables) inside a class. It has two methods:
train()
: Responsible for building the final LSH table.query()
: Computes the number of matches given a query image and also quantifies the similarity score.
Create LSH tables
With our helper utilities and classes implemented, we can now build our LSH table. Since we will be benchmarking performance between optimized and unoptimized embedding models, we will also warm up our GPU to avoid any unfair comparison.
Now we can first do the GPU wam-up and proceed to build the master LSH table with embedding_model
.
At the time of writing, the wall time was 54.1 seconds on a Tesla T4 GPU. This timing may vary based on the GPU you are using.
Optimize the model with TensorRT
For NVIDIA-based GPUs, the TensorRT framework can be used to dramatically enhance the inference latency by using various model optimization techniques like pruning, constant folding, layer fusion, and so on. Here we will use the tf.experimental.tensorrt
module to optimize our embedding model.
Notes on the parameters inside of tf.experimental.tensorrt.ConversionParams()
:
precision_mode
defines the numerical precision of the operations in the to-be-converted model.maximum_cached_engines
specifies the maximum number of TRT engines that will be cached to handle dynamic operations (operations with unknown shapes).
To learn more about the other options, refer to the official documentation. You can also explore the different quantization options provided by the tf.experimental.tensorrt
module.
Build LSH tables with optimized model
Notice the difference in the wall time which is 13.1 seconds. Earlier, with the unoptimized model it was 54.1 seconds.
We can take a closer look into one of the hash tables and get an idea of how they are represented.
Visualize results on validation images
In this section we will first writing a couple of utility functions to visualize the similar image parsing process. Then we will benchmark the query performance of the models with and without optimization.
First, we take 100 images from the validation set for testing purposes.
Now we write our visualization utilities.
Non-TRT model
TRT model
As you may have noticed, there are a couple of incorrect results. This can be mitigated in a few ways:
Better models for generating the initial embeddings especially for noisy samples. We can use techniques like ArcFace, Supervised Contrastive Learning, etc. that implicitly encourage better learning of representations for retrieval purposes.
The trade-off between the number of tables and the reduction dimensionality is crucial and helps set the right recall required for your application.
Benchmarking query performance
We can immediately notice a stark difference between the query performance of the two models.
Final remarks
In this example, we explored the TensorRT framework from NVIDIA for optimizing our model. It's best suited for GPU-based inference servers. There are other choices for such frameworks that cater to different hardware platforms:
TensorFlow Lite for mobile and edge devices.
ONNX for commodity CPU-based servers.
Apache TVM, compiler for machine learning models covering various platforms.
Here are a few resources you might want to check out to learn more about applications based on vector similary search in general: