Skip to content

Apache Lucene open-source search software

Add fp16 (float16) vector encoding (without support for quantization) (#16383)

Pulkit Guptabfe5c847d3c4
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index d67e7742b62..13085581872 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -326,6 +326,8 @@ New Features
and document length instead of corpus statistics such as document frequency. It also supports k3
query-term frequency saturation. (Tianxiao Wei)
+* GITHUB#16383: Add fp16 vector encoding support. (Pulkit Gupta)
+
Improvements
---------------------
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryFlatVectorsScorer.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryFlatVectorsScorer.java
index 16d543e0576..f95c1706adc 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryFlatVectorsScorer.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryFlatVectorsScorer.java
@@ -94,6 +94,13 @@ public class Lucene102BinaryFlatVectorsScorer implements FlatVectorsScorer {
return nonQuantizedDelegate.getRandomVectorScorer(similarityFunction, vectorValues, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String toString() {
return "Lucene102BinaryFlatVectorsScorer(nonQuantizedDelegate=" + nonQuantizedDelegate + ")";
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsReader.java
index 3bf41e40dfb..59fd7d34beb 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene102/Lucene102BinaryQuantizedVectorsReader.java
@@ -40,6 +40,7 @@ import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.KnnVectorValues;
@@ -211,6 +212,11 @@ public class Lucene102BinaryQuantizedVectorsReader extends FlatVectorsReader
return rawVectorsReader.getRandomVectorScorer(field, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(String field, short[] target) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void checkIntegrity(MergePolicy.OneMerge merge) throws IOException {
rawVectorsReader.checkIntegrity(merge);
@@ -253,6 +259,11 @@ public class Lucene102BinaryQuantizedVectorsReader extends FlatVectorsReader
return rawVectorsReader.getByteVectorValues(field);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void search(String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException {
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/Lucene90HnswVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/Lucene90HnswVectorsReader.java
index 15f531cf8d1..008c0831d9e 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/Lucene90HnswVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene90/Lucene90HnswVectorsReader.java
@@ -30,6 +30,7 @@ import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -243,6 +244,11 @@ public final class Lucene90HnswVectorsReader extends KnnVectorsReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void search(String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException {
@@ -280,6 +286,12 @@ public final class Lucene90HnswVectorsReader extends KnnVectorsReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
private OffHeapFloatVectorValues getOffHeapVectorValues(FieldEntry fieldEntry)
throws IOException {
IndexInput bytesSlice =
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene91/Lucene91HnswVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene91/Lucene91HnswVectorsReader.java
index 16df0ba4ca9..28570c8fd76 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene91/Lucene91HnswVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene91/Lucene91HnswVectorsReader.java
@@ -32,6 +32,7 @@ import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -239,6 +240,11 @@ public final class Lucene91HnswVectorsReader extends KnnVectorsReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void search(String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException {
@@ -264,6 +270,12 @@ public final class Lucene91HnswVectorsReader extends KnnVectorsReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
private OffHeapFloatVectorValues getOffHeapVectorValues(FieldEntry fieldEntry)
throws IOException {
IndexInput bytesSlice =
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene92/Lucene92HnswVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene92/Lucene92HnswVectorsReader.java
index dbcc8873db2..24ab63067a9 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene92/Lucene92HnswVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene92/Lucene92HnswVectorsReader.java
@@ -31,6 +31,7 @@ import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -236,6 +237,11 @@ public final class Lucene92HnswVectorsReader extends KnnVectorsReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void search(String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException {
@@ -261,6 +267,12 @@ public final class Lucene92HnswVectorsReader extends KnnVectorsReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
private HnswGraph getGraph(FieldEntry entry) throws IOException {
IndexInput bytesSlice =
vectorIndex.slice("graph-data", entry.vectorIndexOffset, entry.vectorIndexLength);
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsReader.java
index 3cdd0520156..6cddb7df1c0 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsReader.java
@@ -31,6 +31,7 @@ import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -178,6 +179,7 @@ public final class Lucene94HnswVectorsReader extends KnnVectorsReader {
switch (info.getVectorEncoding()) {
case BYTE -> Byte.BYTES;
case FLOAT32 -> Float.BYTES;
+ case FLOAT16 -> Short.BYTES;
};
long vectorBytes = Math.multiplyExact((long) dimension, byteSize);
long numBytes = Math.multiplyExact(vectorBytes, fieldEntry.size);
@@ -270,6 +272,11 @@ public final class Lucene94HnswVectorsReader extends KnnVectorsReader {
return OffHeapByteVectorValues.load(fieldEntry, vectorData);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void search(String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException {
@@ -308,6 +315,12 @@ public final class Lucene94HnswVectorsReader extends KnnVectorsReader {
vectorValues.getAcceptOrds(acceptDocs.bits()));
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
private HnswGraph getGraph(FieldEntry entry) throws IOException {
IndexInput bytesSlice =
vectorIndex.slice("graph-data", entry.vectorIndexOffset, entry.vectorIndexLength);
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene94/OffHeapFloatVectorValues.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene94/OffHeapFloatVectorValues.java
index b21df901ddb..7ae9497129d 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene94/OffHeapFloatVectorValues.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene94/OffHeapFloatVectorValues.java
@@ -86,6 +86,7 @@ abstract class OffHeapFloatVectorValues extends FloatVectorValues {
switch (fieldEntry.vectorEncoding()) {
case BYTE -> fieldEntry.dimension();
case FLOAT32 -> fieldEntry.dimension() * Float.BYTES;
+ case FLOAT16 -> fieldEntry.dimension() * Short.BYTES;
};
if (fieldEntry.docsWithFieldOffset() == -1) {
return new DenseOffHeapVectorValues(
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsReader.java
index de4e1ef9f59..3f524541161 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsReader.java
@@ -35,6 +35,7 @@ import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -177,6 +178,7 @@ public final class Lucene95HnswVectorsReader extends KnnVectorsReader implements
int byteSize =
switch (info.getVectorEncoding()) {
case BYTE -> Byte.BYTES;
+ case FLOAT16 -> Short.BYTES;
case FLOAT32 -> Float.BYTES;
};
long vectorBytes = Math.multiplyExact((long) dimension, byteSize);
@@ -290,6 +292,11 @@ public final class Lucene95HnswVectorsReader extends KnnVectorsReader implements
vectorData);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void search(String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException {
@@ -346,6 +353,12 @@ public final class Lucene95HnswVectorsReader extends KnnVectorsReader implements
vectorValues.getAcceptOrds(acceptDocs.bits()));
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
/** Get knn graph values; used for testing */
@Override
public HnswGraph getGraph(String field) throws IOException {
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsReader.java
index 2fbcf8352b2..6c4b7e402e9 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsReader.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene99/Lucene99ScalarQuantizedVectorsReader.java
@@ -32,6 +32,7 @@ import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -228,6 +229,11 @@ public final class Lucene99ScalarQuantizedVectorsReader extends FlatVectorsReade
return rawVectorsReader.getByteVectorValues(field);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
private static IndexInput openDataInput(
SegmentReadState state,
int versionMeta,
@@ -291,6 +297,11 @@ public final class Lucene99ScalarQuantizedVectorsReader extends FlatVectorsReade
return vectorScorer.getRandomVectorScorer(fieldEntry.similarityFunction, vectorValues, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(String field, short[] target) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public RandomVectorScorer getRandomVectorScorer(String field, byte[] target) throws IOException {
return rawVectorsReader.getRandomVectorScorer(field, target);
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/TestLucene102BinaryQuantizedVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/TestLucene102BinaryQuantizedVectorsFormat.java
index db2aaf1f062..575660ddf8d 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/TestLucene102BinaryQuantizedVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/TestLucene102BinaryQuantizedVectorsFormat.java
@@ -38,6 +38,7 @@ import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.KnnFloatVectorQuery;
@@ -187,6 +188,11 @@ public class TestLucene102BinaryQuantizedVectorsFormat extends BaseKnnVectorsFor
}
}
+ @Override
+ protected VectorEncoding randomVectorEncoding() {
+ return random().nextBoolean() ? VectorEncoding.BYTE : VectorEncoding.FLOAT32;
+ }
+
@Override
protected boolean supportsFloatVectorFallback() {
return false;
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/TestLucene102HnswBinaryQuantizedVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/TestLucene102HnswBinaryQuantizedVectorsFormat.java
index 4cb007c5f83..29eb4819dc4 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/TestLucene102HnswBinaryQuantizedVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene102/TestLucene102HnswBinaryQuantizedVectorsFormat.java
@@ -40,6 +40,7 @@ import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.AcceptDocs;
import org.apache.lucene.search.TopDocs;
@@ -178,6 +179,11 @@ public class TestLucene102HnswBinaryQuantizedVectorsFormat extends BaseKnnVector
}
}
+ @Override
+ protected VectorEncoding randomVectorEncoding() {
+ return random().nextBoolean() ? VectorEncoding.BYTE : VectorEncoding.FLOAT32;
+ }
+
@Override
protected boolean supportsFloatVectorFallback() {
return false;
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene90/Lucene90HnswVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene90/Lucene90HnswVectorsWriter.java
index f60411752d2..71c1750683c 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene90/Lucene90HnswVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene90/Lucene90HnswVectorsWriter.java
@@ -27,6 +27,7 @@ import org.apache.lucene.codecs.BufferingKnnVectorsWriter;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.KnnVectorValues;
@@ -177,6 +178,12 @@ public final class Lucene90HnswVectorsWriter extends BufferingKnnVectorsWriter {
throw new UnsupportedOperationException("byte vectors not supported in this version");
}
+ @Override
+ protected void writeField(
+ FieldInfo fieldInfo, Float16VectorValues float16VectorValues, int maxDoc) {
+ throw new UnsupportedOperationException("float16 vectors not supported in this version");
+ }
+
/**
* Writes the vector values to the output and returns a mapping from dense ordinals to document
* IDs. The length of the returned array matches the total number of documents with a vector
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene91/Lucene91HnswVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene91/Lucene91HnswVectorsWriter.java
index af78293e35a..4b0272c7a48 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene91/Lucene91HnswVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene91/Lucene91HnswVectorsWriter.java
@@ -26,6 +26,7 @@ import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.KnnVectorValues;
@@ -173,6 +174,12 @@ public final class Lucene91HnswVectorsWriter extends BufferingKnnVectorsWriter {
throw new UnsupportedOperationException("byte vectors not supported in this version");
}
+ @Override
+ protected void writeField(
+ FieldInfo fieldInfo, Float16VectorValues float16VectorValues, int maxDoc) {
+ throw new UnsupportedOperationException("float16 vectors not supported in this version");
+ }
+
/**
* Writes the vector values to the output and returns a set of documents that contains vectors.
*/
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene92/Lucene92HnswVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene92/Lucene92HnswVectorsWriter.java
index 917e5dd583f..3aad71b42c8 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene92/Lucene92HnswVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene92/Lucene92HnswVectorsWriter.java
@@ -30,6 +30,7 @@ import org.apache.lucene.codecs.lucene90.IndexedDISI;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.KnnVectorValues;
@@ -181,6 +182,12 @@ public final class Lucene92HnswVectorsWriter extends BufferingKnnVectorsWriter {
throw new UnsupportedOperationException("byte vectors not supported in this version");
}
+ @Override
+ protected void writeField(
+ FieldInfo fieldInfo, Float16VectorValues float16VectorValues, int maxDoc) {
+ throw new UnsupportedOperationException("float16 vectors not supported in this version");
+ }
+
/**
* Writes the vector values to the output and returns a set of documents that contains vectors.
*/
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsWriter.java
index 8c1ce18e05f..f005acddf6d 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/Lucene94HnswVectorsWriter.java
@@ -176,6 +176,7 @@ public final class Lucene94HnswVectorsWriter extends KnnVectorsWriter {
switch (fieldData.fieldInfo.getVectorEncoding()) {
case BYTE -> writeByteVectors(fieldData);
case FLOAT32 -> writeFloat32Vectors(fieldData);
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
}
long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
@@ -241,6 +242,7 @@ public final class Lucene94HnswVectorsWriter extends KnnVectorsWriter {
switch (fieldData.fieldInfo.getVectorEncoding()) {
case BYTE -> writeSortedByteVectors(fieldData, ordMap);
case FLOAT32 -> writeSortedFloat32Vectors(fieldData, ordMap);
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
@@ -405,6 +407,7 @@ public final class Lucene94HnswVectorsWriter extends KnnVectorsWriter {
writeVectorData(
tempVectorData,
MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState));
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
CodecUtil.writeFooter(tempVectorData);
IOUtils.close(tempVectorData);
@@ -461,6 +464,7 @@ public final class Lucene94HnswVectorsWriter extends KnnVectorsWriter {
scorerSupplier, M, beamWidth, HnswGraphBuilder.randSeed);
yield hnswGraphBuilder.build(vectorValues.size());
}
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
writeGraph(graph);
}
@@ -662,6 +666,7 @@ public final class Lucene94HnswVectorsWriter extends KnnVectorsWriter {
return ArrayUtil.copyOfSubArray(value, 0, dim);
}
};
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
}
@@ -683,6 +688,7 @@ public final class Lucene94HnswVectorsWriter extends KnnVectorsWriter {
defaultFlatVectorScorer.getRandomVectorScorerSupplier(
fieldInfo.getVectorSimilarityFunction(),
FloatVectorValues.fromFloats((List<float[]>) vectors, dim));
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
hnswGraphBuilder =
HnswGraphBuilder.create(scorerSupplier, M, beamWidth, HnswGraphBuilder.randSeed);
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/TestLucene94HnswVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/TestLucene94HnswVectorsFormat.java
index 1335f58e9bd..284f032b09d 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/TestLucene94HnswVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene94/TestLucene94HnswVectorsFormat.java
@@ -18,6 +18,7 @@ package org.apache.lucene.backward_codecs.lucene94;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.tests.index.BaseKnnVectorsFormatTestCase;
public class TestLucene94HnswVectorsFormat extends BaseKnnVectorsFormatTestCase {
@@ -43,4 +44,9 @@ public class TestLucene94HnswVectorsFormat extends BaseKnnVectorsFormatTestCase
protected boolean supportsFloatVectorFallback() {
return false;
}
+
+ @Override
+ protected VectorEncoding randomVectorEncoding() {
+ return random().nextBoolean() ? VectorEncoding.BYTE : VectorEncoding.FLOAT32;
+ }
}
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsWriter.java
index c5f1cabe688..198cbae552e 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/Lucene95HnswVectorsWriter.java
@@ -180,6 +180,7 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
switch (fieldData.fieldInfo.getVectorEncoding()) {
case BYTE -> writeByteVectors(fieldData);
case FLOAT32 -> writeFloat32Vectors(fieldData);
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
}
long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
@@ -246,6 +247,7 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
switch (fieldData.fieldInfo.getVectorEncoding()) {
case BYTE -> writeSortedByteVectors(fieldData, ordMap);
case FLOAT32 -> writeSortedFloat32Vectors(fieldData, ordMap);
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
@@ -432,6 +434,7 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
writeVectorData(
tempVectorData,
MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState));
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
CodecUtil.writeFooter(tempVectorData);
IOUtils.close(tempVectorData);
@@ -478,6 +481,8 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
defaultFlatVectorScorer,
fieldInfo.getVectorSimilarityFunction()));
break;
+ case FLOAT16:
+ throw new UnsupportedOperationException("FLOAT16 is not supported");
default:
throw new IllegalArgumentException(
"Unsupported vector encoding: " + fieldInfo.getVectorEncoding());
@@ -499,6 +504,7 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
case FLOAT32 ->
mergedVectorValues =
KnnVectorsWriter.MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState);
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
}
graph =
merger.merge(
@@ -711,6 +717,7 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
return ArrayUtil.copyOfSubArray(value, 0, dim);
}
};
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
}
@@ -731,6 +738,7 @@ public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter {
defaultFlatVectorScorer.getRandomVectorScorerSupplier(
fieldInfo.getVectorSimilarityFunction(),
FloatVectorValues.fromFloats((List<float[]>) vectors, dim));
+ case FLOAT16 -> throw new UnsupportedOperationException("FLOAT16 is not supported");
};
hnswGraphBuilder =
HnswGraphBuilder.create(scorerSupplier, M, beamWidth, HnswGraphBuilder.randSeed);
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/TestLucene95HnswVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/TestLucene95HnswVectorsFormat.java
index 00572e5995c..426d2be5ed5 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/TestLucene95HnswVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene95/TestLucene95HnswVectorsFormat.java
@@ -18,6 +18,7 @@ package org.apache.lucene.backward_codecs.lucene95;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.tests.index.BaseKnnVectorsFormatTestCase;
public class TestLucene95HnswVectorsFormat extends BaseKnnVectorsFormatTestCase {
@@ -39,6 +40,11 @@ public class TestLucene95HnswVectorsFormat extends BaseKnnVectorsFormatTestCase
assertEquals(expectedString, customCodec.getKnnVectorsFormatForField("bogus_field").toString());
}
+ @Override
+ protected VectorEncoding randomVectorEncoding() {
+ return random().nextBoolean() ? VectorEncoding.BYTE : VectorEncoding.FLOAT32;
+ }
+
@Override
protected boolean supportsFloatVectorFallback() {
return false;
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99HnswQuantizedVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99HnswQuantizedVectorsFormat.java
index c42ebfebfbf..b62250a4da0 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99HnswQuantizedVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99HnswQuantizedVectorsFormat.java
@@ -40,6 +40,7 @@ import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.NoMergePolicy;
+import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.AcceptDocs;
import org.apache.lucene.search.IndexSearcher;
@@ -374,4 +375,9 @@ public class TestLucene99HnswQuantizedVectorsFormat extends BaseKnnVectorsFormat
protected boolean supportsFloatVectorFallback() {
return false;
}
+
+ @Override
+ protected VectorEncoding randomVectorEncoding() {
+ return random().nextBoolean() ? VectorEncoding.BYTE : VectorEncoding.FLOAT32;
+ }
}
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99HnswScalarQuantizedVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99HnswScalarQuantizedVectorsFormat.java
index 948ada4ac3d..54e88675925 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99HnswScalarQuantizedVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99HnswScalarQuantizedVectorsFormat.java
@@ -29,6 +29,7 @@ import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.store.Directory;
import org.apache.lucene.tests.index.BaseKnnVectorsFormatTestCase;
import org.apache.lucene.tests.util.TestUtil;
@@ -69,4 +70,9 @@ public class TestLucene99HnswScalarQuantizedVectorsFormat extends BaseKnnVectors
protected boolean supportsFloatVectorFallback() {
return false;
}
+
+ @Override
+ protected VectorEncoding randomVectorEncoding() {
+ return random().nextBoolean() ? VectorEncoding.BYTE : VectorEncoding.FLOAT32;
+ }
}
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99ScalarQuantizedVectorsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99ScalarQuantizedVectorsFormat.java
index 630fe5d9d5c..e6cc1d5e50d 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99ScalarQuantizedVectorsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene99/TestLucene99ScalarQuantizedVectorsFormat.java
@@ -41,6 +41,7 @@ import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.NoMergePolicy;
+import org.apache.lucene.index.VectorEncoding;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
@@ -339,4 +340,9 @@ public class TestLucene99ScalarQuantizedVectorsFormat extends BaseKnnVectorsForm
CodecUtil.writeFooter(out);
}
}
+
+ @Override
+ protected VectorEncoding randomVectorEncoding() {
+ return random().nextBoolean() ? VectorEncoding.BYTE : VectorEncoding.FLOAT32;
+ }
}
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerBenchmark.java
index 10b6818f2a4..a1636aafad9 100644
--- a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerBenchmark.java
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerBenchmark.java
@@ -221,5 +221,11 @@ public class VectorScorerBenchmark {
VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, byte[] target) {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target) {
+ throw new UnsupportedOperationException();
+ }
}
}
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerFloat32Benchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerFloat32Benchmark.java
index ab9a5d976c2..bbfeacdb7bc 100644
--- a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerFloat32Benchmark.java
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/VectorScorerFloat32Benchmark.java
@@ -348,5 +348,11 @@ public class VectorScorerFloat32Benchmark {
VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, byte[] target) {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target) {
+ throw new UnsupportedOperationException();
+ }
}
}
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 189fb7e43f9..fc26a06cfcd 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
@@ -63,6 +63,8 @@ public class VectorUtilBenchmark {
private byte[] dibitQuantized;
private float[] floatsA;
private float[] floatsB;
+ private short[] shortsA;
+ private short[] shortsB;
private int expectedHalfByteDotProduct;
private int expectedHalfByteSquareDistance;
@@ -104,9 +106,13 @@ public class VectorUtilBenchmark {
// random float arrays for float methods
floatsA = new float[size];
floatsB = new float[size];
+ shortsA = new short[size];
+ shortsB = new short[size];
for (int i = 0; i < size; ++i) {
floatsA[i] = random.nextFloat();
+ shortsA[i] = Float.floatToFloat16(floatsA[i]);
floatsB[i] = random.nextFloat();
+ shortsB[i] = Float.floatToFloat16(floatsB[i]);
}
// arrays for BBQ int4-bit and int4-dibit dot product benchmarks
@@ -358,6 +364,11 @@ public class VectorUtilBenchmark {
return VectorUtil.dotProduct(floatsA, floatsB);
}
+ @Benchmark
+ public float fp16DotProductScalar() {
+ return VectorUtil.dotProduct(shortsA, shortsB);
+ }
+
@Benchmark
public float floatSquareScalar() {
return VectorUtil.squareDistance(floatsA, floatsB);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/FlatBitVectorsScorer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/FlatBitVectorsScorer.java
index 676dcba4e35..8085d7ae59a 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/FlatBitVectorsScorer.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/bitvectors/FlatBitVectorsScorer.java
@@ -58,6 +58,13 @@ public class FlatBitVectorsScorer implements FlatVectorsScorer {
throw new IllegalArgumentException("vectorValues must be an instance of ByteVectorValues");
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ throw new IllegalArgumentException("bit vectors do not support short[] targets");
+ }
+
static class BitRandomVectorScorer implements UpdateableRandomVectorScorer, HasKnnVectorValues {
private final ByteVectorValues vectorValues;
private final int bitDimensions;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextKnnVectorsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextKnnVectorsReader.java
index ae17f4770a0..7c93ac8ffa6 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextKnnVectorsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextKnnVectorsReader.java
@@ -32,6 +32,7 @@ import org.apache.lucene.codecs.KnnVectorsReader;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -178,6 +179,35 @@ public class SimpleTextKnnVectorsReader extends KnnVectorsReader {
return new SimpleTextByteVectorValues(fieldEntry, bytesSlice);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ FieldInfo info = readState.fieldInfos.fieldInfo(field);
+ if (info == null) {
+ return null;
+ }
+ int dimension = info.getVectorDimension();
+ if (dimension == 0) {
+ throw new IllegalStateException(
+ "KNN vectors readers should not be called on fields that don't enable KNN vectors");
+ }
+ FieldEntry fieldEntry = fieldEntries.get(info.number);
+ if (fieldEntry == null) {
+ return null;
+ }
+ if (dimension != fieldEntry.dimension) {
+ throw new IllegalStateException(
+ "Inconsistent vector dimension for field=\""
+ + field
+ + "\"; "
+ + dimension
+ + " != "
+ + fieldEntry.dimension);
+ }
+ IndexInput bytesSlice =
+ dataIn.slice("vector-data", fieldEntry.vectorDataOffset, fieldEntry.vectorDataLength);
+ return new SimpleTextFloat16VectorValues(fieldEntry, bytesSlice);
+ }
+
@Override
public void search(String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException {
@@ -239,6 +269,36 @@ public class SimpleTextKnnVectorsReader extends KnnVectorsReader {
}
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ Float16VectorValues values = getFloat16VectorValues(field);
+ if (target.length != values.dimension()) {
+ throw new IllegalArgumentException(
+ "vector query dimension: "
+ + target.length
+ + " differs from field dimension: "
+ + values.dimension());
+ }
+ FieldInfo info = readState.fieldInfos.fieldInfo(field);
+ VectorSimilarityFunction vectorSimilarity = info.getVectorSimilarityFunction();
+ for (int ord = 0; ord < values.size(); ord++) {
+ int doc = values.ordToDoc(ord);
+ if (acceptDocs.bits() != null && acceptDocs.bits().get(doc) == false) {
+ continue;
+ }
+
+ if (knnCollector.earlyTerminated()) {
+ break;
+ }
+
+ short[] vector = values.vectorValue(ord);
+ float score = vectorSimilarity.compare(vector, target);
+ knnCollector.collect(doc, score);
+ knnCollector.incVisitedCount(1);
+ }
+ }
+
@Override
public void checkIntegrity(MergePolicy.OneMerge merge) throws IOException {
IndexInput clone = dataIn.clone();
@@ -398,6 +458,103 @@ public class SimpleTextKnnVectorsReader extends KnnVectorsReader {
}
}
+ private static class SimpleTextFloat16VectorValues extends Float16VectorValues {
+
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
+ private final FieldEntry entry;
+ private final IndexInput in;
+ private final short[][] values;
+
+ int curOrd;
+
+ SimpleTextFloat16VectorValues(FieldEntry entry, IndexInput in) throws IOException {
+ this.entry = entry;
+ this.in = in;
+ values = new short[entry.size()][entry.dimension];
+ curOrd = -1;
+ readAllVectors();
+ }
+
+ private SimpleTextFloat16VectorValues(SimpleTextFloat16VectorValues other) {
+ this.entry = other.entry;
+ this.in = other.in.clone();
+ this.values = other.values;
+ this.curOrd = other.curOrd;
+ }
+
+ @Override
+ public int dimension() {
+ return entry.dimension;
+ }
+
+ @Override
+ public int size() {
+ return entry.size();
+ }
+
+ @Override
+ public short[] vectorValue(int ord) {
+ return values[ord];
+ }
+
+ @Override
+ public int ordToDoc(int ord) {
+ return entry.ordToDoc[ord];
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return createSparseIterator();
+ }
+
+ @Override
+ public VectorScorer scorer(short[] target) {
+ if (size() == 0) {
+ return null;
+ }
+ SimpleTextFloat16VectorValues simpleTextFloat16VectorValues =
+ new SimpleTextFloat16VectorValues(this);
+ DocIndexIterator iterator = simpleTextFloat16VectorValues.iterator();
+ return new VectorScorer() {
+ @Override
+ public float score() throws IOException {
+ int ord = iterator.index();
+ return entry
+ .similarityFunction()
+ .compare(simpleTextFloat16VectorValues.vectorValue(ord), target);
+ }
+
+ @Override
+ public DocIdSetIterator iterator() {
+ return iterator;
+ }
+ };
+ }
+
+ private void readAllVectors() throws IOException {
+ for (short[] value : values) {
+ readVector(value);
+ }
+ }
+
+ private void readVector(short[] value) throws IOException {
+ SimpleTextUtil.readLine(in, scratch);
+ // skip leading "[" and strip trailing "]"
+ String s = new BytesRef(scratch.bytes(), 1, scratch.length() - 2).utf8ToString();
+ String[] shortStrings = s.split(",");
+ assert shortStrings.length == value.length
+ : " read " + s + " when expecting " + value.length + " shorts";
+ for (int i = 0; i < shortStrings.length; i++) {
+ value[i] = Short.parseShort(shortStrings[i].trim());
+ }
+ }
+
+ @Override
+ public SimpleTextFloat16VectorValues copy() {
+ return this;
+ }
+ }
+
private static class SimpleTextByteVectorValues extends ByteVectorValues {
private final BytesRefBuilder scratch = new BytesRefBuilder();
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextKnnVectorsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextKnnVectorsWriter.java
index c7d5840658c..122229c66b7 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextKnnVectorsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextKnnVectorsWriter.java
@@ -26,6 +26,7 @@ import java.util.List;
import org.apache.lucene.codecs.BufferingKnnVectorsWriter;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.KnnVectorValues;
@@ -92,6 +93,28 @@ public class SimpleTextKnnVectorsWriter extends BufferingKnnVectorsWriter {
newline(vectorData);
}
+ @Override
+ public void writeField(FieldInfo fieldInfo, Float16VectorValues float16VectorValues, int maxDoc)
+ throws IOException {
+ long vectorDataOffset = vectorData.getFilePointer();
+ List<Integer> docIds = new ArrayList<>();
+ KnnVectorValues.DocIndexIterator iter = float16VectorValues.iterator();
+ for (int docV = iter.nextDoc(); docV != NO_MORE_DOCS; docV = iter.nextDoc()) {
+ writeFloat16VectorValue(float16VectorValues, iter.index());
+ docIds.add(docV);
+ }
+ long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
+ writeMeta(fieldInfo, vectorDataOffset, vectorDataLength, docIds);
+ }
+
+ private void writeFloat16VectorValue(Float16VectorValues vectors, int ord) throws IOException {
+ // write vector value
+ short[] value = vectors.vectorValue(ord);
+ assert value.length == vectors.dimension();
+ write(vectorData, Arrays.toString(value));
+ newline(vectorData);
+ }
+
@Override
public void writeField(FieldInfo fieldInfo, ByteVectorValues byteVectorValues, int maxDoc)
throws IOException {
diff --git a/lucene/codecs/src/test/org/apache/lucene/codecs/simpletext/TestSimpleTextKnnVectorsFormat.java b/lucene/codecs/src/test/org/apache/lucene/codecs/simpletext/TestSimpleTextKnnVectorsFormat.java
index d9de99f8234..eff223c2289 100644
--- a/lucene/codecs/src/test/org/apache/lucene/codecs/simpletext/TestSimpleTextKnnVectorsFormat.java
+++ b/lucene/codecs/src/test/org/apache/lucene/codecs/simpletext/TestSimpleTextKnnVectorsFormat.java
@@ -28,8 +28,7 @@ public class TestSimpleTextKnnVectorsFormat extends BaseKnnVectorsFormatTestCase
@Override
protected VectorEncoding randomVectorEncoding() {
- // TODO: Should SimpleTextKnnVectorsFormat support all encodings?
- return VectorEncoding.FLOAT32;
+ return random().nextBoolean() ? VectorEncoding.FLOAT32 : VectorEncoding.FLOAT16;
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/BufferingKnnVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/BufferingKnnVectorsWriter.java
index 629afec1ec1..2944489bfeb 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/BufferingKnnVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/BufferingKnnVectorsWriter.java
@@ -24,6 +24,7 @@ import java.util.function.Supplier;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.MergeState;
import org.apache.lucene.index.Sorter;
@@ -68,6 +69,15 @@ public abstract class BufferingKnnVectorsWriter extends KnnVectorsWriter {
}
};
break;
+ case FLOAT16:
+ newField =
+ new FieldWriter<short[]>(fieldInfo) {
+ @Override
+ public short[] copyValue(short[] vectorValue) {
+ return ArrayUtil.copyOfSubArray(vectorValue, 0, fieldInfo.getVectorDimension());
+ }
+ };
+ break;
default:
throw new UnsupportedOperationException();
}
@@ -106,6 +116,19 @@ public abstract class BufferingKnnVectorsWriter extends KnnVectorsWriter {
: bufferedByteVectorValues;
writeField(fieldData.fieldInfo, byteVectorValues, maxDoc);
break;
+ case FLOAT16:
+ BufferedFloat16VectorValues bufferedFloat16VectorValues =
+ new BufferedFloat16VectorValues(
+ (List<short[]>) fieldData.vectors,
+ fieldData.fieldInfo.getVectorDimension(),
+ fieldData.docsWithField);
+ Float16VectorValues float16VectorValues =
+ sortMap != null
+ ? new SortingFloat16VectorValues(
+ bufferedFloat16VectorValues, fieldData.docsWithField, sortMap)
+ : bufferedFloat16VectorValues;
+ writeField(fieldData.fieldInfo, float16VectorValues, maxDoc);
+ break;
}
}
}
@@ -148,6 +171,46 @@ public abstract class BufferingKnnVectorsWriter extends KnnVectorsWriter {
}
}
+ /**
+ * Sorting Float16VectorValues that iterate over documents in the order of the provided sortMap
+ */
+ private static class SortingFloat16VectorValues extends Float16VectorValues {
+ private final BufferedFloat16VectorValues delegate;
+ private final Supplier<SortingValuesIterator> iteratorSupplier;
+
+ SortingFloat16VectorValues(
+ BufferedFloat16VectorValues delegate, DocsWithFieldSet docsWithField, Sorter.DocMap sortMap)
+ throws IOException {
+ this.delegate = delegate.copy();
+ iteratorSupplier = SortingCodecReader.iteratorSupplier(delegate, sortMap);
+ }
+
+ @Override
+ public short[] vectorValue(int ord) throws IOException {
+ return delegate.vectorValue(ord);
+ }
+
+ @Override
+ public int dimension() {
+ return delegate.dimension();
+ }
+
+ @Override
+ public int size() {
+ return delegate.size();
+ }
+
+ @Override
+ public SortingFloat16VectorValues copy() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return iteratorSupplier.get();
+ }
+ }
+
/** Sorting ByteVectorValues that iterate over documents in the order of the provided sortMap */
private static class SortingByteVectorValues extends ByteVectorValues {
private final BufferedByteVectorValues delegate;
@@ -208,6 +271,11 @@ public abstract class BufferingKnnVectorsWriter extends KnnVectorsWriter {
MergedVectorValues.mergeByteVectorValues(fieldInfo, mergeState);
writeField(fieldInfo, byteVectorValues, mergeState.segmentInfo.maxDoc());
break;
+ case FLOAT16:
+ Float16VectorValues float16VectorValues =
+ MergedVectorValues.mergeFloat16VectorValues(fieldInfo, mergeState);
+ writeField(fieldInfo, float16VectorValues, mergeState.segmentInfo.maxDoc());
+ break;
}
return null;
}
@@ -216,6 +284,10 @@ public abstract class BufferingKnnVectorsWriter extends KnnVectorsWriter {
protected abstract void writeField(
FieldInfo fieldInfo, FloatVectorValues floatVectorValues, int maxDoc) throws IOException;
+ /** Write the provided float16 vector field */
+ protected abstract void writeField(
+ FieldInfo fieldInfo, Float16VectorValues float16VectorValues, int maxDoc) throws IOException;
+
/** Write the provided byte vector field */
protected abstract void writeField(
FieldInfo fieldInfo, ByteVectorValues byteVectorValues, int maxDoc) throws IOException;
@@ -312,6 +384,52 @@ public abstract class BufferingKnnVectorsWriter extends KnnVectorsWriter {
}
}
+ private static class BufferedFloat16VectorValues extends Float16VectorValues {
+ // These are always the vectors of a VectorValuesWriter, which are copied when added to it
+ final List<short[]> vectors;
+ final int dimension;
+ private final DocIdSet docsWithField;
+ private final DocIndexIterator iterator;
+
+ BufferedFloat16VectorValues(List<short[]> vectors, int dimension, DocIdSet docsWithField)
+ throws IOException {
+ this.vectors = vectors;
+ this.dimension = dimension;
+ this.docsWithField = docsWithField;
+ this.iterator = fromDISI(docsWithField.iterator());
+ }
+
+ @Override
+ public int dimension() {
+ return dimension;
+ }
+
+ @Override
+ public int size() {
+ return vectors.size();
+ }
+
+ @Override
+ public int ordToDoc(int ord) {
+ return ord;
+ }
+
+ @Override
+ public short[] vectorValue(int targetOrd) {
+ return vectors.get(targetOrd);
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return iterator;
+ }
+
+ @Override
+ public BufferedFloat16VectorValues copy() throws IOException {
+ return new BufferedFloat16VectorValues(vectors, dimension, docsWithField);
+ }
+ }
+
private static class BufferedByteVectorValues extends ByteVectorValues {
// These are always the vectors of a VectorValuesWriter, which are copied when added to it
final List<byte[]> vectors;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsFormat.java
index e29de34ef53..8d7205b66e0 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsFormat.java
@@ -22,6 +22,7 @@ import java.util.Map;
import java.util.Set;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.MergePolicy;
import org.apache.lucene.index.SegmentReadState;
@@ -139,6 +140,11 @@ public abstract class KnnVectorsFormat implements NamedSPILoader.NamedSPI {
throw new UnsupportedOperationException();
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void search(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {
@@ -151,6 +157,12 @@ public abstract class KnnVectorsFormat implements NamedSPILoader.NamedSPI {
throw new UnsupportedOperationException();
}
+ @Override
+ public void search(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public Map<String, Long> getOffHeapByteSize(FieldInfo fieldInfo) {
return Map.of();
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsReader.java
index 77454874934..768dd6efcd0 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsReader.java
@@ -24,6 +24,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.MergePolicy;
import org.apache.lucene.search.AcceptDocs;
@@ -73,6 +74,13 @@ public abstract class KnnVectorsReader implements Closeable {
*/
public abstract ByteVectorValues getByteVectorValues(String field) throws IOException;
+ /**
+ * Returns the {@link Float16VectorValues} for the given {@code field}. The behavior is undefined
+ * if the given field doesn't have KNN vectors enabled on its {@link FieldInfo}. The return value
+ * is never {@code null}.
+ */
+ public abstract Float16VectorValues getFloat16VectorValues(String field) throws IOException;
+
/**
* Return the k nearest neighbor documents as determined by comparison of their vector values for
* this field, to the given vector, by the field's similarity function. The score of each document
@@ -131,6 +139,35 @@ public abstract class KnnVectorsReader implements Closeable {
String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException;
+ /**
+ * Return the k nearest neighbor documents as determined by comparison of their vector values for
+ * this field, to the given vector, by the field's similarity function. The score of each document
+ * is derived from the vector similarity in a way that ensures scores are positive and that a
+ * larger score corresponds to a higher ranking.
+ *
+ * <p>The search is allowed to be approximate, meaning the results are not guaranteed to be the
+ * true k closest neighbors. For large values of k (for example when k is close to the total
+ * number of documents), the search may also retrieve fewer than k documents.
+ *
+ * <p>The returned {@link TopDocs} will contain a {@link ScoreDoc} for each nearest neighbor, in
+ * order of their similarity to the query vector (decreasing scores). The {@link TotalHits}
+ * contains the number of documents visited during the search. If the search stopped early because
+ * it hit {@code visitedLimit}, it is indicated through the relation {@code
+ * TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO}.
+ *
+ * <p>The behavior is undefined if the given field doesn't have KNN vectors enabled on its {@link
+ * FieldInfo}.
+ *
+ * @param field the vector field to search
+ * @param target the vector-valued query
+ * @param knnCollector a KnnResults collector and relevant settings for gathering vector results
+ * @param acceptDocs {@link Bits} that represents the allowed documents to match, or {@code null}
+ * if they are all allowed to match.
+ */
+ public abstract void search(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException;
+
/**
* Returns an instance optimized for merging. This instance may only be consumed in the thread
* that called {@link #getMergeInstance()}.
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsWriter.java
index 5a4413685ff..667caa74c44 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/KnnVectorsWriter.java
@@ -29,6 +29,7 @@ import org.apache.lucene.index.DocIDMerger;
import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.MergeState;
@@ -94,6 +95,17 @@ public abstract class KnnVectorsWriter implements Accountable, Closeable {
floatWriter.addValue(doc, mergedFloats.vectorValue(iter.index()));
}
}
+
+ case FLOAT16 -> {
+ KnnFieldVectorsWriter<short[]> floatWriter =
+ (KnnFieldVectorsWriter<short[]>) addField(fieldInfo);
+ Float16VectorValues mergedValues =
+ MergedVectorValues.mergeFloat16VectorValues(fieldInfo, mergeState);
+ KnnVectorValues.DocIndexIterator iter = mergedValues.iterator();
+ for (int doc = iter.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = iter.nextDoc()) {
+ floatWriter.addValue(doc, mergedValues.vectorValue(iter.index()));
+ }
+ }
}
return null;
}
@@ -184,6 +196,33 @@ public abstract class KnnVectorsWriter implements Accountable, Closeable {
}
}
+ /**
+ * Tracks state of one sub-reader of float16 vectors that we are merging.
+ *
+ * @lucene.internal
+ */
+ static class Float16VectorValuesSub extends DocIDMerger.Sub {
+
+ final Float16VectorValues values;
+ final KnnVectorValues.DocIndexIterator iterator;
+
+ Float16VectorValuesSub(MergeState.DocMap docMap, Float16VectorValues values) {
+ super(docMap);
+ this.values = values;
+ this.iterator = values.iterator();
+ assert iterator.docID() == -1;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ return iterator.nextDoc();
+ }
+
+ public int index() {
+ return iterator.index();
+ }
+ }
+
/**
* Tracks state of one sub-reader of byte vectors that we are merging.
*
@@ -337,6 +376,21 @@ public abstract class KnnVectorsWriter implements Accountable, Closeable {
mergeState);
}
+ /** Returns a merged view over all the segment's {@link Float16VectorValues}. */
+ public static Float16VectorValues mergeFloat16VectorValues(
+ FieldInfo fieldInfo, MergeState mergeState) throws IOException {
+ validateFieldEncoding(fieldInfo, VectorEncoding.FLOAT16);
+ return new MergedFloat16VectorValues(
+ mergeVectorValues(
+ mergeState.knnVectorsReaders,
+ mergeState.docMaps,
+ fieldInfo,
+ mergeState.fieldInfos,
+ knnVectorsReader -> knnVectorsReader.getFloat16VectorValues(fieldInfo.name),
+ Float16VectorValuesSub::new),
+ mergeState);
+ }
+
/** Returns a merged view over all the segment's {@link ByteVectorValues}. */
public static ByteVectorValues mergeByteVectorValues(FieldInfo fieldInfo, MergeState mergeState)
throws IOException {
@@ -456,6 +510,104 @@ public abstract class KnnVectorsWriter implements Accountable, Closeable {
}
}
+ static class MergedFloat16VectorValues extends Float16VectorValues {
+ private final List<Float16VectorValuesSub> subs;
+ private final DocIDMerger<Float16VectorValuesSub> docIdMerger;
+ private final int size;
+ private int docId = -1;
+ private int lastOrd = -1;
+ Float16VectorValuesSub current;
+
+ MergedFloat16VectorValues(List<Float16VectorValuesSub> subs, MergeState mergeState)
+ throws IOException {
+ this.subs = subs;
+ docIdMerger = DocIDMerger.of(subs, mergeState.needsIndexSort);
+ int totalSize = 0;
+ for (Float16VectorValuesSub sub : subs) {
+ totalSize += sub.values.size();
+ }
+ size = totalSize;
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return new DocIndexIterator() {
+ private int index = -1;
+
+ @Override
+ public int docID() {
+ return docId;
+ }
+
+ @Override
+ public int index() {
+ return index;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ current = docIdMerger.next();
+ if (current == null) {
+ docId = NO_MORE_DOCS;
+ index = NO_MORE_DOCS;
+ } else {
+ docId = current.mappedDocID;
+ ++lastOrd;
+ ++index;
+ }
+ return docId;
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public long cost() {
+ return size;
+ }
+ };
+ }
+
+ @Override
+ public short[] vectorValue(int ord) throws IOException {
+ if (ord != lastOrd) {
+ throw new IllegalStateException(
+ "only supports forward iteration with a single iterator: ord="
+ + ord
+ + ", lastOrd="
+ + lastOrd);
+ }
+ return current.values.vectorValue(current.index());
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ @Override
+ public int dimension() {
+ return subs.get(0).values.dimension();
+ }
+
+ @Override
+ public int ordToDoc(int ord) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public VectorScorer scorer(short[] target) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Float16VectorValues copy() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
/**
* Unified view over several segments containing byte vector values.
*
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/DefaultFlatVectorScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/DefaultFlatVectorScorer.java
index 6a94eef3377..6dba31f46a0 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/DefaultFlatVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/DefaultFlatVectorScorer.java
@@ -19,6 +19,7 @@ package org.apache.lucene.codecs.hnsw;
import java.io.IOException;
import org.apache.lucene.index.ByteVectorValues;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.VectorSimilarityFunction;
@@ -43,6 +44,9 @@ public class DefaultFlatVectorScorer implements FlatVectorsScorer {
case FLOAT32 -> {
return new FloatScoringSupplier((FloatVectorValues) vectorValues, similarityFunction);
}
+ case FLOAT16 -> {
+ return new Float16ScoringSupplier((Float16VectorValues) vectorValues, similarityFunction);
+ }
case BYTE -> {
return new ByteScoringSupplier((ByteVectorValues) vectorValues, similarityFunction);
}
@@ -82,6 +86,21 @@ public class DefaultFlatVectorScorer implements FlatVectorsScorer {
return new ByteVectorScorer((ByteVectorValues) vectorValues, target, similarityFunction);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ assert vectorValues instanceof Float16VectorValues;
+ if (target.length != vectorValues.dimension()) {
+ throw new IllegalArgumentException(
+ "vector query dimension: "
+ + target.length
+ + " differs from field dimension: "
+ + vectorValues.dimension());
+ }
+ return new Float16VectorScorer((Float16VectorValues) vectorValues, target, similarityFunction);
+ }
+
@Override
public String toString() {
return "DefaultFlatVectorScorer()";
@@ -168,6 +187,46 @@ public class DefaultFlatVectorScorer implements FlatVectorsScorer {
}
}
+ private static final class Float16ScoringSupplier implements RandomVectorScorerSupplier {
+ private final Float16VectorValues vectors;
+ private final Float16VectorValues targetVectors;
+ private final VectorSimilarityFunction similarityFunction;
+
+ private Float16ScoringSupplier(
+ Float16VectorValues vectors, VectorSimilarityFunction similarityFunction)
+ throws IOException {
+ this.vectors = vectors;
+ targetVectors = vectors.copy();
+ this.similarityFunction = similarityFunction;
+ }
+
+ @Override
+ public UpdateableRandomVectorScorer scorer() throws IOException {
+ short[] vector = new short[vectors.dimension()];
+ return new UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer(vectors) {
+ @Override
+ public float score(int node) throws IOException {
+ return similarityFunction.compare(vector, targetVectors.vectorValue(node));
+ }
+
+ @Override
+ public void setScoringOrdinal(int node) throws IOException {
+ System.arraycopy(targetVectors.vectorValue(node), 0, vector, 0, vector.length);
+ }
+ };
+ }
+
+ @Override
+ public RandomVectorScorerSupplier copy() throws IOException {
+ return new Float16ScoringSupplier(vectors, similarityFunction);
+ }
+
+ @Override
+ public String toString() {
+ return "Float16ScoringSupplier(similarityFunction=" + similarityFunction + ")";
+ }
+ }
+
/** A {@link RandomVectorScorer} for float vectors. */
private static class FloatVectorScorer extends RandomVectorScorer.AbstractRandomVectorScorer {
private final FloatVectorValues values;
@@ -188,6 +247,25 @@ public class DefaultFlatVectorScorer implements FlatVectorsScorer {
}
}
+ private static class Float16VectorScorer extends RandomVectorScorer.AbstractRandomVectorScorer {
+ private final Float16VectorValues values;
+ private final short[] query;
+ private final VectorSimilarityFunction similarityFunction;
+
+ public Float16VectorScorer(
+ Float16VectorValues values, short[] query, VectorSimilarityFunction similarityFunction) {
+ super(values);
+ this.values = values;
+ this.query = query;
+ this.similarityFunction = similarityFunction;
+ }
+
+ @Override
+ public float score(int node) throws IOException {
+ return similarityFunction.compare(query, values.vectorValue(node));
+ }
+ }
+
/** A {@link RandomVectorScorer} for byte vectors. */
private static class ByteVectorScorer extends RandomVectorScorer.AbstractRandomVectorScorer {
private final ByteVectorValues values;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatFieldVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatFieldVectorsWriter.java
index d9126cca055..2100f85f23d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatFieldVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatFieldVectorsWriter.java
@@ -22,6 +22,7 @@ import java.util.List;
import org.apache.lucene.codecs.KnnFieldVectorsWriter;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.DocsWithFieldSet;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.VectorEncoding;
@@ -52,8 +53,9 @@ public abstract class FlatFieldVectorsWriter<T> extends KnnFieldVectorsWriter<T>
@SuppressWarnings("unchecked")
public KnnVectorValues asKnnVectorValues(VectorEncoding encoding, int dim) throws IOException {
return switch (encoding) {
- case FLOAT32 -> FloatVectorValues.fromFloats((List<float[]>) getVectors(), dim);
case BYTE -> ByteVectorValues.fromBytes((List<byte[]>) getVectors(), dim);
+ case FLOAT16 -> Float16VectorValues.fromFloats16((List<short[]>) getVectors(), dim);
+ case FLOAT32 -> FloatVectorValues.fromFloats((List<float[]>) getVectors(), dim);
};
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsReader.java
index 850648409f9..7246edf591b 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsReader.java
@@ -59,6 +59,12 @@ public abstract class FlatVectorsReader extends KnnVectorsReader implements Acco
// don't scan stored field data. If we didn't index it, produce no search results
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ // don't scan stored field data. If we didn't index it, produce no search results
+ }
+
/**
* Returns a {@link RandomVectorScorer} for the given field and target vector.
*
@@ -81,6 +87,17 @@ public abstract class FlatVectorsReader extends KnnVectorsReader implements Acco
public abstract RandomVectorScorer getRandomVectorScorer(String field, byte[] target)
throws IOException;
+ /**
+ * Returns a {@link RandomVectorScorer} for the given field and target vector.
+ *
+ * @param field the field to search
+ * @param target the target vector
+ * @return a {@link RandomVectorScorer} for the given field and target vector.
+ * @throws IOException if an I/O error occurs when reading from the index.
+ */
+ public abstract RandomVectorScorer getRandomVectorScorer(String field, short[] target)
+ throws IOException;
+
/**
* Returns an instance optimized for merging. This instance may only be consumed in the thread
* that called {@link #getMergeInstance()}.
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsScorer.java
index 969c624c880..fc80a720dfd 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsScorer.java
@@ -68,6 +68,10 @@ public interface FlatVectorsScorer {
VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, byte[] target)
throws IOException;
+ RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException;
+
static void checkDimensions(int queryLen, int fieldLen) {
if (queryLen != fieldLen) {
throw new IllegalArgumentException(
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/PrefetchableFlatVectorScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/PrefetchableFlatVectorScorer.java
index eca64dea9f4..faa1051ef6d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/PrefetchableFlatVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/PrefetchableFlatVectorScorer.java
@@ -77,6 +77,15 @@ public class PrefetchableFlatVectorScorer implements FlatVectorsScorer {
flatVectorsScorer.getRandomVectorScorer(similarityFunction, vectorValues, target));
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ return new PrefetchableRandomVectorScorer(
+ (RandomVectorScorer.AbstractRandomVectorScorer)
+ flatVectorsScorer.getRandomVectorScorer(similarityFunction, vectorValues, target));
+ }
+
@Override
public String toString() {
return "PrefetchableFlatVectorScorer()";
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/ScalarQuantizedVectorScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/ScalarQuantizedVectorScorer.java
index aa8a1aac45b..fbb1d30bede 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/ScalarQuantizedVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/ScalarQuantizedVectorScorer.java
@@ -108,6 +108,13 @@ public class ScalarQuantizedVectorScorer implements FlatVectorsScorer {
return nonQuantizedDelegate.getRandomVectorScorer(similarityFunction, vectorValues, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ return nonQuantizedDelegate.getRandomVectorScorer(similarityFunction, vectorValues, target);
+ }
+
@Override
public String toString() {
return "ScalarQuantizedVectorScorer(" + "nonQuantizedDelegate=" + nonQuantizedDelegate + ')';
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorScorer.java
index 53d3363e64b..70dad47d928 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorScorer.java
@@ -107,6 +107,13 @@ public class Lucene104ScalarQuantizedVectorScorer implements FlatVectorsScorer {
return nonQuantizedDelegate.getRandomVectorScorer(similarityFunction, vectorValues, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ return nonQuantizedDelegate.getRandomVectorScorer(similarityFunction, vectorValues, target);
+ }
+
public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
VectorSimilarityFunction similarityFunction,
QuantizedByteVectorValues scoringVectors,
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java
index 946b1745fc6..ef458b05162 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsReader.java
@@ -37,6 +37,7 @@ import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.KnnVectorValues;
@@ -221,6 +222,11 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader
return rawVectorsReader.getRandomVectorScorer(field, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(String field, short[] target) throws IOException {
+ return rawVectorsReader.getRandomVectorScorer(field, target);
+ }
+
@Override
public void checkIntegrity(MergePolicy.OneMerge merge) throws IOException {
rawVectorsReader.checkIntegrity(merge);
@@ -281,6 +287,11 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader
return rawVectorsReader.getByteVectorValues(field);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ return rawVectorsReader.getFloat16VectorValues(field);
+ }
+
@Override
public void search(String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException {
@@ -328,6 +339,12 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader
}
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ rawVectorsReader.search(field, target, knnCollector, acceptDocs);
+ }
+
@Override
public void close() throws IOException {
IOUtils.close(quantizedVectorData, rawVectorsReader);
@@ -349,7 +366,10 @@ public class Lucene104ScalarQuantizedVectorsReader extends FlatVectorsReader
var raw = rawVectorsReader.getOffHeapByteSize(fieldInfo);
var fieldEntry = fields.get(fieldInfo.name);
if (fieldEntry == null) {
- assert fieldInfo.getVectorEncoding() == VectorEncoding.BYTE;
+ // Only FLOAT32 fields are scalar-quantized by this format; BYTE and FLOAT16 fields are
+ // stored raw by the delegate and therefore have no quantized field entry here.
+ assert fieldInfo.getVectorEncoding() == VectorEncoding.BYTE
+ || fieldInfo.getVectorEncoding() == VectorEncoding.FLOAT16;
return raw;
}
var quant = Map.of(VECTOR_DATA_EXTENSION, fieldEntry.vectorDataLength());
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene95/OffHeapFloat16VectorValues.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene95/OffHeapFloat16VectorValues.java
new file mode 100644
index 00000000000..ab57500b386
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene95/OffHeapFloat16VectorValues.java
@@ -0,0 +1,331 @@
+/*
+ * 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.codecs.lucene95;
+
+import java.io.IOException;
+import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
+import org.apache.lucene.codecs.lucene90.IndexedDISI;
+import org.apache.lucene.index.Float16VectorValues;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.VectorScorer;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.RandomAccessInput;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.packed.DirectMonotonicReader;
+
+/** Read the vector values from the index input. This supports both iterated and random access. */
+public abstract class OffHeapFloat16VectorValues extends Float16VectorValues
+ implements HasIndexSlice {
+
+ protected final int dimension;
+ protected final int size;
+ protected final IndexInput slice;
+ protected final int byteSize;
+ protected int lastOrd = -1;
+ protected final short[] value;
+ protected final VectorSimilarityFunction similarityFunction;
+ protected final FlatVectorsScorer flatVectorsScorer;
+
+ OffHeapFloat16VectorValues(
+ int dimension,
+ int size,
+ IndexInput slice,
+ int byteSize,
+ FlatVectorsScorer flatVectorsScorer,
+ VectorSimilarityFunction similarityFunction) {
+ this.dimension = dimension;
+ this.size = size;
+ this.slice = slice;
+ this.byteSize = byteSize;
+ this.similarityFunction = similarityFunction;
+ this.flatVectorsScorer = flatVectorsScorer;
+ value = new short[dimension];
+ }
+
+ @Override
+ public int dimension() {
+ return dimension;
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ @Override
+ public IndexInput getSlice() {
+ return slice;
+ }
+
+ @Override
+ public short[] vectorValue(int targetOrd) throws IOException {
+ if (lastOrd == targetOrd) {
+ return value;
+ }
+ slice.seek((long) targetOrd * byteSize);
+ slice.readShorts(value, 0, dimension);
+ lastOrd = targetOrd;
+ return value;
+ }
+
+ @Override
+ public VectorEncoding getEncoding() {
+ return VectorEncoding.FLOAT16;
+ }
+
+ public static OffHeapFloat16VectorValues load(
+ VectorSimilarityFunction vectorSimilarityFunction,
+ FlatVectorsScorer flatVectorsScorer,
+ OrdToDocDISIReaderConfiguration configuration,
+ VectorEncoding vectorEncoding,
+ int dimension,
+ long vectorDataOffset,
+ long vectorDataLength,
+ IndexInput vectorData)
+ throws IOException {
+ if (configuration.docsWithFieldOffset == -2 || vectorEncoding != VectorEncoding.FLOAT16) {
+ return new EmptyOffHeapVectorValues(dimension, flatVectorsScorer, vectorSimilarityFunction);
+ }
+ IndexInput bytesSlice = vectorData.slice("vector-data", vectorDataOffset, vectorDataLength);
+ int byteSize = dimension * Short.BYTES;
+
+ if (configuration.docsWithFieldOffset == -1) {
+ return new DenseOffHeapVectorValues(
+ dimension,
+ configuration.size,
+ bytesSlice,
+ byteSize,
+ flatVectorsScorer,
+ vectorSimilarityFunction);
+ } else {
+ return new SparseOffHeapVectorValues(
+ configuration,
+ vectorData,
+ bytesSlice,
+ dimension,
+ byteSize,
+ flatVectorsScorer,
+ vectorSimilarityFunction);
+ }
+ }
+
+ /** Dense vector values that are stored off-heap. This is the case when every doc has a vector. */
+ public static class DenseOffHeapVectorValues extends OffHeapFloat16VectorValues {
+
+ public DenseOffHeapVectorValues(
+ int dimension,
+ int size,
+ IndexInput slice,
+ int byteSize,
+ FlatVectorsScorer flatVectorsScorer,
+ VectorSimilarityFunction similarityFunction) {
+ super(dimension, size, slice, byteSize, flatVectorsScorer, similarityFunction);
+ }
+
+ @Override
+ public DenseOffHeapVectorValues copy() throws IOException {
+ return new DenseOffHeapVectorValues(
+ dimension, size, slice.clone(), byteSize, flatVectorsScorer, similarityFunction);
+ }
+
+ @Override
+ public int ordToDoc(int ord) {
+ return ord;
+ }
+
+ @Override
+ public Bits getAcceptOrds(Bits acceptDocs) {
+ return acceptDocs;
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return createDenseIterator();
+ }
+
+ @Override
+ public VectorScorer scorer(short[] query) throws IOException {
+ DenseOffHeapVectorValues copy = copy();
+ DocIndexIterator iterator = copy.iterator();
+ RandomVectorScorer randomVectorScorer =
+ flatVectorsScorer.getRandomVectorScorer(similarityFunction, copy, query);
+ return new VectorScorer() {
+ @Override
+ public float score() throws IOException {
+ return randomVectorScorer.score(iterator.docID());
+ }
+
+ @Override
+ public DocIdSetIterator iterator() {
+ return iterator;
+ }
+
+ @Override
+ public VectorScorer.Bulk bulk(DocIdSetIterator matchingDocs) {
+ return Bulk.fromRandomScorerDense(randomVectorScorer, iterator, matchingDocs);
+ }
+ };
+ }
+ }
+
+ private static class SparseOffHeapVectorValues extends OffHeapFloat16VectorValues {
+ private final DirectMonotonicReader ordToDoc;
+ private final IndexedDISI disi;
+ // dataIn was used to init a new IndexedDISI for #randomAccess()
+ private final IndexInput dataIn;
+ private final OrdToDocDISIReaderConfiguration configuration;
+
+ public SparseOffHeapVectorValues(
+ OrdToDocDISIReaderConfiguration configuration,
+ IndexInput dataIn,
+ IndexInput slice,
+ int dimension,
+ int byteSize,
+ FlatVectorsScorer flatVectorsScorer,
+ VectorSimilarityFunction similarityFunction)
+ throws IOException {
+
+ super(dimension, configuration.size, slice, byteSize, flatVectorsScorer, similarityFunction);
+ this.configuration = configuration;
+ final RandomAccessInput addressesData =
+ dataIn.randomAccessSlice(configuration.addressesOffset, configuration.addressesLength);
+ this.dataIn = dataIn;
+ this.ordToDoc = DirectMonotonicReader.getInstance(configuration.meta, addressesData);
+ this.disi =
+ new IndexedDISI(
+ dataIn,
+ configuration.docsWithFieldOffset,
+ configuration.docsWithFieldLength,
+ configuration.jumpTableEntryCount,
+ configuration.denseRankPower,
+ configuration.size);
+ }
+
+ @Override
+ public SparseOffHeapVectorValues copy() throws IOException {
+ return new SparseOffHeapVectorValues(
+ configuration,
+ dataIn,
+ slice.clone(),
+ dimension,
+ byteSize,
+ flatVectorsScorer,
+ similarityFunction);
+ }
+
+ @Override
+ public int ordToDoc(int ord) {
+ return (int) ordToDoc.get(ord);
+ }
+
+ @Override
+ public Bits getAcceptOrds(Bits acceptDocs) {
+ if (acceptDocs == null) {
+ return null;
+ }
+ return new Bits() {
+ @Override
+ public boolean get(int index) {
+ return acceptDocs.get(ordToDoc(index));
+ }
+
+ @Override
+ public int length() {
+ return size;
+ }
+ };
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return IndexedDISI.asDocIndexIterator(disi);
+ }
+
+ @Override
+ public VectorScorer scorer(short[] query) throws IOException {
+ SparseOffHeapVectorValues copy = copy();
+ DocIndexIterator iterator = copy.iterator();
+ RandomVectorScorer randomVectorScorer =
+ flatVectorsScorer.getRandomVectorScorer(similarityFunction, copy, query);
+ return new VectorScorer() {
+ @Override
+ public float score() throws IOException {
+ return randomVectorScorer.score(iterator.index());
+ }
+
+ @Override
+ public DocIdSetIterator iterator() {
+ return iterator;
+ }
+
+ @Override
+ public VectorScorer.Bulk bulk(DocIdSetIterator matchingDocs) {
+ return Bulk.fromRandomScorerSparse(randomVectorScorer, iterator, matchingDocs);
+ }
+ };
+ }
+ }
+
+ private static class EmptyOffHeapVectorValues extends OffHeapFloat16VectorValues {
+
+ public EmptyOffHeapVectorValues(
+ int dimension,
+ FlatVectorsScorer flatVectorsScorer,
+ VectorSimilarityFunction similarityFunction) {
+ super(dimension, 0, null, 0, flatVectorsScorer, similarityFunction);
+ }
+
+ @Override
+ public int dimension() {
+ return super.dimension();
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public EmptyOffHeapVectorValues copy() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public short[] vectorValue(int targetOrd) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return createDenseIterator();
+ }
+
+ @Override
+ public Bits getAcceptOrds(Bits acceptDocs) {
+ return null;
+ }
+
+ @Override
+ public VectorScorer scorer(short[] query) {
+ return null;
+ }
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsReader.java
index f2c0b7fa47c..ad046ae64da 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsReader.java
@@ -28,12 +28,14 @@ import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.hnsw.FlatVectorsReader;
import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
import org.apache.lucene.codecs.lucene95.OffHeapByteVectorValues;
+import org.apache.lucene.codecs.lucene95.OffHeapFloat16VectorValues;
import org.apache.lucene.codecs.lucene95.OffHeapFloatVectorValues;
import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -253,6 +255,20 @@ public final class Lucene99FlatVectorsReader extends FlatVectorsReader {
vectorData);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ final FieldEntry fieldEntry = getFieldEntry(field, VectorEncoding.FLOAT16);
+ return OffHeapFloat16VectorValues.load(
+ fieldEntry.similarityFunction,
+ vectorScorer,
+ fieldEntry.ordToDoc,
+ fieldEntry.vectorEncoding,
+ fieldEntry.dimension,
+ fieldEntry.vectorDataOffset,
+ fieldEntry.vectorDataLength,
+ vectorData);
+ }
+
@Override
public FlatVectorsScorer getFlatVectorScorer(String field) throws IOException {
return vectorScorer;
@@ -292,6 +308,24 @@ public final class Lucene99FlatVectorsReader extends FlatVectorsReader {
target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(String field, short[] target) throws IOException {
+
+ final FieldEntry fieldEntry = getFieldEntry(field, VectorEncoding.FLOAT16);
+ return vectorScorer.getRandomVectorScorer(
+ fieldEntry.similarityFunction,
+ OffHeapFloat16VectorValues.load(
+ fieldEntry.similarityFunction,
+ vectorScorer,
+ fieldEntry.ordToDoc,
+ fieldEntry.vectorEncoding,
+ fieldEntry.dimension,
+ fieldEntry.vectorDataOffset,
+ fieldEntry.vectorDataLength,
+ vectorData),
+ target);
+ }
+
@Override
public void finishMerge() throws IOException {
// This makes sure that the access pattern hint is reverted back since HNSW implementation
@@ -338,6 +372,7 @@ public final class Lucene99FlatVectorsReader extends FlatVectorsReader {
int byteSize =
switch (info.getVectorEncoding()) {
case BYTE -> Byte.BYTES;
+ case FLOAT16 -> Short.BYTES;
case FLOAT32 -> Float.BYTES;
};
long vectorBytes = Math.multiplyExact((long) infoVectorDimension, byteSize);
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java
index 4afe4150731..d63d494c7f0 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99FlatVectorsWriter.java
@@ -23,6 +23,7 @@ import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
+import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.codecs.CodecUtil;
@@ -34,6 +35,7 @@ import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.DocsWithFieldSet;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.KnnVectorValues;
@@ -181,6 +183,7 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
return output.alignFilePointer(
switch (encoding) {
case BYTE -> Float.BYTES;
+ case FLOAT16 -> Float.BYTES;
case FLOAT32 -> 64; // optimal alignment for Arm Neoverse machines.
});
}
@@ -192,6 +195,7 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
long vectorDataOffset = alignOutput(vectorData, encoding);
switch (encoding) {
case BYTE -> writeByteVectors(fieldWriter);
+ case FLOAT16 -> writeFloat16Vectors(fieldWriter, fieldInfo);
case FLOAT32 -> writeFloat32Vectors(fieldWriter, fieldInfo);
}
long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
@@ -211,6 +215,19 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
}
}
+ private void writeFloat16Vectors(FlatFieldVectorsWriter<?> fieldWriter, FieldInfo fieldInfo)
+ throws IOException {
+ final ByteBuffer buffer =
+ ByteBuffer.allocate(fieldInfo.getVectorDimension() * Short.BYTES)
+ .order(ByteOrder.LITTLE_ENDIAN);
+ final ShortBuffer shortBuffer = buffer.asShortBuffer();
+ for (Object v : fieldWriter.getVectors()) {
+ shortBuffer.rewind();
+ shortBuffer.put((short[]) v);
+ vectorData.writeBytes(buffer.array(), buffer.array().length);
+ }
+ }
+
private void writeByteVectors(FlatFieldVectorsWriter<?> fieldWriter) throws IOException {
for (Object v : fieldWriter.getVectors()) {
byte[] vector = (byte[]) v;
@@ -232,6 +249,7 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
long vectorDataOffset = alignOutput(vectorData, encoding);
switch (encoding) {
case BYTE -> writeSortedByteVectors(fieldWriter, ordMap);
+ case FLOAT16 -> writeSortedFloat16Vectors(fieldWriter, fieldInfo, ordMap);
case FLOAT32 -> writeSortedFloat32Vectors(fieldWriter, fieldInfo, ordMap);
}
long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset;
@@ -251,6 +269,20 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
}
}
+ private void writeSortedFloat16Vectors(
+ FlatFieldVectorsWriter<?> fieldWriter, FieldInfo fieldInfo, int[] ordMap) throws IOException {
+ final ByteBuffer buffer =
+ ByteBuffer.allocate(fieldInfo.getVectorDimension() * Short.BYTES)
+ .order(ByteOrder.LITTLE_ENDIAN);
+ final ShortBuffer shortBuffer = buffer.asShortBuffer();
+ for (int ordinal : ordMap) {
+ short[] vector = (short[]) fieldWriter.getVectors().get(ordinal);
+ shortBuffer.rewind();
+ shortBuffer.put(vector);
+ vectorData.writeBytes(buffer.array(), buffer.array().length);
+ }
+ }
+
private void writeSortedByteVectors(FlatFieldVectorsWriter<?> fieldWriter, int[] ordMap)
throws IOException {
for (int ordinal : ordMap) {
@@ -273,6 +305,11 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
writeByteVectorData(
vectorData,
KnnVectorsWriter.MergedVectorValues.mergeByteVectorValues(fieldInfo, mergeState));
+ case FLOAT16 ->
+ writeFloat16VectorData(
+ vectorData,
+ KnnVectorsWriter.MergedVectorValues.mergeFloat16VectorValues(
+ fieldInfo, mergeState));
case FLOAT32 ->
writeVectorData(
vectorData,
@@ -347,6 +384,28 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
return docsWithField;
}
+ /**
+ * Writes the vector values to the output and returns a set of documents that contains vectors.
+ */
+ private static DocsWithFieldSet writeFloat16VectorData(
+ IndexOutput output, Float16VectorValues float16VectorValues) throws IOException {
+ DocsWithFieldSet docsWithField = new DocsWithFieldSet();
+ ByteBuffer buffer =
+ ByteBuffer.allocate(float16VectorValues.dimension() * VectorEncoding.FLOAT16.byteSize)
+ .order(ByteOrder.LITTLE_ENDIAN);
+ ShortBuffer shortBuffer = buffer.asShortBuffer();
+ KnnVectorValues.DocIndexIterator iter = float16VectorValues.iterator();
+ for (int docV = iter.nextDoc(); docV != NO_MORE_DOCS; docV = iter.nextDoc()) {
+ // write vector
+ short[] value = float16VectorValues.vectorValue(iter.index());
+ shortBuffer.rewind();
+ shortBuffer.put(value);
+ output.writeBytes(buffer.array(), buffer.limit());
+ docsWithField.add(docV);
+ }
+ return docsWithField;
+ }
+
@Override
public void close() throws IOException {
IOUtils.close(meta, vectorData);
@@ -378,6 +437,13 @@ public final class Lucene99FlatVectorsWriter extends FlatVectorsWriter {
return ArrayUtil.copyOfSubArray(value, 0, dim);
}
};
+ case FLOAT16 ->
+ new DefaultFieldWriter<short[]>(fieldInfo) {
+ @Override
+ public short[] copyValue(short[] value) {
+ return ArrayUtil.copyOfSubArray(value, 0, dim);
+ }
+ };
case FLOAT32 ->
new DefaultFieldWriter<float[]>(fieldInfo) {
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsReader.java
index 7078b365b45..59b76694874 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsReader.java
@@ -32,6 +32,7 @@ import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -278,6 +279,11 @@ public final class Lucene99HnswVectorsReader extends KnnVectorsReader
return flatVectorsReader.getByteVectorValues(field);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ return flatVectorsReader.getFloat16VectorValues(field);
+ }
+
private FieldEntry getFieldEntryOrThrow(String field) {
final FieldInfo info = fieldInfos.fieldInfo(field);
final FieldEntry entry;
@@ -323,6 +329,17 @@ public final class Lucene99HnswVectorsReader extends KnnVectorsReader
() -> flatVectorsReader.getRandomVectorScorer(field, target));
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ final FieldEntry fieldEntry = getFieldEntry(field, VectorEncoding.FLOAT16);
+ search(
+ fieldEntry,
+ knnCollector,
+ acceptDocs,
+ () -> flatVectorsReader.getRandomVectorScorer(field, target));
+ }
+
private void search(
FieldEntry fieldEntry,
KnnCollector knnCollector,
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java
index 0b0bf5bda50..ef3c6f700b6 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99HnswVectorsWriter.java
@@ -425,6 +425,7 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
KnnVectorValues vectorValues =
switch (fieldInfo.getVectorEncoding()) {
case BYTE -> flatVectorsReader.getByteVectorValues(fieldInfo.name);
+ case FLOAT16 -> flatVectorsReader.getFloat16VectorValues(fieldInfo.name);
case FLOAT32 -> flatVectorsReader.getFloatVectorValues(fieldInfo.name);
};
int totalVectorCount = vectorValues == null ? 0 : vectorValues.size();
@@ -708,6 +709,15 @@ public final class Lucene99HnswVectorsWriter extends KnnVectorsWriter {
beamWidth,
infoStream,
tinySegmentsThreshold);
+ case FLOAT16 ->
+ new FieldWriter<>(
+ scorer,
+ (FlatFieldVectorsWriter<short[]>) flatFieldVectorsWriter,
+ fieldInfo,
+ M,
+ beamWidth,
+ infoStream,
+ tinySegmentsThreshold);
case FLOAT32 ->
new FieldWriter<>(
scorer,
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorScorer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorScorer.java
index 57f5b77f290..79560da1c9e 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene99/Lucene99ScalarQuantizedVectorScorer.java
@@ -85,6 +85,14 @@ public class Lucene99ScalarQuantizedVectorScorer implements FlatVectorsScorer {
return nonQuantizedDelegate.getRandomVectorScorer(similarityFunction, vectorValues, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ // It is possible to get to this branch during initial indexing and flush
+ return nonQuantizedDelegate.getRandomVectorScorer(similarityFunction, vectorValues, target);
+ }
+
@Override
public String toString() {
return "ScalarQuantizedVectorScorer(" + "nonQuantizedDelegate=" + nonQuantizedDelegate + ')';
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldKnnVectorsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldKnnVectorsFormat.java
index 1e7f8931670..adc6c786982 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldKnnVectorsFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldKnnVectorsFormat.java
@@ -32,6 +32,7 @@ import org.apache.lucene.codecs.hnsw.HnswGraphProvider;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.MergePolicy;
import org.apache.lucene.index.MergeState;
@@ -294,6 +295,16 @@ public abstract class PerFieldKnnVectorsFormat extends KnnVectorsFormat {
return reader.getByteVectorValues(field);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ final FieldInfo info = fieldInfos.fieldInfo(field);
+ final KnnVectorsReader reader;
+ if (info == null || (reader = fields.get(info.number)) == null) {
+ return null;
+ }
+ return reader.getFloat16VectorValues(field);
+ }
+
@Override
public void search(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
@@ -318,6 +329,18 @@ public abstract class PerFieldKnnVectorsFormat extends KnnVectorsFormat {
reader.search(field, target, knnCollector, acceptDocs);
}
+ @Override
+ public void search(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ final FieldInfo info = fieldInfos.fieldInfo(field);
+ final KnnVectorsReader reader;
+ if (info == null || (reader = fields.get(info.number)) == null) {
+ return;
+ }
+ reader.search(field, target, knnCollector, acceptDocs);
+ }
+
@Override
public HnswGraph getGraph(String field) throws IOException {
final FieldInfo info = fieldInfos.fieldInfo(field);
diff --git a/lucene/core/src/java/org/apache/lucene/document/KnnFloat16VectorField.java b/lucene/core/src/java/org/apache/lucene/document/KnnFloat16VectorField.java
new file mode 100644
index 00000000000..276f3d80a44
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/document/KnnFloat16VectorField.java
@@ -0,0 +1,91 @@
+/*
+ * 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.document;
+
+import org.apache.lucene.index.Float16VectorValues;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.util.VectorUtil;
+
+/**
+ * A field that contains a single float16 numeric vector (or none) for each document. Vectors are
+ * dense - that is, every dimension of a vector contains an explicit value, stored packed into an
+ * array (of type short[]) whose length is the vector dimension. Values can be retrieved using
+ * {@link Float16VectorValues}, which is a forward-only docID-based iterator and also offers
+ * random-access by dense ordinal (not docId). {@link VectorSimilarityFunction} may be used to
+ * compare vectors at query time (for example as part of result ranking). A {@link
+ * KnnFloat16VectorField} is associated with a search similarity function defining the metric used
+ * for nearest-neighbor search among vectors of that field.
+ *
+ * @lucene.experimental
+ */
+public class KnnFloat16VectorField extends Field {
+
+ private static FieldType createType(short[] v, VectorSimilarityFunction similarityFunction) {
+ if (v == null) {
+ throw new IllegalArgumentException("vector value must not be null");
+ }
+ int dimension = v.length;
+ if (dimension == 0) {
+ throw new IllegalArgumentException("cannot index an empty vector");
+ }
+ if (similarityFunction == null) {
+ throw new IllegalArgumentException("similarity function must not be null");
+ }
+ FieldType type = new FieldType();
+ type.setVectorAttributes(dimension, VectorEncoding.FLOAT16, similarityFunction);
+ type.freeze();
+ return type;
+ }
+
+ /**
+ * Creates a numeric vector field. Fields are single-valued: each document has either one value or
+ * no value. Vectors of a single field share the same dimension and similarity function.
+ *
+ * @param name field name
+ * @param vector value
+ * @param similarityFunction a function defining vector proximity.
+ * @throws IllegalArgumentException if any parameter is null, or the vector is empty
+ */
+ public KnnFloat16VectorField(
+ String name, short[] vector, VectorSimilarityFunction similarityFunction) {
+ super(name, createType(vector, similarityFunction));
+ fieldsData = VectorUtil.checkFiniteFloat16(vector); // null check done above
+ }
+
+ /** Return the vector value of this field */
+ public short[] vectorValue() {
+ return (short[]) fieldsData;
+ }
+
+ /**
+ * Set the vector value of this field
+ *
+ * @param value the value to set; must not be null, and length must match the field type
+ */
+ public void setVectorValue(short[] value) {
+ if (value == null) {
+ throw new IllegalArgumentException("value must not be null");
+ }
+ if (value.length != type.vectorDimension()) {
+ throw new IllegalArgumentException(
+ "value length " + value.length + " must match field dimension " + type.vectorDimension());
+ }
+ fieldsData = VectorUtil.checkFiniteFloat16(value);
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
index 303698149b8..8939c5b59c9 100644
--- a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
+++ b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
@@ -2857,6 +2857,13 @@ public final class CheckIndex implements Closeable {
status,
reader);
break;
+ case FLOAT16:
+ checkFloat16VectorValues(
+ Objects.requireNonNull(reader.getFloat16VectorValues(fieldInfo.name)),
+ fieldInfo,
+ status,
+ reader);
+ break;
case FLOAT32:
checkFloatVectorValues(
Objects.requireNonNull(reader.getFloatVectorValues(fieldInfo.name)),
@@ -3136,6 +3143,58 @@ public final class CheckIndex implements Closeable {
status.totalVectorValues += count;
}
+ private static void checkFloat16VectorValues(
+ Float16VectorValues values,
+ FieldInfo fieldInfo,
+ CheckIndex.Status.VectorValuesStatus status,
+ CodecReader codecReader)
+ throws IOException {
+ int count = 0;
+ int everyNdoc = Math.max(values.size() / 64, 1);
+ while (count < values.size()) {
+ // search the first maxNumSearches vectors to exercise the graph
+ if (values.ordToDoc(count) % everyNdoc == 0) {
+ KnnCollector collector = new TopKnnCollector(10, Integer.MAX_VALUE);
+ if (vectorsReaderSupportsSearch(codecReader, fieldInfo.name)) {
+ codecReader
+ .getVectorReader()
+ .search(
+ fieldInfo.name,
+ values.vectorValue(count),
+ collector,
+ AcceptDocs.fromLiveDocs(null, codecReader.maxDoc()));
+ TopDocs docs = collector.topDocs();
+ if (docs.scoreDocs.length == 0) {
+ throw new CheckIndexException(
+ "Field \"" + fieldInfo.name + "\" failed to search k nearest neighbors");
+ }
+ }
+ }
+ int valueLength = values.vectorValue(count).length;
+ if (valueLength != fieldInfo.getVectorDimension()) {
+ throw new CheckIndexException(
+ "Field \""
+ + fieldInfo.name
+ + "\" has a value whose dimension="
+ + valueLength
+ + " not matching the field's dimension="
+ + fieldInfo.getVectorDimension());
+ }
+ ++count;
+ }
+ if (count != values.size()) {
+ throw new CheckIndexException(
+ "Field \""
+ + fieldInfo.name
+ + "\" has size="
+ + values.size()
+ + " but when iterated, returns "
+ + count
+ + " docs with values");
+ }
+ status.totalVectorValues += count;
+ }
+
private static void checkByteVectorValues(
ByteVectorValues values,
FieldInfo fieldInfo,
diff --git a/lucene/core/src/java/org/apache/lucene/index/CodecReader.java b/lucene/core/src/java/org/apache/lucene/index/CodecReader.java
index 4f7a1ea213e..8f0eccf3a08 100644
--- a/lucene/core/src/java/org/apache/lucene/index/CodecReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/CodecReader.java
@@ -258,6 +258,20 @@ public abstract class CodecReader extends LeafReader {
return getVectorReader().getByteVectorValues(field);
}
+ @Override
+ public final Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ ensureOpen();
+ FieldInfo fi = getFieldInfos().fieldInfo(field);
+ if (fi == null
+ || fi.getVectorDimension() == 0
+ || fi.getVectorEncoding() != VectorEncoding.FLOAT16) {
+ // Field does not exist or does not index vectors
+ return null;
+ }
+
+ return getVectorReader().getFloat16VectorValues(field);
+ }
+
@Override
public final void searchNearestVectors(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
@@ -266,7 +280,22 @@ public abstract class CodecReader extends LeafReader {
FieldInfo fi = getFieldInfos().fieldInfo(field);
if (fi == null
|| fi.getVectorDimension() == 0
- || fi.getVectorEncoding() != VectorEncoding.FLOAT32) {
+ || (fi.getVectorEncoding() != VectorEncoding.FLOAT32)) {
+ // Field does not exist or does not index vectors
+ return;
+ }
+ getVectorReader().search(field, target, knnCollector, acceptDocs);
+ }
+
+ @Override
+ public final void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ ensureOpen();
+ FieldInfo fi = getFieldInfos().fieldInfo(field);
+ if (fi == null
+ || fi.getVectorDimension() == 0
+ || fi.getVectorEncoding() != VectorEncoding.FLOAT16) {
// Field does not exist or does not index vectors
return;
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocValuesLeafReader.java b/lucene/core/src/java/org/apache/lucene/index/DocValuesLeafReader.java
index 86f9482606d..6ee69b2c13e 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocValuesLeafReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocValuesLeafReader.java
@@ -58,6 +58,11 @@ abstract class DocValuesLeafReader extends LeafReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public final Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void searchNearestVectors(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
@@ -72,6 +77,13 @@ abstract class DocValuesLeafReader extends LeafReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public final void checkIntegrity() throws IOException {
throw new UnsupportedOperationException();
diff --git a/lucene/core/src/java/org/apache/lucene/index/ExitableDirectoryReader.java b/lucene/core/src/java/org/apache/lucene/index/ExitableDirectoryReader.java
index ef58d3d1136..d437df74a62 100644
--- a/lucene/core/src/java/org/apache/lucene/index/ExitableDirectoryReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/ExitableDirectoryReader.java
@@ -338,6 +338,15 @@ public class ExitableDirectoryReader extends FilterDirectoryReader {
return new ExitableFloatVectorValues(vectorValues);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ final Float16VectorValues vectorValues = in.getFloat16VectorValues(field);
+ if (vectorValues == null) {
+ return null;
+ }
+ return new ExitableFloat16VectorValues(vectorValues);
+ }
+
@Override
public ByteVectorValues getByteVectorValues(String field) throws IOException {
final ByteVectorValues vectorValues = in.getByteVectorValues(field);
@@ -428,6 +437,14 @@ public class ExitableDirectoryReader extends FilterDirectoryReader {
in.searchNearestVectors(field, target, knnCollector, timeoutCheckingAcceptDocs);
}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ AcceptDocs timeoutCheckingAcceptDocs = new ExitableAcceptDocs(acceptDocs);
+ in.searchNearestVectors(field, target, knnCollector, timeoutCheckingAcceptDocs);
+ }
+
@Override
public void searchNearestVectors(
String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
@@ -511,6 +528,49 @@ public class ExitableDirectoryReader extends FilterDirectoryReader {
}
}
+ private class ExitableFloat16VectorValues extends Float16VectorValues {
+ private final Float16VectorValues vectorValues;
+
+ public ExitableFloat16VectorValues(Float16VectorValues vectorValues) {
+ this.vectorValues = vectorValues;
+ }
+
+ @Override
+ public int dimension() {
+ return vectorValues.dimension();
+ }
+
+ @Override
+ public short[] vectorValue(int ord) throws IOException {
+ return vectorValues.vectorValue(ord);
+ }
+
+ @Override
+ public int ordToDoc(int ord) {
+ return vectorValues.ordToDoc(ord);
+ }
+
+ @Override
+ public int size() {
+ return vectorValues.size();
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return createExitableIterator(vectorValues.iterator(), queryTimeout);
+ }
+
+ @Override
+ public VectorScorer scorer(short[] target) throws IOException {
+ return vectorValues.scorer(target);
+ }
+
+ @Override
+ public Float16VectorValues copy() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
private class ExitableByteVectorValues extends ByteVectorValues {
private final ByteVectorValues vectorValues;
diff --git a/lucene/core/src/java/org/apache/lucene/index/FilterLeafReader.java b/lucene/core/src/java/org/apache/lucene/index/FilterLeafReader.java
index e571f890c32..88a89bef3c8 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FilterLeafReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FilterLeafReader.java
@@ -358,6 +358,11 @@ public abstract class FilterLeafReader extends LeafReader {
return in.getFloatVectorValues(field);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ return in.getFloat16VectorValues(field);
+ }
+
@Override
public ByteVectorValues getByteVectorValues(String field) throws IOException {
return in.getByteVectorValues(field);
@@ -370,6 +375,13 @@ public abstract class FilterLeafReader extends LeafReader {
in.searchNearestVectors(field, target, knnCollector, acceptDocs);
}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ in.searchNearestVectors(field, target, knnCollector, acceptDocs);
+ }
+
@Override
public void searchNearestVectors(
String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
diff --git a/lucene/core/src/java/org/apache/lucene/index/Float16VectorValues.java b/lucene/core/src/java/org/apache/lucene/index/Float16VectorValues.java
new file mode 100644
index 00000000000..06815fd8e93
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/index/Float16VectorValues.java
@@ -0,0 +1,136 @@
+/*
+ * 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.index;
+
+import java.io.IOException;
+import java.util.List;
+import org.apache.lucene.document.KnnFloat16VectorField;
+import org.apache.lucene.search.VectorScorer;
+
+/**
+ * This class provides access to per-document float16 vector values indexed as {@link
+ * KnnFloat16VectorField}.
+ *
+ * @lucene.experimental
+ */
+public abstract class Float16VectorValues extends KnnVectorValues {
+
+ /** Sole constructor */
+ protected Float16VectorValues() {}
+
+ /**
+ * Return the vector value for the given vector ordinal which must be in [0, size() - 1],
+ * otherwise IndexOutOfBoundsException is thrown. The returned array may be shared across calls.
+ *
+ * @return the vector value
+ */
+ public abstract short[] vectorValue(int ord) throws IOException;
+
+ @Override
+ public abstract Float16VectorValues copy() throws IOException;
+
+ /**
+ * Checks the Vector Encoding of a field
+ *
+ * @throws IllegalStateException if {@code field} has vectors, but using a different encoding
+ * @lucene.internal
+ * @lucene.experimental
+ */
+ public static void checkField(LeafReader in, String field) {
+ FieldInfo fi = in.getFieldInfos().fieldInfo(field);
+ if (fi != null && fi.hasVectorValues() && fi.getVectorEncoding() != VectorEncoding.FLOAT16) {
+ throw new IllegalStateException(
+ "Unexpected vector encoding ("
+ + fi.getVectorEncoding()
+ + ") for field "
+ + field
+ + "(expected="
+ + VectorEncoding.FLOAT16
+ + ")");
+ }
+ }
+
+ /**
+ * Return a {@link VectorScorer} for the given query vector and the current {@link
+ * Float16VectorValues}. When the underlying format quantizes the vectors, this will return a
+ * {@link VectorScorer} that scores against the quantized vectors.
+ *
+ * @param target the query vector
+ * @return a {@link VectorScorer} instance or null
+ */
+ public VectorScorer scorer(short[] target) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Rescore using the given query vector and the current {@link Float16VectorValues}. This is
+ * unique from scorer() in that it is explicitly for rescoring an existing set of hits and thus
+ * will often utilize the highest fidelity scoring algorithm available. This is useful when the
+ * initial search used a quantized index or an approximate search algorithm, and now we want to
+ * rescore the hits using the full fidelity vectors. The default implementation is to call {@link
+ * #scorer(short[])} assuming that the scorer is already the highest fidelity implementation
+ * available.
+ *
+ * @param target the query vector
+ * @return a {@link VectorScorer} instance or null
+ * @throws IOException if an I/O error occurs
+ */
+ public VectorScorer rescorer(short[] target) throws IOException {
+ return scorer(target);
+ }
+
+ @Override
+ public VectorEncoding getEncoding() {
+ return VectorEncoding.FLOAT16;
+ }
+
+ /**
+ * Creates a {@link Float16VectorValues} from a list of float16 vectors.
+ *
+ * @param vectors the list of float16 vectors, each stored as a {@code short[]}
+ * @param dim the dimension of the vectors
+ * @return a {@link Float16VectorValues} instance
+ */
+ public static Float16VectorValues fromFloats16(List<short[]> vectors, int dim) {
+ return new Float16VectorValues() {
+ @Override
+ public int size() {
+ return vectors.size();
+ }
+
+ @Override
+ public int dimension() {
+ return dim;
+ }
+
+ @Override
+ public short[] vectorValue(int targetOrd) {
+ return vectors.get(targetOrd);
+ }
+
+ @Override
+ public Float16VectorValues copy() {
+ return this;
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return createDenseIterator();
+ }
+ };
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
index 5e81ddb2b0a..b0e29104682 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
@@ -40,6 +40,7 @@ import org.apache.lucene.codecs.PointsFormat;
import org.apache.lucene.codecs.PointsWriter;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.KnnByteVectorField;
+import org.apache.lucene.document.KnnFloat16VectorField;
import org.apache.lucene.document.KnnFloatVectorField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StoredValue;
@@ -1258,26 +1259,39 @@ final class IndexingChain implements Accountable {
int consumed = 0;
int batchDocID;
switch (encoding) {
- case FLOAT32 -> {
- KnnFieldVectorsWriter<float[]> writer =
- (KnnFieldVectorsWriter<float[]>) pf.knnFieldVectorsWriter;
+ case BYTE -> {
+ KnnFieldVectorsWriter<byte[]> writer =
+ (KnnFieldVectorsWriter<byte[]>) pf.knnFieldVectorsWriter;
while ((batchDocID = cursor.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
ColumnValidation.checkDocID(column, batchDocID, numDocs);
ColumnValidation.checkVectorDocIDStrictlyIncreasing(column, batchDocID, prevBatchDocID);
- float[] vec = (float[]) cursor.value();
+ byte[] vec = (byte[]) cursor.value();
ColumnValidation.checkVectorDimension(column, vec.length, dimension, batchDocID);
writer.addValue(baseDocID + batchDocID, vec);
prevBatchDocID = batchDocID;
consumed++;
}
}
- case BYTE -> {
- KnnFieldVectorsWriter<byte[]> writer =
- (KnnFieldVectorsWriter<byte[]>) pf.knnFieldVectorsWriter;
+ case FLOAT16 -> {
+ KnnFieldVectorsWriter<short[]> writer =
+ (KnnFieldVectorsWriter<short[]>) pf.knnFieldVectorsWriter;
while ((batchDocID = cursor.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
ColumnValidation.checkDocID(column, batchDocID, numDocs);
ColumnValidation.checkVectorDocIDStrictlyIncreasing(column, batchDocID, prevBatchDocID);
- byte[] vec = (byte[]) cursor.value();
+ short[] vec = (short[]) cursor.value();
+ ColumnValidation.checkVectorDimension(column, vec.length, dimension, batchDocID);
+ writer.addValue(baseDocID + batchDocID, vec);
+ prevBatchDocID = batchDocID;
+ consumed++;
+ }
+ }
+ case FLOAT32 -> {
+ KnnFieldVectorsWriter<float[]> writer =
+ (KnnFieldVectorsWriter<float[]>) pf.knnFieldVectorsWriter;
+ while ((batchDocID = cursor.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ ColumnValidation.checkDocID(column, batchDocID, numDocs);
+ ColumnValidation.checkVectorDocIDStrictlyIncreasing(column, batchDocID, prevBatchDocID);
+ float[] vec = (float[]) cursor.value();
ColumnValidation.checkVectorDimension(column, vec.length, dimension, batchDocID);
writer.addValue(baseDocID + batchDocID, vec);
prevBatchDocID = batchDocID;
@@ -1690,6 +1704,9 @@ final class IndexingChain implements Accountable {
case BYTE ->
((KnnFieldVectorsWriter<byte[]>) pf.knnFieldVectorsWriter)
.addValue(docID, ((KnnByteVectorField) field).vectorValue());
+ case FLOAT16 ->
+ ((KnnFieldVectorsWriter<short[]>) pf.knnFieldVectorsWriter)
+ .addValue(docID, ((KnnFloat16VectorField) field).vectorValue());
case FLOAT32 ->
((KnnFieldVectorsWriter<float[]>) pf.knnFieldVectorsWriter)
.addValue(docID, ((KnnFloatVectorField) field).vectorValue());
diff --git a/lucene/core/src/java/org/apache/lucene/index/LeafReader.java b/lucene/core/src/java/org/apache/lucene/index/LeafReader.java
index 91aecdeb228..7d746561461 100644
--- a/lucene/core/src/java/org/apache/lucene/index/LeafReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/LeafReader.java
@@ -219,6 +219,14 @@ public abstract non-sealed class LeafReader extends IndexReader {
*/
public abstract FloatVectorValues getFloatVectorValues(String field) throws IOException;
+ /**
+ * Returns {@link Float16VectorValues} for this field, or null if no {@link Float16VectorValues}
+ * were indexed. The returned instance should only be used by a single thread.
+ *
+ * @lucene.experimental
+ */
+ public abstract Float16VectorValues getFloat16VectorValues(String field) throws IOException;
+
/**
* Returns {@link ByteVectorValues} for this field, or null if no {@link ByteVectorValues} were
* indexed. The returned instance should only be used by a single thread.
@@ -315,6 +323,50 @@ public abstract non-sealed class LeafReader extends IndexReader {
return collector.topDocs();
}
+ /**
+ * Return the k nearest neighbor documents as determined by comparison of their vector values for
+ * this field, to the given vector, by the field's similarity function. The score of each document
+ * is derived from the vector similarity in a way that ensures scores are positive and that a
+ * larger score corresponds to a higher ranking.
+ *
+ * <p>The search is allowed to be approximate, meaning the results are not guaranteed to be the
+ * true k closest neighbors. For large values of k (for example when k is close to the total
+ * number of documents), the search may also retrieve fewer than k documents.
+ *
+ * <p>The returned {@link TopDocs} will contain a {@link ScoreDoc} for each nearest neighbor,
+ * sorted in order of their similarity to the query vector (decreasing scores). The {@link
+ * TotalHits} contains the number of documents visited during the search. If the search stopped
+ * early because it hit {@code visitedLimit}, it is indicated through the relation {@code
+ * TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO}.
+ *
+ * @param field the vector field to search
+ * @param target the fp16 vector-valued query
+ * @param k the number of docs to return
+ * @param acceptDocs {@link AcceptDocs} that represents the allowed documents to match
+ * @param visitedLimit the maximum number of nodes that the search is allowed to visit
+ * @return the k nearest neighbor documents, along with their (searchStrategy-specific) scores.
+ * @lucene.experimental
+ */
+ public final TopDocs searchNearestVectors(
+ String field, short[] target, int k, AcceptDocs acceptDocs, int visitedLimit)
+ throws IOException {
+ FieldInfo fi = getFieldInfos().fieldInfo(field);
+ if (fi == null || fi.getVectorDimension() == 0) {
+ return TopDocsCollector.EMPTY_TOPDOCS;
+ }
+ Float16VectorValues vectorValues = getFloat16VectorValues(fi.name);
+ if (vectorValues == null) {
+ return TopDocsCollector.EMPTY_TOPDOCS;
+ }
+ k = Math.min(k, vectorValues.size());
+ if (k == 0) {
+ return TopDocsCollector.EMPTY_TOPDOCS;
+ }
+ KnnCollector collector = new TopKnnCollector(k, visitedLimit);
+ searchNearestVectors(field, target, collector, acceptDocs);
+ return collector.topDocs();
+ }
+
/**
* Return the k nearest neighbor documents as determined by comparison of their vector values for
* this field, to the given vector, by the field's similarity function. The score of each document
@@ -344,6 +396,35 @@ public abstract non-sealed class LeafReader extends IndexReader {
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
throws IOException;
+ /**
+ * Return the k nearest neighbor documents as determined by comparison of their vector values for
+ * this field, to the given vector, by the field's similarity function. The score of each document
+ * is derived from the vector similarity in a way that ensures scores are positive and that a
+ * larger score corresponds to a higher ranking.
+ *
+ * <p>The search is allowed to be approximate, meaning the results are not guaranteed to be the
+ * true k closest neighbors. For large values of k (for example when k is close to the total
+ * number of documents), the search may also retrieve fewer than k documents.
+ *
+ * <p>The returned {@link TopDocs} will contain a {@link ScoreDoc} for each nearest neighbor, in
+ * order of their similarity to the query vector (decreasing scores). The {@link TotalHits}
+ * contains the number of documents visited during the search. If the search stopped early because
+ * it hit {@code visitedLimit}, it is indicated through the relation {@code
+ * TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO}.
+ *
+ * <p>The behavior is undefined if the given field doesn't have KNN vectors enabled on its {@link
+ * FieldInfo}. The return value is never {@code null}.
+ *
+ * @param field the vector field to search
+ * @param target the fp16 vector-valued query
+ * @param knnCollector collector with settings for gathering the vector results.
+ * @param acceptDocs {@link AcceptDocs} that represents the allowed documents to match
+ * @lucene.experimental
+ */
+ public abstract void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException;
+
/**
* Return the k nearest neighbor documents as determined by comparison of their vector values for
* this field, to the given vector, by the field's similarity function. The score of each document
diff --git a/lucene/core/src/java/org/apache/lucene/index/ParallelLeafReader.java b/lucene/core/src/java/org/apache/lucene/index/ParallelLeafReader.java
index 036a8fbdd15..2933e9ebf65 100644
--- a/lucene/core/src/java/org/apache/lucene/index/ParallelLeafReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/ParallelLeafReader.java
@@ -456,6 +456,12 @@ public class ParallelLeafReader extends LeafReader {
return reader == null ? null : reader.getFloatVectorValues(fieldName);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ LeafReader reader = fieldToReader.get(field);
+ return reader == null ? null : reader.getFloat16VectorValues(field);
+ }
+
@Override
public ByteVectorValues getByteVectorValues(String fieldName) throws IOException {
ensureOpen();
@@ -474,6 +480,17 @@ public class ParallelLeafReader extends LeafReader {
}
}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ ensureOpen();
+ LeafReader reader = fieldToReader.get(field);
+ if (reader != null) {
+ reader.searchNearestVectors(field, target, knnCollector, acceptDocs);
+ }
+ }
+
@Override
public void searchNearestVectors(
String fieldName, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
diff --git a/lucene/core/src/java/org/apache/lucene/index/SlowCodecReaderWrapper.java b/lucene/core/src/java/org/apache/lucene/index/SlowCodecReaderWrapper.java
index 8b09766bf0c..b082d984996 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SlowCodecReaderWrapper.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SlowCodecReaderWrapper.java
@@ -174,6 +174,11 @@ public final class SlowCodecReaderWrapper {
return reader.getByteVectorValues(field);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ return reader.getFloat16VectorValues(field);
+ }
+
@Override
public void search(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
@@ -188,6 +193,13 @@ public final class SlowCodecReaderWrapper {
reader.searchNearestVectors(field, target, knnCollector, acceptDocs);
}
+ @Override
+ public void search(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ reader.searchNearestVectors(field, target, knnCollector, acceptDocs);
+ }
+
@Override
public void checkIntegrity(MergePolicy.OneMerge merge) {
// We already checkIntegrity the entire reader up front
diff --git a/lucene/core/src/java/org/apache/lucene/index/SlowCompositeCodecReaderWrapper.java b/lucene/core/src/java/org/apache/lucene/index/SlowCompositeCodecReaderWrapper.java
index 7f92668458d..6a01b1fa2f7 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SlowCompositeCodecReaderWrapper.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SlowCompositeCodecReaderWrapper.java
@@ -928,6 +928,86 @@ final class SlowCompositeCodecReaderWrapper extends CodecReader {
return new MergedByteVectorValues(dimension, size, subs);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ List<DocValuesSub<Float16VectorValues>> subs = new ArrayList<>();
+ int i = 0;
+ int dimension = -1;
+ int size = 0;
+ for (CodecReader reader : codecReaders) {
+ Float16VectorValues values = reader.getFloat16VectorValues(field);
+ subs.add(new DocValuesSub<>(values, docStarts[i], size));
+ if (values != null) {
+ if (dimension == -1) {
+ dimension = values.dimension();
+ }
+ size += values.size();
+ }
+ i++;
+ }
+ return new MergedFloat16VectorValues(dimension, size, subs);
+ }
+
+ class MergedFloat16VectorValues extends Float16VectorValues {
+ final int dimension;
+ final int size;
+ final List<DocValuesSub<Float16VectorValues>> subs;
+ final MergedDocIterator<Float16VectorValues> iter;
+ final int[] starts;
+ int lastSubIndex;
+
+ MergedFloat16VectorValues(
+ int dimension, int size, List<DocValuesSub<Float16VectorValues>> subs) {
+ this.dimension = dimension;
+ this.size = size;
+ this.subs = subs;
+ iter = new MergedDocIterator<>(subs);
+ // [0, start(1), ..., size] - we want the extra element
+ // to avoid checking for out-of-array bounds
+ starts = new int[subs.size() + 1];
+ for (int i = 0; i < subs.size(); i++) {
+ starts[i] = subs.get(i).ordStart;
+ }
+ starts[starts.length - 1] = size;
+ }
+
+ @Override
+ public MergedDocIterator<Float16VectorValues> iterator() {
+ return iter;
+ }
+
+ @Override
+ public int dimension() {
+ return dimension;
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Float16VectorValues copy() throws IOException {
+ List<DocValuesSub<Float16VectorValues>> subsCopy = new ArrayList<>();
+ for (DocValuesSub<Float16VectorValues> sub : subs) {
+ subsCopy.add(sub.copy());
+ }
+ return new MergedFloat16VectorValues(dimension, size, subsCopy);
+ }
+
+ @Override
+ public short[] vectorValue(int ord) throws IOException {
+ assert ord >= 0 && ord < size;
+ // We need to implement fully random-access API here in order to support callers like
+ // SortingCodecReader that rely on it.
+ lastSubIndex = findSub(ord, lastSubIndex, starts);
+ DocValuesSub<Float16VectorValues> sub = subs.get(lastSubIndex);
+ assert sub.sub != null;
+ return (sub.sub).vectorValue(ord - sub.ordStart);
+ }
+ }
+
class MergedByteVectorValues extends ByteVectorValues {
final int dimension;
final int size;
@@ -1026,6 +1106,13 @@ final class SlowCompositeCodecReaderWrapper extends CodecReader {
throws IOException {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public void search(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortingCodecReader.java b/lucene/core/src/java/org/apache/lucene/index/SortingCodecReader.java
index f21c87cdb00..659218353ee 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SortingCodecReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SortingCodecReader.java
@@ -383,6 +383,43 @@ public final class SortingCodecReader extends FilterCodecReader {
}
}
+ private static class SortingFloat16VectorValues extends Float16VectorValues {
+ final Float16VectorValues delegate;
+ final SortingIteratorSupplier iteratorSupplier;
+
+ SortingFloat16VectorValues(Float16VectorValues delegate, Sorter.DocMap sortMap)
+ throws IOException {
+ this.delegate = delegate;
+ // SortingValuesIterator consumes the iterator and records the docs and ord mapping
+ iteratorSupplier = iteratorSupplier(delegate, sortMap);
+ }
+
+ @Override
+ public short[] vectorValue(int ord) throws IOException {
+ return delegate.vectorValue(ord);
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return iteratorSupplier.get();
+ }
+
+ @Override
+ public int dimension() {
+ return delegate.dimension();
+ }
+
+ @Override
+ public int size() {
+ return iteratorSupplier.size();
+ }
+
+ @Override
+ public Float16VectorValues copy() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
/**
* Return a sorted view of <code>reader</code> according to the order defined by <code>sort</code>
* . If the reader is already sorted, this method might return the reader as-is.
@@ -581,6 +618,11 @@ public final class SortingCodecReader extends FilterCodecReader {
return new SortingByteVectorValues(delegate.getByteVectorValues(field), docMap);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ return new SortingFloat16VectorValues(delegate.getFloat16VectorValues(field), docMap);
+ }
+
@Override
public void search(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {
@@ -593,6 +635,13 @@ public final class SortingCodecReader extends FilterCodecReader {
throw new UnsupportedOperationException();
}
+ @Override
+ public void search(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public Map<String, Long> getOffHeapByteSize(FieldInfo fieldInfo) {
return delegate.getOffHeapByteSize(fieldInfo);
diff --git a/lucene/core/src/java/org/apache/lucene/index/VectorEncoding.java b/lucene/core/src/java/org/apache/lucene/index/VectorEncoding.java
index 8ae6dd40e34..f4582180f19 100644
--- a/lucene/core/src/java/org/apache/lucene/index/VectorEncoding.java
+++ b/lucene/core/src/java/org/apache/lucene/index/VectorEncoding.java
@@ -29,7 +29,13 @@ public enum VectorEncoding {
BYTE(1),
/** Encodes vector using 32 bits of precision per sample in IEEE floating point format. */
- FLOAT32(4);
+ FLOAT32(4),
+
+ /**
+ * Encodes vector using 16 bits of precision per sample in IEEE half-precision floating-point
+ * format.
+ */
+ FLOAT16(2);
/**
* The number of bytes required to encode a scalar in this format. A vector will nominally require
diff --git a/lucene/core/src/java/org/apache/lucene/index/VectorSimilarityFunction.java b/lucene/core/src/java/org/apache/lucene/index/VectorSimilarityFunction.java
index a692d917e60..79ce3babfbb 100644
--- a/lucene/core/src/java/org/apache/lucene/index/VectorSimilarityFunction.java
+++ b/lucene/core/src/java/org/apache/lucene/index/VectorSimilarityFunction.java
@@ -42,6 +42,11 @@ public enum VectorSimilarityFunction {
public float compare(byte[] v1, byte[] v2) {
return 1 / (1f + squareDistance(v1, v2));
}
+
+ @Override
+ public float compare(short[] v1, short[] v2) {
+ return normalizeDistanceToUnitInterval(squareDistance(v1, v2));
+ }
},
/**
@@ -61,6 +66,11 @@ public enum VectorSimilarityFunction {
public float compare(byte[] v1, byte[] v2) {
return dotProductScore(v1, v2);
}
+
+ @Override
+ public float compare(short[] v1, short[] v2) {
+ return normalizeToUnitInterval(dotProduct(v1, v2));
+ }
},
/**
@@ -79,6 +89,11 @@ public enum VectorSimilarityFunction {
public float compare(byte[] v1, byte[] v2) {
return (1 + cosine(v1, v2)) / 2;
}
+
+ @Override
+ public float compare(short[] v1, short[] v2) {
+ return normalizeToUnitInterval(cosine(v1, v2));
+ }
},
/**
@@ -96,6 +111,11 @@ public enum VectorSimilarityFunction {
public float compare(byte[] v1, byte[] v2) {
return scaleMaxInnerProductScore(dotProduct(v1, v2));
}
+
+ @Override
+ public float compare(short[] v1, short[] v2) {
+ return scaleMaxInnerProductScore(dotProduct(v1, v2));
+ }
};
/**
@@ -118,4 +138,14 @@ public enum VectorSimilarityFunction {
* @return the value of the similarity function applied to the two vectors
*/
public abstract float compare(byte[] v1, byte[] v2);
+
+ /**
+ * Calculates a similarity score between the two vectors with a specified function. Higher
+ * similarity scores correspond to closer vectors. Each short represents a vector dimension.
+ *
+ * @param v1 a vector
+ * @param v2 another vector, of the same dimension
+ * @return the value of the similarity function applied to the two vectors
+ */
+ public abstract float compare(short[] v1, short[] v2);
}
diff --git a/lucene/core/src/java/org/apache/lucene/internal/vectorization/DefaultVectorUtilSupport.java b/lucene/core/src/java/org/apache/lucene/internal/vectorization/DefaultVectorUtilSupport.java
index 698fefa0278..cc11918baf0 100644
--- a/lucene/core/src/java/org/apache/lucene/internal/vectorization/DefaultVectorUtilSupport.java
+++ b/lucene/core/src/java/org/apache/lucene/internal/vectorization/DefaultVectorUtilSupport.java
@@ -64,6 +64,17 @@ final class DefaultVectorUtilSupport implements VectorUtilSupport {
return res;
}
+ @Override
+ public float dotProduct(short[] a, short[] b) {
+ assert a.length == b.length : "Vector lengths must match";
+
+ float sum = 0f;
+ for (int i = 0; i < a.length; i++) {
+ sum = Float.float16ToFloat(a[i]) * Float.float16ToFloat(b[i]) + sum;
+ }
+ return sum;
+ }
+
@Override
public float cosine(float[] a, float[] b) {
float sum = 0.0f;
@@ -105,6 +116,22 @@ final class DefaultVectorUtilSupport implements VectorUtilSupport {
return (float) (sum / Math.sqrt((double) norm1 * (double) norm2));
}
+ @Override
+ public float cosine(short[] a, short[] b) {
+ float sum = 0.0f;
+ float norm1 = 0.0f;
+ float norm2 = 0.0f;
+
+ for (int i = 0; i < a.length; i++) {
+ float f1 = Float.float16ToFloat(a[i]);
+ float f2 = Float.float16ToFloat(b[i]);
+ sum = fma(f1, f2, sum);
+ norm1 = fma(f1, f1, norm1);
+ norm2 = fma(f2, f2, norm2);
+ }
+ return (float) (sum / Math.sqrt((double) norm1 * (double) norm2));
+ }
+
@Override
public float squareDistance(float[] a, float[] b) {
float res = 0;
@@ -145,6 +172,16 @@ final class DefaultVectorUtilSupport implements VectorUtilSupport {
return res;
}
+ @Override
+ public float squareDistance(short[] a, short[] b) {
+ float res = 0f; // Accumulate in float32 for precision
+ for (int i = 0; i < a.length; i++) {
+ float diff = Float.float16ToFloat(a[i]) - Float.float16ToFloat(b[i]);
+ res += diff * diff;
+ }
+ return res;
+ }
+
@Override
public int dotProduct(byte[] a, byte[] b) {
int total = 0;
diff --git a/lucene/core/src/java/org/apache/lucene/internal/vectorization/VectorUtilSupport.java b/lucene/core/src/java/org/apache/lucene/internal/vectorization/VectorUtilSupport.java
index 66a16469a5d..5569d77a337 100644
--- a/lucene/core/src/java/org/apache/lucene/internal/vectorization/VectorUtilSupport.java
+++ b/lucene/core/src/java/org/apache/lucene/internal/vectorization/VectorUtilSupport.java
@@ -27,12 +27,23 @@ public interface VectorUtilSupport {
/** Calculates the dot product of the given float arrays. */
float dotProduct(float[] a, float[] b);
+ /**
+ * Calculates the dot product of the given short arrays used when we are using float16 vectors.
+ */
+ float dotProduct(short[] a, short[] b);
+
/** Returns the cosine similarity between the two vectors. */
float cosine(float[] v1, float[] v2);
+ /** Returns the cosine similarity between the two vectors. */
+ float cosine(short[] v1, short[] v2);
+
/** Returns the sum of squared differences of the two vectors. */
float squareDistance(float[] a, float[] b);
+ /** Returns the sum of squared differences of the two vectors. */
+ float squareDistance(short[] a, short[] b);
+
/** Returns the dot product computed over signed bytes. */
int dotProduct(byte[] a, byte[] b);
diff --git a/lucene/core/src/java/org/apache/lucene/search/FieldExistsQuery.java b/lucene/core/src/java/org/apache/lucene/search/FieldExistsQuery.java
index c6c6f28c607..ddbc8c2e9f0 100644
--- a/lucene/core/src/java/org/apache/lucene/search/FieldExistsQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/FieldExistsQuery.java
@@ -26,6 +26,7 @@ import org.apache.lucene.index.DocValuesSkipper;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexReader;
@@ -180,8 +181,9 @@ public class FieldExistsQuery extends Query {
} else if (fieldInfo.getVectorDimension() != 0) { // the field indexes vectors
iterator =
switch (fieldInfo.getVectorEncoding()) {
- case FLOAT32 -> context.reader().getFloatVectorValues(field).iterator();
case BYTE -> context.reader().getByteVectorValues(field).iterator();
+ case FLOAT16 -> context.reader().getFloat16VectorValues(field).iterator();
+ case FLOAT32 -> context.reader().getFloatVectorValues(field).iterator();
};
} else if (fieldInfo.getDocValuesType()
!= DocValuesType.NONE) { // the field indexes doc values
@@ -294,16 +296,21 @@ public class FieldExistsQuery extends Query {
private int getVectorValuesSize(FieldInfo fi, LeafReader reader) throws IOException {
assert fi.name.equals(field);
return switch (fi.getVectorEncoding()) {
- case FLOAT32 -> {
- FloatVectorValues floatVectorValues = reader.getFloatVectorValues(field);
- assert floatVectorValues != null : "unexpected null float vector values";
- yield floatVectorValues.size();
- }
case BYTE -> {
ByteVectorValues byteVectorValues = reader.getByteVectorValues(field);
assert byteVectorValues != null : "unexpected null byte vector values";
yield byteVectorValues.size();
}
+ case FLOAT16 -> {
+ Float16VectorValues float16VectorValues = reader.getFloat16VectorValues(field);
+ assert float16VectorValues != null : "unexpected null float vector values";
+ yield float16VectorValues.size();
+ }
+ case FLOAT32 -> {
+ FloatVectorValues floatVectorValues = reader.getFloatVectorValues(field);
+ assert floatVectorValues != null : "unexpected null float vector values";
+ yield floatVectorValues.size();
+ }
};
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/KnnFloat16VectorQuery.java b/lucene/core/src/java/org/apache/lucene/search/KnnFloat16VectorQuery.java
new file mode 100644
index 00000000000..16ad5c73870
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/KnnFloat16VectorQuery.java
@@ -0,0 +1,167 @@
+/*
+ * 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.search;
+
+import static org.apache.lucene.search.knn.KnnSearchStrategy.Hnsw.DEFAULT;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Objects;
+import org.apache.lucene.codecs.KnnVectorsReader;
+import org.apache.lucene.document.KnnFloat16VectorField;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.knn.KnnCollectorManager;
+import org.apache.lucene.search.knn.KnnSearchStrategy;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.VectorUtil;
+
+/**
+ * Uses {@link KnnVectorsReader#search(String, short[], KnnCollector, AcceptDocs)} to perform
+ * nearest neighbour search.
+ *
+ * <p>This query also allows for performing a kNN search subject to a filter. In this case, it first
+ * executes the filter for each leaf, then chooses a strategy dynamically:
+ *
+ * <ul>
+ * <li>If the filter cost is less than k, just execute an exact search
+ * <li>Otherwise run a kNN search subject to the filter
+ * <li>If the kNN search visits too many vectors without completing, stop and run an exact search
+ * </ul>
+ */
+public class KnnFloat16VectorQuery extends AbstractKnnVectorQuery {
+
+ private static final TopDocs NO_RESULTS = TopDocsCollector.EMPTY_TOPDOCS;
+
+ protected final short[] target;
+
+ /**
+ * Find the <code>k</code> nearest documents to the target vector according to the vectors in the
+ * given field. <code>target</code> vector.
+ *
+ * @param field a field that has been indexed as a {@link KnnFloat16VectorField}.
+ * @param target the target of the search
+ * @param k the number of documents to find
+ * @throws IllegalArgumentException if <code>k</code> is less than 1
+ */
+ public KnnFloat16VectorQuery(String field, short[] target, int k) {
+ this(field, target, k, null);
+ }
+
+ /**
+ * Find the <code>k</code> nearest documents to the target vector according to the vectors in the
+ * given field. <code>target</code> vector.
+ *
+ * @param field a field that has been indexed as a {@link KnnFloat16VectorField}.
+ * @param target the target of the search
+ * @param k the number of documents to find
+ * @param filter a filter applied before the vector search
+ * @throws IllegalArgumentException if <code>k</code> is less than 1
+ */
+ public KnnFloat16VectorQuery(String field, short[] target, int k, Query filter) {
+ this(field, target, k, filter, DEFAULT);
+ }
+
+ /**
+ * Find the <code>k</code> nearest documents to the target vector according to the vectors in the
+ * given field. <code>target</code> vector.
+ *
+ * @param field a field that has been indexed as a {@link KnnFloat16VectorField}.
+ * @param target the target of the search
+ * @param k the number of documents to find
+ * @param filter a filter applied before the vector search
+ * @param searchStrategy the search strategy to use. If null, the default strategy will be used.
+ * The underlying format may not support all strategies and is free to ignore the requested
+ * strategy.
+ * @lucene.experimental
+ */
+ public KnnFloat16VectorQuery(
+ String field, short[] target, int k, Query filter, KnnSearchStrategy searchStrategy) {
+ super(field, k, filter, searchStrategy);
+ this.target = VectorUtil.checkFiniteFloat16(Objects.requireNonNull(target, "target"));
+ }
+
+ @Override
+ protected TopDocs approximateSearch(
+ LeafReaderContext context,
+ AcceptDocs acceptDocs,
+ int visitedLimit,
+ KnnCollectorManager knnCollectorManager)
+ throws IOException {
+ KnnCollector knnCollector =
+ knnCollectorManager.newCollector(visitedLimit, searchStrategy, context);
+ LeafReader reader = context.reader();
+ Float16VectorValues float16VectorValues = reader.getFloat16VectorValues(field);
+ if (float16VectorValues == null) {
+ Float16VectorValues.checkField(reader, field);
+ return NO_RESULTS;
+ }
+ if (Math.min(knnCollector.k(), float16VectorValues.size()) == 0) {
+ return NO_RESULTS;
+ }
+ reader.searchNearestVectors(field, target, knnCollector, acceptDocs);
+ TopDocs results = knnCollector.topDocs();
+ return results != null ? results : NO_RESULTS;
+ }
+
+ @Override
+ VectorScorer createVectorScorer(LeafReaderContext context, FieldInfo fi) throws IOException {
+ LeafReader reader = context.reader();
+ Float16VectorValues vectorValues = reader.getFloat16VectorValues(field);
+ if (vectorValues == null) {
+ Float16VectorValues.checkField(reader, field);
+ return null;
+ }
+ return vectorValues.scorer(target);
+ }
+
+ @Override
+ public String toString(String field) {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append(getClass().getSimpleName() + ":");
+ buffer.append(this.field + "[" + target[0] + ",...]");
+ buffer.append("[" + k + "]");
+ if (this.filter != null) {
+ buffer.append("[" + this.filter + "]");
+ }
+ return buffer.toString();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (super.equals(o) == false) return false;
+ KnnFloat16VectorQuery that = (KnnFloat16VectorQuery) o;
+ return Arrays.equals(target, that.target);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ result = 31 * result + Arrays.hashCode(target);
+ return result;
+ }
+
+ /**
+ * @return the target query vector of the search. Each vector element is a short (float16).
+ */
+ public short[] getTargetCopy() {
+ return ArrayUtil.copyArray(target);
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/store/DataInput.java b/lucene/core/src/java/org/apache/lucene/store/DataInput.java
index 62ea389a835..7bcf13a234e 100644
--- a/lucene/core/src/java/org/apache/lucene/store/DataInput.java
+++ b/lucene/core/src/java/org/apache/lucene/store/DataInput.java
@@ -79,6 +79,20 @@ public abstract class DataInput implements Cloneable {
return (short) (((b2 & 0xFF) << 8) | (b1 & 0xFF));
}
+ /**
+ * Reads a specified number of shorts into an array at the specified offset.
+ *
+ * @param values the array to read shorts into
+ * @param offset the offset in the array to start storing shorts
+ * @param len the number of shorts to read
+ */
+ public void readShorts(short[] values, int offset, int len) throws IOException {
+ Objects.checkFromIndexSize(offset, len, values.length);
+ for (int i = 0; i < len; i++) {
+ values[offset + i] = readShort();
+ }
+ }
+
/**
* Reads four bytes and returns an int (LE byte order).
*
diff --git a/lucene/core/src/java/org/apache/lucene/store/MemorySegmentIndexInput.java b/lucene/core/src/java/org/apache/lucene/store/MemorySegmentIndexInput.java
index 32f8a5e4efa..6c6dc5b67b9 100644
--- a/lucene/core/src/java/org/apache/lucene/store/MemorySegmentIndexInput.java
+++ b/lucene/core/src/java/org/apache/lucene/store/MemorySegmentIndexInput.java
@@ -264,6 +264,18 @@ abstract class MemorySegmentIndexInput extends IndexInput implements MemorySegme
}
}
+ @Override
+ public void readShorts(short[] dst, int offset, int length) throws IOException {
+ try {
+ MemorySegment.copy(curSegment, LAYOUT_LE_SHORT, curPosition, dst, offset, length);
+ curPosition += Short.BYTES * (long) length;
+ } catch (IndexOutOfBoundsException _) {
+ super.readShorts(dst, offset, length);
+ } catch (NullPointerException | IllegalStateException e) {
+ throw alreadyClosed(e);
+ }
+ }
+
@Override
public final int readInt() throws IOException {
try {
diff --git a/lucene/core/src/java/org/apache/lucene/util/VectorUtil.java b/lucene/core/src/java/org/apache/lucene/util/VectorUtil.java
index 0841440063a..641cc420bf6 100644
--- a/lucene/core/src/java/org/apache/lucene/util/VectorUtil.java
+++ b/lucene/core/src/java/org/apache/lucene/util/VectorUtil.java
@@ -76,6 +76,22 @@ public final class VectorUtil {
return r;
}
+ public static float dotProduct(short[] a, short[] b) {
+ if (a.length != b.length) {
+ throw new IllegalArgumentException("vector dimensions differ: " + a.length + "!=" + b.length);
+ }
+ float result = IMPL.dotProduct(a, b);
+ assert Float.isFinite(result)
+ : "not finite: "
+ + result
+ + " from <"
+ + java.util.Arrays.toString(a)
+ + ","
+ + java.util.Arrays.toString(b)
+ + ">";
+ return result;
+ }
+
/**
* Returns the cosine similarity between the two vectors.
*
@@ -98,6 +114,14 @@ public final class VectorUtil {
return IMPL.cosine(a, b);
}
+ /** Returns the cosine similarity between the two vectors. */
+ public static float cosine(short[] a, short[] b) {
+ if (a.length != b.length) {
+ throw new IllegalArgumentException("vector dimensions differ: " + a.length + "!=" + b.length);
+ }
+ return IMPL.cosine(a, b);
+ }
+
/**
* Returns the sum of squared differences of the two vectors.
*
@@ -112,6 +136,20 @@ public final class VectorUtil {
return r;
}
+ /**
+ * Returns the sum of squared differences of the two vectors.
+ *
+ * @throws IllegalArgumentException if the vectors' dimensions differ.
+ */
+ public static float squareDistance(short[] a, short[] b) {
+ if (a.length != b.length) {
+ throw new IllegalArgumentException("vector dimensions differ: " + a.length + "!=" + b.length);
+ }
+ float result = IMPL.squareDistance(a, b);
+ assert Float.isFinite(result);
+ return result;
+ }
+
/** Returns the sum of squared differences of the two vectors. */
public static int squareDistance(byte[] a, byte[] b) {
if (a.length != b.length) {
@@ -441,6 +479,27 @@ public final class VectorUtil {
return v;
}
+ /**
+ * Checks if a float16 vector, encoded as {@code short[]}, only has finite components. A float16
+ * value is non-finite (i.e. an infinity or NaN) when all five exponent bits are set, which is
+ * detected by {@code (v[i] & 0x7C00) == 0x7C00}. This bitmask check is used instead of {@code
+ * Float.isFinite(Float.float16ToFloat(v[i]))} because it avoids a per-element half-to-single
+ * precision conversion and is measurably faster.
+ *
+ * @param v shorts containing a float16 vector
+ * @return the vector for call-chaining
+ * @throws IllegalArgumentException if any component of the vector is not finite
+ */
+ public static short[] checkFiniteFloat16(short[] v) {
+ for (int i = 0; i < v.length; i++) {
+ if ((v[i] & 0x7C00) == 0x7C00) {
+ throw new IllegalArgumentException(
+ "non-finite float16 value at vector[" + i + "]=" + Float.float16ToFloat(v[i]));
+ }
+ }
+ return v;
+ }
+
/** Returns true if all dimensions of provided vector are zero, false otherwise. */
public static boolean isZeroVector(float[] v) {
for (float value : v) {
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/ConcurrentHnswMerger.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/ConcurrentHnswMerger.java
index 0803c1389ed..ea306fec0ce 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/ConcurrentHnswMerger.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/ConcurrentHnswMerger.java
@@ -125,6 +125,8 @@ public class ConcurrentHnswMerger extends IncrementalHnswGraphMerger {
switch (fieldInfo.getVectorEncoding()) {
case BYTE -> initializerIterator = initReader.getByteVectorValues(fieldInfo.name).iterator();
+ case FLOAT16 ->
+ initializerIterator = initReader.getFloat16VectorValues(fieldInfo.name).iterator();
case FLOAT32 ->
initializerIterator = initReader.getFloatVectorValues(fieldInfo.name).iterator();
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/IncrementalHnswGraphMerger.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/IncrementalHnswGraphMerger.java
index d9dc4144472..014e801924a 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/IncrementalHnswGraphMerger.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/IncrementalHnswGraphMerger.java
@@ -114,6 +114,7 @@ public class IncrementalHnswGraphMerger implements HnswGraphMerger {
KnnVectorValues knnVectorValues =
switch (fieldInfo.getVectorEncoding()) {
case BYTE -> reader.getByteVectorValues(fieldInfo.name);
+ case FLOAT16 -> reader.getFloat16VectorValues(fieldInfo.name);
case FLOAT32 -> reader.getFloatVectorValues(fieldInfo.name);
};
@@ -189,6 +190,9 @@ public class IncrementalHnswGraphMerger implements HnswGraphMerger {
switch (fieldInfo.getVectorEncoding()) {
case BYTE ->
vectorsIter = graphReaders.get(i).reader.getByteVectorValues(fieldInfo.name).iterator();
+ case FLOAT16 ->
+ vectorsIter =
+ graphReaders.get(i).reader.getFloat16VectorValues(fieldInfo.name).iterator();
case FLOAT32 ->
vectorsIter =
graphReaders.get(i).reader.getFloatVectorValues(fieldInfo.name).iterator();
diff --git a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentFlatVectorsScorer.java b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentFlatVectorsScorer.java
index c8a9efb07ac..9b7da5c1d28 100644
--- a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentFlatVectorsScorer.java
+++ b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/Lucene99MemorySegmentFlatVectorsScorer.java
@@ -43,8 +43,9 @@ public class Lucene99MemorySegmentFlatVectorsScorer implements FlatVectorsScorer
public RandomVectorScorerSupplier getRandomVectorScorerSupplier(
VectorSimilarityFunction similarityType, KnnVectorValues vectorValues) throws IOException {
return switch (vectorValues.getEncoding()) {
- case FLOAT32 -> getFloatScoringSupplier((FloatVectorValues) vectorValues, similarityType);
case BYTE -> getByteScorerSupplier((ByteVectorValues) vectorValues, similarityType);
+ case FLOAT16 -> delegate.getRandomVectorScorerSupplier(similarityType, vectorValues);
+ case FLOAT32 -> getFloatScoringSupplier((FloatVectorValues) vectorValues, similarityType);
};
}
@@ -98,6 +99,13 @@ public class Lucene99MemorySegmentFlatVectorsScorer implements FlatVectorsScorer
return delegate.getRandomVectorScorer(similarityType, vectorValues, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityType, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ return delegate.getRandomVectorScorer(similarityType, vectorValues, target);
+ }
+
@Override
public RandomVectorScorer getRandomVectorScorer(
VectorSimilarityFunction similarityType, KnnVectorValues vectorValues, byte[] queryVector)
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 98e7bd9ed5c..83a36b4df6e 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
@@ -79,6 +79,13 @@ class Lucene99MemorySegmentScalarQuantizedVectorScorer implements FlatVectorsSco
return DELEGATE.getRandomVectorScorer(similarityFunction, vectorValues, target);
}
+ @Override
+ public RandomVectorScorer getRandomVectorScorer(
+ VectorSimilarityFunction similarityFunction, KnnVectorValues vectorValues, short[] target)
+ throws IOException {
+ return DELEGATE.getRandomVectorScorer(similarityFunction, vectorValues, target);
+ }
+
@Override
public String toString() {
return "Lucene99MemorySegmentScalarQuantizedVectorScorer()";
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 d9673300c92..e35b472f71d 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
@@ -580,6 +580,21 @@ final class NativeVectorUtilSupport implements VectorUtilSupport {
return v;
}
+ @Override
+ public float dotProduct(short[] a, short[] b) {
+ return delegateVectorUtilSupport.dotProduct(a, b);
+ }
+
+ @Override
+ public float cosine(short[] v1, short[] v2) {
+ return delegateVectorUtilSupport.cosine(v1, v2);
+ }
+
+ @Override
+ public float squareDistance(short[] a, short[] b) {
+ return delegateVectorUtilSupport.squareDistance(a, b);
+ }
+
@Override
public void expand8(int[] arr) {
invokeOrDelegate(
diff --git a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/PanamaVectorUtilSupport.java b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/PanamaVectorUtilSupport.java
index 3053c1a7f36..4ef2dca2512 100644
--- a/lucene/core/src/java25/org/apache/lucene/internal/vectorization/PanamaVectorUtilSupport.java
+++ b/lucene/core/src/java25/org/apache/lucene/internal/vectorization/PanamaVectorUtilSupport.java
@@ -56,6 +56,9 @@ import org.apache.lucene.util.SuppressForbidden;
*/
final class PanamaVectorUtilSupport implements VectorUtilSupport {
+ // Delegate for float16 (short[]) operations until JDK 27 provides Float16Vector support
+ private static final DefaultVectorUtilSupport FLOAT16_DELEGATE = new DefaultVectorUtilSupport();
+
// preferred vector sizes, which can be altered for testing
private static final VectorSpecies<Float> FLOAT_SPECIES;
private static final VectorSpecies<Double> DOUBLE_SPECIES =
@@ -300,6 +303,23 @@ final class PanamaVectorUtilSupport implements VectorUtilSupport {
return res1.add(res2).reduceLanes(ADD);
}
+ // float16 (short[]) operations delegate to scalar implementation until JDK 27
+
+ @Override
+ public float dotProduct(short[] a, short[] b) {
+ return FLOAT16_DELEGATE.dotProduct(a, b);
+ }
+
+ @Override
+ public float cosine(short[] a, short[] b) {
+ return FLOAT16_DELEGATE.cosine(a, b);
+ }
+
+ @Override
+ public float squareDistance(short[] a, short[] b) {
+ return FLOAT16_DELEGATE.squareDistance(a, b);
+ }
+
// Binary functions, these all follow a general pattern like this:
//
// short intermediate = a * b;
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestKnnVectorsFormatCustomWriter.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestKnnVectorsFormatCustomWriter.java
index 51c37bbc04c..92f4329ca51 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestKnnVectorsFormatCustomWriter.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene99/TestKnnVectorsFormatCustomWriter.java
@@ -128,8 +128,9 @@ public class TestKnnVectorsFormatCustomWriter extends BaseKnnVectorsFormatTestCa
static PagedFieldVectorsWriter<?> create(FieldInfo fi) {
return switch (fi.getVectorEncoding()) {
- case FLOAT32 -> new FloatPaged(fi);
case BYTE -> new BytePaged(fi);
+ case FLOAT16 -> new Float16Paged(fi);
+ case FLOAT32 -> new FloatPaged(fi);
};
}
@@ -262,5 +263,26 @@ public class TestKnnVectorsFormatCustomWriter extends BaseKnnVectorsFormatTestCa
return out;
}
}
+
+ private static final class Float16Paged extends PagedFieldVectorsWriter<short[]> {
+ private final int dim;
+
+ Float16Paged(FieldInfo fi) {
+ super(fi, fi.getVectorDimension() * Short.BYTES);
+ this.dim = fi.getVectorDimension();
+ }
+
+ @Override
+ void serialize(ByteBuffer buf, short[] vector) {
+ buf.asShortBuffer().put(vector);
+ }
+
+ @Override
+ short[] deserialize(ByteBuffer buf) {
+ short[] out = new short[dim];
+ buf.asShortBuffer().get(out);
+ return out;
+ }
+ }
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/document/TestField.java b/lucene/core/src/test/org/apache/lucene/document/TestField.java
index 116e880dbfd..26dcb96a051 100644
--- a/lucene/core/src/test/org/apache/lucene/document/TestField.java
+++ b/lucene/core/src/test/org/apache/lucene/document/TestField.java
@@ -32,6 +32,7 @@ import org.apache.lucene.index.KnnVectorValues;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.KnnFloat16VectorQuery;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
@@ -810,6 +811,54 @@ public class TestField extends LuceneTestCase {
assertTrue(nanError.getMessage().contains("non-finite"));
}
+ public void testKnnFloat16FieldNonFinite() {
+ short one = Float.floatToFloat16(1f);
+ short two = Float.floatToFloat16(2f);
+ short[] finite = {one, two, Float.floatToFloat16(3f)};
+
+ // constructor rejects a non-finite (+Infinity) component
+ IllegalArgumentException ctorError =
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ new KnnFloat16VectorField(
+ "knnF16",
+ new short[] {one, (short) 0x7C00, two}, // 0x7C00 = +Infinity
+ VectorSimilarityFunction.EUCLIDEAN));
+ assertTrue(ctorError.getMessage(), ctorError.getMessage().contains("non-finite"));
+
+ // constructing with a finite vector succeeds
+ KnnFloat16VectorField field =
+ new KnnFloat16VectorField("knnF16", finite, VectorSimilarityFunction.EUCLIDEAN);
+
+ // setVectorValue rejects NaN (0x7E00)
+ IllegalArgumentException nanError =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> field.setVectorValue(new short[] {one, (short) 0x7E00, two}));
+ assertTrue(nanError.getMessage(), nanError.getMessage().contains("non-finite"));
+
+ // setVectorValue with a finite vector succeeds
+ field.setVectorValue(new short[] {two, one, Float.floatToFloat16(4f)});
+ }
+
+ public void testKnnFloat16QueryNonFinite() {
+ short one = Float.floatToFloat16(1f);
+
+ // null target
+ expectThrows(NullPointerException.class, () -> new KnnFloat16VectorQuery("f", null, 1));
+
+ // -Infinity (0xFC00) target
+ IllegalArgumentException infError =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> new KnnFloat16VectorQuery("f", new short[] {one, (short) 0xFC00}, 1));
+ assertTrue(infError.getMessage(), infError.getMessage().contains("non-finite"));
+
+ // finite target constructs fine
+ new KnnFloat16VectorQuery("f", new short[] {one, Float.floatToFloat16(2f)}, 1);
+ }
+
private void trySetByteValue(Field f) {
expectThrows(
IllegalArgumentException.class,
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestSegmentToThreadMapping.java b/lucene/core/src/test/org/apache/lucene/index/TestSegmentToThreadMapping.java
index 730c16148ac..0b115dd6fb5 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestSegmentToThreadMapping.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestSegmentToThreadMapping.java
@@ -112,6 +112,11 @@ public class TestSegmentToThreadMapping extends LuceneTestCase {
return null;
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ return null;
+ }
+
@Override
public ByteVectorValues getByteVectorValues(String field) {
return null;
@@ -121,6 +126,11 @@ public class TestSegmentToThreadMapping extends LuceneTestCase {
public void searchNearestVectors(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {}
+
@Override
public void searchNearestVectors(
String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {}
diff --git a/lucene/core/src/test/org/apache/lucene/search/BaseKnnVectorQueryTestCase.java b/lucene/core/src/test/org/apache/lucene/search/BaseKnnVectorQueryTestCase.java
index 7fcf44afebd..debd90b800a 100644
--- a/lucene/core/src/test/org/apache/lucene/search/BaseKnnVectorQueryTestCase.java
+++ b/lucene/core/src/test/org/apache/lucene/search/BaseKnnVectorQueryTestCase.java
@@ -909,6 +909,9 @@ abstract class BaseKnnVectorQueryTestCase extends LuceneTestCase {
case BYTE:
vectorValues = leafReader.getByteVectorValues("field");
break;
+ case FLOAT16:
+ vectorValues = leafReader.getFloat16VectorValues("field");
+ break;
case FLOAT32:
vectorValues = leafReader.getFloatVectorValues("field");
break;
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestVectorScorer.java b/lucene/core/src/test/org/apache/lucene/search/TestVectorScorer.java
index de728f4db4d..be08c48fec7 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestVectorScorer.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestVectorScorer.java
@@ -23,9 +23,11 @@ import java.io.IOException;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.KnnByteVectorField;
+import org.apache.lucene.document.KnnFloat16VectorField;
import org.apache.lucene.document.KnnFloatVectorField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.VectorEncoding;
@@ -50,6 +52,11 @@ public class TestVectorScorer extends LuceneTestCase {
case BYTE:
vectorScorer = context.reader().getByteVectorValues("field").scorer(new byte[] {1, 2});
break;
+ case FLOAT16:
+ Float16VectorValues val = context.reader().getFloat16VectorValues("field");
+ vectorScorer =
+ val.scorer(new short[] {Float.floatToFloat16(1f), Float.floatToFloat16(2f)});
+ break;
case FLOAT32:
vectorScorer = context.reader().getFloatVectorValues("field").scorer(new float[] {1, 2});
break;
@@ -109,8 +116,14 @@ public class TestVectorScorer extends LuceneTestCase {
v[j] = (byte) contents[i][j];
}
doc.add(new KnnByteVectorField(field, v, EUCLIDEAN));
+ } else if (encoding == VectorEncoding.FLOAT16) {
+ short[] v = new short[contents[i].length];
+ for (int j = 0; j < v.length; j++) {
+ v[j] = Float.floatToFloat16(contents[i][j]);
+ }
+ doc.add(new KnnFloat16VectorField(field, v, EUCLIDEAN));
} else {
- doc.add(new KnnFloatVectorField(field, contents[i]));
+ doc.add(new KnnFloatVectorField(field, contents[i], EUCLIDEAN));
}
doc.add(new StringField("id", "id" + i, Field.Store.YES));
writer.addDocument(doc);
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 f92362ea50c..f34ab3ddbfc 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestVectorUtil.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestVectorUtil.java
@@ -122,6 +122,37 @@ public class TestVectorUtil extends LuceneTestCase {
expectThrows(IllegalArgumentException.class, () -> VectorUtil.l2normalize(v));
}
+ public void testCheckFiniteFloat16() {
+ // finite vector passes and returns the same array
+ short[] finite = {
+ Float.floatToFloat16(-1.5f),
+ Float.floatToFloat16(0f),
+ Float.floatToFloat16(3.25f),
+ (short) 0x7BFF, // largest finite float16 (65504)
+ (short) 0xFBFF // most negative finite float16 (-65504)
+ };
+ assertSame(finite, VectorUtil.checkFiniteFloat16(finite));
+
+ // +Infinity
+ IllegalArgumentException e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ VectorUtil.checkFiniteFloat16(
+ new short[] {Float.floatToFloat16(1f), (short) 0x7C00}));
+ assertTrue(e.getMessage(), e.getMessage().contains("non-finite float16 value at vector[1]"));
+
+ // -Infinity
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> VectorUtil.checkFiniteFloat16(new short[] {(short) 0xFC00}));
+
+ // NaN (any non-zero mantissa with all exponent bits set)
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> VectorUtil.checkFiniteFloat16(new short[] {(short) 0x7E00}));
+ }
+
public void testNormalizeToUnitInterval() {
for (int i = 0; i < 100; i++) {
// Generates a float in the range [-1.0, 1.0)
diff --git a/lucene/core/src/test/org/apache/lucene/util/hnsw/HnswGraphTestCase.java b/lucene/core/src/test/org/apache/lucene/util/hnsw/HnswGraphTestCase.java
index 0928b718f58..8e4f1c801cb 100644
--- a/lucene/core/src/test/org/apache/lucene/util/hnsw/HnswGraphTestCase.java
+++ b/lucene/core/src/test/org/apache/lucene/util/hnsw/HnswGraphTestCase.java
@@ -49,6 +49,7 @@ import org.apache.lucene.document.StringField;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CodecReader;
import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
@@ -123,6 +124,8 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
return switch (getVectorEncoding()) {
case BYTE ->
flatVectorScorer.getRandomVectorScorer(similarityFunction, vectorsCopy, (byte[]) query);
+ case FLOAT16 ->
+ flatVectorScorer.getRandomVectorScorer(similarityFunction, vectorsCopy, (short[]) query);
case FLOAT32 ->
flatVectorScorer.getRandomVectorScorer(similarityFunction, vectorsCopy, (float[]) query);
};
@@ -175,6 +178,13 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
(T) ((ByteVectorValues) vectors).vectorValue(ord),
similarityFunction));
}
+ case FLOAT16 -> {
+ doc.add(
+ knnVectorField(
+ "field",
+ (T) ((Float16VectorValues) vectors).vectorValue(ord),
+ similarityFunction));
+ }
case FLOAT32 -> {
doc.add(
knnVectorField(
@@ -240,6 +250,13 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
(T) ((ByteVectorValues) vectors).vectorValue(i),
similarityFunction));
}
+ case FLOAT16 -> {
+ doc.add(
+ knnVectorField(
+ vectorFieldName,
+ (T) ((Float16VectorValues) vectors).vectorValue(i),
+ similarityFunction));
+ }
case FLOAT32 -> {
doc.add(
knnVectorField(
@@ -283,6 +300,9 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
case BYTE -> {
return (T) ((ByteVectorValues) vectors).vectorValue(ord);
}
+ case FLOAT16 -> {
+ return (T) ((Float16VectorValues) vectors).vectorValue(ord);
+ }
case FLOAT32 -> {
return (T) ((FloatVectorValues) vectors).vectorValue(ord);
}
@@ -809,6 +829,9 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
case BYTE ->
similarityFunction.compare(
((ByteVectorValues) vectorValues).vectorValue(i), (byte[]) target);
+ case FLOAT16 ->
+ similarityFunction.compare(
+ ((Float16VectorValues) vectorValues).vectorValue(i), (short[]) target);
case FLOAT32 ->
similarityFunction.compare(
((FloatVectorValues) vectorValues).vectorValue(i), (float[]) target);
@@ -1042,6 +1065,9 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
if (getVectorEncoding() == VectorEncoding.BYTE) {
expected.add(
j, similarityFunction.compare((byte[]) query, (byte[]) vectorValue(vectors, j)));
+ } else if (getVectorEncoding() == VectorEncoding.FLOAT16) {
+ expected.add(
+ j, similarityFunction.compare((short[]) query, (short[]) vectorValue(vectors, j)));
} else {
expected.add(
j, similarityFunction.compare((float[]) query, (float[]) vectorValue(vectors, j)));
@@ -1262,6 +1288,71 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
}
}
+ /** Returns vectors evenly distributed around the upper unit semicircle. */
+ static class CircularFloat16VectorValues extends Float16VectorValues {
+ private final int size;
+ private final short[] value;
+
+ int doc = -1;
+
+ CircularFloat16VectorValues(int size) {
+ this.size = size;
+ value = new short[2];
+ }
+
+ @Override
+ public CircularFloat16VectorValues copy() {
+ return new CircularFloat16VectorValues(size);
+ }
+
+ @Override
+ public int dimension() {
+ return 2;
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ public short[] vectorValue() {
+ return vectorValue(doc);
+ }
+
+ public int docID() {
+ return doc;
+ }
+
+ public int nextDoc() {
+ return advance(doc + 1);
+ }
+
+ public int advance(int target) {
+ if (target >= 0 && target < size) {
+ doc = target;
+ } else {
+ doc = NO_MORE_DOCS;
+ }
+ return doc;
+ }
+
+ @Override
+ public short[] vectorValue(int ord) {
+ return unitVector2d(ord / (double) size, value);
+ }
+
+ private static short[] unitVector2d(double piRadians, short[] value) {
+ value[0] = Float.floatToFloat16((float) Math.cos(Math.PI * piRadians));
+ value[1] = Float.floatToFloat16((float) Math.sin(Math.PI * piRadians));
+ return value;
+ }
+
+ @Override
+ public VectorScorer scorer(short[] target) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
/** Returns vectors evenly distributed around the upper unit semicircle. */
static class CircularByteVectorValues extends ByteVectorValues {
private final int size;
@@ -1359,6 +1450,11 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
"vectors do not match for doc=" + uDoc,
(byte[]) vectorValue(u, ord),
(byte[]) vectorValue(v, ord));
+ case FLOAT16 ->
+ assertArrayEquals(
+ "vectors do not match for doc=" + uDoc,
+ (short[]) vectorValue(u, ord),
+ (short[]) vectorValue(v, ord));
case FLOAT32 ->
assertArrayEquals(
"vectors do not match for doc=" + uDoc,
@@ -1379,6 +1475,14 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
return vectors;
}
+ static short[][] createRandomFloat16Vectors(int size, int dimension, Random random) {
+ short[][] vectors = new short[size][];
+ for (int offset = 0; offset < size; offset++) {
+ vectors[offset] = randomFloat16Vector(random, dimension);
+ }
+ return vectors;
+ }
+
static byte[][] createRandomByteVectors(int size, int dimension, Random random) {
byte[][] vectors = new byte[size][];
for (int offset = 0; offset < size; offset++) {
@@ -1418,6 +1522,15 @@ abstract class HnswGraphTestCase<T> extends LuceneTestCase {
return vec;
}
+ static short[] randomFloat16Vector(Random random, int dim) {
+ float[] vec = randomVector(random, dim);
+ short[] v = new short[vec.length];
+ for (int i = 0; i < dim; i++) {
+ v[i] = Float.floatToFloat16(vec[i]);
+ }
+ return v;
+ }
+
static byte[] randomVector8(Random random, int dim) {
float[] fvec = randomVector(random, dim);
byte[] bvec = new byte[dim];
diff --git a/lucene/core/src/test/org/apache/lucene/util/hnsw/MockFloat16VectorValues.java b/lucene/core/src/test/org/apache/lucene/util/hnsw/MockFloat16VectorValues.java
new file mode 100644
index 00000000000..57c7408c8ab
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/util/hnsw/MockFloat16VectorValues.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.lucene.util.hnsw;
+
+import org.apache.lucene.index.Float16VectorValues;
+import org.apache.lucene.tests.util.LuceneTestCase;
+import org.apache.lucene.util.ArrayUtil;
+
+class MockFloat16VectorValues extends Float16VectorValues {
+ private final int dimension;
+ private final short[][] denseValues;
+ protected final short[][] values;
+ private final int numVectors;
+ private final short[] scratch;
+
+ static MockFloat16VectorValues fromValues(short[][] values) {
+ short[] firstNonNull = null;
+ int j = 0;
+ while (firstNonNull == null && j < values.length) {
+ firstNonNull = values[j++];
+ }
+ int dimension = firstNonNull.length;
+ int maxDoc = values.length;
+ short[][] denseValues = new short[maxDoc][];
+ int count = 0;
+ for (int i = 0; i < maxDoc; i++) {
+ if (values[i] != null) {
+ denseValues[count++] = values[i];
+ }
+ }
+ return new MockFloat16VectorValues(values, dimension, denseValues, count);
+ }
+
+ MockFloat16VectorValues(short[][] values, int dimension, short[][] denseValues, int numVectors) {
+ this.dimension = dimension;
+ this.values = values;
+ this.denseValues = denseValues;
+ this.numVectors = numVectors;
+ this.scratch = new short[dimension];
+ }
+
+ @Override
+ public int size() {
+ return values.length;
+ }
+
+ @Override
+ public int dimension() {
+ return dimension;
+ }
+
+ @Override
+ public MockFloat16VectorValues copy() {
+ return new MockFloat16VectorValues(
+ ArrayUtil.copyArray(values), dimension, ArrayUtil.copyArray(denseValues), numVectors);
+ }
+
+ @Override
+ public short[] vectorValue(int ord) {
+ if (LuceneTestCase.random().nextBoolean()) {
+ return values[ord];
+ } else {
+ // Sometimes use the same scratch array repeatedly, mimicking what the codec will do.
+ // This should help us catch cases of aliasing where the same vector values source is used
+ // twice in a single computation.
+ System.arraycopy(values[ord], 0, scratch, 0, dimension);
+ return scratch;
+ }
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return createDenseIterator();
+ }
+}
diff --git a/lucene/core/src/test/org/apache/lucene/util/hnsw/TestHnswFloat16VectorGraph.java b/lucene/core/src/test/org/apache/lucene/util/hnsw/TestHnswFloat16VectorGraph.java
new file mode 100644
index 00000000000..ac5f830ae02
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/util/hnsw/TestHnswFloat16VectorGraph.java
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.lucene.util.hnsw;
+
+import com.carrotsearch.randomizedtesting.RandomizedTest;
+import java.io.IOException;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.KnnFloat16VectorField;
+import org.apache.lucene.index.Float16VectorValues;
+import org.apache.lucene.index.KnnVectorValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.search.KnnCollector;
+import org.apache.lucene.search.KnnFloat16VectorQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.ScoreDoc;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.FixedBitSet;
+import org.junit.Before;
+
+/** Tests HNSW KNN graphs */
+public class TestHnswFloat16VectorGraph extends HnswGraphTestCase<short[]> {
+
+ @Before
+ public void setup() {
+ similarityFunction = RandomizedTest.randomFrom(VectorSimilarityFunction.values());
+ }
+
+ @Override
+ VectorEncoding getVectorEncoding() {
+ return VectorEncoding.FLOAT16;
+ }
+
+ @Override
+ Query knnQuery(String field, short[] vector, int k) {
+ return new KnnFloat16VectorQuery(field, vector, k);
+ }
+
+ @Override
+ short[] randomVector(int dim) {
+ return randomFloat16Vector(random(), dim);
+ }
+
+ @Override
+ MockFloat16VectorValues vectorValues(int size, int dimension) {
+ return MockFloat16VectorValues.fromValues(
+ createRandomFloat16Vectors(size, dimension, random()));
+ }
+
+ @Override
+ MockFloat16VectorValues vectorValues(float[][] values) {
+ short[][] float16Values = new short[values.length][];
+ for (int i = 0; i < values.length; i++) {
+
+ float16Values[i] = new short[values[i].length];
+ for (int j = 0; j < values[i].length; j++) {
+ float16Values[i][j] = Float.floatToFloat16(values[i][j]);
+ }
+ }
+ return MockFloat16VectorValues.fromValues(float16Values);
+ }
+
+ @Override
+ MockFloat16VectorValues vectorValues(LeafReader reader, String fieldName) throws IOException {
+ Float16VectorValues vectorValues = reader.getFloat16VectorValues(fieldName);
+ short[][] vectors = new short[reader.maxDoc()][];
+ for (int i = 0; i < vectorValues.size(); i++) {
+ vectors[vectorValues.ordToDoc(i)] =
+ ArrayUtil.copyOfSubArray(vectorValues.vectorValue(i), 0, vectorValues.dimension());
+ }
+ return MockFloat16VectorValues.fromValues(vectors);
+ }
+
+ @Override
+ MockFloat16VectorValues vectorValues(
+ int size, int dimension, KnnVectorValues pregeneratedVectorValues, int pregeneratedOffset) {
+ MockFloat16VectorValues pvv = (MockFloat16VectorValues) pregeneratedVectorValues;
+ short[][] vectors = new short[size][];
+ short[][] randomVectors =
+ createRandomFloat16Vectors(size - pvv.values.length, dimension, random());
+
+ for (int i = 0; i < pregeneratedOffset; i++) {
+ vectors[i] = randomVectors[i];
+ }
+
+ for (int currentOrd = 0; currentOrd < pvv.size(); currentOrd++) {
+ vectors[pregeneratedOffset + currentOrd] = pvv.values[currentOrd];
+ }
+
+ for (int i = pregeneratedOffset + pvv.values.length; i < vectors.length; i++) {
+ vectors[i] = randomVectors[i - pvv.values.length];
+ }
+
+ return MockFloat16VectorValues.fromValues(vectors);
+ }
+
+ @Override
+ Field knnVectorField(String name, short[] vector, VectorSimilarityFunction similarityFunction) {
+ return new KnnFloat16VectorField(name, vector, similarityFunction);
+ }
+
+ @Override
+ CircularFloat16VectorValues circularVectorValues(int nDoc) {
+ return new CircularFloat16VectorValues(nDoc);
+ }
+
+ @Override
+ short[] getTargetVector() {
+ return new short[] {Float.floatToFloat16(1f), Float.floatToFloat16(0f)};
+ }
+
+ public void testSearchWithSkewedAcceptOrds() throws IOException {
+ int nDoc = 1000;
+ similarityFunction = VectorSimilarityFunction.EUCLIDEAN;
+ Float16VectorValues vectors = circularVectorValues(nDoc);
+ RandomVectorScorerSupplier scorerSupplier = buildScorerSupplier(vectors);
+ HnswGraphBuilder builder = HnswGraphBuilder.create(scorerSupplier, 16, 100, random().nextInt());
+ OnHeapHnswGraph hnsw = builder.build(vectors.size());
+
+ // Skip over half of the documents that are closest to the query vector
+ FixedBitSet acceptOrds = new FixedBitSet(nDoc);
+ for (int i = 500; i < nDoc; i++) {
+ acceptOrds.set(i);
+ }
+ KnnCollector nn =
+ HnswGraphSearcher.search(
+ buildScorer(vectors, getTargetVector()), 10, hnsw, acceptOrds, Integer.MAX_VALUE);
+
+ TopDocs nodes = nn.topDocs();
+ assertEquals("Number of found results is not equal to [10].", 10, nodes.scoreDocs.length);
+ int sum = 0;
+ for (ScoreDoc node : nodes.scoreDocs) {
+ assertTrue("the results include a deleted document: " + node, acceptOrds.get(node.doc));
+ sum += node.doc;
+ }
+ // We still expect to get reasonable recall. The lowest non-skipped docIds
+ // are closest to the query vector: sum(500,509) = 5045
+ assertTrue("sum(result docs)=" + sum, sum < 5100);
+ }
+}
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TermVectorLeafReader.java b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TermVectorLeafReader.java
index 0a03a61f5b1..5f4b9444c81 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TermVectorLeafReader.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/TermVectorLeafReader.java
@@ -27,6 +27,7 @@ import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.Fields;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.LeafMetaData;
@@ -175,6 +176,11 @@ public class TermVectorLeafReader extends LeafReader {
return null;
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) {
+ return null;
+ }
+
@Override
public ByteVectorValues getByteVectorValues(String fieldName) {
return null;
@@ -184,6 +190,11 @@ public class TermVectorLeafReader extends LeafReader {
public void searchNearestVectors(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {}
+
@Override
public void searchNearestVectors(
String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {}
diff --git a/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java b/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java
index 6d3f7f8dc2f..efd49fdc21f 100644
--- a/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java
+++ b/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java
@@ -37,6 +37,7 @@ import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.KnnByteVectorField;
+import org.apache.lucene.document.KnnFloat16VectorField;
import org.apache.lucene.document.KnnFloatVectorField;
import org.apache.lucene.index.BaseTermsEnum;
import org.apache.lucene.index.BinaryDocValues;
@@ -48,6 +49,7 @@ import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.FieldInvertState;
import org.apache.lucene.index.Fields;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.ImpactsEnum;
import org.apache.lucene.index.IndexOptions;
@@ -813,6 +815,30 @@ public class MemoryIndex {
+ vectorField.name()
+ "] is not a byte vector field, but the field info is configured for byte vectors");
}
+
+ case FLOAT16 -> {
+ if (vectorField instanceof KnnFloat16VectorField float16VectorField) {
+ if (info.float16VectorCount == 1) {
+ throw new IllegalArgumentException(
+ "Only one value per field allowed for float16 vector field ["
+ + vectorField.name()
+ + "]");
+ }
+ info.float16VectorCount++;
+ if (info.float16VectorValues == null) {
+ info.float16VectorValues = new short[1][];
+ }
+ info.float16VectorValues[0] =
+ ArrayUtil.copyOfSubArray(
+ float16VectorField.vectorValue(), 0, info.fieldInfo.getVectorDimension());
+ return;
+ }
+ throw new IllegalArgumentException(
+ "Field ["
+ + vectorField.name()
+ + "] is not a float16 vector field, but the field info is configured for float16 vectors");
+ }
+
case FLOAT32 -> {
if (vectorField instanceof KnnFloatVectorField floatVectorField) {
if (info.floatVectorCount == 1) {
@@ -1243,9 +1269,15 @@ public class MemoryIndex {
/** the float vectors added for this field */
private float[][] floatVectorValues;
+ /** the float16 vectors added for this field */
+ private short[][] float16VectorValues;
+
/** Number of byte vectors added for this field */
private int byteVectorCount;
+ /** Number of float16 vectors added for this field */
+ private int float16VectorCount;
+
/** the byte vectors added for this field */
private byte[][] byteVectorValues;
@@ -1747,6 +1779,15 @@ public class MemoryIndex {
return new MemoryFloatVectorValues(info);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ Info info = fields.get(field);
+ if (info == null || info.float16VectorValues == null) {
+ return null;
+ }
+ return new MemoryFloat16VectorValues(info);
+ }
+
@Override
public ByteVectorValues getByteVectorValues(String fieldName) {
Info info = fields.get(fieldName);
@@ -1760,6 +1801,11 @@ public class MemoryIndex {
public void searchNearestVectors(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {}
+
@Override
public void searchNearestVectors(
String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {}
@@ -2376,6 +2422,70 @@ public class MemoryIndex {
}
}
+ private static final class MemoryFloat16VectorValues extends Float16VectorValues {
+ private final Info info;
+
+ MemoryFloat16VectorValues(Info info) {
+ this.info = info;
+ }
+
+ @Override
+ public int dimension() {
+ return info.fieldInfo.getVectorDimension();
+ }
+
+ @Override
+ public int size() {
+ return info.float16VectorCount;
+ }
+
+ @Override
+ public short[] vectorValue(int ord) {
+ if (ord == 0) {
+ return info.float16VectorValues[0];
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public DocIndexIterator iterator() {
+ return createDenseIterator();
+ }
+
+ @Override
+ public VectorScorer scorer(short[] query) {
+ if (query.length != info.fieldInfo.getVectorDimension()) {
+ throw new IllegalArgumentException(
+ "query vector dimension "
+ + query.length
+ + " does not match field dimension "
+ + info.fieldInfo.getVectorDimension());
+ }
+ MemoryFloat16VectorValues vectorValues = new MemoryFloat16VectorValues(info);
+ DocIndexIterator iterator = vectorValues.iterator();
+ return new VectorScorer() {
+ @Override
+ public float score() throws IOException {
+ assert iterator.docID() == 0;
+ return info.fieldInfo
+ .getVectorSimilarityFunction()
+ .compare(vectorValues.vectorValue(0), query);
+ }
+
+ @Override
+ public DocIdSetIterator iterator() {
+ return iterator;
+ }
+ };
+ }
+
+ @Override
+ public MemoryFloat16VectorValues copy() {
+ return this;
+ }
+ }
+
private static final class MemoryByteVectorValues extends ByteVectorValues {
private final Info info;
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionValues.java b/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionValues.java
index ec3eb99a198..8e4b333ffa6 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionValues.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionValues.java
@@ -74,6 +74,10 @@ public abstract class FunctionValues {
throw new UnsupportedOperationException();
}
+ public short[] float16VectorVal(int doc) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
public byte[] byteVectorVal(int doc) throws IOException {
throw new UnsupportedOperationException();
}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/ConstKnnFloat16ValueSource.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/ConstKnnFloat16ValueSource.java
new file mode 100644
index 00000000000..4ca6dd9d579
--- /dev/null
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/ConstKnnFloat16ValueSource.java
@@ -0,0 +1,73 @@
+/*
+ * 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.queries.function.valuesource;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Objects;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.queries.function.FunctionValues;
+import org.apache.lucene.queries.function.ValueSource;
+
+/** Function that returns a constant float16 vector value for every document. */
+public class ConstKnnFloat16ValueSource extends ValueSource {
+ private final short[] vector;
+
+ public ConstKnnFloat16ValueSource(short[] constVector) {
+ this.vector = Objects.requireNonNull(constVector, "constVector");
+ }
+
+ @Override
+ public FunctionValues getValues(Map<Object, Object> context, LeafReaderContext readerContext)
+ throws IOException {
+ return new FunctionValues() {
+ @Override
+ public short[] float16VectorVal(int doc) {
+ return vector;
+ }
+
+ @Override
+ public String strVal(int doc) {
+ return Arrays.toString(vector);
+ }
+
+ @Override
+ public String toString(int doc) throws IOException {
+ return description() + '=' + strVal(doc);
+ }
+ };
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ ConstKnnFloat16ValueSource other = (ConstKnnFloat16ValueSource) o;
+ return Arrays.equals(vector, other.vector);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getClass().hashCode(), Arrays.hashCode(vector));
+ }
+
+ @Override
+ public String description() {
+ return "ConstKnnFloat16ValueSource(" + Arrays.toString(vector) + ')';
+ }
+}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/Float16KnnVectorFieldSource.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/Float16KnnVectorFieldSource.java
new file mode 100644
index 00000000000..c7b5b191825
--- /dev/null
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/Float16KnnVectorFieldSource.java
@@ -0,0 +1,101 @@
+/*
+ * 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.queries.function.valuesource;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.Objects;
+import org.apache.lucene.index.Float16VectorValues;
+import org.apache.lucene.index.KnnVectorValues;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.VectorEncoding;
+import org.apache.lucene.queries.function.FunctionValues;
+import org.apache.lucene.queries.function.ValueSource;
+import org.apache.lucene.search.DocIdSetIterator;
+
+/**
+ * An implementation for retrieving {@link FunctionValues} instances for float16 knn vectors fields.
+ */
+public class Float16KnnVectorFieldSource extends ValueSource {
+ private final String fieldName;
+
+ public Float16KnnVectorFieldSource(String fieldName) {
+ this.fieldName = fieldName;
+ }
+
+ @Override
+ public FunctionValues getValues(Map<Object, Object> context, LeafReaderContext readerContext)
+ throws IOException {
+
+ final LeafReader reader = readerContext.reader();
+ final Float16VectorValues vectorValues = reader.getFloat16VectorValues(fieldName);
+
+ if (vectorValues == null) {
+ VectorFieldFunction.checkField(reader, fieldName, VectorEncoding.FLOAT16);
+ return new VectorFieldFunction(this) {
+ private final DocIdSetIterator empty = DocIdSetIterator.empty();
+
+ @Override
+ public short[] float16VectorVal(int doc) throws IOException {
+ return null;
+ }
+
+ @Override
+ protected DocIdSetIterator getVectorIterator() {
+ return empty;
+ }
+ };
+ }
+
+ return new VectorFieldFunction(this) {
+ KnnVectorValues.DocIndexIterator iterator = vectorValues.iterator();
+
+ @Override
+ public short[] float16VectorVal(int doc) throws IOException {
+ if (exists(doc)) {
+ return vectorValues.vectorValue(iterator.index());
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ protected DocIdSetIterator getVectorIterator() {
+ return iterator;
+ }
+ };
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Float16KnnVectorFieldSource other = (Float16KnnVectorFieldSource) o;
+ return Objects.equals(fieldName, other.fieldName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getClass().hashCode(), fieldName);
+ }
+
+ @Override
+ public String description() {
+ return "Float16KnnVectorFieldSource(" + fieldName + ")";
+ }
+}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/Float16VectorSimilarityFunction.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/Float16VectorSimilarityFunction.java
new file mode 100644
index 00000000000..37f7dc7b532
--- /dev/null
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/Float16VectorSimilarityFunction.java
@@ -0,0 +1,48 @@
+/*
+ * 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.queries.function.valuesource;
+
+import java.io.IOException;
+import org.apache.lucene.queries.function.FunctionValues;
+import org.apache.lucene.queries.function.ValueSource;
+
+/**
+ * <code>Float16VectorSimilarityFunction</code> returns a similarity function between two knn
+ * vectors with float16 elements.
+ */
+public class Float16VectorSimilarityFunction extends VectorSimilarityFunction {
+ public Float16VectorSimilarityFunction(
+ org.apache.lucene.index.VectorSimilarityFunction similarityFunction,
+ ValueSource vector1,
+ ValueSource vector2) {
+ super(similarityFunction, vector1, vector2);
+ }
+
+ @Override
+ protected float func(int doc, FunctionValues f1, FunctionValues f2) throws IOException {
+
+ var v1 = f1.float16VectorVal(doc);
+ var v2 = f2.float16VectorVal(doc);
+
+ if (v1 == null || v2 == null) {
+ return 0.f;
+ }
+
+ assert v1.length == v2.length : "Vectors must have the same length";
+ return similarityFunction.compare(v1, v2);
+ }
+}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsReader.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsReader.java
index 580f3757c22..3d3e27db564 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsReader.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsReader.java
@@ -35,6 +35,7 @@ import org.apache.lucene.codecs.hnsw.FlatVectorsReader;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MergePolicy;
@@ -168,6 +169,11 @@ final class FaissKnnVectorsReader extends KnnVectorsReader {
throw new UnsupportedOperationException("Byte vectors not supported");
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ throw new UnsupportedOperationException("Float16 vectors not supported");
+ }
+
@Override
public void search(
String field, float[] vector, KnnCollector knnCollector, AcceptDocs acceptDocs) {
@@ -185,6 +191,12 @@ final class FaissKnnVectorsReader extends KnnVectorsReader {
throw new UnsupportedOperationException("Byte vectors not supported");
}
+ @Override
+ public void search(String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ throw new UnsupportedOperationException("Float16 vectors not supported");
+ }
+
@Override
public Map<String, Long> getOffHeapByteSize(FieldInfo fieldInfo) {
// TODO: How to estimate Faiss usage?
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java
index c269653c490..31c0f543fa6 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java
@@ -104,6 +104,7 @@ final class FaissKnnVectorsWriter extends KnnVectorsWriter {
// TODO: Support using SQ8 quantization, see:
// - https://github.com/opensearch-project/k-NN/pull/2425
throw new UnsupportedOperationException("Byte vectors not supported");
+ case FLOAT16 -> throw new UnsupportedOperationException("Float16 vectors not supported");
case FLOAT32 -> {
FloatVectorValues merged =
KnnVectorsWriter.MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState);
@@ -131,6 +132,8 @@ final class FaissKnnVectorsWriter extends KnnVectorsWriter {
// - https://github.com/opensearch-project/k-NN/pull/2425
throw new UnsupportedOperationException("Byte vectors not supported");
+ case FLOAT16 -> throw new UnsupportedOperationException("Float16 vectors not supported");
+
case FLOAT32 -> {
@SuppressWarnings("unchecked")
FlatFieldVectorsWriter<float[]> rawWriter =
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/codecs/asserting/AssertingKnnVectorsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/tests/codecs/asserting/AssertingKnnVectorsFormat.java
index f1f4f1044ad..6cc9746b1f6 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/codecs/asserting/AssertingKnnVectorsFormat.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/codecs/asserting/AssertingKnnVectorsFormat.java
@@ -28,6 +28,7 @@ import org.apache.lucene.codecs.hnsw.HnswGraphProvider;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.MergePolicy;
import org.apache.lucene.index.MergeState;
@@ -159,6 +160,20 @@ public class AssertingKnnVectorsFormat extends KnnVectorsFormat {
return values;
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ FieldInfo fi = fis.fieldInfo(field);
+ assert fi != null
+ && fi.getVectorDimension() > 0
+ && fi.getVectorEncoding() == VectorEncoding.FLOAT16;
+ Float16VectorValues values = delegate.getFloat16VectorValues(field);
+ assert values != null;
+ assert values.iterator().docID() == -1;
+ assert values.size() >= 0;
+ assert values.dimension() > 0;
+ return values;
+ }
+
@Override
public void search(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
@@ -183,6 +198,18 @@ public class AssertingKnnVectorsFormat extends KnnVectorsFormat {
delegate.search(field, target, knnCollector, acceptDocs);
}
+ @Override
+ public void search(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ FieldInfo fi = fis.fieldInfo(field);
+ assert fi != null
+ && fi.getVectorDimension() > 0
+ && fi.getVectorEncoding() == VectorEncoding.FLOAT16;
+ acceptDocs = AssertingAcceptDocs.wrap(acceptDocs);
+ delegate.search(field, target, knnCollector, acceptDocs);
+ }
+
@Override
public KnnVectorsReader getMergeInstance() throws IOException {
var mergeVectorsReader = delegate.getMergeInstance();
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/AssertingLeafReader.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/AssertingLeafReader.java
index bdedb641c47..98417d47d82 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/AssertingLeafReader.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/AssertingLeafReader.java
@@ -1914,6 +1914,14 @@ public class AssertingLeafReader extends FilterLeafReader {
super.searchNearestVectors(field, target, knnCollector, acceptDocs);
}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ acceptDocs = AssertingAcceptDocs.wrap(acceptDocs);
+ super.searchNearestVectors(field, target, knnCollector, acceptDocs);
+ }
+
// we don't change behavior of the reader: just validate the API.
@Override
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java
index 7556c0b020a..bc3b93a77db 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java
@@ -49,6 +49,7 @@ import org.apache.lucene.codecs.simpletext.SimpleTextKnnVectorsReader;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.KnnByteVectorField;
+import org.apache.lucene.document.KnnFloat16VectorField;
import org.apache.lucene.document.KnnFloatVectorField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StoredField;
@@ -61,6 +62,7 @@ import org.apache.lucene.index.DocValuesSkipIndexType;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexReader;
@@ -143,6 +145,10 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
protected void addRandomFields(Document doc) {
switch (vectorEncoding) {
case BYTE -> doc.add(new KnnByteVectorField("v2", randomVector8(30), similarityFunction));
+ case FLOAT16 ->
+ doc.add(
+ new KnnFloat16VectorField(
+ "v2", randomNormalizedFloat16Vector(30), similarityFunction));
case FLOAT32 ->
doc.add(new KnnFloatVectorField("v2", randomNormalizedVector(30), similarityFunction));
}
@@ -969,6 +975,11 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
doc.add(new KnnByteVectorField(fieldName, b, fieldSimilarityFunctions[field]));
fieldTotals[field] += b[0];
}
+ case FLOAT16 -> {
+ short[] v = randomNormalizedFloat16Vector(fieldDims[field]);
+ doc.add(new KnnFloat16VectorField(fieldName, v, fieldSimilarityFunctions[field]));
+ fieldTotals[field] += v[0];
+ }
case FLOAT32 -> {
float[] v = randomNormalizedVector(fieldDims[field]);
doc.add(new KnnFloatVectorField(fieldName, v, fieldSimilarityFunctions[field]));
@@ -999,6 +1010,19 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
}
}
}
+ case FLOAT16 -> {
+ for (LeafReaderContext ctx : r.leaves()) {
+ Float16VectorValues vectorValues = ctx.reader().getFloat16VectorValues(fieldName);
+ if (vectorValues != null) {
+ docCount += vectorValues.size();
+ KnnVectorValues.DocIndexIterator iterator = vectorValues.iterator();
+ while (true) {
+ if (!(iterator.nextDoc() != NO_MORE_DOCS)) break;
+ checksum += vectorValues.vectorValue(iterator.index())[0];
+ }
+ }
+ }
+ }
case FLOAT32 -> {
for (LeafReaderContext ctx : r.leaves()) {
FloatVectorValues vectorValues = ctx.reader().getFloatVectorValues(fieldName);
@@ -1774,6 +1798,19 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
return v;
}
+ public static short[] randomNormalizedFloat16Vector(int dim) {
+ float[] v = randomVector(dim);
+ VectorUtil.l2normalize(v);
+ for (int i = 0; i < v.length; i++) {
+ v[i] = Float.float16ToFloat(Float.floatToFloat16(v[i]));
+ }
+ short[] s = new short[v.length];
+ for (int i = 0; i < v.length; i++) {
+ s[i] = Float.floatToFloat16(v[i]);
+ }
+ return s;
+ }
+
public static float[] randomNormalizedVector(int dim) {
float[] v = randomVector(dim);
VectorUtil.l2normalize(v);
@@ -1836,7 +1873,8 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
// enumerators
assertEquals(0, VectorEncoding.BYTE.ordinal());
assertEquals(1, VectorEncoding.FLOAT32.ordinal());
- assertEquals(2, VectorEncoding.values().length);
+ assertEquals(2, VectorEncoding.FLOAT16.ordinal());
+ assertEquals(3, VectorEncoding.values().length);
}
public void testAdvance() throws Exception {
@@ -1912,6 +1950,11 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
fieldValuesCheckSum += b[0];
doc.add(new KnnByteVectorField("knn_vector", b, similarityFunction));
}
+ case FLOAT16 -> {
+ short[] v = randomNormalizedFloat16Vector(dim);
+ fieldValuesCheckSum += v[0];
+ doc.add(new KnnFloat16VectorField("knn_vector", v, similarityFunction));
+ }
case FLOAT32 -> {
float[] v = randomNormalizedVector(dim);
fieldValuesCheckSum += v[0];
@@ -1956,6 +1999,27 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
}
}
}
+ case FLOAT16 -> {
+ for (LeafReaderContext ctx : r.leaves()) {
+ Float16VectorValues vectorValues = ctx.reader().getFloat16VectorValues("knn_vector");
+ if (vectorValues != null) {
+ docCount += vectorValues.size();
+ StoredFields storedFields = ctx.reader().storedFields();
+ KnnVectorValues.DocIndexIterator iter = vectorValues.iterator();
+ for (iter.nextDoc(); iter.docID() != NO_MORE_DOCS; iter.nextDoc()) {
+ int ord = iter.index();
+ checksum += vectorValues.vectorValue(ord)[0];
+ Document doc = storedFields.document(iter.docID(), Set.of("id"));
+ sumDocIds += Integer.parseInt(doc.get("id"));
+ }
+ for (int ord = 0; ord < vectorValues.size(); ord++) {
+ Document doc = storedFields.document(vectorValues.ordToDoc(ord), Set.of("id"));
+ sumOrdToDocIds += Integer.parseInt(doc.get("id"));
+ }
+ assertOffHeapByteSize(ctx.reader(), "knn_vector");
+ }
+ }
+ }
case FLOAT32 -> {
for (LeafReaderContext ctx : r.leaves()) {
FloatVectorValues vectorValues = ctx.reader().getFloatVectorValues("knn_vector");
@@ -2350,6 +2414,7 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
return switch (fieldInfo.getVectorEncoding()) {
case BYTE -> reader.getByteVectorValues(fieldInfo.getName()).size();
case FLOAT32 -> reader.getFloatVectorValues(fieldInfo.getName()).size();
+ case FLOAT16 -> reader.getFloat16VectorValues(fieldInfo.getName()).size();
};
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/MergeReaderWrapper.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/MergeReaderWrapper.java
index 3d2c802413d..bf5cd83c564 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/MergeReaderWrapper.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/MergeReaderWrapper.java
@@ -30,6 +30,7 @@ import org.apache.lucene.index.DocValuesSkipper;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.LeafMetaData;
import org.apache.lucene.index.LeafReader;
@@ -235,6 +236,11 @@ class MergeReaderWrapper extends LeafReader {
return in.getFloatVectorValues(fieldName);
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ return in.getFloat16VectorValues(field);
+ }
+
@Override
public ByteVectorValues getByteVectorValues(String fieldName) throws IOException {
return in.getByteVectorValues(fieldName);
@@ -247,6 +253,13 @@ class MergeReaderWrapper extends LeafReader {
in.searchNearestVectors(field, target, knnCollector, acceptDocs);
}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {
+ in.searchNearestVectors(field, target, knnCollector, acceptDocs);
+ }
+
@Override
public void searchNearestVectors(
String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/search/QueryUtils.java b/lucene/test-framework/src/java/org/apache/lucene/tests/search/QueryUtils.java
index 41d94746d0d..b7f58280a64 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/search/QueryUtils.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/search/QueryUtils.java
@@ -27,6 +27,7 @@ import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.ByteVectorValues;
import org.apache.lucene.index.DocValuesSkipper;
import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.Float16VectorValues;
import org.apache.lucene.index.FloatVectorValues;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafMetaData;
@@ -237,6 +238,11 @@ public class QueryUtils {
return null;
}
+ @Override
+ public Float16VectorValues getFloat16VectorValues(String field) throws IOException {
+ return null;
+ }
+
@Override
public ByteVectorValues getByteVectorValues(String field) throws IOException {
return null;
@@ -246,6 +252,11 @@ public class QueryUtils {
public void searchNearestVectors(
String field, float[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {}
+ @Override
+ public void searchNearestVectors(
+ String field, short[] target, KnnCollector knnCollector, AcceptDocs acceptDocs)
+ throws IOException {}
+
@Override
public void searchNearestVectors(
String field, byte[] target, KnnCollector knnCollector, AcceptDocs acceptDocs) {}