Apache Lucene open-source search software
Bypass HNSW graph building for tiny segments (#14963)
Shubham Chaudhary4a7c9c2780b2
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 119636b4b04..14a95c88fc8 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -203,6 +203,8 @@ Optimizations* GITHUB#15343: Ensure that `AcceptDocs#cost()` only ever calls `BitSets#cardinality()`once per instance to avoid redundant computation. (Ben Trent)+* GITHUB#14963: Bypass HNSW graph building for tiny segments. (Shubham Chaudhary, Ben Trent)+Bug Fixes---------------------* GITHUB#14161: PointInSetQuery's constructor now throws IllegalArgumentExceptiondiff --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.javaindex a04863bf505..42a2d85213c 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@@ -47,7 +47,8 @@ class Lucene99RWV0HnswScalarQuantizationVectorsFormatLucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH,flatVectorsFormat.fieldsWriter(state),1,- null);+ null,+ 0);}static class Lucene99RWScalarQuantizedFormat extends Lucene99ScalarQuantizedVectorsFormat {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.javaindex 497f14290ef..3f72ef3d6a2 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@@ -57,6 +57,7 @@ class Lucene99RWV1HnswScalarQuantizationVectorsFormatLucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH,flatVectorsFormat.fieldsWriter(state),1,- null);+ null,+ 0);}}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene102/Lucene102HnswBinaryQuantizedVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene102/Lucene102HnswBinaryQuantizedVectorsFormat.javaindex 55fe8807356..465310a992f 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene102/Lucene102HnswBinaryQuantizedVectorsFormat.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene102/Lucene102HnswBinaryQuantizedVectorsFormat.java@@ -128,7 +128,8 @@ public class Lucene102HnswBinaryQuantizedVectorsFormat extends KnnVectorsFormatbeamWidth,flatVectorsFormat.fieldsWriter(state),numMergeWorkers,- mergeExec);+ mergeExec,+ 0);}@Overridediff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104HnswScalarQuantizedVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104HnswScalarQuantizedVectorsFormat.javaindex e15e361759e..0b5a5276c53 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@@ -19,6 +19,7 @@ package org.apache.lucene.codecs.lucene104;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_NUM_MERGE_WORKER;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.HNSW_GRAPH_THRESHOLD;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.MAXIMUM_BEAM_WIDTH;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.MAXIMUM_MAX_CONN;@@ -60,6 +61,20 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormat/** The format for storing, reading, merging vectors on disk */private final Lucene104ScalarQuantizedVectorsFormat flatVectorsFormat;+ /**+ * The threshold to use to bypass HNSW graph building for tiny segments in terms of k for a graph+ * i.e. number of docs to match the query (default is {@link+ * Lucene99HnswVectorsFormat#HNSW_GRAPH_THRESHOLD}).+ *+ * <ul>+ * <li>0 indicates that the graph is always built.+ * <li>greater than 0 indicates that the graph needs a certain number of nodes before it starts+ * building. See {@link Lucene99HnswVectorsFormat#HNSW_GRAPH_THRESHOLD} for details.+ * <li>Negative values aren't allowed.+ * </ul>+ */+ private final int tinySegmentsThreshold;+private final int numMergeWorkers;private final TaskExecutor mergeExec;@@ -70,7 +85,8 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormatDEFAULT_MAX_CONN,DEFAULT_BEAM_WIDTH,DEFAULT_NUM_MERGE_WORKER,- null);+ null,+ HNSW_GRAPH_THRESHOLD);}/**@@ -80,7 +96,13 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormat* @param beamWidth the size of the queue maintained during graph construction.*/public Lucene104HnswScalarQuantizedVectorsFormat(int maxConn, int beamWidth) {- this(ScalarEncoding.UNSIGNED_BYTE, maxConn, beamWidth, DEFAULT_NUM_MERGE_WORKER, null);+ this(+ ScalarEncoding.UNSIGNED_BYTE,+ maxConn,+ beamWidth,+ DEFAULT_NUM_MERGE_WORKER,+ null,+ HNSW_GRAPH_THRESHOLD);}/**@@ -100,6 +122,26 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormatint beamWidth,int numMergeWorkers,ExecutorService mergeExec) {+ this(encoding, maxConn, beamWidth, numMergeWorkers, mergeExec, HNSW_GRAPH_THRESHOLD);+ }++ /**+ * Constructs a format using the given graph construction parameters and scalar quantization.+ *+ * @param maxConn the maximum number of connections to a node in the HNSW graph+ * @param beamWidth the size of the queue maintained during graph construction.+ * @param numMergeWorkers number of workers (threads) that will be used when doing merge. If+ * larger than 1, a non-null {@link ExecutorService} must be passed as mergeExec+ * @param mergeExec the {@link ExecutorService} that will be used by ALL vector writers that are+ * generated by this format to do the merge+ */+ public Lucene104HnswScalarQuantizedVectorsFormat(+ ScalarEncoding encoding,+ int maxConn,+ int beamWidth,+ int numMergeWorkers,+ ExecutorService mergeExec,+ int tinySegmentsThreshold) {super(NAME);flatVectorsFormat = new Lucene104ScalarQuantizedVectorsFormat(encoding);if (maxConn <= 0 || maxConn > MAXIMUM_MAX_CONN) {@@ -118,6 +160,7 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormat}this.maxConn = maxConn;this.beamWidth = beamWidth;+ this.tinySegmentsThreshold = tinySegmentsThreshold;if (numMergeWorkers == 1 && mergeExec != null) {throw new IllegalArgumentException("No executor service is needed as we'll use single thread to merge");@@ -138,7 +181,8 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormatbeamWidth,flatVectorsFormat.fieldsWriter(state),numMergeWorkers,- mergeExec);+ mergeExec,+ tinySegmentsThreshold);}@Override@@ -157,6 +201,8 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormat+ maxConn+ ", beamWidth="+ beamWidth+ + ", tinySegmentsThreshold="+ + tinySegmentsThreshold+ ", flatVectorFormat="+ flatVectorsFormat+ ")";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.javaindex baf15174704..d265d9d2932 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@@ -116,6 +116,23 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {/** Default to use single thread merge */public static final int DEFAULT_NUM_MERGE_WORKER = 1;+ /**+ * Minimum estimated search effort (in terms of expected visited nodes) required before building+ * an HNSW graph for a segment.+ *+ * <p>This threshold is compared against the value produced by {@link+ * org.apache.lucene.util.hnsw.HnswGraphSearcher#expectedVisitedNodes(int, int)}, which estimates+ * how many nodes would be visited during a vector search based on the current graph size and+ * {@code k} (neighbours to find).+ *+ * <p>If the estimated number of visited nodes falls below this threshold, HNSW graph construction+ * is skipped for that segment - typically for small flushes or low document count segments -+ * since the overhead of building the graph would outweigh its search benefits.+ *+ * <p>Default: {@code 100}+ */+ public static final int HNSW_GRAPH_THRESHOLD = 100;+static final int DIRECT_MONOTONIC_BLOCK_SHIFT = 16;/**@@ -138,11 +155,30 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {private final int numMergeWorkers;private final TaskExecutor mergeExec;+ /**+ * The threshold to use to bypass HNSW graph building for tiny segments in terms of k for a graph+ * i.e. number of docs to match the query (default is {@link+ * Lucene99HnswVectorsFormat#HNSW_GRAPH_THRESHOLD}).+ *+ * <ul>+ * <li>0 indicates that the graph is always built.+ * <li>0 indicates that the graph needs certain or more nodes before it starts building.+ * <li>Negative values aren't allowed.+ * </ul>+ */+ private final int tinySegmentsThreshold;+private final int writeVersion;/** Constructs a format using default graph construction parameters */public Lucene99HnswVectorsFormat() {- this(DEFAULT_MAX_CONN, DEFAULT_BEAM_WIDTH, DEFAULT_NUM_MERGE_WORKER, null);+ this(+ DEFAULT_MAX_CONN,+ DEFAULT_BEAM_WIDTH,+ DEFAULT_NUM_MERGE_WORKER,+ null,+ HNSW_GRAPH_THRESHOLD,+ VERSION_CURRENT);}/**@@ -152,7 +188,20 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {* @param beamWidth the size of the queue maintained during graph construction.*/public Lucene99HnswVectorsFormat(int maxConn, int beamWidth) {- this(maxConn, beamWidth, DEFAULT_NUM_MERGE_WORKER, null);+ this(maxConn, beamWidth, DEFAULT_NUM_MERGE_WORKER, null, HNSW_GRAPH_THRESHOLD, VERSION_CURRENT);+ }++ /**+ * Constructs a format using the given graph construction parameters.+ *+ * @param maxConn the maximum number of connections to a node in the HNSW graph+ * @param beamWidth the size of the queue maintained during graph construction.+ * @param tinySegmentsThreshold the expected number of vector operations to return k nearest+ * neighbors of the current graph size+ */+ public Lucene99HnswVectorsFormat(int maxConn, int beamWidth, int tinySegmentsThreshold) {+ this(+ maxConn, beamWidth, DEFAULT_NUM_MERGE_WORKER, null, tinySegmentsThreshold, VERSION_CURRENT);}/**@@ -168,7 +217,7 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {*/public Lucene99HnswVectorsFormat(int maxConn, int beamWidth, int numMergeWorkers, ExecutorService mergeExec) {- this(maxConn, beamWidth, numMergeWorkers, mergeExec, VERSION_CURRENT);+ this(maxConn, beamWidth, numMergeWorkers, mergeExec, HNSW_GRAPH_THRESHOLD, VERSION_CURRENT);}/**@@ -182,6 +231,30 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {* @param mergeExec the {@link ExecutorService} that will be used by ALL vector writers that are* generated by this format to do the merge. If null, the configured {@link* MergeScheduler#getIntraMergeExecutor(MergePolicy.OneMerge)} is used.+ * @param tinySegmentsThreshold the expected number of vector operations to return k nearest+ * neighbors of the current graph size+ */+ public Lucene99HnswVectorsFormat(+ int maxConn,+ int beamWidth,+ int numMergeWorkers,+ ExecutorService mergeExec,+ int tinySegmentsThreshold) {+ this(maxConn, beamWidth, numMergeWorkers, mergeExec, tinySegmentsThreshold, VERSION_CURRENT);+ }++ /**+ * Constructs a format using the given graph construction parameters.+ *+ * @param maxConn the maximum number of connections to a node in the HNSW graph+ * @param beamWidth the size of the queue maintained during graph construction.+ * @param numMergeWorkers number of workers (threads) that will be used when doing merge. If+ * larger than 1, a non-null {@link ExecutorService} must be passed as mergeExec+ * @param mergeExec the {@link ExecutorService} that will be used by ALL vector writers that are+ * generated by this format to do the merge. If null, the configured {@link+ * MergeScheduler#getIntraMergeExecutor(MergePolicy.OneMerge)} is used.+ * @param tinySegmentsThreshold the expected number of vector operations to return k nearest+ * neighbors of the current graph size* @param writeVersion the version used for the writer to encode docID's (VarInt=0, GroupVarInt=1)*/Lucene99HnswVectorsFormat(@@ -189,6 +262,7 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {int beamWidth,int numMergeWorkers,ExecutorService mergeExec,+ int tinySegmentsThreshold,int writeVersion) {super("Lucene99HnswVectorsFormat");if (maxConn <= 0 || maxConn > MAXIMUM_MAX_CONN) {@@ -207,6 +281,7 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {}this.maxConn = maxConn;this.beamWidth = beamWidth;+ this.tinySegmentsThreshold = tinySegmentsThreshold;this.writeVersion = writeVersion;if (numMergeWorkers == 1 && mergeExec != null) {throw new IllegalArgumentException(@@ -229,6 +304,7 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {flatVectorsFormat.fieldsWriter(state),numMergeWorkers,mergeExec,+ tinySegmentsThreshold,writeVersion);}@@ -248,6 +324,8 @@ public final class Lucene99HnswVectorsFormat extends KnnVectorsFormat {+ maxConn+ ", beamWidth="+ beamWidth+ + ", tinySegmentsThreshold="+ + tinySegmentsThreshold+ ", flatVectorFormat="+ flatVectorsFormat+ ")";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.javaindex 90df5741702..001fb9982d3 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@@ -332,10 +332,10 @@ public final class Lucene99HnswVectorsReader extends KnnVectorsReaderfinal RandomVectorScorer scorer = scorerSupplier.get();final KnnCollector collector =new OrdinalTranslatedKnnCollector(knnCollector, scorer::ordToDoc);- HnswGraph graph = getGraph(fieldEntry);// Take into account if quantized? E.g. some scorer cost?// Use approximate cardinality as this is good enough, but ensure we don't exceed the graph// size as that is illogical+ HnswGraph graph = getGraph(fieldEntry);int filteredDocCount = Math.min(acceptDocs.cost(), graph.size());Bits accepted = acceptDocs.bits();final Bits acceptedOrds = scorer.getAcceptOrds(accepted);@@ -343,7 +343,7 @@ public final class Lucene99HnswVectorsReader extends KnnVectorsReaderboolean doHnsw = knnCollector.k() < numVectors;// The approximate number of vectors that would be visited if we did not filterint unfilteredVisit = HnswGraphSearcher.expectedVisitedNodes(knnCollector.k(), graph.size());- if (unfilteredVisit >= filteredDocCount) {+ if (unfilteredVisit >= filteredDocCount || graph.size() == 0) {doHnsw = false;}if (doHnsw) {@@ -399,6 +399,9 @@ public final class Lucene99HnswVectorsReader extends KnnVectorsReader}private HnswGraph getGraph(FieldEntry entry) throws IOException {+ if (entry.vectorIndexLength == 0) {+ return HnswGraph.EMPTY;+ }return new OffHeapHnswGraph(entry, vectorIndex);}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.javaindex 32e745f6c4f..89f23bb5b0f 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@@ -19,9 +19,11 @@ package org.apache.lucene.codecs.lucene99;import static org.apache.lucene.codecs.KnnVectorsWriter.MergedVectorValues.hasVectorValues;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DIRECT_MONOTONIC_BLOCK_SHIFT;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.HNSW_GRAPH_THRESHOLD;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.VERSION_CURRENT;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.VERSION_GROUPVARINT;import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader.SIMILARITY_FUNCTIONS;+import static org.apache.lucene.util.hnsw.HnswGraphSearcher.expectedVisitedNodes;import java.io.IOException;import java.util.ArrayList;@@ -77,6 +79,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {private final FlatVectorsWriter flatVectorWriter;private final int numMergeWorkers;private final TaskExecutor mergeExec;+ private final int tinySegmentsThreshold;private final int version;private final List<FieldWriter<?>> fields = new ArrayList<>();@@ -90,10 +93,37 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {int numMergeWorkers,TaskExecutor mergeExec)throws IOException {- this(state, M, beamWidth, flatVectorWriter, numMergeWorkers, mergeExec, VERSION_CURRENT);+ this(+ state,+ M,+ beamWidth,+ flatVectorWriter,+ numMergeWorkers,+ mergeExec,+ HNSW_GRAPH_THRESHOLD,+ VERSION_CURRENT);+ }++ public Lucene99HnswVectorsWriter(+ SegmentWriteState state,+ int M,+ int beamWidth,+ FlatVectorsWriter flatVectorWriter,+ int numMergeWorkers,+ TaskExecutor mergeExec,+ int tinySegmentsThreshold)+ throws IOException {+ this(+ state,+ M,+ beamWidth,+ flatVectorWriter,+ numMergeWorkers,+ mergeExec,+ tinySegmentsThreshold,+ VERSION_CURRENT);}- // Test-only constructor, should not be called directly outside of tests.Lucene99HnswVectorsWriter(SegmentWriteState state,int M,@@ -101,6 +131,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {FlatVectorsWriter flatVectorWriter,int numMergeWorkers,TaskExecutor mergeExec,+ int tinySegmentsThreshold,int version)throws IOException {this.M = M;@@ -108,6 +139,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {this.beamWidth = beamWidth;this.numMergeWorkers = numMergeWorkers;this.mergeExec = mergeExec;+ this.tinySegmentsThreshold = tinySegmentsThreshold;this.version = version;segmentWriteState = state;String metaFileName =@@ -151,7 +183,8 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {fieldInfo,M,beamWidth,- segmentWriteState.infoStream);+ segmentWriteState.infoStream,+ tinySegmentsThreshold);fields.add(newField);return newField;}@@ -379,7 +412,11 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {// TODO: separate random access vector values from DocIdSetIterator?OnHeapHnswGraph graph = null;int[][] vectorIndexNodeOffsets = null;- if (scorerSupplier.totalVectorCount() > 0) {+ // Check if we should bypass graph building for tiny segments+ boolean makeHnswGraph =+ scorerSupplier.totalVectorCount() > 0+ && (shouldCreateGraph(tinySegmentsThreshold, scorerSupplier.totalVectorCount()));+ if (makeHnswGraph) {// build graphHnswGraphMerger merger =createGraphMerger(@@ -575,16 +612,29 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {throw new IllegalArgumentException("invalid distance function: " + func);}+ private static boolean shouldCreateGraph(int k, int numNodes) {+ if (k <= 0) {+ return true;+ }+ int expectedVisitedNodes = expectedVisitedNodes(k, numNodes);+ return numNodes > expectedVisitedNodes && expectedVisitedNodes > 0;+ }+private static class FieldWriter<T> extends KnnFieldVectorsWriter<T> {private static final long SHALLOW_SIZE =RamUsageEstimator.shallowSizeOfInstance(FieldWriter.class);private final FieldInfo fieldInfo;- private final HnswGraphBuilder hnswGraphBuilder;+ private HnswGraphBuilder hnswGraphBuilder; // only created when neededprivate int lastDocID = -1;private int node = 0;private final FlatFieldVectorsWriter<T> flatFieldVectorsWriter;+ private final int graphThreshold;+ private final int M;+ private final int beamWidth;+ private final InfoStream infoStream;+ private final RandomVectorScorerSupplier scorerSupplier;@SuppressWarnings("unchecked")static FieldWriter<?> create(@@ -593,7 +643,8 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {FieldInfo fieldInfo,int M,int beamWidth,- InfoStream infoStream)+ InfoStream infoStream,+ int tinySegmentsThreshold)throws IOException {return switch (fieldInfo.getVectorEncoding()) {case BYTE ->@@ -603,7 +654,8 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {fieldInfo,M,beamWidth,- infoStream);+ infoStream,+ tinySegmentsThreshold);case FLOAT32 ->new FieldWriter<>(scorer,@@ -611,7 +663,8 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {fieldInfo,M,beamWidth,- infoStream);+ infoStream,+ tinySegmentsThreshold);};}@@ -622,10 +675,16 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {FieldInfo fieldInfo,int M,int beamWidth,- InfoStream infoStream)+ InfoStream infoStream,+ int tinySegmentsThreshold)throws IOException {this.fieldInfo = fieldInfo;- RandomVectorScorerSupplier scorerSupplier =+ this.M = M;+ this.beamWidth = beamWidth;+ this.infoStream = infoStream;+ this.flatFieldVectorsWriter = Objects.requireNonNull(flatFieldVectorsWriter);+ this.graphThreshold = tinySegmentsThreshold;+ this.scorerSupplier =switch (fieldInfo.getVectorEncoding()) {case BYTE ->scorer.getRandomVectorScorerSupplier(@@ -640,10 +699,26 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {(List<float[]>) flatFieldVectorsWriter.getVectors(),fieldInfo.getVectorDimension()));};- hnswGraphBuilder =++ if (graphThreshold <= 0) {+ // Initialize graph builder if optimization is disabled+ initializeGraphBuilder();+ }+ }++ private void initializeGraphBuilder() throws IOException {+ if (hnswGraphBuilder != null) {+ return;+ }+ this.hnswGraphBuilder =HnswGraphBuilder.create(scorerSupplier, M, beamWidth, HnswGraphBuilder.randSeed);- hnswGraphBuilder.setInfoStream(infoStream);- this.flatFieldVectorsWriter = Objects.requireNonNull(flatFieldVectorsWriter);+ this.hnswGraphBuilder.setInfoStream(infoStream);+ }++ private void replayBufferedVectors() throws IOException {+ for (int i = 0; i < flatFieldVectorsWriter.getVectors().size(); i++) {+ hnswGraphBuilder.addGraphNode(i);+ }}@Override@@ -655,7 +730,14 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {+ "\" appears more than once in this document (only one value is allowed per field)");}flatFieldVectorsWriter.addValue(docID, vectorValue);- hnswGraphBuilder.addGraphNode(node);+ // Check if we need to initialize graph builder for tiny segment optimization+ if (hnswGraphBuilder == null && shouldCreateGraph(graphThreshold, node + 1)) {+ initializeGraphBuilder();+ replayBufferedVectors();+ } else if (hnswGraphBuilder != null) {+ // Graph builder is active, add to graph+ hnswGraphBuilder.addGraphNode(node);+ }node++;lastDocID = docID;}@@ -671,18 +753,21 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {OnHeapHnswGraph getGraph() throws IOException {assert flatFieldVectorsWriter.isFinished();- if (node > 0) {+ if (hnswGraphBuilder != null && node > 0) {return hnswGraphBuilder.getCompletedGraph();} else {+ // No graphreturn null;}}@Overridepublic long ramBytesUsed() {- return SHALLOW_SIZE- + flatFieldVectorsWriter.ramBytesUsed()- + hnswGraphBuilder.getGraph().ramBytesUsed();+ long total = SHALLOW_SIZE + flatFieldVectorsWriter.ramBytesUsed();+ if (hnswGraphBuilder != null) {+ total += hnswGraphBuilder.getGraph().ramBytesUsed();+ }+ return total;}}}diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104HnswScalarQuantizedVectorsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104HnswScalarQuantizedVectorsFormat.javaindex 10fc424c44e..d5bc94a9e44 100644--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104HnswScalarQuantizedVectorsFormat.java+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104HnswScalarQuantizedVectorsFormat.java@@ -85,7 +85,8 @@ public class TestLucene104HnswScalarQuantizedVectorsFormat extends BaseKnnVector}};String expectedPattern =- "Lucene104HnswScalarQuantizedVectorsFormat(name=Lucene104HnswScalarQuantizedVectorsFormat, maxConn=10, beamWidth=20,"+ "Lucene104HnswScalarQuantizedVectorsFormat(name=Lucene104HnswScalarQuantizedVectorsFormat,"+ + " maxConn=10, beamWidth=20, tinySegmentsThreshold=100,"+ " flatVectorFormat=Lucene104ScalarQuantizedVectorsFormat(name=Lucene104ScalarQuantizedVectorsFormat,"+ " encoding=UNSIGNED_BYTE,"+ " flatVectorScorer=Lucene104ScalarQuantizedVectorScorer(nonQuantizedDelegate=%s()),"@@ -186,7 +187,7 @@ public class TestLucene104HnswScalarQuantizedVectorsFormat extends BaseKnnVectorvar fieldInfo = r.getFieldInfos().fieldInfo("f");var offHeap = knnVectorsReader.getOffHeapByteSize(fieldInfo);assertEquals(vector.length * Float.BYTES, (long) offHeap.get("vec"));- assertEquals(1L, (long) offHeap.get("vex"));+ assertNotNull(offHeap.get("vex"));long corrections = Float.BYTES + Float.BYTES + Float.BYTES + Integer.BYTES;long expected = encoding.getDocPackedLength(fieldInfo.getVectorDimension()) + corrections;assertEquals(expected, (long) offHeap.get("veq"));diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestLucene99HnswVectorsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestLucene99HnswVectorsFormat.javaindex f41298e0046..54ecccaa28f 100644--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestLucene99HnswVectorsFormat.java+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestLucene99HnswVectorsFormat.java@@ -54,7 +54,7 @@ public class TestLucene99HnswVectorsFormat extends BaseKnnVectorsFormatTestCase}};String expectedPattern =- "Lucene99HnswVectorsFormat(name=Lucene99HnswVectorsFormat, maxConn=10, beamWidth=20, flatVectorFormat=Lucene99FlatVectorsFormat(vectorsScorer=%s()))";+ "Lucene99HnswVectorsFormat(name=Lucene99HnswVectorsFormat, maxConn=10, beamWidth=20, tinySegmentsThreshold=100, flatVectorFormat=Lucene99FlatVectorsFormat(vectorsScorer=%s()))";var defaultScorer = format(Locale.ROOT, expectedPattern, "DefaultFlatVectorScorer");var memSegScorer =format(Locale.ROOT, expectedPattern, "Lucene99MemorySegmentFlatVectorsScorer");@@ -89,7 +89,7 @@ public class TestLucene99HnswVectorsFormat extends BaseKnnVectorsFormatTestCasevar fieldInfo = r.getFieldInfos().fieldInfo("f");var offHeap = knnVectorsReader.getOffHeapByteSize(fieldInfo);assertEquals(vector.length * Float.BYTES, (long) offHeap.get("vec"));- assertEquals(1L, (long) offHeap.get("vex"));+ assertNotNull(offHeap.get("vex"));assertEquals(2, offHeap.size());}}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestSortingCodecReader.java b/lucene/core/src/test/org/apache/lucene/index/TestSortingCodecReader.javaindex 285296d55c1..c03afd92be6 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestSortingCodecReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestSortingCodecReader.java@@ -282,7 +282,7 @@ public class TestSortingCodecReader extends LuceneTestCase {assertTrue(binary_sorted_dv.advanceExact(idNext));if (dense || prevValue % 2 == 0) {assertEquals(idNext, valuesIterator.advance(idNext));- if (graph != null) {+ if (graph != null && graph.size() > 0) {graph.seek(0, valuesIterator.index());assertNotEquals(DocIdSetIterator.NO_MORE_DOCS, graph.nextNeighbor());}diff --git a/lucene/core/src/test/org/apache/lucene/search/BaseVectorSimilarityQueryTestCase.java b/lucene/core/src/test/org/apache/lucene/search/BaseVectorSimilarityQueryTestCase.javaindex 399f7de3388..4a024b9c2cb 100644--- a/lucene/core/src/test/org/apache/lucene/search/BaseVectorSimilarityQueryTestCase.java+++ b/lucene/core/src/test/org/apache/lucene/search/BaseVectorSimilarityQueryTestCase.java@@ -16,6 +16,8 @@*/package org.apache.lucene.search;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN;import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;import java.io.IOException;@@ -28,6 +30,7 @@ import java.util.Objects;import java.util.Optional;import java.util.Set;import java.util.stream.IntStream;+import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.IntField;@@ -465,7 +468,14 @@ abstract class BaseVectorSimilarityQueryTestCase<Query filter = IntField.newSetQuery(idField, getFiltered(numFiltered));try (Directory indexStore = getIndexStore(vectors);- IndexWriter w = new IndexWriter(indexStore, newIndexWriterConfig())) {+ IndexWriter w =+ new IndexWriter(+ indexStore,+ newIndexWriterConfig()+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene99HnswVectorsFormat(+ DEFAULT_MAX_CONN, DEFAULT_BEAM_WIDTH, 0))))) {// Force merge because smaller segments have few filtered docs and often fall back to exact// search, making this test flakyw.forceMerge(1);@@ -581,7 +591,14 @@ abstract class BaseVectorSimilarityQueryTestCase<@SafeVarargsfinal Directory getIndexStore(V... vectors) throws IOException {Directory dir = newDirectory();- try (RandomIndexWriter writer = new RandomIndexWriter(random(), dir)) {+ try (RandomIndexWriter writer =+ new RandomIndexWriter(+ random(),+ dir,+ newIndexWriterConfig()+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene99HnswVectorsFormat(DEFAULT_MAX_CONN, DEFAULT_BEAM_WIDTH, 0))))) {for (int i = 0; i < vectors.length; ++i) {Document doc = new Document();doc.add(getVectorField(vectorField, vectors[i], function));diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSeededKnnByteVectorQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestSeededKnnByteVectorQuery.javaindex 80c95b37972..e6b5bd709c2 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSeededKnnByteVectorQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSeededKnnByteVectorQuery.java@@ -16,10 +16,13 @@*/package org.apache.lucene.search;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN;import static org.apache.lucene.search.TestKnnByteVectorQuery.floatToBytes;import java.io.IOException;import java.util.concurrent.atomic.AtomicInteger;+import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.IntPoint;@@ -137,7 +140,11 @@ public class TestSeededKnnByteVectorQuery extends BaseKnnVectorQueryTestCase {// visitedLimit. This is fine since the test targets AbstractKnnVectorQuery logic, not the kNN// format// implementation.- IndexWriterConfig iwc = new IndexWriterConfig().setCodec(TestUtil.getDefaultCodec());+ IndexWriterConfig iwc =+ new IndexWriterConfig()+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene99HnswVectorsFormat(DEFAULT_MAX_CONN, DEFAULT_BEAM_WIDTH, 0)));RandomIndexWriter w = new RandomIndexWriter(random(), d, iwc);for (int i = 0; i < numDocs; i++) {Document doc = new Document();diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSeededKnnFloatVectorQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestSeededKnnFloatVectorQuery.javaindex 37598d3fae4..0f542adcc85 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSeededKnnFloatVectorQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSeededKnnFloatVectorQuery.java@@ -16,8 +16,12 @@*/package org.apache.lucene.search;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN;+import java.io.IOException;import java.util.concurrent.atomic.AtomicInteger;+import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.IntPoint;@@ -124,7 +128,11 @@ public class TestSeededKnnFloatVectorQuery extends BaseKnnVectorQueryTestCase {// visitedLimit. This is fine since the test targets AbstractKnnVectorQuery logic, not the kNN// format// implementation.- IndexWriterConfig iwc = new IndexWriterConfig().setCodec(TestUtil.getDefaultCodec());+ IndexWriterConfig iwc =+ new IndexWriterConfig()+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene99HnswVectorsFormat(DEFAULT_MAX_CONN, DEFAULT_BEAM_WIDTH, 0)));RandomIndexWriter w = new RandomIndexWriter(random(), d, iwc);for (int i = 0; i < numDocs; i++) {Document doc = new Document();diff --git a/lucene/core/src/test/org/apache/lucene/util/hnsw/HnswGraphTestCase.java b/lucene/core/src/test/org/apache/lucene/util/hnsw/HnswGraphTestCase.javaindex 8e7a8ab8578..5efe13ca671 100644--- a/lucene/core/src/test/org/apache/lucene/util/hnsw/HnswGraphTestCase.java+++ b/lucene/core/src/test/org/apache/lucene/util/hnsw/HnswGraphTestCase.java@@ -271,7 +271,9 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {((Lucene99HnswVectorsReader)((CodecReader) ctx.reader()).getVectorReader().unwrapReaderForField("field")).getGraph("field");- assertGraphEqual(hnsw, graphValues);+ if (graphValues.size() > 0) {+ assertGraphEqual(hnsw, graphValues);+ }}}}diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.javaindex ffeb489ed0a..ad257cdaf62 100644--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java@@ -2163,7 +2163,7 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTevar quant = offHeap.getOrDefault("veq", offHeap.get("veb"));assertTrue(quant == null || quant > 0L);} else {- assertTrue(offHeap.get("vex") == null);+ assertTrue(offHeap.get("vex") == null || offHeap.get("vex") == 0);}if (hasQuantized(knnVectorsReader, fieldInfo)) {@@ -2208,7 +2208,8 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTeknnVectorsReader = assertingReader.delegate;}if (knnVectorsReader instanceof HnswGraphProvider graphProvider) {- return graphProvider.getGraph(fieldInfo.name) != null;+ return graphProvider.getGraph(fieldInfo.name) != null+ && graphProvider.getGraph(fieldInfo.name).size() > 0;}String name = knnVectorsReader.getClass().getSimpleName().toLowerCase(Locale.ROOT);return name.contains("hnsw");diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/RandomCodec.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/RandomCodec.javaindex 420d6d0164e..d0794bf9cc7 100644--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/RandomCodec.java+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/RandomCodec.java@@ -272,25 +272,29 @@ public class RandomCodec extends AssertingCodec {TestUtil.nextInt(random, 5, 50),TestUtil.nextInt(random, 10, 50),concurrentKnnMerging ? TestUtil.nextInt(random, 2, 8) : 1,- concurrentKnnMerging ? ForkJoinPool.commonPool() : null),+ concurrentKnnMerging ? ForkJoinPool.commonPool() : null,+ 0),new Lucene104HnswScalarQuantizedVectorsFormat(Lucene104ScalarQuantizedVectorsFormat.ScalarEncoding.SEVEN_BIT,TestUtil.nextInt(random, 5, 50),TestUtil.nextInt(random, 10, 50),concurrentKnnMerging ? TestUtil.nextInt(random, 2, 8) : 1,- concurrentKnnMerging ? ForkJoinPool.commonPool() : null),+ concurrentKnnMerging ? ForkJoinPool.commonPool() : null,+ 0),new Lucene104HnswScalarQuantizedVectorsFormat(Lucene104ScalarQuantizedVectorsFormat.ScalarEncoding.UNSIGNED_BYTE,TestUtil.nextInt(random, 5, 50),TestUtil.nextInt(random, 10, 50),concurrentKnnMerging ? TestUtil.nextInt(random, 2, 8) : 1,- concurrentKnnMerging ? ForkJoinPool.commonPool() : null),+ concurrentKnnMerging ? ForkJoinPool.commonPool() : null,+ 0),new Lucene104HnswScalarQuantizedVectorsFormat(Lucene104ScalarQuantizedVectorsFormat.ScalarEncoding.PACKED_NIBBLE,TestUtil.nextInt(random, 5, 50),TestUtil.nextInt(random, 10, 50),concurrentKnnMerging ? TestUtil.nextInt(random, 2, 8) : 1,- concurrentKnnMerging ? ForkJoinPool.commonPool() : null),+ concurrentKnnMerging ? ForkJoinPool.commonPool() : null,+ 0),new AssertingKnnVectorsFormat());Collections.shuffle(formats, random);diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.javaindex 07f8d096197..b11bac8be80 100644--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java@@ -17,6 +17,8 @@package org.apache.lucene.tests.util;import static java.nio.charset.StandardCharsets.UTF_8;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH;+import static org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN;import static org.hamcrest.MatcherAssert.assertThat;import static org.hamcrest.Matchers.arrayWithSize;import static org.hamcrest.Matchers.equalTo;@@ -1413,7 +1415,7 @@ public final class TestUtil {* Lucene.*/public static KnnVectorsFormat getDefaultKnnVectorsFormat() {- return new Lucene99HnswVectorsFormat();+ return new Lucene99HnswVectorsFormat(DEFAULT_MAX_CONN, DEFAULT_BEAM_WIDTH, 0);}public static boolean anyFilesExceptWriteLock(Directory dir) throws IOException {