Skip to content
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions .github/workflows/run-special-checks-sandbox.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: "Run special checks: module lucene/sandbox"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm add a CHANGES.txt entry? I think this can be safely backported to 10.x, after we bake for a week or two in main? It's sandbox, completely separate from everything else, experimental ...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added!

It's sandbox, completely separate from everything else, experimental ...

+1 -- I don't think it should affect users who won't use it

on:
workflow_dispatch:

pull_request:
branches:
- '*'

push:
branches:
- 'main'
- 'branch_10x'

jobs:
faiss-tests:
name: tests for the Faiss codec (v${{ matrix.faiss-version }} with JDK ${{ matrix.java }} on ${{ matrix.os }})
timeout-minutes: 15

strategy:
matrix:
os: [ ubuntu-latest ]
java: [ '24' ]
faiss-version: [ '1.11.0' ]

runs-on: ${{ matrix.os }}

steps:
- name: Install Faiss
uses: mamba-org/setup-micromamba@v2
id: setup
with:
environment-name: faiss-env
# TODO: Use only conda-forge if possible, see https://github.com/conda-forge/faiss-split-feedstock/pull/88
condarc: 'channels: [pytorch, conda-forge]'
create-args: faiss-cpu=${{ matrix.faiss-version }}

- name: Checkout Lucene
uses: actions/checkout@v4

- name: Prepare Lucene workspace
uses: ./.github/actions/prepare-for-build

- name: Run tests for Faiss codec
env:
LD_LIBRARY_PATH: ${{ steps.setup.outputs.environment-path }}/lib
run: ./gradlew -p lucene/sandbox -Dtests.faiss.run=true test --tests "org.apache.lucene.sandbox.codecs.faiss.*"

defaults:
run:
shell: bash -leo pipefail {0}
1 change: 1 addition & 0 deletions gradle/testing/defaults-tests.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ allprojects {
':lucene:core',
':lucene:codecs',
":lucene:distribution.tests",
':lucene:sandbox',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm was this a pre-existing issue (not running any tests in sandbox module when running a root ./gradlew test)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line allows the sandbox module to call native libraries from tests (i.e. --enable-native-access), but tests were still being run earlier..

":lucene:test-framework"
] ? 'ALL-UNNAMED' : 'org.apache.lucene.core')

Expand Down
1 change: 1 addition & 0 deletions gradle/testing/randomization.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ allprojects {
description: "Forces use of integer vectors even when slow."],
[propName: 'tests.defaultvectorization', value: false,
description: "Uses defaults for running tests with correct JVM settings to test Panama vectorization (tests.jvmargs, tests.vectorsize, tests.forceintegervectors)."],
[propName: 'tests.faiss.run', value: false, description: "Explicitly run tests for the Faiss codec."],
]
}
}
Expand Down
3 changes: 3 additions & 0 deletions gradle/testing/randomization/policies/tests.policy
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ grant {
permission java.io.FilePermission "${hunspell.corpora}${/}-", "read";
permission java.io.FilePermission "${hunspell.dictionaries}", "read";
permission java.io.FilePermission "${hunspell.dictionaries}${/}-", "read";

// allow loading specific library for the Faiss codec
permission java.lang.RuntimePermission "loadLibrary.faiss_c";
};

// Permissions for jacoco code coverage
Expand Down
3 changes: 3 additions & 0 deletions lucene/sandbox/src/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
requires org.apache.lucene.facet;

exports org.apache.lucene.payloads;
exports org.apache.lucene.sandbox.codecs.faiss;
exports org.apache.lucene.sandbox.codecs.idversion;
exports org.apache.lucene.sandbox.codecs.quantization;
exports org.apache.lucene.sandbox.document;
Expand All @@ -39,4 +40,6 @@

provides org.apache.lucene.codecs.PostingsFormat with
org.apache.lucene.sandbox.codecs.idversion.IDVersionPostingsFormat;
provides org.apache.lucene.codecs.KnnVectorsFormat with
org.apache.lucene.sandbox.codecs.faiss.FaissKnnVectorsFormat;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* 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.hnsw.FlatVectorsFormat;
import org.apache.lucene.codecs.lucene99.Lucene99FlatVectorsFormat;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;

/**
* A format which uses <a href="https://github.com/facebookresearch/faiss">Faiss</a> to create and
* search vector indexes, using {@link LibFaissC} to interact with the native library.
*
* <p>A separate Faiss index is created per-segment, and uses the following files:
*
* <ul>
* <li><code>.faissm</code> (metadata file): stores field number, offset and length of actual
* Faiss index in data file.
* <li><code>.faissd</code> (data file): stores concatenated Faiss indexes for all fields.
* <li>All files required by {@link Lucene99FlatVectorsFormat} for storing raw vectors.
* </ul>
*
* <p>Note: Set the {@code $OMP_NUM_THREADS} environment variable to control internal threading.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, I'll add it

*
* @lucene.experimental
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you also add a sentence making it clear there is no promise of backwards compatibility here?

That said, does Faiss have any promise? If I write a Faiss HNSW graph with version X, and then upgrade Faiss to version X+1, can the HNSW graph be read/written?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do see some references of backwards compatibility, and an old comment which says that newer versions of Faiss can read older indexes -- but I couldn't find documentation for it..

Further, we may change some internals of the codec making it incompatible with earlier versions -- but I'll add a comment saying there's no guarantee today, and a TODO to figure that out

*/
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 FlatVectorsFormat rawVectorsFormat;

public FaissKnnVectorsFormat() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a comment somewhere or maybe a README with rough high level instructions for how to build this? E.g. install Faiss 1.11.0 or newer, typically via pytorch or conda-forge channel from XYZ, then set this gradle property or so, then ./gradlew such-and-suchat root level, etc?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added to package-info.java as suggested below!

this("IDMap,HNSW32", "efConstruction=200");
}

public FaissKnnVectorsFormat(String description, String indexParams) {
super(NAME);
this.description = description;
this.indexParams = indexParams;
this.rawVectorsFormat =
new Lucene99FlatVectorsFormat(FlatVectorScorerUtil.getLucene99FlatVectorsScorer());
}

@Override
public KnnVectorsWriter fieldsWriter(SegmentWriteState state) throws IOException {
return new FaissKnnVectorsWriter(
description, indexParams, state, rawVectorsFormat.fieldsWriter(state));
}

@Override
public KnnVectorsReader fieldsReader(SegmentReadState state) throws IOException {
return new FaissKnnVectorsReader(state, rawVectorsFormat.fieldsReader(state));
}

@Override
public int getMaxDimensions(String fieldName) {
return DEFAULT_MAX_DIMENSIONS;
}

@Override
public String toString() {
return String.format(
Locale.ROOT, "%s(description=%s indexParams=%s)", NAME, description, indexParams);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/*
* 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.index.VectorSimilarityFunction;
import org.apache.lucene.search.KnnCollector;
import org.apache.lucene.store.DataAccessHint;
import org.apache.lucene.store.FileTypeHint;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.IOUtils;

/**
* Read per-segment Faiss indexes and associated metadata.
*
* @lucene.experimental
*/
final class FaissKnnVectorsReader extends KnnVectorsReader {
private final FlatVectorsReader rawVectorsReader;
private final IndexInput meta, data;
private final Map<String, IndexEntry> indexMap;
private final Arena arena;
private boolean closed;

public FaissKnnVectorsReader(SegmentReadState state, FlatVectorsReader rawVectorsReader)
throws IOException {
this.rawVectorsReader = rawVectorsReader;
this.indexMap = new HashMap<>();
this.arena = Arena.ofShared();
this.closed = false;

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.withHints(FileTypeHint.DATA, DataAccessHint.RANDOM));

Map.Entry<String, IndexEntry> 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, IndexEntry> 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");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Include the fieldNumber in the exception message?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, I'll add it

}

long dataOffset = meta.readLong();
long dataLength = meta.readLong();

// See flags defined in c_api/index_io_c.h
int ioFlags = 3;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm can you use the flag names? Maybe 3 FAISS_IO_FLAG_MMAP | FAISS_IO_FLAG_READ_ONLY? We'd have to define these flags here in javaland, and add a comment pointing back to the C header where they are originally defined.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, this seems cleaner too


// Read index into memory
MemorySegment indexPointer =
indexRead(data.slice(fieldInfo.name, dataOffset, dataLength), ioFlags)
// Ensure timely cleanup
.reinterpret(arena, LibFaissC::freeIndex);

return Map.entry(
fieldInfo.name, new IndexEntry(indexPointer, fieldInfo.getVectorSimilarityFunction()));
}

@Override
public void checkIntegrity() throws IOException {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you tried running Lucene's CheckIndex command-line tool on a Faiss index to confirm it's happy? Does Faiss have any API to "check integrity" that we could call here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't run it on a large index, but tests do call the checkIntegrity function -- so it will be tested regularly on all Faiss indexes created within tests, should that be enough?

Does Faiss have any API to "check integrity" that we could call here?

I didn't find any explicit API -- but Faiss seems to have small sanity checks when reading an index (https://github.com/facebookresearch/faiss/blob/main/faiss/impl/index_read.cpp)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe leave a TODO asking how we could check integrity of Faiss's data structures too? But we are confirming checksums match, so at least we'll catch an errant bit flip, even if it happens in Faiss's on-disk structures.

rawVectorsReader.checkIntegrity();
CodecUtil.checksumEntireFile(meta);
CodecUtil.checksumEntireFile(data);
}

@Override
public FloatVectorValues getFloatVectorValues(String field) throws IOException {
return rawVectorsReader.getFloatVectorValues(field);
}

@Override
public ByteVectorValues getByteVectorValues(String field) {
// TODO: Support using SQ8 quantization, see:
// - https://github.com/opensearch-project/k-NN/pull/2425
throw new UnsupportedOperationException("Byte vectors not supported");
}

@Override
public void search(String field, float[] vector, KnnCollector knnCollector, Bits acceptDocs) {
IndexEntry entry = indexMap.get(field);
if (entry != null) {
indexSearch(entry.indexPointer, entry.function, vector, knnCollector, acceptDocs);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, else should we throw an exception? Or are other KnnVectorsReader also quietly lenient too? Oh, hmm, I guess one segment may not have the field and others do (in the sparse case -- not all docs have vectors), so we probably cannot thow an exception if we don't recognize the field?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, other readers seem to follow the same pattern where they do not collect results if the segment does not have vectors (example)

}

@Override
public void search(String field, byte[] vector, KnnCollector knnCollector, Bits acceptDocs) {
// TODO: Support using SQ8 quantization, see:
// - https://github.com/opensearch-project/k-NN/pull/2425
throw new UnsupportedOperationException("Byte vectors not supported");
}

@Override
public Map<String, Long> getOffHeapByteSize(FieldInfo fieldInfo) {
// TODO: How to estimate Faiss usage?
return rawVectorsReader.getOffHeapByteSize(fieldInfo);
}

@Override
public void close() throws IOException {
if (closed == false) {
IOUtils.close(rawVectorsReader, arena::close, meta, data);
closed = true;
}
}

private record IndexEntry(MemorySegment indexPointer, VectorSimilarityFunction function) {}
}
Loading