Search binary-quantised embeddings by Hamming distance

Why it matters Binary embeddings cut vector storage 32x and are a first-stage filter in large RAG systems.

Binary quantisation keeps one bit per dimension (1 if positive) and compares vectors with XOR and popcount.

Write hamming_topk(db, q, k). db is (n, d) floats, q is (d,). Binarise both with x > 0, pack bits with np.packbits along the last axis, compute Hamming distances via XOR and a bit count, and return the indices of the k smallest distances (ties by smaller index).

Signaturedef hamming_topk(db, q, k)

Example

db [[1, -1], [-1, 1], [1, 1]], q [1, -1], k 2 gives [0, 2].

Understand the idea

Binary quantisation shrinks an embedding to one bit per dimension: 1 if the value is positive, else 0. Similar vectors share most bits, so you compare them by Hamming distance, the number of differing bits. Packing 8 bits into a byte makes a 1024-dimension vector only 128 bytes, and XOR plus a bit count is very fast. Worked example: q = [1, -2, 3, -1] gives bits 1010. db row 0 [0.5, -1, 2, 0.1] gives 1011, distance 1. Row 1 [-1, -1, 1, 1] gives 0011, distance 2. Row 2 [1, 1, -1, -1] gives 1100, distance 2. With k = 2 the answer is [0, 1]: rows 1 and 2 tie at 2, so the smaller index wins. Rule: bits = x > 0 (zero counts as 0); pack bits along the last axis; distance = bit count of (db_packed XOR q_packed) summed over bytes; return indices of the k smallest distances using a stable sort. Padding bits added by packing are 0 on both sides, so they never change distances. Used in: memory-cheap first-stage retrieval before rescoring with full vectors.

Shapes and data flow

db (n, d) bool -> packbits -> (n, ceil(d/8)) uint8
XOR with q -> unpackbits -> sum -> dist (n,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplehamming_topk([[1, -1], [-1, 1], [1, 1]], [1, -1], 2)
  • Sample 2: randomhamming_topk(_db, _q, 4)
  • Test 3: self matchint(hamming_topk(_db, _db[7], 1)[0])