diff --git a/Dockerfile.cuda b/Dockerfile.cuda index fc46c34..fc7c74e 100644 --- a/Dockerfile.cuda +++ b/Dockerfile.cuda @@ -27,6 +27,13 @@ RUN find /venv -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null; \ true # ----------------------------------------------------------------------------- +# 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" @@ -41,7 +48,8 @@ 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 \ + gcc g++ \ curl libxcb1 libxcb-xinerama0 libxrender1 libxext6 libsm6 libice6 libgl1 && \ apt-get clean && rm -rf /var/lib/apt/lists/* @@ -57,6 +65,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 . . diff --git a/src/app/predictors/process_vits.py b/src/app/predictors/process_vits.py index 99bf59e..7c0436d 100644 --- a/src/app/predictors/process_vits.py +++ b/src/app/predictors/process_vits.py @@ -28,11 +28,32 @@ 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. + # 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): raise FileNotFoundError(f"Model directory {model_name} does not exist") @@ -66,18 +87,38 @@ 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]}") 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()} + + 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: + raise 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 +132,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))