Skip to content

Apache Lucene open-source search software

Add updateable random scorer interface for vector index building (#14181)

Benjamin Trent48884e76e087
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 2b7222245f2..1775c8b8554 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -90,7 +90,11 @@ Optimizations
* GITHUB#14133: Dense blocks of postings are now encoded as bit sets.
(Adrien Grand)
-# GITHUB#14169: Optimize ContextQuery with big number of contexts. (Mayya Sharipova)
+* GITHUB#14169: Optimize ContextQuery with big number of contexts. (Mayya Sharipova)
+
+* GITHUB#14181: Add updateable random scorer interface for knn vector index building. This allows
+ for fewer objects to be created during indexing and simplifies internally used iterfaces.
+ (Ben Trent)
Bug Fixes
---------------------
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerBenchmark.java
index 0a4da1f4886..4e0afbb75d0 100644
--- a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerBenchmark.java
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerBenchmark.java
@@ -35,6 +35,7 @@ import org.apache.lucene.store.MMapDirectory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.hnsw.RandomVectorScorer;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
import org.openjdk.jmh.annotations.*;
@BenchmarkMode(Mode.Throughput)
@@ -57,7 +58,7 @@ public class VectorScorerBenchmark {
IndexInput in;
KnnVectorValues vectorValues;
byte[] vec1, vec2;
- RandomVectorScorer scorer;
+ UpdateableRandomVectorScorer scorer;
@Setup(Level.Iteration)
public void init() throws IOException {
@@ -76,7 +77,8 @@ public class VectorScorerBenchmark {
scorer =
FlatVectorScorerUtil.getLucene99FlatVectorsScorer()
.getRandomVectorScorerSupplier(DOT_PRODUCT, vectorValues)
- .scorer(0);
+ .scorer();
+ scorer.setScoringOrdinal(0);
}
@TearDown
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/FlatBitVectorsScorer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/FlatBitVectorsScorer.java
index 8ffcc1c8d50..b74e051573b 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/FlatBitVectorsScorer.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/FlatBitVectorsScorer.java
@@ -26,6 +26,7 @@ import org.apache.lucene.util.Bits;
import org.apache.lucene.util.VectorUtil;
import org.apache.lucene.util.hnsw.RandomVectorScorer;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
/** A bit vector scorer for scoring byte vectors. */
public class FlatBitVectorsScorer implements FlatVectorsScorer {
@@ -33,7 +34,6 @@ public class FlatBitVectorsScorer implements FlatVectorsScorer {
public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues)
throws IOException {
- assert vectorValues instanceof ByteVectorValues;
if (vectorValues instanceof ByteVectorValues byteVectorValues) {
return new BitRandomVectorScorerSupplier(byteVectorValues);
}
@@ -51,14 +51,13 @@ public class FlatBitVectorsScorer implements FlatVectorsScorer {
public RandomVectorScorer getRandomVectorScorer(
VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, byte[] target)
throws IOException {
- assert vectorValues instanceof ByteVectorValues;
if (vectorValues instanceof ByteVectorValues byteVectorValues) {
return new BitRandomVectorScorer(byteVectorValues, target);
}
throw new IllegalArgumentException("vectorValues must be an instance of ByteVectorValues");
}
- static class BitRandomVectorScorer implements RandomVectorScorer {
+ static class BitRandomVectorScorer implements UpdateableRandomVectorScorer {
private final ByteVectorValues vectorValues;
private final int bitDimensions;
private final byte[] query;
@@ -80,6 +79,11 @@ public class FlatBitVectorsScorer implements FlatVectorsScorer {
return vectorValues.size();
}
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(vectorValues.vectorValue(node), 0, query, 0, query.length);
+ }
+
@Override
public int ordToDoc(int ord) {
return vectorValues.ordToDoc(ord);
@@ -93,24 +97,22 @@ public class FlatBitVectorsScorer implements FlatVectorsScorer {
static class BitRandomVectorScorerSupplier implements RandomVectorScorerSupplier {
protected final ByteVectorValues vectorValues;
- protected final ByteVectorValues vectorValues1;
- protected final ByteVectorValues vectorValues2;
+ protected final ByteVectorValues targetVectors;
public BitRandomVectorScorerSupplier(ByteVectorValues vectorValues) throws IOException {
this.vectorValues = vectorValues;
- this.vectorValues1 = vectorValues.copy();
- this.vectorValues2 = vectorValues.copy();
+ this.targetVectors = vectorValues.copy();
}
@Override
- public RandomVectorScorer scorer(int ord) throws IOException {
- byte[] query = vectorValues1.vectorValue(ord);
- return new BitRandomVectorScorer(vectorValues2, query);
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ byte[] query = new byte[vectorValues.dimension()];
+ return new BitRandomVectorScorer(vectorValues, query);
}
@Override
public RandomVectorScorerSupplier copy() throws IOException {
- return new BitRandomVectorScorerSupplier(vectorValues.copy());
+ return new BitRandomVectorScorerSupplier(vectorValues);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/DefaultFlatVectorScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/DefaultFlatVectorScorer.java
index 3e506037969..6a94eef3377 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/DefaultFlatVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/DefaultFlatVectorScorer.java
@@ -24,6 +24,7 @@ import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.util.hnsw.RandomVectorScorer;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
/**
* Default implementation of {@link FlatVectorsScorer}.
@@ -89,24 +90,29 @@ public class DefaultFlatVectorScorer implements FlatVectorsScorer {
/** RandomVectorScorerSupplier for bytes vector */
private static final class ByteScoringSupplier implements RandomVectorScorerSupplier {
private final ByteVectorValues vectors;
- private final ByteVectorValues vectors1;
- private final ByteVectorValues vectors2;
+ private final ByteVectorValues targetVectors;
private final VectorSimilarityFunction similarityFunction;
private ByteScoringSupplier(
ByteVectorValues vectors, VectorSimilarityFunction similarityFunction) throws IOException {
this.vectors = vectors;
- vectors1 = vectors.copy();
- vectors2 = vectors.copy();
+ targetVectors = vectors.copy();
this.similarityFunction = similarityFunction;
}
@Override
- public RandomVectorScorer scorer(int ord) {
- return new RandomVectorScorer.AbstractRandomVectorScorer(vectors) {
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ byte[] vector = new byte[vectors.dimension()];
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(vectors) {
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(targetVectors.vectorValue(node), 0, vector, 0, vector.length);
+ }
+
@Override
public float score(int node) throws IOException {
- return similarityFunction.compare(vectors1.vectorValue(ord), vectors2.vectorValue(node));
+ return similarityFunction.compare(vector, targetVectors.vectorValue(node));
}
};
}
@@ -125,24 +131,28 @@ public class DefaultFlatVectorScorer implements FlatVectorsScorer {
/** RandomVectorScorerSupplier for Float vector */
private static final class FloatScoringSupplier implements RandomVectorScorerSupplier {
private final FloatVectorValues vectors;
- private final FloatVectorValues vectors1;
- private final FloatVectorValues vectors2;
+ private final FloatVectorValues targetVectors;
private final VectorSimilarityFunction similarityFunction;
private FloatScoringSupplier(
FloatVectorValues vectors, VectorSimilarityFunction similarityFunction) throws IOException {
this.vectors = vectors;
- vectors1 = vectors.copy();
- vectors2 = vectors.copy();
+ targetVectors = vectors.copy();
this.similarityFunction = similarityFunction;
}
@Override
- public RandomVectorScorer scorer(int ord) {
- return new RandomVectorScorer.AbstractRandomVectorScorer(vectors) {
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ float[] vector = new float[vectors.dimension()];
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(vectors) {
@Override
public float score(int node) throws IOException {
- return similarityFunction.compare(vectors1.vectorValue(ord), vectors2.vectorValue(node));
+ return similarityFunction.compare(vector, targetVectors.vectorValue(node));
+ }
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(targetVectors.vectorValue(node), 0, vector, 0, vector.length);
}
};
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/ScalarQuantizedVectorScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/ScalarQuantizedVectorScorer.java
index ceb826aa3a1..ad4bb7e3c6d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/ScalarQuantizedVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/ScalarQuantizedVectorScorer.java
@@ -24,6 +24,7 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.VectorUtil;
import org.apache.lucene.util.hnsw.RandomVectorScorer;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
import org.apache.lucene.util.quantization.ScalarQuantizedVectorSimilarity;
import org.apache.lucene.util.quantization.ScalarQuantizer;
@@ -147,11 +148,18 @@ public class ScalarQuantizedVectorScorer implements FlatVectorsScorer {
}
@Override
- public RandomVectorScorer scorer(int ord) throws IOException {
+ public UpdateableRandomVectorScorer scorer() throws IOException {
final QuantizedByteVectorValues vectorsCopy = values.copy();
- final byte[] queryVector = values.vectorValue(ord);
- final float queryOffset = values.getScoreCorrectionConstant(ord);
- return new RandomVectorScorer.AbstractRandomVectorScorer(vectorsCopy) {
+ byte[] queryVector = new byte[values.dimension()];
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(vectorsCopy) {
+ float queryOffset = 0;
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(vectorsCopy.vectorValue(node), 0, queryVector, 0, queryVector.length);
+ queryOffset = vectorsCopy.getScoreCorrectionConstant(node);
+ }
+
@Override
public float score(int node) throws IOException {
byte[] nodeVector = vectorsCopy.vectorValue(node);
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java
index b731e758b7a..2ee7a2a0665 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java
@@ -52,8 +52,8 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
-import org.apache.lucene.util.hnsw.RandomVectorScorer;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
/**
* Writes vector values to index segments.
@@ -507,8 +507,8 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
}
@Override
- public RandomVectorScorer scorer(int ord) throws IOException {
- return supplier.scorer(ord);
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ return supplier.scorer();
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java
index e219157ab98..62c7f5c807b 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java
@@ -57,6 +57,7 @@ import org.apache.lucene.util.hnsw.IncrementalHnswGraphMerger;
import org.apache.lucene.util.hnsw.NeighborArray;
import org.apache.lucene.util.hnsw.OnHeapHnswGraph;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
import org.apache.lucene.util.packed.DirectMonotonicWriter;
/**
@@ -561,6 +562,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
private int lastDocID = -1;
private int node = 0;
private final FlatFieldVectorsWriter<T> flatFieldVectorsWriter;
+ private UpdateableRandomVectorScorer scorer;
@SuppressWarnings("unchecked")
static FieldWriter<?> create(
@@ -616,6 +618,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
(List<float[]>) flatFieldVectorsWriter.getVectors(),
fieldInfo.getVectorDimension()));
};
+ this.scorer = scorerSupplier.scorer();
hnswGraphBuilder =
HnswGraphBuilder.create(scorerSupplier, M, beamWidth, HnswGraphBuilder.randSeed);
hnswGraphBuilder.setInfoStream(infoStream);
@@ -631,7 +634,8 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
+ "\" appears more than once in this document (only one value is allowed per field)");
}
flatFieldVectorsWriter.addValue(docID, vectorValue);
- hnswGraphBuilder.addGraphNode(node);
+ scorer.setScoringOrdinal(node);
+ hnswGraphBuilder.addGraphNode(node, scorer);
node++;
lastDocID = docID;
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorScorer.java
index 8fc417e22f0..9153e0da38e 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorScorer.java
@@ -26,6 +26,7 @@ import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.util.VectorUtil;
import org.apache.lucene.util.hnsw.RandomVectorScorer;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
import org.apache.lucene.util.quantization.ScalarQuantizer;
@@ -87,7 +88,7 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
return "ScalarQuantizedVectorScorer(" + "nonQuantizedDelegate=" + nonQuantizedDelegate + ')';
}
- static RandomVectorScorer fromVectorSimilarity(
+ static UpdateableRandomVectorScorer fromVectorSimilarity(
byte[] targetBytes,
float offsetCorrection,
VectorSimilarityFunction sim,
@@ -120,12 +121,13 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
}
}
- private static RandomVectorScorer.AbstractRandomVectorScorer dotProductFactory(
- byte[] targetBytes,
- float offsetCorrection,
- float constMultiplier,
- QuantizedByteVectorValues values,
- FloatToFloatFunction scoreAdjustmentFunction) {
+ private static UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer
+ dotProductFactory(
+ byte[] targetBytes,
+ float offsetCorrection,
+ float constMultiplier,
+ QuantizedByteVectorValues values,
+ FloatToFloatFunction scoreAdjustmentFunction) {
if (values.getScalarQuantizer().getBits() <= 4) {
if (values.getVectorByteLength() != values.dimension() && values.getSlice() != null) {
return new CompressedInt4DotProduct(
@@ -138,7 +140,8 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
values, constMultiplier, targetBytes, offsetCorrection, scoreAdjustmentFunction);
}
- private static class Euclidean extends RandomVectorScorer.AbstractRandomVectorScorer {
+ private static class Euclidean
+ extends UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer {
private final float constMultiplier;
private final byte[] targetBytes;
private final QuantizedByteVectorValues values;
@@ -157,14 +160,20 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
float adjustedDistance = squareDistance * constMultiplier;
return 1 / (1f + adjustedDistance);
}
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(values.vectorValue(node), 0, targetBytes, 0, targetBytes.length);
+ }
}
/** Calculates dot product on quantized vectors, applying the appropriate corrections */
- private static class DotProduct extends RandomVectorScorer.AbstractRandomVectorScorer {
+ private static class DotProduct
+ extends UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer {
private final float constMultiplier;
private final QuantizedByteVectorValues values;
private final byte[] targetBytes;
- private final float offsetCorrection;
+ private float offsetCorrection;
private final FloatToFloatFunction scoreAdjustmentFunction;
public DotProduct(
@@ -191,15 +200,24 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
float adjustedDistance = dotProduct * constMultiplier + offsetCorrection + vectorOffset;
return scoreAdjustmentFunction.apply(adjustedDistance);
}
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(values.vectorValue(node), 0, targetBytes, 0, targetBytes.length);
+ offsetCorrection = values.getScoreCorrectionConstant(node);
+ }
}
+ // TODO consider splitting this into two classes. right now the "query" vector is always
+ // decompressed
+ // it could stay compressed if we had a compressed version of the target vector
private static class CompressedInt4DotProduct
- extends RandomVectorScorer.AbstractRandomVectorScorer {
+ extends UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer {
private final float constMultiplier;
private final QuantizedByteVectorValues values;
private final byte[] compressedVector;
private final byte[] targetBytes;
- private final float offsetCorrection;
+ private float offsetCorrection;
private final FloatToFloatFunction scoreAdjustmentFunction;
private CompressedInt4DotProduct(
@@ -230,13 +248,20 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
float adjustedDistance = dotProduct * constMultiplier + offsetCorrection + vectorOffset;
return scoreAdjustmentFunction.apply(adjustedDistance);
}
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(values.vectorValue(node), 0, targetBytes, 0, targetBytes.length);
+ offsetCorrection = values.getScoreCorrectionConstant(node);
+ }
}
- private static class Int4DotProduct extends RandomVectorScorer.AbstractRandomVectorScorer {
+ private static class Int4DotProduct
+ extends UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer {
private final float constMultiplier;
private final QuantizedByteVectorValues values;
private final byte[] targetBytes;
- private final float offsetCorrection;
+ private float offsetCorrection;
private final FloatToFloatFunction scoreAdjustmentFunction;
public Int4DotProduct(
@@ -263,6 +288,12 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
float adjustedDistance = dotProduct * constMultiplier + offsetCorrection + vectorOffset;
return scoreAdjustmentFunction.apply(adjustedDistance);
}
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(values.vectorValue(node), 0, targetBytes, 0, targetBytes.length);
+ offsetCorrection = values.getScoreCorrectionConstant(node);
+ }
}
@FunctionalInterface
@@ -275,28 +306,26 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
private final VectorSimilarityFunction vectorSimilarityFunction;
private final QuantizedByteVectorValues values;
- private final QuantizedByteVectorValues values1;
- private final QuantizedByteVectorValues values2;
+ private final QuantizedByteVectorValues targetVectors;
public ScalarQuantizedRandomVectorScorerSupplier(
QuantizedByteVectorValues values, VectorSimilarityFunction vectorSimilarityFunction)
throws IOException {
this.values = values;
- this.values1 = values.copy();
- this.values2 = values.copy();
+ this.targetVectors = values.copy();
this.vectorSimilarityFunction = vectorSimilarityFunction;
}
@Override
- public RandomVectorScorer scorer(int ord) throws IOException {
- byte[] vectorValue = values1.vectorValue(ord);
- float offsetCorrection = values1.getScoreCorrectionConstant(ord);
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ byte[] vectorValue = new byte[values.dimension()];
+ float offsetCorrection = 0;
return fromVectorSimilarity(
vectorValue,
offsetCorrection,
vectorSimilarityFunction,
values.getScalarQuantizer().getConstantMultiplier(),
- values2);
+ targetVectors);
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java
index 39f3a81983b..bcfbb30c261 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java
@@ -58,8 +58,8 @@ import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.VectorUtil;
import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
-import org.apache.lucene.util.hnsw.RandomVectorScorer;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
import org.apache.lucene.util.quantization.QuantizedVectorsReader;
import org.apache.lucene.util.quantization.ScalarQuantizer;
@@ -1128,8 +1128,8 @@ public final class Lucene99ScalarQuantizedVectorsWriter extends FlatVectorsWrite
}
@Override
- public RandomVectorScorer scorer(int ord) throws IOException {
- return supplier.scorer(ord);
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ return supplier.scorer();
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/CloseableRandomVectorScorerSupplier.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/CloseableRandomVectorScorerSupplier.java
index 148963e7dc9..8c66147f1a8 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/CloseableRandomVectorScorerSupplier.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/CloseableRandomVectorScorerSupplier.java
@@ -20,8 +20,8 @@ package org.apache.lucene.util.hnsw;
import java.io.Closeable;
/**
- * A supplier that creates {@link RandomVectorScorer} from an ordinal. Caller should be sure to
- * close after use
+ * A supplier that creates {@link UpdateableRandomVectorScorer} from an ordinal. Caller should be
+ * sure to close after use
*
* <p>NOTE: the {@link #copy()} returned {@link RandomVectorScorerSupplier} is not necessarily
* closeable
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/HnswConcurrentMergeBuilder.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/HnswConcurrentMergeBuilder.java
index d9d58c829d3..415e6cd2314 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/HnswConcurrentMergeBuilder.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/HnswConcurrentMergeBuilder.java
@@ -142,6 +142,7 @@ public class HnswConcurrentMergeBuilder implements HnswBuilder {
private final BitSet initializedNodes;
private int batchSize = DEFAULT_BATCH_SIZE;
+ private final UpdateableRandomVectorScorer scorer;
private ConcurrentMergeWorker(
RandomVectorScorerSupplier scorerSupplier,
@@ -162,6 +163,7 @@ public class HnswConcurrentMergeBuilder implements HnswBuilder {
new NeighborQueue(beamWidth, true), hnswLock, new FixedBitSet(hnsw.maxNodeId() + 1)));
this.workProgress = workProgress;
this.initializedNodes = initializedNodes;
+ this.scorer = scorerSupplier.scorer();
}
/**
@@ -190,12 +192,21 @@ public class HnswConcurrentMergeBuilder implements HnswBuilder {
}
}
+ @Override
+ public void addGraphNode(int node, UpdateableRandomVectorScorer scorer) throws IOException {
+ if (initializedNodes != null && initializedNodes.get(node)) {
+ return;
+ }
+ super.addGraphNode(node, scorer);
+ }
+
@Override
public void addGraphNode(int node) throws IOException {
if (initializedNodes != null && initializedNodes.get(node)) {
return;
}
- super.addGraphNode(node);
+ scorer.setScoringOrdinal(node);
+ addGraphNode(node, scorer);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/HnswGraphBuilder.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/HnswGraphBuilder.java
index d3cef0bc6d1..465d8c8c6eb 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/HnswGraphBuilder.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/HnswGraphBuilder.java
@@ -61,7 +61,7 @@ public class HnswGraphBuilder implements HnswBuilder {
private final double ml;
private final SplittableRandom random;
- private final RandomVectorScorerSupplier scorerSupplier;
+ protected final RandomVectorScorerSupplier scorerSupplier;
private final HnswGraphSearcher graphSearcher;
private final GraphBuilderKnnCollector entryCandidates; // for upper levels of graph search
private final GraphBuilderKnnCollector
@@ -191,8 +191,10 @@ public class HnswGraphBuilder implements HnswBuilder {
if (infoStream.isEnabled(HNSW_COMPONENT)) {
infoStream.message(HNSW_COMPONENT, "addVectors [" + minOrd + " " + maxOrd + ")");
}
+ UpdateableRandomVectorScorer scorer = scorerSupplier.scorer();
for (int node = minOrd; node < maxOrd; node++) {
- addGraphNode(node);
+ scorer.setScoringOrdinal(node);
+ addGraphNode(node, scorer);
if ((node % 10000 == 0) && infoStream.isEnabled(HNSW_COMPONENT)) {
t = printGraphBuildStatus(node, start, t);
}
@@ -203,30 +205,10 @@ public class HnswGraphBuilder implements HnswBuilder {
addVectors(0, maxOrd);
}
- @Override
- public void addGraphNode(int node) throws IOException {
- /*
- Note: this implementation is thread safe when graph size is fixed (e.g. when merging)
- The process of adding a node is roughly:
- 1. Add the node to all level from top to the bottom, but do not connect it to any other node,
- nor try to promote itself to an entry node before the connection is done. (Unless the graph is empty
- and this is the first node, in that case we set the entry node and return)
- 2. Do the search from top to bottom, remember all the possible neighbours on each level the node
- is on.
- 3. Add the neighbor to the node from bottom to top level, when adding the neighbour,
- we always add all the outgoing links first before adding incoming link such that
- when a search visits this node, it can always find a way out
- 4. If the node has level that is less or equal to graph level, then we're done here.
- If the node has level larger than graph level, then we need to promote the node
- as the entry node. If, while we add the node to the graph, the entry node has changed
- (which means the graph level has changed as well), we need to reinsert the node
- to the newly introduced levels (repeating step 2,3 for new levels) and again try to
- promote the node to entry node.
- */
+ public void addGraphNode(int node, UpdateableRandomVectorScorer scorer) throws IOException {
if (frozen) {
throw new IllegalStateException("Graph builder is already frozen");
}
- RandomVectorScorer scorer = scorerSupplier.scorer(node);
final int nodeLevel = getRandomGraphLevel(ml, random);
// first add nodes to all levels
for (int level = nodeLevel; level >= 0; level--) {
@@ -271,7 +253,7 @@ public class HnswGraphBuilder implements HnswBuilder {
// then do connections from bottom up
for (int i = 0; i < scratchPerLevel.length; i++) {
- addDiverseNeighbors(i + lowestUnsetLevel, node, scratchPerLevel[i]);
+ addDiverseNeighbors(i + lowestUnsetLevel, node, scratchPerLevel[i], scorer);
}
lowestUnsetLevel += scratchPerLevel.length;
assert lowestUnsetLevel == Math.min(nodeLevel, curMaxLevel) + 1;
@@ -296,6 +278,31 @@ public class HnswGraphBuilder implements HnswBuilder {
} while (true);
}
+ @Override
+ public void addGraphNode(int node) throws IOException {
+ /*
+ Note: this implementation is thread safe when graph size is fixed (e.g. when merging)
+ The process of adding a node is roughly:
+ 1. Add the node to all level from top to the bottom, but do not connect it to any other node,
+ nor try to promote itself to an entry node before the connection is done. (Unless the graph is empty
+ and this is the first node, in that case we set the entry node and return)
+ 2. Do the search from top to bottom, remember all the possible neighbours on each level the node
+ is on.
+ 3. Add the neighbor to the node from bottom to top level, when adding the neighbour,
+ we always add all the outgoing links first before adding incoming link such that
+ when a search visits this node, it can always find a way out
+ 4. If the node has level that is less or equal to graph level, then we're done here.
+ If the node has level larger than graph level, then we need to promote the node
+ as the entry node. If, while we add the node to the graph, the entry node has changed
+ (which means the graph level has changed as well), we need to reinsert the node
+ to the newly introduced levels (repeating step 2,3 for new levels) and again try to
+ promote the node to entry node.
+ */
+ UpdateableRandomVectorScorer scorer = scorerSupplier.scorer();
+ scorer.setScoringOrdinal(node);
+ addGraphNode(node, scorer);
+ }
+
private long printGraphBuildStatus(int node, long start, long t) {
long now = System.nanoTime();
infoStream.message(
@@ -309,7 +316,8 @@ public class HnswGraphBuilder implements HnswBuilder {
return now;
}
- private void addDiverseNeighbors(int level, int node, NeighborArray candidates)
+ private void addDiverseNeighbors(
+ int level, int node, NeighborArray candidates, UpdateableRandomVectorScorer scorer)
throws IOException {
/* For each of the beamWidth nearest candidates (going from best to worst), select it only if it
* is closer to target than it is to any of the already-selected neighbors (ie selected in this method,
@@ -318,7 +326,7 @@ public class HnswGraphBuilder implements HnswBuilder {
NeighborArray neighbors = hnsw.getNeighbors(level, node);
assert neighbors.size() == 0; // new node
int maxConnOnLevel = level == 0 ? M * 2 : M;
- boolean[] mask = selectAndLinkDiverse(neighbors, candidates, maxConnOnLevel);
+ boolean[] mask = selectAndLinkDiverse(neighbors, candidates, maxConnOnLevel, scorer);
// Link the selected nodes to the new node, and the new node to the selected nodes (again
// applying diversity heuristic)
@@ -334,13 +342,13 @@ public class HnswGraphBuilder implements HnswBuilder {
Lock lock = hnswLock.write(level, nbr);
try {
NeighborArray nbrsOfNbr = getGraph().getNeighbors(level, nbr);
- nbrsOfNbr.addAndEnsureDiversity(node, candidates.scores()[i], nbr, scorerSupplier);
+ nbrsOfNbr.addAndEnsureDiversity(node, candidates.scores()[i], nbr, scorer);
} finally {
lock.unlock();
}
} else {
NeighborArray nbrsOfNbr = hnsw.getNeighbors(level, nbr);
- nbrsOfNbr.addAndEnsureDiversity(node, candidates.scores()[i], nbr, scorerSupplier);
+ nbrsOfNbr.addAndEnsureDiversity(node, candidates.scores()[i], nbr, scorer);
}
}
}
@@ -350,7 +358,11 @@ public class HnswGraphBuilder implements HnswBuilder {
* are selected
*/
private boolean[] selectAndLinkDiverse(
- NeighborArray neighbors, NeighborArray candidates, int maxConnOnLevel) throws IOException {
+ NeighborArray neighbors,
+ NeighborArray candidates,
+ int maxConnOnLevel,
+ UpdateableRandomVectorScorer scorer)
+ throws IOException {
boolean[] mask = new boolean[candidates.size()];
// Select the best maxConnOnLevel neighbors of the new node, applying the diversity heuristic
for (int i = candidates.size() - 1; neighbors.size() < maxConnOnLevel && i >= 0; i--) {
@@ -359,7 +371,8 @@ public class HnswGraphBuilder implements HnswBuilder {
int cNode = candidates.nodes()[i];
float cScore = candidates.scores()[i];
assert cNode <= hnsw.maxNodeId();
- if (diversityCheck(cNode, cScore, neighbors)) {
+ scorer.setScoringOrdinal(cNode);
+ if (diversityCheck(cScore, neighbors, scorer)) {
mask[i] = true;
// here we don't need to lock, because there's no incoming link so no others is able to
// discover this node such that no others will modify this neighbor array as well
@@ -381,15 +394,13 @@ public class HnswGraphBuilder implements HnswBuilder {
}
/**
- * @param candidate the vector of a new candidate neighbor of a node n
* @param score the score of the new candidate and node n, to be compared with scores of the
* candidate and n's neighbors
* @param neighbors the neighbors selected so far
* @return whether the candidate is diverse given the existing neighbors
*/
- private boolean diversityCheck(int candidate, float score, NeighborArray neighbors)
+ private boolean diversityCheck(float score, NeighborArray neighbors, RandomVectorScorer scorer)
throws IOException {
- RandomVectorScorer scorer = scorerSupplier.scorer(candidate);
for (int i = 0; i < neighbors.size(); i++) {
float neighborSimilarity = scorer.score(neighbors.nodes()[i]);
if (neighborSimilarity >= score) {
@@ -452,6 +463,7 @@ public class HnswGraphBuilder implements HnswBuilder {
// while linking
GraphBuilderKnnCollector beam = new GraphBuilderKnnCollector(2);
int[] eps = new int[1];
+ UpdateableRandomVectorScorer scorer = scorerSupplier.scorer();
for (Component c : components) {
if (c != c0) {
if (c.start() == NO_MORE_DOCS) {
@@ -463,7 +475,7 @@ public class HnswGraphBuilder implements HnswBuilder {
beam.clear();
eps[0] = c0.start();
- RandomVectorScorer scorer = scorerSupplier.scorer(c.start());
+ scorer.setScoringOrdinal(c.start());
// find the closest node in the largest component to the lowest-numbered node in this
// component that has room to make a connection
graphSearcher.searchLevel(beam, scorer, level, eps, hnsw, notFullyConnected);
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/InitializedHnswGraphBuilder.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/InitializedHnswGraphBuilder.java
index 7dff036ddde..c4c790c7025 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/InitializedHnswGraphBuilder.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/InitializedHnswGraphBuilder.java
@@ -98,6 +98,14 @@ public final class InitializedHnswGraphBuilder extends HnswGraphBuilder {
this.initializedNodes = initializedNodes;
}
+ @Override
+ public void addGraphNode(int node, UpdateableRandomVectorScorer scorer) throws IOException {
+ if (initializedNodes.get(node)) {
+ return;
+ }
+ super.addGraphNode(node, scorer);
+ }
+
@Override
public void addGraphNode(int node) throws IOException {
if (initializedNodes.get(node)) {
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/NeighborArray.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/NeighborArray.java
index 716364a39dc..c7745120a5f 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/NeighborArray.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/NeighborArray.java
@@ -87,14 +87,15 @@ public class NeighborArray {
* @param nodeId node Id of the owner of this NeighbourArray
*/
public void addAndEnsureDiversity(
- int newNode, float newScore, int nodeId, RandomVectorScorerSupplier scorerSupplier)
+ int newNode, float newScore, int nodeId, UpdateableRandomVectorScorer scorer)
throws IOException {
addOutOfOrder(newNode, newScore);
if (size < nodes.length) {
return;
}
// we're oversize, need to do diversity check and pop out the least diverse neighbour
- removeIndex(findWorstNonDiverse(nodeId, scorerSupplier));
+ scorer.setScoringOrdinal(nodeId);
+ removeIndex(findWorstNonDiverse(scorer));
assert size == nodes.length - 1;
}
@@ -235,9 +236,7 @@ public class NeighborArray {
* Find first non-diverse neighbour among the list of neighbors starting from the most distant
* neighbours
*/
- private int findWorstNonDiverse(int nodeOrd, RandomVectorScorerSupplier scorerSupplier)
- throws IOException {
- RandomVectorScorer scorer = scorerSupplier.scorer(nodeOrd);
+ private int findWorstNonDiverse(UpdateableRandomVectorScorer scorer) throws IOException {
int[] uncheckedIndexes = sort(scorer);
assert uncheckedIndexes != null : "We will always have something unchecked";
int uncheckedCursor = uncheckedIndexes.length - 1;
@@ -246,7 +245,8 @@ public class NeighborArray {
// no unchecked node left
break;
}
- if (isWorstNonDiverse(i, uncheckedIndexes, uncheckedCursor, scorerSupplier)) {
+ scorer.setScoringOrdinal(nodes[i]);
+ if (isWorstNonDiverse(i, uncheckedIndexes, uncheckedCursor, scorer)) {
return i;
}
if (i == uncheckedIndexes[uncheckedCursor]) {
@@ -257,13 +257,9 @@ public class NeighborArray {
}
private boolean isWorstNonDiverse(
- int candidateIndex,
- int[] uncheckedIndexes,
- int uncheckedCursor,
- RandomVectorScorerSupplier scorerSupplier)
+ int candidateIndex, int[] uncheckedIndexes, int uncheckedCursor, RandomVectorScorer scorer)
throws IOException {
float minAcceptedSimilarity = scores[candidateIndex];
- RandomVectorScorer scorer = scorerSupplier.scorer(nodes[candidateIndex]);
if (candidateIndex == uncheckedIndexes[uncheckedCursor]) {
// the candidate itself is unchecked
for (int i = candidateIndex - 1; i >= 0; i--) {
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/RandomVectorScorer.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/RandomVectorScorer.java
index a135df43699..d2ea8e28a24 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/RandomVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/RandomVectorScorer.java
@@ -21,7 +21,10 @@ import java.io.IOException;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.util.Bits;
-/** A {@link RandomVectorScorer} for scoring random nodes in batches against an abstract query. */
+/**
+ * A {@link RandomVectorScorer} for scoring random nodes in batches against an abstract query. This
+ * class isn't thread-safe and should be used by a single thread.
+ */
public interface RandomVectorScorer {
/**
* Returns the score between the query and the provided node.
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/RandomVectorScorerSupplier.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/RandomVectorScorerSupplier.java
index f8436f061d6..b6bdea0d3b9 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/RandomVectorScorerSupplier.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/RandomVectorScorerSupplier.java
@@ -22,13 +22,12 @@ import java.io.IOException;
/** A supplier that creates {@link RandomVectorScorer} from an ordinal. */
public interface RandomVectorScorerSupplier {
/**
- * This creates a {@link RandomVectorScorer} for scoring random nodes in batches against the given
- * ordinal.
+ * This creates a {@link UpdateableRandomVectorScorer} for scoring random nodes in batches against
+ * an ordinal.
*
- * @param ord the ordinal of the node to compare
- * @return a new {@link RandomVectorScorer}
+ * @return a new {@link UpdateableRandomVectorScorer}
*/
- RandomVectorScorer scorer(int ord) throws IOException;
+ UpdateableRandomVectorScorer scorer() throws IOException;
/**
* Make a copy of the supplier, which will copy the underlying vectorValues so the copy is safe to
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/UpdateableRandomVectorScorer.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/UpdateableRandomVectorScorer.java
new file mode 100644
index 00000000000..ac07cf0fd6e
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/UpdateableRandomVectorScorer.java
@@ -0,0 +1,67 @@
+/*
+ * 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.util.hnsw;
+
+import java.io.IOException;
+import org.apache.lucene.index.KnnVectorValues;
+import org.apache.lucene.util.Bits;
+
+/**
+ * Just like a {@link RandomVectorScorer} but allows the scoring ordinal to be changed. Useful
+ * during indexing operations
+ *
+ * @lucene.internal
+ */
+public interface UpdateableRandomVectorScorer extends RandomVectorScorer {
+ /**
+ * Changes the scoring ordinal to the given node. If the same scorer object is being used
+ * continually, this can be used to avoid creating a new scorer for each node.
+ *
+ * @param node the node to score against
+ * @throws IOException if an exception occurs initializing the scorer for the given node
+ */
+ void setScoringOrdinal(int node) throws IOException;
+
+ /** Creates a default scorer for random access vectors. */
+ abstract class AbstractUpdateableRandomVectorScorer implements UpdateableRandomVectorScorer {
+ private final KnnVectorValues values;
+
+ /**
+ * Creates a new scorer for the given vector values.
+ *
+ * @param values the vector values
+ */
+ public AbstractUpdateableRandomVectorScorer(KnnVectorValues values) {
+ this.values = values;
+ }
+
+ @Override
+ public int maxOrd() {
+ return values.size();
+ }
+
+ @Override
+ public int ordToDoc(int ord) {
+ return values.ordToDoc(ord);
+ }
+
+ @Override
+ public Bits getAcceptOrds(Bits acceptDocs) {
+ return values.getAcceptOrds(acceptDocs);
+ }
+ }
+}
diff --git a/lucene/core/src/java21/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorerSupplier.java b/lucene/core/src/java21/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorerSupplier.java
index 02c71561122..74b31e1bf0c 100644
--- a/lucene/core/src/java21/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorerSupplier.java
+++ b/lucene/core/src/java21/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorerSupplier.java
@@ -25,8 +25,8 @@ import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.store.FilterIndexInput;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.MemorySegmentAccessInput;
-import org.apache.lucene.util.hnsw.RandomVectorScorer;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
/** A score supplier of vectors whose element size is byte. */
public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
@@ -110,15 +110,23 @@ public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
}
@Override
- public RandomVectorScorer scorer(int ord) {
- checkOrdinal(ord);
- return new RandomVectorScorer.AbstractRandomVectorScorer(values) {
+ public UpdateableRandomVectorScorer scorer() {
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(values) {
+ private int queryOrd = 0;
+
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
- float raw = PanamaVectorUtilSupport.cosine(getFirstSegment(ord), getSecondSegment(node));
+ float raw =
+ PanamaVectorUtilSupport.cosine(getFirstSegment(queryOrd), getSecondSegment(node));
return (1 + raw) / 2;
}
+
+ @Override
+ public void setScoringOrdinal(int node) {
+ checkOrdinal(node);
+ queryOrd = node;
+ }
};
}
@@ -135,17 +143,24 @@ public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
}
@Override
- public RandomVectorScorer scorer(int ord) {
- checkOrdinal(ord);
- return new RandomVectorScorer.AbstractRandomVectorScorer(values) {
+ public UpdateableRandomVectorScorer scorer() {
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(values) {
+ private int queryOrd = 0;
+
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
// divide by 2 * 2^14 (maximum absolute value of product of 2 signed bytes) * len
float raw =
- PanamaVectorUtilSupport.dotProduct(getFirstSegment(ord), getSecondSegment(node));
+ PanamaVectorUtilSupport.dotProduct(getFirstSegment(queryOrd), getSecondSegment(node));
return 0.5f + raw / (float) (values.dimension() * (1 << 15));
}
+
+ @Override
+ public void setScoringOrdinal(int node) {
+ checkOrdinal(node);
+ queryOrd = node;
+ }
};
}
@@ -162,16 +177,24 @@ public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
}
@Override
- public RandomVectorScorer scorer(int ord) {
- checkOrdinal(ord);
- return new RandomVectorScorer.AbstractRandomVectorScorer(values) {
+ public UpdateableRandomVectorScorer scorer() {
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(values) {
+ private int queryOrd = 0;
+
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
float raw =
- PanamaVectorUtilSupport.squareDistance(getFirstSegment(ord), getSecondSegment(node));
+ PanamaVectorUtilSupport.squareDistance(
+ getFirstSegment(queryOrd), getSecondSegment(node));
return 1 / (1f + raw);
}
+
+ @Override
+ public void setScoringOrdinal(int node) {
+ checkOrdinal(node);
+ queryOrd = node;
+ }
};
}
@@ -188,19 +211,26 @@ public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
}
@Override
- public RandomVectorScorer scorer(int ord) {
- checkOrdinal(ord);
- return new RandomVectorScorer.AbstractRandomVectorScorer(values) {
+ public UpdateableRandomVectorScorer scorer() {
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(values) {
+ private int queryOrd = 0;
+
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
float raw =
- PanamaVectorUtilSupport.dotProduct(getFirstSegment(ord), getSecondSegment(node));
+ PanamaVectorUtilSupport.dotProduct(getFirstSegment(queryOrd), getSecondSegment(node));
if (raw < 0) {
return 1 / (1 + -1 * raw);
}
return raw + 1;
}
+
+ @Override
+ public void setScoringOrdinal(int node) {
+ checkOrdinal(node);
+ queryOrd = node;
+ }
};
}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/hnsw/TestFlatVectorScorer.java b/lucene/core/src/test/org/apache/lucene/codecs/hnsw/TestFlatVectorScorer.java
index 6fe9a685e1b..9f97a602d4e 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/hnsw/TestFlatVectorScorer.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/hnsw/TestFlatVectorScorer.java
@@ -102,10 +102,12 @@ public class TestFlatVectorScorer extends LuceneTestCase {
var vectorValues = byteVectorValues(4, 3, in, EUCLIDEAN);
var ss = flatVectorsScorer.getRandomVectorScorerSupplier(EUCLIDEAN, vectorValues);
- var scorerAgainstOrd0 = ss.scorer(0);
+ var scorerAgainstOrd0 = ss.scorer();
+ scorerAgainstOrd0.setScoringOrdinal(0);
var firstScore = scorerAgainstOrd0.score(1);
@SuppressWarnings("unused")
- var scorerAgainstOrd2 = ss.scorer(2);
+ var scorerAgainstOrd2 = ss.scorer();
+ scorerAgainstOrd2.setScoringOrdinal(2);
var scoreAgain = scorerAgainstOrd0.score(1);
assertThat(scoreAgain, equalTo(firstScore));
@@ -128,10 +130,12 @@ public class TestFlatVectorScorer extends LuceneTestCase {
var vectorValues = floatVectorValues(4, 3, in, EUCLIDEAN);
var ss = flatVectorsScorer.getRandomVectorScorerSupplier(EUCLIDEAN, vectorValues);
- var scorerAgainstOrd0 = ss.scorer(0);
+ var scorerAgainstOrd0 = ss.scorer();
+ scorerAgainstOrd0.setScoringOrdinal(0);
var firstScore = scorerAgainstOrd0.score(1);
@SuppressWarnings("unused")
- var scorerAgainstOrd2 = ss.scorer(2);
+ var scorerAgainstOrd2 = ss.scorer();
+ scorerAgainstOrd2.setScoringOrdinal(2);
var scoreAgain = scorerAgainstOrd0.score(1);
assertThat(scoreAgain, equalTo(firstScore));
diff --git a/lucene/core/src/test/org/apache/lucene/internal/vectorization/TestVectorScorer.java b/lucene/core/src/test/org/apache/lucene/internal/vectorization/TestVectorScorer.java
index bc3b6813a5b..a1ffbd7c94a 100644
--- a/lucene/core/src/test/org/apache/lucene/internal/vectorization/TestVectorScorer.java
+++ b/lucene/core/src/test/org/apache/lucene/internal/vectorization/TestVectorScorer.java
@@ -52,7 +52,7 @@ import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.MMapDirectory;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.util.NamedThreadFactory;
-import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
import org.junit.BeforeClass;
public class TestVectorScorer extends LuceneTestCase {
@@ -107,9 +107,13 @@ public class TestVectorScorer extends LuceneTestCase {
// getRandomVectorScorerSupplier
var scorer1 = DEFAULT_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- float expected = scorer1.scorer(idx0).score(idx1);
+ var scorer1idx0 = scorer1.scorer();
+ scorer1idx0.setScoringOrdinal(idx0);
+ float expected = scorer1idx0.score(idx1);
var scorer2 = MEMSEG_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- assertEquals(scorer2.scorer(idx0).score(idx1), expected, DELTA);
+ scorer1idx0 = scorer2.scorer();
+ scorer1idx0.setScoringOrdinal(idx0);
+ assertEquals(scorer1idx0.score(idx1), expected, DELTA);
// getRandomVectorScorer
var scorer3 = DEFAULT_SCORER.getRandomVectorScorer(sim, vectorValues, vectors[idx0]);
@@ -164,9 +168,13 @@ public class TestVectorScorer extends LuceneTestCase {
// getRandomVectorScorerSupplier
var scorer1 = DEFAULT_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- float expected = scorer1.scorer(idx0).score(idx1);
+ var scorer1idx0 = scorer1.scorer();
+ scorer1idx0.setScoringOrdinal(idx0);
+ float expected = scorer1idx0.score(idx1);
var scorer2 = MEMSEG_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- assertEquals(scorer2.scorer(idx0).score(idx1), expected, DELTA);
+ scorer1idx0 = scorer2.scorer();
+ scorer1idx0.setScoringOrdinal(idx0);
+ assertEquals(scorer1idx0.score(idx1), expected, DELTA);
// getRandomVectorScorer
var scorer3 = DEFAULT_SCORER.getRandomVectorScorer(sim, vectorValues, vectors[idx0]);
@@ -218,9 +226,13 @@ public class TestVectorScorer extends LuceneTestCase {
// getRandomVectorScorerSupplier
var scorer1 = DEFAULT_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- float expected = scorer1.scorer(idx0).score(idx1);
+ var scorer1idx0 = scorer1.scorer();
+ scorer1idx0.setScoringOrdinal(idx0);
+ float expected = scorer1idx0.score(idx1);
var scorer2 = MEMSEG_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- assertEquals(scorer2.scorer(idx0).score(idx1), expected, DELTA);
+ scorer1idx0 = scorer2.scorer();
+ scorer1idx0.setScoringOrdinal(idx0);
+ assertEquals(scorer1idx0.score(idx1), expected, DELTA);
// getRandomVectorScorer
var scorer3 = DEFAULT_SCORER.getRandomVectorScorer(sim, vectorValues, vectors[idx0]);
@@ -251,14 +263,17 @@ public class TestVectorScorer extends LuceneTestCase {
for (var sim : List.of(COSINE, EUCLIDEAN, DOT_PRODUCT, MAXIMUM_INNER_PRODUCT)) {
var vectorValues = vectorValues(dims, 4, in, sim);
var scoreSupplier = DEFAULT_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- var expectedScore1 = scoreSupplier.scorer(0).score(1);
- var expectedScore2 = scoreSupplier.scorer(2).score(3);
+ var scorer1 = scoreSupplier.scorer();
+ scorer1.setScoringOrdinal(0);
+ var expectedScore1 = scorer1.score(1);
+ scorer1.setScoringOrdinal(2);
+ var expectedScore2 = scorer1.score(3);
var scorer = MEMSEG_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
var tasks =
List.<Callable<Optional<Throwable>>>of(
- new AssertingScoreCallable(scorer.copy().scorer(0), 1, expectedScore1),
- new AssertingScoreCallable(scorer.copy().scorer(2), 3, expectedScore2));
+ new AssertingScoreCallable(scorer.copy().scorer(), 0, 1, expectedScore1),
+ new AssertingScoreCallable(scorer.copy().scorer(), 2, 3, expectedScore2));
var executor = Executors.newFixedThreadPool(2, new NamedThreadFactory("copiesThreads"));
var results = executor.invokeAll(tasks);
executor.shutdown();
@@ -273,11 +288,13 @@ public class TestVectorScorer extends LuceneTestCase {
}
// A callable that scores the given ord and scorer and asserts the expected result.
- record AssertingScoreCallable(RandomVectorScorer scorer, int ord, float expectedScore)
+ record AssertingScoreCallable(
+ UpdateableRandomVectorScorer scorer, int target, int ord, float expectedScore)
implements Callable<Optional<Throwable>> {
@Override
public Optional<Throwable> call() throws Exception {
+ scorer.setScoringOrdinal(target);
try {
for (int i = 0; i < 100; i++) {
assertEquals(scorer.score(ord), expectedScore, DELTA);
@@ -316,9 +333,13 @@ public class TestVectorScorer extends LuceneTestCase {
// getRandomVectorScorerSupplier
var scorer1 = DEFAULT_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- float expected = scorer1.scorer(idx0).score(idx1);
+ var scorer1idx0 = scorer1.scorer();
+ scorer1idx0.setScoringOrdinal(idx0);
+ float expected = scorer1idx0.score(idx1);
var scorer2 = MEMSEG_SCORER.getRandomVectorScorerSupplier(sim, vectorValues);
- assertEquals(scorer2.scorer(idx0).score(idx1), expected, DELTA);
+ scorer1idx0 = scorer2.scorer();
+ scorer1idx0.setScoringOrdinal(idx0);
+ assertEquals(scorer1idx0.score(idx1), expected, DELTA);
// getRandomVectorScorer
var query = vector(idx0, dims);
@@ -354,10 +375,14 @@ public class TestVectorScorer extends LuceneTestCase {
// in it, since it's based on float vectors.
assertTrue(supplier1.toString().toLowerCase(ROOT).contains("float"));
assertTrue(supplier2.toString().toLowerCase(ROOT).contains("float"));
- assertTrue(supplier1.scorer(0).toString().toLowerCase(ROOT).contains("float"));
- assertTrue(supplier2.scorer(0).toString().toLowerCase(ROOT).contains("float"));
- float expected = supplier1.scorer(0).score(0);
- assertEquals(supplier2.scorer(0).score(0), expected, DELTA);
+ assertTrue(supplier1.scorer().toString().toLowerCase(ROOT).contains("float"));
+ assertTrue(supplier2.scorer().toString().toLowerCase(ROOT).contains("float"));
+ var scorer1idx0 = supplier1.scorer();
+ scorer1idx0.setScoringOrdinal(0);
+ float expected = scorer1idx0.score(0);
+ scorer1idx0 = supplier2.scorer();
+ scorer1idx0.setScoringOrdinal(0);
+ assertEquals(scorer1idx0.score(0), expected, DELTA);
var scorer1 = DEFAULT_SCORER.getRandomVectorScorer(sim, vectorValues, new float[] {1f});
var scorer2 = MEMSEG_SCORER.getRandomVectorScorer(sim, vectorValues, new float[] {1f});