jimczi commented on code in PR #12582: URL: https://github.com/apache/lucene/pull/12582#discussion_r1334738549
########## lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorsWriter.java: ########## @@ -0,0 +1,851 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.codecs.lucene99; + +import static org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat.DIRECT_MONOTONIC_BLOCK_SHIFT; +import static org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsFormat.calculateDefaultQuantile; +import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.apache.lucene.codecs.CodecUtil; +import org.apache.lucene.codecs.KnnFieldVectorsWriter; +import org.apache.lucene.codecs.KnnVectorsReader; +import org.apache.lucene.codecs.KnnVectorsWriter; +import org.apache.lucene.codecs.lucene90.IndexedDISI; +import org.apache.lucene.codecs.perfield.PerFieldKnnVectorsFormat; +import org.apache.lucene.index.DocIDMerger; +import org.apache.lucene.index.DocsWithFieldSet; +import org.apache.lucene.index.FieldInfo; +import org.apache.lucene.index.FloatVectorValues; +import org.apache.lucene.index.IndexFileNames; +import org.apache.lucene.index.MergeState; +import org.apache.lucene.index.SegmentWriteState; +import org.apache.lucene.index.Sorter; +import org.apache.lucene.index.VectorEncoding; +import org.apache.lucene.index.VectorSimilarityFunction; +import org.apache.lucene.search.DocIdSetIterator; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.util.ArrayUtil; +import org.apache.lucene.util.IOUtils; +import org.apache.lucene.util.RamUsageEstimator; +import org.apache.lucene.util.ScalarQuantizer; +import org.apache.lucene.util.VectorUtil; +import org.apache.lucene.util.packed.DirectMonotonicWriter; + +/** + * Writes quantized vector values and metadata to index segments. + * + * @lucene.experimental + */ +public final class Lucene99ScalarQuantizedVectorsWriter implements QuantizedVectorsWriter { + + private static final long BASE_RAM_BYTES_USED = + RamUsageEstimator.shallowSizeOfInstance(Lucene99ScalarQuantizedVectorsWriter.class); + + private static final float QUANTIZATION_RECOMPUTE_LIMIT = 32; + private final SegmentWriteState segmentWriteState; + private final IndexOutput meta, quantizedVectorData; + private final Float quantile; + private final List<QuantizationVectorWriter> fields = new ArrayList<>(); + + private boolean finished; + + Lucene99ScalarQuantizedVectorsWriter(SegmentWriteState state, Float quantile) throws IOException { + this.quantile = quantile; + segmentWriteState = state; + String metaFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, + state.segmentSuffix, + Lucene99ScalarQuantizedVectorsFormat.QUANTIZED_VECTOR_META_EXTENSION); + + String quantizedVectorDataFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, + state.segmentSuffix, + Lucene99ScalarQuantizedVectorsFormat.QUANTIZED_VECTOR_DATA_EXTENSION); + + boolean success = false; + try { + meta = state.directory.createOutput(metaFileName, state.context); + quantizedVectorData = + state.directory.createOutput(quantizedVectorDataFileName, state.context); + + CodecUtil.writeIndexHeader( + meta, + Lucene99ScalarQuantizedVectorsFormat.META_CODEC_NAME, + Lucene99ScalarQuantizedVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + CodecUtil.writeIndexHeader( + quantizedVectorData, + Lucene99ScalarQuantizedVectorsFormat.QUANTIZED_VECTOR_DATA_CODEC_NAME, + Lucene99ScalarQuantizedVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + success = true; + } finally { + if (success == false) { + IOUtils.closeWhileHandlingException(this); + } + } + } + + @Override + public KnnFieldVectorsWriter<float[]> addField(FieldInfo fieldInfo) throws IOException { + if (fieldInfo.getVectorEncoding() != VectorEncoding.FLOAT32) { + throw new IllegalArgumentException( + "Only float32 vector fields are supported for quantization"); + } + float quantile = + this.quantile == null + ? calculateDefaultQuantile(fieldInfo.getVectorDimension()) + : this.quantile; + QuantizationVectorWriter newField = QuantizationVectorWriter.create(fieldInfo, quantile); + fields.add(newField); + return newField; + } + + @Override + public void flush(int maxDoc, Sorter.DocMap sortMap) throws IOException { + for (QuantizationVectorWriter field : fields) { + field.finish(); + if (sortMap == null) { + writeField(field, maxDoc); + } else { + writeSortingField(field, maxDoc, sortMap); + } + } + } + + @Override + public void finish() throws IOException { + if (finished) { + throw new IllegalStateException("already finished"); + } + finished = true; + if (meta != null) { + // write end of fields marker + meta.writeInt(-1); + CodecUtil.writeFooter(meta); + } + if (quantizedVectorData != null) { + CodecUtil.writeFooter(quantizedVectorData); + } + } + + @Override + public long ramBytesUsed() { + long total = BASE_RAM_BYTES_USED; + for (QuantizationVectorWriter field : fields) { + total += field.ramBytesUsed(); + } + return total; + } + + private void writeField(QuantizationVectorWriter fieldData, int maxDoc) throws IOException { + long quantizedVectorDataOffset = quantizedVectorData.alignFilePointer(Float.BYTES); + writeQuantizedVectors(fieldData); + long quantizedVectorDataLength = + quantizedVectorData.getFilePointer() - quantizedVectorDataOffset; + + writeMeta( + fieldData.fieldInfo, + maxDoc, + quantizedVectorDataOffset, + quantizedVectorDataLength, + fieldData.getMinQuantile(), + fieldData.getMaxQuantile(), + fieldData.docsWithField); + } + + private void writeQuantizedVectors(QuantizationVectorWriter fieldData) throws IOException { + ScalarQuantizer scalarQuantizer = fieldData.createQuantizer(); + byte[] vector = new byte[fieldData.dim]; + for (float[] v : fieldData.floatVectors) { + scalarQuantizer.quantize(v, vector); + quantizedVectorData.writeBytes(vector, vector.length); + float offsetCorrection = + scalarQuantizer.calculateVectorOffset(vector, fieldData.vectorSimilarityFunction); + quantizedVectorData.writeInt(Float.floatToIntBits(offsetCorrection)); + } + } + + private ScalarQuantizationState writeSortingField( + QuantizationVectorWriter fieldData, int maxDoc, Sorter.DocMap sortMap) throws IOException { + final int[] docIdOffsets = new int[sortMap.size()]; + int offset = 1; // 0 means no vector for this (field, document) + DocIdSetIterator iterator = fieldData.docsWithField.iterator(); + for (int docID = iterator.nextDoc(); + docID != DocIdSetIterator.NO_MORE_DOCS; + docID = iterator.nextDoc()) { + int newDocID = sortMap.oldToNew(docID); + docIdOffsets[newDocID] = offset++; + } + DocsWithFieldSet newDocsWithField = new DocsWithFieldSet(); + final int[] ordMap = new int[offset - 1]; // new ord to old ord + final int[] oldOrdMap = new int[offset - 1]; // old ord to new ord + int ord = 0; + int doc = 0; + for (int docIdOffset : docIdOffsets) { + if (docIdOffset != 0) { + ordMap[ord] = docIdOffset - 1; + oldOrdMap[docIdOffset - 1] = ord; + newDocsWithField.add(doc); + ord++; + } + doc++; + } + + // write vector values + long vectorDataOffset = quantizedVectorData.alignFilePointer(Float.BYTES); + long quantizedVectorDataOffset = writeSortedQuantizedVectors(fieldData, ordMap); + long quantizedVectorLength = quantizedVectorData.getFilePointer() - vectorDataOffset; + + writeMeta( + fieldData.fieldInfo, + maxDoc, + quantizedVectorDataOffset, + quantizedVectorLength, + fieldData.minQuantile, + fieldData.maxQuantile, + newDocsWithField); + return new ScalarQuantizationState(fieldData.minQuantile, fieldData.maxQuantile); + } + + private long writeSortedQuantizedVectors(QuantizationVectorWriter fieldData, int[] ordMap) + throws IOException { + long vectorDataOffset = quantizedVectorData.alignFilePointer(Float.BYTES); + ScalarQuantizer scalarQuantizer = fieldData.createQuantizer(); + byte[] vector = new byte[fieldData.dim]; + for (int ordinal : ordMap) { + float[] v = fieldData.floatVectors.get(ordinal); + scalarQuantizer.quantize(v, vector); + quantizedVectorData.writeBytes(vector, vector.length); + float offsetCorrection = + scalarQuantizer.calculateVectorOffset(vector, fieldData.vectorSimilarityFunction); + quantizedVectorData.writeInt(Float.floatToIntBits(offsetCorrection)); + } + return vectorDataOffset; + } + + @Override + public ScalarQuantizationState mergeQuantiles(FieldInfo fieldInfo, MergeState mergeState) + throws IOException { + if (fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32) == false) { + return null; + } + float quantile = + this.quantile == null + ? calculateDefaultQuantile(fieldInfo.getVectorDimension()) + : this.quantile; + return mergeAndRecalculateQuantiles(mergeState, fieldInfo, quantile); + } + + @Override + public IndexInput mergeOneField( + FieldInfo fieldInfo, MergeState mergeState, ScalarQuantizationState mergedQuantizationState) + throws IOException { Review Comment: Quantisation as a codec makes sense to me but not as an additive layer on top of the HNSW one. If we want to follow this path I think we need to separate the concern and make another codec responsible for writing the flat index in HNSW. That's your suggestion below and I think it's much cleaner. The question is whether we want to generalise the feature on the first attempt. We could also start by adding a quantization option inlined with the HNSW codec. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: issues-unsubscr...@lucene.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@lucene.apache.org For additional commands, e-mail: issues-h...@lucene.apache.org