Apache Lucene open-source search software
Support for Re-Ranking Queries using Late Interaction Model Multi-Vectors. (#14729)
Vigya Sharmad9618080b340
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 3bc3c8ca27c..de42da723f4 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -126,6 +126,8 @@ New Features* GITHUB#14009: Add a new Query that can rescore other Query based on a generic DoubleValueSourceand trim the results down to top N (Anh Dung Bui)+* GITHUB#14729: Support for Re-Ranking Queries using Late Interaction Model Multi-Vectors. (Vigya Sharma, Jim Ferenczi)+Improvements---------------------* GITHUB#14458: Add an IndexDeletion policy that retains the last N commits. (Owais Kazi)diff --git a/lucene/core/src/java/org/apache/lucene/document/LateInteractionField.java b/lucene/core/src/java/org/apache/lucene/document/LateInteractionField.javanew file mode 100644index 00000000000..d6d9d75a88a--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/LateInteractionField.java@@ -0,0 +1,138 @@+/*+ * 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.document;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.nio.FloatBuffer;+import org.apache.lucene.util.BytesRef;++/**+ * A field for storing multi-vector values for late interaction models.+ *+ * <p>The value is stored as a binary payload, and can be retrieved using {@link+ * LateInteractionField#decode(BytesRef)}. Multi-vectors are expected to have the same dimension for+ * each composing token vector. This is stored along with the token vectors in the first 4 bytes of+ * the payload.+ *+ * <p>Note: This field does not ensure consistency in token vector dimensions for values across+ * documents.+ */+public class LateInteractionField extends BinaryDocValuesField {++ /**+ * Creates a new {@link LateInteractionField} from the provided multi-vector matrix.+ *+ * @param name field name+ * @param value multi-vector value+ */+ public LateInteractionField(String name, float[][] value) {+ super(name, encode(value));+ }++ /**+ * Set multi-vector value for the field.+ *+ * <p>Value should not be null or empty. Composing token vectors for provided multi-vector value+ * should have the same dimension.+ */+ public void setValue(float[][] value) {+ this.fieldsData = encode(value);+ }++ /** Returns the multi-vector value stored in this field */+ public float[][] getValue() {+ return decode((BytesRef) fieldsData);+ }++ /**+ * Encodes provided multi-vector matrix into a {@link BytesRef} that can be stored in the {@link+ * LateInteractionField}.+ *+ * <p>Composing token vectors for the multi-vector are expected to have the same dimension, which+ * is stored along with the token vectors in the first 4 bytes of the payload. Use {@link+ * LateInteractionField#decode(BytesRef)} to retrieve the multi-vector.+ *+ * @param value Multi-Vector to encode+ * @return BytesRef representation for provided multi-vector+ */+ public static BytesRef encode(float[][] value) {+ if (value == null || value.length == 0) {+ throw new IllegalArgumentException("Value should not be null or empty");+ }+ if (value[0] == null || value[0].length == 0) {+ throw new IllegalArgumentException("Composing token vectors should not be null or empty");+ }+ final int tokenVectorDimension = value[0].length;+ final ByteBuffer buffer =+ ByteBuffer.allocate(Integer.BYTES + value.length * tokenVectorDimension * Float.BYTES)+ .order(ByteOrder.LITTLE_ENDIAN);+ // TODO: Should we store dimension in FieldType to ensure consistency across all documents?+ buffer.putInt(tokenVectorDimension);+ FloatBuffer floatBuffer = buffer.asFloatBuffer();+ for (int i = 0; i < value.length; i++) {+ if (value[i].length != tokenVectorDimension) {+ throw new IllegalArgumentException(+ "Composing token vectors should have the same dimension. "+ + "Mismatching dimensions detected between token[0] and token["+ + i+ + "], "+ + value[0].length+ + " != "+ + value[i].length);+ }+ floatBuffer.put(value[i]);+ }+ return new BytesRef(buffer.array());+ }++ /**+ * Decodes provided {@link BytesRef} into a multi-vector matrix.+ *+ * <p>The token vectors are expected to have the same dimension, which is stored along with the+ * token vectors in the first 4 bytes of the payload. Meant to be used as a counterpart to {@link+ * LateInteractionField#encode(float[][])}+ *+ * @param payload to decode into multi-vector value+ * @return decoded multi-vector value+ */+ public static float[][] decode(BytesRef payload) {+ final ByteBuffer buffer = ByteBuffer.wrap(payload.bytes, payload.offset, payload.length);+ buffer.order(ByteOrder.LITTLE_ENDIAN);+ final int tokenVectorDimension = buffer.getInt();+ int numVectors = (payload.length - Integer.BYTES) / (tokenVectorDimension * Float.BYTES);+ if (numVectors * tokenVectorDimension * Float.BYTES + Integer.BYTES != payload.length) {+ throw new IllegalArgumentException(+ "Provided payload does not appear to have been encoded via LateInteractionField.encode. "+ + "Payload length should be equal to 4 + numVectors * tokenVectorDimension, "+ + "got "+ + payload.length+ + " != 4 + "+ + numVectors+ + " * "+ + tokenVectorDimension);+ }+ var floatBuffer = buffer.asFloatBuffer();+ float[][] value = new float[numVectors][];+ for (int i = 0; i < numVectors; i++) {+ value[i] = new float[tokenVectorDimension];+ floatBuffer.get(value[i]);+ }+ return value;+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/search/LateInteractionFloatValuesSource.java b/lucene/core/src/java/org/apache/lucene/search/LateInteractionFloatValuesSource.javanew file mode 100644index 00000000000..3bf3bcb3d0b--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/search/LateInteractionFloatValuesSource.java@@ -0,0 +1,183 @@+/*+ * 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.Arrays;+import java.util.Objects;+import org.apache.lucene.document.LateInteractionField;+import org.apache.lucene.index.BinaryDocValues;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.VectorSimilarityFunction;++/**+ * A {@link DoubleValuesSource} that scores documents using similarity between a multi-vector query,+ * and indexed document multi-vectors.+ *+ * <p>This is useful re-ranking query results using late interaction models, where documents and+ * queries are represented as multi-vectors of composing token vectors. Document vectors are indexed+ * using {@link org.apache.lucene.document.LateInteractionField}.+ *+ * @lucene.experimental+ */+public class LateInteractionFloatValuesSource extends DoubleValuesSource {++ private final String fieldName;+ private final float[][] queryVector;+ private final VectorSimilarityFunction vectorSimilarityFunction;+ private final MultiVectorSimilarity scoreFunction;++ public LateInteractionFloatValuesSource(String fieldName, float[][] queryVector) {+ this(fieldName, queryVector, VectorSimilarityFunction.COSINE, ScoreFunction.SUM_MAX_SIM);+ }++ public LateInteractionFloatValuesSource(+ String fieldName, float[][] queryVector, VectorSimilarityFunction vectorSimilarityFunction) {+ this(fieldName, queryVector, vectorSimilarityFunction, ScoreFunction.SUM_MAX_SIM);+ }++ public LateInteractionFloatValuesSource(+ String fieldName,+ float[][] queryVector,+ VectorSimilarityFunction vectorSimilarityFunction,+ MultiVectorSimilarity scoreFunction) {+ this.fieldName = Objects.requireNonNull(fieldName);+ this.queryVector = validateQueryVector(queryVector);+ this.vectorSimilarityFunction = Objects.requireNonNull(vectorSimilarityFunction);+ this.scoreFunction = Objects.requireNonNull(scoreFunction);+ }++ private float[][] validateQueryVector(float[][] queryVector) {+ if (queryVector == null || queryVector.length == 0) {+ throw new IllegalArgumentException("queryVector must not be null or empty");+ }+ if (queryVector[0] == null || queryVector[0].length == 0) {+ throw new IllegalArgumentException(+ "composing token vectors in provided query vector should not be null or empty");+ }+ for (int i = 1; i < queryVector.length; i++) {+ if (queryVector[i] == null || queryVector[i].length != queryVector[0].length) {+ throw new IllegalArgumentException(+ "all composing token vectors in provided query vector should have the same length");+ }+ }+ return queryVector;+ }++ @Override+ public DoubleValues getValues(LeafReaderContext ctx, DoubleValues scores) throws IOException {+ BinaryDocValues values = ctx.reader().getBinaryDocValues(fieldName);+ if (values == null) {+ return DoubleValues.EMPTY;+ }++ return new DoubleValues() {+ @Override+ public double doubleValue() throws IOException {+ return scoreFunction.compare(+ queryVector,+ LateInteractionField.decode(values.binaryValue()),+ vectorSimilarityFunction);+ }++ @Override+ public boolean advanceExact(int doc) throws IOException {+ return values.advanceExact(doc);+ }+ };+ }++ @Override+ public boolean needsScores() {+ return false;+ }++ @Override+ public DoubleValuesSource rewrite(IndexSearcher reader) throws IOException {+ return this;+ }++ @Override+ public int hashCode() {+ return Objects.hash(+ fieldName, Arrays.deepHashCode(queryVector), vectorSimilarityFunction, scoreFunction);+ }++ @Override+ public boolean equals(Object obj) {+ if (this == obj) return true;+ if (obj == null || getClass() != obj.getClass()) return false;+ LateInteractionFloatValuesSource other = (LateInteractionFloatValuesSource) obj;+ return Objects.equals(fieldName, other.fieldName)+ && vectorSimilarityFunction == other.vectorSimilarityFunction+ && scoreFunction == other.scoreFunction+ && Arrays.deepEquals(queryVector, other.queryVector);+ }++ @Override+ public String toString() {+ return "LateInteractionFloatValuesSource(fieldName="+ + fieldName+ + " similarityFunction="+ + vectorSimilarityFunction+ + " scoreFunction="+ + scoreFunction.getClass()+ + " queryVector="+ + Arrays.deepToString(queryVector)+ + ")";+ }++ @Override+ public boolean isCacheable(LeafReaderContext ctx) {+ return true;+ }++ /** Defines the function to compute similarity score between query and document multi-vectors */+ public enum ScoreFunction implements MultiVectorSimilarity {++ /** Computes the sum of max similarity between query and document vectors */+ SUM_MAX_SIM {+ @Override+ public float compare(+ float[][] queryVector,+ float[][] docVector,+ VectorSimilarityFunction vectorSimilarityFunction) {+ if (docVector.length == 0) {+ return Float.MIN_VALUE;+ }+ float result = 0f;+ for (float[] q : queryVector) {+ float maxSim = Float.MIN_VALUE;+ for (float[] d : docVector) {+ if (q.length != d.length) {+ throw new IllegalArgumentException(+ "Provided multi-vectors are incompatible. "+ + "Their composing token vectors should have the same dimension, got "+ + q.length+ + " != "+ + d.length);+ }+ maxSim = Float.max(maxSim, vectorSimilarityFunction.compare(q, d));+ }+ result += maxSim;+ }+ return result;+ }+ };+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/search/LateInteractionRescorer.java b/lucene/core/src/java/org/apache/lucene/search/LateInteractionRescorer.javanew file mode 100644index 00000000000..921614e9d62--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/search/LateInteractionRescorer.java@@ -0,0 +1,90 @@+/*+ * 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 org.apache.lucene.index.VectorSimilarityFunction;++/**+ * Rescores top N results from a first pass query using a {@link LateInteractionFloatValuesSource}+ *+ * <p>Typically, you run a low-cost first pass query to collect results from across the index, then+ * use this rescorer to rerank top N hits using multi-vectors, usually from a late interaction+ * model. Multi-vectors should be indexed in the {@link+ * org.apache.lucene.document.LateInteractionField} provided to rescorer.+ *+ * @lucene.experimental+ */+public class LateInteractionRescorer extends DoubleValuesSourceRescorer {++ public LateInteractionRescorer(LateInteractionFloatValuesSource valuesSource) {+ super(valuesSource);+ }++ /** Creates a LateInteractionRescorer for provided query vector. */+ public static LateInteractionRescorer create(String fieldName, float[][] queryVector) {+ return create(fieldName, queryVector, VectorSimilarityFunction.COSINE);+ }++ /**+ * Creates a LateInteractionRescorer for provided query vector.+ *+ * <p>Top N results from a first pass query are rescored based on the similarity between {@code+ * queryVector} and the multi-vector indexed in {@code fieldName}. If document does not have a+ * value indexed in {@code fieldName}, a 0f score is assigned.+ *+ * @param fieldName the {@link org.apache.lucene.document.LateInteractionField} used for+ * reranking.+ * @param queryVector query multi-vector to use for similarity comparison+ * @param vectorSimilarityFunction function used for vector similarity comparisons+ */+ public static LateInteractionRescorer create(+ String fieldName, float[][] queryVector, VectorSimilarityFunction vectorSimilarityFunction) {+ final LateInteractionFloatValuesSource valuesSource =+ new LateInteractionFloatValuesSource(fieldName, queryVector, vectorSimilarityFunction);+ return new LateInteractionRescorer(valuesSource);+ }++ @Override+ protected float combine(float firstPassScore, boolean valuePresent, double sourceValue) {+ return valuePresent ? (float) sourceValue : 0f;+ }++ /**+ * Creates a LateInteractionRescorer for provided query vector.+ *+ * <p>Top N results from a first pass query are rescored based on the similarity between {@code+ * queryVector} and the multi-vector indexed in {@code fieldName}. Falls back to score from the+ * first pass query if a document does not have a value indexed in {@code fieldName}.+ *+ * @param fieldName the {@link org.apache.lucene.document.LateInteractionField} used for+ * reranking.+ * @param queryVector query multi-vector to use for similarity comparison+ * @param vectorSimilarityFunction function used for vector similarity comparisons.+ */+ public static LateInteractionRescorer withFallbackToFirstPassScore(+ String fieldName, float[][] queryVector, VectorSimilarityFunction vectorSimilarityFunction) {+ final LateInteractionFloatValuesSource valuesSource =+ new LateInteractionFloatValuesSource(fieldName, queryVector, vectorSimilarityFunction);+ return new LateInteractionRescorer(valuesSource) {+ @Override+ protected float combine(float firstPassScore, boolean valuePresent, double sourceValue) {+ return valuePresent ? (float) sourceValue : firstPassScore;+ }+ };+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiVectorSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/MultiVectorSimilarity.javanew file mode 100644index 00000000000..2816f97b14a--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/search/MultiVectorSimilarity.java@@ -0,0 +1,41 @@+/*+ * 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 org.apache.lucene.index.VectorSimilarityFunction;++/**+ * Interface to define the similarity function between multi-vectors+ *+ * @lucene.experimental+ */+public interface MultiVectorSimilarity {++ /**+ * Computes similarity between two multi-vectors using provided {@link VectorSimilarityFunction}+ *+ * <p>Provided multi-vectors can have varying number of composing token vectors, but their token+ * vectors should have the same dimension.+ *+ * @param outer a multi-vector+ * @param inner another multi-vector+ * @return similarity score between two multi-vectors+ */+ float compare(+ float[][] outer, float[][] inner, VectorSimilarityFunction vectorSimilarityFunction);+}diff --git a/lucene/core/src/java/org/apache/lucene/search/RescoreTopNQuery.java b/lucene/core/src/java/org/apache/lucene/search/RescoreTopNQuery.javaindex 3b9a8fa045c..523d194c0e8 100644--- a/lucene/core/src/java/org/apache/lucene/search/RescoreTopNQuery.java+++ b/lucene/core/src/java/org/apache/lucene/search/RescoreTopNQuery.java@@ -19,6 +19,7 @@ package org.apache.lucene.search;import java.io.IOException;import java.util.Objects;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.VectorSimilarityFunction;/*** A Query that re-scores another Query with a {@link DoubleValuesSource} function and cut-off the@@ -148,4 +149,31 @@ public class RescoreTopNQuery extends Query {new FullPrecisionFloatVectorSimilarityValuesSource(targetVector, field);return new RescoreTopNQuery(in, valuaSource, n);}++ /**+ * Creates a {@code RescoreTopNQuery} that computes top N results using multi-vector similarity+ * comparisons against a late interaction field.+ *+ * <p>Note: This query computes late interaction field similarity for the entire match-set of+ * wrapped query, and returns a new query with only top-N hits in the match-set. This is typically+ * useful in combining a query's results with other queries for hybrid search. To simply rerank+ * the top N hits without scoring entire match-set, see {@link LateInteractionRescorer}.+ *+ * @param in the inner Query to rescore+ * @param n number of results to keep+ * @param fieldName the {@link org.apache.lucene.document.LateInteractionField} for recomputing+ * top N hits+ * @param queryVector query multi-vector to use for similarity comparisons+ * @param vectorSimilarityFunction function to use for vector similarity comparisons.+ */+ public static Query createLateInteractionQuery(+ Query in,+ int n,+ String fieldName,+ float[][] queryVector,+ VectorSimilarityFunction vectorSimilarityFunction) {+ final LateInteractionFloatValuesSource valuesSource =+ new LateInteractionFloatValuesSource(fieldName, queryVector, vectorSimilarityFunction);+ return new RescoreTopNQuery(in, valuesSource, n);+ }}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestLateInteractionField.java b/lucene/core/src/test/org/apache/lucene/document/TestLateInteractionField.javanew file mode 100644index 00000000000..5adf59daf89--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/TestLateInteractionField.java@@ -0,0 +1,87 @@+/*+ * 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.document;++import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.TestVectorUtil;++public class TestLateInteractionField extends LuceneTestCase {++ public void testEncodeDecode() {+ float[][] value = new float[random().nextInt(3, 12)][];+ final int dim = 128;+ for (int i = 0; i < value.length; i++) {+ value[i] = TestVectorUtil.randomVector(dim);+ }+ final LateInteractionField field = new LateInteractionField("test", value);+ BytesRef encoded = LateInteractionField.encode(value);+ float[][] decoded = LateInteractionField.decode(encoded);+ assertEqualArrays(value, decoded);+ assertEqualArrays(value, field.getValue());+ }++ public void testSetterGetter() {+ final int dim = 128;+ float[][] value = new float[random().nextInt(3, 12)][];+ for (int i = 0; i < value.length; i++) {+ value[i] = TestVectorUtil.randomVector(dim);+ }+ final LateInteractionField field = new LateInteractionField("test", value);++ float[][] value2 = new float[random().nextInt(3, 12)][];+ for (int i = 0; i < value2.length; i++) {+ value2[i] = TestVectorUtil.randomVector(dim);+ }+ assertEqualArrays(field.getValue(), value);+ field.setValue(value2);+ assertEqualArrays(field.getValue(), value2);+ }++ public void testInputValidation() {+ expectThrows(IllegalArgumentException.class, () -> LateInteractionField.encode(null));+ expectThrows(IllegalArgumentException.class, () -> new LateInteractionField("test", null));+ expectThrows(IllegalArgumentException.class, () -> LateInteractionField.encode(new float[0][]));+ expectThrows(IllegalArgumentException.class, () -> LateInteractionField.encode(new float[3][]));++ float[][] emptyTokens = new float[1][];+ emptyTokens[0] = new float[0];+ expectThrows(IllegalArgumentException.class, () -> LateInteractionField.encode(emptyTokens));++ final int dim = 128;+ float[][] value = new float[random().nextInt(3, 12)][];+ for (int i = 0; i < value.length; i++) {+ if (random().nextBoolean()) {+ value[i] = TestVectorUtil.randomVector(dim);+ } else {+ value[i] = TestVectorUtil.randomVector(dim + 1);+ }+ }+ expectThrows(IllegalArgumentException.class, () -> LateInteractionField.encode(value));+ }++ private void assertEqualArrays(float[][] a, float[][] b) {+ assertEquals(a.length, b.length);+ for (int i = 0; i < a.length; i++) {+ assertEquals(a[i].length, b[i].length);+ for (int j = 0; j < a[i].length; j++) {+ assertEquals(a[i][j], b[i][j], 1e-5f);+ }+ }+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestLateInteractionFloatValuesSource.java b/lucene/core/src/test/org/apache/lucene/search/TestLateInteractionFloatValuesSource.javanew file mode 100644index 00000000000..6d72830a055--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestLateInteractionFloatValuesSource.java@@ -0,0 +1,159 @@+/*+ * 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.ArrayList;+import java.util.List;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.IntField;+import org.apache.lucene.document.LateInteractionField;+import org.apache.lucene.index.BinaryDocValues;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.StoredFields;+import org.apache.lucene.index.VectorSimilarityFunction;+import org.apache.lucene.store.Directory;+import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.util.TestVectorUtil;++public class TestLateInteractionFloatValuesSource extends LuceneTestCase {++ private static final int dimension = 128;+ private static final String LATE_I_FIELD = "lateIF";++ public void testValidations() {+ expectThrows(+ IllegalArgumentException.class,+ () -> new LateInteractionFloatValuesSource("fieldName", null, null));+ expectThrows(+ IllegalArgumentException.class,+ () -> new LateInteractionFloatValuesSource("fieldName", new float[0][], null));+ float[][] emptyTokens = new float[1][];+ emptyTokens[0] = new float[0];+ expectThrows(+ IllegalArgumentException.class,+ () -> new LateInteractionFloatValuesSource("fieldName", emptyTokens, null));++ float[][] valueBad = new float[random().nextInt(3, 12)][];+ for (int i = 0; i < valueBad.length; i++) {+ if (random().nextBoolean()) {+ valueBad[i] = TestVectorUtil.randomVector(dimension);+ } else {+ valueBad[i] = TestVectorUtil.randomVector(dimension + 1);+ }+ }+ }++ public void testValues() throws IOException {+ List<float[][]> corpus = new ArrayList<>();+ final int numDocs = atLeast(1000);+ final int numSegments = random().nextInt(2, 10);+ final VectorSimilarityFunction vectorSimilarityFunction =+ VectorSimilarityFunction.values()[+ random().nextInt(VectorSimilarityFunction.values().length)];+ LateInteractionFloatValuesSource.ScoreFunction scoreFunction =+ LateInteractionFloatValuesSource.ScoreFunction.values()[+ random().nextInt(LateInteractionFloatValuesSource.ScoreFunction.values().length)];++ try (Directory dir = newDirectory()) {+ int id = 0;+ try (IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (int j = 0; j < numSegments; j++) {+ for (int i = 0; i < numDocs; i++) {+ Document doc = new Document();+ if (random().nextInt(100) < 30) {+ // skip value for some docs to create sparse field+ doc.add(new IntField("has_li_vector", 0, Field.Store.YES));+ } else {+ float[][] value = createMultiVector();+ corpus.add(value);+ doc.add(new IntField("id", id++, Field.Store.YES));+ doc.add(new LateInteractionField(LATE_I_FIELD, value));+ doc.add(new IntField("has_li_vector", 1, Field.Store.YES));+ }+ w.addDocument(doc);+ w.flush();+ }+ }+ // add a segment with no vectors+ for (int i = 0; i < 100; i++) {+ Document doc = new Document();+ doc.add(new IntField("has_li_vector", 0, Field.Store.YES));+ w.addDocument(doc);+ }+ w.flush();+ }++ float[][] queryVector = createMultiVector();+ LateInteractionFloatValuesSource source =+ new LateInteractionFloatValuesSource(+ LATE_I_FIELD, queryVector, vectorSimilarityFunction, scoreFunction);+ try (IndexReader reader = DirectoryReader.open(dir)) {+ for (LeafReaderContext ctx : reader.leaves()) {+ DoubleValues values = source.getValues(ctx, null);+ final FieldInfo fi = ctx.reader().getFieldInfos().fieldInfo(LATE_I_FIELD);+ if (fi == null) {+ assertEquals(values, DoubleValues.EMPTY);+ continue;+ }+ BinaryDocValues disi = ctx.reader().getBinaryDocValues(LATE_I_FIELD);+ StoredFields storedFields = ctx.reader().storedFields();+ while (disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {+ int doc = disi.docID();+ int idValue = Integer.parseInt(storedFields.document(doc).get("id"));+ float[][] docVector = corpus.get(idValue);+ float expected =+ scoreFunction.compare(queryVector, docVector, vectorSimilarityFunction);+ values.advanceExact(doc);+ assertEquals(expected, values.doubleValue(), 0.0001);+ }+ }+ }+ }+ }++ public void testSumMaxSim() {+ float[][] queryVector = createMultiVector();+ // docVector has all the token vectors in the query and some random token vectors+ float[][] docVector = new float[queryVector.length + 4][];+ for (int i = 0; i < queryVector.length; i++) {+ docVector[i] = new float[queryVector[i].length];+ System.arraycopy(queryVector[i], 0, docVector[i], 0, queryVector[i].length);+ }+ for (int i = queryVector.length; i < docVector.length; i++) {+ docVector[i] = TestVectorUtil.randomVector(queryVector[0].length);+ }+ float score =+ LateInteractionFloatValuesSource.ScoreFunction.SUM_MAX_SIM.compare(+ queryVector, docVector, VectorSimilarityFunction.COSINE);+ assertEquals(queryVector.length, score, 1e-5);+ }++ private float[][] createMultiVector() {+ float[][] value = new float[random().nextInt(3, 12)][];+ for (int i = 0; i < value.length; i++) {+ value[i] = TestVectorUtil.randomVector(dimension);+ }+ return value;+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestLateInteractionRescorer.java b/lucene/core/src/test/org/apache/lucene/search/TestLateInteractionRescorer.javanew file mode 100644index 00000000000..c3685434591--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestLateInteractionRescorer.java@@ -0,0 +1,180 @@+/*+ * 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 static org.apache.lucene.search.LateInteractionFloatValuesSource.ScoreFunction;++import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;+import java.util.Random;+import java.util.Set;+import java.util.stream.Collectors;+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.document.LateInteractionField;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.StoredFields;+import org.apache.lucene.index.VectorSimilarityFunction;+import org.apache.lucene.store.Directory;+import org.apache.lucene.tests.util.LuceneTestCase;++public class TestLateInteractionRescorer extends LuceneTestCase {++ private final String LATE_I_FIELD = "li_vector";+ private final String KNN_FIELD = "knn_vector";+ private final int DIMENSION = 128;++ public void testBasic() throws Exception {+ List<float[][]> corpus = new ArrayList<>();+ final VectorSimilarityFunction vectorSimilarityFunction =+ VectorSimilarityFunction.values()[+ random().nextInt(VectorSimilarityFunction.values().length)];+ ScoreFunction scoreFunction = ScoreFunction.SUM_MAX_SIM;++ try (Directory dir = newDirectory()) {+ indexMultiVectors(dir, corpus);+ float[][] lateIQueryVector = createMultiVector(DIMENSION);+ float[] knnQueryVector = randomFloatVector(DIMENSION, random());+ KnnFloatVectorQuery knnQuery = new KnnFloatVectorQuery(KNN_FIELD, knnQueryVector, 50);++ try (IndexReader reader = DirectoryReader.open(dir)) {+ final int topN = 10;+ IndexSearcher s = new IndexSearcher(reader);+ TopDocs knnHits = s.search(knnQuery, 5 * topN);+ LateInteractionRescorer rescorer =+ LateInteractionRescorer.create(+ LATE_I_FIELD, lateIQueryVector, vectorSimilarityFunction);+ TopDocs rerankedHits = rescorer.rescore(s, knnHits, topN);+ Set<Integer> knnHitDocs =+ Arrays.stream(knnHits.scoreDocs).map(k -> k.doc).collect(Collectors.toSet());+ assertEquals(topN, rerankedHits.scoreDocs.length);+ StoredFields storedFields = reader.storedFields();+ for (int i = 0; i < rerankedHits.scoreDocs.length; i++) {+ assertTrue(knnHitDocs.contains(rerankedHits.scoreDocs[i].doc));+ int idValue =+ Integer.parseInt(storedFields.document(rerankedHits.scoreDocs[i].doc).get("id"));+ float[][] docVector = corpus.get(idValue);+ float expected =+ scoreFunction.compare(lateIQueryVector, docVector, vectorSimilarityFunction);+ assertEquals(expected, rerankedHits.scoreDocs[i].score, 1e-5);+ if (i > 0) {+ assertTrue(rerankedHits.scoreDocs[i].score <= rerankedHits.scoreDocs[i - 1].score);+ }+ }+ }+ }+ }++ public void testMissingLateIValues() throws Exception {+ List<float[][]> corpus = new ArrayList<>();+ final VectorSimilarityFunction vectorSimilarityFunction =+ VectorSimilarityFunction.values()[+ random().nextInt(VectorSimilarityFunction.values().length)];++ try (Directory dir = newDirectory()) {+ indexMultiVectors(dir, corpus);+ float[][] lateIQueryVector = createMultiVector(DIMENSION);+ float[] knnQueryVector = randomFloatVector(DIMENSION, random());+ KnnFloatVectorQuery knnQuery = new KnnFloatVectorQuery(KNN_FIELD, knnQueryVector, 50);++ try (IndexReader reader = DirectoryReader.open(dir)) {+ final int topN = 10;+ IndexSearcher s = new IndexSearcher(reader);+ TopDocs knnHits = s.search(knnQuery, 5 * topN);+ LateInteractionRescorer rescorer =+ LateInteractionRescorer.create(+ "bad-test-field", lateIQueryVector, vectorSimilarityFunction);+ TopDocs rerankedHits = rescorer.rescore(s, knnHits, topN);+ Set<Integer> knnHitDocs =+ Arrays.stream(knnHits.scoreDocs).map(k -> k.doc).collect(Collectors.toSet());+ assertEquals(topN, rerankedHits.scoreDocs.length);+ for (int i = 0; i < rerankedHits.scoreDocs.length; i++) {+ assertTrue(knnHitDocs.contains(rerankedHits.scoreDocs[i].doc));+ assertEquals(0f, rerankedHits.scoreDocs[i].score, 1e-5);+ }++ LateInteractionRescorer rescorerWithFallback =+ LateInteractionRescorer.withFallbackToFirstPassScore(+ "bad-test-field", lateIQueryVector, vectorSimilarityFunction);+ knnHits = s.search(knnQuery, 5 * topN);+ rerankedHits = rescorerWithFallback.rescore(s, knnHits, topN);+ knnHitDocs = Arrays.stream(knnHits.scoreDocs).map(k -> k.doc).collect(Collectors.toSet());+ assertEquals(topN, rerankedHits.scoreDocs.length);+ for (int i = 0; i < rerankedHits.scoreDocs.length; i++) {+ assertTrue(knnHitDocs.contains(rerankedHits.scoreDocs[i].doc));+ assertEquals(knnHits.scoreDocs[i].score, rerankedHits.scoreDocs[i].score, 1e-5);+ }+ }+ }+ }++ private void indexMultiVectors(Directory dir, List<float[][]> corpus) throws IOException {+ final int numDocs = atLeast(1000);+ final int numSegments = random().nextInt(2, 10);+ int id = 0;+ try (IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (int j = 0; j < numSegments; j++) {+ for (int i = 0; i < numDocs; i++) {+ Document doc = new Document();+ if (random().nextInt(100) < 30) {+ // skip value for some docs to create sparse field+ doc.add(new IntField("has_li_vector", 0, Field.Store.YES));+ } else {+ float[][] value = createMultiVector(DIMENSION);+ corpus.add(value);+ doc.add(new IntField("id", id++, Field.Store.YES));+ doc.add(new LateInteractionField(LATE_I_FIELD, value));+ doc.add(new KnnFloatVectorField(KNN_FIELD, randomFloatVector(DIMENSION, random())));+ doc.add(new IntField("has_li_vector", 1, Field.Store.YES));+ }+ w.addDocument(doc);+ w.flush();+ }+ }+ // add a segment with no vectors+ for (int i = 0; i < 100; i++) {+ Document doc = new Document();+ doc.add(new IntField("has_li_vector", 0, Field.Store.YES));+ w.addDocument(doc);+ }+ w.flush();+ }+ }++ private float[][] createMultiVector(int dimension) {+ float[][] value = new float[random().nextInt(3, 12)][];+ for (int i = 0; i < value.length; i++) {+ value[i] = randomFloatVector(dimension, random());+ }+ return value;+ }++ private float[] randomFloatVector(int dimension, Random random) {+ float[] vector = new float[dimension];+ for (int i = 0; i < dimension; i++) {+ vector[i] = random.nextFloat();+ }+ return vector;+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestRescoreTopNQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestRescoreTopNQuery.javaindex e1be2c81822..df21442e2b5 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestRescoreTopNQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestRescoreTopNQuery.java@@ -17,18 +17,25 @@package org.apache.lucene.search;import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;import java.util.HashMap;+import java.util.List;import java.util.Map;import java.util.Random;+import java.util.Set;+import java.util.stream.Collectors;import org.apache.lucene.codecs.lucene99.Lucene99HnswScalarQuantizedVectorsFormat;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.document.LateInteractionField;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.StoredFields;import org.apache.lucene.index.Term;import org.apache.lucene.index.VectorSimilarityFunction;import org.apache.lucene.store.ByteBuffersDirectory;@@ -156,6 +163,87 @@ public class TestRescoreTopNQuery extends LuceneTestCase {}}+ public void testLateInteractionQuery() throws Exception {+ final String LATE_I_FIELD = "li_vector";+ final String KNN_FIELD = "knn_vector";+ List<float[][]> corpus = new ArrayList<>();+ final int numDocs = atLeast(1000);+ final int numSegments = random().nextInt(2, 10);+ final int dim = 128;+ final VectorSimilarityFunction vectorSimilarityFunction =+ VectorSimilarityFunction.values()[+ random().nextInt(VectorSimilarityFunction.values().length)];+ LateInteractionFloatValuesSource.ScoreFunction scoreFunction =+ LateInteractionFloatValuesSource.ScoreFunction.values()[+ random().nextInt(LateInteractionFloatValuesSource.ScoreFunction.values().length)];++ try (Directory dir = newDirectory()) {+ int id = 0;+ try (IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ for (int j = 0; j < numSegments; j++) {+ for (int i = 0; i < numDocs; i++) {+ Document doc = new Document();+ if (random().nextInt(100) < 30) {+ // skip value for some docs to create sparse field+ doc.add(new IntField("has_li_vector", 0, Field.Store.YES));+ } else {+ float[][] value = createMultiVector(dim);+ corpus.add(value);+ doc.add(new IntField("id", id++, Field.Store.YES));+ doc.add(new LateInteractionField(LATE_I_FIELD, value));+ doc.add(new KnnFloatVectorField(KNN_FIELD, randomFloatVector(dim, random())));+ doc.add(new IntField("has_li_vector", 1, Field.Store.YES));+ }+ w.addDocument(doc);+ w.flush();+ }+ }+ // add a segment with no vectors+ for (int i = 0; i < 100; i++) {+ Document doc = new Document();+ doc.add(new IntField("has_li_vector", 0, Field.Store.YES));+ w.addDocument(doc);+ }+ w.flush();+ }++ float[][] lateIQueryVector = createMultiVector(dim);+ float[] knnQueryVector = randomFloatVector(dim, random());+ KnnFloatVectorQuery knnQuery = new KnnFloatVectorQuery(KNN_FIELD, knnQueryVector, 50);++ try (IndexReader reader = DirectoryReader.open(dir)) {+ final int topN = 10;+ IndexSearcher s = new IndexSearcher(reader);+ TopDocs knnHits = s.search(knnQuery, 5 * topN);+ Set<Integer> knnHitDocs =+ Arrays.stream(knnHits.scoreDocs).map(k -> k.doc).collect(Collectors.toSet());+ Query lateIQuery =+ RescoreTopNQuery.createLateInteractionQuery(+ knnQuery, topN, LATE_I_FIELD, lateIQueryVector, vectorSimilarityFunction);+ TopDocs lateIHits = s.search(lateIQuery, 3 * topN);+ // total match-set for RescoreTopNQuery is topN+ assertEquals(topN, lateIHits.scoreDocs.length);+ StoredFields storedFields = reader.storedFields();+ for (ScoreDoc hit : lateIHits.scoreDocs) {+ assertTrue(knnHitDocs.contains(hit.doc));+ int idValue = Integer.parseInt(storedFields.document(hit.doc).get("id"));+ float[][] docVector = corpus.get(idValue);+ float expected =+ scoreFunction.compare(lateIQueryVector, docVector, vectorSimilarityFunction);+ assertEquals(expected, hit.score, 1e-5);+ }+ }+ }+ }++ private float[][] createMultiVector(int dimension) {+ float[][] value = new float[random().nextInt(3, 12)][];+ for (int i = 0; i < value.length; i++) {+ value[i] = randomFloatVector(dimension, random());+ }+ return value;+ }+private float[] randomFloatVector(int dimension, Random random) {float[] vector = new float[dimension];for (int i = 0; i < dimension; i++) {