vigyasharma commented on code in PR #14009: URL: https://github.com/apache/lucene/pull/14009#discussion_r2162100578
########## lucene/core/src/java/org/apache/lucene/search/RescoreTopNQuery.java: ########## @@ -0,0 +1,128 @@ +/* + * 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. + */ +package org.apache.lucene.search; + +import java.io.IOException; +import java.util.Objects; +import org.apache.lucene.index.IndexReader; + +/** + * A Query that re-scores another Query with a DoubleValueSource function and cut-off the results at + * top N. + * + * @lucene.experimental + */ +public class RescoreTopNQuery extends Query { + + private final int n; + private final Query query; + private final DoubleValuesSource valuesSource; + + /** + * Execute the inner Query, re-score using a customizable DoubleValueSource and trim down the + * result to k + * + * @param query the query to execute as initial phase + * @param valuesSource the double value source to re-score + * @param n the number of documents to find + * @throws IllegalArgumentException if <code>n</code> is less than 1 + */ + public RescoreTopNQuery(Query query, DoubleValuesSource valuesSource, int n) { + if (n < 1) { + throw new IllegalArgumentException("n must be >= 1"); + } + this.query = query; + this.valuesSource = valuesSource; + this.n = n; + } + + @Override + public Query rewrite(IndexSearcher indexSearcher) throws IOException { + DoubleValuesSource rewrittenValueSource = valuesSource.rewrite(indexSearcher); + IndexReader reader = indexSearcher.getIndexReader(); + Query rewritten = indexSearcher.rewrite(query); + Weight weight = indexSearcher.createWeight(rewritten, ScoreMode.COMPLETE_NO_SCORES, 1.0f); + HitQueue queue = new HitQueue(n, false); + for (var leaf : reader.leaves()) { + Scorer innerScorer = weight.scorer(leaf); + if (innerScorer == null) { + continue; + } + DoubleValues rescores = rewrittenValueSource.getValues(leaf, getDoubleValues(innerScorer)); + DocIdSetIterator iterator = innerScorer.iterator(); + while (iterator.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { + int docId = iterator.docID(); + if (rescores.advanceExact(docId)) { + double v = rescores.doubleValue(); + queue.insertWithOverflow(new ScoreDoc(leaf.docBase + docId, (float) v)); + } else { + queue.insertWithOverflow(new ScoreDoc(leaf.docBase + docId, 0f)); + } + } + } + int i = 0; + ScoreDoc[] scoreDocs = new ScoreDoc[queue.size()]; + for (ScoreDoc topDoc : queue) { + scoreDocs[i++] = topDoc; + } + TopDocs topDocs = + new TopDocs(new TotalHits(queue.size(), TotalHits.Relation.EQUAL_TO), scoreDocs); Review Comment: Instead of setting this to configured `n`, should we retain the total no. of hits and relation from original query? ########## lucene/core/src/java/org/apache/lucene/search/RescoreTopNQuery.java: ########## @@ -0,0 +1,128 @@ +/* + * 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. + */ +package org.apache.lucene.search; + +import java.io.IOException; +import java.util.Objects; +import org.apache.lucene.index.IndexReader; + +/** + * A Query that re-scores another Query with a DoubleValueSource function and cut-off the results at + * top N. + * + * @lucene.experimental + */ +public class RescoreTopNQuery extends Query { + + private final int n; + private final Query query; + private final DoubleValuesSource valuesSource; + + /** Review Comment: This query will override the `rewrite` phase of any provided query to gather all hits, find top N based on provided DoubleValuesSource, and return a DocAndScoreQuery. This only applies to vector search queries right now, but in spirit is generic to all approx search queries (not sure what other candidates might use it)? I think we should call this out in the query doc string, to disambiguate what this query does v/s other rescoring methods like `Rescorer`s and `FunctionScoreQuery`. ########## lucene/core/src/java/org/apache/lucene/search/RescoreTopNQuery.java: ########## @@ -0,0 +1,128 @@ +/* + * 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. + */ +package org.apache.lucene.search; + +import java.io.IOException; +import java.util.Objects; +import org.apache.lucene.index.IndexReader; + +/** + * A Query that re-scores another Query with a DoubleValueSource function and cut-off the results at + * top N. + * + * @lucene.experimental + */ +public class RescoreTopNQuery extends Query { + + private final int n; + private final Query query; + private final DoubleValuesSource valuesSource; + + /** + * Execute the inner Query, re-score using a customizable DoubleValueSource and trim down the + * result to k + * + * @param query the query to execute as initial phase + * @param valuesSource the double value source to re-score + * @param n the number of documents to find + * @throws IllegalArgumentException if <code>n</code> is less than 1 + */ + public RescoreTopNQuery(Query query, DoubleValuesSource valuesSource, int n) { + if (n < 1) { + throw new IllegalArgumentException("n must be >= 1"); + } + this.query = query; + this.valuesSource = valuesSource; + this.n = n; + } + + @Override + public Query rewrite(IndexSearcher indexSearcher) throws IOException { + DoubleValuesSource rewrittenValueSource = valuesSource.rewrite(indexSearcher); + IndexReader reader = indexSearcher.getIndexReader(); + Query rewritten = indexSearcher.rewrite(query); + Weight weight = indexSearcher.createWeight(rewritten, ScoreMode.COMPLETE_NO_SCORES, 1.0f); + HitQueue queue = new HitQueue(n, false); + for (var leaf : reader.leaves()) { + Scorer innerScorer = weight.scorer(leaf); + if (innerScorer == null) { + continue; + } + DoubleValues rescores = rewrittenValueSource.getValues(leaf, getDoubleValues(innerScorer)); + DocIdSetIterator iterator = innerScorer.iterator(); + while (iterator.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { + int docId = iterator.docID(); + if (rescores.advanceExact(docId)) { + double v = rescores.doubleValue(); + queue.insertWithOverflow(new ScoreDoc(leaf.docBase + docId, (float) v)); + } else { + queue.insertWithOverflow(new ScoreDoc(leaf.docBase + docId, 0f)); + } + } + } + int i = 0; + ScoreDoc[] scoreDocs = new ScoreDoc[queue.size()]; + for (ScoreDoc topDoc : queue) { + scoreDocs[i++] = topDoc; + } + TopDocs topDocs = + new TopDocs(new TotalHits(queue.size(), TotalHits.Relation.EQUAL_TO), scoreDocs); + return KnnFloatVectorQuery.createRewrittenQuery(reader, topDocs, 0); Review Comment: Hmm, so while this is called `KnnFloatVectorQuery.createRewrittenQuery`, it isn't specific to vector queries, right? It just creates a new `DocAndScoreQuery`. Should we rename the method (or create a different one) to fit better with this generic query? ########## lucene/core/src/test/org/apache/lucene/search/TestRescoreTopNQuery.java: ########## @@ -0,0 +1,140 @@ +/* + * 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. + */ +package org.apache.lucene.search; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.IntField; +import org.apache.lucene.document.KnnFloatVectorField; +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.VectorSimilarityFunction; +import org.apache.lucene.store.ByteBuffersDirectory; +import org.apache.lucene.store.Directory; +import org.apache.lucene.tests.util.LuceneTestCase; +import org.apache.lucene.tests.util.TestUtil; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TestRescoreTopNQuery extends LuceneTestCase { + + private static final String FIELD = "vector"; + private static final String RESCORE_FIELD = "vector-rescore"; + private static final VectorSimilarityFunction VECTOR_SIMILARITY_FUNCTION = + VectorSimilarityFunction.COSINE; + private static final int NUM_VECTORS = 1000; + private static final int VECTOR_DIMENSION = 128; + + private Directory directory; + private IndexWriterConfig config; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + directory = new ByteBuffersDirectory(); + + // Set up the IndexWriterConfig to use quantized vector storage + config = new IndexWriterConfig(); + config.setCodec(TestUtil.alwaysKnnVectorsFormat(new Lucene99HnswVectorsFormat())); + } + + @Test + public void testInvalidN() { + expectThrows( + IllegalArgumentException.class, + () -> + new RescoreTopNQuery( + new TermQuery(new Term("test")), DoubleValuesSource.constant(0), 0)); + } + + @Test + public void testRescoreField() throws Exception { Review Comment: Can we also add a test for when the document is missing from double values source? I think we should get a `0f` score based on your query? ########## lucene/core/src/test/org/apache/lucene/search/TestRescoreTopNQuery.java: ########## @@ -0,0 +1,140 @@ +/* + * 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. + */ +package org.apache.lucene.search; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.IntField; +import org.apache.lucene.document.KnnFloatVectorField; +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.VectorSimilarityFunction; +import org.apache.lucene.store.ByteBuffersDirectory; +import org.apache.lucene.store.Directory; +import org.apache.lucene.tests.util.LuceneTestCase; +import org.apache.lucene.tests.util.TestUtil; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TestRescoreTopNQuery extends LuceneTestCase { + + private static final String FIELD = "vector"; + private static final String RESCORE_FIELD = "vector-rescore"; + private static final VectorSimilarityFunction VECTOR_SIMILARITY_FUNCTION = + VectorSimilarityFunction.COSINE; + private static final int NUM_VECTORS = 1000; + private static final int VECTOR_DIMENSION = 128; + + private Directory directory; + private IndexWriterConfig config; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + directory = new ByteBuffersDirectory(); + + // Set up the IndexWriterConfig to use quantized vector storage + config = new IndexWriterConfig(); + config.setCodec(TestUtil.alwaysKnnVectorsFormat(new Lucene99HnswVectorsFormat())); + } + + @Test + public void testInvalidN() { + expectThrows( + IllegalArgumentException.class, + () -> + new RescoreTopNQuery( + new TermQuery(new Term("test")), DoubleValuesSource.constant(0), 0)); + } + + @Test + public void testRescoreField() throws Exception { + Map<Integer, float[]> vectors = new HashMap<>(); + + Random random = random(); + + int numVectors = atLeast(NUM_VECTORS); + int numSegments = random.nextInt(2, 10); + + // Step 1: Index random vectors in quantized format + try (IndexWriter writer = new IndexWriter(directory, config)) { + for (int j = 0; j < numSegments; j++) { + for (int i = 0; i < numVectors; i++) { + float[] vector = randomFloatVector(VECTOR_DIMENSION, random); + float[] rescoreVector = randomFloatVector(VECTOR_DIMENSION, random); + Document doc = new Document(); + int id = j * numVectors + i; + doc.add(new IntField("id", id, Field.Store.YES)); + doc.add(new KnnFloatVectorField(FIELD, vector, VECTOR_SIMILARITY_FUNCTION)); + doc.add( + new KnnFloatVectorField(RESCORE_FIELD, rescoreVector, VECTOR_SIMILARITY_FUNCTION)); + writer.addDocument(doc); + vectors.put(id, rescoreVector); + + writer.flush(); + } + } + } + + // Step 2: Run TwoPhaseKnnVectorQuery with a random target vector + try (IndexReader reader = DirectoryReader.open(directory)) { + IndexSearcher searcher = new IndexSearcher(reader); + float[] targetVector = randomFloatVector(VECTOR_DIMENSION, random); + int k = 10; + double oversample = random.nextFloat(1.5f, 3.0f); + + FloatVectorSimilarityValuesSource valueSource = Review Comment: Can we test it against the [FullPrecisionValuesSource](https://github.com/apache/lucene/blob/main/lucene/core/src/java/org/apache/lucene/search/FullPrecisionFloatVectorSimilarityValuesSource.java) instead? I understand this predates us merging the FP values source but let's update it now? Otherwise this is essentially a no-op, the KnnFloatVectorQuery was already scored by quantized scores, and we used the same scores again. ########## lucene/core/src/java/org/apache/lucene/search/RescoreTopNQuery.java: ########## @@ -0,0 +1,128 @@ +/* + * 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. + */ +package org.apache.lucene.search; + +import java.io.IOException; +import java.util.Objects; +import org.apache.lucene.index.IndexReader; + +/** + * A Query that re-scores another Query with a DoubleValueSource function and cut-off the results at + * top N. + * + * @lucene.experimental + */ +public class RescoreTopNQuery extends Query { Review Comment: How about we add a static function to create a RescoreTopNQuery for full precision vector rescoring? It would accept the relevant args, internally create a [FullPrecisionFloatVectorSimilarityValuesSource](https://github.com/apache/lucene/blob/main/lucene/core/src/java/org/apache/lucene/search/FullPrecisionFloatVectorSimilarityValuesSource.java), and use it to create the `RescoreTopNQuery`. -- 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: issues-unsubscr...@lucene.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@lucene.apache.org For additional commands, e-mail: issues-h...@lucene.apache.org