File size: 4,398 Bytes
f2c824d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python3
"""Reproducible benchmark for two-stage 1024-dim binary Hamming + int8 rescore retrieval."""

from __future__ import annotations

import argparse
import ctypes
import time
from pathlib import Path

import numpy as np


def pack_binary(vecs: np.ndarray) -> np.ndarray:
    bits = np.packbits(vecs > 0, axis=-1, bitorder="little")
    return np.ascontiguousarray(bits).view(np.uint64)


def quantize_i8(vecs: np.ndarray) -> np.ndarray:
    return np.ascontiguousarray(np.clip(np.round(vecs * 127.0), -127, 127).astype(np.int8))


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=200_000, help="Corpus vectors (1024-dim)")
    ap.add_argument("--dim", type=int, default=1024)
    ap.add_argument("--cand", type=int, default=3000)
    ap.add_argument("--k", type=int, default=10)
    ap.add_argument("--queries", type=int, default=20)
    ap.add_argument("--seed", type=int, default=42)
    args = ap.parse_args()
    assert args.dim == 1024, "Kernel specializes 1024 dimensions (16 x uint64 words)."

    lib_path = Path(__file__).resolve().parent / "libhamming_rescore.so"
    lib = ctypes.CDLL(str(lib_path))
    lib.scan_hamming_top_k.argtypes = [
        ctypes.POINTER(ctypes.c_uint64),
        ctypes.c_uint32,
        ctypes.POINTER(ctypes.c_uint64),
        ctypes.c_int,
        ctypes.POINTER(ctypes.c_uint32),
        ctypes.POINTER(ctypes.c_uint32),
    ]
    lib.scan_hamming_top_k.restype = ctypes.c_int
    lib.rescore_int8.argtypes = [
        ctypes.POINTER(ctypes.c_int8),
        ctypes.c_int,
        ctypes.POINTER(ctypes.c_float),
        ctypes.POINTER(ctypes.c_uint32),
        ctypes.c_int,
        ctypes.POINTER(ctypes.c_float),
    ]

    rng = np.random.default_rng(args.seed)
    print(f"Generating {args.n:,} unit-normalized {args.dim}-dim vectors...")
    db_f32 = rng.standard_normal((args.n, args.dim), dtype=np.float32)
    db_f32 /= np.linalg.norm(db_f32, axis=1, keepdims=True)
    db_bin = pack_binary(db_f32)
    db_i8 = quantize_i8(db_f32)

    q_f32 = rng.standard_normal((args.queries, args.dim), dtype=np.float32)
    # Mix real corpus neighbors + noise so top-k recall is meaningful on synthetic unit sphere
    for qi in range(args.queries):
        q_f32[qi] = 0.65 * db_f32[qi * (args.n // args.queries)] + 0.35 * q_f32[qi]
    q_f32 /= np.linalg.norm(q_f32, axis=1, keepdims=True)
    q_bin = pack_binary(q_f32)

    out_ids = np.empty(args.cand, dtype=np.uint32)
    out_dists = np.empty(args.cand, dtype=np.uint32)
    out_scores = np.empty(args.cand, dtype=np.float32)

    scan_ms, rescore_ms, recalls = [], [], []
    for qi in range(args.queries):
        t0 = time.perf_counter()
        got = lib.scan_hamming_top_k(
            db_bin.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)),
            args.n,
            q_bin[qi].ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)),
            args.cand,
            out_ids.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)),
            out_dists.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)),
        )
        t1 = time.perf_counter()
        lib.rescore_int8(
            db_i8.ctypes.data_as(ctypes.POINTER(ctypes.c_int8)),
            args.dim,
            q_f32[qi].ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
            out_ids.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)),
            got,
            out_scores.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
        )
        t2 = time.perf_counter()
        scan_ms.append((t1 - t0) * 1000.0)
        rescore_ms.append((t2 - t1) * 1000.0)

        top_pred = set(out_ids[np.argsort(-out_scores[:got])[: args.k]].tolist())
        exact = db_f32 @ q_f32[qi]
        top_true = set(np.argpartition(-exact, args.k)[: args.k].tolist())
        recalls.append(len(top_pred & top_true) / args.k)

    print(f"Binary RAM: {db_bin.nbytes / 1e6:.1f} MB | Int8 size: {db_i8.nbytes / 1e6:.1f} MB")
    print(f"Extrapolated to 47,018,430 vecs: {47_018_430 * 128 / 1e9:.3f} GB RAM (binary) | {47_018_430 * 1024 / 1e9:.3f} GB NVMe (int8)")
    print(f"Hamming scan p50: {np.median(scan_ms):.2f} ms (p95: {np.percentile(scan_ms, 95):.2f} ms)")
    print(f"Int8 rescore p50: {np.median(rescore_ms):.2f} ms (p95: {np.percentile(rescore_ms, 95):.2f} ms)")
    print(f"Recall@{args.k} vs exact float32: {np.mean(recalls) * 100:.1f}%")


if __name__ == "__main__":
    main()