Quantisation, Recall Trade-offs, Batch Imports and Index Tuning

Article · 8:00

Product, binary and scalar quantisation with their measured recall costs, memory sizing per vector, batch import tuning, and the full recall-latency-memory surface.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Quantisation is the subject that makes this course distinct, because it is a memory-for-recall trade you configure explicitly and measure directly - and because an HNSW index holds its vectors in memory, so the memory question is the cost question.

The arithmetic to start from: a 768-dimension vector of 32-bit floats is 3,072 bytes, plus the graph's links. A million vectors is roughly 3 GB of vector data before the index overhead. Ten million is 30 GB. That is the number quantisation attacks.

Three kinds, in increasing aggression:

  • Scalar quantisation (SQ) stores each dimension as 8 bits instead of 32 - a 4x reduction, with a small recall cost that is often negligible. The safe first choice.
  • Product quantisation (PQ) splits the vector into segments and replaces each with a centroid id from a learned codebook. Typically 8x to 32x reduction, configurable, with a moderate recall cost. It requires training on your data, so it is enabled after an initial import, and the training set size matters.
  • Binary quantisation (BQ) reduces each dimension to a single bit - a 32x reduction, and the largest recall cost. It works surprisingly well for some models and badly for others, so it must be measured rather than assumed.

All three support rescoring: retrieve more candidates using the compressed vectors, then re-rank them using the full-precision vectors (which remain on disk). The rescore_limit parameter controls this, and rescoring recovers most of the lost recall for a modest latency cost - which makes aggressive quantisation far more usable than the raw numbers suggest and is the single most useful thing to know in this module.

The full surface has three axes - recall, latency and memory - and the module's purpose is to measure it rather than reason about it. The deliverable is a table: for each quantisation setting crossed with a few ef values, the recall, the p95 latency and the resident memory. Once you have it, the deployment decision is arithmetic rather than opinion.

Batch imports are where ingestion time goes. The v4 client's dynamic batching adjusts the batch size and concurrency automatically and is the right default; fixed-size batching gives you more control. The points that matter: check the failed-objects list, because a batch can partially fail and silently drop objects; the vectoriser is usually the bottleneck when using a module, exactly as the embedding model was in the Pinecone course; efConstruction and maxConnections affect import speed significantly; and importing with the HNSW index built incrementally is slower than importing and then building, which matters for a very large initial load.

Laboratory exercise 4 - the full surface, measured.

Load at least two million objects. Declare a baseline: recall@5, recall@10, MRR, p50/p95/p99 latency and resident memory, with no quantisation.

Measure the quantisation surface. For no quantisation, SQ, PQ at two compression settings, and BQ, each at ef of 64, 128 and 256, record recall@5, p95 latency and resident memory. That is a table of about fifteen rows and it is the module's main artefact.

Then measure rescoring: for BQ and the most aggressive PQ setting, record recall at rescore_limit of 0, 2x and 4x the limit, with the latency each adds. The recall recovery should be substantial.

Verify the memory arithmetic: compute the expected memory per vector for each setting and compare with the measured resident memory. Reconcile any difference - that reconciliation is the exercise, exactly as the capacity arithmetic was in the DynamoDB course.

Measure batch import three ways: dynamic batching, fixed batches of 100, and fixed batches of 1,000, recording objects per second and the failure rate. Demonstrate a partial batch failure and show the failed-objects list.

Then measure the import cost of the index parameters: import the same data with efConstruction of 64, 128 and 256 and record the import time and the resulting recall.

Deliverable: the baseline, the fifteen-row quantisation surface, the rescoring recovery measurements, the memory arithmetic reconciled against measurement, the three batch import measurements with the partial failure handling, the efConstruction import cost, and a recommended configuration with the numbers behind it.

PY Example 1 177 lines
# ==================================================================
# *** THE ARITHMETIC TO START FROM. An HNSW index holds its vectors
# *** IN MEMORY, so the memory question IS the cost question. ***
# ==================================================================
#   768 dimensions x 4 bytes (float32)        = 3,072 bytes/vector
#   + the HNSW graph's links
#     (~ max_connections x 2 layers x 8 bytes) ≈   512 bytes/vector
#   -------------------------------------------------------------
#   ~3.6 KB per vector
#
#     1,000,000 vectors  ->  ~3.6 GB
#    10,000,000 vectors  ->  ~36 GB
#   100,000,000 vectors  ->  ~360 GB     <- and now it is a budget
#
# *** THAT IS THE NUMBER QUANTISATION ATTACKS. ***

# ==================================================================
# THREE KINDS, in increasing aggression.
# ==================================================================
# SQ - SCALAR. 8 bits per dimension instead of 32. 4x. Small recall
#      cost, often negligible. *** THE SAFE FIRST CHOICE. ***
products.config.update(
    vector_index_config=wvc.config.Reconfigure.VectorIndex.hnsw(
        quantizer=wvc.config.Reconfigure.VectorIndex.Quantizer.sq(
            rescore_limit=200, training_limit=100000)))

# PQ - PRODUCT. Splits the vector into SEGMENTS and replaces each
#      with a CENTROID ID from a LEARNED CODEBOOK. 8x to 32x,
#      configurable. Moderate recall cost.
#      *** IT REQUIRES TRAINING ON YOUR DATA ***, so it is enabled
#      AFTER an initial import, and the training set size matters:
products.config.update(
    vector_index_config=wvc.config.Reconfigure.VectorIndex.hnsw(
        quantizer=wvc.config.Reconfigure.VectorIndex.Quantizer.pq(
            segments=96,              # 768 / 96 = 8 dims per segment
            centroids=256,            # 1 byte per segment
            training_limit=100000,
            rescore_limit=200,
            encoder_distribution=wvc.config.PQEncoderDistribution.NORMAL,
        )))
#   768 dims -> 96 bytes. *** 32x smaller. ***

# BQ - BINARY. ONE BIT per dimension. 32x, and the LARGEST recall
#      cost. *** IT WORKS SURPRISINGLY WELL FOR SOME MODELS AND
#      BADLY FOR OTHERS, SO IT MUST BE MEASURED RATHER THAN
#      ASSUMED. ***
products.config.update(
    vector_index_config=wvc.config.Reconfigure.VectorIndex.hnsw(
        quantizer=wvc.config.Reconfigure.VectorIndex.Quantizer.bq(
            rescore_limit=400, cache=True)))
#   768 dims -> 96 bytes of bits.

# ==================================================================
# *** RESCORING: THE MOST USEFUL THING IN THIS MODULE. ***
# ==================================================================
# All three support it: retrieve MORE candidates using the
# COMPRESSED vectors, then RE-RANK them using the FULL-PRECISION
# vectors, WHICH REMAIN ON DISK.
#
# *** RESCORING RECOVERS MOST OF THE LOST RECALL FOR A MODEST
# *** LATENCY COST, WHICH MAKES AGGRESSIVE QUANTISATION FAR MORE
# *** USABLE THAN THE RAW NUMBERS SUGGEST. ***
#
#   BQ, rescore_limit=0      recall@5 0.71    p95  3.1 ms
#   BQ, rescore_limit=100    recall@5 0.86    p95  5.8 ms
#   BQ, rescore_limit=200    recall@5 0.91    p95  8.2 ms
#   BQ, rescore_limit=400    recall@5 0.94    p95 13.4 ms
#   none                     recall@5 0.96    p95  8.1 ms
#
# 32x less memory for two points of recall and five milliseconds.
# THAT is the trade worth knowing, and nobody would guess it from
# the compression ratio alone.

# ==================================================================
# *** THE FULL SURFACE: recall x latency x memory. The main artefact. ***
# ==================================================================
import subprocess, json

def resident_memory_gb():
    # The honest measurement: what the container actually holds.
    out = subprocess.run(["docker", "stats", "--no-stream",
                          "--format", "{{.MemUsage}}", "weaviate"],
                         capture_output=True, text=True).stdout
    return out.strip()

for quant in ["none", "sq", "pq-96", "pq-192", "bq"]:
    apply_quantizer(products, quant)
    wait_for_reindex(products)
    for ef in [64, 128, 256]:
        products.config.update(
            vector_index_config=wvc.config.Reconfigure.VectorIndex.hnsw(ef=ef))
        m = evaluate(products, GROUND_TRUTH)
        print(quant, ef, m["recall@5"], m["p95"], resident_memory_gb())
#
#   quantizer   ef    recall@5   p95      memory   bytes/vector
#   none         64     0.87     8.1ms    7.4 GB      3,700
#   none        128     0.93    14.2ms    7.4 GB      3,700
#   none        256     0.96    26.1ms    7.4 GB      3,700
#   sq           64     0.86     6.2ms    2.4 GB      1,200
#   sq          128     0.92    10.1ms    2.4 GB      1,200
#   sq          256     0.95    18.4ms    2.4 GB      1,200
#   pq-96        64     0.79     4.1ms    1.2 GB        600
#   pq-96       256     0.91    12.8ms    1.2 GB        600
#   pq-192      256     0.94    14.1ms    1.6 GB        800
#   bq           64     0.71     3.1ms    0.9 GB        450
#   bq          256     0.91     8.2ms    0.9 GB        450
#
# *** ONCE YOU HAVE THIS TABLE, THE DEPLOYMENT DECISION IS
# *** ARITHMETIC RATHER THAN OPINION: *** "SQ at ef=256 gives 0.95
# recall at 18 ms in 2.4 GB; unquantised gives 0.96 at 26 ms in
# 7.4 GB. We take SQ and spend the memory on more tenants."

# ==================================================================
# VERIFY THE MEMORY ARITHMETIC against the measurement.
# ==================================================================
#   expected, SQ:  768 x 1 byte  +  ~512 links = ~1,280 bytes/vector
#                  x 2,000,000                  = ~2.56 GB
#   measured:                                     2.4 GB
#   -> close. RECONCILE ANY DIFFERENCE - that reconciliation is the
#   exercise, exactly as the capacity arithmetic was in the DynamoDB
#   course. If measured is much HIGHER, look for the inverted index,
#   the object store and the BM25 index, which are separate from the
#   vectors and which people forget.
print(products.aggregate.over_all(total_count=True).total_count)
#   and the node-level view:
for node in client.cluster.nodes(output="verbose"):
    print(node.name, node.stats.object_count, node.shards)

# ==================================================================
# BATCH IMPORTS: where ingestion time goes.
# ==================================================================
# DYNAMIC BATCHING - the right default. The client adjusts batch size
# and concurrency itself:
with products.batch.dynamic() as batch:
    for obj in source_objects():
        batch.add_object(properties=obj["properties"],
                         uuid=generate_uuid5(obj["sku"]),
                         vector=obj.get("vector"))

# *** CHECK THE FAILED OBJECTS. A BATCH CAN PARTIALLY FAIL AND
# *** SILENTLY DROP OBJECTS. ***
failed = products.batch.failed_objects
if failed:
    for f in failed[:10]:
        print(f.message, f.object_.properties.get("sku"))
    # Retry them individually, with backoff. Code that only checks
    # for an exception loses objects, and the only symptom is
    # slightly worse recall - the same failure shape as every other
    # vector course in this programme.

# FIXED batching, for more control:
with products.batch.fixed_size(batch_size=200, concurrent_requests=4) as batch:
    for obj in source_objects():
        batch.add_object(...)

#   measured:
#     dynamic batching             ___ objects/s
#     fixed 100 / 2 concurrent     ___ objects/s
#     fixed 1000 / 8 concurrent    ___ objects/s
#
# *** THE VECTORISER IS USUALLY THE BOTTLENECK when using a module ***
# - exactly as the embedding model was in the Pinecone course. With
# a local transformers module on CPU it dominates completely:
#     with text2vec-transformers (CPU)   ~120 objects/s
#     with text2vec-transformers (GPU)  ~1,800 objects/s
#     with pre-computed vectors (none)  ~6,000 objects/s
# NAME THE BOTTLENECK before tuning the database.

# AND THE INDEX PARAMETERS AFFECT IMPORT SPEED SIGNIFICANTLY:
#   ef_construction=64    import ___ s   recall@5 at ef=128: 0.89
#   ef_construction=128   import ___ s   recall@5 at ef=128: 0.93
#   ef_construction=256   import ___ s   recall@5 at ef=128: 0.94
#   -> diminishing recall for growing import time. Measure the knee.
#
# For a VERY LARGE initial load, importing with the index built
# incrementally is slower than importing and then building - check
# your version's support for deferring index construction.

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.