vector_index.py
4.61 KB
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
"""Exact, tenant-filtered recall. SQLite is the only persistent state."""
import threading
import numpy as np
from .feature_extractor import CNN_VECTOR_DIM
def configured_dimension(config):
return config.get('feature_extractor', {}).get('cnn', {}).get('vector_dim', CNN_VECTOR_DIM)
class VectorIndex:
def __init__(self, dimension=CNN_VECTOR_DIM):
self.dimension = dimension
self.lock = threading.RLock()
self.vectors = np.empty((0, dimension), dtype=np.float32)
self.ids = np.empty(0, dtype=np.int64)
self.eps_ids = np.empty(0, dtype=np.int64)
self.versions = np.empty(0, dtype=np.int64)
self.rows = {}
self._size = 0
def bulk_load(self, rows):
"""Replace the index from a single pass over SQLite's vector-only rows."""
rows = list(rows)
ids = np.array([row['id'] for row in rows], dtype=np.int64)
positions = {int(design_id): i for i, design_id in enumerate(ids)}
if len(positions) != len(rows):
raise ValueError('Duplicate design id in bulk load')
for row in rows:
shape = np.shape(row['cnn_vector'])
if shape != (self.dimension,):
raise ValueError(f"CNN vector dimension mismatch for design {row['id']}: "
f"expected ({self.dimension},), got {shape}")
vectors = np.array([row['cnn_vector'] for row in rows], dtype=np.float32).reshape(-1, self.dimension)
norms = np.linalg.norm(vectors, axis=1)
if not np.isfinite(norms).all() or np.any(norms == 0):
raise ValueError('Invalid CNN vector')
vectors /= norms[:, None]
eps_ids = np.array([row['eps_id'] for row in rows], dtype=np.int64)
versions = np.array([row['feat_version'] for row in rows], dtype=np.int64)
with self.lock:
self.vectors, self.ids = vectors, ids
self.eps_ids, self.versions = eps_ids, versions
self.rows = positions
self._size = len(rows)
def _grow(self):
"""Double storage only when full, making incremental appends amortized."""
capacity = max(1, len(self.ids) * 2)
vectors = np.empty((capacity, self.dimension), dtype=np.float32)
ids = np.empty(capacity, dtype=np.int64)
eps_ids = np.empty(capacity, dtype=np.int64)
versions = np.empty(capacity, dtype=np.int64)
for target, source in zip((vectors, ids, eps_ids, versions),
(self.vectors, self.ids, self.eps_ids, self.versions)):
target[:self._size] = source[:self._size]
self.vectors, self.ids = vectors, ids
self.eps_ids, self.versions = eps_ids, versions
def upsert(self, design_id, eps_id, vector, feat_version):
vector = np.asarray(vector, dtype=np.float32).reshape(self.dimension)
norm = np.linalg.norm(vector)
if not np.isfinite(norm) or norm == 0:
raise ValueError('Invalid CNN vector')
vector = vector / norm
with self.lock:
row = self.rows.get(int(design_id))
if row is None:
if self._size == len(self.ids):
self._grow()
row = self._size
self.rows[int(design_id)] = row
self.ids[row] = design_id
self._size += 1
self.vectors[row] = vector
self.eps_ids[row] = eps_id
self.versions[row] = feat_version
def remove(self, design_id):
with self.lock:
row = self.rows.pop(int(design_id), None)
if row is None:
return
last = self._size - 1
if row != last:
for array in (self.vectors, self.ids, self.eps_ids, self.versions):
array[row] = array[last]
self.rows[int(self.ids[row])] = row
self._size -= 1
def search(self, vector, eps_id, k):
vector = np.asarray(vector, dtype=np.float32).reshape(self.dimension)
vector = vector / (np.linalg.norm(vector) or 1)
with self.lock:
rows = np.flatnonzero(self.eps_ids[:self._size] == eps_id)
scores = self.vectors[rows] @ vector
order = np.lexsort((self.ids[rows], -scores))[:max(0, k)]
return [(int(self.ids[rows[i]]), float(scores[i]),
int(self.versions[rows[i]])) for i in order]
def stats(self):
with self.lock:
tenants, counts = np.unique(self.eps_ids[:self._size], return_counts=True)
return {'total_vectors': self._size,
'by_eps_id': {str(t): int(n) for t, n in zip(tenants, counts)}}