Embedding collections grow faster than the text they describe because each float32 dimension costs four bytes in memory and on disk. Binary-quantized search cuts that cost by retrieving candidates from one-bit vectors, then ranking the shortlist with int8 vectors to recover detail the bits discard.

Sentence Transformers reduces each dimension to its sign for the binary vectors and to one of 256 levels for the int8 vectors. FAISS compares the packed bits by Hamming distance, a coarse measure that can tie two documents or order them differently from their cosine similarity, so the float32 query embedding has the final say over the shortlist.

Storage savings depend on what stays online. Packed binary vectors take one thirty-second of the float32 space, but rescoring still needs the int8 array, its calibration ranges, and a map from FAISS rows to document IDs. A document that misses the shortlist can never be rescored, so the shortlist must be larger than the number of results returned.

Steps to build binary-quantized search with Sentence Transformers:

  1. Activate the Python virtual environment in your project directory.
    $ source .venv/bin/activate
  2. Install Sentence Transformers and the CPU build of FAISS in the active environment.
    $ python -m pip install sentence-transformers faiss-cpu

    Tested with Sentence Transformers 6.2.0, faiss-cpu 1.16.0, and Python 3.14 on Ubuntu 26.04 arm64. On Linux, a plain install also pulls CUDA packages. CPU-only projects can install the CPU PyTorch wheel first.
    Related: How to install Sentence Transformers with pip

  3. Create documents.csv in the project directory with the following records, or with your own records in the same id and text columns.
    documents.csv
    id,text
    kb-101,Restart the router if every device loses Wi-Fi.
    kb-102,Reset a forgotten password from the sign-in page.
    kb-103,Replace the ink cartridge when pages come out faded.
    kb-104,Refunds reach the payment card within five business days.
    kb-105,Update the battery driver if charging stops at 80%.
    kb-106,Scan the QR code with an authenticator app to enable 2FA.
    kb-107,Connect a second monitor to the HDMI port.
    kb-108,Back up photos to the cloud before replacing a phone.
    kb-109,Move the router away from thick walls for better signal.
    kb-110,Cancel a subscription before renewal to avoid a charge.
    kb-111,Clear the browser cache if a site shows an old version.
    kb-112,Hold the power button for 10 seconds to restart a tablet.
    kb-113,Change the shipping address before the order leaves.
    kb-114,Pair headphones by holding the Bluetooth button.
    kb-115,Export contacts to a CSV file before closing an account.
    kb-116,Replace a swollen battery and do not charge the device.

    Row order matters because FAISS identifies each vector by its position. The first record becomes row 0.

  4. Save documents.csv.
  5. Create build_index.py in the same directory with the following imports and float32 encoding section.
    build_index.py
    import csv
    import json
    from pathlib import Path
     
    import faiss
    import numpy as np
    from sentence_transformers import SentenceTransformer
    from sentence_transformers.util.quantization import (
        quantize_embeddings,
    )
     
    csv_path = Path("documents.csv")
    with csv_path.open(newline="", encoding="utf-8") as csv_file:
        documents = list(csv.DictReader(csv_file))
     
    model = SentenceTransformer(
        "sentence-transformers/all-MiniLM-L6-v2"
    )
    float_embeddings = model.encode_document(
        [document["text"] for document in documents],
        normalize_embeddings=True,
    )

    encode_document() keeps the document prompt or route of retrieval models that separate corpus text from queries. Normalized vectors make the final scores comparable to cosine similarity.

  6. Add the following calibration and int8 section at the end of build_index.py.
    ranges = np.vstack(
        (float_embeddings.min(axis=0), float_embeddings.max(axis=0))
    )
    int8_embeddings = quantize_embeddings(
        float_embeddings,
        precision="int8",
        ranges=ranges,
    )
    np.save("corpus_int8.npy", int8_embeddings)
    np.save("int8_ranges.npy", ranges)

    The ranges hold each dimension's minimum and maximum, here calibrated on the corpus itself. For a larger corpus, calculate them from the whole corpus or a representative sample. Values outside the ranges clip to the int8 limits. Int8 files made before Sentence Transformers 5.7 use different bucket values, so they need a rebuild.

  7. Add the following binary index section at the end of build_index.py.
    binary_embeddings = quantize_embeddings(
        float_embeddings,
        precision="ubinary",
    )
    index = faiss.IndexBinaryFlat(float_embeddings.shape[1])
    index.add(binary_embeddings)
    faiss.write_index_binary(index, "corpus_binary.faiss")
    Path("row_documents.json").write_text(
        json.dumps(documents, indent=2),
        encoding="utf-8",
    )

    FAISS binary indexes accept uint8 rows, so the precision is ubinary. The signed binary form raises a TypeError. IndexBinaryFlat takes the vector length in bits and compares the query with each stored row.

  8. Add the following storage report at the end of build_index.py.
    saved_files = [
        "corpus_binary.faiss",
        "corpus_int8.npy",
        "int8_ranges.npy",
        "row_documents.json",
    ]
    print(f"indexed rows: {index.ntotal}, bits per row: {index.d}")
    print(f"float32: {float_embeddings.nbytes} bytes")
    print(f"packed binary: {binary_embeddings.nbytes} bytes")
    print(f"int8: {int8_embeddings.nbytes} bytes")
    for name in saved_files:
        print(f"{name}: {Path(name).stat().st_size} bytes on disk")
    total = sum(Path(name).stat().st_size for name in saved_files)
    print(f"total saved search files: {total} bytes")
  9. Save build_index.py.
  10. Run build_index.py to create the search files.
    $ python build_index.py
    ##### snipped #####
    indexed rows: 16, bits per row: 384
    float32: 24576 bytes
    packed binary: 768 bytes
    int8: 6144 bytes
    corpus_binary.faiss: 801 bytes on disk
    corpus_int8.npy: 6272 bytes on disk
    int8_ranges.npy: 3200 bytes on disk
    row_documents.json: 1548 bytes on disk
    total saved search files: 11821 bytes

    The first run downloads the public model, so the omitted lines include a warning about unauthenticated Hugging Face requests and a progress bar. No token is required.

    The packed binary vectors take 768 bytes against 24576 bytes of float32 embeddings. The 11821-byte total is what a deployment keeps, because rescoring still needs the int8 vectors, the ranges, and the row map.

  11. Create search_index.py in the same directory with the section that opens the saved files.
    search_index.py
    import json
    import sys
     
    import faiss
    import numpy as np
    from sentence_transformers import SentenceTransformer
    from sentence_transformers.util.quantization import (
        quantize_embeddings,
    )
     
    query, expected_id = sys.argv[1:3]
    top_k = 3
    rescore_multiplier = 2
     
    index = faiss.read_index_binary("corpus_binary.faiss")
    corpus_int8 = np.load("corpus_int8.npy", mmap_mode="r")
    starts, stops = np.load("int8_ranges.npy")
    with open("row_documents.json", encoding="utf-8") as json_file:
        documents = json.load(json_file)
    if not index.ntotal == len(corpus_int8) == len(documents):
        raise SystemExit("Saved search files differ in row count")

    mmap_mode="r" leaves the int8 array on disk, so a search reads the candidate rows instead of loading the whole file. The row-count check rejects files with different numbers of rows. The index, int8 array, calibration ranges, and row map must stay together from one build.

  12. Add the following binary retrieval section at the end of search_index.py.
    model = SentenceTransformer(
        "sentence-transformers/all-MiniLM-L6-v2"
    )
    query_embedding = model.encode_query(
        [query],
        normalize_embeddings=True,
    )
    query_binary = quantize_embeddings(
        query_embedding,
        precision="ubinary",
    )
    candidate_count = min(top_k * rescore_multiplier, index.ntotal)
    distances, rows = index.search(query_binary, candidate_count)
    candidate_rows = rows[0]
     
    print(f"binary candidates for: {query}")
    for row, distance in zip(candidate_rows, distances[0]):
        document_id = documents[row]["id"]
        print(f"row {row}: {document_id} hamming={distance}")

    The query model must match the model that built the index. A larger rescore_multiplier gives more documents a chance to be rescored and reads more int8 rows per search.

  13. Add the following rescoring section at the end of search_index.py.
    steps = (stops - starts) / 255
    candidate_int8 = corpus_int8[candidate_rows].astype("float32")
    decoded = (candidate_int8 + 128) * steps + starts
    scores = decoded @ query_embedding[0]
    ranked = np.argsort(-scores)[:top_k]

    The ranges decode each int8 value back to its original scale before the dot product. Multiplying the query by the stored codes directly ignores that per-dimension scale and can change the winning document.

  14. Add the following results and expected-document section at the end of search_index.py.
    print("int8 rescored results:")
    result_ids = []
    for rank, position in enumerate(ranked, start=1):
        document = documents[candidate_rows[position]]
        score = scores[position]
        result_ids.append(document["id"])
        print(f"{rank}. {document['id']} score={score:.4f}")
        print(f"   {document['text']}")
     
    top_id = result_ids[0]
    if top_id != expected_id:
        raise SystemExit(f"Expected {expected_id}, got {top_id}")
    print(f"expected top hit: {expected_id}")
  15. Save search_index.py.
  16. Run search_index.py with the sample query and expected document ID, or with your own pair.
    $ python search_index.py "keep my address book" kb-115
    ##### snipped #####
    binary candidates for: keep my address book
    row 14: kb-115 hamming=145
    row 12: kb-113 hamming=147
    row 2: kb-103 hamming=157
    row 9: kb-110 hamming=163
    row 1: kb-102 hamming=168
    row 15: kb-116 hamming=172
    int8 rescored results:
    1. kb-115 score=0.3523
       Export contacts to a CSV file before closing an account.
    2. kb-113 score=0.3410
       Change the shipping address before the order leaves.
    3. kb-103 score=0.2448
       Replace the ink cartridge when pages come out faded.
    expected top hit: kb-115

    Omitted lines hold the model loading messages. Each row line maps a FAISS row to its document. The script stops with an Expected error when another document ranks first, which also happens for this query if the rescoring section skips the ranges.

Share this guide