An excellent and well-structured piece of code! This is a robust implementation of a GPU-accelerated image similarity search application. The use of a class structure, Streamlit session state, cached resources, and advanced features like adaptive batching and multiple FAISS index types makes it both powerful and user-friendly.
Below is a detailed breakdown of the code, explaining the purpose and design choices behind each section, as if we were building it from scratch.
Design Philosophy
The primary goal is to create a fast, interactive, and robust image similarity search tool. The design choices reflect this:
- Encapsulation: All logic is contained within the
ImageSimilaritySearch class. This makes the code clean, organized, and easier to maintain. State (like the model, index, and dataset paths) is managed as instance attributes.
- Interactivity & State Management: Streamlit reruns the script on every user interaction. To prevent re-loading models or re-building the index constantly, we heavily rely on
st.session_state to persist data across reruns and @st.cache_resource for expensive, read-only objects like the ML model.
- Performance: Performance is critical. We achieve it through:
- GPU Acceleration: Using PyTorch on CUDA for model inference and FAISS for search.
- Batch Processing: Processing images in large batches to maximize GPU utilization.
- Half-Precision (FP16): Using
torch.half() and autocast to nearly double inference speed and halve GPU memory usage with minimal accuracy loss.
- Optimized Search: Employing
faiss, a library purpose-built for extremely fast vector similarity search.
- Robustness & User Experience (UX):
- Error Handling: The code gracefully handles common issues like corrupted images and GPU out-of-memory (OOM) errors by adapting the batch size dynamically.
- Clear Feedback: The UI provides constant feedback with progress bars, status text, and real-time memory stats, so the user knows what's happening during long operations.
- Windows Compatibility: Explicitly using
pathlib.Path and Windows-style default paths (r"...") ensures the application runs smoothly on Windows, a common OS for users with NVIDIA GPUs.
Code Breakdown
#
# --- 1. Imports and Class Definition ---
#
# Import necessary libraries for file operations, deep learning, data handling,
# UI, vector search, and system monitoring.
import os
import torch
import numpy as np
from PIL import Image
from transformers import AutoImageProcessor, AutoModel
from torchvision import transforms, datasets
import streamlit as st
import faiss
import time
import gc
import psutil
from pathlib import Path
class ImageSimilaritySearch:
"""
A class that encapsulates the entire image similarity search application.
"""
def __init__(self):
# --- 2. Initialization and Configuration ---
# Set up constants and default configurations.
# The model is a large Vision Transformer (ViT) pre-trained on ImageNet-21k,
# known for generating high-quality image embeddings.
self.MODEL_CHECKPOINT = "google/vit-large-patch16-224-in21k"
# A default path is provided for convenience. The 'r' prefix makes it a raw
# string, which is crucial for handling backslashes in Windows paths correctly.
self.DEFAULT_DATASET_PATH = r"G:\thedeathofyouth"
# A sensible default for displaying images without cluttering the UI.
self.MAX_IMAGE_WIDTH = 300
# Initialize placeholders for objects that will be created later.
self.device = None
self.processor = None
self.model = None
self.transformation_chain = None
self.class_names = []
self.index = None
self.gpu_resources = None
# Initialize Streamlit's session state to persist data across reruns.
# This is the "memory" of the web app.
self._init_session_state()
def _init_session_state(self):
"""
Initializes st.session_state keys if they don't exist. This prevents
the app from crashing on the first run and preserves state.
"""
keys = [
'run', 'clear_embeddings', 'query_image', 'last_results',
'candidate_paths', 'candidate_labels', 'index_built', 'total_images'
]
for key in keys:
if key not in st.session_state:
st.session_state[key] = None if key in ['last_results', 'total_images'] else False
def setup_sidebar(self):
"""
Configures the Streamlit sidebar for user inputs and status display.
This separates configuration from the main application flow.
"""
st.sidebar.title("⚙️ Configuration")
self.DATASET_PATH = st.sidebar.text_input("📂 Dataset Path", self.DEFAULT_DATASET_PATH)
self.SEED = st.sidebar.number_input("🎲 Random Seed", value=42, min_value=0)
self.BATCH_SIZE = st.sidebar.slider("📦 Batch Size", 64, 512, 256, step=64)
self.TOP_K = st.sidebar.slider("🔍 Similar Images to Show", 1, 50, 12)
self.COLUMNS = st.sidebar.slider("Number of Columns", 2, 8, 4)
# Display hardware information, which is helpful for debugging and context.
st.sidebar.markdown("### 🔧 Hardware Status")
if torch.cuda.is_available():
gpu_name = torch.cuda.get_device_name(0)
gpu_mem = f"{torch.cuda.get_device_properties(0).total_memory/1024**3:.1f} GB"
st.sidebar.markdown(f"- **GPU**: {gpu_name} ({gpu_mem} VRAM)")
st.sidebar.markdown(f"- **CPU**: Ryzen 9 5900X (12-core)") # Example static info
st.sidebar.markdown(f"- **RAM**: 64GB") # Example static info
st.sidebar.markdown(f"- **Storage**: NVMe SSD") # Example static info
# Advanced performance settings give the user control over the speed/accuracy trade-off.
st.sidebar.markdown("### 🚀 Performance Settings")
self.INDEX_TYPE = st.sidebar.selectbox(
"🔧 Search Algorithm",
["GPU-Powered Exact Search", "HNSW (Fast Approximate)"],
index=0
)
self.USE_HALF_PRECISION = st.sidebar.checkbox("Use FP16 Precision", value=True)
# This button allows the user to force a re-indexing of the dataset.
if st.sidebar.button("🚀 Build New Index", use_container_width=True):
st.session_state.clear_embeddings = True
st.session_state.query_image = None
st.session_state.index_built = False
st.rerun() # Force a script rerun to apply the changes.
@st.cache_resource
def load_model(_self):
"""
Loads the ML model and processor. Caching this function is CRITICAL.
It prevents the time-consuming model loading process on every script rerun.
The '_self' argument is a convention for instance methods within cached functions.
"""
device = "cuda" if torch.cuda.is_available() else "cpu"
st.toast(f"✅ Using device: {device}", icon="🚀")
processor = AutoImageProcessor.from_pretrained(_self.MODEL_CHECKPOINT)
model = AutoModel.from_pretrained(_self.MODEL_CHECKPOINT)
# Using half-precision (FP16) dramatically speeds up inference and reduces
# GPU memory, making it possible to use larger models and batches.
if _self.USE_HALF_PRECISION and device == "cuda":
model = model.half()
st.toast("Using FP16 precision for faster inference", icon="⚡")
model = model.to(device)
model.eval() # Set model to evaluation mode (disables dropout, etc.)
return device, processor, model
def setup_model(self):
"""
A helper function to orchestrate the model setup process.
"""
self.device, self.processor, self.model = self.load_model()
self.transformation_chain = self._get_transforms()
# Initialize FAISS GPU resources if we have a CUDA device.
# This pre-allocates memory on the GPU for FAISS to use.
if self.device == "cuda" and faiss.get_num_gpus() > 0:
self.gpu_resources = faiss.StandardGpuResources()
st.toast(f"FAISS using {faiss.get_num_gpus()} GPUs", icon="🎮")
def _get_transforms(self):
"""
Creates the image transformation pipeline required by the ViT model.
The parameters (mean, std, size) are sourced directly from the model's processor.
"""
normalize = transforms.Normalize(
mean=self.processor.image_mean,
std=self.processor.image_std
)
size = self.processor.size.get("shortest_edge", 224)
return transforms.Compose([
transforms.Lambda(lambda img: img.convert("RGB")), # Ensure 3 channels
transforms.Resize(size, interpolation=transforms.InterpolationMode.BICUBIC),
transforms.CenterCrop(size),
transforms.ToTensor(),
normalize,
])
def load_dataset(self, dataset_path: str):
"""
Loads the image dataset using torchvision.datasets.ImageFolder.
Using pathlib.Path enhances compatibility, especially on Windows.
"""
try:
dataset_path_obj = Path(dataset_path)
if not dataset_path_obj.exists():
raise FileNotFoundError(f"Path not found: {dataset_path_obj}")
# ImageFolder is a convenient loader that assumes a structure like:
# dataset/class_a/1.jpg, dataset/class_b/2.jpg, etc.
full_dataset = datasets.ImageFolder(root=str(dataset_path_obj))
class_names = full_dataset.classes
st.session_state.total_images = len(full_dataset)
return full_dataset, class_names
except Exception as e:
st.error(f"❌ Dataset loading failed: {str(e)}")
st.stop() # Stop execution if the dataset can't be loaded.
def batch_extract_embeddings(self, images: list):
"""
Processes a batch of images to generate their embeddings.
This function is optimized for speed and memory efficiency.
"""
try:
# Transform PIL images to a batch of PyTorch tensors.
images_transformed = torch.stack(
[self.transformation_chain(img) for img in images]
).to(self.device)
if self.USE_HALF_PRECISION and self.device == "cuda":
images_transformed = images_transformed.half()
# `torch.no_grad()` disables gradient calculation, saving memory and computation.
with torch.no_grad():
# `autocast` enables automatic mixed-precision for FP16.
with torch.cuda.amp.autocast(enabled=self.USE_HALF_PRECISION):
# For ViT, the embedding of the entire image is conventionally stored
# in the output corresponding to the first '[CLS]' token.
embeddings = self.model(images_transformed).last_hidden_state[:, 0]
# Move embeddings to CPU and convert to float32 NumPy array for FAISS.
return embeddings.cpu().float().numpy()
except RuntimeError as e:
# A robust way to handle GPU Out-of-Memory (OOM) errors.
if "out of memory" in str(e).lower():
st.warning("⚠️ GPU memory overflow! Reducing batch size...")
return None # Signal failure to the calling function.
raise # Re-raise other runtime errors.
def build_faiss_index(self, embeddings: np.ndarray):
"""
Creates a FAISS index for fast similarity search.
Offers both exact (GPU) and approximate (CPU) search options.
"""
dim = embeddings.shape[1]
embeddings = embeddings.astype('float32') # FAISS requires float32.
# Normalizing vectors to unit length (L2 norm) is crucial. When normalized,
# a dot product (Inner Product) search is mathematically equivalent to
# cosine similarity, which is a great metric for vector similarity.
faiss.normalize_L2(embeddings)
if self.INDEX_TYPE == "GPU-Powered Exact Search" and self.device == "cuda":
# IndexFlatIP performs an exact, brute-force search using Inner Product.
index_flat = faiss.IndexFlatIP(dim)
# This moves the index and its data to the GPU for massive parallelization.
index = faiss.index_cpu_to_gpu(self.gpu_resources, 0, index_flat)
index.add(embeddings)
return index
else:
# HNSW (Hierarchical Navigable Small World) is a state-of-the-art
# graph-based index for approximate nearest neighbor search. It's
# extremely fast, especially for very large datasets.
index = faiss.IndexHNSWFlat(dim, 32) # 32 is the number of neighbors per node.
# Tuning parameters for the build/search speed vs. accuracy trade-off.
index.hnsw.efConstruction = 100
index.hnsw.efSearch = 128
index.add(embeddings)
return index
def generate_embeddings(self):
"""
The main workflow for processing the entire dataset and building the search index.
This function provides detailed UI feedback during the process.
"""
full_dataset, self.class_names = self.load_dataset(self.DATASET_PATH)
n_images = st.session_state.total_images
if n_images == 0:
st.error("❌ No images found in the dataset directory.")
return
# UI elements for providing feedback.
st.info(f"Found {n_images} images. Starting embedding generation...")
progress_bar = st.progress(0)
status_text = st.empty()
ram_usage = st.empty()
gpu_stats = st.empty()
# Store paths and labels in session_state to be accessible by the search function.
all_samples = [(str(Path(path)), label) for path, label in full_dataset.samples]
all_embeddings = []
st.session_state.candidate_paths = []
st.session_state.candidate_labels = []
# Adaptive batching loop.
current_batch_size = self.BATCH_SIZE
processed = 0
while processed < n_images:
batch_end = min(processed + current_batch_size, n_images)
batch_samples = all_samples[processed:batch_end]
# Load images for the current batch, skipping corrupted ones.
images = []
valid_samples = []
for path, label in batch_samples:
try:
img = Image.open(path).convert("RGB")
images.append(img)
valid_samples.append((path, label))
except Exception:
st.warning(f"Skipping potentially corrupted image: {path}", icon="⚠️")
continue
if not images: # If all images in batch were corrupt
processed = batch_end
continue
embeddings = self.batch_extract_embeddings(images)
# If OOM occurred, reduce batch size and retry the same chunk.
if embeddings is None:
current_batch_size = max(32, current_batch_size // 2)
st.toast(f"Reduced batch size to {current_batch_size}", icon="📉")
torch.cuda.empty_cache() # Free up cached GPU memory.
gc.collect() # Trigger garbage collection.
continue # The `processed` counter is not incremented, so we retry.
all_embeddings.append(embeddings)
st.session_state.candidate_paths.extend([path for path, _ in valid_samples])
st.session_state.candidate_labels.extend([label for _, label in valid_samples])
processed += len(images) # Update progress with the number of successfully processed images
# Update UI feedback.
progress_bar.progress(processed / n_images)
status_text.text(f"🔄 Processed {processed}/{n_images} images")
if self.device == "cuda":
mem_used = torch.cuda.memory_allocated() / (1024**3)
mem_total = torch.cuda.get_device_properties(0).total_memory / (1024**3)
gpu_stats.text(f"🎮 GPU Memory: {mem_used:.2f}/{mem_total:.2f} GB")
ram_usage.text(f"💻 RAM Usage: {psutil.Process().memory_info().rss / (1024**3):.2f} GB")
if all_embeddings:
status_text.text("⚡ Building final search index...")
all_embeddings = np.vstack(all_embeddings)
start_time = time.time()
self.index = self.build_faiss_index(all_embeddings)
build_time = time.time() - start_time
st.session_state.index_built = True
status_text.text(f"✅ Index built in {build_time:.1f}s | {all_embeddings.shape[0]} vectors")
st.toast(f"Index is ready!", icon="🎉")
else:
st.error("Could not generate any embeddings. Check image files.")
# Clean up the temporary UI elements.
progress_bar.empty()
ram_usage.empty()
gpu_stats.empty()
def search_similar(self, query_image: Image.Image, top_k: int):
"""
Performs a similarity search for a given query image against the FAISS index.
"""
query_tensor = self.transformation_chain(query_image).unsqueeze(0)
if self.USE_HALF_PRECISION and self.device == "cuda":
query_tensor = query_tensor.half()
with torch.no_grad():
with torch.cuda.amp.autocast(enabled=self.USE_HALF_PRECISION):
query_embed = self.model(query_tensor.to(self.device)).last_hidden_state[:, 0].cpu().numpy()
# CRITICAL: The query vector must undergo the same normalization as the index vectors.
faiss.normalize_L2(query_embed)
start_time = time.perf_counter()
distances, indices = self.index.search(query_embed.astype('float32'), top_k)
search_time = (time.perf_counter() - start_time) * 1000 # ms
# Convert cosine similarity scores (from -1 to 1) to a more intuitive 0-1 range.
scores = (1 + distances[0]) / 2
paths = [st.session_state.candidate_paths[i] for i in indices[0]]
labels = [st.session_state.candidate_labels[i] for i in indices[0]]
return paths, labels, scores.tolist(), search_time
def display_results(self, paths: list, labels: list, scores: list, search_time: float):
"""
Displays the search results in a clean, interactive grid.
"""
if not paths:
st.warning("⚠️ No similar images found.")
return
st.subheader(f"🔍 Found {len(paths)} similar images in {search_time:.2f}ms")
cols = st.columns(self.COLUMNS)
for idx, (path, label, score) in enumerate(zip(paths, labels, scores)):
with cols[idx % self.COLUMNS]:
try:
img = Image.open(path)
st.image(img,
caption=f"{self.class_names[label]} ({score:.3f})",
use_column_width=True)
# This button makes the UI highly interactive, allowing users to
# chain searches together. A unique key is essential.
if st.button(f"🔍 Use as Query #{idx+1}", key=f"query_{idx}", use_container_width=True):
st.session_state.query_image = img
st.session_state.last_results = None # Clear old results to trigger new search
st.rerun()
except Exception as e:
st.error(f"⚠️ Error loading {Path(path).name}")
# --- 3. Main Application Flow ---
def run(self):
"""
The main entry point that orchestrates the application's UI and logic.
"""
st.set_page_config(layout="wide", page_title="Image Similarity Search")
st.title("🚀 GPU-Powered Image Similarity Search (Windows Optimized)")
with st.expander("💡 How to use", expanded=True):
st.markdown("""
1. **Check Settings**: Ensure the dataset path in the sidebar is correct.
2. **Build Index**: The app will automatically build an index on the first run. Use the button in the sidebar to rebuild if your dataset changes.
3. **Upload Image**: Use the file uploader to select a query image.
4. **Explore & Refine**: The most similar images will appear. Click "Use as Query" on any result to start a new search with that image.
""")
self.setup_sidebar()
self.setup_model()
# Logic to build the index only when necessary.
if st.session_state.get('clear_embeddings') or not st.session_state.get('index_built'):
with st.spinner("Building image index for the first time... This may take a while."):
self.generate_embeddings()
st.session_state.clear_embeddings = False
# Main UI logic: display uploader or search results based on session state.
if st.session_state.query_image is None:
st.subheader("📤 Upload Query Image")
uploaded_file = st.file_uploader(
"Select an image to find similar ones in your dataset.",
type=["jpg", "jpeg", "png", "bmp", "webp"]
)
if uploaded_file:
st.session_state.query_image = Image.open(uploaded_file)
st.rerun() # Rerun to switch to the "results" view.
else:
st.subheader("🖼️ Current Query")
col1, col2 = st.columns([1, 4])
with col1:
st.image(st.session_state.query_image, width=self.MAX_IMAGE_WIDTH)
if st.button("❌ Clear Query", use_container_width=True):
st.session_state.query_image = None
st.session_state.last_results = None
st.rerun()
with col2:
# Perform search only if results are not already cached in the session.
if st.session_state.last_results is None and st.session_state.index_built:
with st.spinner("🔍 Searching..."):
try:
paths, labels, scores, search_time = self.search_similar(
st.session_state.query_image, self.TOP_K
)
# Cache results in session state to avoid re-searching on resize/etc.
st.session_state.last_results = (paths, labels, scores, search_time)
except Exception as e:
st.error(f"Search failed: {str(e)}")
# Display results if they exist.
if st.session_state.last_results:
self.display_results(*st.session_state.last_results)
if __name__ == "__main__":
app = ImageSimilaritySearch()
app.run()