msokolov commented on code in PR #17013:
URL: https://github.com/apache/lucene/pull/17013#discussion_r4603526946


##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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;

Review Comment:
   I suppose it can be catastrophic if this fallback occurs a lot? But we 
expect memory segments to be large I think? So the only case where we'd expect 
this fallback to come in to play is in case we have a very large vector field 
where a single segment's worth of data cannot fit in a single memory segment? I 
think? Is there some other case where we expect to have to fall back?



##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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) {
+      QuantizedVectorField quantizedVectorField = QuantizedVectorField.of(qv, 
similarityFunction);
+      if (quantizedVectorField != null) {
+        return new OffHeapScorerSupplier(quantizedVectorField, qv, qv);
+      }
+    }
+    return super.getRandomVectorScorerSupplier(similarityFunction, 
vectorValues);
+  }
+
+  @Override
+  public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+      VectorSimilarityFunction similarityFunction,
+      QuantizedByteVectorValues scoringVectors,
+      QuantizedByteVectorValues targetVectors)
+      throws IOException {
+    if (targetVectors.getScalarEncoding().isAsymmetric()) {
+      QuantizedVectorField quantizedVectorField =
+          QuantizedVectorField.of(targetVectors, similarityFunction);
+      if (quantizedVectorField != null) {
+        return new OffHeapScorerSupplier(quantizedVectorField, targetVectors, 
scoringVectors);
+      }
+    }
+    return super.getRandomVectorScorerSupplier(similarityFunction, 
scoringVectors, targetVectors);
+  }
+
+  @Override
+  protected RandomVectorScorer getVectorScorer(
+      VectorSimilarityFunction similarityFunction,
+      QuantizedByteVectorValues qv,
+      byte[] quantizedQuery,
+      QuantizationResult queryCorrections)
+      throws IOException {
+    QuantizedVectorField quantizedVectorField = QuantizedVectorField.of(qv, 
similarityFunction);
+    if (quantizedVectorField != null) {
+      return ScorerBase.create(quantizedVectorField, qv, quantizedQuery, 
queryCorrections);
+    }
+    return super.getVectorScorer(similarityFunction, qv, quantizedQuery, 
queryCorrections);
+  }
+
+  /**
+   * Represent quantized vectors in a single field. {@code dataSeg} contains 
the vectors laid out
+   * serially as entries, each entry consists of quantized bytes followed by 
corrective terms.
+   */
+  private record QuantizedVectorField(
+      MemorySegment dataSeg,
+      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);
+
+    static QuantizedVectorField 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());

Review Comment:
   can this return null? If not, maybe it's clearer to replace
   
   ```
         if (segment == null) {
           return null;
         }
   ```
   
   with
   
   ``` 
       else {
         return null;
       }
   ```
   



##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/MemorySegmentQuantizedVectorOps.java:
##########
@@ -0,0 +1,397 @@
+/*
+ * 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 static java.lang.foreign.ValueLayout.JAVA_BYTE;
+import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED;
+import static java.nio.ByteOrder.LITTLE_ENDIAN;
+import static jdk.incubator.vector.VectorOperators.ADD;
+import static jdk.incubator.vector.VectorOperators.BIT_COUNT;
+import static jdk.incubator.vector.VectorOperators.LSHL;
+import static jdk.incubator.vector.VectorOperators.LSHR;
+import static jdk.incubator.vector.VectorOperators.ZERO_EXTEND_B2I;
+import static jdk.incubator.vector.VectorOperators.ZERO_EXTEND_B2S;
+import static jdk.incubator.vector.VectorOperators.ZERO_EXTEND_S2I;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorConstants.PRERERRED_INT_SPECIES;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorUtilSupport.BYTE_SPECIES;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorUtilSupport.BYTE_SPECIES_FULL;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorUtilSupport.SHORT_SPECIES;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorUtilSupport.VECTOR_BITSIZE;
+
+import java.lang.foreign.MemorySegment;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.VarHandle;
+import java.nio.ByteOrder;
+import jdk.incubator.vector.ByteVector;
+import jdk.incubator.vector.IntVector;
+import jdk.incubator.vector.LongVector;
+import jdk.incubator.vector.ShortVector;
+import jdk.incubator.vector.Vector;
+import jdk.incubator.vector.VectorShape;
+import jdk.incubator.vector.VectorSpecies;
+
+/**
+ * Dot products of a quantized query on heap with quantized vectors read in 
place from a {@link
+ * MemorySegment}, several vectors per pass so that the CPU overlaps their 
cache misses instead of
+ * waiting for the misses of one vector after the other. The 8 bit kernels 
read four vectors per
+ * pass; the 4, 2 and 1 bit kernels read two, because a pass over four would 
exceed the budget C2

Review Comment:
   this is depressing :(



##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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) {
+      QuantizedVectorField quantizedVectorField = QuantizedVectorField.of(qv, 
similarityFunction);
+      if (quantizedVectorField != null) {
+        return new OffHeapScorerSupplier(quantizedVectorField, qv, qv);
+      }
+    }
+    return super.getRandomVectorScorerSupplier(similarityFunction, 
vectorValues);
+  }
+
+  @Override
+  public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+      VectorSimilarityFunction similarityFunction,
+      QuantizedByteVectorValues scoringVectors,
+      QuantizedByteVectorValues targetVectors)
+      throws IOException {
+    if (targetVectors.getScalarEncoding().isAsymmetric()) {

Review Comment:
   I'm confused why this new scorer(supplier) is only used for asymmetric 
encodings (which are the 1- and 2-bit encodings). Isn't this also going to be 
helpful for 4- and 8-bit encodings?



##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/MemorySegmentQuantizedVectorOps.java:
##########
@@ -0,0 +1,397 @@
+/*
+ * 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 static java.lang.foreign.ValueLayout.JAVA_BYTE;
+import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED;
+import static java.nio.ByteOrder.LITTLE_ENDIAN;
+import static jdk.incubator.vector.VectorOperators.ADD;
+import static jdk.incubator.vector.VectorOperators.BIT_COUNT;
+import static jdk.incubator.vector.VectorOperators.LSHL;
+import static jdk.incubator.vector.VectorOperators.LSHR;
+import static jdk.incubator.vector.VectorOperators.ZERO_EXTEND_B2I;
+import static jdk.incubator.vector.VectorOperators.ZERO_EXTEND_B2S;
+import static jdk.incubator.vector.VectorOperators.ZERO_EXTEND_S2I;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorConstants.PRERERRED_INT_SPECIES;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorUtilSupport.BYTE_SPECIES;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorUtilSupport.BYTE_SPECIES_FULL;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorUtilSupport.SHORT_SPECIES;
+import static 
org.apache.lucene.internal.vectorization.PanamaVectorUtilSupport.VECTOR_BITSIZE;
+
+import java.lang.foreign.MemorySegment;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.VarHandle;
+import java.nio.ByteOrder;
+import jdk.incubator.vector.ByteVector;
+import jdk.incubator.vector.IntVector;
+import jdk.incubator.vector.LongVector;
+import jdk.incubator.vector.ShortVector;
+import jdk.incubator.vector.Vector;
+import jdk.incubator.vector.VectorShape;
+import jdk.incubator.vector.VectorSpecies;
+
+/**
+ * Dot products of a quantized query on heap with quantized vectors read in 
place from a {@link
+ * MemorySegment}, several vectors per pass so that the CPU overlaps their 
cache misses instead of
+ * waiting for the misses of one vector after the other. The 8 bit kernels 
read four vectors per
+ * pass; the 4, 2 and 1 bit kernels read two, because a pass over four would 
exceed the budget C2
+ * has for inlining the vector operations of a method, and vector operations 
that are not inlined
+ * are hundreds of times slower.
+ *
+ * <p>The query and vector layouts are those of {@link
+ * org.apache.lucene.codecs.lucene104.Lucene104ScalarQuantizedVectorsFormat}; 
see the matching
+ * single vector methods of {@link org.apache.lucene.util.VectorUtil} for each 
layout. The results
+ * are identical to those methods. The callers pass the vector length, which 
they know from the
+ * index, and a query of exactly the length the layout needs. Every kernel 
zeroes {@code
+ * results[0..3]} first and then adds to them, pass by pass.
+ */
+final class MemorySegmentQuantizedVectorOps {
+
+  // Reads query longs in the order of the segment reads, which is the native 
one. (The handles in
+  // BitUtil use a randomized order in tests.)
+  private static final VarHandle NATIVE_LONG =
+      MethodHandles.byteArrayViewVarHandle(long[].class, 
ByteOrder.nativeOrder());
+
+  // Bit counts are summed in 64 bit lanes like the single vector kernel of 
VectorUtil does for
+  // 256 bit vectors and up.
+  private static final VectorSpecies<Long> LONG_SPECIES =
+      LongVector.SPECIES_MAX.withShape(VectorShape.forBitSize(VECTOR_BITSIZE));
+
+  private MemorySegmentQuantizedVectorOps() {}
+
+  // -- unsigned bytes (8 bit and 7 bit values)
+
+  /**
+   * Dot products of the first {@code length} bytes of {@code q} with the four 
vectors of that
+   * length at the given offsets, all treated as unsigned bytes, into {@code 
results[0..3]}.
+   */
+  static void uint8DotProductBulk(

Review Comment:
   This whole file is pretty hairy. Do we have some good tests demonstrating 
that these functionsa are correct?



##########
lucene/core/src/test/org/apache/lucene/internal/vectorization/TestLucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,555 @@
+/*
+ * 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 com.carrotsearch.randomizedtesting.generators.RandomPicks;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.lucene.codecs.hnsw.DefaultFlatVectorScorer;
+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.tests.util.LuceneTestCase;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.NamedThreadFactory;
+import org.apache.lucene.util.VectorUtil;
+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;
+import 
org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import 
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+import org.junit.BeforeClass;
+
+/**
+ * Checks that the memory segment scorer of the Lucene104 scalar quantized 
format gives the same
+ * scores as the default scorer, for every encoding, similarity, and scoring 
path.
+ */
+public class TestLucene104MemorySegmentScalarQuantizedVectorScorer extends 
LuceneTestCase {
+
+  // The reference scorer reads vectors on heap and scores them through 
VectorUtil. With a
+  // tests.vectorsize set, which the build picks at random, VectorUtil is the 
scalar
+  // DefaultVectorUtilSupport; otherwise it is the Panama single vector 
kernels, so that the two
+  // scorers are checked against each other.
+  private static final Lucene104ScalarQuantizedVectorScorer DEFAULT_SCORER =
+      new 
Lucene104ScalarQuantizedVectorScorer(DefaultFlatVectorScorer.INSTANCE);
+  private static final Lucene104ScalarQuantizedVectorScorer MEMSEG_SCORER =
+      
VectorizationProvider.lookup(true).getLucene104ScalarQuantizedVectorsScorer();
+
+  // dimensions around the widths of the vector kernels and their tails
+  private static final int[] DIMENSIONS = {
+    1, 2, 3, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127, 128, 129, 255, 
256, 257, 511, 512,
+    513, 1024, 1025
+  };
+
+  @BeforeClass
+  public static void beforeClass() {
+    assumeTrue(
+        "Test only works when the memory segment scorer is present.",
+        MEMSEG_SCORER.getClass() != DEFAULT_SCORER.getClass());
+  }
+
+  public void testAllEncodingsAndSimilarities() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testAll"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        for (VectorSimilarityFunction similarity : 
VectorSimilarityFunction.values()) {
+          for (int dims : DIMENSIONS) {
+            try (Vectors vectors =
+                new Vectors(dir, encoding, similarity, dims, 
random().nextInt(1, 12))) {
+              assertSameScores(vectors, true);
+            }
+          }
+        }
+      }
+    }
+  }
+
+  public void testRandom() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testRandom"))) {
+      for (int iter = 0; iter < 20; iter++) {
+        try (Vectors vectors =
+            new Vectors(
+                dir,
+                RandomPicks.randomFrom(random(), ScalarEncoding.values()),
+                RandomPicks.randomFrom(random(), 
VectorSimilarityFunction.values()),
+                random().nextInt(1, 2000),
+                random().nextInt(1, 100))) {
+          assertSameScores(vectors, true);
+        }
+      }
+    }
+  }
+
+  /** Vectors that span mapped chunks are scored by the default scorer, with 
the same result. */
+  public void testSmallChunkSize() throws IOException {
+    long maxChunkSize = random().nextLong(32, 4096);
+    try (Directory dir = new MMapDirectory(createTempDir("testSmallChunk"), 
maxChunkSize)) {
+      for (int iter = 0; iter < 10; iter++) {
+        try (Vectors vectors =
+            new Vectors(
+                dir,
+                RandomPicks.randomFrom(random(), ScalarEncoding.values()),
+                RandomPicks.randomFrom(random(), 
VectorSimilarityFunction.values()),
+                random().nextInt(1, 300),
+                random().nextInt(1, 50))) {
+          // records that fit in one chunk (a power of two) are still scored 
off heap
+          long recordBytes = (long) vectors.values.getVectorByteLength() + 16;
+          long chunkSize = Long.highestOneBit(maxChunkSize);
+          assertSameScores(vectors, recordBytes * vectors.size <= chunkSize);
+        }
+      }
+    }
+  }
+
+  public void testIllegalOrdinal() throws IOException {
+    try (Directory dir = new 
MMapDirectory(createTempDir("testIllegalOrdinal"))) {
+      try (Vectors vectors =
+          new Vectors(
+              dir,
+              RandomPicks.randomFrom(random(), ScalarEncoding.values()),
+              VectorSimilarityFunction.DOT_PRODUCT,
+              random().nextInt(1, 100),
+              random().nextInt(1, 10))) {
+        RandomVectorScorer scorer =
+            MEMSEG_SCORER.getRandomVectorScorer(
+                vectors.similarity, vectors.values, vectors.randomQuery());
+        float[] scores = new float[2];
+        // the same exception as the Lucene99 memory segment scorers; the 
default scorer differs
+        for (int ord : new int[] {-1, vectors.size, vectors.size + 
random().nextInt(100)}) {
+          expectThrows(IllegalArgumentException.class, () -> 
scorer.score(ord));
+          expectThrows(
+              IllegalArgumentException.class,
+              () -> scorer.bulkScore(new int[] {0, ord}, scores, 2));
+          expectThrows(
+              IllegalArgumentException.class,
+              () -> scorer.bulkScore(new int[] {0, 0, 0, 0, ord}, new 
float[5], 5));
+        }
+      }
+    }
+  }
+
+  /**
+   * Vectors with the largest quantized values, at lengths around the 
accumulator chunks: the 4 bit
+   * kernel sums 16 bit lanes over chunks of 1024, 2048 or 4096 packed bytes 
(2048, 4096 or 8192
+   * dims) for 128, 256 or 512 bit vectors, and with all values at 15 a lane 
reaches 57600 of 65535
+   * at the end of a chunk. A larger chunk, or one more product per step, 
overflows and fails here.
+   *
+   * <p>Only the bulk path of one query is checked: the vectors are long and 
the kernels are slow
+   * when the test JVM does not compile the Vector API (the other tests cover 
the paths).
+   */
+  public void testSaturatedValues() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testSaturated"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        // one less, exactly, and one more packed byte than one and two 
chunks, at each width
+        for (int dims :
+            new int[] {
+              31, 1024, 2046, 2048, 2050, 4094, 4096, 4098, 8190, 8192, 8194, 
8320, 8334, 16384,
+              16398
+            }) {
+          try (Vectors vectors =
+              new Vectors(
+                  dir,
+                  encoding,
+                  RandomPicks.randomFrom(random(), 
VectorSimilarityFunction.values()),
+                  dims,
+                  5,
+                  true)) {
+            float[] query = vectors.randomQuery();
+            RandomVectorScorer expected =
+                DEFAULT_SCORER.getRandomVectorScorer(
+                    vectors.similarity, vectors.values, query.clone());
+            RandomVectorScorer scorer =
+                MEMSEG_SCORER.getRandomVectorScorer(
+                    vectors.similarity, vectors.values, query.clone());
+            assertTrue(scorer.getClass().getName().contains("MemorySegment"));
+            // a full pass of the kernel and a tail, then two full passes
+            assertSameBulkScores(vectors.toString(), expected, scorer, 
vectors.size, vectors.size);
+            assertSameBulkScores(vectors.toString(), expected, scorer, 
vectors.size, 8);
+          }
+        }
+      }
+    }
+  }
+
+  public void testQueryLengthIsChecked() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testQueryLength"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        try (Vectors vectors =
+            new Vectors(dir, encoding, VectorSimilarityFunction.DOT_PRODUCT, 
64, 3)) {
+          // a query vector of another dimension is refused before reaching 
the kernels
+          expectThrows(
+              IllegalArgumentException.class,
+              () ->
+                  MEMSEG_SCORER.getRandomVectorScorer(
+                      vectors.similarity, vectors.values, new float[65]));
+        }
+      }
+    }
+  }
+
+  public void testShortInputIsRejected() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testShortInput"))) {
+      try (Vectors vectors =
+          new Vectors(
+              dir, ScalarEncoding.UNSIGNED_BYTE, 
VectorSimilarityFunction.DOT_PRODUCT, 16, 4)) {
+        // claim one record more than the slice holds
+        QuantizedByteVectorValues values = vectors.values(vectors.size + 1);
+        expectThrows(
+            IllegalArgumentException.class,
+            () -> MEMSEG_SCORER.getRandomVectorScorer(vectors.similarity, 
values, new float[16]));
+      }
+    }
+  }
+
+  public void testScoringOrdinalMustBeSet() throws IOException {
+    try (Directory dir = new 
MMapDirectory(createTempDir("testOrdinalNotSet"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        try (Vectors vectors =
+            new Vectors(dir, encoding, VectorSimilarityFunction.DOT_PRODUCT, 
32, 3)) {
+          UpdateableRandomVectorScorer scorer = 
vectors.supplier(MEMSEG_SCORER).scorer();
+          expectThrows(IllegalStateException.class, () -> scorer.score(0));
+          expectThrows(
+              IllegalStateException.class, () -> scorer.bulkScore(new int[] 
{0}, new float[1], 1));
+        }
+      }
+    }
+  }
+
+  /** Values without records have nothing to score, but a query scorer can 
still be made. */
+  public void testNoVectors() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testNoVectors"))) {
+      try (Vectors vectors =
+          new Vectors(
+              dir,
+              RandomPicks.randomFrom(random(), ScalarEncoding.values()),
+              VectorSimilarityFunction.DOT_PRODUCT,
+              random().nextInt(1, 100),
+              1)) {
+        RandomVectorScorer scorer =
+            MEMSEG_SCORER.getRandomVectorScorer(
+                vectors.similarity, vectors.values(0), vectors.randomQuery());
+        assertTrue(scorer.getClass().getName().contains("MemorySegment"));
+        assertEquals(Float.NEGATIVE_INFINITY, scorer.bulkScore(new int[0], new 
float[0], 0), 0f);
+        expectThrows(IllegalArgumentException.class, () -> scorer.score(0));
+      }
+    }
+  }
+
+  /** Copies of a supplier do not share scoring state. */
+  public void testCopiesAcrossThreads() throws Exception {
+    try (Directory dir = new MMapDirectory(createTempDir("testCopies"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        try (Vectors vectors =
+            new Vectors(
+                dir,
+                encoding,
+                RandomPicks.randomFrom(random(), 
VectorSimilarityFunction.values()),
+                random().nextInt(1, 300),
+                4)) {
+          RandomVectorScorerSupplier expected = 
vectors.supplier(DEFAULT_SCORER);
+          RandomVectorScorerSupplier supplier = 
vectors.supplier(MEMSEG_SCORER);
+          List<Callable<Optional<Throwable>>> tasks =
+              List.of(
+                  new AssertingScoreCallable(expected.copy(), supplier.copy(), 
0, 1),
+                  new AssertingScoreCallable(expected.copy(), supplier.copy(), 
2, 3),
+                  new AssertingScoreCallable(expected.copy(), supplier.copy(), 
1, 1));
+          var executor = Executors.newFixedThreadPool(3, new 
NamedThreadFactory("copiesThreads"));
+          var results = executor.invokeAll(tasks);
+          executor.shutdown();
+          assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));
+          for (var result : results) {
+            assertTrue("Unexpected exception " + result.get(), 
result.get().isEmpty());
+          }
+        }
+      }
+    }
+  }
+
+  private record AssertingScoreCallable(
+      RandomVectorScorerSupplier expectedSupplier,
+      RandomVectorScorerSupplier supplier,
+      int target,
+      int ord)
+      implements Callable<Optional<Throwable>> {
+    @Override
+    public Optional<Throwable> call() throws Exception {
+      UpdateableRandomVectorScorer expected = expectedSupplier.scorer();
+      expected.setScoringOrdinal(target);
+      UpdateableRandomVectorScorer scorer = supplier.scorer();
+      scorer.setScoringOrdinal(target);
+      try {
+        int[] nodes = {ord, 0, 1, 2, 3, ord};
+        float[] expectedScores = new float[nodes.length];
+        float[] scores = new float[nodes.length];
+        for (int i = 0; i < 100; i++) {
+          assertEquals(expected.score(ord), scorer.score(ord), 0f);
+          assertEquals(
+              expected.bulkScore(nodes, expectedScores, nodes.length),
+              scorer.bulkScore(nodes, scores, nodes.length),
+              0f);
+          assertArrayEquals(expectedScores, scores, 0f);
+        }
+      } catch (Throwable t) {
+        return Optional.of(t);
+      }
+      return Optional.empty();
+    }
+  }
+
+  /** Compares every scoring path of the two scorers, exactly. */
+  private void assertSameScores(Vectors vectors, boolean expectOffHeap) throws 
IOException {
+    // float and float16 queries
+    for (int q = 0; q < 2; q++) {
+      float[] query = vectors.randomQuery();
+      RandomVectorScorer expected =
+          DEFAULT_SCORER.getRandomVectorScorer(vectors.similarity, 
vectors.values, query.clone());
+      RandomVectorScorer scorer =
+          MEMSEG_SCORER.getRandomVectorScorer(vectors.similarity, 
vectors.values, query.clone());
+      assertEquals(expectOffHeap, 
scorer.getClass().getName().contains("MemorySegment"));
+      assertSameScores(vectors + " float query", expected, scorer, 
vectors.size);
+      short[] query16 = new short[query.length];
+      for (int i = 0; i < query.length; i++) {
+        query16[i] = Float.floatToFloat16(query[i]);
+      }
+      expected = DEFAULT_SCORER.getRandomVectorScorer(vectors.similarity, 
vectors.values, query16);
+      scorer = MEMSEG_SCORER.getRandomVectorScorer(vectors.similarity, 
vectors.values, query16);
+      assertSameScores(vectors + " float16 query", expected, scorer, 
vectors.size);
+    }
+    // vectors as queries, as when building a graph; also through a copy of 
the supplier
+    UpdateableRandomVectorScorer expected = 
vectors.supplier(DEFAULT_SCORER).scorer();
+    RandomVectorScorerSupplier supplier = vectors.supplier(MEMSEG_SCORER);
+    UpdateableRandomVectorScorer scorer =
+        random().nextBoolean() ? supplier.scorer() : supplier.copy().scorer();
+    assertEquals(expectOffHeap, 
scorer.getClass().getName().contains("MemorySegment"));
+    for (int q = 0; q < 2; q++) {
+      int target = random().nextInt(vectors.size);
+      expected.setScoringOrdinal(target);
+      scorer.setScoringOrdinal(target);
+      assertSameScores(vectors + " ordinal " + target, expected, scorer, 
vectors.size);
+    }
+  }
+
+  private static void assertSameScores(
+      String context, RandomVectorScorer expected, RandomVectorScorer scorer, 
int size)
+      throws IOException {
+    for (int ord = 0; ord < size; ord++) {
+      assertEquals(context + " ord " + ord, expected.score(ord), 
scorer.score(ord), 0f);
+    }
+    // batches of every size up to a neighbor list, with repeated ordinals, 
and a batch shorter
+    // than its arrays
+    for (int numNodes = 0; numNodes <= 13; numNodes++) {
+      assertSameBulkScores(context, expected, scorer, size, numNodes);
+    }
+    assertSameBulkScores(context, expected, scorer, size, 64 + 
random().nextInt(4));
+  }
+
+  private static void assertSameBulkScores(
+      String context,
+      RandomVectorScorer expected,
+      RandomVectorScorer scorer,
+      int size,
+      int numNodes)
+      throws IOException {
+    int[] nodes = new int[numNodes + random().nextInt(3)];
+    for (int i = 0; i < nodes.length; i++) {
+      nodes[i] = random().nextInt(size);
+    }
+    float[] expectedScores = new float[nodes.length];
+    float[] scores = new float[nodes.length];
+    float expectedMax = expected.bulkScore(nodes, expectedScores, numNodes);
+    float max = scorer.bulkScore(nodes, scores, numNodes);
+    assertEquals(context, expectedMax, max, 0f);
+    for (int i = 0; i < numNodes; i++) {
+      assertEquals(context + " node " + i + " of " + numNodes, 
expectedScores[i], scores[i], 0f);
+    }
+  }
+
+  /** Quantized vectors written like the Lucene104 format writes them. */
+  private static final class Vectors implements Closeable {

Review Comment:
   let;s give this class a better name. Maybe `MockLucene104Vectors`?



##########
lucene/core/src/test/org/apache/lucene/internal/vectorization/TestLucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,555 @@
+/*
+ * 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 com.carrotsearch.randomizedtesting.generators.RandomPicks;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.lucene.codecs.hnsw.DefaultFlatVectorScorer;
+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.tests.util.LuceneTestCase;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.NamedThreadFactory;
+import org.apache.lucene.util.VectorUtil;
+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;
+import 
org.apache.lucene.util.quantization.OptimizedScalarQuantizer.QuantizationResult;
+import org.apache.lucene.util.quantization.QuantizedByteVectorValues;
+import 
org.apache.lucene.util.quantization.QuantizedByteVectorValues.ScalarEncoding;
+import org.junit.BeforeClass;
+
+/**
+ * Checks that the memory segment scorer of the Lucene104 scalar quantized 
format gives the same
+ * scores as the default scorer, for every encoding, similarity, and scoring 
path.
+ */
+public class TestLucene104MemorySegmentScalarQuantizedVectorScorer extends 
LuceneTestCase {
+
+  // The reference scorer reads vectors on heap and scores them through 
VectorUtil. With a
+  // tests.vectorsize set, which the build picks at random, VectorUtil is the 
scalar
+  // DefaultVectorUtilSupport; otherwise it is the Panama single vector 
kernels, so that the two
+  // scorers are checked against each other.
+  private static final Lucene104ScalarQuantizedVectorScorer DEFAULT_SCORER =
+      new 
Lucene104ScalarQuantizedVectorScorer(DefaultFlatVectorScorer.INSTANCE);
+  private static final Lucene104ScalarQuantizedVectorScorer MEMSEG_SCORER =
+      
VectorizationProvider.lookup(true).getLucene104ScalarQuantizedVectorsScorer();
+
+  // dimensions around the widths of the vector kernels and their tails
+  private static final int[] DIMENSIONS = {
+    1, 2, 3, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127, 128, 129, 255, 
256, 257, 511, 512,
+    513, 1024, 1025
+  };
+
+  @BeforeClass
+  public static void beforeClass() {
+    assumeTrue(
+        "Test only works when the memory segment scorer is present.",
+        MEMSEG_SCORER.getClass() != DEFAULT_SCORER.getClass());
+  }
+
+  public void testAllEncodingsAndSimilarities() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testAll"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        for (VectorSimilarityFunction similarity : 
VectorSimilarityFunction.values()) {
+          for (int dims : DIMENSIONS) {
+            try (Vectors vectors =
+                new Vectors(dir, encoding, similarity, dims, 
random().nextInt(1, 12))) {
+              assertSameScores(vectors, true);
+            }
+          }
+        }
+      }
+    }
+  }
+
+  public void testRandom() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testRandom"))) {
+      for (int iter = 0; iter < 20; iter++) {
+        try (Vectors vectors =
+            new Vectors(
+                dir,
+                RandomPicks.randomFrom(random(), ScalarEncoding.values()),
+                RandomPicks.randomFrom(random(), 
VectorSimilarityFunction.values()),
+                random().nextInt(1, 2000),
+                random().nextInt(1, 100))) {
+          assertSameScores(vectors, true);
+        }
+      }
+    }
+  }
+
+  /** Vectors that span mapped chunks are scored by the default scorer, with 
the same result. */
+  public void testSmallChunkSize() throws IOException {
+    long maxChunkSize = random().nextLong(32, 4096);
+    try (Directory dir = new MMapDirectory(createTempDir("testSmallChunk"), 
maxChunkSize)) {
+      for (int iter = 0; iter < 10; iter++) {
+        try (Vectors vectors =
+            new Vectors(
+                dir,
+                RandomPicks.randomFrom(random(), ScalarEncoding.values()),
+                RandomPicks.randomFrom(random(), 
VectorSimilarityFunction.values()),
+                random().nextInt(1, 300),
+                random().nextInt(1, 50))) {
+          // records that fit in one chunk (a power of two) are still scored 
off heap
+          long recordBytes = (long) vectors.values.getVectorByteLength() + 16;
+          long chunkSize = Long.highestOneBit(maxChunkSize);
+          assertSameScores(vectors, recordBytes * vectors.size <= chunkSize);
+        }
+      }
+    }
+  }
+
+  public void testIllegalOrdinal() throws IOException {
+    try (Directory dir = new 
MMapDirectory(createTempDir("testIllegalOrdinal"))) {
+      try (Vectors vectors =
+          new Vectors(
+              dir,
+              RandomPicks.randomFrom(random(), ScalarEncoding.values()),
+              VectorSimilarityFunction.DOT_PRODUCT,
+              random().nextInt(1, 100),
+              random().nextInt(1, 10))) {
+        RandomVectorScorer scorer =
+            MEMSEG_SCORER.getRandomVectorScorer(
+                vectors.similarity, vectors.values, vectors.randomQuery());
+        float[] scores = new float[2];
+        // the same exception as the Lucene99 memory segment scorers; the 
default scorer differs
+        for (int ord : new int[] {-1, vectors.size, vectors.size + 
random().nextInt(100)}) {
+          expectThrows(IllegalArgumentException.class, () -> 
scorer.score(ord));
+          expectThrows(
+              IllegalArgumentException.class,
+              () -> scorer.bulkScore(new int[] {0, ord}, scores, 2));
+          expectThrows(
+              IllegalArgumentException.class,
+              () -> scorer.bulkScore(new int[] {0, 0, 0, 0, ord}, new 
float[5], 5));
+        }
+      }
+    }
+  }
+
+  /**
+   * Vectors with the largest quantized values, at lengths around the 
accumulator chunks: the 4 bit
+   * kernel sums 16 bit lanes over chunks of 1024, 2048 or 4096 packed bytes 
(2048, 4096 or 8192
+   * dims) for 128, 256 or 512 bit vectors, and with all values at 15 a lane 
reaches 57600 of 65535
+   * at the end of a chunk. A larger chunk, or one more product per step, 
overflows and fails here.
+   *
+   * <p>Only the bulk path of one query is checked: the vectors are long and 
the kernels are slow
+   * when the test JVM does not compile the Vector API (the other tests cover 
the paths).
+   */
+  public void testSaturatedValues() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testSaturated"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        // one less, exactly, and one more packed byte than one and two 
chunks, at each width
+        for (int dims :
+            new int[] {
+              31, 1024, 2046, 2048, 2050, 4094, 4096, 4098, 8190, 8192, 8194, 
8320, 8334, 16384,
+              16398
+            }) {
+          try (Vectors vectors =
+              new Vectors(
+                  dir,
+                  encoding,
+                  RandomPicks.randomFrom(random(), 
VectorSimilarityFunction.values()),
+                  dims,
+                  5,
+                  true)) {
+            float[] query = vectors.randomQuery();
+            RandomVectorScorer expected =
+                DEFAULT_SCORER.getRandomVectorScorer(
+                    vectors.similarity, vectors.values, query.clone());
+            RandomVectorScorer scorer =
+                MEMSEG_SCORER.getRandomVectorScorer(
+                    vectors.similarity, vectors.values, query.clone());
+            assertTrue(scorer.getClass().getName().contains("MemorySegment"));
+            // a full pass of the kernel and a tail, then two full passes
+            assertSameBulkScores(vectors.toString(), expected, scorer, 
vectors.size, vectors.size);
+            assertSameBulkScores(vectors.toString(), expected, scorer, 
vectors.size, 8);
+          }
+        }
+      }
+    }
+  }
+
+  public void testQueryLengthIsChecked() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testQueryLength"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        try (Vectors vectors =
+            new Vectors(dir, encoding, VectorSimilarityFunction.DOT_PRODUCT, 
64, 3)) {
+          // a query vector of another dimension is refused before reaching 
the kernels
+          expectThrows(
+              IllegalArgumentException.class,
+              () ->
+                  MEMSEG_SCORER.getRandomVectorScorer(
+                      vectors.similarity, vectors.values, new float[65]));
+        }
+      }
+    }
+  }
+
+  public void testShortInputIsRejected() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testShortInput"))) {
+      try (Vectors vectors =
+          new Vectors(
+              dir, ScalarEncoding.UNSIGNED_BYTE, 
VectorSimilarityFunction.DOT_PRODUCT, 16, 4)) {
+        // claim one record more than the slice holds
+        QuantizedByteVectorValues values = vectors.values(vectors.size + 1);
+        expectThrows(
+            IllegalArgumentException.class,
+            () -> MEMSEG_SCORER.getRandomVectorScorer(vectors.similarity, 
values, new float[16]));
+      }
+    }
+  }
+
+  public void testScoringOrdinalMustBeSet() throws IOException {
+    try (Directory dir = new 
MMapDirectory(createTempDir("testOrdinalNotSet"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        try (Vectors vectors =
+            new Vectors(dir, encoding, VectorSimilarityFunction.DOT_PRODUCT, 
32, 3)) {
+          UpdateableRandomVectorScorer scorer = 
vectors.supplier(MEMSEG_SCORER).scorer();
+          expectThrows(IllegalStateException.class, () -> scorer.score(0));
+          expectThrows(
+              IllegalStateException.class, () -> scorer.bulkScore(new int[] 
{0}, new float[1], 1));
+        }
+      }
+    }
+  }
+
+  /** Values without records have nothing to score, but a query scorer can 
still be made. */
+  public void testNoVectors() throws IOException {
+    try (Directory dir = new MMapDirectory(createTempDir("testNoVectors"))) {
+      try (Vectors vectors =
+          new Vectors(
+              dir,
+              RandomPicks.randomFrom(random(), ScalarEncoding.values()),
+              VectorSimilarityFunction.DOT_PRODUCT,
+              random().nextInt(1, 100),
+              1)) {
+        RandomVectorScorer scorer =
+            MEMSEG_SCORER.getRandomVectorScorer(
+                vectors.similarity, vectors.values(0), vectors.randomQuery());
+        assertTrue(scorer.getClass().getName().contains("MemorySegment"));
+        assertEquals(Float.NEGATIVE_INFINITY, scorer.bulkScore(new int[0], new 
float[0], 0), 0f);
+        expectThrows(IllegalArgumentException.class, () -> scorer.score(0));
+      }
+    }
+  }
+
+  /** Copies of a supplier do not share scoring state. */
+  public void testCopiesAcrossThreads() throws Exception {
+    try (Directory dir = new MMapDirectory(createTempDir("testCopies"))) {
+      for (ScalarEncoding encoding : ScalarEncoding.values()) {
+        try (Vectors vectors =
+            new Vectors(
+                dir,
+                encoding,
+                RandomPicks.randomFrom(random(), 
VectorSimilarityFunction.values()),
+                random().nextInt(1, 300),
+                4)) {
+          RandomVectorScorerSupplier expected = 
vectors.supplier(DEFAULT_SCORER);
+          RandomVectorScorerSupplier supplier = 
vectors.supplier(MEMSEG_SCORER);
+          List<Callable<Optional<Throwable>>> tasks =
+              List.of(
+                  new AssertingScoreCallable(expected.copy(), supplier.copy(), 
0, 1),
+                  new AssertingScoreCallable(expected.copy(), supplier.copy(), 
2, 3),
+                  new AssertingScoreCallable(expected.copy(), supplier.copy(), 
1, 1));
+          var executor = Executors.newFixedThreadPool(3, new 
NamedThreadFactory("copiesThreads"));
+          var results = executor.invokeAll(tasks);
+          executor.shutdown();
+          assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));
+          for (var result : results) {
+            assertTrue("Unexpected exception " + result.get(), 
result.get().isEmpty());
+          }
+        }
+      }
+    }
+  }
+
+  private record AssertingScoreCallable(
+      RandomVectorScorerSupplier expectedSupplier,
+      RandomVectorScorerSupplier supplier,
+      int target,
+      int ord)
+      implements Callable<Optional<Throwable>> {
+    @Override
+    public Optional<Throwable> call() throws Exception {
+      UpdateableRandomVectorScorer expected = expectedSupplier.scorer();
+      expected.setScoringOrdinal(target);
+      UpdateableRandomVectorScorer scorer = supplier.scorer();
+      scorer.setScoringOrdinal(target);
+      try {
+        int[] nodes = {ord, 0, 1, 2, 3, ord};
+        float[] expectedScores = new float[nodes.length];
+        float[] scores = new float[nodes.length];
+        for (int i = 0; i < 100; i++) {
+          assertEquals(expected.score(ord), scorer.score(ord), 0f);
+          assertEquals(
+              expected.bulkScore(nodes, expectedScores, nodes.length),
+              scorer.bulkScore(nodes, scores, nodes.length),
+              0f);
+          assertArrayEquals(expectedScores, scores, 0f);
+        }
+      } catch (Throwable t) {
+        return Optional.of(t);
+      }
+      return Optional.empty();
+    }
+  }
+
+  /** Compares every scoring path of the two scorers, exactly. */
+  private void assertSameScores(Vectors vectors, boolean expectOffHeap) throws 
IOException {
+    // float and float16 queries
+    for (int q = 0; q < 2; q++) {
+      float[] query = vectors.randomQuery();
+      RandomVectorScorer expected =
+          DEFAULT_SCORER.getRandomVectorScorer(vectors.similarity, 
vectors.values, query.clone());
+      RandomVectorScorer scorer =
+          MEMSEG_SCORER.getRandomVectorScorer(vectors.similarity, 
vectors.values, query.clone());
+      assertEquals(expectOffHeap, 
scorer.getClass().getName().contains("MemorySegment"));
+      assertSameScores(vectors + " float query", expected, scorer, 
vectors.size);
+      short[] query16 = new short[query.length];
+      for (int i = 0; i < query.length; i++) {
+        query16[i] = Float.floatToFloat16(query[i]);
+      }
+      expected = DEFAULT_SCORER.getRandomVectorScorer(vectors.similarity, 
vectors.values, query16);
+      scorer = MEMSEG_SCORER.getRandomVectorScorer(vectors.similarity, 
vectors.values, query16);
+      assertSameScores(vectors + " float16 query", expected, scorer, 
vectors.size);
+    }
+    // vectors as queries, as when building a graph; also through a copy of 
the supplier
+    UpdateableRandomVectorScorer expected = 
vectors.supplier(DEFAULT_SCORER).scorer();
+    RandomVectorScorerSupplier supplier = vectors.supplier(MEMSEG_SCORER);
+    UpdateableRandomVectorScorer scorer =
+        random().nextBoolean() ? supplier.scorer() : supplier.copy().scorer();
+    assertEquals(expectOffHeap, 
scorer.getClass().getName().contains("MemorySegment"));
+    for (int q = 0; q < 2; q++) {
+      int target = random().nextInt(vectors.size);
+      expected.setScoringOrdinal(target);
+      scorer.setScoringOrdinal(target);
+      assertSameScores(vectors + " ordinal " + target, expected, scorer, 
vectors.size);
+    }
+  }
+
+  private static void assertSameScores(
+      String context, RandomVectorScorer expected, RandomVectorScorer scorer, 
int size)
+      throws IOException {
+    for (int ord = 0; ord < size; ord++) {
+      assertEquals(context + " ord " + ord, expected.score(ord), 
scorer.score(ord), 0f);
+    }
+    // batches of every size up to a neighbor list, with repeated ordinals, 
and a batch shorter
+    // than its arrays
+    for (int numNodes = 0; numNodes <= 13; numNodes++) {
+      assertSameBulkScores(context, expected, scorer, size, numNodes);
+    }
+    assertSameBulkScores(context, expected, scorer, size, 64 + 
random().nextInt(4));
+  }
+
+  private static void assertSameBulkScores(
+      String context,
+      RandomVectorScorer expected,
+      RandomVectorScorer scorer,
+      int size,
+      int numNodes)
+      throws IOException {
+    int[] nodes = new int[numNodes + random().nextInt(3)];
+    for (int i = 0; i < nodes.length; i++) {
+      nodes[i] = random().nextInt(size);
+    }
+    float[] expectedScores = new float[nodes.length];
+    float[] scores = new float[nodes.length];
+    float expectedMax = expected.bulkScore(nodes, expectedScores, numNodes);
+    float max = scorer.bulkScore(nodes, scores, numNodes);
+    assertEquals(context, expectedMax, max, 0f);
+    for (int i = 0; i < numNodes; i++) {
+      assertEquals(context + " node " + i + " of " + numNodes, 
expectedScores[i], scores[i], 0f);
+    }
+  }
+
+  /** Quantized vectors written like the Lucene104 format writes them. */
+  private static final class Vectors implements Closeable {

Review Comment:
   Also the style of this class is ... kind of unfamiliar. I guess it's OK, but 
it doesn't look like anything anyone I know would have written!



##########
lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene104MemorySegmentScalarQuantizedVectorScorer.java:
##########
@@ -0,0 +1,443 @@
+/*
+ * 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) {
+      QuantizedVectorField quantizedVectorField = QuantizedVectorField.of(qv, 
similarityFunction);
+      if (quantizedVectorField != null) {
+        return new OffHeapScorerSupplier(quantizedVectorField, qv, qv);
+      }
+    }
+    return super.getRandomVectorScorerSupplier(similarityFunction, 
vectorValues);
+  }
+
+  @Override
+  public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
+      VectorSimilarityFunction similarityFunction,
+      QuantizedByteVectorValues scoringVectors,
+      QuantizedByteVectorValues targetVectors)
+      throws IOException {
+    if (targetVectors.getScalarEncoding().isAsymmetric()) {
+      QuantizedVectorField quantizedVectorField =
+          QuantizedVectorField.of(targetVectors, similarityFunction);
+      if (quantizedVectorField != null) {
+        return new OffHeapScorerSupplier(quantizedVectorField, targetVectors, 
scoringVectors);
+      }
+    }
+    return super.getRandomVectorScorerSupplier(similarityFunction, 
scoringVectors, targetVectors);
+  }
+
+  @Override
+  protected RandomVectorScorer getVectorScorer(
+      VectorSimilarityFunction similarityFunction,
+      QuantizedByteVectorValues qv,
+      byte[] quantizedQuery,
+      QuantizationResult queryCorrections)
+      throws IOException {
+    QuantizedVectorField quantizedVectorField = QuantizedVectorField.of(qv, 
similarityFunction);
+    if (quantizedVectorField != null) {
+      return ScorerBase.create(quantizedVectorField, qv, quantizedQuery, 
queryCorrections);
+    }
+    return super.getVectorScorer(similarityFunction, qv, quantizedQuery, 
queryCorrections);
+  }
+
+  /**
+   * Represent quantized vectors in a single field. {@code dataSeg} contains 
the vectors laid out
+   * serially as entries, each entry consists of quantized bytes followed by 
corrective terms.
+   */
+  private record QuantizedVectorField(
+      MemorySegment dataSeg,
+      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);
+
+    static QuantizedVectorField 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");

Review Comment:
   should this be a `CorruptIndexException`?



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

Reply via email to