benwtrent commented on code in PR #12582:
URL: https://github.com/apache/lucene/pull/12582#discussion_r1334388920


##########
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:
   This type of interaction tells me that my current design is seriously 
flawed. 
   
   During segment merging, we need access to the merged quantized values. That 
merging may require requantization and may require us calculating new 
quantiles, etc.
   
   Then, the caller needs access to the newly merged quantized vectors. 
However, since these are done within a writer context, I could not easily see a 
way to return a "reader" interface that was also closable (we don't want to 
keep `quantizedVectorDataInput` open).
   
   @jpountz @jimczi what do you think here?
   
   This indicates to me that merging needs to be done differently. Or 
quantization isn't a "codec" type thing, but just a set of functions that 
provide the tools to read/write/merge the correct things (and consequently, 
wouldn't have logic like this). 



##########
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 {

Review Comment:
   Partially duplicating the KnnVectorWriter codec interface tells me that this 
API is just different enough that we need to rethink it.
   
   Basically, I am not 100% sure if we want to add a new "FlatKnnCodec" that 
quantization satisfies. Thus allowing HNSW to wrap another codec (this gets 
hairy as, what if somebody wants to wrap HNSW with HNSW?!?!?!).
   
   OR, we have SOME other way of exposing these functions. 
   
   NOTE: We will want to add new quantization methods in the future. And future 
quantization methods will probably want to read from other quantized kinds 
(e.g. int8 being read into an int4 quantizer and then writing out int4 
quantized values).



-- 
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

Reply via email to