Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -259,17 +259,19 @@ def _search_batch_raw_split(context, split):

table_read, column, queries, limit, metric = context
scorer = BatchVectorSearchReadImpl(table_read.table, limit, column, queries)
prepared = [scorer._scoring_query(q, metric) for q in queries]
reader, batches = table_read._new_arrow_batch_reader([split])
with _ClosableArrowBatchReader(reader, batches) as batch_reader:
return [_batch_scores(result) for result in scorer._score_raw_batch_queries(batch_reader, metric)]
return [_batch_scores(result) for result in scorer._score_raw_batch_queries(batch_reader, prepared)]


def _search_batch_refine_split(context, split):
table_read, column, queries, limit, metric, queries_by_row = context
scorer = BatchVectorSearchReadImpl(table_read.table, limit, column, queries)
prepared = [scorer._scoring_query(q, metric) for q in queries]
# Read the candidate union once, scoring each row only for its own queries.
return [_batch_scores(result) for result in scorer._score_refine_splits(
table_read, [split], queries_by_row, queries, metric)]
table_read, [split], queries_by_row, prepared)]


def _batch_scores(result):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ def read_batch_plan(self, plan, executor=None):
return self._with_executor(executor).read_batch_plan(plan)
if not isinstance(plan, PrimaryKeyVectorScanPlan):
raise ValueError("Primary-key vector read requires a PrimaryKeyVectorScanPlan.")
self._scoring_queries = {}
self._index_metric = None
index_type = VectorIndexOptions.resolve(
self._table.options.options, None, self._vector_column.name, default_metric=False).index_type
Expand Down Expand Up @@ -120,9 +121,10 @@ def _search_exact_candidates(self, plan):
metric = self._search_metric(
VectorIndexOptions.resolve(
self._table.options.options, None, self._vector_column.name, default_metric=False).index_type)
queries = [self._scoring_query(q, metric) for q in self._query_vectors]
for split, data_file, positions, vectors in self._raw_batches(plan):
partition = _partition_bytes(split.data_split.partition)
for start, query_index, scores in _iter_arrow_batch_scores(vectors, self._query_vectors, metric):
for start, query_index, scores in _iter_arrow_batch_scores(vectors, queries):
rows = (PrimaryKeySearchPosition(
partition, split.data_split.bucket, data_file.file_name, position, score)
for position, score in zip(positions[start:start + len(scores)], scores) if score is not None)
Expand All @@ -144,15 +146,16 @@ def _rerank_indexed_batch(self, plan, candidates, index_type):
candidate_plan = PrimaryKeyVectorScanPlan(plan.snapshot_id, splits, plan.snapshot())
metric = self._search_metric(index_type)
reranked = [[] for _ in self._query_vectors]
queries = [self._scoring_query(q, metric) for q in self._query_vectors]
for split, data_file, positions, vectors in self._raw_batches(candidate_plan):
keys = [(_partition_bytes(split.data_split.partition), split.data_split.bucket,
data_file.file_name, position) for position in positions]
for i, query in enumerate(self._query_vectors):
for i, query in enumerate(queries):
offsets = [offset for offset, key in enumerate(keys) if key in selected[i]]
if not offsets:
continue
rows = vectors.take(pa.array(offsets, type=pa.int64()))
for offset, score in zip(offsets, _iter_arrow_scores(rows, query, metric)):
for offset, score in zip(offsets, _iter_arrow_scores(rows, query)):
if score is None:
raise ValueError("Primary-key vector candidate contains a null vector.")
reranked[i].append(selected[i].pop(keys[offset]).with_score(score))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def read_plan(self, plan, executor=None):
return self._with_executor(executor).read_plan(plan)
if not isinstance(plan, PrimaryKeyVectorScanPlan):
raise ValueError("Primary-key vector read requires a PrimaryKeyVectorScanPlan.")
self._scoring_queries = {}
self._index_metric = None
index_type = VectorIndexOptions.resolve(
self._table.options.options, None, self._vector_column.name, default_metric=False).index_type
Expand Down Expand Up @@ -126,6 +127,8 @@ def _rerank_indexed(self, plan, candidates, index_type):
[self._vector_column.name]).new_read()
metric = self._search_metric(index_type)

query = self._scoring_query(self._query_vector, metric)

def reranked_iter():
for split in candidate_result.splits:
data_split = split.data_split()
Expand All @@ -139,7 +142,7 @@ def reranked_iter():
if key[:3] == (partition, data_split.bucket, data_file_name))
position_iter = iter(positions)
for batch in reader.to_arrow([split]).to_batches():
for score in _iter_arrow_scores(batch.column(0), self._query_vector, metric):
for score in _iter_arrow_scores(batch.column(0), query):
try:
row_position = next(position_iter)
except StopIteration:
Expand Down Expand Up @@ -176,8 +179,9 @@ def _raw_candidates(self, plan):
metric = self._search_metric(
VectorIndexOptions.resolve(
self._table.options.options, None, self._vector_column.name, default_metric=False).index_type)
query = self._scoring_query(self._query_vector, metric)
for split, data_file, positions, vectors in self._raw_batches(plan):
for position, score in zip(positions, _iter_arrow_scores(vectors, self._query_vector, metric)):
for position, score in zip(positions, _iter_arrow_scores(vectors, query)):
if score is not None:
yield PrimaryKeySearchPosition(
_partition_bytes(split.data_split.partition), split.data_split.bucket,
Expand Down
126 changes: 126 additions & 0 deletions paimon-python/pypaimon/execution/python/read/search/vector_scoring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""Scalar and NumPy scoring for exact vector search."""

from typing import TYPE_CHECKING, List, Optional, Sequence, Union

import numpy as np

if TYPE_CHECKING:
from numpy.typing import NDArray

RealArray = NDArray[Union[np.integer, np.floating]]
Float64Array = NDArray[np.float64]
else:
# numpy.typing.NDArray was added after the minimum supported NumPy 1.19.
RealArray = Float64Array = np.ndarray

Vector = Union[Sequence[float], RealArray]


class _PreparedQuery:
"""Query-side operands for one exact search metric, shared by scoring blocks."""

def __init__(self, values: Vector, metric: str) -> None:
self.metric = metric
self.values = values
self.array: Optional[Float64Array] = None
self.cosine_norm: Optional[float] = None
try:
array = np.asarray(values, dtype=np.float64)
except (ValueError, TypeError, OverflowError):
return
if array.ndim != 1 or not array.size:
return
if metric == "cosine":
norm2 = 0.0
for value in array:
x = float(value)
norm2 += x * x
self.cosine_norm = norm2**0.5
if np.isfinite(array).all():
self.array = array

def __len__(self) -> int:
return len(self.values)


def _compute_scores(
query: _PreparedQuery, matrix: Float64Array
) -> Optional[List[float]]:
"""Score an owned float64 matrix, or request scalar fallback with None."""
metric = query.metric
if (
query.array is None
or matrix.ndim != 2
or matrix.shape[1] != len(query)
or not np.isfinite(matrix).all()
or metric not in ("l2", "cosine", "inner_product")
):
return None
with np.errstate(over="ignore", under="ignore", invalid="ignore", divide="ignore"):
if metric == "l2":
np.subtract(query.array, matrix, out=matrix)
np.square(matrix, out=matrix)
np.add.accumulate(matrix, axis=1, out=matrix)
return (1.0 / (1.0 + matrix[:, -1])).tolist()
if metric == "cosine":
norms = np.square(matrix)
np.add.accumulate(norms, axis=1, out=norms)
stored_norms = norms[:, -1].copy()
del norms
np.multiply(matrix, query.array, out=matrix)
if metric == "inner_product":
return [sum(row) for row in matrix.tolist()]
assert query.cosine_norm is not None
matrix[:, 0] += 0.0 # Match a scalar accumulator initialized to +0.0.
np.add.accumulate(matrix, axis=1, out=matrix)
denominators = [query.cosine_norm * float(norm) ** 0.5 for norm in stored_norms]
return [0.0 if denominator == 0 else float(dot) / denominator
for dot, denominator in zip(matrix[:, -1], denominators)]


def _compute_score(prepared: _PreparedQuery, stored: Vector) -> float:
query = prepared.values
metric = prepared.metric
if metric == "l2":
sum_sq = 0.0
for q, s in zip(query, stored):
diff = float(q) - float(s)
sum_sq += diff * diff
return 1.0 / (1.0 + sum_sq)
if metric == "cosine":
dot = 0.0
norm_b = 0.0
for q, s in zip(query, stored):
q = float(q)
s = float(s)
dot += q * s
norm_b += s * s
query_norm = prepared.cosine_norm
if query_norm is None:
# Irregular input remains subject to the scalar conversion rules.
norm2 = 0.0
for value in query:
norm2 += float(value) * float(value)
query_norm = norm2**0.5
denominator = query_norm * (norm_b**0.5)
return 0.0 if denominator == 0 else dot / denominator
if metric == "inner_product":
return sum(float(q) * float(s) for q, s in zip(query, stored))
raise ValueError(f"Unknown vector search metric: {metric}")
Loading
Loading