navneet1v commented on code in PR #14178:
URL: https://github.com/apache/lucene/pull/14178#discussion_r1934791780


##########
lucene/sandbox/src/java22/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java:
##########
@@ -0,0 +1,204 @@
+/*
+ * 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.NAME;
+import static 
org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat.VERSION_CURRENT;
+import static org.apache.lucene.sandbox.codecs.faiss.LibFaissC.createIndex;
+import static org.apache.lucene.sandbox.codecs.faiss.LibFaissC.indexWrite;
+
+import java.io.IOException;
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.apache.lucene.codecs.BufferingKnnVectorsWriter;
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.codecs.KnnFieldVectorsWriter;
+import org.apache.lucene.codecs.KnnVectorsWriter;
+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.MergeState;
+import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.index.Sorter;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.store.InputStreamDataInput;
+import org.apache.lucene.util.IOUtils;
+
+public final class FaissKnnVectorsWriter extends BufferingKnnVectorsWriter {
+  private final String description, indexParams;
+  private final KnnVectorsWriter rawVectorsWriter;
+  private final IndexOutput meta, data;
+  private boolean finished;
+
+  public FaissKnnVectorsWriter(
+      String description,
+      String indexParams,
+      SegmentWriteState state,
+      KnnVectorsWriter rawVectorsWriter)
+      throws IOException {
+    this.description = description;
+    this.indexParams = indexParams;
+    this.rawVectorsWriter = rawVectorsWriter;
+    this.finished = false;
+
+    boolean failure = true;
+    try {
+      this.meta = openOutput(state, META_EXTENSION, META_CODEC_NAME);
+      this.data = openOutput(state, DATA_EXTENSION, DATA_CODEC_NAME);
+      failure = false;
+    } finally {
+      if (failure) {
+        IOUtils.closeWhileHandlingException(this);
+      }
+    }
+  }
+
+  private IndexOutput openOutput(SegmentWriteState state, String extension, 
String codecName)
+      throws IOException {
+    String fileName =
+        IndexFileNames.segmentFileName(state.segmentInfo.name, 
state.segmentSuffix, extension);
+    IndexOutput output = state.directory.createOutput(fileName, state.context);
+    CodecUtil.writeIndexHeader(
+        output, codecName, VERSION_CURRENT, state.segmentInfo.getId(), 
state.segmentSuffix);
+    return output;
+  }
+
+  @Override
+  @SuppressWarnings("unchecked")
+  public KnnFieldVectorsWriter<?> addField(FieldInfo fieldInfo) throws 
IOException {
+    return switch (fieldInfo.getVectorEncoding()) {
+      case BYTE -> throw new UnsupportedOperationException("Byte vectors not 
supported");

Review Comment:
   is this something which will be supported in upcoming PRs? Because the way 
atleast faiss supports byte vector is you pass the float[] to faiss which has 
values within the range of byte and then use the faiss encoders to create a 
byte vector index. Ref: https://github.com/opensearch-project/k-NN/pull/2425 
Opensearch is already looking to add this support. :) Happy to chat on this on 
how we can enable it here. 



##########
lucene/sandbox/src/java22/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsFormat.java:
##########
@@ -0,0 +1,75 @@
+/*
+ * 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 java.io.IOException;
+import java.util.Locale;
+import org.apache.lucene.codecs.KnnVectorsFormat;
+import org.apache.lucene.codecs.KnnVectorsReader;
+import org.apache.lucene.codecs.KnnVectorsWriter;
+import org.apache.lucene.codecs.hnsw.FlatVectorScorerUtil;
+import org.apache.lucene.codecs.lucene99.Lucene99FlatVectorsFormat;
+import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SegmentWriteState;
+
+public final class FaissKnnVectorsFormat extends KnnVectorsFormat {
+  public static final String NAME = 
FaissKnnVectorsFormat.class.getSimpleName();
+  static final int VERSION_START = 0;
+  static final int VERSION_CURRENT = VERSION_START;
+  static final String META_CODEC_NAME = NAME + "Meta";
+  static final String DATA_CODEC_NAME = NAME + "Data";
+  static final String META_EXTENSION = "faissm";
+  static final String DATA_EXTENSION = "faissd";
+
+  private final String description;
+  private final String indexParams;
+  private final KnnVectorsFormat rawVectorsFormat;
+
+  public FaissKnnVectorsFormat() {
+    this("HNSW32", "efConstruction=200");
+  }
+
+  public FaissKnnVectorsFormat(String description, String indexParams) {
+    super(NAME);
+    this.description = description;
+    this.indexParams = indexParams;
+    this.rawVectorsFormat =
+        new 
Lucene99FlatVectorsFormat(FlatVectorScorerUtil.getLucene99FlatVectorsScorer());

Review Comment:
   since Faiss already stores this information in the index what is the reason 
to have a RawFlatVectorsFormat?



##########
lucene/sandbox/src/java22/org/apache/lucene/sandbox/codecs/faiss/LibFaissC.java:
##########
@@ -0,0 +1,268 @@
+/*
+ * 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.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.nio.ByteOrder;
+import java.nio.FloatBuffer;
+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.util.Bits;
+
+public final class LibFaissC {
+  public static final String LIBRARY_VERSION = "1.9.0";
+
+  static {
+    try {
+      System.loadLibrary("faiss_c");
+    } 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() {}
+
+  private static MethodHandle getMethodHandle(
+      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 = getMethodHandle("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 =
+      getMethodHandle("faiss_Index_free", JAVA_INT, ADDRESS);
+
+  public static void freeIndex(MemorySegment indexPointer) {
+    callAndHandleError(FREE_INDEX, indexPointer);
+  }
+
+  private static final MethodHandle FREE_PARAMETER_SPACE =
+      getMethodHandle("faiss_ParameterSpace_free", JAVA_INT, ADDRESS);
+
+  private static void freeParameterSpace(MemorySegment parameterSpacePointer) {
+    callAndHandleError(FREE_PARAMETER_SPACE, parameterSpacePointer);
+  }
+
+  private static final MethodHandle INDEX_FACTORY =
+      getMethodHandle("faiss_index_factory", JAVA_INT, ADDRESS, JAVA_INT, 
ADDRESS, JAVA_INT);
+
+  private static final MethodHandle PARAMETER_SPACE_NEW =
+      getMethodHandle("faiss_ParameterSpace_new", JAVA_INT, ADDRESS);
+
+  private static final MethodHandle SET_INDEX_PARAMETERS =
+      getMethodHandle(
+          "faiss_ParameterSpace_set_index_parameters", JAVA_INT, ADDRESS, 
ADDRESS, ADDRESS);
+
+  private static final MethodHandle INDEX_IS_TRAINED =
+      getMethodHandle("faiss_Index_is_trained", JAVA_INT, ADDRESS);
+
+  private static final MethodHandle INDEX_TRAIN =
+      getMethodHandle("faiss_Index_train", JAVA_INT, ADDRESS, JAVA_LONG, 
ADDRESS);
+
+  private static final MethodHandle INDEX_ADD =
+      getMethodHandle("faiss_Index_add", JAVA_INT, ADDRESS, JAVA_LONG, 
ADDRESS);
+
+  public record Index(MemorySegment indexPointer, int[] ordToDoc) {}
+
+  public static Index createIndex(
+      String description,
+      String indexParams,
+      VectorSimilarityFunction function,
+      FloatVectorValues floatVectorValues) {
+
+    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);

Review Comment:
   there is an index in faiss called as IndexIDMap, that can wrap any Faiss 
index which can be used here to avoid having another ordToDoc array. Faiss 
internally maintains that mapping and will only give you the docIds as results 
on what you have passed during construction. See if we want to use that. FYI 
opensearch actually uses that. :) 



##########
lucene/sandbox/src/java22/org/apache/lucene/sandbox/codecs/faiss/FaissKnnVectorsWriter.java:
##########
@@ -0,0 +1,204 @@
+/*
+ * 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.NAME;
+import static 
org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat.VERSION_CURRENT;
+import static org.apache.lucene.sandbox.codecs.faiss.LibFaissC.createIndex;
+import static org.apache.lucene.sandbox.codecs.faiss.LibFaissC.indexWrite;
+
+import java.io.IOException;
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.apache.lucene.codecs.BufferingKnnVectorsWriter;
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.codecs.KnnFieldVectorsWriter;
+import org.apache.lucene.codecs.KnnVectorsWriter;
+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.MergeState;
+import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.index.Sorter;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.store.InputStreamDataInput;
+import org.apache.lucene.util.IOUtils;
+
+public final class FaissKnnVectorsWriter extends BufferingKnnVectorsWriter {
+  private final String description, indexParams;
+  private final KnnVectorsWriter rawVectorsWriter;
+  private final IndexOutput meta, data;
+  private boolean finished;
+
+  public FaissKnnVectorsWriter(
+      String description,
+      String indexParams,
+      SegmentWriteState state,
+      KnnVectorsWriter rawVectorsWriter)
+      throws IOException {
+    this.description = description;
+    this.indexParams = indexParams;
+    this.rawVectorsWriter = rawVectorsWriter;
+    this.finished = false;
+
+    boolean failure = true;
+    try {
+      this.meta = openOutput(state, META_EXTENSION, META_CODEC_NAME);
+      this.data = openOutput(state, DATA_EXTENSION, DATA_CODEC_NAME);
+      failure = false;
+    } finally {
+      if (failure) {
+        IOUtils.closeWhileHandlingException(this);
+      }
+    }
+  }
+
+  private IndexOutput openOutput(SegmentWriteState state, String extension, 
String codecName)
+      throws IOException {
+    String fileName =
+        IndexFileNames.segmentFileName(state.segmentInfo.name, 
state.segmentSuffix, extension);
+    IndexOutput output = state.directory.createOutput(fileName, state.context);
+    CodecUtil.writeIndexHeader(
+        output, codecName, VERSION_CURRENT, state.segmentInfo.getId(), 
state.segmentSuffix);
+    return output;
+  }
+
+  @Override
+  @SuppressWarnings("unchecked")
+  public KnnFieldVectorsWriter<?> addField(FieldInfo fieldInfo) throws 
IOException {
+    return switch (fieldInfo.getVectorEncoding()) {
+      case BYTE -> throw new UnsupportedOperationException("Byte vectors not 
supported");
+      case FLOAT32 ->
+          new KnnFieldVectorsWriter<float[]>() {
+            private final KnnFieldVectorsWriter<float[]> rawWriter =
+                (KnnFieldVectorsWriter<float[]>) 
rawVectorsWriter.addField(fieldInfo);
+            private final KnnFieldVectorsWriter<float[]> writer =
+                (KnnFieldVectorsWriter<float[]>) 
FaissKnnVectorsWriter.super.addField(fieldInfo);
+
+            @Override
+            public long ramBytesUsed() {
+              return rawWriter.ramBytesUsed() + writer.ramBytesUsed();
+            }
+
+            @Override
+            public void addValue(int i, float[] floats) throws IOException {
+              rawWriter.addValue(i, floats);
+              writer.addValue(i, floats);
+            }
+
+            @Override
+            public float[] copyValue(float[] floats) {
+              return floats.clone();
+            }
+          };
+    };
+  }
+
+  @Override
+  public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws 
IOException {
+    rawVectorsWriter.mergeOneField(fieldInfo, mergeState);
+    super.mergeOneField(fieldInfo, mergeState);
+  }
+
+  @Override
+  protected void writeField(FieldInfo fieldInfo, FloatVectorValues 
floatVectorValues, int maxDoc)
+      throws IOException {
+    int number = fieldInfo.number;
+    meta.writeInt(number);
+
+    VectorSimilarityFunction function = 
fieldInfo.getVectorSimilarityFunction();
+    int size = floatVectorValues.size();
+
+    // TODO: Non FS-based approach?
+    Path tempFile = Files.createTempFile(NAME, fieldInfo.name);

Review Comment:
   This is a limitation with Faiss where it requires a file path for writing 
the index. Opensearch k-NN plugin removed this limitation in recent version of 
Opensearch ref: https://github.com/opensearch-project/k-NN/issues/2033 . So 
Faiss provides an IOInterface which be used to read and write the data on a 
stream. If this is something planned in next PRs then feel free to ignore the 
comment. 



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

Reply via email to