Jackie-Jiang commented on code in PR #20073:
URL: https://github.com/apache/pinot/pull/20073#discussion_r4534107524
##########
pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/VectorTransformFunctions.java:
##########
@@ -48,11 +66,94 @@ public void init(List<TransformFunction> arguments,
Map<String, ColumnContext> c
}
}
+ @Override
+ public void init(List<TransformFunction> arguments, Map<String,
ColumnContext> columnContextMap,
+ QueryContext queryContext) {
+ super.init(arguments, columnContextMap, queryContext);
+ if (_leftTransformFunction instanceof IdentifierTransformFunction
+ && _rightTransformFunction instanceof ArrayLiteralTransformFunction)
{
+ _distancesRequest =
requestIndexDistances((IdentifierTransformFunction) _leftTransformFunction,
+ (ArrayLiteralTransformFunction) _rightTransformFunction,
columnContextMap, queryContext);
+ } else if (_rightTransformFunction instanceof IdentifierTransformFunction
+ && _leftTransformFunction instanceof ArrayLiteralTransformFunction) {
+ _distancesRequest =
requestIndexDistances((IdentifierTransformFunction) _rightTransformFunction,
+ (ArrayLiteralTransformFunction) _leftTransformFunction,
columnContextMap, queryContext);
+ }
+ }
+
+ /// Asks a `VECTOR_SIMILARITY` filter on the column and vector to hand
over the distances of its search, when the
+ /// column has a COSINE vector index (whose distances are cosine
distances).
+ @Nullable
+ private static VectorSearchDistances.Request
requestIndexDistances(IdentifierTransformFunction column,
+ ArrayLiteralTransformFunction vector, Map<String, ColumnContext>
columnContextMap, QueryContext queryContext) {
+ if
(QueryOptionsUtils.isVectorExactDistance(queryContext.getQueryOptions())) {
+ return null;
+ }
+ ColumnContext columnContext =
columnContextMap.get(column.getColumnName());
+ DataSource dataSource = columnContext != null ?
columnContext.getDataSource() : null;
+ if (dataSource == null) {
+ return null;
+ }
+ VectorIndexReader vectorIndexReader = dataSource.getVectorIndex();
+ VectorIndexConfig vectorIndexConfig = dataSource.getVectorIndexConfig();
+ if (vectorIndexReader == null || vectorIndexConfig == null
+ || vectorIndexConfig.getVectorDistanceFunction() !=
VectorIndexConfig.VectorDistanceFunction.COSINE) {
+ return null;
+ }
+ float[] queryVector = toFloatArray(vector);
+ return queryVector != null ?
VectorSearchDistances.of(queryContext).request(vectorIndexReader, queryVector)
+ : null;
+ }
+
+ /// Float array literals are rare in SQL (`ARRAY[0.1, ...]` parses as
DOUBLE, `ARRAY[1, 0]` as INT); narrow every
+ /// numeric array like VECTOR_SIMILARITY does, so the same vector literal
matches the filter's search.
+ @Nullable
+ private static float[] toFloatArray(ArrayLiteralTransformFunction literal)
{
+ float[] floats = literal.getFloatArrayLiteral();
+ if (floats != null) {
+ return floats;
+ }
+ double[] doubles = literal.getDoubleArrayLiteral();
+ int[] ints = literal.getIntArrayLiteral();
+ long[] longs = literal.getLongArrayLiteral();
+ int length = doubles != null ? doubles.length : ints != null ?
ints.length : longs != null ? longs.length : -1;
+ if (length < 0) {
+ return null;
+ }
+ floats = new float[length];
+ for (int i = 0; i < length; i++) {
+ floats[i] = doubles != null ? (float) doubles[i] : ints != null ?
ints[i] : (float) longs[i];
+ }
+ return floats;
+ }
+
@Override
public String getName() {
return FUNCTION_NAME;
}
+ @Override
+ public double[] transformToDoubleValuesSV(ValueBlock valueBlock) {
+ Int2FloatMap distances = _distancesRequest != null ?
_distancesRequest.getDistances() : null;
+ int[] docIds = valueBlock.getDocIds();
+ if (distances != null && docIds != null) {
+ int length = valueBlock.getNumDocs();
+ initDoubleValuesSV(length);
+ boolean allServed = true;
+ for (int i = 0; i < length; i++) {
+ if (!distances.containsKey(docIds[i])) {
+ allServed = false;
+ break;
+ }
+ _doubleValuesSV[i] = distances.get(docIds[i]);
Review Comment:
**Correctness: fall back for non-finite cached distances.** This assignment
bypasses `computeDistance()` and therefore the optional default-value argument.
With JVM assertions disabled, a COSINE index containing one nonzero vector can
return a NaN score for a finite zero query. For example:
```sql
SELECT cosineDistance(embedding, ARRAY[0, 0], 7)
FROM t
WHERE VECTOR_SIMILARITY(embedding, ARRAY[0, 0], 1)
```
The existing scalar path returns `7`; the new fast path returns NaN. This
also affects nonzero tiny vectors: indexed `[0, 1e-30]` and query `[1e-30, 0]`
produce NaN through Lucene's float-norm underflow, while the existing scalar
implementation returns `1`.
Please fall back to the existing computation when a cached distance is
non-finite, and cover both cases. Replacing NaN directly with `_defaultValue`
would still mishandle the nonzero underflow case.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/HnswVectorIndexReader.java:
##########
@@ -64,11 +66,16 @@ public class HnswVectorIndexReader implements
FilterAwareVectorIndexReader, EfSe
private final ThreadLocal<Integer> _efSearchOverride = new ThreadLocal<>();
private final ThreadLocal<Boolean> _useRelativeDistanceOverride = new
ThreadLocal<>();
private final ThreadLocal<Boolean> _useBoundedQueueOverride = new
ThreadLocal<>();
+ /// Lucene returns cosine similarity scores, which convert exactly to `1 -
cosine similarity`; other functions use
+ /// scaled scores, so distances are only returned for COSINE.
+ private final boolean _returnsDistances;
/// File-backed constructor: opens a [FSDirectory] from the Lucene HNSW
index directory
/// found under `indexDir`.
public HnswVectorIndexReader(String column, File indexDir, int numDocs,
VectorIndexConfig config) {
_column = column;
+ _returnsDistances = config != null
+ && config.getVectorDistanceFunction() ==
VectorIndexConfig.VectorDistanceFunction.COSINE;
Review Comment:
**Correctness: determine the metric from the loaded index.** The current
table config can differ from the metric persisted in Lucene. Changing an
existing HNSW column from `EUCLIDEAN` to `COSINE` and reloading does not
rebuild the index: `VectorIndexHandler.needUpdateIndices()` checks
backend/storage changes and compatibility, but not the distance function. Both
this reader and the transform then see the updated config, enabling conversion
of Euclidean scores as cosine scores.
For stored `[2, 0]` and query `[1, 0]`, Lucene's Euclidean score is `0.5`,
so the new conversion returns `1` as `cosineDistance`; the previous projection
returns `0`.
Please inspect the loaded Lucene field's `getVectorSimilarityFunction()` and
only expose cosine distances when that actual metric is COSINE, retaining the
scalar fallback otherwise. The buffer-backed constructor needs the same check.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]