Apache Lucene open-source search software
Implement data-blind scalar quantization (#16030)
Trevor McCullochcab6cfcb6041
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex bc43ec7da15..539b4754d5e 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -401,6 +401,12 @@ New Featurestranslates each term into a SpanTermQuery within a {@link SpanOrQuery}, but retains only the most frequent terms so itwill not overflow the boolean max clause count. (Alan Woodward, Nishant Mehta, David Smiley)+* GITHUB#16029: Scalar quantization option to disable centering and writing of float vectors. This+ reduces vector storage costs by 4x or more but also reduces accuracy of distance estimates and+ "float" vectors when requested. Using this feature is a one-way door -- once merged data blind+ it is not possible to re-encode to a different quantization width or center vectors again.+ (Trevor McCulloch)+Improvements---------------------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.javaindex c7f73cbaa67..ee4c5503b0d 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@@ -28,6 +28,7 @@ import java.util.concurrent.ExecutorService;import org.apache.lucene.codecs.KnnVectorsFormat;import org.apache.lucene.codecs.KnnVectorsReader;import org.apache.lucene.codecs.KnnVectorsWriter;+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorsFormat.Mode;import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat;import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader;import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsWriter;@@ -156,8 +157,43 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormatint numMergeWorkers,ExecutorService mergeExec,int tinySegmentsThreshold) {+ this(+ encoding,+ Lucene104ScalarQuantizedVectorsFormat.Mode.CENTERED,+ maxConn,+ beamWidth,+ numMergeWorkers,+ mergeExec,+ tinySegmentsThreshold);+ }++ /**+ * Constructs a format using the given graph construction parameters and scalar quantization.+ *+ * @param encoding the quantization encoding used to encode the vectors+ * @param mode the quantization {@link Lucene104ScalarQuantizedVectorsFormat.Mode}; by default+ * quantized vectors are centered on a mean vector in the segment. This behavior can be+ * disabled to trade merge cost for distance estimate accuracy. The mode can also disable the+ * write of original float vectors to reduce the size of the index with larger (4,7,8) bit+ * quantizations.+ * @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+ * @param tinySegmentsThreshold the threshold below which HNSW graph building is skipped+ */+ public Lucene104HnswScalarQuantizedVectorsFormat(+ ScalarEncoding encoding,+ Lucene104ScalarQuantizedVectorsFormat.Mode mode,+ int maxConn,+ int beamWidth,+ int numMergeWorkers,+ ExecutorService mergeExec,+ int tinySegmentsThreshold) {super(NAME);- flatVectorsFormat = new Lucene104ScalarQuantizedVectorsFormat(encoding);+ flatVectorsFormat = new Lucene104ScalarQuantizedVectorsFormat(encoding, mode);if (maxConn <= 0 || maxConn > MAXIMUM_MAX_CONN) {throw new IllegalArgumentException("maxConn must be positive and less than or equal to "@@ -172,6 +208,10 @@ public class Lucene104HnswScalarQuantizedVectorsFormat extends KnnVectorsFormat+ "; beamWidth="+ beamWidth);}+ if (mode == Mode.DATA_BLIND_WITHOUT_FLOATS && encoding.isAsymmetric()) {+ throw new IllegalArgumentException(+ "Float vector values must be kept to use an asymmetric vector encoding like " + encoding);+ }this.maxConn = maxConn;this.beamWidth = beamWidth;this.tinySegmentsThreshold = tinySegmentsThreshold;diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsFormat.javaindex fb8221deffb..4b54b7d5b86 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsFormat.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsFormat.java@@ -44,6 +44,14 @@ import org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncod* quantized vectors in the index.* <li>Transforming the half-byte quantized query vectors in such a way that the comparison with* single bit vectors can be done with bit arithmetic.+ * <li>Data blind mode: vectors are quantized without centering. This reduces disk space+ * requirements and makes merges faster since the vectors never need to be re-quantized, but+ * also produces less accurate distance estimates and is less flexible if the writer changes.+ * Data blind mode comes in two variants: one that still stores the full-precision float+ * vectors ({@link Mode#DATA_BLIND_WITH_FLOATS}), and one that discards them ({@link+ * Mode#DATA_BLIND_WITHOUT_FLOATS}). Discarding the floats saves the most space and is what+ * enables quantized-byte pass-through merges, but it removes the ability to rescore with+ * exact vectors or re-quantize to a different encoding.* </ul>** A previous work related to improvements over regular LVQ is <a@@ -85,11 +93,18 @@ import org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncod* <li><b>vlong</b> the length of the vector data in the .veq file* <li><b>vint</b> the number of vectors* <li><b>vint</b> the wire number for ScalarEncoding- * <li><b>[float]</b> the centroid- * <li><b>float</b> the centroid square magnitude+ * <li><b>byte</b> the wire number for {@link Mode}, only present when the metadata version+ * indicates data-blind mode+ * <li><b>[float]</b> the centroid (omitted when the metadata version indicates data-blind mode)+ * <li><b>float</b> the centroid square magnitude (omitted when the metadata version indicates+ * data-blind mode)* <li>The sparse vector information, if required, mapping vector ordinal to doc ID* </ul>*+ * <p>{@code Mode} manifests in the version and metadata: {@link Mode#CENTERED} writes version 0,+ * while both data-blind modes write version 1 plus their {@link Mode} wire number in the metadata;+ * version 0 metadata implies {@link Mode#CENTERED}.+ ** @lucene.experimental*/public class Lucene104ScalarQuantizedVectorsFormat extends FlatVectorsFormat {@@ -97,7 +112,11 @@ public class Lucene104ScalarQuantizedVectorsFormat extends FlatVectorsFormat {public static final String NAME = "Lucene104ScalarQuantizedVectorsFormat";static final int VERSION_START = 0;- static final int VERSION_CURRENT = VERSION_START;++ /** Version written when centering is disabled (data-blind mode). */+ static final int VERSION_DATA_BLIND = 1;++ static final int VERSION_CURRENT = VERSION_DATA_BLIND;static final String META_CODEC_NAME = "Lucene104ScalarQuantizedVectorsFormatMeta";static final String VECTOR_DATA_CODEC_NAME = "Lucene104ScalarQuantizedVectorsFormatData";static final String META_EXTENSION = "vemq";@@ -110,23 +129,83 @@ public class Lucene104ScalarQuantizedVectorsFormat extends FlatVectorsFormat {private static final Lucene104ScalarQuantizedVectorScorer scorer =new Lucene104ScalarQuantizedVectorScorer(FlatVectorScorerUtil.getLucene99FlatVectorsScorer());+ /**+ * How vectors are quantized and stored.+ *+ * @lucene.experimental+ */+ public enum Mode {+ /** Vectors are quantized against a computed centroid, which is stored in the metadata. */+ CENTERED((byte) 0),+ /**+ * Vectors are quantized against a zero centroid (no centering), but full-precision float+ * vectors are still written to disk.+ */+ DATA_BLIND_WITH_FLOATS((byte) 1),+ /**+ * Vectors are quantized against a zero centroid (no centering) and full-precision float vectors+ * are discarded.+ *+ * <p>This setting may not be used with asymmetric {@code ScalarEncoding} types as there is not+ * enough information to produce asymmetric "query" representations and graph quality would be+ * significantly degraded.+ */+ DATA_BLIND_WITHOUT_FLOATS((byte) 2);++ private final byte wireNumber;++ Mode(byte wireNumber) {+ this.wireNumber = wireNumber;+ }++ /** The stable wire number used in segment metadata. */+ public byte wireNumber() {+ return wireNumber;+ }++ /** Returns the mode for the given wire number, or throws if the number is unknown. */+ public static Mode fromWireNumber(byte wireNumber) {+ for (Mode mode : values()) {+ if (mode.wireNumber == wireNumber) {+ return mode;+ }+ }+ throw new IllegalStateException("Unknown Mode wire number: " + wireNumber);+ }+ }+private final ScalarEncoding encoding;+ private final Mode mode;- /** Creates a new instance with UNSIGNED_BYTE encoding. */+ /** Creates a new instance with UNSIGNED_BYTE encoding and centering enabled. */public Lucene104ScalarQuantizedVectorsFormat() {this(ScalarEncoding.UNSIGNED_BYTE);}- /** Creates a new instance with the chosen quantization encoding. */+ /** Creates a new instance with the chosen quantization encoding and centering enabled. */public Lucene104ScalarQuantizedVectorsFormat(ScalarEncoding encoding) {+ this(encoding, Mode.CENTERED);+ }++ /**+ * Creates a new instance with the chosen quantization encoding and mode.+ *+ * <p>For the data-blind modes, no centroid is computed and the centroid is omitted from the+ * segment metadata. This reduces vector storage costs by 4x or more but reduces quantization+ * accuracy, particularly at lower bit rates. {@link Mode#DATA_BLIND_WITHOUT_FLOATS} additionally+ * discards the full-precision float vectors. Data-blind segments must be merged with a format of+ * matching {@link ScalarEncoding}; see the class description.+ */+ public Lucene104ScalarQuantizedVectorsFormat(ScalarEncoding encoding, Mode mode) {super(NAME);this.encoding = encoding;+ this.mode = mode;}@Overridepublic FlatVectorsWriter fieldsWriter(SegmentWriteState state) throws IOException {return new Lucene104ScalarQuantizedVectorsWriter(- state, encoding, rawVectorFormat.fieldsWriter(state), scorer);+ state, encoding, mode, rawVectorFormat.fieldsWriter(state), scorer);}@Override@@ -146,6 +225,8 @@ public class Lucene104ScalarQuantizedVectorsFormat extends FlatVectorsFormat {+ NAME+ ", encoding="+ encoding+ + ", mode="+ + mode+ ", flatVectorScorer="+ scorer+ ", rawVectorFormat="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.javaindex bd4d6c874d9..0aa7758fd1b 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@@ -31,6 +31,7 @@ import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.codecs.KnnVectorsReader;import org.apache.lucene.codecs.hnsw.FlatVectorsReader;import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorsFormat.Mode;import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;import org.apache.lucene.index.ByteVectorValues;import org.apache.lucene.index.CorruptIndexException;@@ -120,7 +121,7 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReaderLucene104ScalarQuantizedVectorsFormat.VERSION_CURRENT,state.segmentInfo.getId(),state.segmentSuffix);- readFields(meta, state.fieldInfos);+ readFields(meta, state.fieldInfos, versionMeta);} catch (Throwable exception) {priorE = exception;} finally {@@ -144,13 +145,14 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader}}- private void readFields(ChecksumIndexInput meta, FieldInfos infos) throws IOException {+ private void readFields(ChecksumIndexInput meta, FieldInfos infos, int version)+ throws IOException {for (int fieldNumber = meta.readInt(); fieldNumber != -1; fieldNumber = meta.readInt()) {FieldInfo info = infos.fieldInfo(fieldNumber);if (info == null) {throw new CorruptIndexException("Invalid field number: " + fieldNumber, meta);}- FieldEntry fieldEntry = readField(meta, info);+ FieldEntry fieldEntry = readField(meta, info, version);validateFieldEntry(info, fieldEntry);fields.put(info.name, fieldEntry);}@@ -240,6 +242,22 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader+ VectorEncoding.FLOAT32);}+ if (fi.storesFloatVectors() == false) {+ // Data-blind mode without floats: full-precision float vectors were never stored. Reconstruct+ // floats from the quantized data.+ return OffHeapScalarQuantizedFloatVectorValues.load(+ fi.ordToDocDISIReaderConfiguration,+ fi.dimension,+ fi.size,+ fi.scalarEncoding,+ fi.similarityFunction,+ vectorScorer,+ fi.centroid,+ fi.vectorDataOffset,+ fi.vectorDataLength,+ quantizedVectorData);+ }+FloatVectorValues rawFloatVectorValues = rawVectorsReader.getFloatVectorValues(field);OffHeapScalarQuantizedVectorValues sqvv = loadQuantizedVectorValues(fi);@@ -289,6 +307,26 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader+ VectorEncoding.FLOAT16);}+ if (fi.storesFloatVectors() == false) {+ // Data-blind mode without floats: full-precision float16 vectors were never stored.+ // Reconstruct the fp16 view by dequantizing, then pair it with the quantized values so+ // scorer() scores in quantized space while vectorValue()/rescorer() dequantize.+ Float16VectorValues dequantizedRawVectorValues =+ OffHeapScalarQuantizedFloat16VectorValues.load(+ fi.ordToDocDISIReaderConfiguration,+ fi.dimension,+ fi.size,+ fi.scalarEncoding,+ fi.similarityFunction,+ vectorScorer,+ fi.centroid,+ fi.vectorDataOffset,+ fi.vectorDataLength,+ quantizedVectorData);+ return new ScalarQuantizedFloat16VectorValues(+ dequantizedRawVectorValues, loadQuantizedVectorValues(fi));+ }+Float16VectorValues rawFloat16VectorValues = rawVectorsReader.getFloat16VectorValues(field);OffHeapScalarQuantizedVectorValues sqvv = loadQuantizedVectorValues(fi);@@ -423,6 +461,36 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReaderreturn null;}+ /**+ * Returns the {@link Mode} the segment was written with for this field, or null when the field is+ * absent. Note that {@link Mode#CENTERED} is also the default for segments written before the+ * mode was stored explicitly.+ */+ Mode getMode(String field) {+ FieldEntry fieldEntry = fields.get(field);+ return fieldEntry == null ? null : fieldEntry.mode;+ }++ /** Returns whether full-precision fp32 vectors were written for this field. */+ boolean hasRawFloatVectors(String field) throws IOException {+ FieldEntry fi = fields.get(field);+ if (fi == null || fi.storesFloatVectors() == false) {+ return false;+ }+ FloatVectorValues raw = rawVectorsReader.getFloatVectorValues(field);+ return raw != null && raw.size() > 0;+ }++ /** Returns whether full-precision fp16 vectors were written for this field. */+ boolean hasRawFloat16Vectors(String field) throws IOException {+ FieldEntry fi = fields.get(field);+ if (fi == null || fi.storesFloatVectors() == false) {+ return false;+ }+ Float16VectorValues raw = rawVectorsReader.getFloat16VectorValues(field);+ return raw != null && raw.size() > 0;+ }+private static IndexInput openDataInput(SegmentReadState state,int versionMeta,@@ -460,7 +528,7 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader}}- private FieldEntry readField(IndexInput input, FieldInfo info) throws IOException {+ private FieldEntry readField(IndexInput input, FieldInfo info, int version) throws IOException {VectorEncoding vectorEncoding = readVectorEncoding(input);VectorSimilarityFunction similarityFunction = readSimilarityFunction(input);if (similarityFunction != info.getVectorSimilarityFunction()) {@@ -472,7 +540,7 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader+ " != "+ info.getVectorSimilarityFunction());}- return FieldEntry.create(input, vectorEncoding, info.getVectorSimilarityFunction());+ return FieldEntry.create(input, vectorEncoding, info.getVectorSimilarityFunction(), version);}@Override@@ -637,14 +705,22 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReaderlong vectorDataLength,int size,ScalarEncoding scalarEncoding,+ Mode mode,float[] centroid,float centroidDP,- OrdToDocDISIReaderConfiguration ordToDocDISIReaderConfiguration) {+ OrdToDocDISIReaderConfiguration ordToDocDISIReaderConfiguration,+ int version) {++ /** Returns true when this segment stores full-precision float vectors for this field. */+ boolean storesFloatVectors() {+ return mode != Mode.DATA_BLIND_WITHOUT_FLOATS;+ }static FieldEntry create(IndexInput input,VectorEncoding vectorEncoding,- VectorSimilarityFunction similarityFunction)+ VectorSimilarityFunction similarityFunction,+ int version)throws IOException {int dimension = input.readVInt();long vectorDataOffset = input.readVLong();@@ -653,6 +729,7 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReaderfinal float[] centroid;float centroidDP = 0;ScalarEncoding scalarEncoding = ScalarEncoding.UNSIGNED_BYTE;+ Mode mode = Mode.CENTERED;if (size > 0) {int wireNumber = input.readVInt();scalarEncoding =@@ -662,8 +739,15 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReadernew IllegalStateException("Could not get ScalarEncoding from wire number: " + wireNumber));centroid = new float[dimension];- input.readFloats(centroid, 0, dimension);- centroidDP = Float.intBitsToFloat(input.readInt());+ if (version == Lucene104ScalarQuantizedVectorsFormat.VERSION_START) {+ // Centered segments store the centroid and its square magnitude; the mode is implied.+ input.readFloats(centroid, 0, dimension);+ centroidDP = Float.intBitsToFloat(input.readInt());+ } else {+ // Data-blind segments omit both; the non-null all-zero centroid is substituted here.+ // The mode is written explicitly since both data-blind variants share this version.+ mode = Mode.fromWireNumber(input.readByte());+ }} else {centroid = null;}@@ -677,9 +761,11 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReadervectorDataLength,size,scalarEncoding,+ mode,centroid,centroidDP,- conf);+ conf,+ version);}}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.javaindex 2525d16bca6..54396c1eff2 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@@ -33,7 +33,10 @@ import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.codecs.KnnVectorsReader;import org.apache.lucene.codecs.hnsw.FlatFieldVectorsWriter;import org.apache.lucene.codecs.hnsw.FlatVectorsWriter;+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorsFormat.Mode;import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;+import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader;+import org.apache.lucene.index.DocIDMerger;import org.apache.lucene.index.DocsWithFieldSet;import org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.Float16VectorValues;@@ -47,6 +50,7 @@ import org.apache.lucene.index.VectorEncoding;import org.apache.lucene.internal.hppc.FloatArrayList;import org.apache.lucene.search.VectorScorer;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.VectorUtil;@@ -67,6 +71,8 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {private final List<FieldWriter<?>> fields = new ArrayList<>();private final IndexOutput meta, vectorData;private final ScalarEncoding encoding;+ private final Mode mode;+ private final int version;private final FlatVectorsWriter rawVectorDelegate;private boolean finished;@@ -74,11 +80,17 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {public Lucene104ScalarQuantizedVectorsWriter(SegmentWriteState state,ScalarEncoding encoding,+ Mode mode,FlatVectorsWriter rawVectorDelegate,Lucene104ScalarQuantizedVectorScorer vectorsScorer)throws IOException {super(vectorsScorer);this.encoding = encoding;+ this.mode = mode;+ this.version =+ mode == Mode.CENTERED+ ? Lucene104ScalarQuantizedVectorsFormat.VERSION_START+ : Lucene104ScalarQuantizedVectorsFormat.VERSION_DATA_BLIND;this.segmentWriteState = state;String metaFileName =IndexFileNames.segmentFileName(@@ -99,13 +111,13 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {CodecUtil.writeIndexHeader(meta,Lucene104ScalarQuantizedVectorsFormat.META_CODEC_NAME,- Lucene104ScalarQuantizedVectorsFormat.VERSION_CURRENT,+ version,state.segmentInfo.getId(),state.segmentSuffix);CodecUtil.writeIndexHeader(vectorData,Lucene104ScalarQuantizedVectorsFormat.VECTOR_DATA_CODEC_NAME,- Lucene104ScalarQuantizedVectorsFormat.VERSION_CURRENT,+ version,state.segmentInfo.getId(),state.segmentSuffix);} catch (Throwable t) {@@ -116,13 +128,26 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {@Overridepublic FlatFieldVectorsWriter<?> addField(FieldInfo fieldInfo) throws IOException {- FlatFieldVectorsWriter<?> rawVectorDelegate = this.rawVectorDelegate.addField(fieldInfo);+ if (fieldInfo.getVectorEncoding().isFloatingPoint() && mode == Mode.DATA_BLIND_WITHOUT_FLOATS) {+ // Data-blind mode without floats: keep vectors in memory only and never write+ // full-precision float vectors.+ FlatFieldVectorsWriter<?> storage =+ switch (fieldInfo.getVectorEncoding()) {+ case FLOAT32 -> new InMemoryFieldWriter<float[]>(fieldInfo, Float.BYTES);+ case FLOAT16 -> new InMemoryFieldWriter<short[]>(fieldInfo, Short.BYTES);+ case BYTE -> throw new IllegalStateException("Byte Vectors aren't supported");+ };+ FieldWriter<?> fieldWriter = FieldWriter.create(fieldInfo, storage, false);+ fields.add(fieldWriter);+ return fieldWriter;+ }+ FlatFieldVectorsWriter<?> storage = this.rawVectorDelegate.addField(fieldInfo);if (fieldInfo.getVectorEncoding().isFloatingPoint()) {- FieldWriter<?> fieldWriter = FieldWriter.create(fieldInfo, rawVectorDelegate);+ FieldWriter<?> fieldWriter = FieldWriter.create(fieldInfo, storage, mode == Mode.CENTERED);fields.add(fieldWriter);return fieldWriter;}- return rawVectorDelegate;+ return storage;}@Override@@ -277,12 +302,19 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {meta.writeVInt(count);if (count > 0) {meta.writeVInt(encoding.getWireNumber());- final ByteBuffer buffer =- ByteBuffer.allocate(field.getVectorDimension() * Float.BYTES)- .order(ByteOrder.LITTLE_ENDIAN);- buffer.asFloatBuffer().put(clusterCenter);- meta.writeBytes(buffer.array(), buffer.array().length);- meta.writeInt(Float.floatToIntBits(centroidDp));+ if (version == Lucene104ScalarQuantizedVectorsFormat.VERSION_START) {+ final ByteBuffer buffer =+ ByteBuffer.allocate(field.getVectorDimension() * Float.BYTES)+ .order(ByteOrder.LITTLE_ENDIAN);+ buffer.asFloatBuffer().put(clusterCenter);+ meta.writeBytes(buffer.array(), buffer.array().length);+ meta.writeInt(Float.floatToIntBits(centroidDp));+ } else {+ // Data-blind (version 1): the centroid and centroidDP are omitted; a zero centroid is+ // substituted at read time. The mode is written explicitly since both data-blind variants+ // share this version.+ meta.writeByte(mode.wireNumber());+ }}OrdToDocDISIReaderConfiguration.writeStoredMeta(DIRECT_MONOTONIC_BLOCK_SHIFT, meta, vectorData, count, maxDoc, docsWithField);@@ -320,39 +352,167 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {return new QuantizedFloatVectorValues(vectorValues, quantizer, encoding, centroid);}+ /**+ * Returns a view that quantizes a single segment's float vectors against {@code centroid} using+ * this writer's encoding, without consulting any quantized bytes the segment may already store.+ */+ private QuantizedFloatVectorValues quantizeFromFloats(+ KnnVectorsReader reader, FieldInfo fieldInfo, float[] centroid) throws IOException {+ OptimizedScalarQuantizer quantizer =+ new OptimizedScalarQuantizer(fieldInfo.getVectorSimilarityFunction());+ FloatVectorValues vectorValues =+ fieldInfo.getVectorEncoding() == VectorEncoding.FLOAT16+ ? new Float16AsFloatVectorValues(reader.getFloat16VectorValues(fieldInfo.name))+ : reader.getFloatVectorValues(fieldInfo.name);+ if (fieldInfo.getVectorSimilarityFunction() == COSINE) {+ vectorValues = new NormalizedFloatVectorValues(vectorValues);+ }+ return new QuantizedFloatVectorValues(vectorValues, quantizer, encoding, centroid);+ }+@Overridepublic 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().isFloatingPoint() == false) {+ rawVectorDelegate.mergeOneFlatVectorField(fieldInfo, mergeState);return;}- final float[] centroid;+ switch (mode) {+ case CENTERED -> {+ failIfFloatVectorsMissing(fieldInfo, mergeState);+ mergeOneFlatVectorFieldCentered(fieldInfo, mergeState);+ }+ case DATA_BLIND_WITH_FLOATS -> {+ // The output segment stores full-precision floats, so every contributing segment must+ // provide them; the quantized merge then re-quantizes them against the zero centroid.+ failIfFloatVectorsMissing(fieldInfo, mergeState);+ rawVectorDelegate.mergeOneFlatVectorField(fieldInfo, mergeState);+ mergeOneFlatVectorFieldDataBlind(fieldInfo, mergeState);+ }+ case DATA_BLIND_WITHOUT_FLOATS -> mergeOneFlatVectorFieldDataBlind(fieldInfo, mergeState);+ }+ }++ /**+ * Fails the merge when the output mode stores full-precision float vectors ({@code mode} is+ * {@link Mode#CENTERED} or {@link Mode#DATA_BLIND_WITH_FLOATS}) but a contributing segment cannot+ * supply them, e.g. a segment written in {@link Mode#DATA_BLIND_WITHOUT_FLOATS}. Such segments+ * can only offer dequantized (already-quantized) values in place of true full-precision vectors;+ * this fails loudly rather than silently degrading quality.+ */+ private void failIfFloatVectorsMissing(FieldInfo fieldInfo, MergeState mergeState)+ throws IOException {+ for (int i = 0; i < mergeState.knnVectorsReaders.length; i++) {+ KnnVectorsReader reader = mergeState.knnVectorsReaders[i];+ if (reader == null || hasRawVectorValues(reader, fieldInfo)) {+ continue;+ }+ // Tolerate segments that have no vectors for the field at all; they contribute nothing.+ FloatVectorValues values = floatingPointVectorValues(reader, fieldInfo);+ if (values == null || values.size() == 0) {+ continue;+ }+ throw new IllegalStateException(+ "Cannot merge field \""+ + fieldInfo.name+ + "\" from a segment without full-precision float vectors into "+ + mode+ + " mode, which stores float vectors. The contributing segment was likely written"+ + " in DATA_BLIND_WITHOUT_FLOATS mode and its vectors cannot be carried over.");+ }+ }++ private void mergeOneFlatVectorFieldCentered(FieldInfo fieldInfo, MergeState mergeState)+ throws IOException {+ // Don't need access to the random vectors, we can just use the merged+ rawVectorDelegate.mergeOneFlatVectorField(fieldInfo, mergeState);final float[] mergedCentroid = new float[fieldInfo.getVectorDimension()];int vectorCount = mergeAndRecalculateCentroids(mergeState, fieldInfo, mergedCentroid);- centroid = mergedCentroid;if (segmentWriteState.infoStream.isEnabled(QUANTIZED_VECTOR_COMPONENT)) {segmentWriteState.infoStream.message(QUANTIZED_VECTOR_COMPONENT, "Vectors' count:" + vectorCount);}QuantizedByteVectorValues quantizedVectorValues =- mergedQuantizedVectorValues(fieldInfo, mergeState, centroid);+ mergedQuantizedVectorValues(fieldInfo, mergeState, mergedCentroid);long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES);DocsWithFieldSet docsWithField = writeVectorData(vectorData, quantizedVectorValues);long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;float centroidDp =- docsWithField.cardinality() > 0 ? VectorUtil.dotProduct(centroid, centroid) : 0;+ docsWithField.cardinality() > 0 ? VectorUtil.dotProduct(mergedCentroid, mergedCentroid) : 0;writeMeta(fieldInfo,segmentWriteState.segmentInfo.maxDoc(),vectorDataOffset,vectorDataLength,- centroid,+ mergedCentroid,centroidDp,docsWithField);}+ private void mergeOneFlatVectorFieldDataBlind(FieldInfo fieldInfo, MergeState mergeState)+ throws IOException {+ float[] zeroCentroid = new float[fieldInfo.getVectorDimension()];+ // Build one merged view where, per contributing segment, either its existing quantized bytes+ // are passed through or its float vectors are quantized fresh. Inputs already quantized to+ // {@code encoding} against a zero centroid (data-blind segments) are copied directly; they are+ // never dequantized and re-quantized, which would only add loss. Segments with raw floats are+ // quantized fresh, as their stored bytes live in a different (centered) quantization space.+ List<QuantizedByteVectorValuesSub> subs = new ArrayList<>();+ for (int i = 0; i < mergeState.knnVectorsReaders.length; i++) {+ KnnVectorsReader reader = mergeState.knnVectorsReaders[i];+ if (reader == null) {+ continue;+ }+ QuantizedByteVectorValues values;+ if (hasRawVectorValues(reader, fieldInfo)) {+ // Segment stored full-precision floats; quantize them against the zero centroid.+ values = quantizeFromFloats(reader, fieldInfo, zeroCentroid);+ } else {+ QuantizedByteVectorValues qvv = getQuantizedVectorValues(reader, fieldInfo.name);+ if (qvv == null || qvv.size() == 0) {+ continue;+ }+ if (qvv.getScalarEncoding() != encoding) {+ // Re-quantization from raw floats would be required, which is not possible when raw+ // floats were never written.+ throw new IllegalStateException(+ "Cannot merge field \""+ + fieldInfo.name+ + "\" from data-blind segment with encoding "+ + qvv.getScalarEncoding()+ + " into data-blind format with encoding "+ + encoding+ + ": re-quantization requires raw float vectors");+ }+ Mode sourceMode = getMode(reader, fieldInfo.name);+ if (sourceMode != null && sourceMode != Mode.CENTERED) {+ // Quantized-only segment whose bytes already match the output format (encoding and zero+ // centroid): copy them directly.+ values = qvv;+ } else {+ // Bytes were produced against a (possibly unknown) non-zero centroid, so they cannot be+ // passed through into the zero-centroid output; re-quantize from floats.+ values = quantizeFromFloats(reader, fieldInfo, zeroCentroid);+ }+ }+ subs.add(new QuantizedByteVectorValuesSub(mergeState.docMaps[i], values));+ }+ long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES);+ MergedQuantizedByteVectorValues mergedQBVV =+ MergedQuantizedByteVectorValues.merge(mergeState, zeroCentroid, encoding, subs);+ DocsWithFieldSet docsWithField = writeVectorData(vectorData, mergedQBVV);+ long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;+ // centroidDp is 0 (zero centroid); the data-blind metadata omits it and the centroid.+ writeMeta(+ fieldInfo,+ segmentWriteState.segmentInfo.maxDoc(),+ vectorDataOffset,+ vectorDataLength,+ null,+ 0f,+ docsWithField);+ }+static DocsWithFieldSet writeVectorData(IndexOutput output, QuantizedByteVectorValues quantizedByteVectorValues) throws IOException {DocsWithFieldSet docsWithField = new DocsWithFieldSet();@@ -412,14 +572,74 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {IOUtils.close(meta, vectorData, rawVectorDelegate);}- static float[] getCentroid(KnnVectorsReader vectorsReader, String fieldName) {+ /**+ * Unwraps a merge-time reader down to the flat vectors reader. The per-field wrapper unwraps to+ * the HNSW reader, which must additionally be unwrapped to reach the flat reader.+ */+ private static KnnVectorsReader unwrapToFlatReader(+ KnnVectorsReader vectorsReader, String fieldName) {vectorsReader = vectorsReader.unwrapReaderForField(fieldName);+ if (vectorsReader instanceof Lucene99HnswVectorsReader hnswReader) {+ vectorsReader = hnswReader.getFlatVectorsReader().unwrapReaderForField(fieldName);+ }+ return vectorsReader;+ }++ static float[] getCentroid(KnnVectorsReader vectorsReader, String fieldName) {+ vectorsReader = unwrapToFlatReader(vectorsReader, fieldName);if (vectorsReader instanceof Lucene104ScalarQuantizedVectorsReader reader) {return reader.getCentroid(fieldName);}return null;}+ /** Returns the mode the source segment was written with, or null for foreign readers. */+ static Mode getMode(KnnVectorsReader vectorsReader, String fieldName) {+ vectorsReader = unwrapToFlatReader(vectorsReader, fieldName);+ if (vectorsReader instanceof Lucene104ScalarQuantizedVectorsReader reader) {+ return reader.getMode(fieldName);+ }+ return null;+ }++ static QuantizedByteVectorValues getQuantizedVectorValues(+ KnnVectorsReader vectorsReader, String fieldName) throws IOException {+ vectorsReader = unwrapToFlatReader(vectorsReader, fieldName);+ if (vectorsReader instanceof Lucene104ScalarQuantizedVectorsReader reader) {+ return reader.getQuantizedVectorValues(fieldName);+ }+ return null;+ }++ /**+ * Returns whether the segment stores full-precision vectors for this field, or false when the+ * field is absent or byte-encoded. Data-blind segments report {@code false} since only quantized+ * bytes were written.+ */+ private static boolean hasRawVectorValues(KnnVectorsReader vectorsReader, FieldInfo fieldInfo)+ throws IOException {+ vectorsReader = unwrapToFlatReader(vectorsReader, fieldInfo.name);+ if (vectorsReader instanceof Lucene104ScalarQuantizedVectorsReader reader) {+ return switch (fieldInfo.getVectorEncoding()) {+ case FLOAT32 -> reader.hasRawFloatVectors(fieldInfo.name);+ case FLOAT16 -> reader.hasRawFloat16Vectors(fieldInfo.name);+ case BYTE -> false;+ };+ }+ // Foreign format: assume full-precision vectors are available when the reader serves them.+ return switch (fieldInfo.getVectorEncoding()) {+ case FLOAT32 -> {+ FloatVectorValues values = vectorsReader.getFloatVectorValues(fieldInfo.name);+ yield values != null && values.size() > 0;+ }+ case FLOAT16 -> {+ Float16VectorValues values = vectorsReader.getFloat16VectorValues(fieldInfo.name);+ yield values != null && values.size() > 0;+ }+ case BYTE -> false;+ };+ }+/*** Returns the reader's floating-point vectors viewed as fp32, inflating fp16 on read, or null* when the field is absent from this reader or is byte-encoded.@@ -456,8 +676,13 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {float[] centroid = getCentroid(knnVectorsReader, fieldInfo.name);totalVectorCount += vectorCount;// If there aren't centroids, or previously clustered with more than one cluster- // or if there are deleted docs, we must recalculate the centroid- if (centroid == null || mergeState.liveDocs[i] != null) {+ // or if there are deleted docs, we must recalculate the centroid. A data-blind segment+ // stores no centroid (its vectors were quantized against zero); it can't be combined with+ // the others, so recompute from the vectors.+ Mode mode = getMode(knnVectorsReader, fieldInfo.name);+ if (centroid == null+ || (mode != null && mode != Mode.CENTERED)+ || mergeState.liveDocs[i] != null) {recalculate = true;break;}@@ -524,16 +749,19 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {@Overridepublic long ramBytesUsed() {long total = SHALLOW_RAM_BYTES_USED;- // The rawVectorDelegate tracks all vector data for both byte and float32 fields.- // For byte vector fields (which bypass our FieldWriter), this is the only accounting.- // For float32 fields, this covers the flat vector data; our FieldWriter adds the- // quantization-specific overhead (magnitudes, dimensionSums) on top.+ // The rawVectorDelegate tracks all vector data for byte and float fields that were+ // written through it. For data-blind fields (held only in memory), it accounts for+ // nothing, so those are tracked via field.ramBytesUsed() instead.total += rawVectorDelegate.ramBytesUsed();for (FieldWriter<?> field : fields) {- // quantizationOverheadBytesUsed() intentionally excludes flatFieldVectorsWriter- // because rawVectorDelegate.ramBytesUsed() already accounts for all flat vector- // data at the writer level. Calling field.ramBytesUsed() here would double-count.- total += field.quantizationOverheadBytesUsed();+ if (mode != Mode.DATA_BLIND_WITHOUT_FLOATS) {+ // quantizationOverheadBytesUsed() intentionally excludes flatFieldVectorsWriter+ // because rawVectorDelegate.ramBytesUsed() already accounts for all flat vector+ // data at the writer level. Calling field.ramBytesUsed() here would double-count.+ total += field.quantizationOverheadBytesUsed();+ } else {+ total += field.ramBytesUsed();+ }}return total;}@@ -547,24 +775,36 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {private final FloatArrayList magnitudes = new FloatArrayList();protected final int dim;- FieldWriter(FieldInfo fieldInfo, FlatFieldVectorsWriter<T> flatFieldVectorsWriter) {+ protected final boolean enableCentering;++ FieldWriter(+ FieldInfo fieldInfo,+ FlatFieldVectorsWriter<T> flatFieldVectorsWriter,+ boolean enableCentering) {this.fieldInfo = fieldInfo;this.flatFieldVectorsWriter = flatFieldVectorsWriter;+ this.enableCentering = enableCentering;this.dim = fieldInfo.getVectorDimension();- this.dimensionSums = new float[dim];+ this.dimensionSums = enableCentering ? new float[dim] : null;}@SuppressWarnings("unchecked")static FieldWriter<?> create(- FieldInfo fieldInfo, FlatFieldVectorsWriter<?> flatFieldVectorsWriter) {+ FieldInfo fieldInfo,+ FlatFieldVectorsWriter<?> flatFieldVectorsWriter,+ boolean enableCentering) {return switch (fieldInfo.getVectorEncoding()) {case BYTE -> throw new UnsupportedOperationException("Byte Vectors aren't supported");case FLOAT32 ->new Float32FieldWriter(- fieldInfo, (FlatFieldVectorsWriter<float[]>) flatFieldVectorsWriter);+ fieldInfo,+ (FlatFieldVectorsWriter<float[]>) flatFieldVectorsWriter,+ enableCentering);case FLOAT16 ->new Float16FieldWriter(- fieldInfo, (FlatFieldVectorsWriter<short[]>) flatFieldVectorsWriter);+ fieldInfo,+ (FlatFieldVectorsWriter<short[]>) flatFieldVectorsWriter,+ enableCentering);};}@@ -588,6 +828,10 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {if (finished) {return;}+ if (flatFieldVectorsWriter.isFinished() == false) {+ // In-memory writers are not flushed through the raw delegate, so finish them here.+ flatFieldVectorsWriter.finish();+ }assert flatFieldVectorsWriter.isFinished();finished = true;}@@ -605,17 +849,19 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {/*** Adds {@code vector} to the centroid sums, unit-scaled when COSINE, and caches its magnitude- * for {@link #scaleToUnitLength}.+ * for {@link #scaleToUnitLength}. In data-blind mode the centroid sums are not accumulated.*/protected final void accumulate(float[] vector) {if (fieldInfo.getVectorSimilarityFunction() == COSINE) {float dp = VectorUtil.dotProduct(vector, vector);float divisor = (float) Math.sqrt(dp);magnitudes.add(divisor);- for (int i = 0; i < vector.length; i++) {- dimensionSums[i] += (vector[i] / divisor);+ if (enableCentering) {+ for (int i = 0; i < vector.length; i++) {+ dimensionSums[i] += (vector[i] / divisor);+ }}- } else {+ } else if (enableCentering) {for (int i = 0; i < vector.length; i++) {dimensionSums[i] += vector[i];}@@ -624,9 +870,13 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {/*** Returns the mean of the accumulated vectors, unit-length for COSINE, used as the quantization- * centroid. All zeroes when no vectors were added.+ * centroid. All zeroes when no vectors were added, or when centering is disabled (data-blind+ * mode).*/protected final float[] computeCentroid() {+ if (enableCentering == false) {+ return new float[dim];+ }float[] centroid = new float[dim];int vectorCount = getVectors().size();if (vectorCount > 0) {@@ -659,7 +909,9 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {long quantizationOverheadBytesUsed() {long size = SHALLOW_SIZE;size += magnitudes.ramBytesUsed();- size += RamUsageEstimator.sizeOf(dimensionSums);+ if (dimensionSums != null) {+ size += RamUsageEstimator.sizeOf(dimensionSums);+ }return size;}@@ -675,8 +927,10 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {private final float[] normalized;Float32FieldWriter(- FieldInfo fieldInfo, FlatFieldVectorsWriter<float[]> flatFieldVectorsWriter) {- super(fieldInfo, flatFieldVectorsWriter);+ FieldInfo fieldInfo,+ FlatFieldVectorsWriter<float[]> flatFieldVectorsWriter,+ boolean enableCentering) {+ super(fieldInfo, flatFieldVectorsWriter, enableCentering);this.normalized = new float[dim];}@@ -706,8 +960,10 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {private final float[] inflated;Float16FieldWriter(- FieldInfo fieldInfo, FlatFieldVectorsWriter<short[]> flatFieldVectorsWriter) {- super(fieldInfo, flatFieldVectorsWriter);+ FieldInfo fieldInfo,+ FlatFieldVectorsWriter<short[]> flatFieldVectorsWriter,+ boolean enableCentering) {+ super(fieldInfo, flatFieldVectorsWriter, enableCentering);this.inflated = new float[dim];}@@ -740,6 +996,86 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {}}+ /**+ * In-memory storage for full-precision vectors used in data-blind mode; nothing is written to+ * disk. fp16 vectors are kept as fp16 so HNSW wrappers can read them back as {@link+ * Float16VectorValues}.+ */+ private static class InMemoryFieldWriter<T> extends FlatFieldVectorsWriter<T> {+ private static final long SHALLOW_SIZE = shallowSizeOfInstance(InMemoryFieldWriter.class);+ private final FieldInfo fieldInfo;+ private final List<T> vectors = new ArrayList<>();+ private final DocsWithFieldSet docsWithField = new DocsWithFieldSet();+ private final int bytesPerElement;+ private boolean finished;+ private int lastDocID = -1;++ InMemoryFieldWriter(FieldInfo fieldInfo, int bytesPerElement) {+ this.fieldInfo = fieldInfo;+ this.bytesPerElement = bytesPerElement;+ }++ @Override+ public void addValue(int docID, T vectorValue) throws IOException {+ if (finished) {+ throw new IllegalStateException("already finished, cannot add more values");+ }+ if (docID == lastDocID) {+ throw new IllegalArgumentException(+ "VectorValuesField \""+ + fieldInfo.name+ + "\" appears more than once in this document (only one value is allowed per field)");+ }+ assert docID > lastDocID;+ vectors.add(copyValue(vectorValue));+ docsWithField.add(docID);+ lastDocID = docID;+ }++ @SuppressWarnings("unchecked")+ @Override+ public T copyValue(T vectorValue) {+ int dim = fieldInfo.getVectorDimension();+ return (T)+ (vectorValue instanceof float[] f+ ? ArrayUtil.copyOfSubArray(f, 0, dim)+ : ArrayUtil.copyOfSubArray((short[]) vectorValue, 0, dim));+ }++ @Override+ public List<T> getVectors() {+ return vectors;+ }++ @Override+ public DocsWithFieldSet getDocsWithFieldSet() {+ return docsWithField;+ }++ @Override+ public void finish() {+ finished = true;+ }++ @Override+ public boolean isFinished() {+ return finished;+ }++ @Override+ public long ramBytesUsed() {+ long size = SHALLOW_SIZE;+ if (vectors.isEmpty()) {+ return size;+ }+ return size+ + docsWithField.ramBytesUsed()+ + (long) vectors.size()+ * (RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.NUM_BYTES_ARRAY_HEADER)+ + (long) vectors.size() * fieldInfo.getVectorDimension() * bytesPerElement;+ }+ }+static class QuantizedFloatVectorValues extends QuantizedByteVectorValues {private OptimizedScalarQuantizer.QuantizationResult corrections;private final byte[] quantized;@@ -860,6 +1196,173 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {}}+ private static final class QuantizedByteVectorValuesSub extends DocIDMerger.Sub {+ final QuantizedByteVectorValues values;+ final KnnVectorValues.DocIndexIterator iterator;++ QuantizedByteVectorValuesSub(MergeState.DocMap docMap, QuantizedByteVectorValues values) {+ super(docMap);+ this.values = values;+ this.iterator = values.iterator();+ assert iterator.docID() == -1;+ }++ @Override+ public int nextDoc() throws IOException {+ return iterator.nextDoc();+ }+ }++ /** Merged view of {@link QuantizedByteVectorValues} from multiple segments. */+ static final class MergedQuantizedByteVectorValues extends QuantizedByteVectorValues {+ private final List<QuantizedByteVectorValuesSub> subs;+ private final DocIDMerger<QuantizedByteVectorValuesSub> docIdMerger;+ private final int size;+ private final float[] centroid;+ private final float centroidDP;+ private final ScalarEncoding scalarEncoding;+ private int docId = -1;+ private int lastOrd = -1;+ private QuantizedByteVectorValuesSub current;++ private MergedQuantizedByteVectorValues(+ List<QuantizedByteVectorValuesSub> subs,+ MergeState mergeState,+ float[] centroid,+ ScalarEncoding scalarEncoding)+ throws IOException {+ this.subs = subs;+ this.docIdMerger = DocIDMerger.of(subs, mergeState.needsIndexSort);+ int totalSize = 0;+ for (QuantizedByteVectorValuesSub sub : subs) {+ totalSize += sub.values.size();+ }+ this.size = totalSize;+ this.centroid = centroid;+ this.centroidDP = VectorUtil.dotProduct(centroid, centroid);+ this.scalarEncoding = scalarEncoding;+ }++ /**+ * Merges the pre-built per-segment {@link QuantizedByteVectorValuesSub}s in doc order. Each sub+ * contributes either a segment's stored quantized bytes (passed through untouched) or freshly+ * quantized values; the caller decides which per segment.+ */+ static MergedQuantizedByteVectorValues merge(+ MergeState mergeState,+ float[] centroid,+ ScalarEncoding encoding,+ List<QuantizedByteVectorValuesSub> subs)+ throws IOException {+ return new MergedQuantizedByteVectorValues(subs, mergeState, centroid, encoding);+ }++ @Override+ public DocIndexIterator iterator() {+ return new DocIndexIterator() {+ private int index = -1;++ @Override+ public int docID() {+ return docId;+ }++ @Override+ public int index() {+ return index;+ }++ @Override+ public int nextDoc() throws IOException {+ current = docIdMerger.next();+ if (current == null) {+ docId = NO_MORE_DOCS;+ index = NO_MORE_DOCS;+ } else {+ docId = current.mappedDocID;+ ++lastOrd;+ ++index;+ }+ return docId;+ }++ @Override+ public int advance(int target) {+ throw new UnsupportedOperationException();+ }++ @Override+ public long cost() {+ return size;+ }+ };+ }++ @Override+ public byte[] vectorValue(int ord) throws IOException {+ if (ord != lastOrd) {+ throw new IllegalStateException(+ "only supports forward iteration: ord=" + ord + ", lastOrd=" + lastOrd);+ }+ return current.values.vectorValue(current.iterator.index());+ }++ @Override+ public OptimizedScalarQuantizer.QuantizationResult getCorrectiveTerms(int ord)+ throws IOException {+ if (ord != lastOrd) {+ throw new IllegalStateException(+ "only supports forward iteration: ord=" + ord + ", lastOrd=" + lastOrd);+ }+ return current.values.getCorrectiveTerms(current.iterator.index());+ }++ @Override+ public int dimension() {+ return subs.isEmpty() ? 0 : subs.get(0).values.dimension();+ }++ @Override+ public int size() {+ return size;+ }++ @Override+ public int ordToDoc(int ord) {+ throw new UnsupportedOperationException();+ }++ @Override+ public ScalarEncoding getScalarEncoding() {+ return scalarEncoding;+ }++ @Override+ public float[] getCentroid() {+ return centroid;+ }++ @Override+ public float getCentroidDP() {+ return centroidDP;+ }++ @Override+ public OptimizedScalarQuantizer getQuantizer() {+ throw new UnsupportedOperationException();+ }++ @Override+ public VectorScorer scorer(float[] target) {+ throw new UnsupportedOperationException();+ }++ @Override+ public QuantizedByteVectorValues copy() {+ throw new UnsupportedOperationException();+ }+ }+/*** Exposes a {@link Float16VectorValues} as {@link FloatVectorValues}, inflating fp16 to fp32 on* read, so the merge path can reuse the fp32 quantization classes.diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/OffHeapScalarQuantizedFloat16VectorValues.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/OffHeapScalarQuantizedFloat16VectorValues.javaindex a18065d765f..9e30f2193d3 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/OffHeapScalarQuantizedFloat16VectorValues.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/OffHeapScalarQuantizedFloat16VectorValues.java@@ -89,7 +89,7 @@ abstract class OffHeapScalarQuantizedFloat16VectorValues extends Float16VectorVathis.byteBuffer = ByteBuffer.allocate(docPackedLength);this.vectorValue = new short[dimension];this.byteValue = byteBuffer.array();- this.unpackedByteVectorValue = new byte[dimension];+ this.unpackedByteVectorValue = new byte[encoding.getDiscreteDimensions(dimension)];}@Overridediff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/OffHeapScalarQuantizedFloatVectorValues.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/OffHeapScalarQuantizedFloatVectorValues.javaindex 8fa87a271d2..7cb1bcd9f57 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/OffHeapScalarQuantizedFloatVectorValues.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/OffHeapScalarQuantizedFloatVectorValues.java@@ -93,7 +93,7 @@ abstract class OffHeapScalarQuantizedFloatVectorValues extends FloatVectorValuesthis.byteBuffer = ByteBuffer.allocate(docPackedLength);this.vectorValue = new float[dimension];this.byteValue = byteBuffer.array();- this.unpackedByteVectorValue = new byte[dimension];+ this.unpackedByteVectorValue = new byte[encoding.getDiscreteDimensions(dimension)];}@Overridediff --git a/lucene/core/src/java/org/apache/lucene/util/quantization/OptimizedScalarQuantizer.java b/lucene/core/src/java/org/apache/lucene/util/quantization/OptimizedScalarQuantizer.javaindex 6038df8d5eb..1926352662d 100644--- a/lucene/core/src/java/org/apache/lucene/util/quantization/OptimizedScalarQuantizer.java+++ b/lucene/core/src/java/org/apache/lucene/util/quantization/OptimizedScalarQuantizer.java@@ -119,7 +119,9 @@ public class OptimizedScalarQuantizer {public QuantizationResult[] multiScalarQuantize(float[] vector, byte[][] destinations, byte[] bits, float[] centroid) {assert similarityFunction != COSINE || VectorUtil.isUnitVector(vector);- assert similarityFunction != COSINE || VectorUtil.isUnitVector(centroid);+ assert similarityFunction != COSINE+ || VectorUtil.isUnitVector(centroid)+ || VectorUtil.dotProduct(centroid, centroid) == 0;assert bits.length == destinations.length;float[] intervalScratch = new float[2];double vecMean = 0;@@ -187,7 +189,9 @@ public class OptimizedScalarQuantizer {public QuantizationResult scalarQuantize(float[] vector, byte[] destination, byte bits, float[] centroid) {assert similarityFunction != COSINE || VectorUtil.isUnitVector(vector);- assert similarityFunction != COSINE || VectorUtil.isUnitVector(centroid);+ assert similarityFunction != COSINE+ || VectorUtil.isUnitVector(centroid)+ || VectorUtil.dotProduct(centroid, centroid) == 0;assert vector.length <= destination.length;assert bits > 0 && bits <= 8;float[] intervalScratch = new float[2];@@ -259,7 +263,9 @@ public class OptimizedScalarQuantizer {float[] centroid) {int nSteps = (1 << bits) - 1;double step = (upperInterval - lowerInterval) / nSteps;- for (int h = 0; h < quantized.length; h++) {+ // The quantized input may hold rounded-up dimensions for packed encodings; the output length+ // defines how many are real.+ for (int h = 0; h < dequantized.length; h++) {double xi = (double) (quantized[h] & 0xFF) * step + lowerInterval;dequantized[h] = (float) (xi + centroid[h]);}@@ -289,7 +295,9 @@ public class OptimizedScalarQuantizer {float[] centroid) {int nSteps = (1 << bits) - 1;double step = (upperInterval - lowerInterval) / nSteps;- for (int h = 0; h < quantized.length; h++) {+ // The quantized input may hold rounded-up dimensions for packed encodings; the output length+ // defines how many are real.+ for (int h = 0; h < dequantized.length; h++) {double xi = (double) (quantized[h] & 0xFF) * step + lowerInterval;dequantized[h] = Float.floatToFloat16((float) (xi + centroid[h]));}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 c2f4f4584e8..7a335f50b53 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@@ -103,7 +103,7 @@ public class TestLucene104HnswScalarQuantizedVectorsFormat extends BaseKnnVector"Lucene104HnswScalarQuantizedVectorsFormat(name=Lucene104HnswScalarQuantizedVectorsFormat,"+ " maxConn=10, beamWidth=20, tinySegmentsThreshold=100,"+ " flatVectorFormat=Lucene104ScalarQuantizedVectorsFormat(name=Lucene104ScalarQuantizedVectorsFormat,"- + " encoding=UNSIGNED_BYTE,"+ + " encoding=UNSIGNED_BYTE, mode=CENTERED,"+ " flatVectorScorer=Lucene104ScalarQuantizedVectorScorer(nonQuantizedDelegate=%s()),"+ " rawVectorFormat=Lucene99FlatVectorsFormat(vectorsScorer=%s())))";@@ -277,6 +277,36 @@ public class TestLucene104HnswScalarQuantizedVectorsFormat extends BaseKnnVectorScalarEncoding.UNSIGNED_BYTE, 20, 100, 1, new SameThreadExecutorService()));}+ public void testDataBlindWithoutFloatsRejectsAsymmetricEncodings() {+ for (ScalarEncoding encoding : ScalarEncoding.values()) {+ if (encoding.isAsymmetric()) {+ IllegalArgumentException e =+ expectThrows(+ IllegalArgumentException.class,+ () ->+ new Lucene104HnswScalarQuantizedVectorsFormat(+ encoding,+ Lucene104ScalarQuantizedVectorsFormat.Mode.DATA_BLIND_WITHOUT_FLOATS,+ Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN,+ Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH,+ 1,+ null,+ Lucene99HnswVectorsFormat.HNSW_GRAPH_THRESHOLD));+ assertTrue(e.getMessage(), e.getMessage().contains(encoding.toString()));+ } else {+ assertNotNull(+ new Lucene104HnswScalarQuantizedVectorsFormat(+ encoding,+ Lucene104ScalarQuantizedVectorsFormat.Mode.DATA_BLIND_WITHOUT_FLOATS,+ Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN,+ Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH,+ 1,+ null,+ Lucene99HnswVectorsFormat.HNSW_GRAPH_THRESHOLD));+ }+ }+ }+// Ensures that all expected vector similarity functions are translatable in the format.public void testVectorSimilarityFuncs() {// This does not necessarily have to be all similarity functions, but@@ -311,6 +341,70 @@ public class TestLucene104HnswScalarQuantizedVectorsFormat extends BaseKnnVector}}+ public void testDataBlindHnswSearch() throws Exception {+ String fieldName = "field";+ int numVectors = random().nextInt(99, 500);+ int dims = random().nextInt(12, 65);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ // asymmetric encodings are rejected with DATA_BLIND_WITHOUT_FLOATS, so restrict to symmetric+ // ones; the encoding field may itself be asymmetric since it is chosen randomly in setUp+ ScalarEncoding dataBlindEncoding = encoding;+ while (dataBlindEncoding.isAsymmetric()) {+ dataBlindEncoding = ScalarEncoding.values()[random().nextInt(ScalarEncoding.values().length)];+ }+ KnnVectorsFormat dataBlind =+ new Lucene104HnswScalarQuantizedVectorsFormat(+ dataBlindEncoding,+ Lucene104ScalarQuantizedVectorsFormat.Mode.DATA_BLIND_WITHOUT_FLOATS,+ Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN,+ Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH,+ 1,+ null,+ Lucene99HnswVectorsFormat.HNSW_GRAPH_THRESHOLD);+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(+ dir, newIndexWriterConfig().setCodec(TestUtil.alwaysKnnVectorsFormat(dataBlind)))) {+ int k = random().nextInt(5, 30);+ for (int i = 0; i < numVectors; i++) {+ Document doc = new Document();+ float[] vector = randomVector(dims);+ if (similarityFunction == VectorSimilarityFunction.DOT_PRODUCT) {+ vector = VectorUtil.l2normalize(vector);+ }+ doc.add(new KnnFloatVectorField(fieldName, vector, similarityFunction));+ w.addDocument(doc);+ if (i % 50 == 0) {+ w.commit(); // create multiple segments to exercise the data-blind merge path+ }+ }+ w.commit();+ float[] query = randomVector(dims);+ if (similarityFunction == VectorSimilarityFunction.DOT_PRODUCT) {+ query = VectorUtil.l2normalize(query);+ }+ // Merge the data-blind segments into one, then read and search the single leaf.+ w.forceMerge(1);+ try (IndexReader reader = DirectoryReader.open(w)) {+ LeafReader r = getOnlyLeafReader(reader);+ FloatVectorValues vectorValues = r.getFloatVectorValues(fieldName);+ // Data-blind segments expose a bare dequantizing view; no raw float vectors are present.+ assertFalse(+ vectorValues+ instanceof Lucene104ScalarQuantizedVectorsReader.ScalarQuantizedVectorValues);+ TopDocs td =+ r.searchNearestVectors(+ fieldName,+ query,+ k,+ AcceptDocs.fromLiveDocs(null, r.maxDoc()),+ Integer.MAX_VALUE);+ assertEquals(k, td.scoreDocs.length);+ }+ }+ }+ }+@Overrideprotected boolean supportsFloatVectorFallback() {return false;diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104ScalarQuantizedVectorsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104ScalarQuantizedVectorsFormat.javaindex f253adb05d3..9089712156c 100644--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104ScalarQuantizedVectorsFormat.java+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104ScalarQuantizedVectorsFormat.java@@ -24,6 +24,7 @@ import static org.hamcrest.Matchers.oneOf;import java.io.IOException;import java.util.ArrayList;+import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Locale;@@ -33,6 +34,7 @@ import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.codecs.FilterCodec;import org.apache.lucene.codecs.KnnVectorsFormat;import org.apache.lucene.codecs.KnnVectorsReader;+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorsFormat.Mode;import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;import org.apache.lucene.document.Document;import org.apache.lucene.document.KnnFloat16VectorField;@@ -46,7 +48,9 @@ import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.KnnVectorValues;import org.apache.lucene.index.LeafReader;+import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.NoMergePolicy;+import org.apache.lucene.index.SerialMergeScheduler;import org.apache.lucene.index.VectorSimilarityFunction;import org.apache.lucene.search.DocIdSetIterator;import org.apache.lucene.search.IndexSearcher;@@ -164,6 +168,7 @@ public class TestLucene104ScalarQuantizedVectorsFormat extends BaseKnnVectorsFor"Lucene104ScalarQuantizedVectorsFormat("+ "name=Lucene104ScalarQuantizedVectorsFormat, "+ "encoding=UNSIGNED_BYTE, "+ + "mode=CENTERED, "+ "flatVectorScorer=Lucene104ScalarQuantizedVectorScorer(nonQuantizedDelegate=%s()), "+ "rawVectorFormat=Lucene99FlatVectorsFormat(vectorsScorer=%s()))";var defaultScorer =@@ -583,4 +588,844 @@ public class TestLucene104ScalarQuantizedVectorsFormat extends BaseKnnVectorsForCodecUtil.writeFooter(out);}}++ /** Returns a codec that always uses the data-blind variant of this format. */+ private Codec dataBlindCodec() {+ return TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(+ encoding, Lucene104ScalarQuantizedVectorsFormat.Mode.DATA_BLIND_WITHOUT_FLOATS));+ }++ /**+ * Returns a codec that always uses the data-blind variant of this format that still stores+ * full-precision float vectors.+ */+ private Codec dataBlindWithFloatsCodec() {+ return TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(+ encoding, Lucene104ScalarQuantizedVectorsFormat.Mode.DATA_BLIND_WITH_FLOATS));+ }++ public void testDataBlindSearchCorrectness() throws Exception {+ String fieldName = "field";+ int numVectors = random().nextInt(99, 500);+ int dims = random().nextInt(4, 65);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ KnnFloatVectorField knnField =+ new KnnFloatVectorField(fieldName, randomVector(dims), similarityFunction);+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ for (int i = 0; i < numVectors; i++) {+ Document doc = new Document();+ knnField.setVectorValue(randomVector(dims));+ doc.add(knnField);+ w.addDocument(doc);+ }+ w.commit();++ try (IndexReader reader = DirectoryReader.open(w)) {+ IndexSearcher searcher = new IndexSearcher(reader);+ final int k = random().nextInt(5, 50);+ float[] queryVector = randomVector(dims);+ TopDocs collectedDocs =+ searcher.search(new KnnFloatVectorQuery(fieldName, queryVector, k), k);+ assertEquals(k, collectedDocs.totalHits.value());+ assertEquals(TotalHits.Relation.EQUAL_TO, collectedDocs.totalHits.relation());+ }+ }+ }+ }++ /**+ * Data-blind segments never write full-precision float vectors, so {@link FloatVectorValues} must+ * be a bare dequantizing view rather than one backed by raw vectors.+ */+ public void testDataBlindNoRawFloatVectors() throws Exception {+ String fieldName = "field";+ int numVectors = random().nextInt(4, 50);+ int dims = random().nextInt(4, 65);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ for (int i = 0; i < numVectors; i++) {+ Document doc = new Document();+ doc.add(new KnnFloatVectorField(fieldName, randomVector(dims), similarityFunction));+ w.addDocument(doc);+ }+ }+ try (IndexReader reader = DirectoryReader.open(dir)) {+ LeafReader r = getOnlyLeafReader(reader);+ FloatVectorValues vectorValues = r.getFloatVectorValues(fieldName);+ assertEquals(numVectors, vectorValues.size());+ assertFalse(+ vectorValues+ instanceof Lucene104ScalarQuantizedVectorsReader.ScalarQuantizedVectorValues);+ }+ }+ }++ public void testDataBlindMultiSegmentMerge() throws Exception {+ String fieldName = "field";+ int numVectorsPerSegment = random().nextInt(4, 50);+ int dims = random().nextInt(4, 65);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ for (int s = 0; s < 2; s++) {+ for (int i = 0; i < numVectorsPerSegment; i++) {+ Document doc = new Document();+ doc.add(new KnnFloatVectorField(fieldName, randomVector(dims), similarityFunction));+ w.addDocument(doc);+ }+ w.commit();+ }+ w.forceMerge(1);+ try (IndexReader reader = DirectoryReader.open(w)) {+ assertEquals(1, reader.leaves().size());+ LeafReader r = getOnlyLeafReader(reader);+ assertEquals(2 * numVectorsPerSegment, r.getFloatVectorValues(fieldName).size());+ int k = random().nextInt(5, 20);+ IndexSearcher searcher = new IndexSearcher(reader);+ TopDocs td =+ searcher.search(new KnnFloatVectorQuery(fieldName, randomVector(dims), k), k);+ // The index holds exactly 2 * numVectorsPerSegment vectors; when k exceeds that, the+ // query can only return the vectors that exist.+ assertEquals(Math.min(k, 2 * numVectorsPerSegment), td.totalHits.value());+ }+ }+ }+ }++ /**+ * Merging a data-blind (quantized-only) segment together with a segment that still stores raw+ * floats must pass the data-blind segment's already-quantized bytes straight through, rather than+ * dequantizing and re-quantizing them (which would only add loss).+ */+ public void testDataBlindMixedMergeKeepsQuantizedBytes() throws Exception {+ assertDataBlindMixedMergeKeepsQuantizedBytes(false);+ }++ /** fp16 counterpart of {@link #testDataBlindMixedMergeKeepsQuantizedBytes}. */+ public void testDataBlindFloat16MixedMergeKeepsQuantizedBytes() throws Exception {+ assertDataBlindMixedMergeKeepsQuantizedBytes(true);+ }++ private void assertDataBlindMixedMergeKeepsQuantizedBytes(boolean float16Data) throws Exception {+ String fieldName = "field";+ int numVectorsPerSegment = random().nextInt(4, 50);+ int dims = float16Data ? 2 * random().nextInt(2, 33) : random().nextInt(4, 65);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ // One segment with no raw floats (data-blind) and one written by the centered writer (keeps+ // raw floats). Segment-name order between the two writes is not asserted.+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setUseCompoundFile(false)+ .setCodec(dataBlindCodec()))) {+ addVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment, float16Data);+ w.commit();+ }+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setUseCompoundFile(false)+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(encoding, Mode.CENTERED))))) {+ addVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment, float16Data);+ w.commit();+ }+ // Capture the data-blind segment's stored quantized bytes and corrective terms.+ List<byte[]> sourceQuantized = new ArrayList<>();+ List<OptimizedScalarQuantizer.QuantizationResult> sourceCorrections = new ArrayList<>();+ try (DirectoryReader reader = DirectoryReader.open(dir)) {+ // Exactly one leaf must be data-blind (no raw floats); the other keeps raw floats.+ boolean foundDataBlindLeaf = false;+ for (LeafReaderContext leaf : reader.leaves()) {+ Lucene104ScalarQuantizedVectorsReader vectorsReader =+ (Lucene104ScalarQuantizedVectorsReader)+ ((CodecReader) leaf.reader()).getVectorReader().unwrapReaderForField(fieldName);+ boolean hasRaw =+ float16Data+ ? vectorsReader.hasRawFloat16Vectors(fieldName)+ : vectorsReader.hasRawFloatVectors(fieldName);+ if (hasRaw == false) {+ foundDataBlindLeaf = true;+ captureQuantized(+ vectorsReader.getQuantizedVectorValues(fieldName),+ sourceQuantized,+ sourceCorrections);+ }+ }+ assertTrue("expected one data-blind segment", foundDataBlindLeaf);+ }+ assertEquals(numVectorsPerSegment, sourceQuantized.size());+ // Merge both segments through a data-blind writer.+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergeScheduler(new SerialMergeScheduler())+ .setCodec(dataBlindCodec()))) {+ w.forceMerge(1);+ try (DirectoryReader reader = DirectoryReader.open(w)) {+ assertEquals(1, reader.leaves().size());+ Lucene104ScalarQuantizedVectorsReader vectorsReader =+ (Lucene104ScalarQuantizedVectorsReader)+ ((CodecReader) getOnlyLeafReader(reader))+ .getVectorReader()+ .unwrapReaderForField(fieldName);+ QuantizedByteVectorValues qvv = vectorsReader.getQuantizedVectorValues(fieldName);+ assertEquals(2 * numVectorsPerSegment, qvv.size());+ List<byte[]> mergedVectors = new ArrayList<>();+ List<OptimizedScalarQuantizer.QuantizationResult> mergedCorrections = new ArrayList<>();+ captureQuantized(qvv, mergedVectors, mergedCorrections);+ // The data-blind segment's vectors must appear contiguously and untouched (the pass+ // through preserves byte and correction terms exactly; re-quantizing them would not).+ // The merged block position is not assertable, so accept either a leading or trailing+ // block.+ boolean leading =+ quantizedBlockEquals(+ sourceQuantized, sourceCorrections, mergedVectors, mergedCorrections, 0);+ boolean trailing =+ quantizedBlockEquals(+ sourceQuantized,+ sourceCorrections,+ mergedVectors,+ mergedCorrections,+ numVectorsPerSegment);+ assertTrue(+ "data-blind quantized bytes must be passed through untouched", leading || trailing);+ }+ }+ }+ }++ private void addVectorDocs(+ IndexWriter w,+ String field,+ int dims,+ VectorSimilarityFunction similarity,+ int count,+ boolean float16Data)+ throws IOException {+ if (float16Data) {+ addFloat16VectorDocs(w, field, dims, similarity, count);+ } else {+ addFloatVectorDocs(w, field, dims, similarity, count);+ }+ }++ private static void captureQuantized(+ QuantizedByteVectorValues qvv,+ List<byte[]> vectors,+ List<OptimizedScalarQuantizer.QuantizationResult> corrections)+ throws IOException {+ KnnVectorValues.DocIndexIterator it = qvv.iterator();+ for (int doc = it.nextDoc(); doc != NO_MORE_DOCS; doc = it.nextDoc()) {+ vectors.add(qvv.vectorValue(it.index()).clone());+ corrections.add(qvv.getCorrectiveTerms(it.index()));+ }+ }++ private static boolean quantizedBlockEquals(+ List<byte[]> expectedVectors,+ List<OptimizedScalarQuantizer.QuantizationResult> expectedCorrections,+ List<byte[]> actualVectors,+ List<OptimizedScalarQuantizer.QuantizationResult> actualCorrections,+ int offset) {+ if (offset + expectedVectors.size() > actualVectors.size()) {+ return false;+ }+ for (int i = 0; i < expectedVectors.size(); i++) {+ if (Arrays.equals(expectedVectors.get(i), actualVectors.get(offset + i)) == false) {+ return false;+ }+ var expected = expectedCorrections.get(i);+ var actual = actualCorrections.get(offset + i);+ if (Float.floatToIntBits(expected.lowerInterval())+ != Float.floatToIntBits(actual.lowerInterval())) {+ return false;+ }+ if (Float.floatToIntBits(expected.upperInterval())+ != Float.floatToIntBits(actual.upperInterval())) {+ return false;+ }+ if (Float.floatToIntBits(expected.additionalCorrection())+ != Float.floatToIntBits(actual.additionalCorrection())) {+ return false;+ }+ if (expected.quantizedComponentSum() != actual.quantizedComponentSum()) {+ return false;+ }+ }+ return true;+ }++ /**+ * Merging two data-blind segments with different encodings is impossible because re-quantization+ * would require raw float vectors that were never written.+ */+ public void testDataBlindIncompatibleEncodingMerge() throws Exception {+ String fieldName = "field";+ int numVectorsPerSegment = 1 + random().nextInt(20);+ int dims = random().nextInt(4, 33);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ // First segment: data-blind with PACKED_NIBBLE.+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(+ ScalarEncoding.PACKED_NIBBLE, Mode.DATA_BLIND_WITHOUT_FLOATS))))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ }+ // Second segment: data-blind with a different encoding (UNSIGNED_BYTE).+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(+ ScalarEncoding.UNSIGNED_BYTE, Mode.DATA_BLIND_WITHOUT_FLOATS))))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ }+ // Merging the two data-blind segments must fail: re-quantization needs raw floats that were+ // never written.+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergeScheduler(new SerialMergeScheduler())+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(+ ScalarEncoding.UNSIGNED_BYTE, Mode.DATA_BLIND_WITHOUT_FLOATS))))) {+ Throwable t =+ expectThrows(+ Exception.class,+ () -> {+ w.forceMerge(1);+ });+ assertTrue(+ "expected encoding-mismatch message, got: " + t,+ exceptionChainContains(t, "re-quantization requires raw float vectors"));+ }+ }+ }++ /**+ * Verifies the on-disk metadata version distinguishes centered (0) from data-blind (1) writes.+ */+ public void testVersionHeaders() throws Exception {+ String fieldName = "field";+ int numVectors = random().nextInt(4, 50);+ int dims = random().nextInt(4, 33);+ VectorSimilarityFunction similarityFunction = randomSimilarity();++ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setUseCompoundFile(false)+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(encoding, Mode.CENTERED))))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectors);+ }+ assertEquals(Lucene104ScalarQuantizedVectorsFormat.VERSION_START, metaVersion(dir));+ assertEquals(+ Lucene104ScalarQuantizedVectorsFormat.Mode.CENTERED,+ metaMode(dir)); // v0 metadata implies centered+ }++ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setUseCompoundFile(false)+ .setCodec(dataBlindCodec()))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectors);+ }+ assertEquals(Lucene104ScalarQuantizedVectorsFormat.VERSION_DATA_BLIND, metaVersion(dir));+ assertEquals(+ Lucene104ScalarQuantizedVectorsFormat.Mode.DATA_BLIND_WITHOUT_FLOATS, metaMode(dir));+ }++ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setUseCompoundFile(false)+ .setCodec(dataBlindWithFloatsCodec()))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectors);+ }+ assertEquals(Lucene104ScalarQuantizedVectorsFormat.VERSION_DATA_BLIND, metaVersion(dir));+ assertEquals(+ Lucene104ScalarQuantizedVectorsFormat.Mode.DATA_BLIND_WITH_FLOATS, metaMode(dir));+ }+ }++ /**+ * Merging data-blind segments (which stored no full-precision floats) through a writer that+ * stores float vectors must fail: the output format expects floats the inputs cannot provide.+ */+ public void testDataBlindSegmentsCannotMergeIntoCenteredWriter() throws Exception {+ String fieldName = "field";+ int numVectorsPerSegment = random().nextInt(1, 20);+ int dims = random().nextInt(4, 33);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ w.commit();+ }+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ w.commit();+ }+ // Re-encode through the centered writer.+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergeScheduler(new SerialMergeScheduler())+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(encoding, Mode.CENTERED))))) {+ Throwable t =+ expectThrows(+ Exception.class,+ () -> {+ w.forceMerge(1);+ });+ assertTrue(+ "expected missing-float-vectors message, got: " + t,+ exceptionChainContains(t, "without full-precision float vectors"));+ }+ }+ }++ /**+ * Data-blind mode with floats quantizes against a zero centroid but still writes full-precision+ * float vectors, which must be readable and report a zero centroid.+ */+ public void testDataBlindWithFloatsKeepsRawFloatVectors() throws Exception {+ String fieldName = "field";+ int numVectors = random().nextInt(4, 50);+ int dims = random().nextInt(4, 65);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setUseCompoundFile(false)+ .setCodec(dataBlindWithFloatsCodec()))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectors);+ }+ try (IndexReader reader = DirectoryReader.open(dir)) {+ LeafReader r = getOnlyLeafReader(reader);+ assertEquals(numVectors, r.getFloatVectorValues(fieldName).size());+ Lucene104ScalarQuantizedVectorsReader vectorsReader =+ (Lucene104ScalarQuantizedVectorsReader)+ ((CodecReader) r).getVectorReader().unwrapReaderForField(fieldName);+ assertTrue(vectorsReader.hasRawFloatVectors(fieldName));+ assertZeroCentroid(vectorsReader.getCentroid(fieldName), dims);+ assertEquals(+ Lucene104ScalarQuantizedVectorsFormat.Mode.DATA_BLIND_WITH_FLOATS, metaMode(dir));+ }+ }+ }++ /** fp16 counterpart of {@link #testDataBlindWithFloatsKeepsRawFloatVectors}. */+ public void testDataBlindWithFloatsKeepsRawFloat16Vectors() throws Exception {+ String fieldName = "field";+ int numVectors = random().nextInt(4, 50);+ int dims = 2 * random().nextInt(2, 33);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setCodec(dataBlindWithFloatsCodec()))) {+ addFloat16VectorDocs(w, fieldName, dims, similarityFunction, numVectors);+ }+ try (IndexReader reader = DirectoryReader.open(dir)) {+ LeafReader r = getOnlyLeafReader(reader);+ assertEquals(numVectors, r.getFloat16VectorValues(fieldName).size());+ Lucene104ScalarQuantizedVectorsReader vectorsReader =+ (Lucene104ScalarQuantizedVectorsReader)+ ((CodecReader) r).getVectorReader().unwrapReaderForField(fieldName);+ assertTrue(vectorsReader.hasRawFloat16Vectors(fieldName));+ assertZeroCentroid(vectorsReader.getCentroid(fieldName), dims);+ }+ }+ }++ /** Data-blind-with-floats segments merge with the float vectors intact. */+ public void testDataBlindWithFloatsMultiSegmentMerge() throws Exception {+ String fieldName = "field";+ int numVectorsPerSegment = random().nextInt(4, 30);+ int dims = random().nextInt(4, 65);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindWithFloatsCodec()))) {+ for (int s = 0; s < 2; s++) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ w.commit();+ }+ w.forceMerge(1);+ try (IndexReader reader = DirectoryReader.open(w)) {+ assertEquals(1, reader.leaves().size());+ LeafReader r = getOnlyLeafReader(reader);+ assertEquals(2 * numVectorsPerSegment, r.getFloatVectorValues(fieldName).size());+ Lucene104ScalarQuantizedVectorsReader vectorsReader =+ (Lucene104ScalarQuantizedVectorsReader)+ ((CodecReader) r).getVectorReader().unwrapReaderForField(fieldName);+ assertTrue(vectorsReader.hasRawFloatVectors(fieldName));+ assertZeroCentroid(vectorsReader.getCentroid(fieldName), dims);+ int k = random().nextInt(5, 20);+ TopDocs td =+ new IndexSearcher(reader)+ .search(new KnnFloatVectorQuery(fieldName, randomVector(dims), k), k);+ // The index holds exactly 2 * numVectorsPerSegment vectors; when k exceeds that, the+ // query can only return the vectors that exist.+ assertEquals(Math.min(k, 2 * numVectorsPerSegment), td.totalHits.value());+ }+ }+ }+ }++ /**+ * Merging a data-blind (no-floats) segment through a data-blind-with-floats writer must fail: the+ * output format expects floats the inputs cannot provide.+ */+ public void testDataBlindNoFloatsCannotMergeIntoDataBlindWithFloatsWriter() throws Exception {+ String fieldName = "field";+ int numVectorsPerSegment = 1 + random().nextInt(20);+ int dims = random().nextInt(4, 33);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ w.commit();+ }+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ addFloatVectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ w.commit();+ }+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergeScheduler(new SerialMergeScheduler())+ .setCodec(dataBlindWithFloatsCodec()))) {+ Throwable t =+ expectThrows(+ Exception.class,+ () -> {+ w.forceMerge(1);+ });+ assertTrue(+ "expected missing-float-vectors message, got: " + t,+ exceptionChainContains(t, "without full-precision float vectors"));+ }+ }+ }++ private static void assertZeroCentroid(float[] centroid, int dims) {+ assertNotNull(centroid);+ assertEquals(dims, centroid.length);+ for (float v : centroid) {+ assertEquals(0f, v, 0f);+ }+ }++ /**+ * Reads the {@link Lucene104ScalarQuantizedVectorsFormat.Mode} wire value from the metadata of+ * the first field with vectors, or {@link Lucene104ScalarQuantizedVectorsFormat.Mode#CENTERED}+ * for version 0 metadata which implies it.+ */+ private Lucene104ScalarQuantizedVectorsFormat.Mode metaMode(Directory dir) throws IOException {+ for (String file : dir.listAll()) {+ if (file.endsWith("." + Lucene104ScalarQuantizedVectorsFormat.META_EXTENSION)) {+ try (IndexInput in = dir.openInput(file, IOContext.DEFAULT)) {+ int version =+ CodecUtil.checkHeader(+ in,+ Lucene104ScalarQuantizedVectorsFormat.META_CODEC_NAME,+ Lucene104ScalarQuantizedVectorsFormat.VERSION_START,+ Lucene104ScalarQuantizedVectorsFormat.VERSION_CURRENT);+ // Consume the segment ID and suffix that checkHeader (unlike checkIndexHeader) leaves.+ in.readBytes(new byte[16], 0, 16);+ in.readString();+ for (int fieldNumber = in.readInt(); fieldNumber != -1; fieldNumber = in.readInt()) {+ in.readInt(); // vector encoding ordinal+ in.readInt(); // similarity ordinal+ int dimension = in.readVInt();+ in.readVLong(); // vector data offset+ in.readVLong(); // vector data length+ int count = in.readVInt();+ if (count > 0) {+ in.readVInt(); // ScalarEncoding wire number+ if (version == Lucene104ScalarQuantizedVectorsFormat.VERSION_START) {+ in.readFloats(new float[dimension], 0, dimension);+ in.readInt(); // centroidDP+ return Lucene104ScalarQuantizedVectorsFormat.Mode.CENTERED;+ }+ return Lucene104ScalarQuantizedVectorsFormat.Mode.fromWireNumber(in.readByte());+ }+ }+ }+ }+ }+ throw new AssertionError("no metadata file found");+ }++ public void testDataBlindFloat16Search() throws Exception {+ String fieldName = "field";+ int numVectors = random().nextInt(99, 500);+ int dims = 2 * random().nextInt(2, 33);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ KnnFloat16VectorField knnField =+ new KnnFloat16VectorField(+ fieldName, randomNormalizedFloat16Vector(dims), similarityFunction);+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ for (int i = 0; i < numVectors; i++) {+ Document doc = new Document();+ knnField.setVectorValue(randomNormalizedFloat16Vector(dims));+ doc.add(knnField);+ w.addDocument(doc);+ }+ w.commit();++ try (IndexReader reader = DirectoryReader.open(w)) {+ IndexSearcher searcher = new IndexSearcher(reader);+ final int k = random().nextInt(5, 50);+ short[] queryVector = randomNormalizedFloat16Vector(dims);+ TopDocs collectedDocs =+ searcher.search(new KnnFloat16VectorQuery(fieldName, queryVector, k), k);+ assertEquals(k, collectedDocs.totalHits.value());+ assertEquals(TotalHits.Relation.EQUAL_TO, collectedDocs.totalHits.relation());+ }+ }+ }+ }++ /**+ * Data-blind fp16 fields reconstruct as fp16-rounded dequantized values via {@link+ * OffHeapScalarQuantizedFloat16VectorValues}, so reads come back as {@link+ * Lucene104ScalarQuantizedVectorsReader.ScalarQuantizedFloat16VectorValues}.+ */+ public void testDataBlindFloat16ReconstructsFp16() throws Exception {+ String vectorFieldName = "vec1";+ int numVectors = 1 + random().nextInt(50);+ int dim = 2 * random().nextInt(1, 33);+ float eps = (1f / (float) (1 << getQuantizationBits())) + 1e-3f;+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ List<short[]> vectors = new ArrayList<>(numVectors);+ for (int i = 0; i < numVectors; i++) {+ vectors.add(randomNormalizedFloat16Vector(dim));+ }++ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMaxBufferedDocs(numVectors + 1)+ .setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setCodec(dataBlindCodec()))) {+ for (int i = 0; i < numVectors; i++) {+ Document doc = new Document();+ doc.add(new KnnFloat16VectorField(vectorFieldName, vectors.get(i), similarityFunction));+ w.addDocument(doc);+ }+ }++ try (IndexReader reader = DirectoryReader.open(dir)) {+ LeafReader r = getOnlyLeafReader(reader);+ Float16VectorValues float16VectorValues = r.getFloat16VectorValues(vectorFieldName);+ assertTrue(+ float16VectorValues+ instanceof+ Lucene104ScalarQuantizedVectorsReader.ScalarQuantizedFloat16VectorValues);+ KnnVectorValues.DocIndexIterator iter = float16VectorValues.iterator();+ for (int docId = iter.nextDoc(); docId != NO_MORE_DOCS; docId = iter.nextDoc()) {+ short[] reconstructed = float16VectorValues.vectorValue(iter.index());+ short[] original = vectors.get(docId);+ float mae = 0;+ for (int i = 0; i < dim; i++) {+ mae +=+ Math.abs(+ Float.float16ToFloat(reconstructed[i]) - Float.float16ToFloat(original[i]));+ }+ mae /= dim;+ assertTrue(+ "bits: " + getQuantizationBits() + " mae: " + mae + " > eps: " + eps, mae <= eps);+ }+ }+ }+ }++ public void testDataBlindFloat16MultiSegmentMerge() throws Exception {+ String fieldName = "field";+ int numVectorsPerSegment = random().nextInt(4, 30);+ int dims = 2 * random().nextInt(2, 17);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(dir, newIndexWriterConfig().setCodec(dataBlindCodec()))) {+ for (int s = 0; s < 2; s++) {+ for (int i = 0; i < numVectorsPerSegment; i++) {+ Document doc = new Document();+ doc.add(+ new KnnFloat16VectorField(+ fieldName, randomNormalizedFloat16Vector(dims), similarityFunction));+ w.addDocument(doc);+ }+ w.commit();+ }+ w.forceMerge(1);+ try (IndexReader reader = DirectoryReader.open(w)) {+ assertEquals(1, reader.leaves().size());+ LeafReader r = getOnlyLeafReader(reader);+ assertEquals(2 * numVectorsPerSegment, r.getFloat16VectorValues(fieldName).size());+ int k = random().nextInt(5, Math.min(15, 2 * numVectorsPerSegment + 1));+ TopDocs td =+ new IndexSearcher(reader)+ .search(+ new KnnFloat16VectorQuery(fieldName, randomNormalizedFloat16Vector(dims), k),+ k);+ assertEquals(k, td.totalHits.value());+ }+ }+ }+ }++ public void testDataBlindFloat16IncompatibleEncodingMerge() throws Exception {+ String fieldName = "field";+ int numVectorsPerSegment = 1 + random().nextInt(20);+ int dims = 2 * random().nextInt(2, 17);+ VectorSimilarityFunction similarityFunction = randomSimilarity();+ try (Directory dir = newDirectory()) {+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(+ ScalarEncoding.PACKED_NIBBLE, Mode.DATA_BLIND_WITHOUT_FLOATS))))) {+ addFloat16VectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ }+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergePolicy(NoMergePolicy.INSTANCE)+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(+ ScalarEncoding.UNSIGNED_BYTE, Mode.DATA_BLIND_WITHOUT_FLOATS))))) {+ addFloat16VectorDocs(w, fieldName, dims, similarityFunction, numVectorsPerSegment);+ }+ try (IndexWriter w =+ new IndexWriter(+ dir,+ newIndexWriterConfig()+ .setMergeScheduler(new SerialMergeScheduler())+ .setCodec(+ TestUtil.alwaysKnnVectorsFormat(+ new Lucene104ScalarQuantizedVectorsFormat(+ ScalarEncoding.UNSIGNED_BYTE, Mode.DATA_BLIND_WITHOUT_FLOATS))))) {+ Throwable t =+ expectThrows(+ Exception.class,+ () -> {+ w.forceMerge(1);+ });+ assertTrue(+ "expected encoding-mismatch message, got: " + t,+ exceptionChainContains(t, "re-quantization requires raw float vectors"));+ }+ }+ }++ private void addFloatVectorDocs(+ IndexWriter w, String field, int dims, VectorSimilarityFunction similarity, int count)+ throws IOException {+ for (int i = 0; i < count; i++) {+ Document doc = new Document();+ doc.add(new KnnFloatVectorField(field, randomVector(dims), similarity));+ w.addDocument(doc);+ }+ }++ private void addFloat16VectorDocs(+ IndexWriter w, String field, int dims, VectorSimilarityFunction similarity, int count)+ throws IOException {+ for (int i = 0; i < count; i++) {+ Document doc = new Document();+ doc.add(new KnnFloat16VectorField(field, randomNormalizedFloat16Vector(dims), similarity));+ w.addDocument(doc);+ }+ }++ private int metaVersion(Directory dir) throws IOException {+ for (String file : dir.listAll()) {+ if (file.endsWith("." + Lucene104ScalarQuantizedVectorsFormat.META_EXTENSION)) {+ try (IndexInput in = dir.openInput(file, IOContext.DEFAULT)) {+ return CodecUtil.checkHeader(+ in,+ Lucene104ScalarQuantizedVectorsFormat.META_CODEC_NAME,+ Lucene104ScalarQuantizedVectorsFormat.VERSION_START,+ Lucene104ScalarQuantizedVectorsFormat.VERSION_CURRENT);+ }+ }+ }+ throw new AssertionError("no metadata file found");+ }++ private static boolean exceptionChainContains(Throwable t, String msg) {+ for (Throwable cause = t; cause != null; cause = cause.getCause()) {+ if (cause.getMessage() != null && cause.getMessage().contains(msg)) {+ return true;+ }+ }+ return false;+ }}