Claude Code for FAISS: Fast Approximate Nearest Neighbor Search — Claude Skills 360 Blog
Blog / AI / Claude Code for FAISS: Fast Approximate Nearest Neighbor Search
AI

Claude Code for FAISS: Fast Approximate Nearest Neighbor Search

Published: October 30, 2027
Read time: 5 min read
By: Claude Skills 360

FAISS enables billion-scale nearest neighbor search on dense vectors. pip install faiss-cpu or faiss-gpu. import faiss. Exact L2: index = faiss.IndexFlatL2(dim) — brute-force, always returns exact results. Exact cosine: faiss.normalize_L2(vectors), then faiss.IndexFlatIP(dim). Add: index.add(np.array(vectors, dtype=np.float32)). Search: distances, indices = index.search(query_vectors, k=10) — returns (N, k) arrays, -1 for not-found. IVF approximate (faster): quantizer = faiss.IndexFlatL2(dim), index = faiss.IndexIVFFlat(quantizer, dim, nlist=100), index.train(training_vectors), index.nprobe = 10. IVF-PQ (compressed): faiss.IndexIVFPQ(quantizer, dim, nlist=100, m=8, nbits=8)m sub-quantizer groups. HNSW (graph-based): faiss.IndexHNSWFlat(dim, M=32)M connections per node, no training needed, best recall/latency tradeoff. Custom IDs: index = faiss.IndexIDMap(faiss.IndexFlatL2(dim)), index.add_with_ids(vectors, ids_array). Save: faiss.write_index(index, "index.faiss"), load: faiss.read_index("index.faiss"). GPU: res = faiss.StandardGpuResources(), gpu_index = faiss.index_cpu_to_gpu(res, 0, cpu_index). Factory: faiss.index_factory(dim, "IVF100,Flat") or "IVF256,PQ16" or "HNSW32". RangeSearch: lims, distances, indices = index.range_search(queries, radius=0.5). Claude Code generates FAISS vector indexes, semantic search backends, RAG retrieval layers, and billion-scale embedding stores.

CLAUDE.md for FAISS

## FAISS Stack
- Version: faiss-cpu >= 1.8 | faiss-gpu for CUDA acceleration
- Exact: IndexFlatL2(dim) | IndexFlatIP(dim) [normalize first for cosine]
- Fast: IndexHNSWFlat(dim, M=32) — no training, best recall/speed
- Large: IndexIVFFlat(quantizer, dim, nlist) → train() → add() → search()
- Compressed: IndexIVFPQ(quantizer, dim, nlist, m=8, nbits=8)
- IDs: IndexIDMap(base_index) → add_with_ids(vecs, int64_ids)
- Persist: write_index(index, path) | read_index(path)
- GPU: index_cpu_to_gpu(StandardGpuResources(), gpu_id, cpu_index)

FAISS Vector Search Pipeline

# nlp/faiss_pipeline.py — billion-scale vector similarity search with FAISS
from __future__ import annotations
import os
import time
import numpy as np
from pathlib import Path
from typing import Optional

import faiss


# ── 1. Index creation ────────────────────────────────────────────────────────

def create_flat_index(
    dim:        int,
    metric:     str = "l2",   # "l2" | "ip" (inner product = cosine if normalized)
) -> faiss.Index:
    """
    Exact brute-force index. No training required.
    - Use "l2"  for Euclidean distance
    - Use "ip"  + normalize_L2 for cosine similarity
    Fast for < 1M vectors; use approximate indexes for larger sets.
    """
    if metric == "ip":
        return faiss.IndexFlatIP(dim)
    return faiss.IndexFlatL2(dim)


def create_hnsw_index(
    dim:              int,
    M:                int = 32,     # Connections per node (16-64 typical)
    ef_construction:  int = 200,    # Build quality (higher = slower build, better recall)
    ef_search:        int = 64,     # Search quality (set at query time)
) -> faiss.Index:
    """
    HNSW graph-based ANN index.
    - Best recall/latency tradeoff, no training
    - M=32 is a good default (increase for higher recall)
    - Memory: ~(M * 4 * dim * n_vectors) bytes
    """
    index = faiss.IndexHNSWFlat(dim, M)
    index.hnsw.efConstruction = ef_construction
    index.hnsw.efSearch        = ef_search
    return index


def create_ivf_flat_index(
    dim:    int,
    nlist:  int = 100,   # Number of Voronoi cells (sqrt(N) is rule of thumb)
    metric: str = "l2",
) -> faiss.Index:
    """
    IVF (Inverted File) + Flat storage. Requires training.
    Good balance of speed and memory when N > 1M.
    nlist ~ sqrt(N): e.g., 100 for 10K, 1000 for 1M, 4096 for 10M vectors.
    """
    quantizer = faiss.IndexFlatL2(dim) if metric == "l2" else faiss.IndexFlatIP(dim)
    index     = faiss.IndexIVFFlat(quantizer, dim, nlist,
                                    faiss.METRIC_L2 if metric=="l2" else faiss.METRIC_INNER_PRODUCT)
    return index


def create_ivf_pq_index(
    dim:    int,
    nlist:  int = 256,
    m:      int = 8,      # Sub-quantizer groups (divides dim evenly)
    nbits:  int = 8,      # Bits per sub-quantizer (8 = 256 centroids)
) -> faiss.Index:
    """
    IVF + Product Quantization. Maximum compression, ~32x smaller than Flat.
    m must divide dim evenly (e.g., dim=768 → m=8, 12, 16, or 24).
    Memory: n_vectors * m * (nbits/8) bytes.
    """
    quantizer = faiss.IndexFlatL2(dim)
    index     = faiss.IndexIVFPQ(quantizer, dim, nlist, m, nbits)
    return index


def create_index_with_ids(base_index: faiss.Index) -> faiss.IndexIDMap:
    """Wrap any index to support custom int64 IDs instead of sequential 0..N-1."""
    return faiss.IndexIDMap(base_index)


# ── 2. Index building ─────────────────────────────────────────────────────────

def build_index(
    index:         faiss.Index,
    vectors:       np.ndarray,   # (N, D) float32
    ids:           np.ndarray = None,  # (N,) int64 — for IDMap indexes
    normalize:     bool = False,
    train_size:    int  = 50_000,
) -> None:
    """
    Train (if needed) and add vectors to the index.
    normalize=True converts to cosine similarity via IP.
    """
    vecs = np.ascontiguousarray(vectors.astype(np.float32))
    if normalize:
        faiss.normalize_L2(vecs)

    # Train if index requires it
    if hasattr(index, "is_trained") and not index.is_trained:
        train_vecs = vecs[:train_size] if len(vecs) > train_size else vecs
        print(f"Training on {len(train_vecs)} vectors...")
        index.train(train_vecs)
        print("Training complete")

    # Add vectors
    if ids is not None and isinstance(index, faiss.IndexIDMap):
        index.add_with_ids(vecs, np.array(ids, dtype=np.int64))
    else:
        index.add(vecs)

    print(f"Index built: {index.ntotal} vectors, dim={index.d}")


# ── 3. Search ─────────────────────────────────────────────────────────────────

def search(
    index:      faiss.Index,
    queries:    np.ndarray,       # (N, D) float32
    k:          int = 10,
    normalize:  bool = False,
    nprobe:     int  = None,      # IVF search quality (higher = slower, better recall)
) -> tuple[np.ndarray, np.ndarray]:
    """
    Search for k nearest neighbors.
    Returns (distances, indices) each shape (N, k).
    indices == -1 means not found (padding).
    """
    queries = np.ascontiguousarray(queries.astype(np.float32))
    if normalize:
        faiss.normalize_L2(queries)

    if nprobe is not None and hasattr(index, "nprobe"):
        index.nprobe = nprobe

    distances, indices = index.search(queries, k)
    return distances, indices


def search_range(
    index:     faiss.Index,
    query:     np.ndarray,   # (D,) or (1, D)
    radius:    float,
    normalize: bool  = False,
) -> list[tuple[int, float]]:
    """
    Range search: return all vectors within a given distance/similarity radius.
    Returns list of (index_id, distance) sorted by distance.
    """
    query = np.ascontiguousarray(query.reshape(1, -1).astype(np.float32))
    if normalize:
        faiss.normalize_L2(query)

    lims, distances, indices = index.range_search(query, radius)
    results = list(zip(indices.tolist(), distances.tolist()))
    return sorted(results, key=lambda x: x[1])


# ── 4. GPU acceleration ───────────────────────────────────────────────────────

def to_gpu(cpu_index: faiss.Index, gpu_id: int = 0) -> faiss.Index:
    """Move a FAISS index to GPU for faster search."""
    res = faiss.StandardGpuResources()
    return faiss.index_cpu_to_gpu(res, gpu_id, cpu_index)


def to_cpu(gpu_index: faiss.Index) -> faiss.Index:
    """Move a GPU index back to CPU for saving."""
    return faiss.index_gpu_to_cpu(gpu_index)


# ── 5. Persistence ────────────────────────────────────────────────────────────

def save_index(index: faiss.Index, path: str) -> None:
    """Save index to disk."""
    faiss.write_index(index, str(path))
    size_mb = os.path.getsize(path) / 1024 / 1024
    print(f"Saved: {path} ({size_mb:.1f} MB)")


def load_index(path: str) -> faiss.Index:
    """Load index from disk."""
    index = faiss.read_index(str(path))
    print(f"Loaded: {index.ntotal} vectors, dim={index.d}")
    return index


# ── 6. Semantic document store ────────────────────────────────────────────────

class FAISSDocumentStore:
    """
    A document store backed by FAISS for semantic retrieval.
    Stores text documents with their embeddings.
    """

    def __init__(
        self,
        dim:         int,
        index_type:  str = "hnsw",  # "flat" | "hnsw" | "ivf" | "ivfpq"
        nlist:       int = 256,
        normalize:   bool = True,
    ):
        self.dim       = dim
        self.normalize = normalize
        self.documents: list[str] = []
        self.metadata:  list[dict] = []

        if index_type == "flat":
            base = create_flat_index(dim, "ip" if normalize else "l2")
        elif index_type == "hnsw":
            base = create_hnsw_index(dim)
        elif index_type == "ivf":
            base = create_ivf_flat_index(dim, nlist)
        elif index_type == "ivfpq":
            m = max(1, dim // 96)  # ~96D per sub-quantizer
            base = create_ivf_pq_index(dim, nlist, m=m)
        else:
            raise ValueError(f"Unknown index_type: {index_type}")

        self.index = create_index_with_ids(base)

    def add(
        self,
        texts:      list[str],
        embeddings: np.ndarray,
        metadata:   list[dict] = None,
        train:      bool = True,
    ) -> None:
        """Add documents with their embeddings."""
        start_id  = len(self.documents)
        ids        = np.arange(start_id, start_id + len(texts), dtype=np.int64)
        self.documents.extend(texts)
        self.metadata.extend(metadata or [{} for _ in texts])

        build_index(self.index.index, embeddings,
                    normalize=self.normalize, train_size=max(len(texts), 50_000))
        # Rebuild IDMap with new vectors
        vecs = np.ascontiguousarray(embeddings.astype(np.float32))
        if self.normalize:
            faiss.normalize_L2(vecs)
        if not self.index.index.is_trained:
            self.index.index.train(vecs)
        self.index.add_with_ids(vecs, ids)

    def query(
        self,
        embedding: np.ndarray,
        k:         int = 10,
    ) -> list[dict]:
        """Return top-k documents by semantic similarity."""
        distances, indices = search(
            self.index, embedding.reshape(1, -1),
            k=k, normalize=self.normalize
        )
        results = []
        for dist, idx in zip(distances[0], indices[0]):
            if idx == -1:
                continue
            results.append({
                "text":     self.documents[idx],
                "metadata": self.metadata[idx],
                "score":    round(float(dist), 4),
                "id":       int(idx),
            })
        return results


# ── 7. Benchmarking ───────────────────────────────────────────────────────────

def benchmark_index(
    n_vectors:  int = 100_000,
    dim:        int = 384,
    n_queries:  int = 1_000,
    k:          int = 10,
) -> None:
    """Compare latency and recall of different FAISS index types."""
    print(f"Benchmark: {n_vectors} vectors, dim={dim}")

    rng     = np.random.default_rng(42)
    vectors = rng.random((n_vectors, dim), dtype=np.float32)
    queries = rng.random((n_queries, dim), dtype=np.float32)
    faiss.normalize_L2(vectors)
    faiss.normalize_L2(queries)

    # Ground truth from flat index
    flat = create_flat_index(dim, "ip")
    flat.add(vectors)
    _, gt_indices = flat.search(queries, k)

    configs = [
        ("Flat (exact)",  flat, None),
        ("HNSW-32",       create_hnsw_index(dim, M=32), None),
        ("IVF-100,Flat",  create_ivf_flat_index(dim, 100, "ip"), 10),
        ("IVF-100,PQ8",   create_ivf_pq_index(dim, 100, m=8), 10),
    ]

    for name, index, nprobe in configs:
        if index is flat:
            t0 = time.perf_counter()
            _, result_ids = index.search(queries, k)
        else:
            vecs = vectors.copy()
            if hasattr(index, "is_trained") and not index.is_trained:
                index.train(vecs)
            index.add(vecs)
            t0 = time.perf_counter()
            result_ids = search(index, queries, k=k, nprobe=nprobe)[1]

        elapsed_ms = (time.perf_counter() - t0) * 1000
        # Recall@k
        recall = np.mean([
            len(set(result_ids[i].tolist()) & set(gt_indices[i].tolist())) / k
            for i in range(n_queries)
        ])
        size_mb = index.ntotal * dim * 4 / 1024 / 1024
        print(f"  {name:<25} latency={elapsed_ms/n_queries:.2f}ms/q  recall={recall:.3f}  ~{size_mb:.0f}MB")


# ── Demo ──────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("FAISS Demo")
    print("="*50)

    dim      = 384
    n        = 10_000
    rng      = np.random.default_rng(0)
    vectors  = rng.random((n, dim), dtype=np.float32)
    faiss.normalize_L2(vectors)

    # Build HNSW index
    index = create_hnsw_index(dim, M=32)
    build_index(index, vectors)
    save_index(index, "/tmp/demo.faiss")
    index = load_index("/tmp/demo.faiss")

    # Search
    query_vec = rng.random((1, dim), dtype=np.float32)
    faiss.normalize_L2(query_vec)
    distances, indices = search(index, query_vec, k=5)
    print(f"\nTop-5 neighbors for random query:")
    for dist, idx in zip(distances[0], indices[0]):
        print(f"  id={idx}  similarity={dist:.4f}")

    # Benchmark
    print()
    benchmark_index(n_vectors=50_000, dim=dim, n_queries=500, k=10)

For the Qdrant/Weaviate/Pinecone alternative when needing a managed vector database with metadata filtering, hybrid search, cloud scaling, and production SLAs — managed vector DBs handle infrastructure while FAISS delivers 10-100x lower latency for read-heavy workloads by residing fully in-memory, supports GPU acceleration for billion-scale datasets in a single process without network overhead, and the IndexIVFPQ compression achieving 32x smaller footprint makes it the standard choice for embedding layers in recommendation systems, RAG retrieval, and image deduplication pipelines where sub-millisecond per-query latency matters. For the ScaNN / DiskANN alternative when needing higher recall at extreme scale (100M+ vectors) with disk-based storage — DiskANN handles datasets that exceed RAM while FAISS IndexHNSWFlat achieves >97% recall@10 at sub-millisecond latency for in-memory datasets up to ~100M vectors, and the faiss-gpu variant processes 1 billion vectors in under 1 second on a single V100 GPU, making it the go-to choice for GPU-accelerated ANN search. The Claude Skills 360 bundle includes FAISS skill sets covering flat/HNSW/IVF/PQ index creation, training and building, k-NN and range search, GPU acceleration, persistence, document store with ID mapping, and recall benchmarking. Start with the free tier to try vector search code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free