navneet1v commented on code in PR #14178: URL: https://github.com/apache/lucene/pull/14178#discussion_r1955523940
########## lucene/sandbox/src/java22/org/apache/lucene/sandbox/codecs/faiss/LibFaissC.java: ########## @@ -0,0 +1,457 @@ +/* + * 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.sandbox.codecs.faiss; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_FLOAT; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; + +import java.io.IOException; +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemoryLayout; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; +import java.nio.LongBuffer; +import java.util.Locale; +import org.apache.lucene.index.FloatVectorValues; +import org.apache.lucene.index.KnnVectorValues; +import org.apache.lucene.index.VectorSimilarityFunction; +import org.apache.lucene.search.KnnCollector; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.util.Bits; +import org.apache.lucene.util.FixedBitSet; +import org.apache.lucene.util.hnsw.IntToIntFunction; + +public final class LibFaissC { + /* + * TODO: Requires some changes to Faiss + * - https://github.com/facebookresearch/faiss/pull/4158 (merged in main, to be released in v1.11.0) + * - https://github.com/facebookresearch/faiss/pull/4167 (merged in main, to be released in v1.11.0) + * - https://github.com/facebookresearch/faiss/pull/4180 (in progress) + */ + + public static final String LIBRARY_NAME = "faiss_c"; + public static final String LIBRARY_VERSION = "1.10.0"; + + static { + try { + System.loadLibrary(LIBRARY_NAME); + } catch (UnsatisfiedLinkError e) { + throw new RuntimeException( + "Shared library not found, build the Faiss C_API from https://github.com/facebookresearch/faiss/blob/main/c_api/INSTALL.md " + + "and link it (along with all dependencies) to the library path " + + "(-Djava.library.path JVM argument or $LD_LIBRARY_PATH environment variable)", + e); + } + checkLibraryVersion(); + } + + private LibFaissC() {} + + @SuppressWarnings("SameParameterValue") + private static MemorySegment getUpcallStub( + Arena arena, MethodHandle target, MemoryLayout resLayout, MemoryLayout... argLayouts) { + return Linker.nativeLinker() + .upcallStub(target, FunctionDescriptor.of(resLayout, argLayouts), arena); + } + + private static MethodHandle getDowncallHandle( + String functionName, MemoryLayout resLayout, MemoryLayout... argLayouts) { + return Linker.nativeLinker() + .downcallHandle( + SymbolLookup.loaderLookup().find(functionName).orElseThrow(), + FunctionDescriptor.of(resLayout, argLayouts)); + } + + private static void checkLibraryVersion() { + MethodHandle getVersion = getDowncallHandle("faiss_get_version", ADDRESS); + String actualVersion = callAndGetString(getVersion); + if (LIBRARY_VERSION.equals(actualVersion) == false) { + throw new UnsupportedOperationException( + String.format( + Locale.ROOT, + "Expected Faiss library version %s, found %s", + LIBRARY_VERSION, + actualVersion)); + } + } + + private static final MethodHandle FREE_INDEX = + getDowncallHandle("faiss_Index_free", JAVA_INT, ADDRESS); + + public static void freeIndex(MemorySegment indexPointer) { + callAndHandleError(FREE_INDEX, indexPointer); + } + + private static final MethodHandle FREE_CUSTOM_IO_WRITER = + getDowncallHandle("faiss_CustomIOWriter_free", JAVA_INT, ADDRESS); + + public static void freeCustomIOWriter(MemorySegment customIOWriterPointer) { + callAndHandleError(FREE_CUSTOM_IO_WRITER, customIOWriterPointer); + } + + private static final MethodHandle FREE_CUSTOM_IO_READER = + getDowncallHandle("faiss_CustomIOReader_free", JAVA_INT, ADDRESS); + + public static void freeCustomIOReader(MemorySegment customIOReaderPointer) { + callAndHandleError(FREE_CUSTOM_IO_READER, customIOReaderPointer); + } + + private static final MethodHandle FREE_PARAMETER_SPACE = + getDowncallHandle("faiss_ParameterSpace_free", JAVA_INT, ADDRESS); + + private static void freeParameterSpace(MemorySegment parameterSpacePointer) { + callAndHandleError(FREE_PARAMETER_SPACE, parameterSpacePointer); + } + + private static final MethodHandle FREE_ID_SELECTOR_BITMAP = + getDowncallHandle("faiss_IDSelectorBitmap_free", JAVA_INT, ADDRESS); + + private static void freeIDSelectorBitmap(MemorySegment idSelectorBitmapPointer) { + callAndHandleError(FREE_ID_SELECTOR_BITMAP, idSelectorBitmapPointer); + } + + private static final MethodHandle FREE_SEARCH_PARAMETERS = + getDowncallHandle("faiss_SearchParameters_free", JAVA_INT, ADDRESS); + + private static void freeSearchParameters(MemorySegment searchParametersPointer) { + callAndHandleError(FREE_SEARCH_PARAMETERS, searchParametersPointer); + } + + private static final MethodHandle INDEX_FACTORY = + getDowncallHandle("faiss_index_factory", JAVA_INT, ADDRESS, JAVA_INT, ADDRESS, JAVA_INT); + + private static final MethodHandle PARAMETER_SPACE_NEW = + getDowncallHandle("faiss_ParameterSpace_new", JAVA_INT, ADDRESS); + + private static final MethodHandle SET_INDEX_PARAMETERS = + getDowncallHandle( + "faiss_ParameterSpace_set_index_parameters", JAVA_INT, ADDRESS, ADDRESS, ADDRESS); + + private static final MethodHandle ID_SELECTOR_BITMAP_NEW = + getDowncallHandle("faiss_IDSelectorBitmap_new", JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS); + + private static final MethodHandle SEARCH_PARAMETERS_NEW = + getDowncallHandle("faiss_SearchParameters_new", JAVA_INT, ADDRESS, ADDRESS); + + private static final MethodHandle INDEX_IS_TRAINED = + getDowncallHandle("faiss_Index_is_trained", JAVA_INT, ADDRESS); + + private static final MethodHandle INDEX_TRAIN = + getDowncallHandle("faiss_Index_train", JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS); + + private static final MethodHandle INDEX_ADD_WITH_IDS = + getDowncallHandle("faiss_Index_add_with_ids", JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS); + + public static MemorySegment createIndex( + String description, + String indexParams, + VectorSimilarityFunction function, + FloatVectorValues floatVectorValues, + IntToIntFunction oldToNewDocId) + throws IOException { + + try (Arena temp = Arena.ofConfined()) { + int size = floatVectorValues.size(); + int dimension = floatVectorValues.dimension(); + + // Mapped from faiss/MetricType.h + int metric = + switch (function) { + case DOT_PRODUCT -> 0; Review Comment: I think you might want to use MAX_INNER_PRODUCT of Lucene to Faiss DOT_PRODUCT. ########## lucene/sandbox/src/java22/org/apache/lucene/sandbox/codecs/faiss/LibFaissC.java: ########## @@ -0,0 +1,457 @@ +/* + * 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.sandbox.codecs.faiss; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_FLOAT; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; + +import java.io.IOException; +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemoryLayout; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; +import java.nio.LongBuffer; +import java.util.Locale; +import org.apache.lucene.index.FloatVectorValues; +import org.apache.lucene.index.KnnVectorValues; +import org.apache.lucene.index.VectorSimilarityFunction; +import org.apache.lucene.search.KnnCollector; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.util.Bits; +import org.apache.lucene.util.FixedBitSet; +import org.apache.lucene.util.hnsw.IntToIntFunction; + +public final class LibFaissC { + /* + * TODO: Requires some changes to Faiss + * - https://github.com/facebookresearch/faiss/pull/4158 (merged in main, to be released in v1.11.0) + * - https://github.com/facebookresearch/faiss/pull/4167 (merged in main, to be released in v1.11.0) + * - https://github.com/facebookresearch/faiss/pull/4180 (in progress) + */ + + public static final String LIBRARY_NAME = "faiss_c"; + public static final String LIBRARY_VERSION = "1.10.0"; + + static { + try { + System.loadLibrary(LIBRARY_NAME); + } catch (UnsatisfiedLinkError e) { + throw new RuntimeException( + "Shared library not found, build the Faiss C_API from https://github.com/facebookresearch/faiss/blob/main/c_api/INSTALL.md " + + "and link it (along with all dependencies) to the library path " + + "(-Djava.library.path JVM argument or $LD_LIBRARY_PATH environment variable)", + e); + } + checkLibraryVersion(); + } + + private LibFaissC() {} + + @SuppressWarnings("SameParameterValue") + private static MemorySegment getUpcallStub( + Arena arena, MethodHandle target, MemoryLayout resLayout, MemoryLayout... argLayouts) { + return Linker.nativeLinker() + .upcallStub(target, FunctionDescriptor.of(resLayout, argLayouts), arena); + } + + private static MethodHandle getDowncallHandle( + String functionName, MemoryLayout resLayout, MemoryLayout... argLayouts) { + return Linker.nativeLinker() + .downcallHandle( + SymbolLookup.loaderLookup().find(functionName).orElseThrow(), + FunctionDescriptor.of(resLayout, argLayouts)); + } + + private static void checkLibraryVersion() { + MethodHandle getVersion = getDowncallHandle("faiss_get_version", ADDRESS); + String actualVersion = callAndGetString(getVersion); + if (LIBRARY_VERSION.equals(actualVersion) == false) { + throw new UnsupportedOperationException( + String.format( + Locale.ROOT, + "Expected Faiss library version %s, found %s", + LIBRARY_VERSION, + actualVersion)); + } + } + + private static final MethodHandle FREE_INDEX = + getDowncallHandle("faiss_Index_free", JAVA_INT, ADDRESS); + + public static void freeIndex(MemorySegment indexPointer) { + callAndHandleError(FREE_INDEX, indexPointer); + } + + private static final MethodHandle FREE_CUSTOM_IO_WRITER = + getDowncallHandle("faiss_CustomIOWriter_free", JAVA_INT, ADDRESS); + + public static void freeCustomIOWriter(MemorySegment customIOWriterPointer) { + callAndHandleError(FREE_CUSTOM_IO_WRITER, customIOWriterPointer); + } + + private static final MethodHandle FREE_CUSTOM_IO_READER = + getDowncallHandle("faiss_CustomIOReader_free", JAVA_INT, ADDRESS); + + public static void freeCustomIOReader(MemorySegment customIOReaderPointer) { + callAndHandleError(FREE_CUSTOM_IO_READER, customIOReaderPointer); + } + + private static final MethodHandle FREE_PARAMETER_SPACE = + getDowncallHandle("faiss_ParameterSpace_free", JAVA_INT, ADDRESS); + + private static void freeParameterSpace(MemorySegment parameterSpacePointer) { + callAndHandleError(FREE_PARAMETER_SPACE, parameterSpacePointer); + } + + private static final MethodHandle FREE_ID_SELECTOR_BITMAP = + getDowncallHandle("faiss_IDSelectorBitmap_free", JAVA_INT, ADDRESS); + + private static void freeIDSelectorBitmap(MemorySegment idSelectorBitmapPointer) { + callAndHandleError(FREE_ID_SELECTOR_BITMAP, idSelectorBitmapPointer); + } + + private static final MethodHandle FREE_SEARCH_PARAMETERS = + getDowncallHandle("faiss_SearchParameters_free", JAVA_INT, ADDRESS); + + private static void freeSearchParameters(MemorySegment searchParametersPointer) { + callAndHandleError(FREE_SEARCH_PARAMETERS, searchParametersPointer); + } + + private static final MethodHandle INDEX_FACTORY = + getDowncallHandle("faiss_index_factory", JAVA_INT, ADDRESS, JAVA_INT, ADDRESS, JAVA_INT); + + private static final MethodHandle PARAMETER_SPACE_NEW = + getDowncallHandle("faiss_ParameterSpace_new", JAVA_INT, ADDRESS); + + private static final MethodHandle SET_INDEX_PARAMETERS = + getDowncallHandle( + "faiss_ParameterSpace_set_index_parameters", JAVA_INT, ADDRESS, ADDRESS, ADDRESS); + + private static final MethodHandle ID_SELECTOR_BITMAP_NEW = + getDowncallHandle("faiss_IDSelectorBitmap_new", JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS); + + private static final MethodHandle SEARCH_PARAMETERS_NEW = + getDowncallHandle("faiss_SearchParameters_new", JAVA_INT, ADDRESS, ADDRESS); + + private static final MethodHandle INDEX_IS_TRAINED = + getDowncallHandle("faiss_Index_is_trained", JAVA_INT, ADDRESS); + + private static final MethodHandle INDEX_TRAIN = + getDowncallHandle("faiss_Index_train", JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS); + + private static final MethodHandle INDEX_ADD_WITH_IDS = + getDowncallHandle("faiss_Index_add_with_ids", JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS); + + public static MemorySegment createIndex( + String description, + String indexParams, + VectorSimilarityFunction function, + FloatVectorValues floatVectorValues, + IntToIntFunction oldToNewDocId) + throws IOException { + + try (Arena temp = Arena.ofConfined()) { + int size = floatVectorValues.size(); + int dimension = floatVectorValues.dimension(); + + // Mapped from faiss/MetricType.h + int metric = + switch (function) { + case DOT_PRODUCT -> 0; + case EUCLIDEAN -> 1; + default -> throw new UnsupportedOperationException("Metric type not supported"); + }; + + // Create an index + MemorySegment pointer = temp.allocate(ADDRESS); + callAndHandleError(INDEX_FACTORY, pointer, dimension, temp.allocateFrom(description), metric); + MemorySegment indexPointer = pointer.get(ADDRESS, 0); Review Comment: Once you get the index pointer, and since we already know how many vectors we are going to add in the index, we can just increase the storage of the index upfront. This will avoid the array/std::vector resizing in faiss happens when you start to call the add_with_ids function. In Opensearch, we call this as iterative graph builds. Pasting the [GH issue](https://github.com/opensearch-project/k-NN/issues/1938) and a code pointer on how to init the space for the index to ensure that during add/add_with_ids no memory spikes are happening. Code Pointer: https://github.com/opensearch-project/k-NN/blob/main/jni/src/faiss_index_service.cpp#L64-L68 Not sure if you want to add this optimization in the current PR or in next PR. ########## lucene/sandbox/src/java22/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsReader.java: ########## @@ -0,0 +1,182 @@ +/* + * 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.sandbox.codecs.faiss; + +import static org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat.DATA_CODEC_NAME; +import static org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat.DATA_EXTENSION; +import static org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat.META_CODEC_NAME; +import static org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat.META_EXTENSION; +import static org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat.VERSION_CURRENT; +import static org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat.VERSION_START; +import static org.apache.lucene.sandbox.codecs.faiss.LibFaissC.indexRead; +import static org.apache.lucene.sandbox.codecs.faiss.LibFaissC.indexSearch; + +import java.io.IOException; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.util.HashMap; +import java.util.Map; +import org.apache.lucene.codecs.CodecUtil; +import org.apache.lucene.codecs.KnnVectorsReader; +import org.apache.lucene.codecs.hnsw.FlatVectorsReader; +import org.apache.lucene.index.ByteVectorValues; +import org.apache.lucene.index.FieldInfo; +import org.apache.lucene.index.FloatVectorValues; +import org.apache.lucene.index.IndexFileNames; +import org.apache.lucene.index.SegmentReadState; +import org.apache.lucene.search.KnnCollector; +import org.apache.lucene.store.IOContext; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.ReadAdvice; +import org.apache.lucene.util.Bits; +import org.apache.lucene.util.IOUtils; + +public final class FaissKnnVectorsReader extends KnnVectorsReader { + private final FlatVectorsReader rawVectorsReader; + private final IndexInput meta, data; + private final Map<String, MemorySegment> indexMap; + private final Arena arena; + + public FaissKnnVectorsReader(SegmentReadState state, FlatVectorsReader rawVectorsReader) + throws IOException { + this.rawVectorsReader = rawVectorsReader; + this.indexMap = new HashMap<>(); + this.arena = Arena.ofConfined(); + + boolean failure = true; + try { + meta = + openInput( + state, + META_EXTENSION, + META_CODEC_NAME, + VERSION_START, + VERSION_CURRENT, + state.context); + data = + openInput( + state, + DATA_EXTENSION, + DATA_CODEC_NAME, + VERSION_START, + VERSION_CURRENT, + state.context.withReadAdvice(ReadAdvice.RANDOM)); + + Map.Entry<String, MemorySegment> entry; + while ((entry = parseNextField(state)) != null) { + this.indexMap.put(entry.getKey(), entry.getValue()); + } + + failure = false; + } finally { + if (failure) { + IOUtils.closeWhileHandlingException(this); + } + } + } + + @SuppressWarnings("SameParameterValue") + private IndexInput openInput( + SegmentReadState state, + String extension, + String codecName, + int versionStart, + int versionEnd, + IOContext context) + throws IOException { + + String fileName = + IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, extension); + IndexInput input = state.directory.openInput(fileName, context); + CodecUtil.checkIndexHeader( + input, codecName, versionStart, versionEnd, state.segmentInfo.getId(), state.segmentSuffix); + return input; + } + + private Map.Entry<String, MemorySegment> parseNextField(SegmentReadState state) + throws IOException { + int fieldNumber = meta.readInt(); + if (fieldNumber == -1) { + return null; + } + + FieldInfo fieldInfo = state.fieldInfos.fieldInfo(fieldNumber); + if (fieldInfo == null) { + throw new IllegalStateException("Invalid field"); + } + + long dataOffset = meta.readLong(); + long dataLength = meta.readLong(); + + // See flags defined in c_api/index_io_c.h + int ioFlags = 3; + + // Read index into memory + MemorySegment indexPointer = + indexRead(data.slice(fieldInfo.name, dataOffset, dataLength), ioFlags) + // Ensure timely cleanup + .reinterpret(arena, LibFaissC::freeIndex); Review Comment: does this map the whole index to memory and keep it ready to be served? Or index file will be just mapped into memory just like any other Lucene file. I think its the first one. Please correct me if I am wrong. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: issues-unsubscr...@lucene.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@lucene.apache.org For additional commands, e-mail: issues-h...@lucene.apache.org