From 19d9bccc26823945b35788bdf245c81ee103e240 Mon Sep 17 00:00:00 2001 From: danellecline Date: Thu, 16 Jul 2026 16:30:09 -0700 Subject: [PATCH 1/4] perf: fp16 autocast inference and parallel Redis KNN search Speed up inference throughput on two fronts: - process_vits: run the ViT forward pass under fp16 autocast (CUDA) with model.eval() and torch.inference_mode(), non-blocking host->device copies, and an optional torch.compile path. Embeddings are cast back to float32 to match the FLOAT32 Redis index. Toggle via VSS_AMP / VSS_TORCH_COMPILE. - vector_similarity: add search_vectors() to issue a batch of KNN queries concurrently over the connection pool instead of one serial round-trip per image; predict() now uses it. Concurrency tunable via VSS_KNN_WORKERS. Co-authored-by: Cursor --- src/app/predictors/process_vits.py | 38 +++++++++++++++++++------ src/app/predictors/vector_similarity.py | 23 +++++++++++++++ 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/app/predictors/process_vits.py b/src/app/predictors/process_vits.py index 99bf59e..367f545 100644 --- a/src/app/predictors/process_vits.py +++ b/src/app/predictors/process_vits.py @@ -28,11 +28,26 @@ class ViTWrapper: def __init__(self, r: redis.Redis, device, model_name: str, reset: bool = False, batch_size: int = 32): self.r = r - self.device = device + self.device = torch.device(device) if not isinstance(device, torch.device) else device self.batch_size = batch_size self.processor = AutoImageProcessor.from_pretrained(model_name) self.model = AutoModel.from_pretrained(model_name).to(self.device) + # eval() disables dropout and puts the model in inference mode + self.model.eval() + + # Mixed-precision (fp16) autocast roughly halves memory and ~2x GPU throughput. + # Only enabled on CUDA; can be disabled with VSS_AMP=0. + amp_enabled = os.getenv("VSS_AMP", "1") == "1" + self.amp_dtype = torch.float16 if (amp_enabled and self.device.type == "cuda") else None + self.vs = VectorSimilarity(r, vector_dimensions=self.vector_dimensions, reset=reset) + + # Optional torch.compile for a further speedup (one-time warmup cost). + # Done last so vector_dimensions is read from the original (uncompiled) module. + if os.getenv("VSS_TORCH_COMPILE", "0") == "1": + info("Compiling model with torch.compile") + self.model = torch.compile(self.model) + if model_name.startswith("/"): if not os.path.exists(model_name): raise FileNotFoundError(f"Model directory {model_name} does not exist") @@ -72,12 +87,17 @@ def get_image_embeddings(self, inputs): debug(inputs["pixel_values"].shape) # Should be (B, 3, H, W) # Move inputs to same device as model (processor returns CPU tensors) - inputs = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} - - with torch.no_grad(): - embeddings = self.model(**inputs) + inputs = {k: v.to(self.device, non_blocking=True) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} + + with torch.inference_mode(): + if self.amp_dtype is not None: + with torch.autocast(device_type=self.device.type, dtype=self.amp_dtype): + embeddings = self.model(**inputs) + else: + embeddings = self.model(**inputs) info("Done getting embeddings for batch") - batch_embeddings = embeddings.last_hidden_state[:, 0, :].cpu().numpy() + # Cast back to float32 to match the Redis index (FLOAT32) regardless of autocast dtype + batch_embeddings = embeddings.last_hidden_state[:, 0, :].float().cpu().numpy() info(f"Batch embeddings shape: {batch_embeddings.shape}") return np.array(batch_embeddings) @@ -91,8 +111,10 @@ def predict(self, image_paths: List[str], top_n: int = 1) -> tuple[list[list[str for inputs, _, _ in self.preprocess_images(image_paths): embeddings = self.get_image_embeddings(inputs) info(f"Searching for {len(embeddings)} embeddings in Redis") - for j, emb in enumerate(embeddings): - r = self.vs.search_vector(emb.tobytes(), top_n=top_n) + # Issue all KNN searches for the batch concurrently instead of one round-trip per image + vectors = [emb.tobytes() for emb in embeddings] + results = self.vs.search_vectors(vectors, top_n=top_n) + for r in results: # Data is doc:label:id - split it into parts data = [x["id"].split(":") for x in r] batch_pred = [] diff --git a/src/app/predictors/vector_similarity.py b/src/app/predictors/vector_similarity.py index 350007b..e52c3e2 100644 --- a/src/app/predictors/vector_similarity.py +++ b/src/app/predictors/vector_similarity.py @@ -1,6 +1,9 @@ # fastapi-vss, Apache-2.0 license # Filename: predictors/vector_similarity.py # Description: Runs operations on Redis database with RediSearch on embedded vectors +import os +from concurrent.futures import ThreadPoolExecutor + import redis from redis.commands.search.field import TagField, VectorField from redis.commands.search.indexDefinition import IndexDefinition, IndexType @@ -8,6 +11,10 @@ from app.logger import err, info, debug +# Number of concurrent Redis KNN queries per batch (redis-py releases the GIL on socket I/O, +# so threads issue searches in parallel over the connection pool). Tunable via VSS_KNN_WORKERS. +KNN_SEARCH_WORKERS = int(os.getenv("VSS_KNN_WORKERS", "16")) + class VectorSimilarity: INDEX_NAME = "index" # Vector Index Name @@ -60,3 +67,19 @@ def search_vector(self, vector: list, top_n: int): except Exception as e: err(f"Error searching vector: {e}") return [] + + def search_vectors(self, vectors: list, top_n: int) -> list: + """Run KNN search for a batch of vectors concurrently. + + Redis-py checks out a connection from the pool per command and releases the GIL + during socket I/O, so issuing searches from a thread pool avoids the serial + round-trip-per-vector cost. Results preserve input order. + """ + if not vectors: + return [] + if len(vectors) == 1: + return [self.search_vector(vectors[0], top_n)] + + max_workers = min(KNN_SEARCH_WORKERS, len(vectors)) + with ThreadPoolExecutor(max_workers=max_workers) as executor: + return list(executor.map(lambda v: self.search_vector(v, top_n), vectors)) From a4018c3fada20a283ea42e3d3bba52656bd21a2a Mon Sep 17 00:00:00 2001 From: danellecline Date: Thu, 16 Jul 2026 16:54:52 -0700 Subject: [PATCH 2/4] fix(docker): make image uid-agnostic to avoid getpass.getuser KeyError torch._dynamo (imported transitively by transformers) calls getpass.getuser() at import time, which raises KeyError when the container runs as an arbitrary uid with no /etc/passwd entry (e.g. compose `user: 12078:20`). Set USER/HOME so getpass short-circuits on the env var, and route torch/HF caches to writable /tmp so the optional torch.compile path works for any uid. Co-authored-by: Cursor --- Dockerfile.cuda | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Dockerfile.cuda b/Dockerfile.cuda index fc46c34..d36403d 100644 --- a/Dockerfile.cuda +++ b/Dockerfile.cuda @@ -57,6 +57,18 @@ ENV IN_DOCKER=1 ENV NVIDIA_VISIBLE_DEVICES=all ENV NVIDIA_DRIVER_CAPABILITIES=compute,utility +# Make the image uid-agnostic: the container may be run with an arbitrary uid +# (e.g. compose `user: 12078:20`) that has no /etc/passwd entry. torch._dynamo, +# imported transitively by transformers, calls getpass.getuser() at import time, +# which raises KeyError on an unknown uid. Setting USER/HOME makes getpass short- +# circuit on the env var, and routing torch/HF caches to world-writable /tmp keeps +# them writable for any uid (needed for the optional VSS_TORCH_COMPILE path). +ENV USER=appuser +ENV HOME=/tmp +ENV XDG_CACHE_HOME=/tmp/.cache +ENV TORCHINDUCTOR_CACHE_DIR=/tmp/torchinductor +ENV TRITON_CACHE_DIR=/tmp/triton + WORKDIR $APP_HOME COPY --from=builder /venv /venv COPY . . From 11bcb29dc19349645412869e544d3b1391bc275a Mon Sep 17 00:00:00 2001 From: danellecline Date: Thu, 16 Jul 2026 17:12:51 -0700 Subject: [PATCH 3/4] fix: enable torch.compile toolchain and add eager fallback Switch the runtime image to the CUDA devel base (plus python3.11-dev) so the Inductor/Triton backend used by VSS_TORCH_COMPILE=1 has the gcc/nvcc toolchain and headers it JIT-compiles against, fixing the "Failed to find C compiler" error. Also catch lazy torch.compile failures on the first forward and fall back to eager execution so a compile problem no longer fails every prediction. Co-authored-by: Cursor --- Dockerfile.cuda | 7 +++++-- src/app/predictors/process_vits.py | 31 +++++++++++++++++++++++++----- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/Dockerfile.cuda b/Dockerfile.cuda index d36403d..c8a79de 100644 --- a/Dockerfile.cuda +++ b/Dockerfile.cuda @@ -27,7 +27,10 @@ RUN find /venv -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null; \ true # ----------------------------------------------------------------------------- -FROM nvidia/cuda:13.0.1-base-ubuntu22.04 +# Use the CUDA "devel" image (not "base"/"runtime") so the optional +# VSS_TORCH_COMPILE path has the gcc/g++ toolchain, nvcc, and CUDA headers that +# torch.compile's Inductor/Triton backend JIT-compiles kernels against at runtime. +FROM nvidia/cuda:13.0.1-devel-ubuntu22.04 ENV DEBIAN_FRONTEND=noninteractive LABEL vendor="MBARI" LABEL maintainer="dcline@mbari.org" @@ -41,7 +44,7 @@ RUN apt-get update && \ add-apt-repository ppa:deadsnakes/ppa && \ apt-get update && \ apt-get install -y --no-install-recommends \ - python3.11 python3.11-venv \ + python3.11 python3.11-venv python3.11-dev \ curl libxcb1 libxcb-xinerama0 libxrender1 libxext6 libsm6 libice6 libgl1 && \ apt-get clean && rm -rf /var/lib/apt/lists/* diff --git a/src/app/predictors/process_vits.py b/src/app/predictors/process_vits.py index 367f545..7c0436d 100644 --- a/src/app/predictors/process_vits.py +++ b/src/app/predictors/process_vits.py @@ -44,9 +44,15 @@ def __init__(self, r: redis.Redis, device, model_name: str, reset: bool = False, # Optional torch.compile for a further speedup (one-time warmup cost). # Done last so vector_dimensions is read from the original (uncompiled) module. + # Compilation is lazy (happens on the first forward), and its Inductor/Triton + # backend requires a C compiler + CUDA headers in the runtime image. If those + # are missing the first forward raises; we keep an eager reference so we can + # fall back gracefully instead of failing every prediction (see get_image_embeddings). + self._compiled = False if os.getenv("VSS_TORCH_COMPILE", "0") == "1": info("Compiling model with torch.compile") self.model = torch.compile(self.model) + self._compiled = True if model_name.startswith("/"): if not os.path.exists(model_name): @@ -81,6 +87,14 @@ def preprocess_images(self, image_paths: List[str]) -> Iterator[Tuple[dict, List debug(f"Done preprocessing batch of {len(images)} images") yield inputs, valid_paths, failed_paths + def _forward(self, inputs): + """Run the model forward pass under inference_mode and optional fp16 autocast.""" + with torch.inference_mode(): + if self.amp_dtype is not None: + with torch.autocast(device_type=self.device.type, dtype=self.amp_dtype): + return self.model(**inputs) + return self.model(**inputs) + def get_image_embeddings(self, inputs): """get embeddings for a batch of images""" debug(f"Getting embeddings for batch of size {inputs['pixel_values'].shape[0]}") @@ -89,12 +103,19 @@ def get_image_embeddings(self, inputs): # Move inputs to same device as model (processor returns CPU tensors) inputs = {k: v.to(self.device, non_blocking=True) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} - with torch.inference_mode(): - if self.amp_dtype is not None: - with torch.autocast(device_type=self.device.type, dtype=self.amp_dtype): - embeddings = self.model(**inputs) + try: + embeddings = self._forward(inputs) + except Exception as e: + # torch.compile is lazy: Inductor/Triton kernel compilation happens on the + # first forward and can fail if the runtime lacks a C compiler/CUDA headers. + # Fall back to eager execution once instead of failing every prediction. + if self._compiled: + logger.warning(f"torch.compile forward failed ({e}); falling back to eager execution") + self.model = getattr(self.model, "_orig_mod", self.model) + self._compiled = False + embeddings = self._forward(inputs) else: - embeddings = self.model(**inputs) + raise info("Done getting embeddings for batch") # Cast back to float32 to match the Redis index (FLOAT32) regardless of autocast dtype batch_embeddings = embeddings.last_hidden_state[:, 0, :].float().cpu().numpy() From a384905e547974a64c433530caf3ef6aa3403650 Mon Sep 17 00:00:00 2001 From: danellecline Date: Thu, 16 Jul 2026 17:20:11 -0700 Subject: [PATCH 4/4] fix(docker): revert to CUDA base image to fix cuBLAS init failure The devel image sets LD_LIBRARY_PATH=/usr/local/cuda/lib64, which shadows the CUDA libraries bundled with the pip torch wheel and caused CUBLAS_STATUS_NOT_INITIALIZED (cublasLtMatmulAlgoGetHeuristic) at runtime. Revert to the lightweight base image and install just gcc/g++ so the optional VSS_TORCH_COMPILE (Triton) path still has a C/C++ compiler without dragging in the conflicting system CUDA libs. Co-authored-by: Cursor --- Dockerfile.cuda | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Dockerfile.cuda b/Dockerfile.cuda index c8a79de..fc7c74e 100644 --- a/Dockerfile.cuda +++ b/Dockerfile.cuda @@ -27,10 +27,14 @@ RUN find /venv -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null; \ true # ----------------------------------------------------------------------------- -# Use the CUDA "devel" image (not "base"/"runtime") so the optional -# VSS_TORCH_COMPILE path has the gcc/g++ toolchain, nvcc, and CUDA headers that -# torch.compile's Inductor/Triton backend JIT-compiles kernels against at runtime. -FROM nvidia/cuda:13.0.1-devel-ubuntu22.04 +# Keep the lightweight CUDA "base" image. Do NOT use the "devel" image here: it +# sets LD_LIBRARY_PATH=/usr/local/cuda/lib64, which shadows the CUDA libraries +# bundled with the pip torch wheel and causes cuBLAS/cuBLASLt version mismatches +# at runtime (CUBLAS_STATUS_NOT_INITIALIZED in cublasLtMatmulAlgoGetHeuristic). +# torch and triton ship their own CUDA libs; the only host dependency the +# optional VSS_TORCH_COMPILE (Inductor/Triton) path needs is a C/C++ compiler, +# installed below. +FROM nvidia/cuda:13.0.1-base-ubuntu22.04 ENV DEBIAN_FRONTEND=noninteractive LABEL vendor="MBARI" LABEL maintainer="dcline@mbari.org" @@ -45,6 +49,7 @@ RUN apt-get update && \ apt-get update && \ apt-get install -y --no-install-recommends \ python3.11 python3.11-venv python3.11-dev \ + gcc g++ \ curl libxcb1 libxcb-xinerama0 libxrender1 libxext6 libsm6 libice6 libgl1 && \ apt-get clean && rm -rf /var/lib/apt/lists/*