Skip to content

Apache Lucene open-source search software

Prevent writing vectors twice during merging HNSW graphs (#15732)

Ignacio Vera733141ec45e2
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 8d5496b9740..43a28ba723e 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -338,6 +338,9 @@ Optimizations
* GITHUB#15868: Optimize DisjunctionMaxBulkScorer by reusing the inner LeafCollector across
sub-scorers and resetting windowScores inline during replay instead of Arrays.fill. (Prithvi S)
+* GITHUB#15732: Prevent writing vectors twice during merging HNSW graphs by allowing doing deferred work after calling
+ merge for vectors is finshed. (Ignacio Vera)
+
Bug Fixes
---------------------
* GITHUB#15754: Fix HTMLStripCharFilter to prevent tags from incorrectly consuming subsequent
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryFlatVectorsScorer.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryFlatVectorsScorer.java
index 9732ca36598..16d543e0576 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryFlatVectorsScorer.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryFlatVectorsScorer.java
@@ -30,6 +30,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.OptimizedScalarQuantizer;
import org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
@@ -54,7 +55,7 @@ public class Lucene102BinaryFlatVectorsScorer implements FlatVectorsScorer {
public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues)
throws IOException {
- throw new UnsupportedOperationException("Old codecs may only be used for reading");
+ return nonQuantizedDelegate.getRandomVectorScorerSupplier(similarityFunction, vectorValues);
}
@Override
@@ -98,6 +99,62 @@ public class Lucene102BinaryFlatVectorsScorer implements FlatVectorsScorer {
return "Lucene102BinaryFlatVectorsScorer(nonQuantizedDelegate=" + nonQuantizedDelegate + ")";
}
+ RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction,
+ Lucene102BinaryQuantizedVectorsReader.OffHeapBinarizedQueryVectorValues scoringVectors,
+ BinarizedByteVectorValues targetVectors) {
+ return new BinarizedRandomVectorScorerSupplier(
+ scoringVectors, targetVectors, similarityFunction);
+ }
+
+ /** Vector scorer supplier over binarized vector values */
+ static class BinarizedRandomVectorScorerSupplier implements RandomVectorScorerSupplier {
+ private final Lucene102BinaryQuantizedVectorsReader.OffHeapBinarizedQueryVectorValues
+ queryVectors;
+ private final BinarizedByteVectorValues targetVectors;
+ private final VectorSimilarityFunction similarityFunction;
+
+ BinarizedRandomVectorScorerSupplier(
+ Lucene102BinaryQuantizedVectorsReader.OffHeapBinarizedQueryVectorValues queryVectors,
+ BinarizedByteVectorValues targetVectors,
+ VectorSimilarityFunction similarityFunction) {
+ this.queryVectors = queryVectors;
+ this.targetVectors = targetVectors;
+ this.similarityFunction = similarityFunction;
+ }
+
+ @Override
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ final BinarizedByteVectorValues targetVectors = this.targetVectors.copy();
+ final Lucene102BinaryQuantizedVectorsReader.OffHeapBinarizedQueryVectorValues queryVectors =
+ this.queryVectors.copy();
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(targetVectors) {
+ private QuantizationResult queryCorrections = null;
+ private byte[] vector = null;
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ queryCorrections = queryVectors.getCorrectiveTerms(node);
+ vector = queryVectors.vectorValue(node);
+ }
+
+ @Override
+ public float score(int node) throws IOException {
+ if (vector == null || queryCorrections == null) {
+ throw new IllegalStateException("setScoringOrdinal was not called");
+ }
+ return quantizedScore(vector, queryCorrections, targetVectors, node, similarityFunction);
+ }
+ };
+ }
+
+ @Override
+ public RandomVectorScorerSupplier copy() throws IOException {
+ return new BinarizedRandomVectorScorerSupplier(
+ queryVectors.copy(), targetVectors.copy(), similarityFunction);
+ }
+ }
+
static float quantizedScore(
byte[] quantizedQuery,
QuantizationResult queryCorrections,
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsReader.java
index 8e3a6d7f307..7a5643bf0ef 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsReader.java
@@ -16,12 +16,17 @@
*/
package org.apache.lucene.backward_codecs.lucene102;
+import static org.apache.lucene.backward_codecs.lucene102.Lucene102BinaryQuantizedVectorsFormat.QUERY_BITS;
import static org.apache.lucene.backward_codecs.lucene102.Lucene102BinaryQuantizedVectorsFormat.VECTOR_DATA_EXTENSION;
import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader.readSimilarityFunction;
import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader.readVectorEncoding;
+import static org.apache.lucene.index.VectorSimilarityFunction.COSINE;
+import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.discretize;
+import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.transposeHalfByte;
import java.io.IOException;
+import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@@ -31,11 +36,14 @@ import org.apache.lucene.codecs.hnsw.FlatVectorsReader;
import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.AcceptDocs;
@@ -47,15 +55,23 @@ import org.apache.lucene.store.FileDataHint;
import org.apache.lucene.store.FileTypeHint;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.VectorUtil;
+import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
import org.apache.lucene.util.hnsw.OrdinalTranslatedKnnCollector;
import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.quantization.BaseQuantizedByteVectorValues;
import org.apache.lucene.util.quantization.OptimizedScalarQuantizer;
+import org.apache.lucene.util.quantization.QuantizedVectorsReader;
+import org.apache.lucene.util.quantization.ScalarQuantizer;
/** Reader for binary quantized vectors in the Lucene 10.2 format. */
-public class Lucene102BinaryQuantizedVectorsReader extends FlatVectorsReader {
+public class Lucene102BinaryQuantizedVectorsReader extends FlatVectorsReader
+ implements QuantizedVectorsReader {
private static final long SHALLOW_SIZE =
RamUsageEstimator.shallowSizeOfInstance(Lucene102BinaryQuantizedVectorsReader.class);
@@ -144,7 +160,7 @@ public class Lucene102BinaryQuantizedVectorsReader extends FlatVectorsReader {
+ fieldEntry.dimension);
}
- int binaryDims = discretize(dimension, 64) / 8;
+ int binaryDims = discretize(dimension, Long.SIZE) / Byte.SIZE;
long numQuantizedVectorBytes =
Math.multiplyExact((binaryDims + (Float.BYTES * 3) + Short.BYTES), (long) fieldEntry.size);
if (numQuantizedVectorBytes != fieldEntry.vectorDataLength) {
@@ -196,7 +212,7 @@ public class Lucene102BinaryQuantizedVectorsReader extends FlatVectorsReader {
}
@Override
- public FloatVectorValues getFloatVectorValues(String field) throws IOException {
+ public BinarizedVectorValues getFloatVectorValues(String field) throws IOException {
FieldEntry fi = fields.get(field);
if (fi == null) {
return null;
@@ -342,6 +358,107 @@ public class Lucene102BinaryQuantizedVectorsReader extends FlatVectorsReader {
return FieldEntry.create(input, vectorEncoding, info.getVectorSimilarityFunction());
}
+ @Override
+ public BaseQuantizedByteVectorValues getQuantizedVectorValues(String fieldName) {
+ return null;
+ }
+
+ @Override
+ public ScalarQuantizer getQuantizationState(String fieldName) {
+ return null;
+ }
+
+ @Override
+ public CloseableRandomVectorScorerSupplier getRandomVectorScorerSupplierForMerge(
+ FieldInfo fieldInfo, SegmentWriteState segmentWriteState) throws IOException {
+ assert fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32);
+ OptimizedScalarQuantizer quantizer =
+ new OptimizedScalarQuantizer(fieldInfo.getVectorSimilarityFunction());
+ String tempScoreQuantizedVectorName = null;
+ float[] centroid = getCentroid(fieldInfo.name);
+ BinarizedVectorValues vectorValues = getFloatVectorValues(fieldInfo.name);
+ FloatVectorValues floatVectorValues = vectorValues.rawVectorValues;
+ if (fieldInfo.getVectorSimilarityFunction() == COSINE) {
+ floatVectorValues = new NormalizedFloatVectorValues(floatVectorValues);
+ }
+
+ DocsWithFieldSet docsWithField;
+ try (IndexOutput tempScoreQuantizedVector =
+ segmentWriteState.directory.createTempOutput(
+ segmentWriteState.segmentInfo.name, "queries", segmentWriteState.context)) {
+ tempScoreQuantizedVectorName = tempScoreQuantizedVector.getName();
+ docsWithField =
+ writeBinarizedQueryData(tempScoreQuantizedVector, floatVectorValues, centroid, quantizer);
+ CodecUtil.writeFooter(tempScoreQuantizedVector);
+ } catch (Throwable t) {
+ if (tempScoreQuantizedVectorName != null) {
+ IOUtils.deleteFilesSuppressingExceptions(
+ t, segmentWriteState.directory, tempScoreQuantizedVectorName);
+ }
+ throw t;
+ }
+ IndexInput quantizedScoreDataInput =
+ segmentWriteState.directory.openInput(
+ tempScoreQuantizedVectorName, segmentWriteState.context);
+ try {
+ RandomVectorScorerSupplier scorerSupplier =
+ vectorScorer.getRandomVectorScorerSupplier(
+ fieldInfo.getVectorSimilarityFunction(),
+ new OffHeapBinarizedQueryVectorValues(
+ quantizedScoreDataInput,
+ fieldInfo.getVectorDimension(),
+ docsWithField.cardinality()),
+ vectorValues.quantizedVectorValues);
+ final String finalTempScoreQuantizedVectorName = tempScoreQuantizedVectorName;
+ return CloseableRandomVectorScorerSupplier.create(
+ scorerSupplier,
+ vectorValues.size(),
+ () -> {
+ IOUtils.close(quantizedScoreDataInput);
+ IOUtils.deleteFilesIgnoringExceptions(
+ segmentWriteState.directory, finalTempScoreQuantizedVectorName);
+ });
+ } catch (Throwable t) {
+ IOUtils.closeWhileSuppressingExceptions(t, quantizedScoreDataInput);
+ IOUtils.deleteFilesSuppressingExceptions(
+ t, segmentWriteState.directory, tempScoreQuantizedVectorName);
+ throw t;
+ }
+ }
+
+ static DocsWithFieldSet writeBinarizedQueryData(
+ IndexOutput binarizedQueryData,
+ FloatVectorValues floatVectorValues,
+ float[] centroid,
+ OptimizedScalarQuantizer binaryQuantizer)
+ throws IOException {
+ int discretizedDimension = discretize(floatVectorValues.dimension(), 64);
+ DocsWithFieldSet docsWithField = new DocsWithFieldSet();
+ byte[] quantizationScratch = new byte[floatVectorValues.dimension()];
+ byte[] toQuery = new byte[(discretizedDimension / 8) * QUERY_BITS];
+ KnnVectorValues.DocIndexIterator iterator = floatVectorValues.iterator();
+ for (int docV = iterator.nextDoc(); docV != NO_MORE_DOCS; docV = iterator.nextDoc()) {
+ // write index vector
+ OptimizedScalarQuantizer.QuantizationResult r =
+ binaryQuantizer.scalarQuantize(
+ floatVectorValues.vectorValue(iterator.index()),
+ quantizationScratch,
+ QUERY_BITS,
+ centroid);
+ docsWithField.add(docV);
+
+ // pack and store the 4bit query vector
+ transposeHalfByte(quantizationScratch, toQuery);
+ binarizedQueryData.writeBytes(toQuery, toQuery.length);
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.lowerInterval()));
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.upperInterval()));
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.additionalCorrection()));
+ assert r.quantizedComponentSum() >= 0 && r.quantizedComponentSum() <= 0xffff;
+ binarizedQueryData.writeShort((short) r.quantizedComponentSum());
+ }
+ return docsWithField;
+ }
+
private record FieldEntry(
VectorSimilarityFunction similarityFunction,
VectorEncoding vectorEncoding,
@@ -448,4 +565,115 @@ public class Lucene102BinaryQuantizedVectorsReader extends FlatVectorsReader {
return quantizedVectorValues;
}
}
+
+ // When accessing vectorValue method, targetOrd here means a row ordinal.
+ static class OffHeapBinarizedQueryVectorValues {
+ private final IndexInput slice;
+ private final int dimension;
+ private final int size;
+ protected final byte[] binaryValue;
+ protected final ByteBuffer byteBuffer;
+ private final int byteSize;
+ protected final float[] correctiveValues;
+ private int lastOrd = -1;
+ private int quantizedComponentSum;
+
+ OffHeapBinarizedQueryVectorValues(IndexInput data, int dimension, int size) {
+ this.slice = data;
+ this.dimension = dimension;
+ this.size = size;
+ // 4x the quantized binary dimensions
+ int binaryDimensions = (discretize(dimension, Long.SIZE) / Byte.SIZE) * QUERY_BITS;
+ this.byteBuffer = ByteBuffer.allocate(binaryDimensions);
+ this.binaryValue = byteBuffer.array();
+ // + 1 for the quantized sum
+ this.correctiveValues = new float[3];
+ this.byteSize = binaryDimensions + Float.BYTES * 3 + Short.BYTES;
+ }
+
+ public OptimizedScalarQuantizer.QuantizationResult getCorrectiveTerms(int targetOrd)
+ throws IOException {
+ if (lastOrd == targetOrd) {
+ return new OptimizedScalarQuantizer.QuantizationResult(
+ correctiveValues[0], correctiveValues[1], correctiveValues[2], quantizedComponentSum);
+ }
+ vectorValue(targetOrd);
+ return new OptimizedScalarQuantizer.QuantizationResult(
+ correctiveValues[0], correctiveValues[1], correctiveValues[2], quantizedComponentSum);
+ }
+
+ public int size() {
+ return size;
+ }
+
+ public int quantizedLength() {
+ return binaryValue.length;
+ }
+
+ public int dimension() {
+ return dimension;
+ }
+
+ public OffHeapBinarizedQueryVectorValues copy() throws IOException {
+ return new OffHeapBinarizedQueryVectorValues(slice.clone(), dimension, size);
+ }
+
+ public IndexInput getSlice() {
+ return slice;
+ }
+
+ public byte[] vectorValue(int targetOrd) throws IOException {
+ if (lastOrd == targetOrd) {
+ return binaryValue;
+ }
+ slice.seek((long) targetOrd * byteSize);
+ slice.readBytes(binaryValue, 0, binaryValue.length);
+ slice.readFloats(correctiveValues, 0, 3);
+ quantizedComponentSum = Short.toUnsignedInt(slice.readShort());
+ lastOrd = targetOrd;
+ return binaryValue;
+ }
+ }
+
+ static final class NormalizedFloatVectorValues extends FloatVectorValues {
+ private final FloatVectorValues values;
+ private final float[] normalizedVector;
+
+ NormalizedFloatVectorValues(FloatVectorValues values) {
+ this.values = values;
+ this.normalizedVector = new float[values.dimension()];
+ }
+
+ @Override
+ public int dimension() {
+ return values.dimension();
+ }
+
+ @Override
+ public int size() {
+ return values.size();
+ }
+
+ @Override
+ public int ordToDoc(int ord) {
+ return values.ordToDoc(ord);
+ }
+
+ @Override
+ public float[] vectorValue(int ord) throws IOException {
+ System.arraycopy(values.vectorValue(ord), 0, normalizedVector, 0, normalizedVector.length);
+ VectorUtil.l2normalize(normalizedVector);
+ return normalizedVector;
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return values.iterator();
+ }
+
+ @Override
+ public NormalizedFloatVectorValues copy() throws IOException {
+ return new NormalizedFloatVectorValues(values.copy());
+ }
+ }
}
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsReader.java
index 377ef2ddc06..317e5e60f16 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsReader.java
@@ -35,6 +35,7 @@ import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.internal.hppc.IntObjectHashMap;
@@ -47,6 +48,7 @@ import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
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.quantization.LegacyQuantizedByteVectorValues;
import org.apache.lucene.util.quantization.QuantizedVectorsReader;
@@ -348,6 +350,18 @@ public final class Lucene99ScalarQuantizedVectorsReader extends FlatVectorsReade
return fieldEntry.scalarQuantizer;
}
+ @Override
+ public CloseableRandomVectorScorerSupplier getRandomVectorScorerSupplierForMerge(
+ FieldInfo fieldInfo, SegmentWriteState segmentWriteState) throws IOException {
+ LegacyQuantizedByteVectorValues quantizedByteVectorValues =
+ getQuantizedVectorValues(fieldInfo.name);
+ return CloseableRandomVectorScorerSupplier.create(
+ vectorScorer.getRandomVectorScorerSupplier(
+ fieldInfo.getVectorSimilarityFunction(), quantizedByteVectorValues),
+ quantizedByteVectorValues.size(),
+ () -> {});
+ }
+
private record FieldEntry(
VectorSimilarityFunction similarityFunction,
VectorEncoding vectorEncoding,
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsWriter.java
index a782aaee097..4b873be3608 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsWriter.java
@@ -19,15 +19,12 @@ package org.apache.lucene.backward_codecs.lucene102;
import static org.apache.lucene.backward_codecs.lucene102.Lucene102BinaryQuantizedVectorsFormat.BINARIZED_VECTOR_COMPONENT;
import static org.apache.lucene.backward_codecs.lucene102.Lucene102BinaryQuantizedVectorsFormat.DIRECT_MONOTONIC_BLOCK_SHIFT;
import static org.apache.lucene.backward_codecs.lucene102.Lucene102BinaryQuantizedVectorsFormat.INDEX_BITS;
-import static org.apache.lucene.backward_codecs.lucene102.Lucene102BinaryQuantizedVectorsFormat.QUERY_BITS;
import static org.apache.lucene.index.VectorSimilarityFunction.COSINE;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import static org.apache.lucene.util.RamUsageEstimator.shallowSizeOfInstance;
import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.discretize;
import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.packAsBinary;
-import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.transposeHalfByte;
-import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -52,13 +49,9 @@ import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.internal.hppc.FloatArrayList;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.VectorScorer;
-import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.VectorUtil;
-import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
-import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
-import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
import org.apache.lucene.util.quantization.OptimizedScalarQuantizer;
/** Copied from Lucene, replace with Lucene's implementation sometime after Lucene 10 */
@@ -70,7 +63,6 @@ class Lucene102BinaryQuantizedVectorsWriter extends FlatVectorsWriter {
private final List<FieldWriter> fields = new ArrayList<>();
private final IndexOutput meta, binarizedVectorData;
private final FlatVectorsWriter rawVectorDelegate;
- private final Lucene102RWBinaryFlatVectorsScorer vectorsScorer;
private boolean finished;
/**
@@ -84,7 +76,6 @@ class Lucene102BinaryQuantizedVectorsWriter extends FlatVectorsWriter {
SegmentWriteState state)
throws IOException {
super(vectorsScorer);
- this.vectorsScorer = vectorsScorer;
this.segmentWriteState = state;
String metaFileName =
IndexFileNames.segmentFileName(
@@ -309,13 +300,14 @@ class Lucene102BinaryQuantizedVectorsWriter extends FlatVectorsWriter {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public void mergeOneFlatVectorField(FieldInfo fieldInfo, MergeState mergeState)
+ throws IOException {
+ // Don't need access to the random vectors, we can just use the merged
+ rawVectorDelegate.mergeOneFlatVectorField(fieldInfo, mergeState);
if (fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
final float[] centroid;
final float[] mergedCentroid = new float[fieldInfo.getVectorDimension()];
int vectorCount = mergeAndRecalculateCentroids(mergeState, fieldInfo, mergedCentroid);
- // Don't need access to the random vectors, we can just use the merged
- rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
centroid = mergedCentroid;
if (segmentWriteState.infoStream.isEnabled(BINARIZED_VECTOR_COMPONENT)) {
segmentWriteState.infoStream.message(
@@ -345,52 +337,7 @@ class Lucene102BinaryQuantizedVectorsWriter extends FlatVectorsWriter {
centroid,
centroidDp,
docsWithField);
- } else {
- rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
- }
- }
-
- static DocsWithFieldSet writeBinarizedVectorAndQueryData(
- IndexOutput binarizedVectorData,
- IndexOutput binarizedQueryData,
- FloatVectorValues floatVectorValues,
- float[] centroid,
- OptimizedScalarQuantizer binaryQuantizer)
- throws IOException {
- int discretizedDimension = discretize(floatVectorValues.dimension(), 64);
- DocsWithFieldSet docsWithField = new DocsWithFieldSet();
- byte[][] quantizationScratch = new byte[2][floatVectorValues.dimension()];
- byte[] toIndex = new byte[discretizedDimension / 8];
- byte[] toQuery = new byte[(discretizedDimension / 8) * QUERY_BITS];
- KnnVectorValues.DocIndexIterator iterator = floatVectorValues.iterator();
- for (int docV = iterator.nextDoc(); docV != NO_MORE_DOCS; docV = iterator.nextDoc()) {
- // write index vector
- OptimizedScalarQuantizer.QuantizationResult[] r =
- binaryQuantizer.multiScalarQuantize(
- floatVectorValues.vectorValue(iterator.index()),
- quantizationScratch,
- new byte[] {INDEX_BITS, QUERY_BITS},
- centroid);
- // pack and store document bit vector
- packAsBinary(quantizationScratch[0], toIndex);
- binarizedVectorData.writeBytes(toIndex, toIndex.length);
- binarizedVectorData.writeInt(Float.floatToIntBits(r[0].lowerInterval()));
- binarizedVectorData.writeInt(Float.floatToIntBits(r[0].upperInterval()));
- binarizedVectorData.writeInt(Float.floatToIntBits(r[0].additionalCorrection()));
- assert r[0].quantizedComponentSum() >= 0 && r[0].quantizedComponentSum() <= 0xffff;
- binarizedVectorData.writeShort((short) r[0].quantizedComponentSum());
- docsWithField.add(docV);
-
- // pack and store the 4bit query vector
- transposeHalfByte(quantizationScratch[1], toQuery);
- binarizedQueryData.writeBytes(toQuery, toQuery.length);
- binarizedQueryData.writeInt(Float.floatToIntBits(r[1].lowerInterval()));
- binarizedQueryData.writeInt(Float.floatToIntBits(r[1].upperInterval()));
- binarizedQueryData.writeInt(Float.floatToIntBits(r[1].additionalCorrection()));
- assert r[1].quantizedComponentSum() >= 0 && r[1].quantizedComponentSum() <= 0xffff;
- binarizedQueryData.writeShort((short) r[1].quantizedComponentSum());
}
- return docsWithField;
}
static DocsWithFieldSet writeBinarizedVectorData(
@@ -414,137 +361,6 @@ class Lucene102BinaryQuantizedVectorsWriter extends FlatVectorsWriter {
return docsWithField;
}
- @Override
- public CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
- FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- if (fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
- final float[] centroid;
- final float cDotC;
- final float[] mergedCentroid = new float[fieldInfo.getVectorDimension()];
- int vectorCount = mergeAndRecalculateCentroids(mergeState, fieldInfo, mergedCentroid);
-
- // Don't need access to the random vectors, we can just use the merged
- rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
- centroid = mergedCentroid;
- cDotC = vectorCount > 0 ? VectorUtil.dotProduct(centroid, centroid) : 0;
- if (segmentWriteState.infoStream.isEnabled(BINARIZED_VECTOR_COMPONENT)) {
- segmentWriteState.infoStream.message(
- BINARIZED_VECTOR_COMPONENT, "Vectors' count:" + vectorCount);
- }
- return mergeOneFieldToIndex(segmentWriteState, fieldInfo, mergeState, centroid, cDotC);
- }
- return rawVectorDelegate.mergeOneFieldToIndex(fieldInfo, mergeState);
- }
-
- private CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
- SegmentWriteState segmentWriteState,
- FieldInfo fieldInfo,
- MergeState mergeState,
- float[] centroid,
- float cDotC)
- throws IOException {
- long vectorDataOffset = binarizedVectorData.alignFilePointer(Float.BYTES);
- IndexOutput tempQuantizedVectorData = null;
- IndexOutput tempScoreQuantizedVectorData = null;
- IndexInput binarizedDataInput = null;
- IndexInput binarizedScoreDataInput = null;
- OptimizedScalarQuantizer quantizer =
- new OptimizedScalarQuantizer(fieldInfo.getVectorSimilarityFunction());
- try {
- tempQuantizedVectorData =
- segmentWriteState.directory.createTempOutput(
- binarizedVectorData.getName(), "temp", segmentWriteState.context);
- tempScoreQuantizedVectorData =
- segmentWriteState.directory.createTempOutput(
- binarizedVectorData.getName(), "score_temp", segmentWriteState.context);
- final String tempQuantizedVectorName = tempQuantizedVectorData.getName();
- final String tempScoreQuantizedVectorName = tempScoreQuantizedVectorData.getName();
- FloatVectorValues floatVectorValues =
- MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState);
- if (fieldInfo.getVectorSimilarityFunction() == COSINE) {
- floatVectorValues = new NormalizedFloatVectorValues(floatVectorValues);
- }
- DocsWithFieldSet docsWithField =
- writeBinarizedVectorAndQueryData(
- tempQuantizedVectorData,
- tempScoreQuantizedVectorData,
- floatVectorValues,
- centroid,
- quantizer);
- CodecUtil.writeFooter(tempQuantizedVectorData);
- IOUtils.close(tempQuantizedVectorData);
- binarizedDataInput =
- segmentWriteState.directory.openInput(tempQuantizedVectorName, segmentWriteState.context);
- binarizedVectorData.copyBytes(
- binarizedDataInput, binarizedDataInput.length() - CodecUtil.footerLength());
- long vectorDataLength = binarizedVectorData.getFilePointer() - vectorDataOffset;
- CodecUtil.retrieveChecksum(binarizedDataInput);
- CodecUtil.writeFooter(tempScoreQuantizedVectorData);
- IOUtils.close(tempScoreQuantizedVectorData);
- binarizedScoreDataInput =
- segmentWriteState.directory.openInput(
- tempScoreQuantizedVectorName, segmentWriteState.context);
- writeMeta(
- fieldInfo,
- segmentWriteState.segmentInfo.maxDoc(),
- vectorDataOffset,
- vectorDataLength,
- centroid,
- cDotC,
- docsWithField);
-
- final IndexInput finalBinarizedDataInput = binarizedDataInput;
- final IndexInput finalBinarizedScoreDataInput = binarizedScoreDataInput;
- tempQuantizedVectorData = null;
- tempScoreQuantizedVectorData = null;
- binarizedDataInput = null;
- binarizedScoreDataInput = null;
-
- OffHeapBinarizedVectorValues vectorValues =
- new OffHeapBinarizedVectorValues.DenseOffHeapVectorValues(
- fieldInfo.getVectorDimension(),
- docsWithField.cardinality(),
- centroid,
- cDotC,
- quantizer,
- fieldInfo.getVectorSimilarityFunction(),
- vectorsScorer,
- finalBinarizedDataInput);
- RandomVectorScorerSupplier scorerSupplier =
- vectorsScorer.getRandomVectorScorerSupplier(
- fieldInfo.getVectorSimilarityFunction(),
- new OffHeapBinarizedQueryVectorValues(
- finalBinarizedScoreDataInput,
- fieldInfo.getVectorDimension(),
- docsWithField.cardinality()),
- vectorValues);
- return new BinarizedCloseableRandomVectorScorerSupplier(
- scorerSupplier,
- vectorValues,
- () -> {
- IOUtils.close(finalBinarizedDataInput, finalBinarizedScoreDataInput);
- IOUtils.deleteFilesIgnoringExceptions(
- segmentWriteState.directory, tempQuantizedVectorName, tempScoreQuantizedVectorName);
- });
- } catch (Throwable t) {
- IOUtils.closeWhileSuppressingExceptions(
- t,
- tempQuantizedVectorData,
- tempScoreQuantizedVectorData,
- binarizedDataInput,
- binarizedScoreDataInput);
- if (tempQuantizedVectorData != null) {
- IOUtils.deleteFilesSuppressingExceptions(
- t, segmentWriteState.directory, tempQuantizedVectorData.getName());
- }
- if (tempScoreQuantizedVectorData != null) {
- IOUtils.deleteFilesSuppressingExceptions(
- t, segmentWriteState.directory, tempScoreQuantizedVectorData.getName());
- }
- throw t;
- }
- }
-
@Override
public void close() throws IOException {
IOUtils.close(meta, binarizedVectorData, rawVectorDelegate);
@@ -723,75 +539,6 @@ class Lucene102BinaryQuantizedVectorsWriter extends FlatVectorsWriter {
}
}
- // When accessing vectorValue method, targerOrd here means a row ordinal.
- static class OffHeapBinarizedQueryVectorValues {
- private final IndexInput slice;
- private final int dimension;
- private final int size;
- protected final byte[] binaryValue;
- protected final ByteBuffer byteBuffer;
- private final int byteSize;
- protected final float[] correctiveValues;
- private int lastOrd = -1;
- private int quantizedComponentSum;
-
- OffHeapBinarizedQueryVectorValues(IndexInput data, int dimension, int size) {
- this.slice = data;
- this.dimension = dimension;
- this.size = size;
- // 4x the quantized binary dimensions
- int binaryDimensions = (discretize(dimension, 64) / 8) * QUERY_BITS;
- this.byteBuffer = ByteBuffer.allocate(binaryDimensions);
- this.binaryValue = byteBuffer.array();
- // + 1 for the quantized sum
- this.correctiveValues = new float[3];
- this.byteSize = binaryDimensions + Float.BYTES * 3 + Short.BYTES;
- }
-
- public OptimizedScalarQuantizer.QuantizationResult getCorrectiveTerms(int targetOrd)
- throws IOException {
- if (lastOrd == targetOrd) {
- return new OptimizedScalarQuantizer.QuantizationResult(
- correctiveValues[0], correctiveValues[1], correctiveValues[2], quantizedComponentSum);
- }
- vectorValue(targetOrd);
- return new OptimizedScalarQuantizer.QuantizationResult(
- correctiveValues[0], correctiveValues[1], correctiveValues[2], quantizedComponentSum);
- }
-
- public int size() {
- return size;
- }
-
- public int quantizedLength() {
- return binaryValue.length;
- }
-
- public int dimension() {
- return dimension;
- }
-
- public OffHeapBinarizedQueryVectorValues copy() throws IOException {
- return new OffHeapBinarizedQueryVectorValues(slice.clone(), dimension, size);
- }
-
- public IndexInput getSlice() {
- return slice;
- }
-
- public byte[] vectorValue(int targetOrd) throws IOException {
- if (lastOrd == targetOrd) {
- return binaryValue;
- }
- slice.seek((long) targetOrd * byteSize);
- slice.readBytes(binaryValue, 0, binaryValue.length);
- slice.readFloats(correctiveValues, 0, 3);
- quantizedComponentSum = Short.toUnsignedInt(slice.readShort());
- lastOrd = targetOrd;
- return binaryValue;
- }
- }
-
static class BinarizedFloatVectorValues extends BinarizedByteVectorValues {
private OptimizedScalarQuantizer.QuantizationResult corrections;
private final byte[] binarized;
@@ -879,40 +626,6 @@ class Lucene102BinaryQuantizedVectorsWriter extends FlatVectorsWriter {
}
}
- static class BinarizedCloseableRandomVectorScorerSupplier
- implements CloseableRandomVectorScorerSupplier {
- private final RandomVectorScorerSupplier supplier;
- private final KnnVectorValues vectorValues;
- private final Closeable onClose;
-
- BinarizedCloseableRandomVectorScorerSupplier(
- RandomVectorScorerSupplier supplier, KnnVectorValues vectorValues, Closeable onClose) {
- this.supplier = supplier;
- this.onClose = onClose;
- this.vectorValues = vectorValues;
- }
-
- @Override
- public UpdateableRandomVectorScorer scorer() throws IOException {
- return supplier.scorer();
- }
-
- @Override
- public RandomVectorScorerSupplier copy() throws IOException {
- return supplier.copy();
- }
-
- @Override
- public void close() throws IOException {
- onClose.close();
- }
-
- @Override
- public int totalVectorCount() {
- return vectorValues.size();
- }
- }
-
static final class NormalizedFloatVectorValues extends FloatVectorValues {
private final FloatVectorValues values;
private final float[] normalizedVector;
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102RWBinaryFlatVectorsScorer.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102RWBinaryFlatVectorsScorer.java
index 6e1b6f69804..2627f23b0a0 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102RWBinaryFlatVectorsScorer.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102RWBinaryFlatVectorsScorer.java
@@ -16,17 +16,11 @@
*/
package org.apache.lucene.backward_codecs.lucene102;
-import static org.apache.lucene.index.VectorSimilarityFunction.EUCLIDEAN;
-import static org.apache.lucene.index.VectorSimilarityFunction.MAXIMUM_INNER_PRODUCT;
-
import java.io.IOException;
import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.VectorSimilarityFunction;
-import org.apache.lucene.util.VectorUtil;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
-import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
-import org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
/** Vector scorer over binarized vector values */
public class Lucene102RWBinaryFlatVectorsScorer extends Lucene102BinaryFlatVectorsScorer {
@@ -49,105 +43,8 @@ public class Lucene102RWBinaryFlatVectorsScorer extends Lucene102BinaryFlatVecto
return nonQuantizedDelegate.getRandomVectorScorerSupplier(similarityFunction, vectorValues);
}
- RandomVectorScorerSupplier getRandomVectorScorerSupplier(
- VectorSimilarityFunction similarityFunction,
- Lucene102BinaryQuantizedVectorsWriter.OffHeapBinarizedQueryVectorValues scoringVectors,
- BinarizedByteVectorValues targetVectors) {
- return new BinarizedRandomVectorScorerSupplier(
- scoringVectors, targetVectors, similarityFunction);
- }
-
@Override
public String toString() {
return "Lucene102BinaryFlatVectorsScorer(nonQuantizedDelegate=" + nonQuantizedDelegate + ")";
}
-
- /** Vector scorer supplier over binarized vector values */
- static class BinarizedRandomVectorScorerSupplier implements RandomVectorScorerSupplier {
- private final Lucene102BinaryQuantizedVectorsWriter.OffHeapBinarizedQueryVectorValues
- queryVectors;
- private final BinarizedByteVectorValues targetVectors;
- private final VectorSimilarityFunction similarityFunction;
-
- BinarizedRandomVectorScorerSupplier(
- Lucene102BinaryQuantizedVectorsWriter.OffHeapBinarizedQueryVectorValues queryVectors,
- BinarizedByteVectorValues targetVectors,
- VectorSimilarityFunction similarityFunction) {
- this.queryVectors = queryVectors;
- this.targetVectors = targetVectors;
- this.similarityFunction = similarityFunction;
- }
-
- @Override
- public UpdateableRandomVectorScorer scorer() throws IOException {
- final BinarizedByteVectorValues targetVectors = this.targetVectors.copy();
- final Lucene102BinaryQuantizedVectorsWriter.OffHeapBinarizedQueryVectorValues queryVectors =
- this.queryVectors.copy();
- return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(targetVectors) {
- private QuantizationResult queryCorrections = null;
- private byte[] vector = null;
-
- @Override
- public void setScoringOrdinal(int node) throws IOException {
- queryCorrections = queryVectors.getCorrectiveTerms(node);
- vector = queryVectors.vectorValue(node);
- }
-
- @Override
- public float score(int node) throws IOException {
- if (vector == null || queryCorrections == null) {
- throw new IllegalStateException("setScoringOrdinal was not called");
- }
- return quantizedScore(vector, queryCorrections, targetVectors, node, similarityFunction);
- }
- };
- }
-
- @Override
- public RandomVectorScorerSupplier copy() throws IOException {
- return new BinarizedRandomVectorScorerSupplier(
- queryVectors.copy(), targetVectors.copy(), similarityFunction);
- }
- }
-
- static float quantizedScore(
- byte[] quantizedQuery,
- QuantizationResult queryCorrections,
- BinarizedByteVectorValues targetVectors,
- int targetOrd,
- VectorSimilarityFunction similarityFunction)
- throws IOException {
- byte[] binaryCode = targetVectors.vectorValue(targetOrd);
- float qcDist = VectorUtil.int4BitDotProduct(quantizedQuery, binaryCode);
- QuantizationResult indexCorrections = targetVectors.getCorrectiveTerms(targetOrd);
- float x1 = indexCorrections.quantizedComponentSum();
- float ax = indexCorrections.lowerInterval();
- // Here we assume `lx` is simply bit vectors, so the scaling isn't necessary
- float lx = indexCorrections.upperInterval() - ax;
- float ay = queryCorrections.lowerInterval();
- float ly = (queryCorrections.upperInterval() - ay) * FOUR_BIT_SCALE;
- float y1 = queryCorrections.quantizedComponentSum();
- float score =
- ax * ay * targetVectors.dimension() + ay * lx * x1 + ax * ly * y1 + lx * ly * qcDist;
- // For euclidean, we need to invert the score and apply the additional correction, which is
- // assumed to be the squared l2norm of the centroid centered vectors.
- if (similarityFunction == EUCLIDEAN) {
- score =
- queryCorrections.additionalCorrection()
- + indexCorrections.additionalCorrection()
- - 2 * score;
- return Math.max(1 / (1f + score), 0);
- } else {
- // For cosine and max inner product, we need to apply the additional correction, which is
- // assumed to be the non-centered dot-product between the vector and the centroid
- score +=
- queryCorrections.additionalCorrection()
- + indexCorrections.additionalCorrection()
- - targetVectors.getCentroidDP();
- if (similarityFunction == MAXIMUM_INNER_PRODUCT) {
- return VectorUtil.scaleMaxInnerProductScore(score);
- }
- return Math.max((1f + score) / 2f, 0);
- }
- }
}
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102RWHnswBinaryQuantizedVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102RWHnswBinaryQuantizedVectorsFormat.java
index 9b175b86ffe..caeab3a308e 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102RWHnswBinaryQuantizedVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/Lucene102RWHnswBinaryQuantizedVectorsFormat.java
@@ -54,6 +54,13 @@ public class Lucene102RWHnswBinaryQuantizedVectorsFormat
@Override
public KnnVectorsWriter fieldsWriter(SegmentWriteState state) throws IOException {
return new Lucene99HnswVectorsWriter(
- state, maxConn, beamWidth, writeFormat.fieldsWriter(state), numMergeWorkers, mergeExec, 0);
+ state,
+ maxConn,
+ beamWidth,
+ writeFormat,
+ writeFormat.fieldsWriter(state),
+ numMergeWorkers,
+ mergeExec,
+ 0);
}
}
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsWriter.java
index da62db66c89..b3192338bc0 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsWriter.java
@@ -45,6 +45,7 @@ import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.IORunnable;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.RamUsageEstimator;
@@ -385,7 +386,7 @@ public final class Lucene94HnswVectorsWriter extends KnnVectorsWriter {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES);
IndexOutput tempVectorData =
segmentWriteState.directory.createTempOutput(
@@ -484,6 +485,7 @@ public final class Lucene94HnswVectorsWriter extends KnnVectorsWriter {
segmentWriteState.directory, tempVectorData.getName());
}
}
+ return null;
}
private void writeGraph(OnHeapHnswGraph graph) throws IOException {
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsWriter.java
index 75abbb3e60b..bce1ae8986a 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsWriter.java
@@ -48,6 +48,7 @@ import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.IORunnable;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.RamUsageEstimator;
@@ -411,7 +412,7 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES);
IndexOutput tempVectorData =
segmentWriteState.directory.createTempOutput(
@@ -526,6 +527,7 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
segmentWriteState.directory, tempVectorData.getName());
}
}
+ return null;
}
/**
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99RWV0HnswScalarQuantizationVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99RWV0HnswScalarQuantizationVectorsFormat.java
index 42a2d85213c..04032d3fa56 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99RWV0HnswScalarQuantizationVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99RWV0HnswScalarQuantizationVectorsFormat.java
@@ -45,6 +45,7 @@ class Lucene99RWV0HnswScalarQuantizationVectorsFormat
state,
Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN,
Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH,
+ flatVectorsFormat,
flatVectorsFormat.fieldsWriter(state),
1,
null,
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99RWV1HnswScalarQuantizationVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99RWV1HnswScalarQuantizationVectorsFormat.java
index 3f72ef3d6a2..c31e139658f 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99RWV1HnswScalarQuantizationVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99RWV1HnswScalarQuantizationVectorsFormat.java
@@ -55,6 +55,7 @@ class Lucene99RWV1HnswScalarQuantizationVectorsFormat
state,
Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN,
Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH,
+ flatVectorsFormat,
flatVectorsFormat.fieldsWriter(state),
1,
null,
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java
index 54424b2915d..331b14ac18e 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java
@@ -53,7 +53,6 @@ import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.internal.hppc.IntArrayList;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.VectorScorer;
-import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
@@ -219,8 +218,9 @@ public final class Lucene99ScalarQuantizedVectorsWriter extends FlatVectorsWrite
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
+ public void mergeOneFlatVectorField(FieldInfo fieldInfo, MergeState mergeState)
+ throws IOException {
+ rawVectorDelegate.mergeOneFlatVectorField(fieldInfo, mergeState);
// Since we know we will not be searching for additional indexing, we can just write the
// vectors directly to the new segment.
// No need to use temporary file as we don't have to re-open for reading
@@ -248,23 +248,6 @@ public final class Lucene99ScalarQuantizedVectorsWriter extends FlatVectorsWrite
}
}
- @Override
- public CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
- FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- if (fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
- // Simply merge the underlying delegate, which just copies the raw vector data to a new
- // segment file
- rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
- ScalarQuantizer mergedQuantizationState =
- mergeAndRecalculateQuantiles(mergeState, fieldInfo, confidenceInterval, bits);
- return mergeOneFieldToIndex(
- segmentWriteState, fieldInfo, mergeState, mergedQuantizationState);
- }
- // We only merge the delegate, since the field type isn't float32, quantization wasn't
- // supported, so bypass it.
- return rawVectorDelegate.mergeOneFieldToIndex(fieldInfo, mergeState);
- }
-
@Override
public void flush(int maxDoc, Sorter.DocMap sortMap) throws IOException {
rawVectorDelegate.flush(maxDoc, sortMap);
@@ -457,81 +440,6 @@ public final class Lucene99ScalarQuantizedVectorsWriter extends FlatVectorsWrite
}
}
- private ScalarQuantizedCloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
- SegmentWriteState segmentWriteState,
- FieldInfo fieldInfo,
- MergeState mergeState,
- ScalarQuantizer mergedQuantizationState)
- throws IOException {
- if (segmentWriteState.infoStream.isEnabled(QUANTIZED_VECTOR_COMPONENT)) {
- segmentWriteState.infoStream.message(
- QUANTIZED_VECTOR_COMPONENT,
- "quantized field="
- + " confidenceInterval="
- + confidenceInterval
- + " minQuantile="
- + mergedQuantizationState.getLowerQuantile()
- + " maxQuantile="
- + mergedQuantizationState.getUpperQuantile());
- }
- long vectorDataOffset = quantizedVectorData.alignFilePointer(Float.BYTES);
- IndexOutput tempQuantizedVectorData =
- segmentWriteState.directory.createTempOutput(
- quantizedVectorData.getName(), "temp", segmentWriteState.context);
- IndexInput quantizationDataInput = null;
- try {
- MergedQuantizedVectorValues byteVectorValues =
- MergedQuantizedVectorValues.mergeQuantizedByteVectorValues(
- fieldInfo, mergeState, mergedQuantizationState);
- DocsWithFieldSet docsWithField =
- writeQuantizedVectorData(tempQuantizedVectorData, byteVectorValues, bits, compress);
- CodecUtil.writeFooter(tempQuantizedVectorData);
- IOUtils.close(tempQuantizedVectorData);
- quantizationDataInput =
- segmentWriteState.directory.openInput(
- tempQuantizedVectorData.getName(), segmentWriteState.context);
- quantizedVectorData.copyBytes(
- quantizationDataInput, quantizationDataInput.length() - CodecUtil.footerLength());
- long vectorDataLength = quantizedVectorData.getFilePointer() - vectorDataOffset;
- CodecUtil.retrieveChecksum(quantizationDataInput);
- writeMeta(
- fieldInfo,
- segmentWriteState.segmentInfo.maxDoc(),
- vectorDataOffset,
- vectorDataLength,
- confidenceInterval,
- bits,
- compress,
- mergedQuantizationState.getLowerQuantile(),
- mergedQuantizationState.getUpperQuantile(),
- docsWithField);
- final IndexInput finalQuantizationDataInput = quantizationDataInput;
- quantizationDataInput = null;
-
- return new ScalarQuantizedCloseableRandomVectorScorerSupplier(
- () -> {
- IOUtils.close(finalQuantizationDataInput);
- segmentWriteState.directory.deleteFile(tempQuantizedVectorData.getName());
- },
- docsWithField.cardinality(),
- vectorsScorer.getRandomVectorScorerSupplier(
- fieldInfo.getVectorSimilarityFunction(),
- new OffHeapQuantizedByteVectorValues.DenseOffHeapVectorValues(
- fieldInfo.getVectorDimension(),
- docsWithField.cardinality(),
- mergedQuantizationState,
- compress,
- fieldInfo.getVectorSimilarityFunction(),
- vectorsScorer,
- finalQuantizationDataInput)));
- } catch (Throwable t) {
- IOUtils.closeWhileSuppressingExceptions(t, tempQuantizedVectorData, quantizationDataInput);
- IOUtils.deleteFilesSuppressingExceptions(
- t, segmentWriteState.directory, tempQuantizedVectorData.getName());
- throw t;
- }
- }
-
static ScalarQuantizer mergeQuantiles(
List<ScalarQuantizer> quantizationStates, IntArrayList segmentSizes, byte bits) {
assert quantizationStates.size() == segmentSizes.size();
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/HnswBitVectorsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/HnswBitVectorsFormat.java
index f5888c0a03c..b8f8f1b5b26 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/HnswBitVectorsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/HnswBitVectorsFormat.java
@@ -41,6 +41,7 @@ import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Sorter;
import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.search.TaskExecutor;
+import org.apache.lucene.util.IORunnable;
import org.apache.lucene.util.hnsw.HnswGraph;
/**
@@ -138,6 +139,7 @@ public final class HnswBitVectorsFormat extends KnnVectorsFormat {
state,
maxConn,
beamWidth,
+ flatVectorsFormat,
flatVectorsFormat.fieldsWriter(state),
numMergeWorkers,
mergeExec));
@@ -172,8 +174,8 @@ public final class HnswBitVectorsFormat extends KnnVectorsFormat {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- delegate.mergeOneField(fieldInfo, mergeState);
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ return delegate.mergeOneField(fieldInfo, mergeState);
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/BufferingKnnVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/BufferingKnnVectorsWriter.java
index 96b0f75a259..32df27bad71 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/BufferingKnnVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/BufferingKnnVectorsWriter.java
@@ -31,6 +31,7 @@ import org.apache.lucene.index.SortingCodecReader;
import org.apache.lucene.index.SortingCodecReader.SortingValuesIterator;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.IORunnable;
import org.apache.lucene.util.RamUsageEstimator;
/**
@@ -195,7 +196,7 @@ public abstract class BufferingKnnVectorsWriter extends KnnVectorsWriter {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
switch (fieldInfo.getVectorEncoding()) {
case FLOAT32:
FloatVectorValues floatVectorValues =
@@ -208,6 +209,7 @@ public abstract class BufferingKnnVectorsWriter extends KnnVectorsWriter {
writeField(fieldInfo, byteVectorValues, mergeState.segmentInfo.maxDoc());
break;
}
+ return null;
}
/** Write the provided float vector field */
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsWriter.java
index feb9aaff9e8..21aac8d972e 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsWriter.java
@@ -39,6 +39,7 @@ import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.VectorScorer;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.IOFunction;
+import org.apache.lucene.util.IORunnable;
/** Writes vectors to an index. */
public abstract class KnnVectorsWriter implements Accountable, Closeable {
@@ -52,9 +53,25 @@ public abstract class KnnVectorsWriter implements Accountable, Closeable {
/** Flush all buffered data on disk * */
public abstract void flush(int maxDoc, Sorter.DocMap sortMap) throws IOException;
- /** Write field for merging */
+ /** Called once at the end before close */
+ public abstract void finish() throws IOException;
+
+ /**
+ * Merges vectors for a single field, returning a runnable for any deferred work (e.g., HNSW graph
+ * construction). The default implementation merges naively the vectors and returns {@code null}
+ * (no deferred work).
+ *
+ * <p>Subclasses should override this method may implement a two-phase merge strategy where flat
+ * vectors are written in the first phase and additional indexing structures (like HNSW graphs)
+ * are built in the second phase using the already-written flat vector data.
+ *
+ * @param fieldInfo the field to merge
+ * @param mergeState the merge state
+ * @return a runnable to execute in phase 2, or {@code null} if there is no deferred work
+ * @throws IOException if an I/O error occurs
+ */
@SuppressWarnings("unchecked")
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
switch (fieldInfo.getVectorEncoding()) {
case BYTE -> {
KnnFieldVectorsWriter<byte[]> byteWriter =
@@ -77,15 +94,18 @@ public abstract class KnnVectorsWriter implements Accountable, Closeable {
}
}
}
+ return null;
}
- /** Called once at the end before close */
- public abstract void finish() throws IOException;
-
/**
- * Merges the segment vectors for all fields. This default implementation delegates to {@link
- * #mergeOneField}, passing a {@link KnnVectorsReader} that combines the vector values and ignores
- * deleted documents.
+ * Merges the segment vectors for all fields using a two-phase strategy:
+ *
+ * <ol>
+ * <li>Phase 1: Merge flat vectors for all fields by calling {@link #mergeOneField(FieldInfo,
+ * MergeState)}, collecting deferred work (runnables) for each field.
+ * <li>Phase 2: Execute the deferred runnables (e.g., HNSW graph construction) using the flat
+ * vector data written in phase 1.
+ * </ol>
*/
public final void merge(MergeState mergeState) throws IOException {
for (int i = 0; i < mergeState.fieldInfos.length; i++) {
@@ -96,19 +116,38 @@ public abstract class KnnVectorsWriter implements Accountable, Closeable {
}
}
+ // Phase 1: merge flat vectors for all fields, collecting deferred work
+ List<IORunnable> deferredWork = new ArrayList<>();
for (FieldInfo fieldInfo : mergeState.mergeFieldInfos) {
if (fieldInfo.hasVectorValues()) {
if (mergeState.infoStream.isEnabled("VV")) {
mergeState.infoStream.message("VV", "merging " + mergeState.segmentInfo);
}
- mergeOneField(fieldInfo, mergeState);
+ IORunnable deferred = mergeOneField(fieldInfo, mergeState);
+ if (deferred != null) {
+ deferredWork.add(deferred);
+ }
if (mergeState.infoStream.isEnabled("VV")) {
mergeState.infoStream.message("VV", "merge done " + mergeState.segmentInfo);
}
}
}
+
+ // Phase 2: execute deferred work (e.g., graph construction using the written flat vectors)
+ for (IORunnable runnable : deferredWork) {
+ if (mergeState.infoStream.isEnabled("VV")) {
+ mergeState.infoStream.message("VV", "merging deferred work" + mergeState.segmentInfo);
+ }
+
+ runnable.run();
+
+ if (mergeState.infoStream.isEnabled("VV")) {
+ mergeState.infoStream.message("VV", "merge deferred work done " + mergeState.segmentInfo);
+ }
+ }
+
finish();
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsWriter.java
index 37c4f546bab..4b0ff173065 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsWriter.java
@@ -21,7 +21,7 @@ import java.io.IOException;
import org.apache.lucene.codecs.KnnVectorsWriter;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.MergeState;
-import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
+import org.apache.lucene.util.IORunnable;
/**
* Vectors' writer for a field that allows additional indexing logic to be implemented by the caller
@@ -54,16 +54,13 @@ public abstract class FlatVectorsWriter extends KnnVectorsWriter {
@Override
public abstract FlatFieldVectorsWriter<?> addField(FieldInfo fieldInfo) throws IOException;
- /**
- * Write the field for merging, providing a scorer over the newly merged flat vectors. This way
- * any additional merging logic can be implemented by the user of this class.
- *
- * @param fieldInfo fieldInfo of the field to merge
- * @param mergeState mergeState of the segments to merge
- * @return a scorer over the newly merged flat vectors, which should be closed as it holds a
- * temporary file handle to read over the newly merged vectors
- * @throws IOException if an I/O error occurs when merging
- */
- public abstract CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
- FieldInfo fieldInfo, MergeState mergeState) throws IOException;
+ @Override
+ public final IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState)
+ throws IOException {
+ mergeOneFlatVectorField(fieldInfo, mergeState);
+ return null;
+ }
+
+ public abstract void mergeOneFlatVectorField(FieldInfo fieldInfo, MergeState mergeState)
+ throws IOException;
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104HnswScalarQuantizedVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104HnswScalarQuantizedVectorsFormat.java
index 4fd3dd6dbcf..c7f73cbaa67 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104HnswScalarQuantizedVectorsFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104HnswScalarQuantizedVectorsFormat.java
@@ -193,6 +193,7 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormat
state,
maxConn,
beamWidth,
+ flatVectorsFormat,
flatVectorsFormat.fieldsWriter(state),
numMergeWorkers,
mergeExec,
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java
index 4954cffc648..15fe4950036 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java
@@ -19,6 +19,8 @@ package org.apache.lucene.codecs.lucene104;
import static org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorsFormat.VECTOR_DATA_EXTENSION;
import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader.readSimilarityFunction;
import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader.readVectorEncoding;
+import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
+import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.transposeHalfByte;
import java.io.IOException;
import java.util.HashMap;
@@ -31,11 +33,14 @@ import org.apache.lucene.codecs.hnsw.FlatVectorsReader;
import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.AcceptDocs;
@@ -47,10 +52,13 @@ import org.apache.lucene.store.FileDataHint;
import org.apache.lucene.store.FileTypeHint;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.Bits;
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.quantization.OptimizedScalarQuantizer;
import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
import org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
@@ -437,6 +445,113 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader
return null;
}
+ @Override
+ public CloseableRandomVectorScorerSupplier getRandomVectorScorerSupplierForMerge(
+ FieldInfo fieldInfo, SegmentWriteState segmentWriteState) throws IOException {
+ FieldEntry fi = fields.get(fieldInfo.name);
+ if (fi == null) {
+ return null;
+ }
+ QuantizedByteVectorValues vectorValues = getQuantizedVectorValues(fieldInfo.name);
+ if (fi.scalarEncoding.isAsymmetric() == false) {
+ RandomVectorScorerSupplier supplier =
+ vectorScorer.getRandomVectorScorerSupplier(
+ fieldInfo.getVectorSimilarityFunction(), vectorValues);
+ return CloseableRandomVectorScorerSupplier.create(supplier, vectorValues.size(), () -> {});
+ }
+ FloatVectorValues floatVectorValues = getFloatVectorValues(fieldInfo.name);
+ OptimizedScalarQuantizer quantizer =
+ new OptimizedScalarQuantizer(fieldInfo.getVectorSimilarityFunction());
+ String tempScoreQuantizedVectorName = null;
+ DocsWithFieldSet docsWithField;
+ try (IndexOutput tempScoreQuantizedVector =
+ segmentWriteState.directory.createTempOutput(
+ segmentWriteState.segmentInfo.name, "queries", segmentWriteState.context)) {
+ tempScoreQuantizedVectorName = tempScoreQuantizedVector.getName();
+ docsWithField =
+ writeBinarizedQueryData(
+ vectorValues,
+ fi.scalarEncoding,
+ tempScoreQuantizedVector,
+ floatVectorValues,
+ quantizer);
+ CodecUtil.writeFooter(tempScoreQuantizedVector);
+ } catch (Throwable t) {
+ if (tempScoreQuantizedVectorName != null) {
+ IOUtils.deleteFilesSuppressingExceptions(
+ t, segmentWriteState.directory, tempScoreQuantizedVectorName);
+ }
+ throw t;
+ }
+ IndexInput quantizedScoreDataInput =
+ segmentWriteState.directory.openInput(
+ tempScoreQuantizedVectorName, segmentWriteState.context);
+ try {
+ OffHeapScalarQuantizedVectorValues scoreVectorValues =
+ new OffHeapScalarQuantizedVectorValues.DenseOffHeapVectorValues(
+ true,
+ fieldInfo.getVectorDimension(),
+ docsWithField.cardinality(),
+ vectorValues.getCentroid(),
+ vectorValues.getCentroidDP(),
+ quantizer,
+ fi.scalarEncoding,
+ fieldInfo.getVectorSimilarityFunction(),
+ vectorScorer,
+ quantizedScoreDataInput);
+ RandomVectorScorerSupplier scorerSupplier =
+ vectorScorer.getRandomVectorScorerSupplier(
+ fieldInfo.getVectorSimilarityFunction(), scoreVectorValues, vectorValues);
+ final String finalTempScoreQuantizedVectorName = tempScoreQuantizedVectorName;
+ return CloseableRandomVectorScorerSupplier.create(
+ scorerSupplier,
+ vectorValues.size(),
+ () -> {
+ IOUtils.close(quantizedScoreDataInput);
+ IOUtils.deleteFilesIgnoringExceptions(
+ segmentWriteState.directory, finalTempScoreQuantizedVectorName);
+ });
+ } catch (Throwable t) {
+ IOUtils.closeWhileSuppressingExceptions(t, quantizedScoreDataInput);
+ throw t;
+ }
+ }
+
+ static DocsWithFieldSet writeBinarizedQueryData(
+ QuantizedByteVectorValues quantizedByteVectorValues,
+ ScalarEncoding encoding,
+ IndexOutput binarizedQueryData,
+ FloatVectorValues floatVectorValues,
+ OptimizedScalarQuantizer binaryQuantizer)
+ throws IOException {
+ if (encoding.isAsymmetric() == false) {
+ throw new IllegalArgumentException("encoding and queryEncoding must be different");
+ }
+ DocsWithFieldSet docsWithField = new DocsWithFieldSet();
+ int discretizedDims = encoding.getDiscreteDimensions(floatVectorValues.dimension());
+ byte[] quantizationScratch = new byte[discretizedDims];
+ byte[] toQuery = new byte[encoding.getQueryPackedLength(discretizedDims)];
+ KnnVectorValues.DocIndexIterator iterator = floatVectorValues.iterator();
+ for (int docV = iterator.nextDoc(); docV != NO_MORE_DOCS; docV = iterator.nextDoc()) {
+ // write index vector
+ OptimizedScalarQuantizer.QuantizationResult r =
+ binaryQuantizer.scalarQuantize(
+ floatVectorValues.vectorValue(iterator.index()),
+ quantizationScratch,
+ encoding.getQueryBits(),
+ quantizedByteVectorValues.getCentroid());
+ docsWithField.add(docV);
+ // pack and store the 4bit query vector
+ transposeHalfByte(quantizationScratch, toQuery);
+ binarizedQueryData.writeBytes(toQuery, toQuery.length);
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.lowerInterval()));
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.upperInterval()));
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.additionalCorrection()));
+ binarizedQueryData.writeInt(r.quantizedComponentSum());
+ }
+ return docsWithField;
+ }
+
private record FieldEntry(
VectorSimilarityFunction similarityFunction,
VectorEncoding vectorEncoding,
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java
index d591aa0a7e7..5373ff85be3 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java
@@ -21,11 +21,8 @@ import static org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectors
import static org.apache.lucene.index.VectorSimilarityFunction.COSINE;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import static org.apache.lucene.util.RamUsageEstimator.shallowSizeOfInstance;
-import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.packAsBinary;
-import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.transposeDibit;
import static org.apache.lucene.util.quantization.OptimizedScalarQuantizer.transposeHalfByte;
-import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -50,13 +47,9 @@ import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.internal.hppc.FloatArrayList;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.VectorScorer;
-import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.VectorUtil;
-import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
-import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
-import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
import org.apache.lucene.util.quantization.OptimizedScalarQuantizer;
import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
import org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
@@ -75,7 +68,6 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {
private final IndexOutput meta, vectorData;
private final ScalarEncoding encoding;
private final FlatVectorsWriter rawVectorDelegate;
- private final Lucene104ScalarQuantizedVectorScorer vectorsScorer;
private boolean finished;
/** Sole constructor */
@@ -87,7 +79,6 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {
throws IOException {
super(vectorsScorer);
this.encoding = encoding;
- this.vectorsScorer = vectorsScorer;
this.segmentWriteState = state;
String metaFileName =
IndexFileNames.segmentFileName(
@@ -328,17 +319,16 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public void mergeOneFlatVectorField(FieldInfo fieldInfo, MergeState mergeState)
+ throws IOException {
+ // Don't need access to the random vectors, we can just use the merged
+ rawVectorDelegate.mergeOneFlatVectorField(fieldInfo, mergeState);
if (!fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
- rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
return;
}
-
final float[] centroid;
final float[] mergedCentroid = new float[fieldInfo.getVectorDimension()];
int vectorCount = mergeAndRecalculateCentroids(mergeState, fieldInfo, mergedCentroid);
- // Don't need access to the random vectors, we can just use the merged
- rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
centroid = mergedCentroid;
if (segmentWriteState.infoStream.isEnabled(QUANTIZED_VECTOR_COMPONENT)) {
segmentWriteState.infoStream.message(
@@ -389,12 +379,11 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {
return docsWithField;
}
- static DocsWithFieldSet writeBinarizedVectorAndQueryData(
- IndexOutput binarizedVectorData,
+ static DocsWithFieldSet writeBinarizedQueryData(
+ QuantizedByteVectorValues quantizedByteVectorValues,
ScalarEncoding encoding,
IndexOutput binarizedQueryData,
FloatVectorValues floatVectorValues,
- float[] centroid,
OptimizedScalarQuantizer binaryQuantizer)
throws IOException {
if (encoding.isAsymmetric() == false) {
@@ -402,207 +391,29 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {
}
DocsWithFieldSet docsWithField = new DocsWithFieldSet();
int discretizedDims = encoding.getDiscreteDimensions(floatVectorValues.dimension());
- byte[][] quantizationScratch = new byte[2][];
- quantizationScratch[0] = new byte[discretizedDims];
- quantizationScratch[1] = new byte[discretizedDims];
- byte[] toIndex = new byte[encoding.getDocPackedLength(discretizedDims)];
+ byte[] quantizationScratch = new byte[discretizedDims];
byte[] toQuery = new byte[encoding.getQueryPackedLength(discretizedDims)];
KnnVectorValues.DocIndexIterator iterator = floatVectorValues.iterator();
for (int docV = iterator.nextDoc(); docV != NO_MORE_DOCS; docV = iterator.nextDoc()) {
// write index vector
- OptimizedScalarQuantizer.QuantizationResult[] r =
- binaryQuantizer.multiScalarQuantize(
+ OptimizedScalarQuantizer.QuantizationResult r =
+ binaryQuantizer.scalarQuantize(
floatVectorValues.vectorValue(iterator.index()),
quantizationScratch,
- new byte[] {encoding.getBits(), encoding.getQueryBits()},
- centroid);
- // pack and store document vector based on encoding type
- switch (encoding) {
- case SINGLE_BIT_QUERY_NIBBLE -> packAsBinary(quantizationScratch[0], toIndex);
- case DIBIT_QUERY_NIBBLE -> transposeDibit(quantizationScratch[0], toIndex);
- case PACKED_NIBBLE, UNSIGNED_BYTE, SEVEN_BIT ->
- throw new IllegalArgumentException("Unsupported asymmetric encoding: " + encoding);
- }
- binarizedVectorData.writeBytes(toIndex, toIndex.length);
- binarizedVectorData.writeInt(Float.floatToIntBits(r[0].lowerInterval()));
- binarizedVectorData.writeInt(Float.floatToIntBits(r[0].upperInterval()));
- binarizedVectorData.writeInt(Float.floatToIntBits(r[0].additionalCorrection()));
- binarizedVectorData.writeInt(r[0].quantizedComponentSum());
+ encoding.getQueryBits(),
+ quantizedByteVectorValues.getCentroid());
docsWithField.add(docV);
-
// pack and store the 4bit query vector
- transposeHalfByte(quantizationScratch[1], toQuery);
+ transposeHalfByte(quantizationScratch, toQuery);
binarizedQueryData.writeBytes(toQuery, toQuery.length);
- binarizedQueryData.writeInt(Float.floatToIntBits(r[1].lowerInterval()));
- binarizedQueryData.writeInt(Float.floatToIntBits(r[1].upperInterval()));
- binarizedQueryData.writeInt(Float.floatToIntBits(r[1].additionalCorrection()));
- binarizedQueryData.writeInt(r[1].quantizedComponentSum());
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.lowerInterval()));
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.upperInterval()));
+ binarizedQueryData.writeInt(Float.floatToIntBits(r.additionalCorrection()));
+ binarizedQueryData.writeInt(r.quantizedComponentSum());
}
return docsWithField;
}
- @Override
- public CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
- FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- if (!fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
- return rawVectorDelegate.mergeOneFieldToIndex(fieldInfo, mergeState);
- }
-
- final float[] centroid;
- final float cDotC;
- final float[] mergedCentroid = new float[fieldInfo.getVectorDimension()];
- int vectorCount = mergeAndRecalculateCentroids(mergeState, fieldInfo, mergedCentroid);
-
- // Don't need access to the random vectors, we can just use the merged
- rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
- centroid = mergedCentroid;
- cDotC = vectorCount > 0 ? VectorUtil.dotProduct(centroid, centroid) : 0;
- if (segmentWriteState.infoStream.isEnabled(QUANTIZED_VECTOR_COMPONENT)) {
- segmentWriteState.infoStream.message(
- QUANTIZED_VECTOR_COMPONENT, "Vectors' count:" + vectorCount);
- }
- return mergeOneFieldToIndex(segmentWriteState, fieldInfo, mergeState, centroid, cDotC);
- }
-
- private CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
- SegmentWriteState segmentWriteState,
- FieldInfo fieldInfo,
- MergeState mergeState,
- float[] centroid,
- float cDotC)
- throws IOException {
- long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES);
- IndexOutput tempQuantizedVectorData = null;
- IndexOutput tempScoreQuantizedVectorData = null;
- IndexInput quantizedDataInput = null;
- IndexInput quantizedScoreDataInput = null;
- OptimizedScalarQuantizer quantizer =
- new OptimizedScalarQuantizer(fieldInfo.getVectorSimilarityFunction());
- try {
- tempQuantizedVectorData =
- segmentWriteState.directory.createTempOutput(
- vectorData.getName(), "temp", segmentWriteState.context);
- final String tempQuantizedVectorName = tempQuantizedVectorData.getName();
- final String tempScoreQuantizedVectorName;
- if (encoding.isAsymmetric()) {
- tempScoreQuantizedVectorData =
- segmentWriteState.directory.createTempOutput(
- vectorData.getName() + "_score", "temp", segmentWriteState.context);
- tempScoreQuantizedVectorName = tempScoreQuantizedVectorData.getName();
- } else {
- tempScoreQuantizedVectorName = null;
- }
- FloatVectorValues floatVectorValues =
- MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState);
- if (fieldInfo.getVectorSimilarityFunction() == COSINE) {
- floatVectorValues = new NormalizedFloatVectorValues(floatVectorValues);
- }
- DocsWithFieldSet docsWithField =
- encoding.isAsymmetric()
- ? writeBinarizedVectorAndQueryData(
- tempQuantizedVectorData,
- encoding,
- tempScoreQuantizedVectorData,
- floatVectorValues,
- centroid,
- quantizer)
- : writeVectorData(
- tempQuantizedVectorData,
- new QuantizedFloatVectorValues(floatVectorValues, quantizer, encoding, centroid));
- CodecUtil.writeFooter(tempQuantizedVectorData);
- IOUtils.close(tempQuantizedVectorData);
- quantizedDataInput =
- segmentWriteState.directory.openInput(tempQuantizedVectorName, segmentWriteState.context);
- vectorData.copyBytes(
- quantizedDataInput, quantizedDataInput.length() - CodecUtil.footerLength());
- long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
- CodecUtil.retrieveChecksum(quantizedDataInput);
- if (tempScoreQuantizedVectorData != null) {
- CodecUtil.writeFooter(tempScoreQuantizedVectorData);
- IOUtils.close(tempScoreQuantizedVectorData);
- quantizedScoreDataInput =
- segmentWriteState.directory.openInput(
- tempScoreQuantizedVectorName, segmentWriteState.context);
- }
- writeMeta(
- fieldInfo,
- segmentWriteState.segmentInfo.maxDoc(),
- vectorDataOffset,
- vectorDataLength,
- centroid,
- cDotC,
- docsWithField);
-
- final IndexInput finalQuantizedDataInput = quantizedDataInput;
- final IndexInput finalQuantizedScoreDataInput = quantizedScoreDataInput;
- tempQuantizedVectorData = null;
- tempScoreQuantizedVectorData = null;
- quantizedDataInput = null;
- quantizedScoreDataInput = null;
-
- OffHeapScalarQuantizedVectorValues vectorValues =
- new OffHeapScalarQuantizedVectorValues.DenseOffHeapVectorValues(
- fieldInfo.getVectorDimension(),
- docsWithField.cardinality(),
- centroid,
- cDotC,
- quantizer,
- encoding,
- fieldInfo.getVectorSimilarityFunction(),
- vectorsScorer,
- finalQuantizedDataInput);
- OffHeapScalarQuantizedVectorValues scoreVectorValues = null;
- if (finalQuantizedScoreDataInput != null) {
- scoreVectorValues =
- new OffHeapScalarQuantizedVectorValues.DenseOffHeapVectorValues(
- true,
- fieldInfo.getVectorDimension(),
- docsWithField.cardinality(),
- centroid,
- cDotC,
- quantizer,
- encoding,
- fieldInfo.getVectorSimilarityFunction(),
- vectorsScorer,
- finalQuantizedScoreDataInput);
- }
- RandomVectorScorerSupplier scorerSupplier =
- scoreVectorValues == null
- ? vectorsScorer.getRandomVectorScorerSupplier(
- fieldInfo.getVectorSimilarityFunction(), vectorValues)
- : vectorsScorer.getRandomVectorScorerSupplier(
- fieldInfo.getVectorSimilarityFunction(), scoreVectorValues, vectorValues);
- return new QuantizedCloseableRandomVectorScorerSupplier(
- scorerSupplier,
- vectorValues,
- () -> {
- IOUtils.close(finalQuantizedDataInput, finalQuantizedScoreDataInput);
- if (tempScoreQuantizedVectorName != null) {
- IOUtils.deleteFilesIgnoringExceptions(
- segmentWriteState.directory, tempScoreQuantizedVectorName);
- }
- IOUtils.deleteFilesIgnoringExceptions(
- segmentWriteState.directory, tempQuantizedVectorName);
- });
- } catch (Throwable t) {
- IOUtils.closeWhileSuppressingExceptions(
- t,
- tempQuantizedVectorData,
- tempScoreQuantizedVectorData,
- quantizedDataInput,
- quantizedScoreDataInput);
- if (tempQuantizedVectorData != null) {
- IOUtils.deleteFilesSuppressingExceptions(
- t, segmentWriteState.directory, tempQuantizedVectorData.getName());
- }
- if (tempScoreQuantizedVectorData != null) {
- IOUtils.deleteFilesSuppressingExceptions(
- t, segmentWriteState.directory, tempScoreQuantizedVectorData.getName());
- }
- throw t;
- }
- }
-
@Override
public void close() throws IOException {
IOUtils.close(meta, vectorData, rawVectorDelegate);
@@ -898,40 +709,6 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {
}
}
- static class QuantizedCloseableRandomVectorScorerSupplier
- implements CloseableRandomVectorScorerSupplier {
- private final RandomVectorScorerSupplier supplier;
- private final KnnVectorValues vectorValues;
- private final Closeable onClose;
-
- QuantizedCloseableRandomVectorScorerSupplier(
- RandomVectorScorerSupplier supplier, KnnVectorValues vectorValues, Closeable onClose) {
- this.supplier = supplier;
- this.onClose = onClose;
- this.vectorValues = vectorValues;
- }
-
- @Override
- public UpdateableRandomVectorScorer scorer() throws IOException {
- return supplier.scorer();
- }
-
- @Override
- public RandomVectorScorerSupplier copy() throws IOException {
- return supplier.copy();
- }
-
- @Override
- public void close() throws IOException {
- onClose.close();
- }
-
- @Override
- public int totalVectorCount() {
- return vectorValues.size();
- }
- }
-
static final class NormalizedFloatVectorValues extends FloatVectorValues {
private final FloatVectorValues values;
private final float[] normalizedVector;
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 3416a131735..20565e0f17f 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
@@ -20,7 +20,6 @@ package org.apache.lucene.codecs.lucene99;
import static org.apache.lucene.codecs.lucene99.Lucene99FlatVectorsFormat.DIRECT_MONOTONIC_BLOCK_SHIFT;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
-import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -31,8 +30,6 @@ import org.apache.lucene.codecs.KnnVectorsWriter;
import org.apache.lucene.codecs.hnsw.FlatFieldVectorsWriter;
import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
import org.apache.lucene.codecs.hnsw.FlatVectorsWriter;
-import org.apache.lucene.codecs.lucene95.OffHeapByteVectorValues;
-import org.apache.lucene.codecs.lucene95.OffHeapFloatVectorValues;
import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.DocsWithFieldSet;
@@ -44,18 +41,10 @@ import org.apache.lucene.index.MergeState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Sorter;
import org.apache.lucene.index.VectorEncoding;
-import org.apache.lucene.store.DataAccessHint;
-import org.apache.lucene.store.FileDataHint;
-import org.apache.lucene.store.FileTypeHint;
-import org.apache.lucene.store.IOContext;
-import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
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.RandomVectorScorerSupplier;
-import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
/**
* Writes vector values to index segments.
@@ -229,7 +218,8 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public void mergeOneFlatVectorField(FieldInfo fieldInfo, MergeState mergeState)
+ throws IOException {
// Since we know we will not be searching for additional indexing, we can just write the
// the vectors directly to the new segment.
VectorEncoding encoding = fieldInfo.getVectorEncoding();
@@ -256,93 +246,6 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
docsWithField);
}
- @Override
- public CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
- FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- VectorEncoding encoding = fieldInfo.getVectorEncoding();
- long vectorDataOffset = alignOutput(vectorData, encoding);
- IndexOutput tempVectorData =
- segmentWriteState.directory.createTempOutput(
- vectorData.getName(), "temp", segmentWriteState.context);
- IndexInput vectorDataInput = null;
- try {
- // write the vector data to a temporary file
- DocsWithFieldSet docsWithField =
- switch (encoding) {
- case BYTE ->
- writeByteVectorData(
- tempVectorData,
- KnnVectorsWriter.MergedVectorValues.mergeByteVectorValues(
- fieldInfo, mergeState));
- case FLOAT32 ->
- writeVectorData(
- tempVectorData,
- KnnVectorsWriter.MergedVectorValues.mergeFloatVectorValues(
- fieldInfo, mergeState));
- };
- CodecUtil.writeFooter(tempVectorData);
- IOUtils.close(tempVectorData);
-
- // This temp file will be accessed in a random-access fashion to construct the HNSW graph.
- // Note: don't use the context from the state, which is a flush/merge context, not expecting
- // to perform random reads.
- vectorDataInput =
- segmentWriteState.directory.openInput(
- tempVectorData.getName(),
- IOContext.DEFAULT.withHints(
- FileTypeHint.DATA, FileDataHint.KNN_VECTORS, DataAccessHint.RANDOM));
- // copy the temporary file vectors to the actual data file
- vectorData.copyBytes(vectorDataInput, vectorDataInput.length() - CodecUtil.footerLength());
- CodecUtil.retrieveChecksum(vectorDataInput);
- long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
- writeMeta(
- fieldInfo,
- segmentWriteState.segmentInfo.maxDoc(),
- vectorDataOffset,
- vectorDataLength,
- docsWithField);
-
- final IndexInput finalVectorDataInput = vectorDataInput;
- vectorDataInput = null;
-
- final RandomVectorScorerSupplier randomVectorScorerSupplier =
- switch (encoding) {
- case BYTE ->
- vectorsScorer.getRandomVectorScorerSupplier(
- fieldInfo.getVectorSimilarityFunction(),
- new OffHeapByteVectorValues.DenseOffHeapVectorValues(
- fieldInfo.getVectorDimension(),
- docsWithField.cardinality(),
- finalVectorDataInput,
- fieldInfo.getVectorDimension() * Byte.BYTES,
- vectorsScorer,
- fieldInfo.getVectorSimilarityFunction()));
- case FLOAT32 ->
- vectorsScorer.getRandomVectorScorerSupplier(
- fieldInfo.getVectorSimilarityFunction(),
- new OffHeapFloatVectorValues.DenseOffHeapVectorValues(
- fieldInfo.getVectorDimension(),
- docsWithField.cardinality(),
- finalVectorDataInput,
- fieldInfo.getVectorDimension() * Float.BYTES,
- vectorsScorer,
- fieldInfo.getVectorSimilarityFunction()));
- };
- return new FlatCloseableRandomVectorScorerSupplier(
- () -> {
- IOUtils.close(finalVectorDataInput);
- segmentWriteState.directory.deleteFile(tempVectorData.getName());
- },
- docsWithField.cardinality(),
- randomVectorScorerSupplier);
- } catch (Throwable t) {
- IOUtils.closeWhileSuppressingExceptions(t, vectorDataInput, tempVectorData);
- IOUtils.deleteFilesSuppressingExceptions(
- t, segmentWriteState.directory, tempVectorData.getName());
- throw t;
- }
- }
-
private void writeMeta(
FieldInfo field,
int maxDoc,
@@ -500,39 +403,4 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
return finished;
}
}
-
- static final class FlatCloseableRandomVectorScorerSupplier
- implements CloseableRandomVectorScorerSupplier {
-
- private final RandomVectorScorerSupplier supplier;
- private final Closeable onClose;
- private final int numVectors;
-
- FlatCloseableRandomVectorScorerSupplier(
- Closeable onClose, int numVectors, RandomVectorScorerSupplier supplier) {
- this.onClose = onClose;
- this.supplier = supplier;
- this.numVectors = numVectors;
- }
-
- @Override
- public UpdateableRandomVectorScorer scorer() throws IOException {
- return supplier.scorer();
- }
-
- @Override
- public RandomVectorScorerSupplier copy() throws IOException {
- return supplier.copy();
- }
-
- @Override
- public void close() throws IOException {
- onClose.close();
- }
-
- @Override
- public int totalVectorCount() {
- return numVectors;
- }
- }
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsFormat.java
index be872dd729f..875a6325431 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsFormat.java
@@ -301,6 +301,7 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {
state,
maxConn,
beamWidth,
+ flatVectorsFormat,
flatVectorsFormat.fieldsWriter(state),
numMergeWorkers,
mergeExec,
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsReader.java
index 5aa8b165ac1..20a4300d824 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsReader.java
@@ -35,6 +35,7 @@ import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.internal.hppc.IntObjectHashMap;
@@ -54,6 +55,7 @@ import org.apache.lucene.util.GroupVIntUtil;
import org.apache.lucene.util.IOSupplier;
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.HnswGraph;
import org.apache.lucene.util.hnsw.HnswGraphSearcher;
import org.apache.lucene.util.hnsw.OrdinalTranslatedKnnCollector;
@@ -434,6 +436,15 @@ public final class Lucene99HnswVectorsReader extends KnnVectorsReader
return null;
}
+ @Override
+ public CloseableRandomVectorScorerSupplier getRandomVectorScorerSupplierForMerge(
+ FieldInfo fieldInfo, SegmentWriteState segmentWriteState) throws IOException {
+ if (flatVectorsReader instanceof QuantizedVectorsReader qvr) {
+ return qvr.getRandomVectorScorerSupplierForMerge(fieldInfo, segmentWriteState);
+ }
+ return null;
+ }
+
private record FieldEntry(
VectorSimilarityFunction similarityFunction,
VectorEncoding vectorEncoding,
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 d2526cff3ab..8882fc4f644 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
@@ -34,6 +34,8 @@ import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.KnnFieldVectorsWriter;
import org.apache.lucene.codecs.KnnVectorsWriter;
import org.apache.lucene.codecs.hnsw.FlatFieldVectorsWriter;
+import org.apache.lucene.codecs.hnsw.FlatVectorsFormat;
+import org.apache.lucene.codecs.hnsw.FlatVectorsReader;
import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
import org.apache.lucene.codecs.hnsw.FlatVectorsWriter;
import org.apache.lucene.index.ByteVectorValues;
@@ -43,11 +45,14 @@ import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.MergeState;
+import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Sorter;
+import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.TaskExecutor;
import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.IORunnable;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.RamUsageEstimator;
@@ -62,6 +67,7 @@ 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.packed.DirectMonotonicWriter;
+import org.apache.lucene.util.quantization.QuantizedVectorsReader;
/**
* Writes vector values and knn graphs to index segments.
@@ -77,6 +83,9 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
private final int M;
private final int beamWidth;
private final FlatVectorsWriter flatVectorWriter;
+ private final FlatVectorsFormat flatVectorsFormat;
+ private FlatVectorsReader flatVectorsReader;
+ private boolean flatWriterClosed = false;
private final int numMergeWorkers;
private final TaskExecutor mergeExec;
private final int tinySegmentsThreshold;
@@ -89,6 +98,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
SegmentWriteState state,
int M,
int beamWidth,
+ FlatVectorsFormat flatVectorsFormat,
FlatVectorsWriter flatVectorWriter,
int numMergeWorkers,
TaskExecutor mergeExec)
@@ -97,6 +107,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
state,
M,
beamWidth,
+ flatVectorsFormat,
flatVectorWriter,
numMergeWorkers,
mergeExec,
@@ -108,6 +119,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
SegmentWriteState state,
int M,
int beamWidth,
+ FlatVectorsFormat flatVectorsFormat,
FlatVectorsWriter flatVectorWriter,
int numMergeWorkers,
TaskExecutor mergeExec,
@@ -117,6 +129,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
state,
M,
beamWidth,
+ flatVectorsFormat,
flatVectorWriter,
numMergeWorkers,
mergeExec,
@@ -128,6 +141,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
SegmentWriteState state,
int M,
int beamWidth,
+ FlatVectorsFormat flatVectorsFormat,
FlatVectorsWriter flatVectorWriter,
int numMergeWorkers,
TaskExecutor mergeExec,
@@ -136,6 +150,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
throws IOException {
this.M = M;
this.flatVectorWriter = flatVectorWriter;
+ this.flatVectorsFormat = flatVectorsFormat;
this.beamWidth = beamWidth;
this.numMergeWorkers = numMergeWorkers;
this.mergeExec = mergeExec;
@@ -207,7 +222,9 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
throw new IllegalStateException("already finished");
}
finished = true;
- flatVectorWriter.finish();
+ if (flatWriterClosed == false) {
+ flatVectorWriter.finish();
+ }
if (meta != null) {
// write end of fields marker
@@ -401,65 +418,96 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- CloseableRandomVectorScorerSupplier scorerSupplier =
- flatVectorWriter.mergeOneFieldToIndex(fieldInfo, mergeState);
- try {
- long vectorIndexOffset = vectorIndex.getFilePointer();
- // build the graph using the temporary vector data
- // we use Lucene99HnswVectorsReader.DenseOffHeapVectorValues for the graph construction
- // doesn't need to know docIds
- OnHeapHnswGraph graph = null;
- int[][] vectorIndexNodeOffsets = null;
- // Check if we should bypass graph building for tiny segments
- boolean makeHnswGraph =
- scorerSupplier.totalVectorCount() > 0
- && (shouldCreateGraph(tinySegmentsThreshold, scorerSupplier.totalVectorCount()));
- if (makeHnswGraph) {
- // build graph
- HnswGraphMerger merger =
- createGraphMerger(
- fieldInfo,
- scorerSupplier,
- mergeState.intraMergeTaskExecutor == null
- ? null
- : new TaskExecutor(mergeState.intraMergeTaskExecutor),
- numMergeWorkers);
- for (int i = 0; i < mergeState.liveDocs.length; i++) {
- if (hasVectorValues(mergeState.fieldInfos[i], fieldInfo.name)) {
- merger.addReader(
- mergeState.knnVectorsReaders[i], mergeState.docMaps[i], mergeState.liveDocs[i]);
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ flatVectorWriter.mergeOneFlatVectorField(fieldInfo, mergeState);
+ return () -> {
+ // Lazily finish flat writer and open a reader for the written segment
+ ensureFlatReaderOpen();
+ // Get the vector values and scorer supplier from the written segment
+ KnnVectorValues vectorValues =
+ switch (fieldInfo.getVectorEncoding()) {
+ case BYTE -> flatVectorsReader.getByteVectorValues(fieldInfo.name);
+ case FLOAT32 -> flatVectorsReader.getFloatVectorValues(fieldInfo.name);
+ };
+ int totalVectorCount = vectorValues == null ? 0 : vectorValues.size();
+ if (totalVectorCount > 0 && shouldCreateGraph(tinySegmentsThreshold, totalVectorCount)) {
+ if (flatVectorsReader instanceof QuantizedVectorsReader quantizedVectorsReader
+ && fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
+ CloseableRandomVectorScorerSupplier scorerSupplier =
+ quantizedVectorsReader.getRandomVectorScorerSupplierForMerge(
+ fieldInfo, segmentWriteState);
+ try {
+ buildAndWriteGraph(
+ fieldInfo, mergeState, vectorValues, scorerSupplier, totalVectorCount);
+ } catch (Throwable t) {
+ IOUtils.closeWhileSuppressingExceptions(t, scorerSupplier);
+ throw t;
}
+ IOUtils.close(scorerSupplier);
+ } else {
+ RandomVectorScorerSupplier scorerSupplier =
+ flatVectorsReader
+ .getFlatVectorScorer()
+ .getRandomVectorScorerSupplier(
+ fieldInfo.getVectorSimilarityFunction(), vectorValues);
+ buildAndWriteGraph(fieldInfo, mergeState, vectorValues, scorerSupplier, totalVectorCount);
}
- KnnVectorValues mergedVectorValues = null;
- switch (fieldInfo.getVectorEncoding()) {
- case BYTE ->
- mergedVectorValues =
- KnnVectorsWriter.MergedVectorValues.mergeByteVectorValues(fieldInfo, mergeState);
- case FLOAT32 ->
- mergedVectorValues =
- KnnVectorsWriter.MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState);
- }
- graph =
- merger.merge(
- mergedVectorValues,
- segmentWriteState.infoStream,
- scorerSupplier.totalVectorCount());
- vectorIndexNodeOffsets = writeGraph(graph);
+ } else {
+ writeMeta(fieldInfo, vectorIndex.getFilePointer(), 0L, totalVectorCount, null, null);
+ }
+ };
+ }
+
+ private void buildAndWriteGraph(
+ FieldInfo fieldInfo,
+ MergeState mergeState,
+ KnnVectorValues vectorValues,
+ RandomVectorScorerSupplier scorerSupplier,
+ int totalVectorCount)
+ throws IOException {
+ long vectorIndexOffset = vectorIndex.getFilePointer();
+ OnHeapHnswGraph graph = null;
+ int[][] vectorIndexNodeOffsets = null;
+ HnswGraphMerger merger =
+ createGraphMerger(
+ fieldInfo,
+ scorerSupplier,
+ mergeState.intraMergeTaskExecutor == null
+ ? null
+ : new TaskExecutor(mergeState.intraMergeTaskExecutor),
+ numMergeWorkers);
+ for (int i = 0; i < mergeState.liveDocs.length; i++) {
+ if (hasVectorValues(mergeState.fieldInfos[i], fieldInfo.name)) {
+ merger.addReader(
+ mergeState.knnVectorsReaders[i], mergeState.docMaps[i], mergeState.liveDocs[i]);
}
- long vectorIndexLength = vectorIndex.getFilePointer() - vectorIndexOffset;
- writeMeta(
- fieldInfo,
- vectorIndexOffset,
- vectorIndexLength,
- scorerSupplier.totalVectorCount(),
- graph,
- vectorIndexNodeOffsets);
- } catch (Throwable t) {
- IOUtils.closeWhileSuppressingExceptions(t, scorerSupplier);
- throw t;
}
- IOUtils.close(scorerSupplier);
+ graph = merger.merge(vectorValues, segmentWriteState.infoStream, totalVectorCount);
+ vectorIndexNodeOffsets = writeGraph(graph);
+ long vectorIndexLength = vectorIndex.getFilePointer() - vectorIndexOffset;
+ writeMeta(
+ fieldInfo,
+ vectorIndexOffset,
+ vectorIndexLength,
+ totalVectorCount,
+ graph,
+ vectorIndexNodeOffsets);
+ }
+
+ private void ensureFlatReaderOpen() throws IOException {
+ if (flatVectorsReader == null) {
+ flatVectorWriter.finish();
+ flatVectorWriter.close();
+ flatWriterClosed = true;
+ SegmentReadState readState =
+ new SegmentReadState(
+ segmentWriteState.directory,
+ segmentWriteState.segmentInfo,
+ segmentWriteState.fieldInfos,
+ segmentWriteState.context,
+ segmentWriteState.segmentSuffix);
+ flatVectorsReader = flatVectorsFormat.fieldsReader(readState);
+ }
}
/**
@@ -599,7 +647,11 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
@Override
public void close() throws IOException {
- IOUtils.close(meta, vectorIndex, flatVectorWriter);
+ if (flatWriterClosed) {
+ IOUtils.close(meta, vectorIndex, flatVectorsReader);
+ } else {
+ IOUtils.close(meta, vectorIndex, flatVectorWriter, flatVectorsReader);
+ }
}
static int distFuncToOrd(VectorSimilarityFunction func) {
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldKnnVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldKnnVectorsFormat.java
index 16ff34042fa..a05ce59a77d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldKnnVectorsFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldKnnVectorsFormat.java
@@ -41,6 +41,7 @@ import org.apache.lucene.internal.hppc.IntObjectHashMap;
import org.apache.lucene.internal.hppc.ObjectCursor;
import org.apache.lucene.search.AcceptDocs;
import org.apache.lucene.search.KnnCollector;
+import org.apache.lucene.util.IORunnable;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.hnsw.HnswGraph;
@@ -124,8 +125,8 @@ public abstract class PerFieldKnnVectorsFormat extends KnnVectorsFormat {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- getInstance(fieldInfo).mergeOneField(fieldInfo, mergeState);
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ return getInstance(fieldInfo).mergeOneField(fieldInfo, mergeState);
}
@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 8c66147f1a8..b3200ea88f0 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
@@ -18,6 +18,7 @@
package org.apache.lucene.util.hnsw;
import java.io.Closeable;
+import java.io.IOException;
/**
* A supplier that creates {@link UpdateableRandomVectorScorer} from an ordinal. Caller should be
@@ -27,5 +28,31 @@ import java.io.Closeable;
* closeable
*/
public interface CloseableRandomVectorScorerSupplier extends Closeable, RandomVectorScorerSupplier {
+
int totalVectorCount();
+
+ static CloseableRandomVectorScorerSupplier create(
+ RandomVectorScorerSupplier supplier, int totalVectorCount, Closeable onClose) {
+ return new CloseableRandomVectorScorerSupplier() {
+ @Override
+ public int totalVectorCount() {
+ return totalVectorCount;
+ }
+
+ @Override
+ public void close() throws IOException {
+ onClose.close();
+ }
+
+ @Override
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ return supplier.scorer();
+ }
+
+ @Override
+ public RandomVectorScorerSupplier copy() throws IOException {
+ return supplier.copy();
+ }
+ };
+ }
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/quantization/QuantizedVectorsReader.java b/lucene/core/src/java/org/apache/lucene/util/quantization/QuantizedVectorsReader.java
index 3bc264fd91a..e94dee121d1 100644
--- a/lucene/core/src/java/org/apache/lucene/util/quantization/QuantizedVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/util/quantization/QuantizedVectorsReader.java
@@ -18,7 +18,10 @@ package org.apache.lucene.util.quantization;
import java.io.Closeable;
import java.io.IOException;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.Accountable;
+import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
/**
* Quantized vector reader
@@ -30,4 +33,17 @@ public interface QuantizedVectorsReader extends Closeable, Accountable {
BaseQuantizedByteVectorValues getQuantizedVectorValues(String fieldName) throws IOException;
ScalarQuantizer getQuantizationState(String fieldName);
+
+ /**
+ * Provides a scorer for merging this quantized vector reader. This way any additional merging
+ * logic can be implemented by the user of this class.
+ *
+ * @param fieldInfo fieldInfo of the field to merge
+ * @param segmentWriteState the SegmentWriteState to write temporary files if needed
+ * @return a scorer over the newly merged flat vectors, which should be closed as it may hold
+ * temporary file handles to read over auxiliary data structures
+ * @throws IOException if an I/O error occurs when merging
+ */
+ CloseableRandomVectorScorerSupplier getRandomVectorScorerSupplierForMerge(
+ FieldInfo fieldInfo, SegmentWriteState segmentWriteState) throws IOException;
}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/perfield/TestPerFieldKnnVectorsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/perfield/TestPerFieldKnnVectorsFormat.java
index 60548dd4e35..96988317f2b 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/perfield/TestPerFieldKnnVectorsFormat.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/perfield/TestPerFieldKnnVectorsFormat.java
@@ -55,6 +55,7 @@ import org.apache.lucene.tests.codecs.asserting.AssertingCodec;
import org.apache.lucene.tests.index.BaseKnnVectorsFormatTestCase;
import org.apache.lucene.tests.index.RandomCodec;
import org.apache.lucene.tests.util.TestUtil;
+import org.apache.lucene.util.IORunnable;
import org.hamcrest.MatcherAssert;
/** Basic tests of PerFieldDocValuesFormat */
@@ -284,9 +285,10 @@ public class TestPerFieldKnnVectorsFormat extends BaseKnnVectorsFormatTestCase {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState)
+ throws IOException {
fieldsWritten.add(fieldInfo.name);
- writer.mergeOneField(fieldInfo, mergeState);
+ return writer.mergeOneField(fieldInfo, mergeState);
}
@Override
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java
index f41986d8e8c..c269653c490 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java
@@ -39,6 +39,7 @@ import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Sorter;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.IORunnable;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.hnsw.IntToIntFunction;
@@ -96,8 +97,8 @@ final class FaissKnnVectorsWriter extends KnnVectorsWriter {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
- rawVectorsWriter.mergeOneField(fieldInfo, mergeState);
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ rawVectorsWriter.mergeOneFlatVectorField(fieldInfo, mergeState);
switch (fieldInfo.getVectorEncoding()) {
case BYTE ->
// TODO: Support using SQ8 quantization, see:
@@ -109,6 +110,7 @@ final class FaissKnnVectorsWriter extends KnnVectorsWriter {
writeFloatField(fieldInfo, merged, doc -> doc);
}
}
+ return null;
}
@Override
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/codecs/asserting/AssertingKnnVectorsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/tests/codecs/asserting/AssertingKnnVectorsFormat.java
index 97cb31911ba..dc06aa4faff 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/codecs/asserting/AssertingKnnVectorsFormat.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/codecs/asserting/AssertingKnnVectorsFormat.java
@@ -38,6 +38,7 @@ import org.apache.lucene.search.AcceptDocs;
import org.apache.lucene.search.KnnCollector;
import org.apache.lucene.tests.search.AssertingAcceptDocs;
import org.apache.lucene.tests.util.TestUtil;
+import org.apache.lucene.util.IORunnable;
import org.apache.lucene.util.hnsw.HnswGraph;
/** Wraps the default KnnVectorsFormat and provides additional assertions. */
@@ -88,10 +89,10 @@ public class AssertingKnnVectorsFormat extends KnnVectorsFormat {
}
@Override
- public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ public IORunnable mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
assert fieldInfo != null;
assert mergeState != null;
- delegate.mergeOneField(fieldInfo, mergeState);
+ return delegate.mergeOneField(fieldInfo, mergeState);
}
@Override