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


##########
lucene/core/src/java/org/apache/lucene/util/ScalarQuantizer.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.util;
+
+import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Random;
+import java.util.stream.IntStream;
+import org.apache.lucene.index.FloatVectorValues;
+import org.apache.lucene.index.VectorSimilarityFunction;
+
+/** Will scalar quantize float vectors into `int8` byte values */
+public class ScalarQuantizer {
+
+  public static final int SCALAR_QUANTIZATION_SAMPLE_SIZE = 25_000;
+
+  private final float alpha;
+  private final float scale;
+  private final float minQuantile, maxQuantile, configuredQuantile;
+
+  /**
+   * @param minQuantile the lower quantile of the distribution
+   * @param maxQuantile the upper quantile of the distribution
+   * @param configuredQuantile The configured quantile/confidence interval 
used to calculate the
+   *     quantiles.
+   */
+  public ScalarQuantizer(float minQuantile, float maxQuantile, float 
configuredQuantile) {
+    assert maxQuantile >= maxQuantile;
+    this.minQuantile = minQuantile;
+    this.maxQuantile = maxQuantile;
+    this.scale = 127f / (maxQuantile - minQuantile);
+    this.alpha = (maxQuantile - minQuantile) / 127f;
+    this.configuredQuantile = configuredQuantile;
+  }
+
+  /**
+   * Quantize a float vector into a byte vector
+   *
+   * @param src the source vector
+   * @param dest the destination vector
+   * @param similarityFunction the similarity function used to calculate the 
quantile
+   * @return the corrective offset that needs to be applied to the score
+   */
+  public float quantize(float[] src, byte[] dest, VectorSimilarityFunction 
similarityFunction) {
+    assert src.length == dest.length;
+    float correctiveOffset = 0f;
+    for (int i = 0; i < src.length; i++) {
+      float v = src[i];
+      float dx = Math.max(minQuantile, Math.min(maxQuantile, src[i])) - 
minQuantile;
+      float dxs = scale * dx;
+      float dxq = Math.round(dxs) * alpha;
+      correctiveOffset += minQuantile * (v - minQuantile / 2.0F) + (dx - dxq) 
* dxq;
+      dest[i] = (byte) Math.round(dxs);
+    }
+    if (similarityFunction.equals(VectorSimilarityFunction.EUCLIDEAN)) {
+      return 0;
+    }
+    return correctiveOffset;
+  }
+
+  /**
+   * Recalculate the old score corrective value given new current quantiles
+   *
+   * @param quantizedVector the old vector
+   * @param oldQuantizer the old quantizer
+   * @param similarityFunction the similarity function used to calculate the 
quantile
+   * @return the new offset
+   */
+  public float recalculateCorrectiveOffset(
+      byte[] quantizedVector,
+      ScalarQuantizer oldQuantizer,
+      VectorSimilarityFunction similarityFunction) {
+    if (similarityFunction.equals(VectorSimilarityFunction.EUCLIDEAN)) {
+      return 0f;
+    }
+    // TODO this could probably be some simple algebra with the old offset
+    float correctiveOffset = 0f;
+    for (int i = 0; i < quantizedVector.length; i++) {
+      float v = (oldQuantizer.alpha * quantizedVector[i]) + 
oldQuantizer.minQuantile;
+      float dx = Math.max(minQuantile, Math.min(maxQuantile, v)) - minQuantile;
+      float dxs = scale * dx;
+      float dxq = Math.round(dxs) * alpha;
+      correctiveOffset += minQuantile * (v - minQuantile / 2.0F) + (dx - dxq) 
* dxq;
+    }
+    return correctiveOffset;
+  }
+
+  /**
+   * Dequantize a byte vector into a float vector
+   *
+   * @param src the source vector
+   * @param dest the destination vector
+   */
+  public void deQuantize(byte[] src, float[] dest) {
+    assert src.length == dest.length;
+    for (int i = 0; i < src.length; i++) {
+      dest[i] = (alpha * src[i]) + minQuantile;
+    }
+  }
+
+  public float getLowerQuantile() {
+    return minQuantile;
+  }
+
+  public float getUpperQuantile() {
+    return maxQuantile;
+  }
+
+  public float getConfiguredQuantile() {
+    return configuredQuantile;
+  }
+
+  public float getConstantMultiplier() {
+    return alpha * alpha;
+  }
+
+  @Override
+  public String toString() {
+    return "ScalarQuantizer{"
+        + "minQuantile="
+        + minQuantile
+        + ", maxQuantile="
+        + maxQuantile
+        + ", configuredQuantile="
+        + configuredQuantile
+        + '}';
+  }
+
+  private static final Random random = new Random(42);
+
+  /**
+   * This will read the float vector values and calculate the quantiles. If 
the number of float
+   * vectors is less than {@link #SCALAR_QUANTIZATION_SAMPLE_SIZE} then all 
the values will be read
+   * and the quantiles calculated. If the number of float vectors is greater 
than {@link
+   * #SCALAR_QUANTIZATION_SAMPLE_SIZE} then a random sample of {@link
+   * #SCALAR_QUANTIZATION_SAMPLE_SIZE} will be read and the quantiles 
calculated.
+   *
+   * @param floatVectorValues the float vector values from which to calculate 
the quantiles
+   * @param quantile the quantile/confidence interval used to calculate the 
quantiles
+   * @return A new {@link ScalarQuantizer} instance
+   * @throws IOException if there is an error reading the float vector values
+   */
+  public static ScalarQuantizer fromVectors(FloatVectorValues 
floatVectorValues, float quantile)
+      throws IOException {
+    assert 0.9f <= quantile && quantile <= 1f;
+    if (floatVectorValues.size() == 0) {
+      return new ScalarQuantizer(0f, 0f, quantile);
+    }
+    if (quantile == 1f) {
+      float min = Float.POSITIVE_INFINITY;
+      float max = Float.NEGATIVE_INFINITY;
+      while (floatVectorValues.nextDoc() != NO_MORE_DOCS) {
+        for (float v : floatVectorValues.vectorValue()) {
+          min = Math.min(min, v);
+          max = Math.max(max, v);
+        }
+      }
+      return new ScalarQuantizer(min, max, quantile);
+    }
+    int dim = floatVectorValues.dimension();
+    if (floatVectorValues.size() < SCALAR_QUANTIZATION_SAMPLE_SIZE) {
+      int copyOffset = 0;
+      float[] values = new float[floatVectorValues.size() * dim];
+      while (floatVectorValues.nextDoc() != NO_MORE_DOCS) {
+        float[] floatVector = floatVectorValues.vectorValue();
+        System.arraycopy(floatVector, 0, values, copyOffset, 
floatVector.length);
+        copyOffset += dim;
+      }
+      float[] upperAndLower = getUpperAndLowerQuantile(values, quantile);
+      return new ScalarQuantizer(upperAndLower[0], upperAndLower[1], quantile);
+    }
+    int numFloatVecs = floatVectorValues.size();
+    // Reservoir sample the vector ordinals we want to read
+    float[] values = new float[SCALAR_QUANTIZATION_SAMPLE_SIZE * dim];
+    int[] vectorsToTake = IntStream.range(0, 
SCALAR_QUANTIZATION_SAMPLE_SIZE).toArray();
+    for (int i = SCALAR_QUANTIZATION_SAMPLE_SIZE; i < numFloatVecs; i++) {
+      int j = random.nextInt(i + 1);
+      if (j < SCALAR_QUANTIZATION_SAMPLE_SIZE) {
+        vectorsToTake[j] = i;

Review Comment:
   > they can just sit on disk enabling requantization, and the storage 
increase is not too costly: it's not what we optimize for.
   
   Correct. In the future @msokolov we maybe could allow users to have a 
"limit" where at a certain point the codec just stops storing the raw vectors. 
But, I think this would require a larger change as our vector search also 
provides doc values via `getFloatVectors`, and this isn't assumed to be lossy 
:/.
   
   I would like to make that a separate and future discussion if we think users 
will find it useful.



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