Skip to content

Apache Lucene open-source search software

Fix the native function contract of NativeVectorUtilSupport: float lengths, byte cosine, l2normalize, symbol lookup (#16812)

Lantao Jin54c6dc8becd4
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
index bad26257cbc..4c1951fbff0 100644
--- a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/NativeVectorUtilSupport.java
+++ b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/NativeVectorUtilSupport.java
@@ -49,6 +49,11 @@ import org.apache.lucene.util.Constants;
* <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.
*
+ * <p>The native functions are looked up by their name prefixed with {@value #SYMBOL_PREFIX}, only
+ * in libraries loaded by this class's class loader. Their signatures are declared in {@code
+ * lucene/misc/src/c/dotProduct.h}: where a function takes a single length argument, it is the
+ * element count of its first array argument.
+ *
* @lucene.experimental
*/
@SuppressWarnings("restricted")
@@ -67,6 +72,9 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
// TODO: Make this dynamic?
public static final String NATIVE_VECTOR_LIBRARY_NAME = "dotProduct";
+ /** Prefix of the native symbol names, so that an unrelated library cannot supply them. */
+ public static final String SYMBOL_PREFIX = "lucene_";
+
public NativeVectorUtilSupport(VectorUtilSupport vectorUtilSupport) {
this.delegateVectorUtilSupport = vectorUtilSupport;
}
@@ -161,13 +169,12 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
static {
if (isLibraryLoaded) {
- SymbolLookup loaderLookup = SymbolLookup.loaderLookup();
- SYMBOL_LOOKUP = name -> loaderLookup.find(name).or(() -> LINKER.defaultLookup().find(name));
+ SYMBOL_LOOKUP = SymbolLookup.loaderLookup();
// Each method handle with a unique native method name
dotProduct$MH = getMethodHandle("dotProduct", twoPointerIntToInt);
squareDistance$MH = getMethodHandle("squareDistance", twoPointerIntToInt);
- cosine$MH = getMethodHandle("cosine", twoPointerIntToInt);
+ cosine$MH = getMethodHandle("cosine", twoPointerIntToFloat);
dotProductFloat$MH = getMethodHandle("dotProductFloat", twoPointerIntToFloat);
squareDistanceFloat$MH = getMethodHandle("squareDistanceFloat", twoPointerIntToFloat);
cosineFloat$MH = getMethodHandle("cosineFloat", twoPointerIntToFloat);
@@ -221,18 +228,21 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
}
private static MethodHandle getMethodHandle(String methodName, FunctionDescriptor descriptor) {
+ String symbolName = SYMBOL_PREFIX + methodName;
MethodHandle mh =
SYMBOL_LOOKUP
- .find(methodName)
+ .find(symbolName)
.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!");
+ throw new RuntimeException("C code for " + symbolName + " was not linked!");
}
return mh;
}
- // Reusable invoke helpers for signatures used multiple times
+ // Reusable invoke helpers for signatures used multiple times. The length argument is the element
+ // count of the first array; the int and long helpers are only used for byte arrays, where it
+ // equals the byte size.
private static int invokeIntMethodHandle(MethodHandle mh, MemorySegment a, MemorySegment b) {
try {
return (int) mh.invokeExact(a, b, (int) a.byteSize());
@@ -249,9 +259,10 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
}
}
- private static float invokeFloatMethodHandle(MethodHandle mh, MemorySegment a, MemorySegment b) {
+ private static float invokeFloatMethodHandle(
+ MethodHandle mh, MemorySegment a, MemorySegment b, int length) {
try {
- return (float) mh.invokeExact(a, b, (int) a.byteSize());
+ return (float) mh.invokeExact(a, b, length);
} catch (Throwable ex) {
throw new AssertionError("should not reach here", ex);
}
@@ -279,7 +290,7 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
public static float cosine(MemorySegment a, MemorySegment b) {
return (cosine$MH != null)
- ? invokeIntMethodHandle(cosine$MH, a, b)
+ ? invokeFloatMethodHandle(cosine$MH, a, b, (int) a.byteSize())
: PanamaVectorUtilSupport.cosine(a, b);
}
@@ -384,7 +395,7 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
public float dotProduct(float[] a, float[] b) {
return (dotProductFloat$MH != null)
? invokeFloatMethodHandle(
- dotProductFloat$MH, MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ dotProductFloat$MH, MemorySegment.ofArray(a), MemorySegment.ofArray(b), a.length)
: delegateVectorUtilSupport.dotProduct(a, b);
}
@@ -392,7 +403,7 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
public float cosine(float[] v1, float[] v2) {
return (cosineFloat$MH != null)
? invokeFloatMethodHandle(
- cosineFloat$MH, MemorySegment.ofArray(v1), MemorySegment.ofArray(v2))
+ cosineFloat$MH, MemorySegment.ofArray(v1), MemorySegment.ofArray(v2), v1.length)
: delegateVectorUtilSupport.cosine(v1, v2);
}
@@ -400,7 +411,7 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
public float squareDistance(float[] a, float[] b) {
return (squareDistanceFloat$MH != null)
? invokeFloatMethodHandle(
- squareDistanceFloat$MH, MemorySegment.ofArray(a), MemorySegment.ofArray(b))
+ squareDistanceFloat$MH, MemorySegment.ofArray(a), MemorySegment.ofArray(b), a.length)
: delegateVectorUtilSupport.squareDistance(a, b);
}
@@ -576,12 +587,22 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
@Override
public float[] l2normalize(float[] v, boolean throwOnZero) {
- invokeOrDelegate(
- l2normalize$MH,
- () -> delegateVectorUtilSupport.l2normalize(v, throwOnZero),
- MemorySegment.ofArray(v),
- (byte) (throwOnZero ? 1 : 0),
- v.length);
+ if (l2normalize$MH == null) {
+ return delegateVectorUtilSupport.l2normalize(v, throwOnZero);
+ }
+ final MemorySegment result;
+ try {
+ result =
+ (MemorySegment)
+ l2normalize$MH.invokeExact(
+ MemorySegment.ofArray(v), (byte) (throwOnZero ? 1 : 0), v.length);
+ } catch (Throwable ex) {
+ throw new AssertionError("should not reach here", ex);
+ }
+ // the native function returns NULL for a zero vector, which it leaves unchanged
+ if (result.address() == 0 && throwOnZero) {
+ throw new IllegalArgumentException("Cannot normalize a zero-length vector");
+ }
return v;
}
diff --git a/lucene/misc/src/c/dotProduct.c b/lucene/misc/src/c/dotProduct.c
index 3eec293f6b7..1fbecbafc07 100644
--- a/lucene/misc/src/c/dotProduct.c
+++ b/lucene/misc/src/c/dotProduct.c
@@ -198,10 +198,10 @@ static void* resolve_dot8s(void) {
// 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);
+int32_t lucene_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) {
+int32_t lucene_dotProduct(int8_t vec1[], int8_t vec2[], int32_t limit) {
return vdot8s_scalar(vec1, vec2, limit);
}
#endif
diff --git a/lucene/misc/src/c/dotProduct.h b/lucene/misc/src/c/dotProduct.h
index 2f556fd6074..47e56c8e72e 100644
--- a/lucene/misc/src/c/dotProduct.h
+++ b/lucene/misc/src/c/dotProduct.h
@@ -15,4 +15,64 @@
* limitations under the License.
*/
-int32_t dotProduct(int8_t vec1[], int8_t vec2[], int32_t limit);
+// Functions that NativeVectorUtilSupport binds from the "dotProduct" library. A library may
+// implement any subset; Lucene uses its Java implementation for the others. Each function must
+// return what the VectorUtilSupport method it replaces returns.
+//
+// Where a function takes a single length argument `n`, it is the number of elements of its FIRST
+// array argument. The other array has the same number of elements unless stated otherwise.
+
+#include <stdint.h>
+
+// Signed bytes.
+int32_t lucene_dotProduct(int8_t a[], int8_t b[], int32_t n);
+int32_t lucene_squareDistance(int8_t a[], int8_t b[], int32_t n);
+float lucene_cosine(int8_t a[], int8_t b[], int32_t n);
+
+// Unsigned bytes.
+int32_t lucene_uint8DotProduct(uint8_t a[], uint8_t b[], int32_t n);
+int32_t lucene_uint8SquareDistance(uint8_t a[], uint8_t b[], int32_t n);
+
+// Unsigned half-bytes, one value per byte.
+int32_t lucene_int4DotProduct(int8_t a[], int8_t b[], int32_t n);
+int32_t lucene_int4SquareDistance(int8_t a[], int8_t b[], int32_t n);
+
+// `packed` holds n / 2 bytes: the high nibble of packed[i] pairs with unpacked[i], the low nibble
+// with unpacked[n / 2 + i].
+int32_t lucene_int4DotProductSinglePacked(int8_t unpacked[], uint8_t packed[], int32_t n);
+int32_t lucene_int4SquareDistanceSinglePacked(int8_t unpacked[], uint8_t packed[], int32_t n);
+
+// Both arrays packed as above; n is their length in bytes.
+int32_t lucene_int4DotProductBothPacked(uint8_t a[], uint8_t b[], int32_t n);
+int32_t lucene_int4SquareDistanceBothPacked(uint8_t a[], uint8_t b[], int32_t n);
+
+// `q` is a transposed int4 vector of n bytes (4 bit planes); `d` holds n / 4 bytes (1 bit plane)
+// for int4BitDotProduct and n / 2 bytes (2 bit planes, lower bits first) for int4DibitDotProduct.
+int64_t lucene_int4BitDotProduct(uint8_t q[], uint8_t d[], int32_t n);
+int64_t lucene_int4DibitDotProduct(uint8_t q[], uint8_t d[], int32_t n);
+
+// Floats; n is the number of floats, not bytes.
+float lucene_dotProductFloat(float a[], float b[], int32_t n);
+float lucene_squareDistanceFloat(float a[], float b[], int32_t n);
+float lucene_cosineFloat(float a[], float b[], int32_t n);
+
+// Writes n quantized values to dest and returns the corrective offset.
+float lucene_minMaxScalarQuantize(float vector[], int8_t dest[], float scale, float alpha,
+ float minQuantile, float maxQuantile, int32_t n);
+float lucene_recalculateScalarQuantizationOffset(int8_t vector[], float oldAlpha,
+ float oldMinQuantile, float scale, float alpha, float minQuantile, float maxQuantile,
+ int32_t n);
+
+// Compacts the first upTo entries of both buffers in place; returns the number kept.
+int32_t lucene_filterByScore(int32_t docBuffer[], double scoreBuffer[], double minScoreInclusive,
+ int32_t upTo);
+
+// Normalizes v in place and returns v. For a vector with zero norm it must leave v unchanged and
+// return NULL; Lucene then throws IllegalArgumentException if throwOnZero is non-zero.
+float *lucene_l2normalize(float v[], int8_t throwOnZero, int32_t n);
+
+// n is the array length, which is 256.
+void lucene_expand8(int32_t arr[], int32_t n);
+
+// Returns the first index in [from, to) whose value is >= target, or `to`.
+int32_t lucene_findNextGEQ(int32_t buffer[], int32_t target, int32_t from, int32_t to);