msokolov commented on code in PR #17013:
URL: https://github.com/apache/lucene/pull/17013#discussion_r4568305128
##########
lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorScorer.java:
##########
@@ -278,34 +305,63 @@ private static float quantizedScore(
};
OptimizedScalarQuantizer.QuantizationResult indexCorrections =
targetVectors.getCorrectiveTerms(targetOrd);
+ return quantizedScore(
+ qcDist,
+ queryCorrections,
+ indexCorrections.lowerInterval(),
+ indexCorrections.upperInterval(),
+ indexCorrections.additionalCorrection(),
+ indexCorrections.quantizedComponentSum(),
+ scalarEncoding,
+ targetVectors.dimension(),
+ targetVectors.getCentroidDP(),
+ similarityFunction);
+ }
+
+ /**
+ * Turns {@code qcDist}, the dot product of a quantized query and a
quantized vector, into a
+ * similarity score using the corrective terms of both. The corrective terms
of the vector and the
+ * properties of its field are passed as values, so that a caller that reads
them from the index
+ * allocates nothing and needs no {@link QuantizedByteVectorValues}.
+ *
+ * @param scalarEncoding the encoding of the vectors
+ * @param dimension the dimension of the vectors
+ * @param centroidDp the dot product of the centroid with itself, see {@link
+ * QuantizedByteVectorValues#getCentroidDP}
+ * @lucene.internal
+ */
+ protected static float quantizedScore(
Review Comment:
this is basically a refactor? Why did we do it? Do we want to call this
method from somewhere else now, too?
##########
lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerQuantizedBenchmark.java:
##########
@@ -0,0 +1,200 @@
+/*
+ * 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.benchmark.jmh;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+import org.apache.lucene.codecs.hnsw.DefaultFlatVectorScorer;
+import org.apache.lucene.codecs.hnsw.FlatVectorScorerUtil;
+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorScorer;
+import org.apache.lucene.codecs.lucene104.OffHeapScalarQuantizedVectorValues;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.store.MMapDirectory;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.quantization.OptimizedScalarQuantizer;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Warmup;
+
+/**
+ * One {@link RandomVectorScorer#bulkScore} call over eight memory mapped
{@link
+ * org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorsFormat}
records, with the
+ * scorer the format uses, in a JVM without the Vector API ({@link
#bulkScoreScalar}) and with it
+ * ({@link #bulkScoreVector}). Each call scores the next eight nodes of a
random permutation of the
+ * vectors, so with many vectors every node is a cache miss and with few they
are all cache hits.
+ * Run it on two checkouts to compare them.
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@State(Scope.Benchmark)
+@Warmup(iterations = 4, time = 1)
+@Measurement(iterations = 5, time = 1)
+@Fork(
+ value = 3,
+ jvmArgsAppend = {"-Xmx2g", "-Xms2g", "-XX:+AlwaysPreTouch"})
+public class VectorScorerQuantizedBenchmark {
Review Comment:
Q: why do we need a new benchmark
##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,448 @@
+/*
+ * 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.internal.vectorization;
+
+import java.io.IOException;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.nio.ByteOrder;
+import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorScorer;
+import org.apache.lucene.codecs.lucene104.OffHeapScalarQuantizedVectorValues;
+import org.apache.lucene.index.KnnVectorValues;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.FilterIndexInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.MemorySegmentAccessInput;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
+import
org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+
+/**
+ * A {@link Lucene104ScalarQuantizedVectorScorer} that scores vectors in place
in the {@link
+ * MemorySegment} that holds them, several at a time in {@link
RandomVectorScorer#bulkScore} so that
+ * their cache misses overlap, instead of copying each on heap first. Vectors
that are not memory
+ * mapped in one segment are scored by the superclass.
+ */
+final class Lucene104MemorySegmentScalarQuantizedVectorScorer
+ extends Lucene104ScalarQuantizedVectorScorer {
+
+ static final Lucene104MemorySegmentScalarQuantizedVectorScorer INSTANCE =
+ new Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ Lucene99MemorySegmentFlatVectorsScorer.INSTANCE);
+
+ private final FlatVectorsScorer nonQuantizedDelegate;
+
+ private Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ FlatVectorsScorer nonQuantizedDelegate) {
+ super(nonQuantizedDelegate);
+ this.nonQuantizedDelegate = nonQuantizedDelegate;
+ }
+
+ @Override
+ public String toString() {
+ return
"Lucene104MemorySegmentScalarQuantizedVectorScorer(nonQuantizedDelegate="
+ + nonQuantizedDelegate
+ + ")";
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues
vectorValues)
+ throws IOException {
+ if (vectorValues instanceof QuantizedByteVectorValues qv
+ && qv.getScalarEncoding().isAsymmetric() == false) {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, qv, qv);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
vectorValues);
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues scoringVectors,
+ QuantizedByteVectorValues targetVectors)
+ throws IOException {
+ if (targetVectors.getScalarEncoding().isAsymmetric()) {
+ Records records = Records.of(targetVectors, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, targetVectors,
scoringVectors);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
scoringVectors, targetVectors);
+ }
+
+ @Override
+ protected RandomVectorScorer getQuantizedQueryScorer(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues qv,
+ byte[] quantizedQuery,
+ QuantizationResult queryCorrections)
+ throws IOException {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return QueryScorer.create(records, qv, quantizedQuery, queryCorrections);
+ }
+ return super.getQuantizedQueryScorer(similarityFunction, qv,
quantizedQuery, queryCorrections);
+ }
+
+ /**
+ * The records of one field in a segment: each is the packed vector followed
by its corrective
+ * terms, three floats and an int. Holds values only, so one instance serves
every scorer of a
+ * supplier and its copies.
+ *
+ * <p>The segment is that of the whole slice, like in {@link
+ * Lucene99MemorySegmentFlatVectorsScorer}. Scoring after the input is
closed fails on the
+ * segment, not with an {@link
org.apache.lucene.store.AlreadyClosedException}.
+ */
+ private record Records(
+ MemorySegment segment,
+ VectorSimilarityFunction similarity,
+ ScalarEncoding encoding,
+ int size,
+ int dimension,
+ float centroidDp,
+ int packedLength,
+ int stride) {
+
+ static final int CORRECTIONS_BYTES = 3 * Float.BYTES + Integer.BYTES;
+ static final ValueLayout.OfFloat LE_FLOAT =
+ ValueLayout.JAVA_FLOAT_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN);
+ static final ValueLayout.OfInt LE_INT =
+ ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN);
+
+ /**
+ * Returns the records of {@code values}, or null if they cannot be scored
this way: when they
+ * are not off heap, or when they span more than one mapped chunk.
+ */
+ static Records of(QuantizedByteVectorValues values,
VectorSimilarityFunction similarity)
+ throws IOException {
+ if (values instanceof OffHeapScalarQuantizedVectorValues == false) {
+ return null;
+ }
+ IndexInput slice = values.getSlice();
+ MemorySegment segment = null;
+ if (slice != null
+ && FilterIndexInput.unwrapOnlyTest(slice) instanceof
MemorySegmentAccessInput input) {
+ segment = input.segmentSliceOrNull(0, input.length());
+ }
+ if (segment == null) {
+ return null;
+ }
+ int packedLength = values.getVectorByteLength();
+ int stride = packedLength + CORRECTIONS_BYTES;
+ if (segment.byteSize() < (long) stride * values.size()) {
+ throw new IllegalArgumentException("input length is less than expected
vector data");
+ }
+ return new Records(
+ segment,
+ similarity,
+ values.getScalarEncoding(),
+ values.size(),
+ values.dimension(),
+ values.getCentroidDP(),
+ packedLength,
+ stride);
+ }
+
+ /**
+ * The length of a quantized query: the discretized dimensions for 8 and 7
bit vectors, twice
+ * the packed length (one nibble per byte) for 4 bit vectors, and the
transposed 4 bit planes
+ * for the 1 and 2 bit vectors.
+ */
+ int queryLength() {
+ return encoding.isAsymmetric()
+ ? encoding.getQueryPackedLength(dimension)
+ : encoding.getDiscreteDimensions(dimension);
+ }
+
+ void checkQuery(byte[] query) {
+ if (query.length != queryLength()) {
+ throw new IllegalArgumentException(
+ "query length " + query.length + " != " + queryLength() + " for "
+ encoding);
+ }
+ }
+
+ void checkOrdinal(int ord) {
+ if (ord < 0 || ord >= size) {
+ throw new IllegalArgumentException("illegal ordinal: " + ord);
+ }
+ }
+
+ long offset(int ord) {
+ checkOrdinal(ord);
+ return (long) ord * stride;
+ }
+ }
+
+ /**
+ * Scores one quantized query, held on heap, against {@link Records}: four
vectors per {@link
+ * #bulkScore} pass in place, and {@link #score} like the superclass,
reading the vector on heap.
+ * There is one subclass per kernel, chosen once per scorer, so that no
encoding is looked up
+ * while scoring.
+ */
+ private abstract static class QueryScorer extends
RandomVectorScorer.AbstractRandomVectorScorer {
+ final Records records;
+ final MemorySegment segment;
Review Comment:
which memory segment is this? It's not the one in the "Records"? I guess the
"Records" holds he field data and this other segment holds query data? Is that
right? If so can we call it `queryMemorySegment`?? or just `query`
##########
lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java:
##########
@@ -83,13 +84,13 @@ public class Lucene104ScalarQuantizedVectorsReader extends
FlatVectorsReader
private final Map<String, FieldEntry> fields;
private final IndexInput quantizedVectorData;
private final FlatVectorsReader rawVectorsReader;
- private final Lucene104ScalarQuantizedVectorScorer vectorScorer;
+ private final AsymmetricFlatVectorsScorer vectorScorer;
Review Comment:
Why did we do all this renaming? Isn't it still a
`Lucene104ScalarQuantizedVectorScorer` here?
##########
lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java:
##########
@@ -83,13 +84,13 @@ public class Lucene104ScalarQuantizedVectorsReader extends
FlatVectorsReader
private final Map<String, FieldEntry> fields;
private final IndexInput quantizedVectorData;
private final FlatVectorsReader rawVectorsReader;
- private final Lucene104ScalarQuantizedVectorScorer vectorScorer;
+ private final AsymmetricFlatVectorsScorer vectorScorer;
Review Comment:
OK I see the new implementations we added that share the same interface, so
I guess this is needed. Do you find the AsymmetricFlatVectorScorer naming
compelling? Didn't we have asymmetry before (ie different wuantization of query
and documents)? I guess AsymmetricFlatVectorsScorer is a kind of
RandomVectorScorer? What are the kinds? How would we want to distinguish these
kinds from those others?
##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,448 @@
+/*
+ * 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.internal.vectorization;
+
+import java.io.IOException;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.nio.ByteOrder;
+import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorScorer;
+import org.apache.lucene.codecs.lucene104.OffHeapScalarQuantizedVectorValues;
+import org.apache.lucene.index.KnnVectorValues;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.FilterIndexInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.MemorySegmentAccessInput;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
+import
org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+
+/**
+ * A {@link Lucene104ScalarQuantizedVectorScorer} that scores vectors in place
in the {@link
+ * MemorySegment} that holds them, several at a time in {@link
RandomVectorScorer#bulkScore} so that
+ * their cache misses overlap, instead of copying each on heap first. Vectors
that are not memory
+ * mapped in one segment are scored by the superclass.
+ */
+final class Lucene104MemorySegmentScalarQuantizedVectorScorer
+ extends Lucene104ScalarQuantizedVectorScorer {
+
+ static final Lucene104MemorySegmentScalarQuantizedVectorScorer INSTANCE =
+ new Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ Lucene99MemorySegmentFlatVectorsScorer.INSTANCE);
+
+ private final FlatVectorsScorer nonQuantizedDelegate;
+
+ private Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ FlatVectorsScorer nonQuantizedDelegate) {
+ super(nonQuantizedDelegate);
+ this.nonQuantizedDelegate = nonQuantizedDelegate;
+ }
+
+ @Override
+ public String toString() {
+ return
"Lucene104MemorySegmentScalarQuantizedVectorScorer(nonQuantizedDelegate="
+ + nonQuantizedDelegate
+ + ")";
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues
vectorValues)
+ throws IOException {
+ if (vectorValues instanceof QuantizedByteVectorValues qv
+ && qv.getScalarEncoding().isAsymmetric() == false) {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, qv, qv);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
vectorValues);
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues scoringVectors,
+ QuantizedByteVectorValues targetVectors)
+ throws IOException {
+ if (targetVectors.getScalarEncoding().isAsymmetric()) {
+ Records records = Records.of(targetVectors, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, targetVectors,
scoringVectors);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
scoringVectors, targetVectors);
+ }
+
+ @Override
+ protected RandomVectorScorer getQuantizedQueryScorer(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues qv,
+ byte[] quantizedQuery,
+ QuantizationResult queryCorrections)
+ throws IOException {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return QueryScorer.create(records, qv, quantizedQuery, queryCorrections);
+ }
+ return super.getQuantizedQueryScorer(similarityFunction, qv,
quantizedQuery, queryCorrections);
+ }
+
+ /**
+ * The records of one field in a segment: each is the packed vector followed
by its corrective
+ * terms, three floats and an int. Holds values only, so one instance serves
every scorer of a
+ * supplier and its copies.
+ *
+ * <p>The segment is that of the whole slice, like in {@link
+ * Lucene99MemorySegmentFlatVectorsScorer}. Scoring after the input is
closed fails on the
+ * segment, not with an {@link
org.apache.lucene.store.AlreadyClosedException}.
+ */
+ private record Records(
Review Comment:
naming -- what is "Records" trying to tell us? It's a totally abstract
name. We might as well call this "Rrrrr". I guess it's all a part of the
vectror field we are scoring over? I guess the javadoc says it: "one field in
a segment". What if we call it SegmentVectorFieldInfo or just SegmentFieldInfo
or so
##########
lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorScorer.java:
##########
@@ -123,18 +124,38 @@ private RandomVectorScorer getRandomQuantizedVectorScorer(
|| scalarEncoding == ScalarEncoding.DIBIT_QUERY_NIBBLE) {
OptimizedScalarQuantizer.transposeHalfByte(scratch, targetQuantized);
}
+ return getQuantizedQueryScorer(similarityFunction, qv, targetQuantized,
targetCorrectiveTerms);
+ }
+
+ /**
+ * Returns a scorer of a quantized query against the vectors of {@code qv}.
Subclasses may
+ * override this to score the vectors another way.
+ *
+ * @param quantizedQuery the query, quantized to {@link
ScalarEncoding#getQueryBits()} and packed
+ * like the query side of the encoding
+ * @param queryCorrections the corrective terms of the quantized query
+ * @lucene.internal
+ */
+ protected RandomVectorScorer getQuantizedQueryScorer(
Review Comment:
I don't understand the naming of these functions: the difference between
"getQuantizedQueryScorer" and "getRandomQuantizedVectorScorer" is ... that the
first one uses a quantized query and the second one uses a floating point
query? These names ... do not say that. I guess it's unfortunate that
`getRandomQuantizedVectorScorer` was meaningless to begin with. Maybe we should
rename all the methods to `getVectorScorer` and let the argument types do the
explaining?
##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,448 @@
+/*
+ * 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.internal.vectorization;
+
+import java.io.IOException;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.nio.ByteOrder;
+import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorScorer;
+import org.apache.lucene.codecs.lucene104.OffHeapScalarQuantizedVectorValues;
+import org.apache.lucene.index.KnnVectorValues;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.FilterIndexInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.MemorySegmentAccessInput;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
+import
org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+
+/**
+ * A {@link Lucene104ScalarQuantizedVectorScorer} that scores vectors in place
in the {@link
+ * MemorySegment} that holds them, several at a time in {@link
RandomVectorScorer#bulkScore} so that
+ * their cache misses overlap, instead of copying each on heap first. Vectors
that are not memory
+ * mapped in one segment are scored by the superclass.
+ */
+final class Lucene104MemorySegmentScalarQuantizedVectorScorer
+ extends Lucene104ScalarQuantizedVectorScorer {
+
+ static final Lucene104MemorySegmentScalarQuantizedVectorScorer INSTANCE =
+ new Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ Lucene99MemorySegmentFlatVectorsScorer.INSTANCE);
+
+ private final FlatVectorsScorer nonQuantizedDelegate;
+
+ private Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ FlatVectorsScorer nonQuantizedDelegate) {
+ super(nonQuantizedDelegate);
+ this.nonQuantizedDelegate = nonQuantizedDelegate;
+ }
+
+ @Override
+ public String toString() {
+ return
"Lucene104MemorySegmentScalarQuantizedVectorScorer(nonQuantizedDelegate="
+ + nonQuantizedDelegate
+ + ")";
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues
vectorValues)
+ throws IOException {
+ if (vectorValues instanceof QuantizedByteVectorValues qv
+ && qv.getScalarEncoding().isAsymmetric() == false) {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, qv, qv);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
vectorValues);
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues scoringVectors,
+ QuantizedByteVectorValues targetVectors)
+ throws IOException {
+ if (targetVectors.getScalarEncoding().isAsymmetric()) {
+ Records records = Records.of(targetVectors, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, targetVectors,
scoringVectors);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
scoringVectors, targetVectors);
+ }
+
+ @Override
+ protected RandomVectorScorer getQuantizedQueryScorer(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues qv,
+ byte[] quantizedQuery,
+ QuantizationResult queryCorrections)
+ throws IOException {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return QueryScorer.create(records, qv, quantizedQuery, queryCorrections);
+ }
+ return super.getQuantizedQueryScorer(similarityFunction, qv,
quantizedQuery, queryCorrections);
+ }
+
+ /**
+ * The records of one field in a segment: each is the packed vector followed
by its corrective
+ * terms, three floats and an int. Holds values only, so one instance serves
every scorer of a
+ * supplier and its copies.
+ *
+ * <p>The segment is that of the whole slice, like in {@link
+ * Lucene99MemorySegmentFlatVectorsScorer}. Scoring after the input is
closed fails on the
+ * segment, not with an {@link
org.apache.lucene.store.AlreadyClosedException}.
+ */
+ private record Records(
Review Comment:
oh hmm the actual vector data is in the MemorySegment? So ... this is not a
Segment in the Lucene sense. Can we change the usage of "segment" to
"memorySegment" or "memory segment" throughout so the distinction is clear?
And then the name of this record needs to be something else like
MemorySegmentVectorField? Because it's not just info (ie metadata) but also
stores the data
##########
lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorScorer.java:
##########
@@ -278,34 +305,63 @@ private static float quantizedScore(
};
OptimizedScalarQuantizer.QuantizationResult indexCorrections =
targetVectors.getCorrectiveTerms(targetOrd);
+ return quantizedScore(
+ qcDist,
+ queryCorrections,
+ indexCorrections.lowerInterval(),
+ indexCorrections.upperInterval(),
+ indexCorrections.additionalCorrection(),
+ indexCorrections.quantizedComponentSum(),
+ scalarEncoding,
+ targetVectors.dimension(),
+ targetVectors.getCentroidDP(),
+ similarityFunction);
+ }
+
+ /**
+ * Turns {@code qcDist}, the dot product of a quantized query and a
quantized vector, into a
+ * similarity score using the corrective terms of both. The corrective terms
of the vector and the
+ * properties of its field are passed as values, so that a caller that reads
them from the index
+ * allocates nothing and needs no {@link QuantizedByteVectorValues}.
+ *
+ * @param scalarEncoding the encoding of the vectors
+ * @param dimension the dimension of the vectors
+ * @param centroidDp the dot product of the centroid with itself, see {@link
+ * QuantizedByteVectorValues#getCentroidDP}
+ * @lucene.internal
+ */
+ protected static float quantizedScore(
Review Comment:
it creates a lot of noise in the CR -- if it's not needed, let's roll it
back and do refactors separately
##########
lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerQuantizedBenchmark.java:
##########
@@ -0,0 +1,200 @@
+/*
+ * 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.benchmark.jmh;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+import org.apache.lucene.codecs.hnsw.DefaultFlatVectorScorer;
+import org.apache.lucene.codecs.hnsw.FlatVectorScorerUtil;
+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorScorer;
+import org.apache.lucene.codecs.lucene104.OffHeapScalarQuantizedVectorValues;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.store.MMapDirectory;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.quantization.OptimizedScalarQuantizer;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Warmup;
+
+/**
+ * One {@link RandomVectorScorer#bulkScore} call over eight memory mapped
{@link
+ * org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorsFormat}
records, with the
+ * scorer the format uses, in a JVM without the Vector API ({@link
#bulkScoreScalar}) and with it
+ * ({@link #bulkScoreVector}). Each call scores the next eight nodes of a
random permutation of the
+ * vectors, so with many vectors every node is a cache miss and with few they
are all cache hits.
+ * Run it on two checkouts to compare them.
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@State(Scope.Benchmark)
+@Warmup(iterations = 4, time = 1)
+@Measurement(iterations = 5, time = 1)
+@Fork(
+ value = 3,
+ jvmArgsAppend = {"-Xmx2g", "-Xms2g", "-XX:+AlwaysPreTouch"})
+public class VectorScorerQuantizedBenchmark {
Review Comment:
is it scoring 8-at-a-time and we didn't test that before?
##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,448 @@
+/*
+ * 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.internal.vectorization;
+
+import java.io.IOException;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.nio.ByteOrder;
+import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorScorer;
+import org.apache.lucene.codecs.lucene104.OffHeapScalarQuantizedVectorValues;
+import org.apache.lucene.index.KnnVectorValues;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.FilterIndexInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.MemorySegmentAccessInput;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
+import
org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+
+/**
+ * A {@link Lucene104ScalarQuantizedVectorScorer} that scores vectors in place
in the {@link
+ * MemorySegment} that holds them, several at a time in {@link
RandomVectorScorer#bulkScore} so that
+ * their cache misses overlap, instead of copying each on heap first. Vectors
that are not memory
+ * mapped in one segment are scored by the superclass.
+ */
+final class Lucene104MemorySegmentScalarQuantizedVectorScorer
+ extends Lucene104ScalarQuantizedVectorScorer {
+
+ static final Lucene104MemorySegmentScalarQuantizedVectorScorer INSTANCE =
+ new Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ Lucene99MemorySegmentFlatVectorsScorer.INSTANCE);
+
+ private final FlatVectorsScorer nonQuantizedDelegate;
+
+ private Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ FlatVectorsScorer nonQuantizedDelegate) {
+ super(nonQuantizedDelegate);
+ this.nonQuantizedDelegate = nonQuantizedDelegate;
+ }
+
+ @Override
+ public String toString() {
+ return
"Lucene104MemorySegmentScalarQuantizedVectorScorer(nonQuantizedDelegate="
+ + nonQuantizedDelegate
+ + ")";
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues
vectorValues)
+ throws IOException {
+ if (vectorValues instanceof QuantizedByteVectorValues qv
+ && qv.getScalarEncoding().isAsymmetric() == false) {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, qv, qv);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
vectorValues);
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues scoringVectors,
+ QuantizedByteVectorValues targetVectors)
+ throws IOException {
+ if (targetVectors.getScalarEncoding().isAsymmetric()) {
+ Records records = Records.of(targetVectors, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, targetVectors,
scoringVectors);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
scoringVectors, targetVectors);
+ }
+
+ @Override
+ protected RandomVectorScorer getQuantizedQueryScorer(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues qv,
+ byte[] quantizedQuery,
+ QuantizationResult queryCorrections)
+ throws IOException {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return QueryScorer.create(records, qv, quantizedQuery, queryCorrections);
+ }
+ return super.getQuantizedQueryScorer(similarityFunction, qv,
quantizedQuery, queryCorrections);
+ }
+
+ /**
+ * The records of one field in a segment: each is the packed vector followed
by its corrective
+ * terms, three floats and an int. Holds values only, so one instance serves
every scorer of a
+ * supplier and its copies.
+ *
+ * <p>The segment is that of the whole slice, like in {@link
+ * Lucene99MemorySegmentFlatVectorsScorer}. Scoring after the input is
closed fails on the
+ * segment, not with an {@link
org.apache.lucene.store.AlreadyClosedException}.
+ */
+ private record Records(
+ MemorySegment segment,
+ VectorSimilarityFunction similarity,
+ ScalarEncoding encoding,
+ int size,
+ int dimension,
+ float centroidDp,
+ int packedLength,
+ int stride) {
+
+ static final int CORRECTIONS_BYTES = 3 * Float.BYTES + Integer.BYTES;
+ static final ValueLayout.OfFloat LE_FLOAT =
+ ValueLayout.JAVA_FLOAT_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN);
+ static final ValueLayout.OfInt LE_INT =
+ ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN);
+
+ /**
+ * Returns the records of {@code values}, or null if they cannot be scored
this way: when they
+ * are not off heap, or when they span more than one mapped chunk.
+ */
+ static Records of(QuantizedByteVectorValues values,
VectorSimilarityFunction similarity)
+ throws IOException {
+ if (values instanceof OffHeapScalarQuantizedVectorValues == false) {
+ return null;
+ }
+ IndexInput slice = values.getSlice();
+ MemorySegment segment = null;
+ if (slice != null
+ && FilterIndexInput.unwrapOnlyTest(slice) instanceof
MemorySegmentAccessInput input) {
+ segment = input.segmentSliceOrNull(0, input.length());
+ }
+ if (segment == null) {
+ return null;
+ }
+ int packedLength = values.getVectorByteLength();
+ int stride = packedLength + CORRECTIONS_BYTES;
+ if (segment.byteSize() < (long) stride * values.size()) {
+ throw new IllegalArgumentException("input length is less than expected
vector data");
+ }
+ return new Records(
+ segment,
+ similarity,
+ values.getScalarEncoding(),
+ values.size(),
+ values.dimension(),
+ values.getCentroidDP(),
+ packedLength,
+ stride);
+ }
+
+ /**
+ * The length of a quantized query: the discretized dimensions for 8 and 7
bit vectors, twice
+ * the packed length (one nibble per byte) for 4 bit vectors, and the
transposed 4 bit planes
+ * for the 1 and 2 bit vectors.
+ */
+ int queryLength() {
+ return encoding.isAsymmetric()
+ ? encoding.getQueryPackedLength(dimension)
+ : encoding.getDiscreteDimensions(dimension);
+ }
+
+ void checkQuery(byte[] query) {
+ if (query.length != queryLength()) {
+ throw new IllegalArgumentException(
+ "query length " + query.length + " != " + queryLength() + " for "
+ encoding);
+ }
+ }
+
+ void checkOrdinal(int ord) {
+ if (ord < 0 || ord >= size) {
+ throw new IllegalArgumentException("illegal ordinal: " + ord);
+ }
+ }
+
+ long offset(int ord) {
+ checkOrdinal(ord);
+ return (long) ord * stride;
+ }
+ }
+
+ /**
+ * Scores one quantized query, held on heap, against {@link Records}: four
vectors per {@link
+ * #bulkScore} pass in place, and {@link #score} like the superclass,
reading the vector on heap.
+ * There is one subclass per kernel, chosen once per scorer, so that no
encoding is looked up
+ * while scoring.
+ */
+ private abstract static class QueryScorer extends
RandomVectorScorer.AbstractRandomVectorScorer {
+ final Records records;
+ final MemorySegment segment;
+ final int packedLength;
+
+ /** The values {@link #score} reads from; not shared with another scorer.
*/
+ private final QuantizedByteVectorValues values;
Review Comment:
So is *this* the queries?
##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,448 @@
+/*
+ * 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.internal.vectorization;
+
+import java.io.IOException;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.nio.ByteOrder;
+import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
+import org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorScorer;
+import org.apache.lucene.codecs.lucene104.OffHeapScalarQuantizedVectorValues;
+import org.apache.lucene.index.KnnVectorValues;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.FilterIndexInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.MemorySegmentAccessInput;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
+import
org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+
+/**
+ * A {@link Lucene104ScalarQuantizedVectorScorer} that scores vectors in place
in the {@link
+ * MemorySegment} that holds them, several at a time in {@link
RandomVectorScorer#bulkScore} so that
+ * their cache misses overlap, instead of copying each on heap first. Vectors
that are not memory
+ * mapped in one segment are scored by the superclass.
+ */
+final class Lucene104MemorySegmentScalarQuantizedVectorScorer
+ extends Lucene104ScalarQuantizedVectorScorer {
+
+ static final Lucene104MemorySegmentScalarQuantizedVectorScorer INSTANCE =
+ new Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ Lucene99MemorySegmentFlatVectorsScorer.INSTANCE);
+
+ private final FlatVectorsScorer nonQuantizedDelegate;
+
+ private Lucene104MemorySegmentScalarQuantizedVectorScorer(
+ FlatVectorsScorer nonQuantizedDelegate) {
+ super(nonQuantizedDelegate);
+ this.nonQuantizedDelegate = nonQuantizedDelegate;
+ }
+
+ @Override
+ public String toString() {
+ return
"Lucene104MemorySegmentScalarQuantizedVectorScorer(nonQuantizedDelegate="
+ + nonQuantizedDelegate
+ + ")";
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues
vectorValues)
+ throws IOException {
+ if (vectorValues instanceof QuantizedByteVectorValues qv
+ && qv.getScalarEncoding().isAsymmetric() == false) {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, qv, qv);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
vectorValues);
+ }
+
+ @Override
+ public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues scoringVectors,
+ QuantizedByteVectorValues targetVectors)
+ throws IOException {
+ if (targetVectors.getScalarEncoding().isAsymmetric()) {
+ Records records = Records.of(targetVectors, similarityFunction);
+ if (records != null) {
+ return new OffHeapScorerSupplier(records, targetVectors,
scoringVectors);
+ }
+ }
+ return super.getRandomVectorScorerSupplier(similarityFunction,
scoringVectors, targetVectors);
+ }
+
+ @Override
+ protected RandomVectorScorer getQuantizedQueryScorer(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues qv,
+ byte[] quantizedQuery,
+ QuantizationResult queryCorrections)
+ throws IOException {
+ Records records = Records.of(qv, similarityFunction);
+ if (records != null) {
+ return QueryScorer.create(records, qv, quantizedQuery, queryCorrections);
+ }
+ return super.getQuantizedQueryScorer(similarityFunction, qv,
quantizedQuery, queryCorrections);
+ }
+
+ /**
+ * The records of one field in a segment: each is the packed vector followed
by its corrective
+ * terms, three floats and an int. Holds values only, so one instance serves
every scorer of a
+ * supplier and its copies.
+ *
+ * <p>The segment is that of the whole slice, like in {@link
+ * Lucene99MemorySegmentFlatVectorsScorer}. Scoring after the input is
closed fails on the
+ * segment, not with an {@link
org.apache.lucene.store.AlreadyClosedException}.
+ */
+ private record Records(
+ MemorySegment segment,
+ VectorSimilarityFunction similarity,
+ ScalarEncoding encoding,
+ int size,
+ int dimension,
+ float centroidDp,
+ int packedLength,
+ int stride) {
+
+ static final int CORRECTIONS_BYTES = 3 * Float.BYTES + Integer.BYTES;
+ static final ValueLayout.OfFloat LE_FLOAT =
+ ValueLayout.JAVA_FLOAT_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN);
+ static final ValueLayout.OfInt LE_INT =
+ ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.LITTLE_ENDIAN);
+
+ /**
+ * Returns the records of {@code values}, or null if they cannot be scored
this way: when they
+ * are not off heap, or when they span more than one mapped chunk.
+ */
+ static Records of(QuantizedByteVectorValues values,
VectorSimilarityFunction similarity)
+ throws IOException {
+ if (values instanceof OffHeapScalarQuantizedVectorValues == false) {
+ return null;
+ }
+ IndexInput slice = values.getSlice();
+ MemorySegment segment = null;
+ if (slice != null
+ && FilterIndexInput.unwrapOnlyTest(slice) instanceof
MemorySegmentAccessInput input) {
+ segment = input.segmentSliceOrNull(0, input.length());
+ }
+ if (segment == null) {
+ return null;
+ }
+ int packedLength = values.getVectorByteLength();
+ int stride = packedLength + CORRECTIONS_BYTES;
+ if (segment.byteSize() < (long) stride * values.size()) {
+ throw new IllegalArgumentException("input length is less than expected
vector data");
+ }
+ return new Records(
+ segment,
+ similarity,
+ values.getScalarEncoding(),
+ values.size(),
+ values.dimension(),
+ values.getCentroidDP(),
+ packedLength,
+ stride);
+ }
+
+ /**
+ * The length of a quantized query: the discretized dimensions for 8 and 7
bit vectors, twice
+ * the packed length (one nibble per byte) for 4 bit vectors, and the
transposed 4 bit planes
+ * for the 1 and 2 bit vectors.
+ */
+ int queryLength() {
+ return encoding.isAsymmetric()
+ ? encoding.getQueryPackedLength(dimension)
+ : encoding.getDiscreteDimensions(dimension);
+ }
+
+ void checkQuery(byte[] query) {
+ if (query.length != queryLength()) {
+ throw new IllegalArgumentException(
+ "query length " + query.length + " != " + queryLength() + " for "
+ encoding);
+ }
+ }
+
+ void checkOrdinal(int ord) {
+ if (ord < 0 || ord >= size) {
+ throw new IllegalArgumentException("illegal ordinal: " + ord);
+ }
+ }
+
+ long offset(int ord) {
+ checkOrdinal(ord);
+ return (long) ord * stride;
+ }
+ }
+
+ /**
+ * Scores one quantized query, held on heap, against {@link Records}: four
vectors per {@link
+ * #bulkScore} pass in place, and {@link #score} like the superclass,
reading the vector on heap.
+ * There is one subclass per kernel, chosen once per scorer, so that no
encoding is looked up
+ * while scoring.
+ */
+ private abstract static class QueryScorer extends
RandomVectorScorer.AbstractRandomVectorScorer {
+ final Records records;
+ final MemorySegment segment;
+ final int packedLength;
+
+ /** The values {@link #score} reads from; not shared with another scorer.
*/
+ private final QuantizedByteVectorValues values;
+
+ private final int[] dotProducts = new int[4];
+ byte[] query;
+ private QuantizationResult queryCorrections;
+
+ QueryScorer(
+ Records records,
+ QuantizedByteVectorValues values,
+ byte[] query,
+ QuantizationResult queryCorrections) {
+ super(values);
+ this.records = records;
+ this.segment = records.segment();
Review Comment:
oh wait a sec -- this *is* the same as the field's memory segment. Why do we
need a separate variable for it?
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]