From 9eaf4c675720cdd24affb66ae73ec57a4c2116cd Mon Sep 17 00:00:00 2001 From: zhigang <40266193+wangzhigang1999@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:50:59 +0800 Subject: [PATCH] [python] Prepare query vectors once per exact search --- .../read/search/distributed_vector_search.py | 6 +- .../search/primary_key_batch_vector_read.py | 9 +- .../read/search/primary_key_vector_read.py | 8 +- .../python/read/search/vector_scoring.py | 126 ++++++++++++ .../python/read/search/vector_search_read.py | 192 ++++-------------- .../tests/batch_vector_raw_scan_test.py | 2 +- .../batch_vector_streaming_refine_test.py | 12 +- .../primary_key_global_index_golden_test.py | 4 +- .../tests/read_backend_retention_test.py | 6 +- .../pypaimon/tests/vector_scoring_test.py | 127 ++++++++---- .../tests/vector_search_filter_test.py | 4 +- .../tests/vector_search_streaming_test.py | 5 +- 12 files changed, 290 insertions(+), 211 deletions(-) create mode 100644 paimon-python/pypaimon/execution/python/read/search/vector_scoring.py diff --git a/paimon-python/pypaimon/execution/python/read/search/distributed_vector_search.py b/paimon-python/pypaimon/execution/python/read/search/distributed_vector_search.py index 4ffc774511fb..833b9653b29c 100644 --- a/paimon-python/pypaimon/execution/python/read/search/distributed_vector_search.py +++ b/paimon-python/pypaimon/execution/python/read/search/distributed_vector_search.py @@ -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): diff --git a/paimon-python/pypaimon/execution/python/read/search/primary_key_batch_vector_read.py b/paimon-python/pypaimon/execution/python/read/search/primary_key_batch_vector_read.py index f4c168493671..d12c7ca8a54d 100644 --- a/paimon-python/pypaimon/execution/python/read/search/primary_key_batch_vector_read.py +++ b/paimon-python/pypaimon/execution/python/read/search/primary_key_batch_vector_read.py @@ -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 @@ -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) @@ -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)) diff --git a/paimon-python/pypaimon/execution/python/read/search/primary_key_vector_read.py b/paimon-python/pypaimon/execution/python/read/search/primary_key_vector_read.py index 5b82e9e22675..eac3d4a36b1c 100644 --- a/paimon-python/pypaimon/execution/python/read/search/primary_key_vector_read.py +++ b/paimon-python/pypaimon/execution/python/read/search/primary_key_vector_read.py @@ -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 @@ -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() @@ -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: @@ -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, diff --git a/paimon-python/pypaimon/execution/python/read/search/vector_scoring.py b/paimon-python/pypaimon/execution/python/read/search/vector_scoring.py new file mode 100644 index 000000000000..a2eb225d02b0 --- /dev/null +++ b/paimon-python/pypaimon/execution/python/read/search/vector_scoring.py @@ -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}") diff --git a/paimon-python/pypaimon/execution/python/read/search/vector_search_read.py b/paimon-python/pypaimon/execution/python/read/search/vector_search_read.py index 7b54aaa966d1..3b0bf39554b8 100644 --- a/paimon-python/pypaimon/execution/python/read/search/vector_search_read.py +++ b/paimon-python/pypaimon/execution/python/read/search/vector_search_read.py @@ -45,6 +45,7 @@ RawVectorSearchSplit, ) from pypaimon.execution.python.read.search import global_index_live_row_filter +from pypaimon.execution.python.read.search.vector_scoring import _compute_score, _compute_scores, _PreparedQuery from pypaimon.utils.range import Range from pypaimon.utils.roaring_bitmap import RoaringBitmap64 @@ -54,6 +55,7 @@ import pyarrow as pa + from pypaimon.execution.python.read.search.vector_scoring import Vector from pypaimon.read.read_support import _ClosableArrowBatchReader from pypaimon.read.split import Split from pypaimon.read.table_read import TableRead @@ -79,9 +81,18 @@ def __init__( self._filter = filter_ self._partition_filter = partition_filter self._options = dict(options or {}) + self._scoring_queries: Dict[Tuple[int, str], _PreparedQuery] = {} self._index_metric = None self._scalar_pre_filter = None + def _scoring_query(self, query: "Vector", metric: str) -> "_PreparedQuery": + # Refinement and the raw scan can share operands after the index metric + # is known. Prepare on the coordinator before splitting work among threads. + key = (id(query), metric) + if key not in self._scoring_queries: + self._scoring_queries[key] = _PreparedQuery(query, metric) + return self._scoring_queries[key] + def _with_executor(self, executor): from pypaimon.execution.python.read.search.distributed_search import create_distributed_reader return create_distributed_reader(self, executor) @@ -397,6 +408,7 @@ def _iter_raw_scores( ) -> Iterator[Tuple[int, float]]: # Bound the Arrow take as well as the scoring matrix for wide vectors. blocks = batches if score_candidates is None else _slice_batches(batches, _score_block_size(query_vector)) + query = self._scoring_query(query_vector, metric) for block in blocks: row_ids = block.column(SpecialFields.ROW_ID.name).to_pylist() if score_candidates is not None: @@ -410,7 +422,7 @@ def _iter_raw_scores( else: vectors = block.column(self._vector_column.name) for row_id, score in zip( - row_ids, _iter_arrow_scores(vectors, query_vector, metric) + row_ids, _iter_arrow_scores(vectors, query) ): if score is None: continue @@ -419,35 +431,6 @@ def _iter_raw_scores( yield row_id, score del block, row_ids, vectors - def _read_raw_vectors(self, candidates, include_filter=True, snapshot=None): - return self._read_raw_candidate_vectors( - candidates.to_range_list(), candidates, include_filter, snapshot) - - def _read_raw_candidate_vectors(self, raw_row_ranges, candidates, - include_filter=True, snapshot=None): - raw_row_ranges = _filtered_raw_row_ranges(raw_row_ranges, None) - if not raw_row_ranges: - return {} - - table = self._read_raw_arrow(raw_row_ranges, include_filter, snapshot) - if table is None or table.num_rows == 0: - return {} - - row_ids = table.column(SpecialFields.ROW_ID.name).to_pylist() - vectors = table.column(self._vector_column.name).to_pylist() - raw_vectors = {} - for row_id, stored in zip(row_ids, vectors): - if candidates is not None and row_id not in candidates: - continue - if stored is None: - continue - raw_vectors[row_id] = _to_vector_list(stored) - return raw_vectors - - def _read_raw_arrow(self, raw_row_ranges, include_filter, snapshot=None): - reader, splits = self._plan_raw_read(raw_row_ranges, include_filter, snapshot) - return reader.to_arrow(splits) - def _plan_raw_read(self, raw_row_ranges, include_filter, snapshot=None): read_table = global_index_live_row_filter.table_at_snapshot( self._table, snapshot) @@ -464,28 +447,6 @@ def _plan_raw_read(self, raw_row_ranges, include_filter, snapshot=None): plan = read_builder.new_scan().with_row_ranges(raw_row_ranges).plan() return read_builder.new_read(), plan.splits() - def _score_raw_vectors(self, candidates, raw_vectors, query_vector, metric, top_k): - top_k_heap = [] - row_ids, vectors = [], [] - - def offer_block(): - for row_id, score in zip(row_ids, _score_rows(vectors, query_vector, metric)): - _offer_score(top_k_heap, top_k, row_id, score) - - block_size = _score_block_size(query_vector) - for row_id in candidates: - stored_vector = raw_vectors.get(row_id) - if stored_vector is None: - continue - row_ids.append(row_id) - vectors.append(stored_vector) - if len(vectors) == block_size: - offer_block() - row_ids, vectors = [], [] - if vectors: - offer_block() - return _scored_result(top_k_heap) - def _read_raw_refine_search(self, candidates, query_vector, index_type=None, snapshot=None): return self._read_raw_candidate_search( @@ -641,10 +602,11 @@ def _stream_rerank_candidates(self, candidates, union_candidates, query_vectors, table_read, splits = self._plan_raw_read( union_candidates.to_range_list(), include_filter=False, snapshot=snapshot) metric = self._search_metric(index_type) + query_vectors = [self._scoring_query(q, metric) for q in query_vectors] workers = min(len(splits), table_read._resolve_parallelism(None, len(splits))) if workers <= 1: return self._score_refine_splits( - table_read, splits, queries_by_row, query_vectors, metric) + table_read, splits, queries_by_row, query_vectors) # Preserve split read parallelism with one streaming reader per worker. # Candidate membership is shared; vectors are released after each batch. @@ -652,7 +614,7 @@ def _stream_rerank_candidates(self, candidates, union_candidates, query_vectors, with ThreadPoolExecutor(max_workers=workers) as executor: futures = [executor.submit( self._score_refine_splits, table_read, splits[i::workers], - queries_by_row, query_vectors, metric) for i in range(workers)] + queries_by_row, query_vectors) for i in range(workers)] for future in futures: for heap, result in zip(heaps, future.result()): score_getter = result.score_getter() @@ -660,7 +622,7 @@ def _stream_rerank_candidates(self, candidates, union_candidates, query_vectors, _offer_score(heap, self._limit, row_id, score_getter(row_id)) return [_scored_result(heap) for heap in heaps] - def _score_refine_splits(self, table_read, splits, queries_by_row, query_vectors, metric): + def _score_refine_splits(self, table_read, splits, queries_by_row, query_vectors): from pypaimon.read.read_support import _ClosableArrowBatchReader heaps = [[] for _ in query_vectors] @@ -679,7 +641,7 @@ def _score_refine_splits(self, table_read, splits, queries_by_row, query_vectors block_size = _score_block_size(query) for start in range(0, len(selected), block_size): block = selected[start:start + block_size] - scores = _iter_arrow_scores(vectors.take(block), query, metric) + scores = _iter_arrow_scores(vectors.take(block), query) for position, score in zip(block, scores): if score is not None: _offer_score(heaps[query_index], self._limit, @@ -733,6 +695,7 @@ def _new_distributed_reader(self, executor): return DistributedVectorSearchRead(self, executor) def _read(self, splits, snapshot): + self._scoring_queries = {} self._index_metric = None index_splits, raw_splits = self._prepare_search_splits(splits, snapshot) if not index_splits and not raw_splits: @@ -795,6 +758,7 @@ def _new_distributed_reader(self, executor): return DistributedBatchVectorSearchRead(self, executor) def _read_batch(self, splits, snapshot): + self._scoring_queries = {} self._index_metric = None n = len(self._query_vectors) index_splits, raw_splits = self._prepare_search_splits(splits, snapshot) @@ -842,15 +806,16 @@ def _read_raw_batch_search(self, raw_row_ranges, pre_filter, table_read, splits = self._plan_raw_read(raw_row_ranges, True, snapshot) metric = self._search_metric(index_type) + queries = [self._scoring_query(q, metric) for q in self._query_vectors] workers = min(len(splits), table_read._resolve_parallelism(None, len(splits))) if workers <= 1: - return self._score_raw_splits(table_read, splits, metric) + return self._score_raw_splits(table_read, splits, queries) # Keep only one streaming reader and Q top-k heaps per worker, even # when the plan contains many splits. Each split is scanned once. with ThreadPoolExecutor(max_workers=workers) as executor: futures = [executor.submit( - self._score_raw_splits, table_read, splits[i::workers], metric) + self._score_raw_splits, table_read, splits[i::workers], queries) for i in range(workers)] for future in futures: for heap, result in zip(heaps, future.result()): @@ -859,21 +824,21 @@ def _read_raw_batch_search(self, raw_row_ranges, pre_filter, _offer_score(heap, self._limit, row_id, score_getter(row_id)) return [_scored_result(heap) for heap in heaps] - def _score_raw_splits(self, table_read, splits, metric): + def _score_raw_splits(self, table_read, splits, queries): from pypaimon.read.read_support import _ClosableArrowBatchReader reader, batches = table_read._new_arrow_batch_reader(splits) # Close the underlying iterator as well if scoring fails mid-batch. with _ClosableArrowBatchReader(reader, batches) as batch_reader: - return self._score_raw_batch_queries(batch_reader, metric) + return self._score_raw_batch_queries(batch_reader, queries) - def _score_raw_batch_queries(self, batches, metric): + def _score_raw_batch_queries(self, batches, queries): heaps = [[] for _ in self._query_vectors] for batch in batches: row_ids = batch.column(SpecialFields.ROW_ID.name).to_pylist() vectors = batch.column(self._vector_column.name) for start, query_index, scores in _iter_arrow_batch_scores( - vectors, self._query_vectors, metric + vectors, queries ): heap = heaps[query_index] block_row_ids = row_ids[start:start + len(scores)] @@ -1166,12 +1131,12 @@ def _score_block_size(query): return max(1, min(1024, (1 << 20) // max(1, len(query)))) -def _iter_arrow_scores(vectors, query, metric): +def _iter_arrow_scores(vectors, query): block_size = _score_block_size(query) for start in range(0, len(vectors), block_size): block = vectors.slice(start, block_size) matrix = _arrow_score_matrix(block, len(query)) - scores = None if matrix is None else _compute_scores(query, matrix, metric) + scores = None if matrix is None else _compute_scores(query, matrix) if scores is None: for vector in block.to_pylist(): if vector is None: @@ -1179,12 +1144,12 @@ def _iter_arrow_scores(vectors, query, metric): else: vector = _to_vector_list(vector) _check_vector_dimension(query, vector) - yield _compute_score(query, vector, metric) + yield _compute_score(query, vector) else: yield from scores -def _iter_arrow_batch_scores(vectors, queries, metric): +def _iter_arrow_batch_scores(vectors, queries): """Yield vectorized scores for one Arrow batch without expanding its rows. The float64 row matrix is materialized once per bounded block and reused for @@ -1197,18 +1162,10 @@ def _iter_arrow_batch_scores(vectors, queries, metric): return block_size = min(_score_block_size(query) for query in queries) dimension = len(queries[0]) - fast_queries = metric in ("l2", "cosine", "inner_product") - if fast_queries: - for query in queries: - try: - query_array = np.asarray(query, dtype=np.float64) - except (ValueError, TypeError, OverflowError): - fast_queries = False - break - if (query_array.ndim != 1 or len(query_array) != dimension or - not dimension or not np.isfinite(query_array).all()): - fast_queries = False - break + fast_queries = all( + q.array is not None and len(q) == dimension and q.metric in ("l2", "cosine", "inner_product") + for q in queries + ) for start in range(0, len(vectors), block_size): block = vectors.slice(start, block_size) @@ -1225,7 +1182,7 @@ def _iter_arrow_batch_scores(vectors, queries, metric): if matrix is None: rows = block.to_pylist() for query_index, query in enumerate(queries): - yield start, query_index, _score_rows(rows, query, metric) + yield start, query_index, _score_rows(rows, query) continue last_query = len(queries) - 1 @@ -1233,7 +1190,7 @@ def _iter_arrow_batch_scores(vectors, queries, metric): # Scoring mutates its owned matrix. Reuse the original for the last # query and keep only one scratch copy for every preceding query. working = matrix if query_index == last_query else matrix.copy() - scores = _compute_scores(query, working, metric) + scores = _compute_scores(query, working) assert scores is not None if positions is not None: restored = [None] * len(block) @@ -1268,7 +1225,7 @@ def _arrow_score_matrix(vectors, dimension): len(vectors), dimension) -def _score_rows(vectors, query, metric): +def _score_rows(vectors, query): import numpy as np scores = None @@ -1278,7 +1235,7 @@ def _score_rows(vectors, query, metric): except (ValueError, TypeError, OverflowError): matrix = None if matrix is not None: - scores = _compute_scores(query, matrix, metric) + scores = _compute_scores(query, matrix) if scores is not None: return scores result = [] @@ -1288,74 +1245,5 @@ def _score_rows(vectors, query, metric): else: vector = _to_vector_list(vector) _check_vector_dimension(query, vector) - result.append(_compute_score(query, vector, metric)) + result.append(_compute_score(query, vector)) return result - - -def _compute_scores(query, matrix, metric): - """Score an owned float64 matrix while preserving scalar reduction semantics. - - L2/cosine use left-to-right accumulation, as in the scalar loops. Inner - product uses Python's sum on precomputed products, retaining its behavior - across Python versions (including compensated summation on Python 3.12+). - Returning None selects the scalar fallback. - """ - import numpy as np - - try: - query = np.asarray(query, dtype=np.float64) - except (ValueError, TypeError, OverflowError): - return None - if (matrix.ndim != 2 or query.ndim != 1 or not len(query) or - matrix.shape[1] != len(query) or not np.isfinite(matrix).all() or - not np.isfinite(query).all()): - return None - if metric not in ("l2", "cosine", "inner_product"): - return None - with np.errstate(over="ignore", invalid="ignore", divide="ignore"): - if metric == "l2": - np.subtract(query, 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 - query_norm = 0.0 - for value in query: - value = float(value) - query_norm += value * value - np.multiply(matrix, query, out=matrix) - if metric == "inner_product": - return [sum(row) for row in matrix.tolist()] - matrix[:, 0] += 0.0 # Match a scalar accumulator initialized to +0.0. - np.add.accumulate(matrix, axis=1, out=matrix) - denominators = [query_norm ** 0.5 * 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(query, stored, 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_a = 0.0 - norm_b = 0.0 - for q, s in zip(query, stored): - q = float(q) - s = float(s) - dot += q * s - norm_a += q * q - norm_b += s * s - denominator = (norm_a ** 0.5) * (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("Unknown vector search metric: %s" % metric) diff --git a/paimon-python/pypaimon/tests/batch_vector_raw_scan_test.py b/paimon-python/pypaimon/tests/batch_vector_raw_scan_test.py index 58f26a51c039..dc5c68fdf665 100644 --- a/paimon-python/pypaimon/tests/batch_vector_raw_scan_test.py +++ b/paimon-python/pypaimon/tests/batch_vector_raw_scan_test.py @@ -129,7 +129,7 @@ def test_scoring_finishes_each_batch_before_reading_the_next(self): generators = [] batch_sizes = [] module = 'pypaimon.execution.python.read.search.vector_search_read' - from pypaimon.execution.python.read.search.vector_search_read import _compute_scores + from pypaimon.execution.python.read.search.vector_scoring import _compute_scores def batches(table_read, splits): arrow, generator = original(table_read, splits) diff --git a/paimon-python/pypaimon/tests/batch_vector_streaming_refine_test.py b/paimon-python/pypaimon/tests/batch_vector_streaming_refine_test.py index 7d2b2d977dd5..4e5ea724fb15 100644 --- a/paimon-python/pypaimon/tests/batch_vector_streaming_refine_test.py +++ b/paimon-python/pypaimon/tests/batch_vector_streaming_refine_test.py @@ -23,8 +23,9 @@ import pyarrow as pa import pytest +from pypaimon.execution.python.read.search.vector_scoring import _PreparedQuery, _compute_score from pypaimon.globalindex.vector_search_result import DictBasedScoredIndexResult -from pypaimon.execution.python.read.search.vector_search_read import BatchVectorSearchReadImpl, _compute_score +from pypaimon.execution.python.read.search.vector_search_read import BatchVectorSearchReadImpl from pypaimon.tests.vector_search_filter_test import _StubTable, _field from pypaimon.utils.range import Range @@ -83,8 +84,9 @@ def test_streaming_refine_preserves_per_query_membership_and_scores(metric, layo result = read._maybe_rerank_indexed_results( [scored(ids) for ids in candidate_ids], "ivf-pq", queries, snapshot) for i, candidates in enumerate(candidate_ids): - expected = [(row_id, _compute_score(queries[i], values[row_id], metric)) - for row_id in candidates if values.get(row_id) is not None] + query = _PreparedQuery(queries[i], metric) + expected = [(row_id, _compute_score(query, vector)) for row_id, vector in values.items() + if row_id in candidates and vector is not None] expected = sorted(expected, key=lambda item: (-item[1], item[0]))[:2] assert scores(result[i]) == dict(expected) read._plan_raw_read.assert_called_once_with( @@ -197,9 +199,9 @@ def test_large_arrow_batch_bounds_scoring_blocks(): resource = stream(read, [batch]) from pypaimon.execution.python.read.search.vector_search_read import _iter_arrow_scores - def score_block(vectors, query, metric): + def score_block(vectors, query): assert len(vectors) <= 1024 - return _iter_arrow_scores(vectors, query, metric) + return _iter_arrow_scores(vectors, query) with mock.patch(MODULE + "._iter_arrow_scores", side_effect=score_block): result = read._maybe_rerank_indexed_results( diff --git a/paimon-python/pypaimon/tests/primary_key_global_index_golden_test.py b/paimon-python/pypaimon/tests/primary_key_global_index_golden_test.py index 9cd981f8ce9a..3961ae70e7f7 100644 --- a/paimon-python/pypaimon/tests/primary_key_global_index_golden_test.py +++ b/paimon-python/pypaimon/tests/primary_key_global_index_golden_test.py @@ -22,6 +22,7 @@ import pytest +from pypaimon.execution.python.read.search.vector_scoring import _PreparedQuery, _compute_score from pypaimon.catalog.catalog_factory import CatalogFactory @@ -127,7 +128,6 @@ def test_java_primary_key_full_text_index(catalog): def test_java_primary_key_raw_only_uses_column_metric(catalog, metric, expected_id): from dataclasses import replace from pypaimon.table.source.search_types import PrimaryKeyVectorScanPlan - from pypaimon.execution.python.read.search.vector_search_read import _compute_score table = catalog.get_table("default.test_pk_vector_golden") # Remove legacy aliases so only the documented PK column option is available. @@ -147,7 +147,7 @@ def test_java_primary_key_raw_only_uses_column_metric(catalog, metric, expected_ rows = _read_search_result(table, result) assert rows.column("id").to_pylist() == [expected_id] assert result.positions[0].score == _compute_score( - query, rows.column("embedding")[0].as_py(), metric) + _PreparedQuery(query, metric), rows.column("embedding")[0].as_py()) def test_java_primary_key_vector_refinement_matches_scalar(catalog): diff --git a/paimon-python/pypaimon/tests/read_backend_retention_test.py b/paimon-python/pypaimon/tests/read_backend_retention_test.py index a462c34063d2..30734a5aab7f 100644 --- a/paimon-python/pypaimon/tests/read_backend_retention_test.py +++ b/paimon-python/pypaimon/tests/read_backend_retention_test.py @@ -127,9 +127,9 @@ def test_python_search_dependency_reads_keep_real_rows_in_python(search_table, p with _forbid_native(): if path == 'vector': reader = DataEvolutionVectorRead(table, 2, table.field_dict['embedding'], [0., 0.]) - result = reader._read_raw_arrow([Range(0, 1)], include_filter=False) - assert result.column('_ROW_ID').to_pylist() == [0, 1] - assert result.column('embedding').to_pylist() == [[0., 0.], [1., 0.]] + result = reader._read_raw_search([Range(0, 1)], None, [0., 0.], include_filter=False) + assert result.results().to_list() == [0, 1] + assert [result.score_getter()(i) for i in (0, 1)] == [1.0, 0.5] elif path == 'batch-vector': reader = BatchVectorSearchReadImpl(table, 2, table.field_dict['embedding'], [[0., 0.]]) result = reader._read_raw_batch_search([Range(0, 1)], None)[0] diff --git a/paimon-python/pypaimon/tests/vector_scoring_test.py b/paimon-python/pypaimon/tests/vector_scoring_test.py index 0c091d642faf..2e36407edbb7 100644 --- a/paimon-python/pypaimon/tests/vector_scoring_test.py +++ b/paimon-python/pypaimon/tests/vector_scoring_test.py @@ -16,16 +16,18 @@ # under the License. import unittest -from typing import Iterator, List, Tuple +from pathlib import Path +from typing import Iterator, List, Optional, Tuple from unittest import mock import numpy as np import pyarrow as pa +import pytest +import pypaimon.multimodal as pm +from pypaimon.execution.python.read.search.vector_scoring import _PreparedQuery, _compute_score, _compute_scores from pypaimon.execution.python.read.search.vector_search_read import ( DataEvolutionVectorRead, - _compute_score, - _compute_scores, _iter_arrow_batch_scores, _iter_arrow_scores, _score_block_size, @@ -40,6 +42,12 @@ class VectorScoringTest(unittest.TestCase): + def test_batch_rejects_unknown_metric_after_valid_query(self) -> None: + vectors = pa.array([[1.0]], type=pa.list_(pa.float32(), 1)) + queries = [_PreparedQuery([1.0], metric) for metric in ("l2", "unknown")] + with self.assertRaisesRegex(ValueError, "Unknown vector search metric: unknown"): + list(_iter_arrow_batch_scores(vectors, queries)) + def test_scores_exactly_match_scalar_accumulation(self): rng = np.random.default_rng(42) for dimension in (1, 3, 128, 384): @@ -47,8 +55,9 @@ def test_scores_exactly_match_scalar_accumulation(self): query = rng.standard_normal(dimension).tolist() for metric in ("l2", "cosine", "inner_product"): with self.subTest(dimension=dimension, metric=metric): - expected = [_compute_score(query, row, metric) for row in vectors.tolist()] - actual = _compute_scores(query, vectors.astype(np.float64), metric) + prepared = _PreparedQuery(query, metric) + expected = [_compute_score(prepared, row) for row in vectors.tolist()] + actual = _compute_scores(prepared, vectors.astype(np.float64)) self.assertEqual(expected, actual) self.assertEqual(np.array(expected).tobytes(), np.array(actual).tobytes()) @@ -62,8 +71,9 @@ def test_cancellation_zero_norms_and_close_scores(self): for query, values in cases: vectors = np.array(values, dtype=np.float32) for metric in ("l2", "cosine", "inner_product"): - expected = [_compute_score(query, row, metric) for row in vectors.tolist()] - self.assertEqual(expected, _compute_scores(query, vectors.astype(np.float64), metric)) + prepared = _PreparedQuery(query, metric) + expected = [_compute_score(prepared, row) for row in vectors.tolist()] + self.assertEqual(expected, _compute_scores(prepared, vectors.astype(np.float64))) def test_arrow_slices_chunks_and_list_layouts(self): values = np.random.default_rng(7).standard_normal((1031, 7)).astype(np.float32).tolist() @@ -74,8 +84,9 @@ def test_arrow_slices_chunks_and_list_layouts(self): chunked = pa.chunked_array([sliced.slice(0, 511), sliced.slice(511)]) for data in (sliced, chunked): for metric in ("l2", "cosine", "inner_product"): - expected = [_compute_score(query, row, metric) for row in values[2:1029]] - self.assertEqual(expected, list(_iter_arrow_scores(data, query, metric))) + prepared = _PreparedQuery(query, metric) + expected = [_compute_score(prepared, row) for row in values[2:1029]] + self.assertEqual(expected, list(_iter_arrow_scores(data, prepared))) def test_batch_arrow_scores_exactly_match_scalar_accumulation(self): rng = np.random.default_rng(17) @@ -84,15 +95,14 @@ def test_batch_arrow_scores_exactly_match_scalar_accumulation(self): queries = rng.standard_normal((5, 128)).astype(np.float32).tolist() for metric in ("l2", "cosine", "inner_product"): with self.subTest(metric=metric): + prepared = [_PreparedQuery(q, metric) for q in queries] actual = [[] for unused in queries] - for start, query_index, scores in _iter_arrow_batch_scores( - vectors, queries, metric - ): + for start, query_index, scores in _iter_arrow_batch_scores(vectors, prepared): self.assertEqual(start, len(actual[query_index])) actual[query_index].extend(scores) - for query, scores in zip(queries, actual): + for query, scores in zip(prepared, actual): expected = [ - _compute_score(query, row, metric) + _compute_score(query, row) for row in values.tolist() ] self.assertEqual(expected, scores) @@ -100,22 +110,24 @@ def test_batch_arrow_scores_exactly_match_scalar_accumulation(self): np.array(expected).tobytes(), np.array(scores).tobytes()) def test_null_and_unsupported_data_preserve_scalar_behavior(self): + query = _PreparedQuery([1, 2], "l2") for dtype in (pa.list_(pa.float32()), pa.list_(pa.float64()), pa.list_(pa.int64())): array = pa.array([[1, 2], None, [0, 0]], type=dtype) - self.assertEqual([1.0, None, 1.0 / 6.0], list(_iter_arrow_scores(array, [1, 2], "l2"))) - scores = _iter_arrow_scores(pa.array([None, [1.0]], type=pa.list_(pa.float32())), [1, 2], "l2") + self.assertEqual([1.0, None, 1.0 / 6.0], list(_iter_arrow_scores(array, query))) + scores = _iter_arrow_scores(pa.array([None, [1.0]], type=pa.list_(pa.float32())), query) self.assertIsNone(next(scores)) with self.assertRaisesRegex(ValueError, "dimension mismatch"): next(scores) with self.assertRaisesRegex(ValueError, "dimension mismatch"): - list(_iter_arrow_scores(pa.array([[1.0], [1.0, 2.0]]), [1, 2], "l2")) + list(_iter_arrow_scores(pa.array([[1.0], [1.0, 2.0]]), query)) with self.assertRaises(TypeError): - list(_iter_arrow_scores(pa.array([[1.0, None]], type=pa.list_(pa.float32())), [1, 2], "l2")) + list(_iter_arrow_scores(pa.array([[1.0, None]], type=pa.list_(pa.float32())), query)) values = [[float("nan"), 0], [1, 0]] - scores = list(_iter_arrow_scores(pa.array(values, type=pa.list_(pa.float32())), [1, 0], "l2")) + scores = list(_iter_arrow_scores(pa.array(values, type=pa.list_(pa.float32())), _PreparedQuery([1, 0], "l2"))) self.assertTrue(np.isnan(scores[0])) self.assertEqual(1.0, scores[1]) - self.assertEqual([1.0], list(_iter_arrow_scores(pa.array([[]], type=pa.list_(pa.float32())), [], "l2"))) + empty_row = pa.array([[]], type=pa.list_(pa.float32())) + self.assertEqual([1.0], list(_iter_arrow_scores(empty_row, _PreparedQuery([], "l2")))) def test_batch_null_vectors_preserve_scores_without_scalar_fallback(self): rng = np.random.default_rng(37) @@ -129,12 +141,13 @@ def test_batch_null_vectors_preserve_scores_without_scalar_fallback(self): for vectors in (sliced, chunked): for metric in ("l2", "cosine", "inner_product"): with self.subTest(dtype=dtype, chunked=isinstance(vectors, pa.ChunkedArray), metric=metric): - expected = [[None if row is None else _compute_score(query, row, metric) - for row in values[2:2052]] for query in queries] + prepared = [_PreparedQuery(q, metric) for q in queries] + expected = [[None if row is None else _compute_score(query, row) + for row in values[2:2052]] for query in prepared] actual = [[] for _ in queries] with mock.patch("pypaimon.execution.python.read.search.vector_search_read._compute_score", side_effect=AssertionError("valid rows must use vectorized scoring")): - for start, query_index, scores in _iter_arrow_batch_scores(vectors, queries, metric): + for start, query_index, scores in _iter_arrow_batch_scores(vectors, prepared): self.assertEqual(start, len(actual[query_index])) actual[query_index].extend(scores) self.assertEqual(expected, actual) @@ -143,17 +156,19 @@ def test_batch_all_null_vectors_and_invalid_children_keep_existing_behavior(self queries = [[1.0, 0.0], [0.0, 0.0]] for dtype in (pa.list_(pa.float32()), pa.large_list(pa.float32()), pa.list_(pa.float32(), 2)): for metric in ("l2", "cosine", "inner_product"): - result = list(_iter_arrow_batch_scores(pa.array([None, None], type=dtype), queries, metric)) + prepared = [_PreparedQuery(q, metric) for q in queries] + result = list(_iter_arrow_batch_scores(pa.array([None, None], type=dtype), prepared)) self.assertEqual([(0, 0, [None, None]), (0, 1, [None, None])], result) + prepared = [_PreparedQuery(q, "l2") for q in queries] for rows, exception, message in ( ([None, [1.0]], ValueError, "dimension mismatch"), ([None, [1.0, None]], TypeError, "NoneType")): with self.subTest(rows=rows): vectors = pa.array(rows, type=pa.list_(pa.float32())) with self.assertRaisesRegex(exception, message): - list(_iter_arrow_batch_scores(vectors, queries, "l2")) + list(_iter_arrow_batch_scores(vectors, prepared)) vectors = pa.array([None, [float("nan"), 0.0], [1.0, 0.0]], type=pa.list_(pa.float32())) - scores = list(_iter_arrow_batch_scores(vectors, queries, "l2"))[0][2] + _, _, scores = next(_iter_arrow_batch_scores(vectors, prepared)) self.assertIsNone(scores[0]) self.assertTrue(np.isnan(scores[1])) self.assertEqual(1.0, scores[2]) @@ -164,7 +179,7 @@ def test_batch_null_parent_ignores_invalid_child_values(self): children=[pa.array([float("nan"), None, 1.0, 2.0], type=pa.float32())]) with mock.patch("pypaimon.execution.python.read.search.vector_search_read._compute_score", side_effect=AssertionError("null children must not disable the fast path")): - result = list(_iter_arrow_batch_scores(vectors, [[1.0, 2.0]], "l2")) + result = list(_iter_arrow_batch_scores(vectors, [_PreparedQuery([1.0, 2.0], "l2")])) self.assertEqual([(0, 0, [None, 1.0])], result) def test_raw_search_filters_before_scoring_and_preserves_ties(self): @@ -193,15 +208,53 @@ def new_reader(_splits: List[Split]) -> Tuple[pa.ipc.RecordBatchReader, Iterator def test_refinement_and_block_memory_bound(self): column = _field(1, "embedding", "FLOAT") - reader = DataEvolutionVectorRead(_StubTable([column], []), 10, column, [1, 0]) - values = {i: [float(i % 7), 0] for i in range(2051)} - original = {row_id: vector[:] for row_id, vector in values.items()} - candidates = RoaringBitmap64() - for row_id in values: - candidates.add(row_id) - result = reader._score_raw_vectors(candidates, values, [1, 0], "inner_product", 10) - expected = sorted(values, key=lambda i: (-values[i][0], i))[:10] + reader = DataEvolutionVectorRead(_StubTable([column], []), 10, column, [1]) + values = np.arange(2051, dtype=np.float32) % 7 + values[-1] = 8.0 + original = values.copy() + vectors = pa.FixedSizeListArray.from_arrays(pa.array(values), 1) + batch = pa.record_batch([pa.array(range(len(values))), vectors], names=["_ROW_ID", "embedding"]) + candidates = range(len(values)) + result = reader._score_raw_batches([batch], [1], "inner_product", candidates) + expected = sorted(candidates, key=lambda i: (-original[i], i))[:10] self.assertEqual(sorted(expected), result.results().to_list()) - self.assertEqual(original, values) + np.testing.assert_array_equal(values, original) self.assertLessEqual(_score_block_size([0] * 4096) * 4096, 1 << 20) - self.assertEqual([0.0], _score_rows([[0, 0]], [1, 0], "cosine")) + self.assertEqual([0.0], _score_rows([[0, 0]], _PreparedQuery([1, 0], "cosine"))) + + +@pytest.mark.parametrize("batch", [False, True]) +def test_query_conversion_is_shared_across_scoring_blocks(tmp_path: Path, batch: bool) -> None: + conversions = [] + + class Query(list): + def __array__(self, dtype: Optional[np.dtype] = None, copy: Optional[bool] = None) -> np.ndarray: + conversions.append(tuple(self)) + return np.asarray(list(self), dtype=dtype) + + # Cross the 1024-row score block boundary. Tied hits straddle that boundary. + rows = [[1, 0]] + [[0, 1]] * 1023 + [[1, 0]] + data = pa.table( + {"id": range(len(rows)), "embedding": pa.array(rows, type=pa.list_(pa.float32(), 2))} + ) + table = ( + pm.connect(options={"warehouse": str(tmp_path)}) + .create_table( + "vectors", + data=data, + options={"vector.file.format": "parquet", "read.native.enabled": "false"}, + ) + .raw_table + ) + queries = [Query([1.0, 0.0]), Query([0.0, 1.0])] + if batch: + builder = table.new_batch_vector_search_builder().with_query_vectors(queries) + builder.with_vector_column("embedding").with_limit(2).with_option("metric", "cosine") + results = builder.execute_batch_local() + else: + builder = table.new_vector_search_builder().with_query_vector(queries[0]) + builder.with_vector_column("embedding").with_limit(2).with_option("metric", "cosine") + results = [builder.execute_local()] + assert [list(result.results()) for result in results] == [[0, 1024], [1, 2]][: len(results)] + assert all(result.score_getter()(i) == 1.0 for result in results for i in result.results()) + assert sorted(conversions) == sorted(tuple(q) for q in queries[: len(results)]) diff --git a/paimon-python/pypaimon/tests/vector_search_filter_test.py b/paimon-python/pypaimon/tests/vector_search_filter_test.py index 26024e16b572..3ff695980a2b 100644 --- a/paimon-python/pypaimon/tests/vector_search_filter_test.py +++ b/paimon-python/pypaimon/tests/vector_search_filter_test.py @@ -1826,10 +1826,10 @@ def test_raw_vector_read_passes_ranges_without_bitmap(self): GlobalIndexResult, "from_ranges", side_effect=AssertionError("row ranges entered a bitmap")): - result = reader._read_raw_arrow(ranges, include_filter=True) + result = reader._read_raw_search(ranges, None, reader._query_vector) self.assertEqual(ranges, calls["global_index_ranges"]) - self.assertEqual(1, result.num_rows) + self.assertEqual([10], result.results().to_list()) def test_scan_threads_builder_options_to_raw_split_index_type(self): from pypaimon.table.source.vector_search_split import RawVectorSearchSplit diff --git a/paimon-python/pypaimon/tests/vector_search_streaming_test.py b/paimon-python/pypaimon/tests/vector_search_streaming_test.py index 3aabdfc03f55..dabd2dc0696d 100644 --- a/paimon-python/pypaimon/tests/vector_search_streaming_test.py +++ b/paimon-python/pypaimon/tests/vector_search_streaming_test.py @@ -26,6 +26,7 @@ import pyarrow as pa import pytest +from pypaimon.execution.python.read.search.vector_scoring import _PreparedQuery from pypaimon.execution.python.read.search import vector_search_read as search from pypaimon.multimodal.query import VectorQuery from pypaimon.read.split import Split @@ -121,12 +122,12 @@ def fast() -> Iterator[pa.RecordBatch]: assert scored[i - 2].is_set(), "Read more than one batch ahead" yield batch(i, float(i)) - def score(vectors: pa.Array, query: List[float], metric: str) -> Iterator[Optional[float]]: + def score(vectors: pa.Array, query: _PreparedQuery) -> Iterator[Optional[float]]: assert threading.get_ident() == caller value = int(vectors[0].as_py()[0]) if value < len(scored): scored[value].set() - yield from original(vectors, query, metric) + yield from original(vectors, query) read = planned_read(slow(), fast()) with mock.patch.object(search, "_iter_arrow_scores", score):