Add files using upload-large-folder tool
Browse files
src/ctx/core/graph/vector_index.py
CHANGED
|
@@ -73,9 +73,9 @@ class NumpyFlatVectorIndex:
|
|
| 73 |
min_score: float,
|
| 74 |
exclude_node_ids: set[str] | None = None,
|
| 75 |
) -> list[list[Neighbor]]:
|
|
|
|
| 76 |
if top_k <= 0 or self.vectors.size == 0:
|
| 77 |
-
return [[] for _ in range(len(
|
| 78 |
-
queries = _normalize(vectors)
|
| 79 |
scores = queries @ self.vectors.T
|
| 80 |
if exclude_node_ids:
|
| 81 |
for node_id in exclude_node_ids:
|
|
@@ -132,9 +132,9 @@ class HnswlibVectorIndex(NumpyFlatVectorIndex):
|
|
| 132 |
min_score: float,
|
| 133 |
exclude_node_ids: set[str] | None = None,
|
| 134 |
) -> list[list[Neighbor]]:
|
|
|
|
| 135 |
if top_k <= 0 or self.vectors.size == 0:
|
| 136 |
-
return [[] for _ in range(len(
|
| 137 |
-
queries = _normalize(vectors)
|
| 138 |
extra = len(exclude_node_ids or ())
|
| 139 |
k = min(len(self.node_ids), top_k + extra)
|
| 140 |
labels, distances = self._hnsw_index.knn_query(queries, k=k)
|
|
@@ -224,6 +224,7 @@ def load_vector_index(
|
|
| 224 |
node_ids, content_hashes, vectors = _load_numpy_data(cache_dir / _NUMPY_NAME)
|
| 225 |
if (
|
| 226 |
meta.node_count != len(node_ids)
|
|
|
|
| 227 |
or meta.dim != int(vectors.shape[1])
|
| 228 |
or meta.node_ids_sha256 != _hash_list(node_ids)
|
| 229 |
or meta.content_hashes_sha256 != _hash_list(content_hashes)
|
|
@@ -388,5 +389,15 @@ def _normalize(vectors: np.ndarray) -> np.ndarray:
|
|
| 388 |
return (matrix / norms).astype(np.float32)
|
| 389 |
|
| 390 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
def _hash_list(values: list[str]) -> str:
|
| 392 |
return hashlib.sha256("\n".join(values).encode("utf-8")).hexdigest()
|
|
|
|
| 73 |
min_score: float,
|
| 74 |
exclude_node_ids: set[str] | None = None,
|
| 75 |
) -> list[list[Neighbor]]:
|
| 76 |
+
queries = _normalize_query_vectors(vectors, expected_dim=self.meta.dim)
|
| 77 |
if top_k <= 0 or self.vectors.size == 0:
|
| 78 |
+
return [[] for _ in range(len(queries))]
|
|
|
|
| 79 |
scores = queries @ self.vectors.T
|
| 80 |
if exclude_node_ids:
|
| 81 |
for node_id in exclude_node_ids:
|
|
|
|
| 132 |
min_score: float,
|
| 133 |
exclude_node_ids: set[str] | None = None,
|
| 134 |
) -> list[list[Neighbor]]:
|
| 135 |
+
queries = _normalize_query_vectors(vectors, expected_dim=self.meta.dim)
|
| 136 |
if top_k <= 0 or self.vectors.size == 0:
|
| 137 |
+
return [[] for _ in range(len(queries))]
|
|
|
|
| 138 |
extra = len(exclude_node_ids or ())
|
| 139 |
k = min(len(self.node_ids), top_k + extra)
|
| 140 |
labels, distances = self._hnsw_index.knn_query(queries, k=k)
|
|
|
|
| 224 |
node_ids, content_hashes, vectors = _load_numpy_data(cache_dir / _NUMPY_NAME)
|
| 225 |
if (
|
| 226 |
meta.node_count != len(node_ids)
|
| 227 |
+
or vectors.ndim != 2
|
| 228 |
or meta.dim != int(vectors.shape[1])
|
| 229 |
or meta.node_ids_sha256 != _hash_list(node_ids)
|
| 230 |
or meta.content_hashes_sha256 != _hash_list(content_hashes)
|
|
|
|
| 389 |
return (matrix / norms).astype(np.float32)
|
| 390 |
|
| 391 |
|
| 392 |
+
def _normalize_query_vectors(vectors: np.ndarray, *, expected_dim: int) -> np.ndarray:
|
| 393 |
+
queries = _normalize(vectors)
|
| 394 |
+
actual_dim = int(queries.shape[1])
|
| 395 |
+
if actual_dim != expected_dim:
|
| 396 |
+
raise ValueError(
|
| 397 |
+
f"query vector dim {actual_dim} does not match index dim {expected_dim}"
|
| 398 |
+
)
|
| 399 |
+
return queries
|
| 400 |
+
|
| 401 |
+
|
| 402 |
def _hash_list(values: list[str]) -> str:
|
| 403 |
return hashlib.sha256("\n".join(values).encode("utf-8")).hexdigest()
|
src/tests/test_vector_index.py
CHANGED
|
@@ -65,6 +65,23 @@ def test_numpy_flat_query_excludes_node_ids_and_applies_min_score() -> None:
|
|
| 65 |
assert [n.node_id for n in rows[0]] == ["b"]
|
| 66 |
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def test_numpy_flat_round_trip_validates_model_and_fingerprint(tmp_path) -> None:
|
| 69 |
index = build_vector_index(
|
| 70 |
kind="numpy-flat",
|
|
@@ -109,6 +126,32 @@ def test_numpy_flat_round_trip_validates_model_and_fingerprint(tmp_path) -> None
|
|
| 109 |
)
|
| 110 |
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
def test_build_vector_index_rejects_duplicate_node_ids() -> None:
|
| 113 |
with pytest.raises(ValueError, match="duplicate node_id"):
|
| 114 |
build_vector_index(
|
|
|
|
| 65 |
assert [n.node_id for n in rows[0]] == ["b"]
|
| 66 |
|
| 67 |
|
| 68 |
+
def test_numpy_flat_query_rejects_wrong_dimension() -> None:
|
| 69 |
+
index = build_vector_index(
|
| 70 |
+
kind="numpy-flat",
|
| 71 |
+
model_id="model-a",
|
| 72 |
+
node_ids=["a", "b"],
|
| 73 |
+
content_hashes=["ha", "hb"],
|
| 74 |
+
vectors=_vectors()[:2],
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
with pytest.raises(ValueError, match="query vector dim 3 does not match index dim 2"):
|
| 78 |
+
index.query(
|
| 79 |
+
np.asarray([[1.0, 0.0, 0.0]], dtype=np.float32),
|
| 80 |
+
top_k=1,
|
| 81 |
+
min_score=0.0,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
def test_numpy_flat_round_trip_validates_model_and_fingerprint(tmp_path) -> None:
|
| 86 |
index = build_vector_index(
|
| 87 |
kind="numpy-flat",
|
|
|
|
| 126 |
)
|
| 127 |
|
| 128 |
|
| 129 |
+
def test_load_vector_index_rejects_corrupt_vector_shape(tmp_path) -> None:
|
| 130 |
+
index = build_vector_index(
|
| 131 |
+
kind="numpy-flat",
|
| 132 |
+
model_id="model-a",
|
| 133 |
+
node_ids=["a", "b"],
|
| 134 |
+
content_hashes=["ha", "hb"],
|
| 135 |
+
vectors=_vectors()[:2],
|
| 136 |
+
)
|
| 137 |
+
index.save(tmp_path)
|
| 138 |
+
np.savez_compressed(
|
| 139 |
+
tmp_path / "vector-index.numpy.npz",
|
| 140 |
+
node_ids=np.asarray(["a", "b"], dtype="U"),
|
| 141 |
+
content_hashes=np.asarray(["ha", "hb"], dtype="U"),
|
| 142 |
+
vecs=np.asarray([1.0, 0.0], dtype=np.float32),
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
assert (
|
| 146 |
+
load_vector_index(
|
| 147 |
+
tmp_path,
|
| 148 |
+
expected_model_id="model-a",
|
| 149 |
+
expected_content_fingerprint=index.meta.content_fingerprint,
|
| 150 |
+
)
|
| 151 |
+
is None
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
def test_build_vector_index_rejects_duplicate_node_ids() -> None:
|
| 156 |
with pytest.raises(ValueError, match="duplicate node_id"):
|
| 157 |
build_vector_index(
|