Skip to content

Apache Lucene open-source search software

Use native vectorization in Lucene (#15508)

Shubham Chaudhary50dac9063104
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 935ecd655e7..8394c7c5928 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -68,6 +68,8 @@ New Features
* GITHUB#14178: Add a Faiss-based vector format in the sandbox module. (Kaival Parikh)
+* GITHUB#15508: Use native vectorization in Lucene. (Ankur Goel, Shubham Chaudhary, Dawid Weiss)
+
Improvements
---------------------
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorUtilBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorUtilBenchmark.java
index 4c8253fdab9..35e0b81e345 100644
--- a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorUtilBenchmark.java
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorUtilBenchmark.java
@@ -106,6 +106,13 @@ public class VectorUtilBenchmark {
}
}
+ @Benchmark
+ @Fork(
+ jvmArgsPrepend = {"--add-modules=jdk.incubator.vector", "-Dlucene.useNativeDotProduct=true"})
+ public int dot8sNative() {
+ return VectorUtil.dotProduct(bytesA, bytesB);
+ }
+
@Benchmark
public float binaryCosineScalar() {
return VectorUtil.cosine(bytesA, bytesB);
diff --git a/lucene/core/src/java/module-info.java b/lucene/core/src/java/module-info.java
index 9e2acc3caac..1358b9fe068 100644
--- a/lucene/core/src/java/module-info.java
+++ b/lucene/core/src/java/module-info.java
@@ -74,6 +74,8 @@ module org.apache.lucene.core {
exports org.apache.lucene.util.quantization;
exports org.apache.lucene.codecs.hnsw;
+ exports org.apache.lucene.internal.vectorization to
+ org.apache.lucene.benchmark.jmh;
provides org.apache.lucene.analysis.TokenizerFactory with
org.apache.lucene.analysis.standard.StandardTokenizerFactory;
diff --git a/lucene/core/src/java/org/apache/lucene/internal/vectorization/VectorizationProvider.java b/lucene/core/src/java/org/apache/lucene/internal/vectorization/VectorizationProvider.java
index cf9c56c5977..1e429475af4 100644
--- a/lucene/core/src/java/org/apache/lucene/internal/vectorization/VectorizationProvider.java
+++ b/lucene/core/src/java/org/apache/lucene/internal/vectorization/VectorizationProvider.java
@@ -157,31 +157,11 @@ public abstract class VectorizationProvider {
return new DefaultVectorizationProvider();
}
}
- try {
- // we use method handles with lookup, so we do not need to deal with setAccessible as we
- // have private access through the lookup:
- final var lookup = MethodHandles.lookup();
- final var cls =
- lookup.findClass(
- "org.apache.lucene.internal.vectorization.PanamaVectorizationProvider");
- final var constr = lookup.findConstructor(cls, MethodType.methodType(void.class));
- try {
- return (VectorizationProvider) constr.invoke();
- } catch (UnsupportedOperationException uoe) {
- // not supported because preferred vector size too small or similar
- LOG.warning("Java vector incubator API was not enabled. " + uoe.getMessage());
- return new DefaultVectorizationProvider();
- } catch (RuntimeException | Error e) {
- throw e;
- } catch (Throwable th) {
- throw new AssertionError(th);
- }
- } catch (NoSuchMethodException | IllegalAccessException e) {
- throw new LinkageError(
- "PanamaVectorizationProvider is missing correctly typed constructor", e);
- } catch (ClassNotFoundException cnfe) {
- throw new LinkageError("PanamaVectorizationProvider is missing in Lucene JAR file", cnfe);
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ return lookup("NativeVectorizationProvider");
}
+
+ return lookup("PanamaVectorizationProvider");
} else {
LOG.warning(
"You are running with unsupported Java "
@@ -191,6 +171,31 @@ public abstract class VectorizationProvider {
return new DefaultVectorizationProvider();
}
+ static VectorizationProvider lookup(String className) {
+ try {
+ // we use method handles with lookup, so we do not need to deal with setAccessible as we
+ // have private access through the lookup:
+ final var lookup = MethodHandles.lookup();
+ final var cls = lookup.findClass("org.apache.lucene.internal.vectorization." + className);
+ final var constr = lookup.findConstructor(cls, MethodType.methodType(void.class));
+ try {
+ return (VectorizationProvider) constr.invoke();
+ } catch (UnsupportedOperationException uoe) {
+ // not supported because preferred vector size too small or similar
+ LOG.warning("Java vector incubator API was not enabled. " + uoe.getMessage());
+ return new DefaultVectorizationProvider();
+ } catch (RuntimeException | Error e) {
+ throw e;
+ } catch (Throwable th) {
+ throw new AssertionError(th);
+ }
+ } catch (NoSuchMethodException | IllegalAccessException e) {
+ throw new LinkageError(className + " is missing correctly typed constructor", e);
+ } catch (ClassNotFoundException cnfe) {
+ throw new LinkageError(className + " is missing in Lucene JAR file", cnfe);
+ }
+ }
+
/**
* Looks up the vector module from Lucene's {@link ModuleLayer} or the root layer (if unnamed).
*/
@@ -203,6 +208,7 @@ public abstract class VectorizationProvider {
// add all possible callers here as FQCN:
private static final Set<String> VALID_CALLERS =
Set.of(
+ "org.apache.lucene.benchmark.jmh.VectorUtilBenchmark",
"org.apache.lucene.codecs.hnsw.FlatVectorScorerUtil",
"org.apache.lucene.util.VectorUtil",
"org.apache.lucene.codecs.lucene104.Lucene104PostingsReader",
diff --git a/lucene/core/src/java/org/apache/lucene/util/Constants.java b/lucene/core/src/java/org/apache/lucene/util/Constants.java
index 9441685ff56..a8aa066b247 100644
--- a/lucene/core/src/java/org/apache/lucene/util/Constants.java
+++ b/lucene/core/src/java/org/apache/lucene/util/Constants.java
@@ -105,6 +105,18 @@ public final class Constants {
/** true iff we know VFMA has faster throughput than separate vmul/vadd. */
public static final boolean HAS_FAST_VECTOR_FMA = hasFastVectorFMA();
+ public static final boolean NATIVE_DOT_PRODUCT_ENABLED = enableNativeDotProduct();
+
+ private static boolean enableNativeDotProduct() {
+ return Boolean.parseBoolean(getSysProp("lucene.useNativeDotProduct", "false"));
+ }
+
+ public static final boolean NATIVE_STRICT_MODE = hasNativeStrictModeOn();
+
+ private static boolean hasNativeStrictModeOn() {
+ return Boolean.parseBoolean(getSysProp("lucene.useNativeStrict", "false"));
+ }
+
/** true iff we know FMA has faster throughput than separate mul/add. */
public static final boolean HAS_FAST_SCALAR_FMA = hasFastScalarFMA();
diff --git a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorer.java b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorer.java
index a8799c25a30..c76a10c5fca 100644
--- a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorer.java
+++ b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorer.java
@@ -25,6 +25,7 @@ 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.Constants;
import org.apache.lucene.util.hnsw.RandomVectorScorer;
abstract sealed class Lucene99MemorySegmentByteVectorScorer
@@ -98,7 +99,12 @@ abstract sealed class Lucene99MemorySegmentByteVectorScorer
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
- float raw = PanamaVectorUtilSupport.cosine(query, getSegment(node));
+ float raw;
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ raw = NativeVectorUtilSupport.cosine(query, getSegment(node));
+ } else {
+ raw = PanamaVectorUtilSupport.cosine(query, getSegment(node));
+ }
return (1 + raw) / 2;
}
}
@@ -112,7 +118,12 @@ abstract sealed class Lucene99MemorySegmentByteVectorScorer
public float score(int node) throws IOException {
checkOrdinal(node);
// divide by 2 * 2^14 (maximum absolute value of product of 2 signed bytes) * len
- float raw = PanamaVectorUtilSupport.dotProduct(query, getSegment(node));
+ float raw;
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ raw = NativeVectorUtilSupport.dotProduct(query, getSegment(node));
+ } else {
+ raw = PanamaVectorUtilSupport.dotProduct(query, getSegment(node));
+ }
return 0.5f + raw / (float) (query.length * (1 << 15));
}
}
@@ -125,7 +136,12 @@ abstract sealed class Lucene99MemorySegmentByteVectorScorer
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
- float raw = PanamaVectorUtilSupport.squareDistance(query, getSegment(node));
+ float raw;
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ raw = NativeVectorUtilSupport.squareDistance(query, getSegment(node));
+ } else {
+ raw = PanamaVectorUtilSupport.squareDistance(query, getSegment(node));
+ }
return 1 / (1f + raw);
}
}
@@ -138,7 +154,12 @@ abstract sealed class Lucene99MemorySegmentByteVectorScorer
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
- float raw = PanamaVectorUtilSupport.dotProduct(query, getSegment(node));
+ float raw;
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ raw = NativeVectorUtilSupport.dotProduct(query, getSegment(node));
+ } else {
+ raw = PanamaVectorUtilSupport.dotProduct(query, getSegment(node));
+ }
if (raw < 0) {
return 1 / (1 + -1 * raw);
}
diff --git a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorerSupplier.java b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorerSupplier.java
index 74b31e1bf0c..cf772eff483 100644
--- a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorerSupplier.java
+++ b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentByteVectorScorerSupplier.java
@@ -25,6 +25,7 @@ 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.Constants;
import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
import org.apache.lucene.util.hnsw.UpdateableRandomVectorScorer;
@@ -117,8 +118,12 @@ public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
- float raw =
- PanamaVectorUtilSupport.cosine(getFirstSegment(queryOrd), getSecondSegment(node));
+ float raw;
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ raw = NativeVectorUtilSupport.cosine(getFirstSegment(queryOrd), getSecondSegment(node));
+ } else {
+ raw = PanamaVectorUtilSupport.cosine(getFirstSegment(queryOrd), getSecondSegment(node));
+ }
return (1 + raw) / 2;
}
@@ -151,8 +156,16 @@ public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
public float score(int node) throws IOException {
checkOrdinal(node);
// divide by 2 * 2^14 (maximum absolute value of product of 2 signed bytes) * len
- float raw =
- PanamaVectorUtilSupport.dotProduct(getFirstSegment(queryOrd), getSecondSegment(node));
+ float raw;
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ raw =
+ NativeVectorUtilSupport.dotProduct(
+ getFirstSegment(queryOrd), getSecondSegment(node));
+ } else {
+ raw =
+ PanamaVectorUtilSupport.dotProduct(
+ getFirstSegment(queryOrd), getSecondSegment(node));
+ }
return 0.5f + raw / (float) (values.dimension() * (1 << 15));
}
@@ -184,9 +197,16 @@ public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
- float raw =
- PanamaVectorUtilSupport.squareDistance(
- getFirstSegment(queryOrd), getSecondSegment(node));
+ float raw;
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ raw =
+ NativeVectorUtilSupport.squareDistance(
+ getFirstSegment(queryOrd), getSecondSegment(node));
+ } else {
+ raw =
+ PanamaVectorUtilSupport.squareDistance(
+ getFirstSegment(queryOrd), getSecondSegment(node));
+ }
return 1 / (1f + raw);
}
@@ -218,8 +238,16 @@ public abstract sealed class Lucene99MemorySegmentByteVectorScorerSupplier
@Override
public float score(int node) throws IOException {
checkOrdinal(node);
- float raw =
- PanamaVectorUtilSupport.dotProduct(getFirstSegment(queryOrd), getSecondSegment(node));
+ float raw;
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ raw =
+ NativeVectorUtilSupport.dotProduct(
+ getFirstSegment(queryOrd), getSecondSegment(node));
+ } else {
+ raw =
+ PanamaVectorUtilSupport.dotProduct(
+ getFirstSegment(queryOrd), getSecondSegment(node));
+ }
if (raw < 0) {
return 1 / (1 + -1 * raw);
}
diff --git a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentScalarQuantizedVectorScorer.java b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentScalarQuantizedVectorScorer.java
index 12b95f6c2ff..ad97360fee4 100644
--- a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentScalarQuantizedVectorScorer.java
+++ b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentScalarQuantizedVectorScorer.java
@@ -29,6 +29,7 @@ import org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorScorer;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.store.MemorySegmentAccessInput;
+import org.apache.lucene.util.Constants;
import org.apache.lucene.util.FloatToFloatFunction;
import org.apache.lucene.util.VectorUtil;
import org.apache.lucene.util.hnsw.RandomVectorScorer;
@@ -63,6 +64,9 @@ class Lucene99MemorySegmentScalarQuantizedVectorScorer implements FlatVectorsSco
throws IOException {
if (vectorValues instanceof QuantizedByteVectorValues quantized
&& quantized.getSlice() instanceof MemorySegmentAccessInput input) {
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ return new NativeRandomVectorScorerImpl(similarityFunction, quantized, input, target);
+ }
return new RandomVectorScorerImpl(similarityFunction, quantized, input, target);
}
return DELEGATE.getRandomVectorScorer(similarityFunction, vectorValues, target);
@@ -199,7 +203,7 @@ class Lucene99MemorySegmentScalarQuantizedVectorScorer implements FlatVectorsSco
}
private static class RandomVectorScorerImpl extends RandomVectorScorerBase {
- private final byte[] targetBytes;
+ protected final byte[] targetBytes;
private final float queryOffset;
RandomVectorScorerImpl(
@@ -248,6 +252,46 @@ class Lucene99MemorySegmentScalarQuantizedVectorScorer implements FlatVectorsSco
}
}
+ private static class NativeRandomVectorScorerImpl extends RandomVectorScorerImpl {
+ NativeRandomVectorScorerImpl(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues values,
+ MemorySegmentAccessInput input,
+ float[] target) {
+ super(similarityFunction, values, input, target);
+ }
+
+ @Override
+ int euclidean(MemorySegment doc) {
+ return NativeVectorUtilSupport.uint8SquareDistance(targetBytes, doc);
+ }
+
+ @Override
+ int int4Euclidean(MemorySegment doc) {
+ return NativeVectorUtilSupport.int4SquareDistance(targetBytes, doc);
+ }
+
+ @Override
+ int compressedInt4Euclidean(MemorySegment doc) {
+ return NativeVectorUtilSupport.int4SquareDistanceSinglePacked(targetBytes, doc);
+ }
+
+ @Override
+ int dotProduct(MemorySegment doc) {
+ return NativeVectorUtilSupport.uint8DotProduct(targetBytes, doc);
+ }
+
+ @Override
+ int int4DotProduct(MemorySegment doc) {
+ return NativeVectorUtilSupport.int4DotProduct(targetBytes, doc);
+ }
+
+ @Override
+ int compressedInt4DotProduct(MemorySegment doc) {
+ return NativeVectorUtilSupport.int4DotProductSinglePacked(targetBytes, doc);
+ }
+ }
+
private record RandomVectorScorerSupplierImpl(
VectorSimilarityFunction similarityFunction,
QuantizedByteVectorValues values,
@@ -256,6 +300,9 @@ class Lucene99MemorySegmentScalarQuantizedVectorScorer implements FlatVectorsSco
@Override
public UpdateableRandomVectorScorer scorer() {
+ if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ return new NativeUpdateableRandomVectorScorerImpl(similarityFunction, values, input);
+ }
return new UpdateableRandomVectorScorerImpl(similarityFunction, values, input);
}
@@ -267,7 +314,7 @@ class Lucene99MemorySegmentScalarQuantizedVectorScorer implements FlatVectorsSco
private static class UpdateableRandomVectorScorerImpl extends RandomVectorScorerBase
implements UpdateableRandomVectorScorer {
- private MemorySegment query;
+ protected MemorySegment query;
private float queryOffset;
UpdateableRandomVectorScorerImpl(
@@ -320,4 +367,45 @@ class Lucene99MemorySegmentScalarQuantizedVectorScorer implements FlatVectorsSco
return PanamaVectorUtilSupport.int4DotProductBothPacked(query, doc);
}
}
+
+ private static class NativeUpdateableRandomVectorScorerImpl
+ extends UpdateableRandomVectorScorerImpl {
+
+ NativeUpdateableRandomVectorScorerImpl(
+ VectorSimilarityFunction similarityFunction,
+ QuantizedByteVectorValues values,
+ MemorySegmentAccessInput input) {
+ super(similarityFunction, values, input);
+ }
+
+ @Override
+ int euclidean(MemorySegment doc) {
+ return NativeVectorUtilSupport.uint8SquareDistance(query, doc);
+ }
+
+ @Override
+ int int4Euclidean(MemorySegment doc) {
+ return NativeVectorUtilSupport.int4SquareDistance(query, doc);
+ }
+
+ @Override
+ int compressedInt4Euclidean(MemorySegment doc) {
+ return NativeVectorUtilSupport.int4SquareDistanceBothPacked(query, doc);
+ }
+
+ @Override
+ int dotProduct(MemorySegment doc) {
+ return NativeVectorUtilSupport.uint8DotProduct(query, doc);
+ }
+
+ @Override
+ int int4DotProduct(MemorySegment doc) {
+ return NativeVectorUtilSupport.int4DotProduct(query, doc);
+ }
+
+ @Override
+ int compressedInt4DotProduct(MemorySegment doc) {
+ return NativeVectorUtilSupport.int4DotProductBothPacked(query, doc);
+ }
+ }
}
diff --git a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/NativeVectorUtilSupport.java b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/NativeVectorUtilSupport.java
new file mode 100644
index 00000000000..32985c4996c
--- /dev/null
+++ b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/NativeVectorUtilSupport.java
@@ -0,0 +1,590 @@
+/*
+ * 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_DOUBLE;
+import static java.lang.foreign.ValueLayout.JAVA_FLOAT;
+import static java.lang.foreign.ValueLayout.JAVA_INT;
+import static java.lang.foreign.ValueLayout.JAVA_LONG;
+
+import java.lang.foreign.AddressLayout;
+import java.lang.foreign.FunctionDescriptor;
+import java.lang.foreign.Linker;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.SymbolLookup;
+import java.lang.foreign.ValueLayout;
+import java.lang.invoke.MethodHandle;
+import java.util.function.Supplier;
+import java.util.logging.Logger;
+import org.apache.lucene.util.Constants;
+
+/**
+ * VectorUtilSupport implementation that uses native bindings for optimized vector operations(using
+ * Foreign Function and Memory API (FFM)) if available(optional) or else fallback to
+ * PanamaVectorUtil implementations.
+ *
+ * <p>This class provides access to native C implementations of dot product operations from the
+ * loaded shared/dynamic library(.so|.dylib|.dll) which is generated from C code and linked at
+ * runtime. The native library contains multiple optimized implementations:
+ *
+ * <p>PanamaVectorUtilSupport#dotProduct use this Native C implementation for dot product
+ * calculation if system property <b>lucene.useNativeDotProduct=true</b> is passed it always tries
+ * to ensure binary is provided and required methods are implemented
+ *
+ * <p>It Uses <code>Linker.Option.critical(true)</code> for optimal performance by eliminating the
+ * overhead of ensuring MemorySegments are allocated off-heap before native calls.
+ */
+@SuppressWarnings("restricted")
+public final class NativeVectorUtilSupport implements VectorUtilSupport {
+
+ private final VectorUtilSupport delegateVectorUtilSupport;
+
+ public static final AddressLayout POINTER = ValueLayout.ADDRESS;
+
+ private static final Linker LINKER = Linker.nativeLinker();
+ private static final SymbolLookup SYMBOL_LOOKUP;
+
+ @SuppressWarnings("NonFinalStaticField")
+ private static boolean isLibraryLoaded;
+
+ // TODO: Make this dynamic?
+ public static final String NATIVE_VECTOR_LIBRARY_NAME = "dotProduct";
+
+ public NativeVectorUtilSupport(VectorUtilSupport vectorUtilSupport) {
+ this.delegateVectorUtilSupport = vectorUtilSupport;
+ }
+
+ static {
+ try {
+ // Attempt to load the library
+ System.loadLibrary(NATIVE_VECTOR_LIBRARY_NAME);
+ isLibraryLoaded = true; // If successful, set the flag to true
+ } catch (UnsatisfiedLinkError e) {
+ // If the library loading fails, set the flag to false
+ isLibraryLoaded = false;
+ Logger.getLogger(NativeVectorUtilSupport.class.getName())
+ .warning("No native library" + NATIVE_VECTOR_LIBRARY_NAME + " found : " + e.getMessage());
+ }
+ }
+
+ // Function descriptors
+ // (POINTER, POINTER, INT) -> INT
+ private static final FunctionDescriptor twoPointerIntToInt =
+ FunctionDescriptor.of(JAVA_INT, POINTER, POINTER, JAVA_INT);
+
+ // (POINTER, POINTER, INT) -> LONG
+ private static final FunctionDescriptor twoPointerIntToLong =
+ FunctionDescriptor.of(JAVA_LONG, POINTER, POINTER, JAVA_INT);
+
+ // (POINTER, POINTER, INT) -> FLOAT
+ private static final FunctionDescriptor twoPointerIntToFloat =
+ FunctionDescriptor.of(JAVA_FLOAT, POINTER, POINTER, JAVA_INT);
+
+ // (POINTER, POINTER, FLOAT, FLOAT, FLOAT, FLOAT, INT) -> FLOAT
+ private static final FunctionDescriptor minMaxScalarQuantizeDesc =
+ FunctionDescriptor.of(
+ JAVA_FLOAT, POINTER, POINTER, JAVA_FLOAT, JAVA_FLOAT, JAVA_FLOAT, JAVA_FLOAT, JAVA_INT);
+
+ // (POINTER, FLOAT, FLOAT, FLOAT, FLOAT, FLOAT, FLOAT, INT) -> FLOAT
+ private static final FunctionDescriptor recalculateOffsetDesc =
+ FunctionDescriptor.of(
+ JAVA_FLOAT,
+ POINTER,
+ JAVA_FLOAT,
+ JAVA_FLOAT,
+ JAVA_FLOAT,
+ JAVA_FLOAT,
+ JAVA_FLOAT,
+ JAVA_FLOAT,
+ JAVA_INT);
+
+ // (POINTER, POINTER, DOUBLE, INT) -> INT
+ private static final FunctionDescriptor filterByScoreDesc =
+ FunctionDescriptor.of(JAVA_INT, POINTER, POINTER, JAVA_DOUBLE, JAVA_INT);
+
+ // (POINTER, BYTE, INT) -> POINTER
+ private static final FunctionDescriptor l2normalizeDesc =
+ FunctionDescriptor.of(POINTER, POINTER, JAVA_BYTE, JAVA_INT);
+
+ // (POINTER, INT) -> void
+ private static final FunctionDescriptor expand8Desc =
+ FunctionDescriptor.ofVoid(POINTER, JAVA_INT);
+
+ // (POINTER, INT, INT, INT) -> INT
+ private static final FunctionDescriptor findNextGEQDesc =
+ FunctionDescriptor.of(JAVA_INT, POINTER, JAVA_INT, JAVA_INT, JAVA_INT);
+
+ // Method handles
+ private static final MethodHandle dotProduct$MH;
+ private static final MethodHandle squareDistance$MH;
+ private static final MethodHandle cosine$MH;
+ private static final MethodHandle dotProductFloat$MH;
+ private static final MethodHandle squareDistanceFloat$MH;
+ private static final MethodHandle cosineFloat$MH;
+ private static final MethodHandle int4SquareDistance$MH;
+ private static final MethodHandle int4SquareDistanceSinglePacked$MH;
+ private static final MethodHandle int4SquareDistanceBothPacked$MH;
+ private static final MethodHandle uint8SquareDistance$MH;
+ private static final MethodHandle uint8DotProduct$MH;
+ private static final MethodHandle int4DotProduct$MH;
+ private static final MethodHandle int4DotProductSinglePacked$MH;
+ private static final MethodHandle int4DotProductBothPacked$MH;
+ private static final MethodHandle int4BitDotProduct$MH;
+ private static final MethodHandle int4DibitDotProduct$MH;
+ private static final MethodHandle minMaxScalarQuantize$MH;
+ private static final MethodHandle recalculateScalarQuantizationOffset$MH;
+ private static final MethodHandle filterByScore$MH;
+ private static final MethodHandle l2normalize$MH;
+ private static final MethodHandle expand8$MH;
+ private static final MethodHandle findNextGEQ$MH;
+
+ public static boolean isLibraryLoaded() {
+ return isLibraryLoaded;
+ }
+
+ static {
+ if (isLibraryLoaded) {
+ SymbolLookup loaderLookup = SymbolLookup.loaderLookup();
+ SYMBOL_LOOKUP = name -> loaderLookup.find(name).or(() -> LINKER.defaultLookup().find(name));
+
+ // Each method handle with a unique native method name
+ dotProduct$MH = getMethodHandle("dotProduct", twoPointerIntToInt);
+ squareDistance$MH = getMethodHandle("squareDistance", twoPointerIntToInt);
+ cosine$MH = getMethodHandle("cosine", twoPointerIntToInt);
+ dotProductFloat$MH = getMethodHandle("dotProductFloat", twoPointerIntToFloat);
+ squareDistanceFloat$MH = getMethodHandle("squareDistanceFloat", twoPointerIntToFloat);
+ cosineFloat$MH = getMethodHandle("cosineFloat", twoPointerIntToFloat);
+ int4SquareDistance$MH = getMethodHandle("int4SquareDistance", twoPointerIntToInt);
+ int4SquareDistanceSinglePacked$MH =
+ getMethodHandle("int4SquareDistanceSinglePacked", twoPointerIntToInt);
+ int4SquareDistanceBothPacked$MH =
+ getMethodHandle("int4SquareDistanceBothPacked", twoPointerIntToInt);
+ uint8SquareDistance$MH = getMethodHandle("uint8SquareDistance", twoPointerIntToInt);
+ uint8DotProduct$MH = getMethodHandle("uint8DotProduct", twoPointerIntToInt);
+ int4DotProduct$MH = getMethodHandle("int4DotProduct", twoPointerIntToInt);
+ int4DotProductSinglePacked$MH =
+ getMethodHandle("int4DotProductSinglePacked", twoPointerIntToInt);
+ int4DotProductBothPacked$MH = getMethodHandle("int4DotProductBothPacked", twoPointerIntToInt);
+ int4BitDotProduct$MH = getMethodHandle("int4BitDotProduct", twoPointerIntToLong);
+ int4DibitDotProduct$MH = getMethodHandle("int4DibitDotProduct", twoPointerIntToLong);
+ minMaxScalarQuantize$MH = getMethodHandle("minMaxScalarQuantize", minMaxScalarQuantizeDesc);
+ recalculateScalarQuantizationOffset$MH =
+ getMethodHandle("recalculateScalarQuantizationOffset", recalculateOffsetDesc);
+ filterByScore$MH = getMethodHandle("filterByScore", filterByScoreDesc);
+ l2normalize$MH = getMethodHandle("l2normalize", l2normalizeDesc);
+ expand8$MH = getMethodHandle("expand8", expand8Desc);
+ findNextGEQ$MH = getMethodHandle("findNextGEQ", findNextGEQDesc);
+ } else if (Constants.NATIVE_DOT_PRODUCT_ENABLED) {
+ throw new RuntimeException("Native library dotProduct missing!");
+ } else {
+ SYMBOL_LOOKUP = null;
+ dotProduct$MH = null;
+ squareDistance$MH = null;
+ cosine$MH = null;
+ dotProductFloat$MH = null;
+ squareDistanceFloat$MH = null;
+ cosineFloat$MH = null;
+ int4SquareDistance$MH = null;
+ int4SquareDistanceSinglePacked$MH = null;
+ int4SquareDistanceBothPacked$MH = null;
+ uint8SquareDistance$MH = null;
+ uint8DotProduct$MH = null;
+ int4DotProduct$MH = null;
+ int4DotProductSinglePacked$MH = null;
+ int4DotProductBothPacked$MH = null;
+ int4BitDotProduct$MH = null;
+ int4DibitDotProduct$MH = null;
+ minMaxScalarQuantize$MH = null;
+ recalculateScalarQuantizationOffset$MH = null;
+ filterByScore$MH = null;
+ l2normalize$MH = null;
+ expand8$MH = null;
+ findNextGEQ$MH = null;
+ }
+ }
+
+ private static MethodHandle getMethodHandle(String methodName, FunctionDescriptor descriptor) {
+ MethodHandle mh =
+ SYMBOL_LOOKUP
+ .find(methodName)
+ .map(addr -> LINKER.downcallHandle(addr, descriptor, Linker.Option.critical(true)))
+ .orElse(null);
+ if (mh == null && Constants.NATIVE_STRICT_MODE) {
+ throw new RuntimeException("C code for " + methodName + " was not linked!");
+ }
+ return mh;
+ }
+
+ // Reusable invoke helpers for signatures used multiple times
+ private static int invokeIntMethodHandle(MethodHandle mh, MemorySegment a, MemorySegment b) {
+ try {
+ return (int) mh.invokeExact(a, b, (int) a.byteSize());
+ } catch (Throwable ex) {
+ throw new AssertionError("should not reach here", ex);
+ }
+ }
+
+ private static long invokeLongMethodHandle(MethodHandle mh, MemorySegment a, MemorySegment b) {
+ try {
+ return (long) mh.invokeExact(a, b, (int) a.byteSize());
+ } catch (Throwable ex) {
+ throw new AssertionError("should not reach here", ex);
+ }
+ }
+
+ private static float invokeFloatMethodHandle(MethodHandle mh, MemorySegment a, MemorySegment b) {
+ try {
+ return (float) mh.invokeExact(a, b, (int) a.byteSize());
+ } catch (Throwable ex) {
+ throw new AssertionError("should not reach here", ex);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T> T invokeOrDelegate(MethodHandle mh, Supplier<T> delegate, Object... args) {
+ if (mh != null) {
+ try {
+ return (T) mh.invokeExact(args);
+ } catch (Throwable ex) {
+ throw new AssertionError("should not reach here", ex);
+ }
+ }
+ return delegate.get();
+ }
+
+ public static float cosine(byte[] a, MemorySegment b) {
+ return (cosine$MH != null)
+ ? cosine(MemorySegment.ofArray(a), b)
+ : PanamaVectorUtilSupport.cosine(a, b);
+ }
+
+ public static float cosine(MemorySegment a, MemorySegment b) {
+ return (cosine$MH != null)
+ ? invokeIntMethodHandle(cosine$MH, a, b)
+ : PanamaVectorUtilSupport.cosine(a, b);
+ }
+
+ public static int dotProduct(byte[] a, MemorySegment b) {
+ return (dotProduct$MH != null)
+ ? dotProduct(MemorySegment.ofArray(a), b)
+ : PanamaVectorUtilSupport.dotProduct(a, b);
+ }
+
+ public static int dotProduct(MemorySegment a, MemorySegment b) {
+ return (dotProduct$MH != null)
+ ? invokeIntMethodHandle(dotProduct$MH, a, b)
+ : PanamaVectorUtilSupport.dotProduct(a, b);
+ }
+
+ public static int squareDistance(byte[] a, MemorySegment b) {
+ return (squareDistance$MH != null)
+ ? squareDistance(MemorySegment.ofArray(a), b)
+ : PanamaVectorUtilSupport.squareDistance(a, b);
+ }
+
+ public static int squareDistance(MemorySegment a, MemorySegment b) {
+ return (squareDistance$MH != null)
+ ? invokeIntMethodHandle(squareDistance$MH, a, b)
+ : PanamaVectorUtilSupport.squareDistance(a, b);
+ }
+
+ public static int int4SquareDistance(byte[] a, MemorySegment b) {
+ return (int4SquareDistance$MH != null)
+ ? int4SquareDistance(MemorySegment.ofArray(a), b)
+ : PanamaVectorUtilSupport.int4SquareDistance(a, b);
+ }
+
+ public static int int4SquareDistance(MemorySegment a, MemorySegment b) {
+ return (int4SquareDistance$MH != null)
+ ? invokeIntMethodHandle(int4SquareDistance$MH, a, b)
+ : PanamaVectorUtilSupport.int4SquareDistance(a, b);
+ }
+
+ public static int int4SquareDistanceSinglePacked(byte[] a, MemorySegment b) {
+ return (int4SquareDistanceSinglePacked$MH != null)
+ ? invokeIntMethodHandle(int4SquareDistanceSinglePacked$MH, MemorySegment.ofArray(a), b)
+ : PanamaVectorUtilSupport.int4SquareDistanceSinglePacked(a, b);
+ }
+
+ public static int uint8SquareDistance(byte[] a, MemorySegment b) {
+ return (uint8SquareDistance$MH != null)
+ ? uint8SquareDistance(MemorySegment.ofArray(a), b)
+ : PanamaVectorUtilSupport.uint8SquareDistance(a, b);
+ }
+
+ public static int uint8SquareDistance(MemorySegment a, MemorySegment b) {
+ return (uint8SquareDistance$MH != null)
+ ? invokeIntMethodHandle(uint8SquareDistance$MH, a, b)
+ : PanamaVectorUtilSupport.uint8SquareDistance(a, b);
+ }
+
+ public static int uint8DotProduct(byte[] a, MemorySegment b) {
+ return (uint8DotProduct$MH != null)
+ ? uint8DotProduct(MemorySegment.ofArray(a), b)
+ : PanamaVectorUtilSupport.uint8DotProduct(a, b);
+ }
+
+ public static int uint8DotProduct(MemorySegment a, MemorySegment b) {
+ return (uint8DotProduct$MH != null)
+ ? invokeIntMethodHandle(uint8DotProduct$MH, a, b)
+ : PanamaVectorUtilSupport.uint8DotProduct(a, b);
+ }
+
+ public static int int4DotProduct(byte[] a, MemorySegment b) {
+ return (int4DotProduct$MH != null)
+ ? int4DotProduct(MemorySegment.ofArray(a), b)
+ : PanamaVectorUtilSupport.int4DotProduct(a, b);
+ }
+
+ public static int int4DotProduct(MemorySegment a, MemorySegment b) {
+ return (int4DotProduct$MH != null)
+ ? invokeIntMethodHandle(int4DotProduct$MH, a, b)
+ : PanamaVectorUtilSupport.int4DotProduct(a, b);
+ }
+
+ public static int int4DotProductSinglePacked(byte[] unpacked, MemorySegment packed) {
+ return (int4DotProductSinglePacked$MH != null)
+ ? invokeIntMethodHandle(
+ int4DotProductSinglePacked$MH, MemorySegment.ofArray(unpacked), packed)
+ : PanamaVectorUtilSupport.int4DotProductSinglePacked(unpacked, packed);
+ }
+
+ public static int int4SquareDistanceBothPacked(MemorySegment a, MemorySegment b) {
+ return (int4SquareDistanceBothPacked$MH != null)
+ ? invokeIntMethodHandle(int4SquareDistanceBothPacked$MH, a, b)
+ : PanamaVectorUtilSupport.int4SquareDistanceBothPacked(a, b);
+ }
+
+ public static int int4DotProductBothPacked(MemorySegment a, MemorySegment b) {
+ return (int4DotProductBothPacked$MH != null)
+ ? invokeIntMethodHandle(int4DotProductBothPacked$MH, a, b)
+ : PanamaVectorUtilSupport.int4DotProductBothPacked(a, b);
+ }
+
+ @Override
+ public float dotProduct(float[] a, float[] b) {
+ return (dotProductFloat$MH != null)
+ ? invokeFloatMethodHandle(
+ dotProductFloat$MH, MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.dotProduct(a, b);
+ }
+
+ @Override
+ public float cosine(float[] v1, float[] v2) {
+ return (cosineFloat$MH != null)
+ ? invokeFloatMethodHandle(
+ cosineFloat$MH, MemorySegment.ofArray(v1), MemorySegment.ofArray(v2))
+ : delegateVectorUtilSupport.cosine(v1, v2);
+ }
+
+ @Override
+ public float squareDistance(float[] a, float[] b) {
+ return (squareDistanceFloat$MH != null)
+ ? invokeFloatMethodHandle(
+ squareDistanceFloat$MH, MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.squareDistance(a, b);
+ }
+
+ @Override
+ public int dotProduct(byte[] a, byte[] b) {
+ return (dotProduct$MH != null)
+ ? dotProduct(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.dotProduct(a, b);
+ }
+
+ @Override
+ public int int4DotProduct(byte[] a, byte[] b) {
+ return (int4DotProduct$MH != null)
+ ? int4DotProduct(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.int4DotProduct(a, b);
+ }
+
+ @Override
+ public int int4DotProductSinglePacked(byte[] unpacked, byte[] packed) {
+ return int4DotProductSinglePacked$MH != null
+ ? int4DotProductSinglePacked(unpacked, MemorySegment.ofArray(packed))
+ : delegateVectorUtilSupport.int4DotProductSinglePacked(unpacked, packed);
+ }
+
+ @Override
+ public int int4DotProductBothPacked(byte[] a, byte[] b) {
+ return (int4DotProductBothPacked$MH != null)
+ ? int4DotProductBothPacked(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.int4DotProductBothPacked(a, b);
+ }
+
+ @Override
+ public int uint8DotProduct(byte[] a, byte[] b) {
+ return (uint8DotProduct$MH != null)
+ ? uint8DotProduct(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.uint8DotProduct(a, b);
+ }
+
+ @Override
+ public float cosine(byte[] a, byte[] b) {
+ return (cosine$MH != null)
+ ? cosine(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.cosine(a, b);
+ }
+
+ @Override
+ public int squareDistance(byte[] a, byte[] b) {
+ return (squareDistance$MH != null)
+ ? squareDistance(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.squareDistance(a, b);
+ }
+
+ @Override
+ public int int4SquareDistance(byte[] a, byte[] b) {
+ return (int4SquareDistance$MH != null)
+ ? int4SquareDistance(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.int4SquareDistance(a, b);
+ }
+
+ @Override
+ public int int4SquareDistanceSinglePacked(byte[] unpacked, byte[] packed) {
+ return (int4SquareDistanceSinglePacked$MH != null)
+ ? int4SquareDistanceSinglePacked(unpacked, MemorySegment.ofArray(packed))
+ : delegateVectorUtilSupport.int4SquareDistanceSinglePacked(unpacked, packed);
+ }
+
+ @Override
+ public int int4SquareDistanceBothPacked(byte[] a, byte[] b) {
+ return (int4SquareDistanceBothPacked$MH != null)
+ ? int4SquareDistanceBothPacked(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.int4SquareDistanceBothPacked(a, b);
+ }
+
+ @Override
+ public int uint8SquareDistance(byte[] a, byte[] b) {
+ return (uint8SquareDistance$MH != null)
+ ? uint8SquareDistance(MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ : delegateVectorUtilSupport.uint8SquareDistance(a, b);
+ }
+
+ @Override
+ public long int4BitDotProduct(byte[] int4Quantized, byte[] binaryQuantized) {
+ if (int4BitDotProduct$MH != null) {
+ return invokeLongMethodHandle(
+ int4BitDotProduct$MH,
+ MemorySegment.ofArray(int4Quantized),
+ MemorySegment.ofArray(binaryQuantized));
+ }
+ return delegateVectorUtilSupport.int4BitDotProduct(int4Quantized, binaryQuantized);
+ }
+
+ @Override
+ public long int4DibitDotProduct(byte[] int4Quantized, byte[] dibitQuantized) {
+ if (int4DibitDotProduct$MH != null) {
+ return invokeLongMethodHandle(
+ int4DibitDotProduct$MH,
+ MemorySegment.ofArray(int4Quantized),
+ MemorySegment.ofArray(dibitQuantized));
+ }
+ return delegateVectorUtilSupport.int4DibitDotProduct(int4Quantized, dibitQuantized);
+ }
+
+ @Override
+ public int findNextGEQ(int[] buffer, int target, int from, int to) {
+ return invokeOrDelegate(
+ findNextGEQ$MH,
+ () -> delegateVectorUtilSupport.findNextGEQ(buffer, target, from, to),
+ MemorySegment.ofArray(buffer),
+ target,
+ from,
+ to);
+ }
+
+ @Override
+ public float minMaxScalarQuantize(
+ float[] vector, byte[] dest, float scale, float alpha, float minQuantile, float maxQuantile) {
+ return invokeOrDelegate(
+ minMaxScalarQuantize$MH,
+ () ->
+ delegateVectorUtilSupport.minMaxScalarQuantize(
+ vector, dest, scale, alpha, minQuantile, maxQuantile),
+ MemorySegment.ofArray(vector),
+ MemorySegment.ofArray(dest),
+ scale,
+ alpha,
+ minQuantile,
+ maxQuantile,
+ vector.length);
+ }
+
+ @Override
+ public float recalculateScalarQuantizationOffset(
+ byte[] vector,
+ float oldAlpha,
+ float oldMinQuantile,
+ float scale,
+ float alpha,
+ float minQuantile,
+ float maxQuantile) {
+ return invokeOrDelegate(
+ recalculateScalarQuantizationOffset$MH,
+ () ->
+ delegateVectorUtilSupport.recalculateScalarQuantizationOffset(
+ vector, oldAlpha, oldMinQuantile, scale, alpha, minQuantile, maxQuantile),
+ MemorySegment.ofArray(vector),
+ oldAlpha,
+ oldMinQuantile,
+ scale,
+ alpha,
+ minQuantile,
+ maxQuantile,
+ vector.length);
+ }
+
+ @Override
+ public int filterByScore(
+ int[] docBuffer, double[] scoreBuffer, double minScoreInclusive, int upTo) {
+ return invokeOrDelegate(
+ filterByScore$MH,
+ () ->
+ delegateVectorUtilSupport.filterByScore(
+ docBuffer, scoreBuffer, minScoreInclusive, upTo),
+ MemorySegment.ofArray(docBuffer),
+ MemorySegment.ofArray(scoreBuffer),
+ minScoreInclusive,
+ upTo);
+ }
+
+ @Override
+ public float[] l2normalize(float[] v, boolean throwOnZero) {
+ invokeOrDelegate(
+ l2normalize$MH,
+ () -> delegateVectorUtilSupport.l2normalize(v, throwOnZero),
+ MemorySegment.ofArray(v),
+ (byte) (throwOnZero ? 1 : 0),
+ v.length);
+ return v;
+ }
+
+ @Override
+ public void expand8(int[] arr) {
+ invokeOrDelegate(
+ expand8$MH,
+ () -> {
+ delegateVectorUtilSupport.expand8(arr);
+ return null;
+ },
+ MemorySegment.ofArray(arr),
+ arr.length);
+ }
+}
diff --git a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/NativeVectorizationProvider.java b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/NativeVectorizationProvider.java
new file mode 100644
index 00000000000..9289b07cd63
--- /dev/null
+++ b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/NativeVectorizationProvider.java
@@ -0,0 +1,79 @@
+/*
+ * 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.util.Locale;
+import java.util.logging.Logger;
+import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.Constants;
+import org.apache.lucene.util.SuppressForbidden;
+
+/** Native provider returning native implementations which delegates to Panama implementation. */
+public final class NativeVectorizationProvider extends VectorizationProvider {
+
+ private final VectorizationProvider delegateVectorUtilProvider =
+ new PanamaVectorizationProvider();
+
+ private final VectorUtilSupport vectorUtilSupport;
+
+ NativeVectorizationProvider() {
+ vectorUtilSupport =
+ new NativeVectorUtilSupport(delegateVectorUtilProvider.getVectorUtilSupport());
+ logIncubatorSetup();
+ }
+
+ @SuppressForbidden(reason = "We log at info level here, it's fine.")
+ private void logIncubatorSetup() {
+ var log = Logger.getLogger(getClass().getName());
+ log.info(
+ String.format(
+ Locale.ENGLISH,
+ "Native vectorization enabled; uses preferredBitSize=%d%s%s; strict mode=%s; native library loaded=%s;",
+ PanamaVectorConstants.PREFERRED_VECTOR_BITSIZE,
+ Constants.HAS_FAST_VECTOR_FMA ? "; FMA enabled" : "",
+ VectorizationProvider.TESTS_VECTOR_SIZE.isPresent() ? "; testMode enabled" : "",
+ Constants.NATIVE_STRICT_MODE ? "true" : "false",
+ NativeVectorUtilSupport.isLibraryLoaded()
+ ? "true, using " + getClass().getSimpleName()
+ : "false, switching to "
+ + delegateVectorUtilProvider.getClass().getSimpleName()
+ + "as fallback"));
+ }
+
+ @Override
+ public VectorUtilSupport getVectorUtilSupport() {
+ return vectorUtilSupport;
+ }
+
+ @Override
+ public FlatVectorsScorer getLucene99FlatVectorsScorer() {
+ return delegateVectorUtilProvider.getLucene99FlatVectorsScorer();
+ }
+
+ @Override
+ public FlatVectorsScorer getLucene99ScalarQuantizedVectorsScorer() {
+ return delegateVectorUtilProvider.getLucene99ScalarQuantizedVectorsScorer();
+ }
+
+ @Override
+ public PostingDecodingUtil newPostingDecodingUtil(IndexInput input) throws IOException {
+ return delegateVectorUtilProvider.newPostingDecodingUtil(input);
+ }
+}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/hnsw/TestFlatVectorScorer.java b/lucene/core/src/test/org/apache/lucene/codecs/hnsw/TestFlatVectorScorer.java
index 9bea4fcd387..c0d432f7c3b 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/hnsw/TestFlatVectorScorer.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/hnsw/TestFlatVectorScorer.java
@@ -73,7 +73,7 @@ public class TestFlatVectorScorer extends BaseVectorizationTestCase {
DefaultFlatVectorScorer.INSTANCE,
new Lucene99ScalarQuantizedVectorScorer(new DefaultFlatVectorScorer()),
FlatVectorScorerUtil.getLucene99FlatVectorsScorer(),
- maybePanamaProvider().getLucene99FlatVectorsScorer());
+ maybePanamaOrNativeProvider().getLucene99FlatVectorsScorer());
var dirs =
List.<IOSupplier<Directory>>of(
TestFlatVectorScorer::newDirectory,
diff --git a/lucene/core/src/test/org/apache/lucene/internal/vectorization/BaseVectorizationTestCase.java b/lucene/core/src/test/org/apache/lucene/internal/vectorization/BaseVectorizationTestCase.java
index ea6c183c7e7..d57b288d79e 100644
--- a/lucene/core/src/test/org/apache/lucene/internal/vectorization/BaseVectorizationTestCase.java
+++ b/lucene/core/src/test/org/apache/lucene/internal/vectorization/BaseVectorizationTestCase.java
@@ -22,20 +22,21 @@ import org.junit.BeforeClass;
public abstract class BaseVectorizationTestCase extends LuceneTestCase {
protected static final VectorizationProvider LUCENE_PROVIDER = defaultProvider();
- protected static final VectorizationProvider PANAMA_PROVIDER = maybePanamaProvider();
+ protected static final VectorizationProvider PANAMA_OR_NATIVE_PROVIDER =
+ maybePanamaOrNativeProvider();
@BeforeClass
public static void beforeClass() throws Exception {
assumeTrue(
"Test only works when JDK's vector incubator module is enabled.",
- PANAMA_PROVIDER.getClass() != LUCENE_PROVIDER.getClass());
+ PANAMA_OR_NATIVE_PROVIDER.getClass() != LUCENE_PROVIDER.getClass());
}
public static VectorizationProvider defaultProvider() {
return new DefaultVectorizationProvider();
}
- public static VectorizationProvider maybePanamaProvider() {
+ public static VectorizationProvider maybePanamaOrNativeProvider() {
return VectorizationProvider.lookup(true);
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/internal/vectorization/TestVectorUtilSupport.java b/lucene/core/src/test/org/apache/lucene/internal/vectorization/TestVectorUtilSupport.java
index 2e31b865631..ccfed7c8c1a 100644
--- a/lucene/core/src/test/org/apache/lucene/internal/vectorization/TestVectorUtilSupport.java
+++ b/lucene/core/src/test/org/apache/lucene/internal/vectorization/TestVectorUtilSupport.java
@@ -114,16 +114,18 @@ public class TestVectorUtilSupport extends BaseVectorizationTestCase {
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProduct(a, b));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProduct(a, b));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(a, pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(a, pack(b)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(b, pack(a)));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(b, pack(a)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductBothPacked(pack(a), pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER
+ .getVectorUtilSupport()
+ .int4DotProductBothPacked(pack(a), pack(b)));
}
public void testInt4DotProductBoundaries() {
@@ -142,16 +144,18 @@ public class TestVectorUtilSupport extends BaseVectorizationTestCase {
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProduct(a, b));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProduct(a, b));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(a, pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(a, pack(b)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(b, pack(a)));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(b, pack(a)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductBothPacked(pack(a), pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER
+ .getVectorUtilSupport()
+ .int4DotProductBothPacked(pack(a), pack(b)));
byte MIN_VALUE = 0;
Arrays.fill(a, MIN_VALUE);
@@ -164,16 +168,18 @@ public class TestVectorUtilSupport extends BaseVectorizationTestCase {
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProduct(a, b));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProduct(a, b));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(a, pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(a, pack(b)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(b, pack(a)));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(b, pack(a)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductBothPacked(pack(a), pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER
+ .getVectorUtilSupport()
+ .int4DotProductBothPacked(pack(a), pack(b)));
}
public void testInt4SquareDistance() {
@@ -192,16 +198,22 @@ public class TestVectorUtilSupport extends BaseVectorizationTestCase {
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().squareDistance(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4SquareDistance(a, b));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4SquareDistance(a, b));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().squareDistance(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4SquareDistanceSinglePacked(a, pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER
+ .getVectorUtilSupport()
+ .int4SquareDistanceSinglePacked(a, pack(b)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().squareDistance(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4SquareDistanceSinglePacked(b, pack(a)));
+ PANAMA_OR_NATIVE_PROVIDER
+ .getVectorUtilSupport()
+ .int4SquareDistanceSinglePacked(b, pack(a)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().squareDistance(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4SquareDistanceBothPacked(pack(a), pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER
+ .getVectorUtilSupport()
+ .int4SquareDistanceBothPacked(pack(a), pack(b)));
}
public void testInt4SquareDistanceBoundaries() {
@@ -224,16 +236,18 @@ public class TestVectorUtilSupport extends BaseVectorizationTestCase {
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProduct(a, b));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProduct(a, b));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(a, pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(a, pack(b)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(b, pack(a)));
+ PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport().int4DotProductSinglePacked(b, pack(a)));
assertEquals(
LUCENE_PROVIDER.getVectorUtilSupport().dotProduct(a, b),
- PANAMA_PROVIDER.getVectorUtilSupport().int4DotProductBothPacked(pack(a), pack(b)));
+ PANAMA_OR_NATIVE_PROVIDER
+ .getVectorUtilSupport()
+ .int4DotProductBothPacked(pack(a), pack(b)));
}
public void testInt4BitDotProduct() {
@@ -307,7 +321,8 @@ public class TestVectorUtilSupport extends BaseVectorizationTestCase {
private void assertFloatReturningProviders(ToDoubleFunction<VectorUtilSupport> func) {
double luceneProviderResults = func.applyAsDouble(LUCENE_PROVIDER.getVectorUtilSupport());
- double panamaProviderResults = func.applyAsDouble(PANAMA_PROVIDER.getVectorUtilSupport());
+ double panamaProviderResults =
+ func.applyAsDouble(PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport());
double delta =
Math.max(this.delta, this.delta * Math.max(luceneProviderResults, panamaProviderResults));
assertEquals(luceneProviderResults, panamaProviderResults, delta);
@@ -316,12 +331,12 @@ public class TestVectorUtilSupport extends BaseVectorizationTestCase {
private void assertIntReturningProviders(ToIntFunction<VectorUtilSupport> func) {
assertEquals(
func.applyAsInt(LUCENE_PROVIDER.getVectorUtilSupport()),
- func.applyAsInt(PANAMA_PROVIDER.getVectorUtilSupport()));
+ func.applyAsInt(PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport()));
}
private void assertLongReturningProviders(ToLongFunction<VectorUtilSupport> func) {
assertEquals(
func.applyAsLong(LUCENE_PROVIDER.getVectorUtilSupport()),
- func.applyAsLong(PANAMA_PROVIDER.getVectorUtilSupport()));
+ func.applyAsLong(PANAMA_OR_NATIVE_PROVIDER.getVectorUtilSupport()));
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestVectorUtil.java b/lucene/core/src/test/org/apache/lucene/util/TestVectorUtil.java
index 1953d6dff75..a80f5e0146c 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestVectorUtil.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestVectorUtil.java
@@ -489,7 +489,7 @@ public class TestVectorUtil extends LuceneTestCase {
static final VectorizationProvider defaultedProvider =
BaseVectorizationTestCase.defaultProvider();
static final VectorizationProvider defOrPanamaProvider =
- BaseVectorizationTestCase.maybePanamaProvider();
+ BaseVectorizationTestCase.maybePanamaOrNativeProvider();
public void testBasicInt4BitDotProduct() {
testBasicInt4BitDotProductImpl(VectorUtil::int4BitDotProduct);
diff --git a/lucene/distribution.tests/src/test/org/apache/lucene/distribution/TestModularLayer.java b/lucene/distribution.tests/src/test/org/apache/lucene/distribution/TestModularLayer.java
index f19819941db..4531f870c1c 100644
--- a/lucene/distribution.tests/src/test/org/apache/lucene/distribution/TestModularLayer.java
+++ b/lucene/distribution.tests/src/test/org/apache/lucene/distribution/TestModularLayer.java
@@ -351,10 +351,15 @@ public class TestModularLayer extends AbstractLuceneDistributionTest {
if (isInternal && export.source().equals("org.apache.lucene.internal.hppc")) {
return true;
}
- if (isInternal) {
+ if (export.source().equals("org.apache.lucene.internal.tests")) {
Assertions.assertThat(export.targets())
.containsExactlyInAnyOrder("org.apache.lucene.test_framework");
}
+ // Allow export to JMH benchmarks
+ if (export.source().equals("org.apache.lucene.internal.vectorization")) {
+ Assertions.assertThat(export.targets())
+ .containsExactlyInAnyOrder("org.apache.lucene.benchmark.jmh");
+ }
return isInternal;
});
}
diff --git a/lucene/misc/src/c/dotProduct.c b/lucene/misc/src/c/dotProduct.c
new file mode 100644
index 00000000000..3eec293f6b7
--- /dev/null
+++ b/lucene/misc/src/c/dotProduct.c
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+// EXAMPLE CODE FOR DOT PRODUCT IMPLEMENTATION IN C (Scalar, NEON, SVE)
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#if defined(__aarch64__) && defined(__linux__)
+#include <sys/auxv.h>
+#include <asm/hwcap.h>
+#include "dotProduct.h"
+
+#ifdef __ARM_ACLE
+#include <arm_acle.h>
+#endif
+
+#if (defined(__ARM_FEATURE_SVE))
+#include <arm_sve.h>
+
+/**
+ - ARM intrinsics guide - https://developer.arm.com/architectures/instruction-sets/intrinsics/#q=svptrue
+ - SVE Programming examples - https://developer.arm.com/documentation/dai0548/latest/
+*/
+
+ /*
+ * Unrolled and vectorized int8 dotProduct implementation using SVE instructions
+ * NOTE: Clang 15.0 compiler on Apple M3 Max compiles the code below successfully
+ * with '-march=native+sve' option but throws "Illegal Hardware Instruction" error
+ * Looks like Apple M3 does not implement SVE and Apple's official documentation
+ * is not explicit about this or at least I could not find it.
+ *
+ */
+// === Using SVE intrinsics ===
+__attribute__((target("arch=armv8.4-a+sve")))
+int32_t vdot8s_sve(int8_t vec1[], int8_t vec2[], int32_t limit) {
+ int32_t result = 0;
+ int32_t i = 0;
+ // Vectors of 8-bit signed integers
+ svint8_t va1, va2, va3, va4;
+ svint8_t vb1, vb2, vb3, vb4;
+ // Init accumulators
+ svint32_t acc1 = svdup_n_s32(0);
+ svint32_t acc2 = svdup_n_s32(0);
+ svint32_t acc3 = svdup_n_s32(0);
+ svint32_t acc4 = svdup_n_s32(0);
+
+ // Number of 8-bits elements in the SVE vector
+ int32_t vec_length = svcntb();
+
+ // Manually unroll the loop
+ for (i = 0; i + 4 * vec_length <= limit; i += 4 * vec_length) {
+ // Load vectors into the Z registers which can range from 128-bit to 2048-bit wide
+ // The predicate register - P determines which bytes are active
+ // svptrue_b8() returns a predicate in which every element is true
+ va1 = svld1_s8(svptrue_b8(), &vec1[i]);
+ vb1 = svld1_s8(svptrue_b8(), &vec2[i]);
+
+ va2 = svld1_s8(svptrue_b8(), &vec1[i + vec_length]);
+ vb2 = svld1_s8(svptrue_b8(), &vec2[i + vec_length]);
+
+ va3 = svld1_s8(svptrue_b8(), &vec1[i + 2 * vec_length]);
+ vb3 = svld1_s8(svptrue_b8(), &vec2[i + 2 * vec_length]);
+
+ va4 = svld1_s8(svptrue_b8(), &vec1[i + 3 * vec_length]);
+ vb4 = svld1_s8(svptrue_b8(), &vec2[i + 3 * vec_length]);
+
+ // Dot product using SDOT instruction on Z vectors
+ acc1 = svdot_s32(acc1, va1, vb1);
+ acc2 = svdot_s32(acc2, va2, vb2);
+ acc3 = svdot_s32(acc3, va3, vb3);
+ acc4 = svdot_s32(acc4, va4, vb4);
+ }
+
+ // Vector tail: less scalar computations for unaligned sizes, esp with big vector sizes
+ svbool_t pred = svwhilelt_b8_s32(i, limit);
+ while (svptest_first(svptrue_b8(), pred)) {
+ va1 = svld1_s8(pred, &vec1[i]);
+ vb1 = svld1_s8(pred, &vec2[i]);
+ acc1 = svdot_s32(acc1, va1, vb1);
+ i += vec_length;
+ pred = svwhilelt_b8_s32(i, limit);
+ }
+
+ // Add corresponding active elements in each of the vectors
+ acc1 = svadd_s32_x(svptrue_b8(), acc1, acc2);
+ acc3 = svadd_s32_x(svptrue_b8(), acc3, acc4);
+ acc1 = svadd_s32_x(svptrue_b8(), acc1, acc3);
+
+ // REDUCE: Add every vector element in target and write result to scalar
+ result = svaddv_s32(svptrue_b8(), acc1);
+
+ return result;
+}
+#endif
+
+#if defined(__ARM_NEON)
+#include <arm_neon.h>
+
+// https://developer.arm.com/architectures/instruction-sets/intrinsics/
+// === Using NEON intrinsics ===
+__attribute__((target("arch=armv8.2-a+dotprod")))
+int32_t vdot8s_neon(int8_t vec1[], int8_t vec2[], int32_t limit) {
+ int32_t result = 0;
+ int32x4_t acc1 = vdupq_n_s32(0);
+ int32x4_t acc2 = vdupq_n_s32(0);
+ int32x4_t acc3 = vdupq_n_s32(0);
+ int32x4_t acc4 = vdupq_n_s32(0);
+ int32_t i = 0;
+ int8x16_t va1, va2, va3, va4;
+ int8x16_t vb1, vb2, vb3, vb4;
+
+ for (; i + 64 <= limit; i += 64) {
+ // Read into 8 (bit) x 16 (values) vector
+ va1 = vld1q_s8(&vec1[i]);
+ vb1 = vld1q_s8(&vec2[i]);
+
+ va2 = vld1q_s8(&vec1[i + 16]);
+ vb2 = vld1q_s8(&vec2[i + 16]);
+
+ va3 = vld1q_s8(&vec1[i + 32]);
+ vb3 = vld1q_s8(&vec2[i + 32]);
+
+ va4 = vld1q_s8(&vec1[i + 48]);
+ vb4 = vld1q_s8(&vec2[i + 48]);
+
+ // Dot product using SDOT instruction
+ // GCC 7.3 does not define the intrinsic below so we get compile time error.
+ acc1 = vdotq_s32(acc1, va1, vb1);
+ acc2 = vdotq_s32(acc2, va2, vb2);
+ acc3 = vdotq_s32(acc3, va3, vb3);
+ acc4 = vdotq_s32(acc4, va4, vb4);
+ }
+ // Vector tail: less scalar computations for unaligned sizes, esp with big vector sizes
+ for (; i < limit - 16; i += 16) {
+ va1 = vld1q_s8(&vec1[i]);
+ vb1 = vld1q_s8(&vec2[i]);
+ acc1 = vdotq_s32(acc1, va1, vb1);
+ }
+ // Add corresponding elements in each vectors
+ acc1 = vaddq_s32(acc1, acc2);
+ acc3 = vaddq_s32(acc3, acc4);
+ acc1 = vaddq_s32(acc1, acc3);
+
+ // REDUCE: Add every vector element in target and write result to scalar
+ result += vaddvq_s32(acc1);
+ // Scalar tail
+ for (; i < limit; i++) {
+ result += vec1[i] * vec2[i];
+ }
+ return result;
+}
+#endif
+#endif
+
+int32_t vdot8s_scalar(int8_t vec1[], int8_t vec2[], int32_t limit) {
+ int32_t result = 0;
+ #ifdef __clang__
+ #pragma clang loop vectorize(assume_safety) unroll(enable)
+ #endif
+ for (int32_t i = 0; i < limit; i++) {
+ result += vec1[i] * vec2[i];
+ }
+ return result;
+}
+
+static void* resolve_dot8s(void) {
+#ifdef AT_HWCAP
+ unsigned long hwcap = getauxval(AT_HWCAP);
+#endif
+#if defined(HWCAP_SVE) && defined(__ARM_FEATURE_SVE)
+ if (hwcap & HWCAP_SVE) {
+ return (void*) vdot8s_sve;
+ }
+#endif
+#if defined(HWCAP_ASIMDDP) && defined(__ARM_NEON)
+ if (hwcap & HWCAP_ASIMDDP) {
+ return (void*) vdot8s_neon;
+ }
+#endif
+ return (void*) vdot8s_scalar;
+}
+
+// dot8s will dispatch based on runtime capabilities
+#if defined(__aarch64__) && defined(__linux__)
+__attribute__((ifunc("resolve_dot8s")))
+int32_t dotProduct(int8_t vec1[], int8_t vec2[], int32_t limit);
+#else
+// Fallback implementation for non-Linux platforms
+int32_t dotProduct(int8_t vec1[], int8_t vec2[], int32_t limit) {
+ return vdot8s_scalar(vec1, vec2, limit);
+}
+#endif
+
+/*
+int main(int argc, const char* args[]) {
+ int DIMENSIONS = 1024;
+ for (int s = 1; s < DIMENSIONS; s++) {
+ int8_t *a = malloc(sizeof(int8_t) * s);
+ int8_t *b = malloc(sizeof(int8_t) * s);
+ for (int i = 0; i < s; i++) {
+ a[i] = i % 128;
+ b[i] = (s - i) % 128;
+ }
+
+ //printf("\nVector length: %d bits", svcntb() * 8);
+ int sveDot = vdot8s_sve(a, b, s);
+ int vdotNeon = vdot8s_neon(a, b, s);
+ int dot = dot8s(a, b, s);
+ if(vdotNeon != dot || sveDot != dot) {
+ printf("\n-----------------------------------------");
+ printf("\nDimension: [%d]; Sum (Vectorized - SVE) = %d", s, sveDot);
+ printf("\nDimension: [%d]; Sum (Vectorized - NEON) = %d", s, vdot8s_neon(a, b, s));
+ printf("\nDimension: [%d]; Sum (Scalar) = %d", s, dot);
+ }
+
+ free(a);
+ free(b);
+ }
+
+ int8_t a[30] = { 24, -48, 5, 62, -30, -41, 33, -14, -76, -127, -59, -73, -108, -82, 52, -103, -48, -6, 16, -24, -6, 28, 58, 117, -34, -15, 15, -113, 98, 104 };
+ int8_t b[30] = { -54, 47, -81, 1, -72, -12, -5, -92, 61, -64, -40, 5, -43, -62, 14, -9, -37, -82, -7, 123, 59, 46, -83, -116, -70, 42, -120, 63, 48, 8 };
+ printf("\nTest Complete for [1-%d] dimensional vectors\n", DIMENSIONS);
+ printf("\n Scalar Dot Product: %d\n", dot8s(a,b, 30));
+ printf("\n SVE Dot Product: %d\n", vdot8s_neon(a,b, 30));
+}
+*/
diff --git a/lucene/misc/src/c/dotProduct.h b/lucene/misc/src/c/dotProduct.h
new file mode 100644
index 00000000000..2f556fd6074
--- /dev/null
+++ b/lucene/misc/src/c/dotProduct.h
@@ -0,0 +1,18 @@
+/*
+ * 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.
+ */
+
+int32_t dotProduct(int8_t vec1[], int8_t vec2[], int32_t limit);